how to solve number Pelindrom by using for loop in javascript - javascript

How to solve this giving undesired result, getting false always.
function isPelindrom(n) {
if (n < 0) return false;
let orgNum = n
let reversed = 0
for (let x = 0; x <= orgNum; x++) {
let lastDigit = orgNum % 10;
reversed = (reversed * 10) + lastDigit;
orgNum = parseInt(orgNum / 10);
}
return n == reversed
}
isPelindrom(12321)

function Palindrome(num) {
let numToStringArray = num.toString();
const reversed = numToStringArray.toString().split('').reverse().join('');
return numToStringArray === reversed ? "It's a palindrome" : "It's not a palindrome";
}
console.log(Palindrome(989));
console.log(Palindrome(23));
console.log(Palindrome(9));
function Palindrome(number) {
var temp = number, final = 0;
while (number > 0) {
rem = number % 10;
number = parseInt(number / 10);
final = final * 10 + rem;
}
if (temp == final) {
return "It's Palindrome";
}
else {
return "It's not Palindrome";
}
}
console.log(Palindrome(989));
console.log(Palindrome(23));
console.log(Palindrome(9));

You can change it to a for loop and either set it to greater or equal to 0.1 or just greater than 0.
function isPelindrom(n) {
if (n < 0) return false;
let orgNum = n
let reversed = 0
while(orgNum>=0.1) {
let lastDigit = orgNum % 10;
reversed = (reversed * 10) + lastDigit;
orgNum = parseInt(orgNum / 10);
}
return n == reversed
}
console.log(isPelindrom(12321))
console.log(isPelindrom(12322))

Does while loop count?
const isPalindrome = num => {
const origin = num
let reversed = 0
while (num !== 0) {
const digit = num % 10
reversed = reversed * 10 + digit
num = Math.floor(num / 10)
}
return origin === reversed
}
console.log(isPalindrome(12321))
console.log(isPalindrome(12331))

You can try this:
function isPelindrom(n) {
if (n < 0) return false;
let orgNum = n
let reversed = 0
var numberOfDigits = 0;
for(i = orgNum; i > 1; ++i){
++numberOfDigits;
i = Math.floor(i/10);
}
for (let x = 0; x < numberOfDigits; x++) {
let lastDigit = orgNum % 10;
reversed = (reversed * 10) + lastDigit;
orgNum = parseInt(orgNum / 10);
}
return n == reversed
}

Related

How to properly solve fibonacci series in javascript using matrices

I am trying to solve the Fibonacci algorithm using matrices. My target time complexity is an o(logn) instead of an o(n). The return output of the program is not the number for the series but the sixth significant digits. Its why I am returning the remainder of the solution divided by a million.
I have written the code and it runs well but I noticed that for extremely large inputs, I get a NAN(not a number) instead of an output
const fib = (n) => {
let fibMatrix = [[1,1], [1,0]]
if(n == 0){
return 0;
}
raiseToPower(fibMatrix, n - 1);
return Math.floor(fibMatrix[0][0] % 1000000)
}
const raiseToPower = (matrix, n) => {
if(n == 0 || n == 1){
return;
}
let newMatrix = [[1,1], [1,0]]
raiseToPower(matrix, Math.floor(n / 2))
multiplyMatrices(matrix, matrix)
if(n % 2 !== 0){
multiplyMatrices(matrix, newMatrix)
}
}
const multiplyMatrices = (matrix, newMatrix) => {
let x = matrix[0][0]*newMatrix[0][0] + matrix[0][1]*newMatrix[1][0];
let y = matrix[0][0]*newMatrix[0][1] + matrix[0][1]*newMatrix[1][1];
let z = matrix[1][0]*newMatrix[0][0] + matrix[1][1]*newMatrix[1][0];
let w = matrix[1][0]*newMatrix[0][1] + matrix[1][1]*newMatrix[1][1];
matrix[0][0] = x;
matrix[0][1] = y;
matrix[1][0] = z;
matrix[1][1] = w;
}
console.log(fib(2000))
Thats my code above. Is there anything I could change to actually make this much more performant?
I actually found the error. My numbers were getting larger than the maximum value.
I changed this by instead returning the remainder of my value divided by a million to the matrix and then returning the value from the matrix instead of returning the value and then dividing by a million. The former is efficient and works for any sized inputs.
const fib = (n) => {
let fibMatrix = [[1,1], [1,0]]
if(n == 0){
return 0;
}
raiseToPower(fibMatrix, n - 1);
return (fibMatrix[0][0])
}
const raiseToPower = (matrix, n) => {
if(n == 0 || n == 1){
return;
}
let newMatrix = [[1,1], [1,0]]
raiseToPower(matrix, Math.floor(n / 2))
multiplyMatrices(matrix, matrix)
if(n % 2 !== 0){
multiplyMatrices(matrix, newMatrix)
}
}
const multiplyMatrices = (matrix, newMatrix) => {
let x = (matrix[0][0]*newMatrix[0][0] + matrix[0][1]*newMatrix[1][0]);
let y = (matrix[0][0]*newMatrix[0][1] + matrix[0][1]*newMatrix[1][1]);
let z = (matrix[1][0]*newMatrix[0][0] + matrix[1][1]*newMatrix[1][0]);
let w = (matrix[1][0]*newMatrix[0][1] + matrix[1][1]*newMatrix[1][1]);
matrix[0][0] = x % 1000000;
matrix[0][1] = y % 1000000;
matrix[1][0] = z % 1000000;
matrix[1][1] = w % 1000000;
}
console.log(fib(10000))

