Skip to content

Instantly share code, notes, and snippets.

@mreed4
Created March 6, 2025 04:58
Show Gist options
  • Save mreed4/7098c93cb9e8675e458db5c40337b8a7 to your computer and use it in GitHub Desktop.
Save mreed4/7098c93cb9e8675e458db5c40337b8a7 to your computer and use it in GitHub Desktop.
// mreed4 committed on Aug 4, 2021
function randNum() {
return Math.floor(Math.random() * 1000000);
}
function collatz(num = randNum()) {
// num = parseInt(prompt(`Input any number`)); // User input
const initialNumber = num; // Save number before it mutates
// console.log({initialNumber});
let arr = [num]; // Initialize array
while (num != 1 && num > 0) {
// Ensures no infinite loop
if (num % 2 === 0) {
num /= 2;
arr.push(num);
} else {
num = num * 3 + 1;
arr.push(num);
}
}
// console.log(arr);
// Returns new array of the last digits in each number in arr
let arr2 = arr.map((int) => {
int = int.toString();
return parseInt(int[int.length - 1], 10);
});
// console.log(arr2);
let binArr = arr2.reverse().map((int) => int % 2);
let data = [];
for (let i = 0; i < binArr.length; i += 4) {
// let input = binArr.slice(i, i + 4).join("");
// data.push(Number(parseInt(input, 2).toString(10)))
data.push(binArr.slice(i, i + 4).length);
}
// console.log(data)
// console.log(arr)
let steps = arr.length;
// console.log(`${initialNumber} took ${steps} steps to resolve to 1`)
let max = Math.max(...arr);
let maxStep = arr.indexOf(max);
// max = max.toLocaleString();
// console.log(`The largest number was ${max} at step ${maxStep}`)
return [{ initialNumber }, { steps }, { max }, { maxStep }];
}
collatz();
let arr3 = [];
for (let i = 1; i <= Math.pow(10, 3); i++) {
arr3.push(collatz(i));
}
console.log(arr3);
// let arr9232 = arr3.filter(item => item[2] === "9,232").sort(item => ite)
// console.log(arr9232)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment