Skip to content

Instantly share code, notes, and snippets.

@DavidGoussev
Last active October 8, 2015 06:08
Show Gist options
  • Select an option

  • Save DavidGoussev/278d72b9c96dd2652060 to your computer and use it in GitHub Desktop.

Select an option

Save DavidGoussev/278d72b9c96dd2652060 to your computer and use it in GitHub Desktop.
plug board
class Plugboard
def initialize(wires = "")
chars = wires.split('')
if chars.length % 2 == 1 || chars.length > 20
raise
end
@hash = Hash.new
chars.each_with_index do |c, index|
if index % 2 == 0
character_ahead = chars[index+1]
if @hash[c] || @hash[character_ahead]
raise
end
@hash[c] = character_ahead
@hash[character_ahead] = c
end
end
end
def process(wire)
answer = @hash[wire]
return answer ? answer : wire
class Plugboard
def initialize(wires = "")
if wires.length % 2 > 0
raise 'un-assigned character'
end
wires.split(//).each do |c|
if c<'A' || c>'Z'
raise 'character out of bound'
end
end
if wires.split(//).length > wires.split(//).uniq.length
raise 'duplicate association'
end
if wires.length > 20
raise 'cannot be more than 10 pairs'
end
x = wires.split(//)
@codes = Hash.new
(0...(x.length)).step(2) do |i|
@codes[x[i]] = x[i+1]
@codes[x[i+1]] = x[i]
end
end
def process(wire)
if !@codes[wire].nil?
@codes[wire]
else
wire
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment