Executable library
Library saved as Hailstone.sm
1
func hailstone(n) {
2
gather {
3
while (n > 1) {
4
take(n)
5
n = (n.is_even ? n/2 : (3*n + 1))
6
}
7
take(1)
8
}
9
}
10
11
if (__FILE__ == __MAIN__) { # true when not imported
12
var seq = hailstone(27)
13
say "hailstone(27) - #{seq.len} elements: #{seq.ft(0, 3)} [...] #{seq.ft(-4)}"
14
15
var n = 0
16
var max = 0
17
100_000.times { |i|
18
var seq = hailstone(i)
19
if (seq.len > max) {
20
max = seq.len
21
n = i
22
}
23
}
24
25
say "Longest sequence is for #{n}: #{max}"
26
}
Copied!
It can be run with:
1
$ sidef Hailstone.sm
Copied!
It can then be used with a program such as:
1
include Hailstone
2
3
var score = Hash()
4
100_000.times { |i| score{ Hailstone::hailstone(i).len } := 0 ++ }
5
6
var k = score.keys.max_by {|k| score{k} }
7
say "Most common length is #{k}, occurring #{score{k}} times"
Copied!
Called with a command line as:
1
$ sidef test_hailstone.sf
Copied!
The library is searched in the directories specified in the SIDEF_INC environment variable, which defaults to the current directory.
Last modified 1yr ago
Copy link