Last active
December 24, 2015 02:19
-
-
Save lsantos/6729760 to your computer and use it in GitHub Desktop.
Find string pairs puzzlers http://java.dzone.com/articles/thursday-code-puzzler-find-1
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' | |
class StringPairsFinder | |
def find(s) | |
return if s.nil? | |
tokens = s.split | |
result = Result.new | |
tokens.each_with_index do |t,i| | |
comb = result.find_or_create_comb(t) | |
tokens[i+1..tokens.size].each_with_index do |t1, i1| | |
if t == t1 | |
pair = Pair.new | |
pair.idx1 = i | |
pair.idx2 = (i+ i1) + 1 | |
comb << pair | |
end | |
end | |
end | |
result | |
end | |
end | |
class Result | |
attr_accessor :combinations | |
def initialize | |
@combinations = {} | |
end | |
def find_by_word(w) | |
combinations[w] | |
end | |
def find_or_create_comb(w) | |
if c = combinations[w] | |
c | |
else | |
combinations[w] = Combination.new w | |
end | |
end | |
end | |
class Combination | |
attr_accessor :pairs, :word | |
def initialize(word) | |
@pairs = [] | |
@word = word | |
end | |
def <<(e) | |
pairs << e | |
end | |
def find_adjacent | |
pairs.find_all {|p| p.adjacent? } | |
end | |
end | |
class Pair | |
attr_accessor :idx1, :idx2 | |
def initialize | |
@idx1 = 0 | |
@idx2 = 0 | |
end | |
def to_s | |
"(#{idx1},#{idx2})" | |
end | |
def inspect | |
to_s | |
end | |
def adjacent? | |
(idx1 + 1) == idx2 | |
end | |
end | |
class TestStringPairsFinder < MiniTest::Unit::TestCase | |
attr_reader :finder | |
def setup | |
@finder = StringPairsFinder.new | |
end | |
def test_string_pairs_finder | |
s = "dzone java dzone dzone javascript java" | |
result = finder.find(s) | |
assert(result) | |
assert_equal(3, result.combinations.size) | |
dzone_comb = result.find_by_word("dzone") | |
java_comb = result.find_by_word("java") | |
assert_equal(3, dzone_comb.pairs.size) | |
assert_equal("[(0,2), (0,3), (2,3)]", dzone_comb.pairs.inspect) | |
assert_equal("(2,3)", dzone_comb.find_adjacent.first.inspect) | |
assert_equal(1, java_comb.pairs.size) | |
assert_equal("(1,5)", java_comb.pairs.first.inspect) | |
end | |
end | |
# dzone has 1 adjacent pair | |
# dzone has 3 combination pairs (0,2) (0,3) (2,3) | |
# java has 1 combination pair (1,5) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment