Last active
August 7, 2020 15:21
-
-
Save aresnick/223154a7a27ec2434c8e4575f555943b to your computer and use it in GitHub Desktop.
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
#!/usr/bin/env node | |
var logging = false; | |
var raiseTo = function(number, power) { | |
var value = number; | |
for (var i = 1; i < power; i++) { | |
value = value*number; | |
} | |
return value; | |
}; | |
var getNumberInBase = function(number, digits) { | |
var base = digits.length; // What is the biggest number a digit can represent in each place? | |
// Figure out how many digits we'll need | |
var numberDigits = [0]; // Initialize a list to hold our answer | |
// Add digits to our list until the base raised to the number of digits is bigger than our number | |
while (raiseTo(base, numberDigits.length) <= number) { numberDigits.push(0); } | |
// Now we have a list of the right number of 0's. | |
// We're going to go through and subtract from our number to distribute amongst the digits, starting with the biggest | |
var remaining = number; | |
numberDigits.forEach(function(digit, index) { // For each place value, starting with the biggest | |
var placeValue = raiseTo(base,numberDigits.length-index-1); // Compute our place value (base ^ current index), -1 because length is one bigger than our place value | |
logging ? console.log("Looking at the the", placeValue+"'s", "place…") : null; | |
// Iterate from the beginning to the end of our digits, testing which one is bigger than our remainder | |
var testDigit = 0; | |
while (testDigit*placeValue <= remaining) { testDigit++; } | |
// At this point, testDigit*placeValue is bigger than the remainder, so we know which digit this placeValue needs | |
// Note that we subtract one from testDigit because our while loop stops once it's too big, so we want to back up one | |
logging ? console.log("Setting to", digits[testDigit-1]) : null; | |
numberDigits[index] = digits[testDigit-1]; | |
// Subtract the value we've just calculated from our remainder | |
remaining -= placeValue*(testDigit-1); | |
logging ? console.log("Now", remaining, "remains…") : null; | |
}); | |
return numberDigits.join(''); | |
}; | |
var tests = [ | |
{ | |
number: 80, | |
digits: [0,1,2,3,4,5,6,7,8,9] | |
}, | |
{ | |
number: 80, | |
digits: [0,1] | |
}, | |
{ | |
number: 80, | |
digits: ["A", "B", "C", "D"] | |
}, | |
{ | |
number: 80, | |
digits: ["😋", 2, "💩", "🎨", 5, "🐶", "🐿"] | |
} | |
]; | |
tests.forEach(function(test){ | |
console.log( | |
"Converting", test.number, | |
"from base 10 to", test.digits, | |
"yields", getNumberInBase(test.number, test.digits) | |
); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment