Cliques are sets of vertices in a graph that are complete, meaning there is an edge between every pair of the vertices in the clique. This Facebook puzzle is to find maximal cliques in presumably a large but sparse data set, since the problem is NP-complete (worst-case is when the graph is dense).
I will come back and cover this in broader detail at a later time.
The following solution in Ruby passed the Facebook puzzle robot:
#!/usr/bin/env ruby# VROOM# Kanwei Li, 2009# Make sure input file exists and read from itfilename=ARGV[0]unlessfilename&&File.exist?(filename)puts"error: must specify a valid input file"exitendinput=File.open(filename)$build_matrix={}$adj_matrix={}whileline=input.getsline.strip!nextifline.empty?splitted=line.split("\t")a,b=splitted[1..2]unlessa==b$build_matrix[a]||={}$build_matrix[a][b]=trueif$build_matrix[b]&&$build_matrix[b][a]$adj_matrix[a]||=[]$adj_matrix[a]<<b$adj_matrix[b]||=[]$adj_matrix[b]<<aendendend$cliques=[]defprint_cliques(set,neighbors,seen)ifneighbors.empty?&&seen.empty?$cliques<<set.sort.join(", ")ifset.size>2elsepossible_pivots=neighbors+seenpivot=possible_pivots.inject(nil)do|best,p|best.nil?||$adj_matrix[p].size>best.size?best=p:bestendneighbors.size.timesdo|i|n=neighbors[i]nextif$adj_matrix[n].include?(pivot)neighbors[i]=nilprint_cliques(set+[n],neighbors.compact&$adj_matrix[n],seen&$adj_matrix[n])seen<<nendendendprint_cliques([],$adj_matrix.keys,[])puts$cliques.sort.join("\n")<<"\n"
Posted on
About
Kanwei Li
I don't always look good in photos. But when I do, I make sure to post it on the internet.
I game on a Mac and program on a PC.
I write PHP for fun.
I once aced the MCAT... and turned down medical school.