How to generate a random number based on fixed character set in javascript

I'm generating a number based on a fixed character set.
function generator()
{
var text = "";
var char_list = "LEDGJR", number_list = "0123456789";
for(var i=0; i < 2; i++ )
{
text += char_list.charAt(Math.floor(Math.random() * char_list.length));
}
for(var j=0; j < 2; j++ )
{
text += number_list.charAt(Math.floor(Math.random() *
number_list.length));
}
return text;
}
Result :
RE39, JE12 etc...
Once all the permutation related to the above sequence is done, then the generator should generate string as RE391, JE125 means adding one more number to the complete number.
How can I get the permutation count of sequence?
For simplicity consider the case where:
chars = "AB"
nums = "123";
and we want to generate a 4-digit sequence of two chars and two numbers.
We define these variables
rows = [chars, chars, nums, nums]
rowSizes = rows.map(row => row.length) // [2, 2, 3, 3]
It’s easy to see the set size of all possible permuations equals:
spaceSize = rowSizes.reduce((m, n) => m * n, 1) // 2*2*3*3 = 36
And we define two set of utility functions, usage of which I'll explain in detail later.
decodeIndex() which gives us uniqueness
function euclideanDivision(a, b) {
const remainder = a % b;
const quotient = (a - remainder) / b;
return [quotient, remainder]
}
function decodeIndex(index, rowSizes) {
const rowIndexes = []
let dividend = index
for (let i = 0; i < rowSizes.length; i++) {
const [quotient, remainder] = euclideanDivision(dividend, rowSizes[i])
rowIndexes[i] = remainder
dividend = quotient
}
return rowIndexes
}
getNextIndex() which gives us pseudo-randomness
function isPrime(n) {
if (n <= 1) return false;
if (n <= 3) return true;
if (n % 2 == 0 || n % 3 == 0) return false;
for (let i = 5; i * i <= n; i = i + 6) {
if (n % i == 0 || n % (i + 2) == 0) return false;
}
return true;
}
function findNextPrime(n) {
if (n <= 1) return 2;
let prime = n;
while (true) {
prime++;
if (isPrime(prime)) return prime;
}
}
function getIndexGeneratorParams(spaceSize) {
const N = spaceSize;
const Q = findNextPrime(Math.floor(2 * N / (1 + Math.sqrt(5))))
const firstIndex = Math.floor(Math.random() * spaceSize);
return [firstIndex, N, Q]
}
function getNextIndex(prevIndex, N, Q) {
return (prevIndex + Q) % N
}
Uniqueness
Like mentioned above, spaceSize is the number of all possible permutations, thus each index in range(0, spaceSize) uniquely maps to one permutation. decodeIndex helps with this mapping, you can get the corresponding permutation to an index by:
function getSequenceAtIndex(index) {
const tuple = decodeIndex(index, rowSizes)
return rows.map((row, i) => row[tuple[i]]).join('')
}
Pseudo-Randomness
(Credit to this question. I just port that code into JS.)
We get pseudo-randomness by polling a "full cycle iterator"†. The idea is simple:
have the indexes 0..35 layout in a circle, denote upperbound as N=36
decide a step size, denoted as Q (Q=23 in this case) given by this formula‡
Q = findNextPrime(Math.floor(2 * N / (1 + Math.sqrt(5))))
randomly decide a starting point, e.g. number 5
start generating seemingly random nextIndex from prevIndex, by
nextIndex = (prevIndex + Q) % N
So if we put 5 in we get (5 + 23) % 36 == 28. Put 28 in we get (28 + 23) % 36 == 15.
This process will go through every number in circle (jump back and forth among points on the circle), it will pick each number only once, without repeating. When we get back to our starting point 5, we know we've reach the end.
†: I'm not sure about this term, just quoting from this answer
‡: This formula only gives a nice step size that will make things look more "random", the only requirement for Q is it must be coprime to N
Full Solution
Now let's put all the pieces together. Run the snippet to see result.
I've also includes the a counter before each log. For your case with char_list="LEDGJR", number_list="0123456789", the spaceSize for 4-digit sequence should be 6*6*10*10 = 3600
You'll observe the log bump to 5-digit sequence at 3601 😉
function euclideanDivision(a, b) {
const remainder = a % b;
const quotient = (a - remainder) / b;
return [quotient, remainder];
}
function decodeIndex(index, rowSizes) {
const rowIndexes = [];
let divident = index;
for (let i = 0; i < rowSizes.length; i++) {
const [quotient, remainder] = euclideanDivision(divident, rowSizes[i]);
rowIndexes[i] = remainder;
divident = quotient;
}
return rowIndexes;
}
function isPrime(n) {
if (n <= 1) return false;
if (n <= 3) return true;
if (n % 2 == 0 || n % 3 == 0) return false;
for (let i = 5; i * i <= n; i = i + 6) {
if (n % i == 0 || n % (i + 2) == 0) return false;
}
return true;
}
function findNextPrime(n) {
if (n <= 1) return 2;
let prime = n;
while (true) {
prime++;
if (isPrime(prime)) return prime;
}
}
function getIndexGeneratorParams(spaceSize) {
const N = spaceSize;
const Q = findNextPrime(Math.floor((2 * N) / (1 + Math.sqrt(5))));
const firstIndex = Math.floor(Math.random() * spaceSize);
return [firstIndex, N, Q];
}
function getNextIndex(prevIndex, N, Q) {
return (prevIndex + Q) % N;
}
function generatorFactory(rows) {
const rowSizes = rows.map((row) => row.length);
function getSequenceAtIndex(index) {
const tuple = decodeIndex(index, rowSizes);
return rows.map((row, i) => row[tuple[i]]).join("");
}
const spaceSize = rowSizes.reduce((m, n) => m * n, 1);
const [firstIndex, N, Q] = getIndexGeneratorParams(spaceSize);
let currentIndex = firstIndex;
let exhausted = false;
function generator() {
if (exhausted) return null;
const sequence = getSequenceAtIndex(currentIndex);
currentIndex = getNextIndex(currentIndex, N, Q);
if (currentIndex === firstIndex) exhausted = true;
return sequence;
}
return generator;
}
function getRows(chars, nums, rowsOfChars, rowsOfNums) {
const rows = [];
while (rowsOfChars--) {
rows.push(chars);
}
while (rowsOfNums--) {
rows.push(nums);
}
return rows;
}
function autoRenewGeneratorFactory(chars, nums, initRowsOfChars, initRowsOfNums) {
let realGenerator;
let currentRowOfNums = initRowsOfNums;
function createRealGenerator() {
const rows = getRows(chars, nums, initRowsOfChars, currentRowOfNums);
const generator = generatorFactory(rows);
currentRowOfNums++;
return generator;
}
realGenerator = createRealGenerator();
function proxyGenerator() {
const sequence = realGenerator();
if (sequence === null) {
realGenerator = createRealGenerator();
return realGenerator();
} else {
return sequence;
}
}
return proxyGenerator;
}
function main() {
const char_list = "LEDGJR"
const number_list = "0123456789";
const generator = autoRenewGeneratorFactory(char_list, number_list, 2, 2);
let couter = 0
setInterval(() => {
console.log(++couter, generator())
}, 10);
}
main();

