Skip to content

Instantly share code, notes, and snippets.

@you-ssk
Created December 20, 2012 14:31
Show Gist options
  • Save you-ssk/4345600 to your computer and use it in GitHub Desktop.
Save you-ssk/4345600 to your computer and use it in GitHub Desktop.
require 'pp'
def neighbor(s)
[[s[0],s[1]-1],
[s[0],s[1]+1],
[s[0]+1,s[1]],
[s[0]-1,s[1]]]
end
def upper(s)
[s[0]+1,s[1]]
end
def lower(s)
[s[0]-1,s[1]]
end
def find_piece(hashset,mask,fb,piece)
unless piece.include?(fb)
piece << fb
mask[fb] = nil
end
tmp = neighbor(fb).find_all do |e|
(hashset[e] == hashset[fb]) && mask[e]
end
tmp.each{|i| find_piece(hashset,mask,i,piece)}
end
def stat(hashset,piece)
r = []
centroid = []
piece.each do |b|
l = lower(b)
if (hashset[l] && (hashset[l] != hashset[b])) || (l[0] == -1)
r << b[1]
end
centroid << Rational(1,2) + b[1]
end
c = centroid.inject(:+)/piece.size
{:xl=>r.min, :xr=>r.max+1, :cent=>c}
end
def stable?(h)
h[:xl] < h[:cent] and h[:cent] < h[:xr]
end
def is_stable?(a)
base = a[0]
xl,xr = base[:xl],base[:xr]
c = a.inject(0){|r,i| r+i[:cent]}/a.size
h = {:xl=>xl, :xr=>xr, :cent=>c}
stable?(h)
end
def search(hashset,mask,fb)
piece = []
find_piece(hashset,mask,fb,piece)
attr = stat(hashset,piece)
attrs = [attr]
piece.each do |e|
u = upper(e)
next unless mask[u]
unless hashset[u] == hashset[e]
attrs << search(hashset,mask,u)
end
end
attrs.flatten!
raise "UNSTABLE" unless is_stable?(attrs)
attrs
end
def trans(dataset)
hashset = {}
dataset.each_with_index do |m,i|
m.each_with_index do |n,j|
hashset[[i,j]] = n
end
end
hashset
end
def diag(w,h,dataset)
hashset = trans(dataset)
mask = hashset.dup
first_block = hashset.find{|i| i[0][0] == 0 && i[1]}[0]
begin
search(hashset,mask,first_block)
rescue => evar
raise unless evar.to_s == "UNSTABLE"
puts evar
else
puts "STABLE"
end
end
def main
lines = File.open('input.txt').readlines.map!{|i| i.gsub(/\s/,'').split(//)}
input = lines.map do |i|
i.map do |j|
if j=="." then nil else Integer(j) end
end
end
while !input.empty?
w,h = input.shift
dataset = input.shift(Integer(h)).reverse!
exit if w == 0 and h == 0
# puts "width,height = #{[w,h]}\n"
# dataset.each{|l| p l.map{|e| if e then e else 0 end}}
diag(w,h,dataset)
end
end
main
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment