Jump to content

Hailstone sequence: Difference between revisions

m
→‎{{header|Dart}}: Brought Dart code up to date
(→‎{{header|Vlang}}: Rename "Vlang" in "V (Vlang)")
m (→‎{{header|Dart}}: Brought Dart code up to date)
Line 3,038:
 
=={{header|Dart}}==
<syntaxhighlight lang="dart">List<int> hailstone(int n) {
import 'package:collection/collection.dart';
if(n<=0) {
import 'dart:collection';
throw new IllegalArgumentException("start value must be >=1)");
List<int> hailstone(int n) {
if(n <= 0) {
throw new IllegalArgumentExceptionArgumentError("start value must be >=1)");
}
Queue<int>var seq =new Queue<int>();
seq.add(n);
while(n != 1) {
n = n%2 == 0 ?( n ~/ 2).toInt() : 3 * n + 1;
seq.add(n);
}
return new List<int>seq.fromtoList(seq);
 
// apparently List is missing toString()
String iterableToString(Iterable seq) {
String str="[";
Iterator i=seq.iterator();
while(i.hasNext()) {
str+=i.next();
if(i.hasNext()) {
str+=",";
}
}
return str+"]";
}
 
main() {
for(int i = 1; i <= 10; i++) {
print("h($i) ="+iterableToString( ${hailstone(i))}");
}
List<int>var h27 = hailstone(27);
List<int>var first4 = h27.getRangetake(0,4).toList();
print("first 4 elements of h(27): "+iterableToString($first4)");
Expectassert(ListEquality().listEqualsequals([27, 82, 41, 124], first4));
 
List<int>var last4 = h27.getRangeskip(h27.length - 4,).take(4).toList();
print("last 4 elements of h(27): "+iterableToString($last4)");
Expectassert(ListEquality().listEqualsequals([8, 4, 2, 1], last4));
 
print("length of sequence h(27): "+${h27.length}");
Expect.equalsassert(112, == h27.length);
 
int seq = 0, max = 0;
for(int i = 1; i <= 100000; i++) {
List<int>var h = hailstone(i);
if(h.length > max) {
max = h.length;
seq = i;
}
}
print("up to 100000 the sequence h($seq) has the largest length ($max)");
}</syntaxhighlight>
{{out}}
<pre>h(1) = [1]
h(2) = [2, 1]
h(3) = [3, 10, 5, 16, 8, 4, 2, 1]
h(4) = [4, 2, 1]
h(5) = [5, 16, 8, 4, 2, 1]
h(6) = [6, 3, 10, 5, 16, 8, 4, 2, 1]
h(7) = [7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1]
h(8) = [8, 4, 2, 1]
h(9) = [9, 28, 14, 7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1]
h(10) = [10, 5, 16, 8, 4, 2, 1]
first 4 elements of h(27): [27, 82, 41, 124]
last 4 elements of h(27): [8, 4, 2, 1]
length of sequence h(27): 112
up to 100000 the sequence h(77031) has the largest length (351)</pre>
1

edit

Cookies help us deliver our services. By using our services, you agree to our use of cookies.