Published
Edited
Apr 28, 2022
1 star
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
// Imperative solution

resultsImperative = {
const initialNumber = startingNumber;
let maxIterations = maxIterationsConfig;
let intermediateNumber = initialNumber;
let results = [];

while (intermediateNumber !== 1 && maxIterations > 0) {
results.push(intermediateNumber);
if (intermediateNumber % 2) {
intermediateNumber = intermediateNumber * 3 + 1;
} else {
intermediateNumber = intermediateNumber / 2;
}
maxIterations--;
}
results.push(1);
return {
results,
conjectureIsValid: maxIterations !== 0
};
}
Insert cell
Insert cell
Insert cell
// Functional solution

resultsFunctional = {
const collatzSolver = (num, maxIterations = 10000, results = [num]) => {
if (num === 1 || maxIterations <= 0) {
return {
results,
conjectureIsValid: maxIterations !== 0
};
} else {
const newResult = num % 2 ? num * 3 + 1 : num / 2;
return collatzSolver(newResult, maxIterations - 1, [
...results,
newResult
]);
}
};

return collatzSolver(startingNumber, maxIterationsConfig);
}
Insert cell

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more