Module: GentleBrute::PatternFinder

Defined in:
lib/gentle_brute/pattern_finder.rb

Class Method Summary collapse

Class Method Details

.patterns_in_strintg(string) ⇒ Array

Analyzes a given string for different patterns

Parameters:

  • string (String)

    the string to analyze

Returns:

  • (Array)

    a whole bunch of patterns :s



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/gentle_brute/pattern_finder.rb', line 8

def patterns_in_strintg string
  pattern_string = ""
  pattern_length = 0
  pattern_count  = 0
  pattern_bounds = []
  patterns = {}
  
  for i in 0...string.length
    (string.length-1).downto i do | ii |
      slice = string[i..ii]
      slice_length = slice.length
      slice2 = string[i+slice_length..ii+slice_length]
      if slice == slice2
        if not patterns.has_key? slice
          patterns[slice] = {}
          patterns[slice]["count"] = 1
          patterns[slice]["start"] = i
        else
          patterns[slice]["count"] += 1
        end
      end
    end
  end
  
  return nil if patterns == {}
  
  highest_count = 0
  patterns.keys.reverse.each do | key |
    if patterns[key]["count"] > highest_count
      pattern_string = key
      highest_count = patterns[key]["count"]
    end
  end
  
  start = patterns[pattern_string]["start"]
  index = start
  length = pattern_string.length
  pattern_length = length
  pattern_count += 1
  
  while true
    slice = string[index...index+length]
    slice2 = string[index+length...index+(length*2)]
    break if slice != slice2
  
    pattern_bounds = [start, index+(length*2)-1]
    pattern_length += length
    pattern_count += 1
  
    index += length
  end
  full_pattern = pattern_string * pattern_count
  
  [pattern_string, full_pattern, pattern_length, pattern_count, pattern_bounds]
end