Skip to content

Instantly share code, notes, and snippets.

@timothyandrew
Created November 18, 2011 16:31
Show Gist options
  • Save timothyandrew/1376969 to your computer and use it in GitHub Desktop.
Save timothyandrew/1376969 to your computer and use it in GitHub Desktop.
Instagram Engineering Challenge
#!/usr/bin/env ruby
require 'RMagick'
include Magick
#Match right edge of col1 to left edge of col2
def match_edge(col1, col2)
left_edge = col2.get_pixels(0,0,1,col2.rows)
left_edge_plus_one = col2.get_pixels(1,0,1,col2.rows)
right_edge = col1.get_pixels(col1.columns - 2,0,1,col1.rows)
right_edge_minus_one = col1.get_pixels(col1.columns - 3,0,1,col1.rows)
score = 0
col1.rows.times { |i|
tmp = 0
difference = (left_edge[i].red - left_edge_plus_one[i].red).abs
if((right_edge[i].red - left_edge[i].red).abs <= difference)
tmp += 1
end
difference = (left_edge[i].blue - left_edge_plus_one[i].blue).abs
if((right_edge[i].blue - left_edge[i].blue).abs <= difference)
tmp += 1
end
difference = (left_edge[i].green - left_edge_plus_one[i].green).abs
if((right_edge[i].green - left_edge[i].green).abs <= difference)
tmp += 1
end
if tmp > 1
score += 1
end
}
score
end
cols = []
img = ImageList.new("image.png")
#Divide into columns
20.times { |index|
cols.push img.excerpt(index*32,0,32,img.rows)
}
#Find leftmost edge
cols.each_with_index { |col1, i|
flag = false
cols.each_with_index { |col2, j|
if i != j
if match_edge(col2, col1) > 100
flag = true
end
end
}
if not flag
tmp = cols[0]
cols[0] = cols[i]
cols[i] = tmp
end
}
#Find matching edges for other columns
cols.length.times { |i|
if(i < cols.size - 1)
max_match = 0
max_index = 0
cols.length.times { |j|
if(i < j)
match = match_edge(cols[i], cols[j])
if match >= max_match
max_match = match
max_index = j
end
end
}
#puts "Moving #{max_index} to #{i+1}"
tmp = cols[i+1]
cols[i+1] = cols[max_index]
cols[max_index] = tmp
end
}
il = ImageList.new
cols.each { |col|
il << col
}
il.append(false).write("output.png")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment