author | Christian Urban <urbanc@in.tum.de> |
Mon, 24 Sep 2018 11:05:39 +0100 | |
changeset 558 | 447ed6c7cdad |
parent 474 | 4bdf0dedd708 |
child 563 | bddf14e026b3 |
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:
411
diff
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:
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 |