Sorting an integer without using string methods and without using arrays

can anyone come with an idea of how to sort an integer without using an array, and without using string methods as well as sort() method?
for example
input: 642531
output: 123456
I started by writing 2 simple functions - one which checks the length of the number, the other one splits the integer at some point and switches between 2 desired numbers. Below are the 2 functions.
I got stuck with the rest of the solution...
function switchDigits(num, i) { // for input: num=642531, i = 4 returns 624135
let temp = num;
let rest = 0;
for (let j = 0; j < i - 1; j++) {
rest = rest * 10;
rest = rest + temp % 10;
temp = (temp - temp % 10) / 10;
}
let a = temp % 10;
temp = (temp - a) / 10;
let b = temp % 10;
temp = (temp - b) / 10;
temp = Math.pow(10, i - 2) * temp;
temp = temp + 10 * a + b;
temp = Math.pow(10, i - 1) * temp;
temp = temp + rest;
return temp;
}
function checkHowManyDigits(num) { //input: 642534, output: 6 (length of the integer)
let count = 0;
while (num > 0) {
let a = num % 10;
num = (num - a) / 10;
count++;
}
return count;
}
let num = 642534;
let i = checkHowManyDigits(num);
console.log(switchDigits(num));
It actually complicated requirement and so does this answer. It's pure logic and as it is it's a question from a test you should try understanding the logic on your own as a homework.
function checkHowManyDigits(num) { //input: 642534, output: 6 (length of the integer)
let count = 0;
while (num > 0) {
let a = num % 10;
num = (num - a) / 10;
count++;
}
return count;
}
function sortDigit(numOriginal) {
let i = checkHowManyDigits(numOriginal);
let minCount = 0;
let min = 10;
let num = numOriginal;
while (num > 0) {
let d = num % 10;
num = (num - d) / 10;
if (d < min) {
min = d;
minCount = 0;
} else if (d === min) {
minCount++;
}
}
let result = 0;
while (minCount >= 0) {
result += min * Math.pow(10, i - minCount - 1);
minCount--;
}
let newNum = 0;
num = numOriginal;
while (num > 0) {
let d = num % 10;
num = (num - d) / 10;
if (d !== min) {
newNum = newNum * 10 + d;
}
}
if (newNum == 0) return result;
else return result += sortDigit(newNum);
}
console.log(sortDigit(642531));
You could have a look to greater and smaller pairs, like
64
46
The delta is 18, which gets an idea if you compare other pairs, like
71
17
where the delta is 54. Basically any difference of two digits is a multiple of 9.
This in mind, you get a function for taking a single digit out of a number and a single loop who is sorting the digits by using the calculated delta and subtract the value, adjusted by the place.
function sort(number) {
const
getDigit = e => Math.floor(number / 10 ** e) % 10,
l = Math.ceil(Math.log10(number)) - 1;
let e = l;
while (e--) {
const
left = getDigit(e + 1),
right = getDigit(e);
if (left <= right) continue;
number += (right - left) * 9 * 10 ** e;
e = l;
}
return number;
}
console.log(sort(17)); // 17
console.log(sort(71)); // 17
console.log(sort(642531)); // 123456
console.log(sort(987123654)); // 123456789
So eventually I found the best solution.
*This solution is based on a Java solution I found in StackOverFlow forums.
let store = 0;
function getReducedNumbr(number, digit) {
console.log("Remove " + digit + " from " + number);
let newNumber = 0;
let repeateFlag = false;
while (number>0) {
let t = number % 10;
if (t !== digit) {
newNumber = (newNumber * 10) + t;
} else if (t == digit) {
if (repeateFlag) {
console.log(("Repeated min digit " + t + " found. Store is : " + store));
store = (store * 10) + t;
console.log("Repeated min digit " + t + " added to store. Updated store is : " + store);
} else {
repeateFlag = true;
}
}
number = Math.floor(number / 10);
}
console.log("Reduced number is : " + newNumber);
return newNumber;}
function sortNum(num) {
let number = num;
let original = number;
let digit;
while (number > 0) {
digit = number % 10;
console.log("Last digit is : " + digit + " of number : " + number);
temp = Math.floor(number/10);
while (temp > 0) {
console.log("subchunk is " + temp);
t = temp % 10;
if (t < digit) {
digit = t;
}
temp = Math.floor(temp/10);
}
console.log("Smallest digit in " + number + " is " + digit);
store = (store * 10) + digit;
console.log("store is : " + store);
number = getReducedNumbr(number, digit);
}
console.log(("Ascending order of " + original + " is " + store));
return store;
}
console.log(sortNum(4214173));
you can see how it works here https://jsfiddle.net/9dpm14fL/1/

