| author | Christian Urban <urbanc@in.tum.de> | 
| Tue, 25 Sep 2018 20:50:42 +0100 | |
| changeset 561 | cf3e57e6fec7 | 
| parent 558 | c9da2c4586f2 | 
| child 563 | 6bb70f562d37 | 
| permissions | -rw-r--r-- | 
| 558 | 1 | # A case of catastrophic backtracking in Ruby | 
| 2 | #--------------------------------------------- | |
| 3 | # | |
| 4 | # regex: (a?){n} a{n}
 | |
| 5 | # strings: aa... | |
| 6 | # | |
| 420 
25bc57b32efa
updated
 Christian Urban <christian dot urban at kcl dot ac dot uk> parents: 
411diff
changeset | 7 | # example provided by Daniel Baldwin | 
| 558 | 8 | # | 
| 9 | # call with: | |
| 10 | # | |
| 11 | # > ruby catastrophic.rb | |
| 12 | # | |
| 58 | 13 | |
| 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 | 14 | nums = (1..1000) | 
| 57 | 15 | |
| 474 | 16 | #iterate through the nums 1-1000 | 
| 57 | 17 | nums.each do |i| | 
| 18 | ||
| 19 | start_time = Time.now | |
| 20 | string = "a" * i | |
| 474 | 21 | |
| 22 | #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 | 23 | 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 | 24 | re = Regexp.new(re_str) | 
| 57 | 25 | |
| 60 | 26 | re.match(string) | 
| 474 | 27 | |
| 28 | #if re.match(string) | |
| 60 | 29 | 	#	puts "matched string  a * #{i} with regex #{re}"
 | 
| 30 | #else | |
| 31 | 	#	puts "unmatched string a * #{i} with regex #{re}"
 | |
| 32 | #end | |
| 57 | 33 | |
| 60 | 34 |   puts "#{i} %.5f" % (Time.now - start_time)
 | 
| 57 | 35 | end |