Created
August 20, 2016 04:23
-
-
Save worace/b691a43822a03c461b50595e3446ffba to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "minitest/autorun" | |
require "set" | |
class Sequencer | |
def sequences(words) | |
# go through all words | |
# go through each consecutive slice of 4 | |
# look in the map for that slice | |
# add the word to the corresponding set | |
# pick out the keys where values have 1 in the set | |
h = Hash.new { Set.new } # new hash with set as default value | |
pairs = words.reduce(h) do |seqs, word| | |
word.chars.each_cons(4) do |sequence| | |
seqs[sequence.join] += Set.new([word]) | |
end | |
seqs | |
end.select do |sequence, words| | |
words.count == 1 | |
end.map do |sequence, words| | |
[sequence, words.first] | |
end.to_h | |
end | |
end | |
class SequencesTest < Minitest::Test | |
def input | |
%w(arrows | |
carrots | |
give | |
me) | |
end | |
def test_processing_list_of_words | |
out = {"carr" => "carrots", | |
"give" => "give", | |
"rots" => "carrots", | |
"rows" => "arrows", | |
"rrot" => "carrots", | |
"rrow" => "arrows"} | |
assert_equal out, Sequencer.new.sequences(input) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment