Created
March 8, 2017 21:25
-
-
Save yovasx2/fc12cf3efbb59d9249895a7ce56a0d0b 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
#!usr/bin/ruby | |
# Given a comma-separated list of equal-length strings, check if it is possible to rearrange the strings in such a way that after the rearrangement the strings at consecutive positions would differ by exactly one character. | |
# Example | |
# For input: aba,bbb,bab the output should be: false | |
# For input: ab,bb,aa the output should be: true | |
# Input Format | |
# A comma-separated list of strings containing alphanumeric characters. | |
# Constraints | |
# 2 ≤ list length ≤ 10 | |
# 1 ≤ string length ≤ 15. | |
# Output Format | |
# Either the string true or false | |
# Sample Input 0 | |
# aba,bbb,bab | |
# Sample Output 0 | |
# false | |
# Sample Input 1 | |
# ab,bb,aa | |
# Sample Output 1 | |
# true | |
# Sample Input 2 | |
# q,q | |
# Sample Output 2 | |
# false | |
# Sample Input 3 | |
# zzzzab,zzzzbb,zzzzaa | |
# Sample Output 3 | |
# true | |
class Rearrengement | |
attr_accessor :collection | |
def initialize | |
input = clean_params(gets.chop, ',') | |
@collection = [] | |
for i in input | |
@collection << i | |
end | |
@num_elems = @collection.size | |
@res = [] | |
end | |
def verify | |
return @num_elems == @res.size | |
end | |
def order | |
@res = [@collection[0]] | |
reduce(0) | |
change = true | |
while(change && @collection.size!=0) do | |
for i in [email protected] | |
if(insert_in_sides(@collection[i])) | |
reduce(i) | |
change = true | |
break | |
else | |
change = false | |
end | |
end | |
change &= change | |
end | |
end | |
private | |
def reduce(i) | |
@collection[i] = nil | |
@collection.compact! | |
end | |
def insert_in_sides(word) | |
if(similar(word, @res[0], 1)) | |
@res.unshift(word) | |
return true | |
end | |
if(similar(word, @res[@res.length-1], 1)) | |
@res << word | |
return true | |
end | |
return false | |
end | |
def clean_params(str, separator = '') | |
str.split(separator) | |
end | |
def similar(word1, word2, mistakes_allowed) | |
for i in 0..word1.length-1 do | |
if(word1[i] != word2[i]) | |
mistakes_allowed-=1 | |
end | |
end | |
if(mistakes_allowed == 0) | |
return true | |
else | |
return false | |
end | |
end | |
def swap(i,j) | |
return if(i == j) | |
tmp = @collection[i] | |
@collection[i] = @collection[j] | |
@collection[j] = tmp | |
end | |
end | |
r = Rearrengement.new | |
r.order | |
puts r.verify |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment