author | Christian Urban <christian.urban@kcl.ac.uk> |
Sun, 09 Oct 2022 13:39:34 +0100 | |
changeset 882 | 5fcad75ade92 |
parent 753 | d94fdbef1a4f |
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:
121
diff
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:
121
diff
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 |