Skip to content

Instantly share code, notes, and snippets.

@isa
Created May 1, 2012 20:10
  • Star 1 You must be signed in to star a gist
  • Fork 17 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save isa/2571012 to your computer and use it in GitHub Desktop.
Convert in less than 30 lines
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
@stehem
Copy link

stehem commented May 4, 2012

I have been doing a lot of Clojure lately :-)

letters = [["A", "B", "C"], ["A", "C", "E"], ["E", "F", "D"], ["D", "A", "J"], ["E", "D", "J"]]

count_combo = lambda do |combo|
letters.reduce(0) { |memo, l| memo += 1 if [combo[0], combo[1]].all? {|k| l.include?(k)}; memo }  
end

letters.reduce([]) {|memo, x| memo << x.map {|l| (x - [l]).map {|m| l+m}}.flatten.reject {|n| n[1] < n[0]}}.flatten.uniq.sort.reduce([]) {|memo, c| memo << [c.split(""), count_combo.call(c)].flatten}

@tjgfernandes
Copy link

hash,list = {},[["A","B","C"],["A","C","E"],["E","F","D"],["D","A","J"],["E","D","J"]]
list.each { |v| (0..1).each {|n| (1..2).each {|i| (n!=i and key=[v[n],v[i]].sort.to_s) ? hash[key] ? hash[key] +=1 : hash[key] = 1 : "" } } }
hash.sort.each {|p| puts "#{p[0][0..0]}, #{p[0][1..1]}, #{p[1]}" }

@manewitz
Copy link

manewitz commented May 7, 2012

Here's my quick first pass at it. That was fun.

inputs, counts, final = [["A", "B", "C"], ["A", "C", "E"], ["E", "F", "D"], ["D", "A", "J"], ["E", "D", "J"]], Hash.new(0), Array.new
inputs.each{|set| set.combination(2).to_a.sort.each{|pair| pair.sort! && counts[pair] += 1}}

# puts'ing a string of the result:

counts.sort.each{ |n| puts "#{n[0][0]}, #{n[0][1]}, #{n[1]}"}

# or just printing the raw data structure
puts
p counts.sort

@akagr
Copy link

akagr commented Mar 2, 2015

5 lines in ruby... although this is general enough to accept arbitrary number of characters per line and any number of lines

res = Hash.new(0)
while a = gets do
    !a.nil? && a.chomp.split(/,\s?/).sort.combination(2).to_a.each {|tuple| res[tuple.join(', ')] += 1}
end
puts res.to_a.map {|tuple| tuple.join(', ')}.sort

@EricDykstra
Copy link

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