Skip to content

Instantly share code, notes, and snippets.

@bcjordan
Created January 18, 2011 02:43
Show Gist options
  • Save bcjordan/783900 to your computer and use it in GitHub Desktop.
Save bcjordan/783900 to your computer and use it in GitHub Desktop.
parsing / combination exercise
# Run using rspec parse_brackets.rb
# Uses array combination/permutation method from
# http://trevoke.net/blog/2009/12/17/inter-array-permutations-in-ruby/
# Takes an array of arrays and returns permutations of them
# e.g., fancy_array_permutation[["one", "two"], ["three", "four"]]
# returns: ["onethree", "onefour", "twothree", "twofour"]
def fancy_array_permutation array
return array[0] if array.size == 1
first = array.shift
return first.product( fancy_array_permutation(array) ).map {|x| x.flatten.join}
end
def parse(name)
curr_token = ""
tokens = [] # Array of token option arrays.
name.each_char do |char| # Each character...
if char == '['
tokens << [curr_token] unless curr_token.empty?
curr_token = ""
elsif char == ']'
tokens << [curr_token, ""]
curr_token = ""
else
curr_token << char
end
end
tokens << [curr_token] unless curr_token.empty? # Process last word
fancy_array_permutation tokens # Return combinations of words
end
describe "parse" do
it 'should list all permutations, text in brackets is optional' do
strings = parse('foo[bar]')
strings.should include('foo')
strings.should include('foobar')
strings.should_not include('bar')
strings.size.should == 2
end
it 'should list all permutations, text in brackets is optional' do
strings = parse('[foo]bar[baz]')
strings.should include('foobar')
strings.should include('bar')
strings.should include('barbaz')
strings.should include('foobarbaz')
strings.should_not include('foo')
strings.should_not include('baz')
strings.size.should == 4
end
it 'should list all permutations, text in brackets is optional' do
strings = parse('[foo][bar][baz]')
strings.should include('foobarbaz')
strings.should include('foobar')
strings.should include('foobaz')
strings.should include('barbaz')
strings.should include('foo')
strings.should include('bar')
strings.should include('baz')
strings.should include('')
strings.size.should == 8 # or 7, if "" is not a valid permutation
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment