Reputation: 6438
Given a string of characters as input, without using regular expression or pattern matching, how to get the output, if the characters matches aaa should output 1 and if the characters matches aBa should output 2. (Note: Should not re-process characters so as to output both “1” and “2” when processing the same input)
So for example:
given 'aaBaBaaaBaaa' it should output 211
given 'aaaBaBaaaaBBaBaBa' it should output 1212
Thanks in advance.
Upvotes: 0
Views: 185
Reputation: 1599
Sounds like you want a state machine:
require 'statemachine'
state_machine = Statemachine.build do
trans :_, :a, :a
trans :_, :B, :_
trans :a, :a, :aa
trans :a, :B, :aB
trans :aa, :a, :_, 'print 1'
trans :aa, :B, :aB
trans :aB, :a, :_, 'print 2'
trans :aB, :B, :_
end
"aaBaBaaaBaaa".each_char do |i|
state_machine.process_event(i)
end
state_machine.reset
puts
"aaaBaBaaaaBBaBaBa".each_char do |i|
state_machine.process_event(i)
end
Upvotes: 6
Reputation: 2517
without using regular expression or pattern matching
#input = 'aaBaBaaaBaaa'
input = 'aaaBaBaaaaBBaBaBa'
codes = {'aaa' => 1, 'aBa' => 2}
patterns = codes.keys
output = []
current = 0
length = input.length
while current <= length - 1
is_find = false
patterns.each do|pattern|
len = pattern.length
if input[current, len] == pattern
output << codes[pattern]
current += len
is_find = true
break
end
end
current += 1 if !is_find
end
p output
Upvotes: 4