Last active
August 29, 2015 14:20
-
-
Save karmadude/6eb59b536215e282faae to your computer and use it in GitHub Desktop.
Happy Number
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://en.wikipedia.org/wiki/Happy_number | |
function happy(n) { | |
if(typeof n === "undefined") throw new Error("Missing argument n"); | |
var result = { | |
n: n, | |
happy: true, | |
seq: [n], | |
toString: function() { | |
return this.happy | |
? "Happy " + this.n + ": " + this.seq.join(", ") | |
: "Sad " + this.n; | |
} | |
}; | |
if(n === 1) return result; | |
function next(n) { | |
return ("" + n).split("") | |
.map(function(d) { d = parseInt(d); return d*d; }) | |
.reduce(function(p, c) { | |
return p + c; | |
}, 0); | |
} | |
do { | |
n = next(n); | |
if(result.seq.indexOf(n) > -1) { | |
result.happy = false; | |
result.seq = []; | |
} else { | |
result.seq.push(n); | |
} | |
} while(n > 1 && result.seq.length > 0); | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment