| author | Christian Urban <christian.urban@kcl.ac.uk> | 
| Sat, 23 Sep 2023 21:22:17 +0100 | |
| changeset 924 | 6d85d0850b99 | 
| parent 753 | 30ea6b01db46 | 
| permissions | -rwxr-xr-x | 
| 753 | 1 | #!/usr/bin/env ruby | 
| 2 | ||
| 558 | 3 | # A case of catastrophic backtracking in Ruby | 
| 4 | #--------------------------------------------- | |
| 563 | 5 | # example provided by Daniel Baldwin | 
| 558 | 6 | # | 
| 563 | 7 | # | 
| 558 | 8 | # regex: (a?){n} a{n}
 | 
| 9 | # strings: aa... | |
| 10 | # | |
| 563 | 11 | # run on the command line with: | 
| 558 | 12 | # | 
| 753 | 13 | # ./catastrophic.rb | 
| 558 | 14 | # | 
| 58 | 15 | |
| 753 | 16 | nums = (1..30) | 
| 57 | 17 | |
| 753 | 18 | #iterate through the nums 1-30 | 
| 57 | 19 | nums.each do |i| | 
| 20 | ||
| 21 | start_time = Time.now | |
| 22 | string = "a" * i | |
| 474 | 23 | |
| 24 | #create a new regular expression based on current value of i | |
| 226 
e3c454e31224
updated so that it works with more recent versions of Ruby
 Christian Urban <christian dot urban at kcl dot ac dot uk> parents: 
121diff
changeset | 25 | re_str = "a?" * i + "+" + "a" * i | 
| 
e3c454e31224
updated so that it works with more recent versions of Ruby
 Christian Urban <christian dot urban at kcl dot ac dot uk> parents: 
121diff
changeset | 26 | re = Regexp.new(re_str) | 
| 57 | 27 | |
| 60 | 28 | re.match(string) | 
| 474 | 29 | |
| 30 | #if re.match(string) | |
| 60 | 31 | 	#	puts "matched string  a * #{i} with regex #{re}"
 | 
| 32 | #else | |
| 33 | 	#	puts "unmatched string a * #{i} with regex #{re}"
 | |
| 34 | #end | |
| 57 | 35 | |
| 60 | 36 |   puts "#{i} %.5f" % (Time.now - start_time)
 | 
| 57 | 37 | end |