Created
May 1, 2012 20:10
-
-
Save isa/2571012 to your computer and use it in GitHub Desktop.
Convert in less than 30 lines
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
Question: Convert following into the latter data structure in less than 30 lines: | |
List: | |
A, B, C | |
A, C, E | |
E, F, D | |
D, A, J | |
E, D, J | |
List | |
A, B, 1 (frequency) | |
A, C, 2 | |
A, D, 1 | |
A, E, 1 | |
A, J, 1 | |
B, C, 1 | |
C, E, 1 | |
D, E, 2 | |
D, F, 1 | |
D, J, 2 | |
E, F, 1 | |
E, J, 1 |
Simple 4 line answer, and in code golf form with a minimum number of characters. Could probably be cut down a bit further, but I didn't spend too much time on it.
h=Hash.new(0)
input.split("\n").map{|a|a.split(", ")}.map{|x|x.combination(2).map{|y|h[y]+=1}}
h.sort_by{|x,y|x[0]}.map{|x,y|puts"#{x[0]}, #{x[1]}, #{y}"}
puts h
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
5 lines in ruby... although this is general enough to accept arbitrary number of characters per line and any number of lines