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>
Related
I want to have a logic where if I enter an even number I want next 10 even numbers to be printed and If I enter an odd number, I want next 10 odd numbers to be printed. How should I rectify this logic inside a function. If someone can please help me rectifying the logic which was answered.
JS
function oddEven() {
var input = prompt("");
for (let x = 1; x <= 10; x++) {
console.log(input + x * 2);
}
}
oddEven()
This should work for any number
const input = 2
for (let x = 1; x <= 10; x += 1) {
console.log(input + x * 2)
}
i hope this help
function printTen(input){
let list = []
let number = input
while(list.length <= 10){
number++
if(input % 2 === 0 && number % 2 === 0){
console.log(number + " is even");
list.push(number)
}else if(input % 2 !== 0 && number % 2 !== 0) {
console.log(number + " is odd");
list.push(number)
}
}
}
printTen(9)
let inputval = 2;
for (let x = 1; x <= 10; x++) {
console.log(inputval + x * 2)
}
Thinking it would be like
for number from range x,y
if number in ones or number in hundreds
print
else
??? I don't know what command to do the if statement.
You may try using the modulus operator here:
for (i=100; i <= 200; ++i) {
if (i % 10 == 2 || Math.floor(i / 10) % 10 == 3) {
console.log(i);
}
else {
// turned this off for demo purposes
// console.log("???");
}
}
for (let i = 100; i <= 200; i++) {
if (i % 10 === 2 || (i / 10) % 10 === 3) {
// do something
} else {
console.log('???')
}
}
You could store the tensDigit and onesDigit in variables and then check them in the if statement for better readabilty:
for (let num = 100; num <= 200; num++) {
const tensDigit = Math.floor((num % 100) / 10);
const onesDigit = num % 10;
if (tensDigit === 3 || onesDigit === 2) {
console.log(num);
}
}
your question is super ambiguous, please be more specific. That being said this function should do what you are asking.
function printIfDigitIsInPlace(INPUT, DIGIT, PLACE) {
const arr = Array.from(INPUT.toString());
if (arr[PLACE] === DIGIT.toString()) console.log(INPUT);
}
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
}
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/
I wrote a function to solve Euler #2 in Javascript for adding all the even Fibonacci numbers up to 4,000,000. However, when I run my function, the chrome dev tool keeps giving me zero as the answer. I am not sure why.
function DoEverything() {
oldnum = 0;
num = 1;
total = 0;
result = addFibNumbers(num, oldnum);
console.log(result);
}
function addFibNumbers(num, oldnum) {
while(num < 4000000) {
if (num % 2 == 0) {
newnum = num + oldnum;
total += newnum;
oldnum = num;
num = newnum;
}
return total;
}
}
DoEverything();
The reason its returning 0:
result = addFibNumbers(num, oldnum);//num=1,oldNum=0
//function
while(num < 4000000) { //num is 1, so it enters while
if (num % 2 == 0) {// 1 % 2 == 1, so skip this if
return total;// this ends the function, returning total=0 as nothing was changed
I guess you are looking to do this:
while(num < 4000000) {
newnum = num + oldnum;
if (newnum % 2 == 0 && newnum < 4000000) {
total += newnum;
}
oldnum = num;
num = newnum;
}
return total;
I would guess it is your while loop
Change this:
while(num < 4000000) {
if (num % 2 == 0) {
newnum = num + oldnum;
total += newnum;
oldnum = num;
num = newnum;
}
return total;
}
to this:
while(num < 4000000) {
if (num % 2 == 0) {
newnum = num + oldnum;
total += newnum;
oldnum = num;
num = newnum;
}
}
return total;
Your while loop is useless with a return in it and no if statement to control it's use.
In addition to modifying your while statement inside of addFibNumbers() like so:
function addFibNumbers(num, oldnum) {
while(num < 4000000) {
newnum = oldnum + num;
if (oldnum % 2 == 0) {
total += oldnum;
}
oldnum = num;
num = newnum;
}
return total;
}
you will also need to initialize the first two Fibonacci terms to 1 and 2:
oldnum = 1; and num = 2;