Begin forwarded message:
On Mon, 18 Dec 2006 01:44:16 +0900, James Edward G. II wrote:
#960 it will have to iterate about 20,000 times, however it still
while h.size<i.to_i
p=p.sort_by{rand}
$=p*’ ’
h[$]=1if~/R.*K.*R/&&~/B(…)*B/
end
puts"Position ##{i}:",$_
My solution borrows heavily from Darren’s, but I don’t like the idea of
creating permutations by bogosorting, since there’s no guarantee you’ll
ever see every necessary permutation. (Here, he does see every
permutation, quickly, but that’s not guaranteed for different random
seeds.)
#!/usr/bin/env ruby
require ‘rubygems’
require ‘facets/core/enumerable/permutation’
require ‘set’
i=ARGV[0] || rand(960)+1
i=i.to_i
fail “A number between 1 and 960 is required” if not (1…960).include? i
pieces=%w’K R N B B Q N R’
generated=Set.new
pieces.each_permutation do |p|
arrangement=p.join
if arrangement=~/R.*K.*R/ and arrangement=~/B(…)*B/ and
not generated.include?(arrangement)
#the "generated" set is needed because identical objects will
#nevertheless appear in both possible permutations, like so:
# [1,1].each_permutation {|pe| p pe}
# gives the output
# [1, 1]
# [1, 1]
generated.add arrangement
if generated.size==i
print "Position ##{generated.size}:", arrangement, "\n"
break
end
end
end