我正在寻找一种从字符串中选择伪随机字符的方法。
例如,我有一个64个字符的字符串。我想选择0,1,4,5,8,9位置。
或者更难的是使用相同的字符串,我会选择位置0,1,2,4,6,8,10,11,12等等。
有快速的方法吗?
答案 0 :(得分:0)
这可能对您有用:
#!/usr/bin/env ruby
# Returns a string whose length is a random number between 0
# and the string length, and whose values are characters from
# random positions in the input string.
def random_string_char_subset(string)
chars = string.chars.shuffle
char_count = Random.rand(string.length + 1)
subset = ''
char_count.times { subset << chars.pop }
subset
end
puts random_string_char_subset 'hello' # => lhl
puts random_string_char_subset '0123456789' # => 821097634
puts random_string_char_subset 'bye' # => b
答案 1 :(得分:-1)
可以使用a = 'test string'
a[1] #=>e, assuming you are using a known value
a[Random.rand(a.length)] #assuming you want a random value
> "64charstring".chars.values_at(*[0, 1, 4])
=> ["6", "4", "a"]
答案 2 :(得分:-1)
是的,您可以使用Array#values_at
> "64charstring".chars.values_at(*[0, 1, 4]).join
=> "64a"
更新
如果您想获得字符串结果,请加入结果。
Cookie score = new Cookie("score", "0");
response.addCookie(score);
HttpSession session = request.getSession();
session.setAttribute("score", new Integer(0));