Skip to content

Instantly share code, notes, and snippets.

@akuraru
Created April 23, 2014 03:27
Show Gist options
  • Save akuraru/11201920 to your computer and use it in GitHub Desktop.
Save akuraru/11201920 to your computer and use it in GitHub Desktop.
ぶどう問題。最後の方は明らかに力尽きている
require 'set'
class Bunch
def initialize(bunch1, bunch2 = nil)
(bunch2 != nil) ? mergeBunch(bunch1, bunch2) : initValue(bunch1)
end
def initValue(value)
@bunch1 = nil
@bunch2 = nil
@value = value
@values = [value].to_set
@rank = 1
end
def mergeBunch(bunch1, bunch2)
@bunch1 = bunch1;
@bunch2 = bunch2;
@value = (bunch1.value - bunch2.value).abs
@values = bunch1.values + bunch2.values
@values.add(@value)
@rank = bunch1.rank + 1
end
def check
(@rank + 1) * @rank / 2 == @values.count
end
attr_accessor :bunch1, :bunch2, :value, :values, :rank
end
class Rank
def initialize(bunchs)
@bunchs = bunchs
end
def nextRank
r = Rank.new(self.nextBunchs)
(r.check) ? r : nil
end
def nextBunchs
@bunchs[1..-1].inject([[], @bunchs[0]]){|s, b| [s[0] + [Bunch.new(s[1], b)], b] }[0]
end
def check
@bunchs.inject(true) {|s, b| s && b.check}
end
attr_accessor :bunchs
end
class Grape
def initialize(numbers)
bunchs = numbers.map{|s| Bunch.new(s)}
rank = Rank.new(bunchs)
ranks = [rank]
for i in (2..(numbers.count))
rank = rank.nextRank
if (rank != nil)
ranks += [rank]
else
break
end
end
if (ranks.count == numbers.count)
@ranks = ranks
end
end
def print
@ranks.map{|r| r.bunchs.map{|b| "#{b.value}"}.join(" ")}.join("\n")
end
attr_accessor :ranks
end
for i1 in 1..15
for i2 in 1..15
for i3 in 1..15
for i4 in 1..15
for i5 in 1..15
g = Grape.new([i1, i2, i3, i4, i5])
if (g.ranks != nil)
puts g.print
end
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment