-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathP14.js
More file actions
74 lines (55 loc) · 1.17 KB
/
Copy pathP14.js
File metadata and controls
74 lines (55 loc) · 1.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
var struct = {};
determineLongestChain();
function getEven(num) {
return num / 2;
}
function getOdd(num) {
return (3 * num) + 1;
}
function getSequence(seq, num) {
if (num === 1)
return seq;
if (structContains(num)) {
seq.push(getStructSequence(num));
return seq;
} else if (num % 2 === 0) {
seq.push(getEven(num));
} else {
seq.push(getOdd(num));
}
return getSequence(seq, seq[seq.length - 1]);
}
function determineLongestChain() {
for (var i = 1e6; i > 1; i--) {
createStruct(i, getSequence([], i));
}
getLongest();
}
function getLongest() {
var llen = 0, len = 0, largest = {};
for (var i in struct) {
len = struct[i].length;
if (len > llen) {
llen = len;
largest = struct[i];
}
}
console.log(`The largest sequence length is ${largest.index}`);
}
function createStruct(index, sequence) {
if (struct[index]) {
throw new Error('Structure already has this index.');
} else {
struct[index] = {
index: index,
sequence: sequence,
length: sequence.length
}
}
}
function structContains(index) {
return !!struct[index] && !!(struct.index === index);
}
function getStructSequence(index) {
return struct[index].sequence;
}