Nonoblock: Difference between revisions

→‎{{header|Ruby}}: add Class version
(Added Ruby)
(→‎{{header|Ruby}}: add Class version)
Line 365:
else
rest = cell - blocks.inject(:+) - blocks.size + 2
b0bl, brest = blocks[0], blocks.drop(1)
rest.times do |i|
nblock(cell-i-b0bl-1, brest, position + '.'*i + '#'*b0bl + '.', result)
end
end
Line 424:
 
5 cells and [2, 3] blocks
#<RuntimeError: Those blocks will not fit in those cells>
</pre>
 
'''Class version:'''
<lang ruby>class NonoBlock
def self.cell(cell)
"|#{(['_']*cell).join('|')}|"
end
def initialize(cell, blocks)
raise 'Those blocks will not fit in those cells' if cell < blocks.inject(0,:+) + blocks.size - 1
@result = []
nonoblocks(cell, blocks, '')
end
def result(correct=true)
correct ? @result.map{|str| str2cell(str)} : @result
end
private
def nonoblocks(cell, blocks, position)
if cell <= 0
@result << position[0..cell-1]
elsif blocks.empty? or blocks[0].zero?
@result << position + '.' * cell
else
rest = cell - blocks.inject(0,:+) - blocks.size + 2
bl, brest = blocks[0], blocks.drop(1)
rest.times do |i|
nonoblocks(cell-i-bl-1, brest, position + '.'*i + '#'*bl + '.')
end
end
end
def str2cell(str) # "##.###..##" -> "|A|A|_|B|B|B|_|_|C|C|"
chr = ('A'..'Z').each
s = str.tr('.','_').gsub(/#+/){|sharp| chr.next * sharp.size}
"|#{s.chars.join('|')}|"
end
end
 
if __FILE__ == $0
conf = [[ 5, [2, 1]],
[ 5, []],
[10, [8]],
[15, [2, 3, 2, 3]],
[ 5, [2, 3]], ]
conf.each do |cell, blocks|
begin
puts "Configuration:",
"#{NonoBlock.cell(cell)} # #{cell} cells and #{blocks} blocks",
"Possibilities:"
result = NonoBlock.new(cell, blocks).result
puts result,
"A total of #{result.size} Possible configurations.", ""
rescue => e
p e
end
end
end</lang>
The output form consulted the one of the python.
 
{{out}}
<pre>
Configuration:
|_|_|_|_|_| # 5 cells and [2, 1] blocks
Possibilities:
|A|A|_|B|_|
|A|A|_|_|B|
|_|A|A|_|B|
A total of 3 Possible configurations.
 
Configuration:
|_|_|_|_|_| # 5 cells and [] blocks
Possibilities:
|_|_|_|_|_|
A total of 1 Possible configurations.
 
Configuration:
|_|_|_|_|_|_|_|_|_|_| # 10 cells and [8] blocks
Possibilities:
|A|A|A|A|A|A|A|A|_|_|
|_|A|A|A|A|A|A|A|A|_|
|_|_|A|A|A|A|A|A|A|A|
A total of 3 Possible configurations.
 
Configuration:
|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_| # 15 cells and [2, 3, 2, 3] blocks
Possibilities:
|A|A|_|B|B|B|_|C|C|_|D|D|D|_|_|
|A|A|_|B|B|B|_|C|C|_|_|D|D|D|_|
|A|A|_|B|B|B|_|C|C|_|_|_|D|D|D|
|A|A|_|B|B|B|_|_|C|C|_|D|D|D|_|
|A|A|_|B|B|B|_|_|C|C|_|_|D|D|D|
|A|A|_|B|B|B|_|_|_|C|C|_|D|D|D|
|A|A|_|_|B|B|B|_|C|C|_|D|D|D|_|
|A|A|_|_|B|B|B|_|C|C|_|_|D|D|D|
|A|A|_|_|B|B|B|_|_|C|C|_|D|D|D|
|A|A|_|_|_|B|B|B|_|C|C|_|D|D|D|
|_|A|A|_|B|B|B|_|C|C|_|D|D|D|_|
|_|A|A|_|B|B|B|_|C|C|_|_|D|D|D|
|_|A|A|_|B|B|B|_|_|C|C|_|D|D|D|
|_|A|A|_|_|B|B|B|_|C|C|_|D|D|D|
|_|_|A|A|_|B|B|B|_|C|C|_|D|D|D|
A total of 15 Possible configurations.
 
Configuration:
|_|_|_|_|_| # 5 cells and [2, 3] blocks
Possibilities:
#<RuntimeError: Those blocks will not fit in those cells>
</pre>
Anonymous user