Created
July 7, 2018 21:10
-
-
Save jredville/a2a5fbe233367b0c5883669654af9e62 to your computer and use it in GitHub Desktop.
This file contains 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
class Letter | |
include Comparable | |
attr_reader :before, :after | |
def initialize(letter) | |
@letter = letter | |
@before = [] | |
@after = [] | |
end | |
def <=>(other) | |
@letter <=> other | |
end | |
def before? | |
[email protected]? | |
end | |
def is_before(other) | |
@before << other | |
@before.uniq! | |
end | |
def after? | |
[email protected]? | |
end | |
def is_after(other) | |
@after << other | |
@after.uniq! | |
end | |
def inspect | |
"#<Letter(#@letter): before: #@before after: #@after>" | |
end | |
def to_str | |
@letter | |
end | |
end | |
class Triplets | |
attr_reader :letters | |
def initialize | |
@letters = [] | |
end | |
def add(first, sec, last) | |
add_one first, sec, nil | |
add_one sec, last, first | |
add_one last, nil, sec | |
self | |
end | |
def add_letter(letter) | |
Letter.new(letter).tap { |let| @letters << let } | |
end | |
def find_letter(letter) | |
return unless letter | |
@letters.find(-> { add_letter letter }) { |l| l == letter } | |
end | |
def add_one(letter, before, after) | |
letter = find_letter letter | |
before = find_letter before | |
after = find_letter after | |
letter.is_before before if before | |
letter.is_after after if after | |
end | |
def to_s | |
@letters.reject(&:after?).tap do |res| | |
res.push find_next_letter res.last until @letters.empty? | |
end.join | |
end | |
def find_next_letter(letter) | |
letter.before.find { |let| let.after == [letter] }.tap do | |
letter.before.each { |bef| bef.after.delete letter } | |
@letters.delete letter | |
end | |
end | |
end | |
def recover_secret(triplets) | |
trips = triplets.reduce(Triplets.new) { |l, t| l.add(*t) } | |
trips.to_s | |
end | |
triplets_1 = [ | |
['t','u','p'], | |
['w','h','i'], | |
['t','s','u'], | |
['a','t','s'], | |
['h','a','p'], | |
['t','i','s'], | |
['w','h','s'] | |
] | |
puts recover_secret triplets_1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment