Created
December 10, 2009 16:00
-
-
Save epitron/253415 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def each_bits(size): | |
if size == 0: | |
yield () | |
else: | |
for bit in xrange(2): | |
for bits in each_bits(size-1): | |
yield (bit,) + bits | |
if __name__ == '__main__': | |
import sys | |
size = int( sys.argv[1] ) | |
for bits in each_bits(size): | |
print ''.join( str(b) for b in bits ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def each_bits(size, &block) | |
if size == 0 | |
yield [] | |
else | |
(0..1).each do |bit| | |
each_bits(size-1) do |bits| | |
yield [bit] + bits | |
end | |
end | |
end | |
end | |
if $0 == __FILE__ | |
each_bits(ARGV[0].to_i) { |bits| puts bits.join '' } | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ time ruby1.8 bits.rb 16 > /dev/null | |
real 0m9.861s | |
user 0m8.977s | |
sys 0m0.872s | |
$ time ruby1.9 bits.rb 16 > /dev/null | |
real 0m1.742s | |
user 0m1.740s | |
sys 0m0.004s | |
$ time python bits.py 16 > /dev/null | |
real 0m1.227s | |
user 0m1.204s | |
sys 0m0.016s |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment