Nonoblock: Difference between revisions

Content added Content deleted
(Added Ruby)
Line 348: Line 348:
'Those blocks will not fit in those cells'
'Those blocks will not fit in those cells'
AssertionError: Those blocks will not fit in those cells</pre>
AssertionError: Those blocks will not fit in those cells</pre>

=={{header|Ruby}}==
'''Simple version:'''
<lang ruby>def nonoblocks(cell, blocks)
raise 'Those blocks will not fit in those cells' if cell < blocks.inject(0,:+) + blocks.size - 1
result = []
nblock(cell, blocks, '', result)
result
end

def nblock(cell, blocks, position, result)
if cell <= 0
result << position[0..cell-1]
elsif blocks.empty? or blocks[0].zero?
result << position + '.' * cell
else
rest = cell - blocks.inject(:+) - blocks.size + 2
b0, brest = blocks[0], blocks.drop(1)
rest.times do |i|
nblock(cell-i-b0-1, brest, position + '.'*i + '#'*b0 + '.', result)
end
end
end

conf = [[ 5, [2, 1]],
[ 5, []],
[10, [8]],
[15, [2, 3, 2, 3]],
[ 5, [2, 3]], ]
conf.each do |cell, blocks|
begin
puts "#{cell} cells and #{blocks} blocks"
result = nonoblocks(cell, blocks)
puts result, result.size, ""
rescue => e
p e
end
end</lang>

{{out}}
<pre>
5 cells and [2, 1] blocks
##.#.
##..#
.##.#
3

5 cells and [] blocks
.....
1

10 cells and [8] blocks
########..
.########.
..########
3

15 cells and [2, 3, 2, 3] blocks
##.###.##.###..
##.###.##..###.
##.###.##...###
##.###..##.###.
##.###..##..###
##.###...##.###
##..###.##.###.
##..###.##..###
##..###..##.###
##...###.##.###
.##.###.##.###.
.##.###.##..###
.##.###..##.###
.##..###.##.###
..##.###.##.###
15

5 cells and [2, 3] blocks
#<RuntimeError: Those blocks will not fit in those cells>
</pre>


=={{header|Tcl}}==
=={{header|Tcl}}==