Money denomination program for ATM in js that would be flexible to handle and dispense money in minimum notes

the code should be able to handle any amount up to 20000, For example, suppose the Entered amount is 2600 when the balance in the card is 3000. Will output following :
New Balance - 400
Notes:
2000 * 1
500 * 1
100 * 1
(only three banknotes 2000, 500, 100) and the cash limit is 20000
I am new in the javascript world, and I am not able to write the code, could anyone help me out??? please!
var h = 5;
var f = 2;
var t = 1;
var ifAmtLessThn2000 = ifAmtLessThn2000(n) {
var temp;
if (n < 500) {
h += (n / 100);
return {
h
}
} else if (n >= 500 && n < 2000) {
f += n / 500;
h += (n - 500) / 100;
return {
h,
f
}
} else {
temp = n - 1500;
if (temp < 500) {
h += (temp / 100);
return {
h
}
console.log('hundred : ' + h);
} else {
f += 1;
h += (temp - 500) / 100;
console.log('five hundred : ' + f);
console.log('hundred : ' + h);
return {
f,
h
}
}
}
}
var ifAmtGreaterthan2000 = (n) => {
var h = 0;
var f = 0;
var t = 0;
var tt = 0;
var temp;
if (n < 2000) {
tt += (n / 2000);
}
else if (n >= 2000 && n < 10000) {
f += n / 500;
h += (n - 500) / 100;
}
else {
temp = n - 1500;
if (temp < 500) {
h += (temp / 100);
}
else {
f += 1;
h += (temp - 500) / 100;
}
}
}
var checkAmt = (n) => {
if (n < 100 || (n % 100) > 0) {
console.log("Invalid Amount : less than 100 ");
} else {
if (n > 20000) {
console.log("ATM Cash Limit exceeds.");
} else {
if (n <= 2500) {
ifAmtLessThn2500(n);
console.log(h + " x 100");
console.log(f + " x 500");
} else {
temp = n - 2500;
t += temp / 1000;
if (temp > 500)
temp = temp - (1000 * (t - 1));
ifAmtLessThn2500(temp);
console.log(h + " x 100");
console.log(f + " x 500");
console.log(t + " x 1000");
}
}
}
}
checkAmt(2500);
Sorry for a dumb program, but I need help please can anyone give me a solution in typeScript code, returning the req denomination in array!!
const withdraw = (amount) => {
let hundredNotes = 0;
let fiftyNotes = 0;
let twentyNotes = 0;
while (amount >= 20) {
if (
amount >= 100 &&
((amount % 100) % 50 === 0 || (amount % 100) % 20 === 0)
) {
amount -= 100;
hundredNotes++;
} else if (
amount >= 50 &&
((amount % 50) % 100 === 0 || (amount % 50) % 20 === 0)
) {
amount -= 50;
fiftyNotes++;
} else {
amount -= 20;
twentyNotes++;
}
}
return [hundredNotes, fiftyNotes, twentyNotes];
};
console.log(withdraw(230));
console.log(withdraw(250));
amtArray = [2000, 500, 100]; // the denomination you want to find.
for (let i = 0; i < this.amtArray.length; i++) {
this.resultArray.push(Math.floor(total / this.amtArray[i]));
// Get the new total
total = total % this.amtArray[i];
}
var twothousands_notes = this.resultArray[0];
var fivehundred_notes = this.resultArray[1];
var hundred_notes = this.resultArray[2];
console.log('calculated amt : ' + '100 : ' +
hundred_notes + ' 500 : ' +
fivehundred_notes + ' 2000 : ' +
twothousands_notes);
Based on the amount you can adjust the logic.
Hope this helps.. :)
this would cover all your cases
function dispenseCase (inputAmount) {
var notes = [];
var balance = 3000;
if(inputAmount !== 0 && inputAmount % 100 == 0 && inputAmount <= balance) {
var notes2000 = Math.round(inputAmount / 2000);
var notes500 = Math.round((inputAmount - (notes2000 * 2000)) / 500 );
var notes100 = Math.round((inputAmount - ((notes2000 * 2000) + (notes500 * 500))) / 100);
notes.push(notes2000);
notes.push(notes500);
notes.push(notes100);
console.log("balance in you account = ", balance - inputAmount);
console.log(notes);
}
else if (inputAmount > balance) {
console.log("Insufficient balance in your account");
}
else if ( inputAmount % 100 != 0 || inputAmount < 100 ) {
console.log( "Invalid amount entered, amount should be multiples of 100");
}
}
dispenseCase(2600);
ATM denomination program in Javascript.
Here, It'll find the minimum number of notes of different denominations that sum the entered amount. Starting from the highest denomination note to the lowest notes.
function countCurrency(amount) {
var notes = [2000, 500, 200, 100];
var noteCounter = [0, 0, 0, 0];
for (var i = 0; i < 4; i++) {
if (amount >= notes[i]) {
noteCounter[i] = Math.floor(amount / notes[i]);
amount = amount - noteCounter[i] * notes[i];
}
}
// Print notes denomination
console.log("Denomination Count:");
for (var j = 0; j < 4; j++) {
if (noteCounter[j] !== 0) {
console.log(notes[j] + " : " + noteCounter[j]);
}
}
}
countCurrency(3300);
Here is the working example
https://codesandbox.io/s/atm-denomination-javascript-o0wb4?file=/src/index.js
this would print the number of notes in a 2000, 500, 100 order for the amount you enter
function dispenseCase (inputAmount) {
var notes = [];
if(inputAmount !== 0) {
var notes2000 = Math.round(inputAmount / 2000);
var notes500 = Math.round((inputAmount - (notes2000 * 2000)) / 500 );
var notes100 = Math.round((inputAmount - ((notes2000 * 2000) + (notes500 * 500))) / 100);
notes.push(notes2000);
notes.push(notes500);
notes.push(notes100);
console.log(notes);
}
}
dispenseCase(2600);
hope this helps
//ATM Cash Denominations //Cash Input Value Already been Provided in this method // You may use a input stream method to input a user input value
public class Denominations
{
public static void main(String args[])//throws IOException
{
int notes[]={5000,2000,1000,500,100}; //storing all the denominations in an array
int amount = 27000;
int copy=amount; //Making a copy of the amount
int totalNotes=0,count=0;
System.out.println("\nATM CASH DENOMINATIONS: \n");
for(int i=0;i<5;i++) //Since there are 5 different types of notes, hence we check for each note.
{
count=amount/notes[i]; // counting number of notes[i] notes
if(count!=0) //printing that denomination if the count is not zero
{
System.out.println(notes[i]+"\tx\t"+count+"\t= "+notes[i]*count);
}
totalNotes=totalNotes+count; //finding the total number of notes
amount=amount%notes[i]; //finding the remaining amount whose denomination is to be found
}
System.out.println("--------------------------------");
System.out.println("TOTAL\t\t\t= "+copy); //printing the total amount
System.out.println("--------------------------------");
System.out.println("Total Number of Notes\t= "+totalNotes); //printing the total number of notes
}
}
let sumToDenominate=Math.floor(Math.random() * 100);
let billsValues = [100, 50, 20, 10, 5,1];
let restAfterDenomination = [];
let billsNumber = [];
function denomination(sum, billsValues) {
printInitialValue( sumToDenominate, billsValues);
initializeArray( sumToDenominate, billsValues);
for (let i = 1; i <= billsValues.length; i++) {
if (restAfterDenomination[i - 1] > 0 || restAfterDenomination < billsNumber[i]) {
billsNumber.push(Math.floor(restAfterDenomination[i - 1] / billsValues[i]));
console.log(`bill's number of `, billsValues[i], "=>", billsNumber[i]);
restAfterDenomination.push(restAfterDenomination[i - 1] - (billsNumber[i] * billsValues[i]));
} else {
console.log(`rest is less than smallest bill or equal to 0`);
billsNumber.push(0);
// break;
}
}
}
function printInitialValue(amount, billsValue) {
console.log("Denomination sumToDenominate: ", amount);
console.log("____________");
for (const logEntry of billsValue) {
console.log(logEntry);
}
console.log("__________");
}
function initializeArray(amount, billsValues) {
billsNumber.push(Math.floor(amount / billsValues[0]));
console.log(`bill's number of`, billsValues[0], "=>", billsNumber[0]);
restAfterDenomination.push(amount - (billsNumber[0] * billsValues[0]));
denomination(sumToDenominate,billsValues);

Convert integer to roman numerals - there must be a better way [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I'm working through the intermediate algorithms in the FreeCodeCamp curriculum. One of them involves converting integers to roman numerals. My solution (presented below) works, however it is very much the "naive" approach, if you will. The task hints that array.splice(), array.indexOf(), and array.join() ought to be used. My implementation only uses array.join().
Edited question for precision: Will someone provide an implementation that makes use of all of the aforementioned methods?
Thanks.
My implementation:
function convertToRoman(num) {
var I = 1, V = 5, X = 10, L = 50, C = 100, D = 500, M = 1000;
var numerals = [];
var i;
if(num >= 1000){
var numMs = Math.floor(num / 1000);
for (i = 0; i < numMs; i++){
numerals.push('M');
}
num = num % 1000;
}
if(num >= 900){
numerals.push('CM');
num = num - 900;
}
if(num < 900){
if(num >= 500){
numerals.push('D');
num = num - 500;
}
if(num >= 400){
numerals.push('CD');
num = num - 400;
}
var numCs = Math.floor(num / 100);
for(i = 0; i < numCs; i++){
numerals.push('C');
}
num = num % 100;
}
if(num >= 90){
numerals.push('XC');
num = num - 90;
}
if(num < 90){
if(num >= 50){
numerals.push('L');
num = num - 50;
}
if(num >= 40){
numerals.push('XL');
num = num - 40;
}
var numXs = Math.floor(num / 10);
for(i = 0; i < numXs; i++){
numerals.push('X');
}
num = num % 10;
}
if(num == 9){
numerals.push('IX');
num = num - 9;
}
if(num < 9){
if(num >= 5){
numerals.push('V');
num = num - 5;
}
if(num >=4){
numerals.push('IV');
num = num - 4;
}
var numIs = Math.floor(num / 1);
for(i = 0; i < numIs; i++){
numerals.push('I');
}
}
var converted = numerals.join('');
return converted;
}
UPDATE: Another answer found here, but it does not use the methods I'm interested in using.
You may do as follows;
function toRoman(n){
var numerals = ["I","V","X","L","C","D","M"];
return n.toString()
.split("")
.reverse()
.reduce((p,c,i) => (c === "0" ? ""
: c < "4" ? numerals[2*i].repeat(c)
: c === "4" ? numerals[2*i] + numerals[2*i+1]
: c < "9" ? numerals[2*i+1] + numerals[2*i].repeat(c-5)
: numerals[2*i] + numerals[2*i+2]) + p,"");
}
console.log(toRoman(1453));
This is a proposal which use Array#reduce for any part of the number to convert.
function toRoman(i) {
return ('0000' + i).slice(-4).split('').map(Number).reduce(function (r, a, i) {
var value = 'MDCLXVI';
if (a === 4 || a === 9) {
r += value[i * 2];
a++;
}
if (a === 10) {
r += value[i * 2 - 2];
a -= 10;
}
if (a >= 5) {
r += value[i * 2 - 1];
a -= 5;
}
while (a) {
r += value[i * 2];
a--;
}
return r;
}, '');
}
var i;
for (i = 1; i <= 3000; i++) {
document.getElementById('tt').innerHTML += i + ' ' + toRoman(i) + `\n`;
}
<pre id="tt"></pre>

Categories