| author | Christian Urban <urbanc@in.tum.de> | 
| Sun, 27 Oct 2019 13:03:58 +0000 | |
| changeset 673 | 4e254e201ce9 | 
| parent 563 | 6bb70f562d37 | 
| permissions | -rw-r--r-- | 
| 558 | 1  | 
# A case of catastrophic backtracking in Ruby  | 
2  | 
#---------------------------------------------  | 
|
| 563 | 3  | 
# example provided by Daniel Baldwin  | 
| 558 | 4  | 
#  | 
| 563 | 5  | 
#  | 
| 558 | 6  | 
# regex: (a?){n} a{n}
 | 
7  | 
# strings: aa...  | 
|
8  | 
#  | 
|
| 563 | 9  | 
# run on the command line with:  | 
| 558 | 10  | 
#  | 
| 563 | 11  | 
# $> ruby catastrophic.rb  | 
| 558 | 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: 
121 
diff
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: 
121 
diff
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: 
121 
diff
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  |