Create a gist now

Instantly share code, notes, and snippets.

@zunda /pw.rb
Created Feb 17, 2016

りっぱになったふっかつのじゅもん生成器
#/usr/bin/ruby
class Integer
def stringify(chars, min_digits = nil)
if self < 0
raise ArgumentError, "Can not stringify negative numbers"
end
i = 0
d = chars.size
x = self
r = ''
begin
x, c = x.divmod(d)
r << chars[c]
i += 1
end while x > 0 or (min_digits and i < min_digits)
return r.reverse
end
end
if __FILE__ == $0
require 'optparse'
default_length = 16
cset = {
:Alphabet => ('A'..'Z').to_a + ('a'..'z').to_a,
:Numbers => ('0'..'9').to_a,
:Space => [' '],
:Printables => (32..126).map{|i| i.chr},
:Hiragana_dot_bar => (''..'').to_a + ['', ''],
}
c = []
l = default_length
opt = OptionParser.new
opt.on('-a', 'include lower and upper case alphabet'){c += cset[:Alphabet]}
opt.on('-n', 'include 0 - 9'){c += cset[:Numbers]}
opt.on('-s', 'include space'){c += cset[:Space]}
opt.on('-p', 'include all printable characters (default)'){
c += cset[:Printables]
}
opt.on('--hiragana-dot-bar', 'include hiragana, cdot, and bar'){
c += cset[:Hiragana_dot_bar]
}
opt.on('-l LENGTH', "number of characters (default: #{default_length}"){|v|
l = Integer(v)
}
opt.on('--test', 'run tests'){
require 'test/unit'
class TestStringify < Test::Unit::TestCase
def setup
@c = ('0'..'9').to_a
end
def test_normal
assert_equal '123', 123.stringify(@c)
end
def test_negative
assert_raise ArgumentError do
-123.stringify(@c)
end
end
def test_normal_with_len
assert_equal '0123', 123.stringify(@c, 4)
assert_equal '123', 123.stringify(@c, 1)
end
end
r = Test::Unit::AutoRunner.run
exit r
}
opt.parse!(ARGV)
c += cset[:Printables] if c.empty?
c.uniq!
puts rand(c.size**l).stringify(c, l)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment