Skip to content

Instantly share code, notes, and snippets.

@FliiFe
Created January 8, 2016 16:51
Show Gist options
  • Save FliiFe/e16271d801951ff109cc to your computer and use it in GitHub Desktop.
Save FliiFe/e16271d801951ff109cc to your computer and use it in GitHub Desktop.
Bruteforcing the self-descriptive number.
/*jslint node: true */
'use strict';
//Initialize vars
var value = '00000';
var int = 0;
var finalString = "";
//Main code
while(!selfDescripting(value)){
value = increment(value);
console.log(value);
}
console.log(value, "Gotcha !");
//Guess it doesn't require doc... Just increment and add missing zeroes
function increment(toIncrement){
int = parseInt(toIncrement, 10);
++int;
finalString = ""+int;
while(finalString.length !== value.length){
finalString = "0" + finalString;
}
return finalString;
}
/**
* Tells wether or not a number is self-descripting.
* This means first digit is the number of 0 in the number, second the number of 1, ...
* @param {string} toCheck - string of the number to check.
* @return {boolean} true if number is self-descripting. Otherwise, false.
*/
function selfDescripting(toCheck){
var array = toCheck.split('');
var returns = true;
array.forEach(function (current, i){
var int = parseInt(current, 10);
if(int !== amountOf(i+'', toCheck)){
returns = false;
}
});
return returns;
}
/**
* Amount of character in a string.
* @param {string} char - Char to check for. Can only be 1 length.
* @param {string} inString - string to check for char.
* @return {number} Amount of char in inString.
*/
function amountOf(char, inString){
var amount = 0;
for(var i=0; i<inString.length; ++i){
if(inString[i] === char){
amount++;
}
}
return amount;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment