Skip to content

Instantly share code, notes, and snippets.

@worace
Created August 20, 2016 04:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save worace/b691a43822a03c461b50595e3446ffba to your computer and use it in GitHub Desktop.
Save worace/b691a43822a03c461b50595e3446ffba to your computer and use it in GitHub Desktop.
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