Why is my function sometimes squaring twice? - javascript

Writing a function to take a number, square each number and return them as a concatenated integer, ie. 3214 => 94116. For some reason, my code appears to occasionally square 2's and 3's twice making a 2 turn into 16 and 3 into 81. I can't figure it out. I'm not a super experienced debugger yet so any help would be appreciated.
function squareDigits(num){
let digits = (""+num).split("");
let intDigits = [];
for (x of digits) {
intDigits.push(parseInt(x));
}
for (x of intDigits) {
intDigits.splice(intDigits.indexOf(x), 1, x * x);
}
return parseInt(intDigits.join(""));
}
console.log(squareDigits(24));

Leaving aside the fact that you can do this more elegantly with something like map() the issue in your code is that it uses indexOf() while changing the values on each iteration. Since indexOf() returns the index of the first occurrence it is going to find digits that you have already replaced.
This is your original code with a few logs so you can understand what I mean:
function squareDigits(num){
let digits = (""+num).split("");
let intDigits = [];
for (x of digits) {
intDigits.push(parseInt(x));
}
for (x of intDigits) {
console.log('intDigits: ' + intDigits);
console.log(` index of ${x} = ${intDigits.indexOf(x)}`);
intDigits.splice(intDigits.indexOf(x), 1, x * x);
}
return parseInt(intDigits.join(""));
}
console.log('RESULT: ' + squareDigits(24));
Notice how in the second pass the index of 4 is 0 (the first position in the array) because you have replaced the original 2 by it's squared value 4.
A simple way to fix this is to not rely on indexOf() and iterate over the array the good old way, like this:
function squareDigits(num){
let digits = (""+num).split("");
let intDigits = [];
for (x of digits) {
intDigits.push(parseInt(x));
}
for (let i = 0; i < intDigits.length; i++) {
const x = intDigits[i];
console.log('intDigits: ' + intDigits);
console.log(` index of ${x} = ${i}`);
intDigits.splice(i, 1, x * x);
}
return parseInt(intDigits.join(""));
}
console.log('RESULT: ' + squareDigits(24));

A simplistic (and bug free) version of your function could be this:
const squareDigits = num => [...num.toString()].map(x => x ** 2).join('');
console.log(squareDigits(24));
Other variant:
const squareDigits = num => num.toString().replaceAll(/\d/g, x => x ** 2);
console.log(squareDigits(24));

Instead of looping twice use array methods .map() , .reduce() etc it will make your code effective .. wrote a simple function
See =>
function squareDigits(num){
let digits = String(num).split("");
digits = digits.reduce((final , digit)=> final += String( parseInt(digit) **2 ), "");
return digits
}
console.log(squareDigits(312));

As #Sebastian mentioned, intDigits.indexOf(x) will find the
first index. So after replacing the first one, there's a change you'll find the number you've just replaced.
We can simplify the function to :
function squareDigits(num){
return num.toString().split('').map(n => n ** 2).join('');
}
Where :
We convert the number to a string using toString()
We split the string into loose numbers using split('')
map() over each number
Return the square by using the Exponentiation (**) operator
join() the numbers to get the result
Example snippet:
function squareDigits(num){
return num.toString().split('').map(n => n ** 2).join('');
}
console.log(squareDigits(3214)); // 94116

Related

Recursive approach to Persistent bugger problem returns undefined

I've been trying to solve the following problem in codewars using recursion:
Write a function, persistence, that takes in a positive parameter num and returns its multiplicative persistence, which is the number of times you must multiply the digits in num until you reach a single digit.
For example (Input --> Output):
39 --> 3 (because 3*9 = 27, 2*7 = 14, 1*4 = 4 and 4 has only one digit)
999 --> 4 (because 9*9*9 = 729, 7*2*9 = 126, 1*2*6 = 12, and finally 1*2 = 2)
4 --> 0 (because 4 is already a one-digit number)
Here's what I've tried:
var numOfIterations = 0;
function persistence(num) {
//code me
var i;
var digits=[];
var result = 1;
if (num.toString().length==1) {
return numOfIterations;
} else {
numOfIterations++;
digits = Array.from(String(num), Number);
for (i=0;i<digits.size;i++) {
result=result*digits[i];
}
persistence(result);
}
}
But for some reason, instead of returning the number of iterations, it returns undefined. I've been told that I'm not using recursion correctly, but I just can't find the problem.
Other answers have explained what's wrong with your code. I just want to point out a simpler implementation:
const multiplyDigits = (n) =>
n < 10 ? n : (n % 10) * multiplyDigits (n / 10 | 0);
const persistence = (n) =>
n < 10 ? 0 : 1 + persistence (multiplyDigits (n));
[39, 999, 4] .forEach (t => console .log (`${t}:\t${persistence (t)}`));
multiplyDigits does just what it says, recursively multiplying the final digit by the number left when you remove that last digit (Think of | 0 as like Math .floor), and stopping when n is a single digit.
persistence checks to see if we're already a single digit, and if so, returns zero. If not, we add one to the value we get when we recur on the multiple of the digits.
I've been told that I'm not using recursion correctly
You're recursing, but you're not returning the result of that recursion. Imagine for a moment just this structure:
function someFunc() {
if (someCondition) {
return 1;
} else {
anotherFunc();
}
}
If someCondition is false, what does someFunc() return? Nothing. So it's result is undefined.
Regardless of any recursion, at its simplest if you want to return a result from a function then you need to return it:
function persistence(num) {
//...
if (num.toString().length==1) {
//...
} else {
//...
return persistence(result); // <--- here
}
}
As #David wrote in his answer, you were missing the return of the recursive call to itself.
Plus you were using digits.size instead of digits.length.
Anyway consider that one single digit being zero will collpse the game because that's enough to set the result to zero despite how many digits the number is made of.
To deal with the reset of numOfIterations, at first I tried using function.caller to discriminate between recursive call and direct call and set the variable accordingly. Since that method is deprecated as shown here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/caller
I opted for the optional argument iteration that gets set to zero as default, to keep track of that value while it goes down the call stack. This solution still fulfills the fact that the caller doesn't need to know a new interface for the function to work.
//var numOfIterations = 0;
function persistence(num, iteration=0) {
/*
Commented strategy using the function.caller
working but deprecated so I can't recommend anymore
used optional argument iteration instead
//gets the name of the caller scope
let callerName = persistence.caller?.name;
//if it's different from the name of this function
if (callerName !== 'persistence')
//reset the numOfIterations
numOfIterations = 0;
*/
var digits=[];
if (num.toString().length==1){
return iteration;
} else {
var result = 1;
digits = Array.from(String(num), Number);
for (let i=0;i<digits.length;i++) {
result = result * digits[i];
}
return persistence(result, iteration+1);
}
}
console.log( persistence(39) ); //-> 3
console.log( persistence(999 ) ); //-> 4
console.log( persistence(4) ); //-> 0
You can do something like this
const persistenceTailRecursive = (num, iterations = 0) => {
const str = '' + num;
if(str.length === 1){
return iterations;
}
return persistenceTailRecursive(str.split('').reduce((res, a) => res * parseInt(a), 1), iterations + 1)
}
const persistence = (num) => {
const str = '' + num;
if(str.length === 1){
return 0;
}
return 1 + persistence(str.split('').reduce((res, a) => res * parseInt(a), 1))
}
console.log(persistenceTailRecursive(93))
console.log(persistenceTailRecursive(999))
console.log(persistence(93))
console.log(persistence(999))
There are 2 versions
1 tailRecursive call the same method with the exact signature (preventing stackoverflow in some languages like scala)
2 basic the result is calculated at the end

javascript external called function does not return value [duplicate]

Im solving a codewars problem and im pretty sure i've got it working:
function digital_root(n) {
// ...
n = n.toString();
if (n.length === 1) {
return parseInt(n);
} else {
let count = 0;
for (let i = 0; i < n.length; i++) {
//console.log(parseInt(n[i]))
count += parseInt(n[i]);
}
//console.log(count);
digital_root(count);
}
}
console.log(digital_root(942));
Essentially it's supposed to find a "digital root":
A digital root is the recursive sum of all the digits in a number.
Given n, take the sum of the digits of n. If that value has two
digits, continue reducing in this way until a single-digit number is
produced. This is only applicable to the natural numbers.
So im actually getting the correct answer at the end but for whatever reason on the if statement (which im watching the debugger run and it does enter that statement it will say the return value is the correct value.
But then it jumps out of the if statement and tries to return from the main digital_root function?
Why is this? shouldn't it break out of this when it hits the if statement? Im confused why it attempt to jump out of the if statement and then try to return nothing from digital_root so the return value ends up being undefined?
You're not returning anything inside else. It should be:
return digital_root(count);
^^^^^^^
Why?
digital_root is supposed to return something. If we call it with a one digit number, then the if section is executed, and since we return from that if, everything works fine. But if we provide a number composed of more than one digit then the else section get executed. Now, in the else section we calculate the digital_root of the count but we don't use that value (the value that should be returned). The line above could be split into two lines of code that makes it easy to understand:
var result = digital_root(count); // get the digital root of count (may or may not call digital_root while calculating it, it's not owr concern)
return result; // return the result of that so it can be used from the caller of digital_root
Code review
My remarks is code comments below
// javascript generally uses camelCase for function names
// so this should be digitalRoot, not digital_root
function digital_root(n) {
// variable reassignment is generally frowned upon
// it's somewhat silly to convert a number to a string if you're just going to parse it again
n = n.toString();
if (n.length === 1) {
// you should always specify a radix when using parseInt
return parseInt(n);
} else {
let count = 0;
for (let i = 0; i < n.length; i++) {
//console.log(parseInt(n[i]))
count += parseInt(n[i]);
}
// why are you looping above but then using recursion here?
// missing return keyword below
digital_root(count);
}
}
console.log(digital_root(942));
Simple recursive solution
With some of those things in mind, let's simplify our approach to digitalRoot...
const digitalRoot = n =>
n < 10 ? n : digitalRoot(n % 10 + digitalRoot((n - n % 10) / 10))
console.log(digitalRoot(123)) // => 6
console.log(digitalRoot(1234)) // 10 => 1
console.log(digitalRoot(12345)) // 15 => 6
console.log(digitalRoot(123456)) // 21 => 3
console.log(digitalRoot(99999999999)) // 99 => 18 => 9
Using reduce
A digital root is the recursive sum of all the digits in a number. Given n, take the sum of the digits of n. If that value has two digits, continue reducing in this way until a single-digit number is produced. This is only applicable to the natural numbers.
If you are meant to use an actual reducing function, I'll show you how to do that here. First, we'll make a toDigits function which takes an integer, and returns an Array of its digits. Then, we'll implement digitalRoot by reducing those those digits using an add reducer initialized with the empty sum, 0
// toDigits :: Int -> [Int]
const toDigits = n =>
n === 0 ? [] : [...toDigits((n - n % 10) / 10), n % 10]
// add :: (Number, Number) -> Number
const add = (x,y) => x + y
// digitalRoot :: Int -> Int
const digitalRoot = n =>
n < 10 ? n : digitalRoot(toDigits(n).reduce(add, 0))
console.log(digitalRoot(123)) // => 6
console.log(digitalRoot(1234)) // 10 => 1
console.log(digitalRoot(12345)) // 15 => 6
console.log(digitalRoot(123456)) // 21 => 3
console.log(digitalRoot(99999999999)) // 99 => 18 => 9
its a recursive function the code should be somewhat like this
function digital_root(n) {
// ...
n=n.toString();
if(n.length === 1){
return parseInt(n);
}
else
{
let count = 0;
for(let i = 0; i<n.length;i++)
{
//console.log(parseInt(n[i]))
count+=parseInt(n[i]);
}
//console.log(count);
return digital_root(count);
}
}
you should return the same function instead of just calling it to get the correct call stack

C++ to javascript conversion

The question I'm doing is:
Write a JavaScript program to create a function which returns the number of times required to replace a given number with the sum of its digits until it converts to a single digit number. Like if given number is 123, number of times required to convert it into a single digit number is 1 (1+2+3=6). Your output code should be in the format console.log("Result is ", variableName)
I could not find the solution to this problem so I googled it and found this page.
The code on this page is in C/C++ ,Java etc...I took the C++ code and tried to convert it to javascript myself and this is the result:
var num=prompt("Enter a number");
var a= num.toString();
function test(x)
{var temporary_sum = 0, count = 0;
while (x.length() > 1)
{
temporary_sum = 0;
// computing sum of its digits
for (var i = 0; i < x.length(); i++)
temporary_sum += ( x[ i ] - '0' ) ;
// converting temporary_sum into string
// x again .
x = temporary_sum.toString() ;
// increase the count
count++;
}
return count;
}
var output = test(a) ;
console.log("Result is: ", output);
This code does not give any output at all. How can I fix this? Is there a better way to do this question?
Here is a better way to do that using recursion. And reduce
function test(x,count=0){
if(String(x).length === 1) return count;
let sum = String(x).split('').reduce((ac,a) => Number(a) + ac,0);
return test(sum,++count);
}
console.log(test(123)) //1
console.log(test(456)) //2
console.log(test(99999999999)) //3
I'll answer your last question - yes, there is a better way to do this question. You want to use recursion. You can also split the string on '' to convert its digits into an array, and you want to use parseInt to turn it back into a number.
I will use a different approach (I don't say it would be better). First, I will skip the mapping from number to string and wraps the logic that sums the digits of some number into a function called sumDigits(). This way you have a resusable method you can use for other purposes later. The second step is to define your test function using the previously created sumDigits mainly using the while loop you already have but testing with another condition and generalized to accept also integer negative numbers:
const sumDigits = (num) =>
{
let sum = 0;
while (num)
{
sum += num % 10, num = Math.floor(num / 10);
}
return sum;
}
const test = (num) =>
{
let counter = 0;
num = Math.abs(num);
while (num >= 10)
{
num = sumDigits(num), counter++;
}
return counter;
}
console.log(test(123));
console.log(test(456));
console.log(test(-789));

Javascript recursive function not returning value?

Im solving a codewars problem and im pretty sure i've got it working:
function digital_root(n) {
// ...
n = n.toString();
if (n.length === 1) {
return parseInt(n);
} else {
let count = 0;
for (let i = 0; i < n.length; i++) {
//console.log(parseInt(n[i]))
count += parseInt(n[i]);
}
//console.log(count);
digital_root(count);
}
}
console.log(digital_root(942));
Essentially it's supposed to find a "digital root":
A digital root is the recursive sum of all the digits in a number.
Given n, take the sum of the digits of n. If that value has two
digits, continue reducing in this way until a single-digit number is
produced. This is only applicable to the natural numbers.
So im actually getting the correct answer at the end but for whatever reason on the if statement (which im watching the debugger run and it does enter that statement it will say the return value is the correct value.
But then it jumps out of the if statement and tries to return from the main digital_root function?
Why is this? shouldn't it break out of this when it hits the if statement? Im confused why it attempt to jump out of the if statement and then try to return nothing from digital_root so the return value ends up being undefined?
You're not returning anything inside else. It should be:
return digital_root(count);
^^^^^^^
Why?
digital_root is supposed to return something. If we call it with a one digit number, then the if section is executed, and since we return from that if, everything works fine. But if we provide a number composed of more than one digit then the else section get executed. Now, in the else section we calculate the digital_root of the count but we don't use that value (the value that should be returned). The line above could be split into two lines of code that makes it easy to understand:
var result = digital_root(count); // get the digital root of count (may or may not call digital_root while calculating it, it's not owr concern)
return result; // return the result of that so it can be used from the caller of digital_root
Code review
My remarks is code comments below
// javascript generally uses camelCase for function names
// so this should be digitalRoot, not digital_root
function digital_root(n) {
// variable reassignment is generally frowned upon
// it's somewhat silly to convert a number to a string if you're just going to parse it again
n = n.toString();
if (n.length === 1) {
// you should always specify a radix when using parseInt
return parseInt(n);
} else {
let count = 0;
for (let i = 0; i < n.length; i++) {
//console.log(parseInt(n[i]))
count += parseInt(n[i]);
}
// why are you looping above but then using recursion here?
// missing return keyword below
digital_root(count);
}
}
console.log(digital_root(942));
Simple recursive solution
With some of those things in mind, let's simplify our approach to digitalRoot...
const digitalRoot = n =>
n < 10 ? n : digitalRoot(n % 10 + digitalRoot((n - n % 10) / 10))
console.log(digitalRoot(123)) // => 6
console.log(digitalRoot(1234)) // 10 => 1
console.log(digitalRoot(12345)) // 15 => 6
console.log(digitalRoot(123456)) // 21 => 3
console.log(digitalRoot(99999999999)) // 99 => 18 => 9
Using reduce
A digital root is the recursive sum of all the digits in a number. Given n, take the sum of the digits of n. If that value has two digits, continue reducing in this way until a single-digit number is produced. This is only applicable to the natural numbers.
If you are meant to use an actual reducing function, I'll show you how to do that here. First, we'll make a toDigits function which takes an integer, and returns an Array of its digits. Then, we'll implement digitalRoot by reducing those those digits using an add reducer initialized with the empty sum, 0
// toDigits :: Int -> [Int]
const toDigits = n =>
n === 0 ? [] : [...toDigits((n - n % 10) / 10), n % 10]
// add :: (Number, Number) -> Number
const add = (x,y) => x + y
// digitalRoot :: Int -> Int
const digitalRoot = n =>
n < 10 ? n : digitalRoot(toDigits(n).reduce(add, 0))
console.log(digitalRoot(123)) // => 6
console.log(digitalRoot(1234)) // 10 => 1
console.log(digitalRoot(12345)) // 15 => 6
console.log(digitalRoot(123456)) // 21 => 3
console.log(digitalRoot(99999999999)) // 99 => 18 => 9
its a recursive function the code should be somewhat like this
function digital_root(n) {
// ...
n=n.toString();
if(n.length === 1){
return parseInt(n);
}
else
{
let count = 0;
for(let i = 0; i<n.length;i++)
{
//console.log(parseInt(n[i]))
count+=parseInt(n[i]);
}
//console.log(count);
return digital_root(count);
}
}
you should return the same function instead of just calling it to get the correct call stack

Fibonacci Sequence - Find the number of digits - JavaScript

So, I have successfully written the Fibonacci sequence to create an array with the sequence of numbers, but I need to know the length (how many digits) the 500th number has.
I've tried the below code, but its finding the length of the scientific notation (22 digits), not the proper 105 it should be returning.
Any ideas how to convert a scientific notation number into an actual integer?
var fiblength = function fiblength(nth) {
var temparr = [0,1];
for(var i = 2; i<=nth; i++){
var prev = temparr[temparr.length-2],
cur = temparr[temparr.length-1],
next = prev + cur;
temparr.push(next);
}
var final = temparr[temparr.length-1].toString().length;
console.log(temparr[temparr.length-1]);
return final;
};
a = fiblength(500);
console.log(a);
Why not use the simple procedure of dividing the number by 10 until the number is less than 1.
Something as simple as this should work (a recursive def obv works as well)
function getDigits(n) {
var digits = 0;
while(n >= 1) {
n/=10;
digits += 1;
}
return digits;
}
getDigits(200);//3
getDigits(3.2 * 10e20);//=>22
Here's a solution in constant time:
function fiblength(n) {
return Math.floor((n>1)?n*.2089+.65051:1);
}
Let's explain how I arrived to it.
All previous solutions will probably not work for N>300 unless you have a BigNumber library in place. Also they're pretty inneficient.
There is a formula to get any Fibonacci number, which uses PHI (golden ratio number), it's very simple:
F(n) = ABS((PHI^n)/sqrt(5))
Where PHI=1.61803399 (golden ratio, found all over the fibonacci sequence)
If you want to know how many digits a number has, you calculate the log base 10 and add 1 to that. Let's call that function D(n) = log10(n) + 1
So what you want fiblength to be is in just the following function
fiblength(n) = D(F(n)) // number of digits of a fibonacci number...
Let's work it out, so you see what the one liner code will be like once you use math.
Substitute F(n)
fiblength(n) = D(ABS((PHI^n)/sqrt(5)))
Now apply D(n) on that:
fiblength(n) = log10(ABS((PHI^n)/sqrt(5))) + 1
So, since log(a/b) = log(a) - log(b)
fiblength(n) = log10(ABS((PHI^n))) - log10(sqrt(5))) + 1
and since log(a^n) = n * log(a)
fiblength(n) = n*log10(PHI) - log10(sqrt(5))) + 1
Then we evaluate those logarithms since they're all on constants
and add the special cases of n=0 and n=1 to return 1
function fiblength(n) {
return Math.floor((n>1)?n*.2089+.65051:1);
}
Enjoy :)
fiblength(500) => 105 //no iterations necessary.
Most of the javascript implementations, internally use 64 bit numbers. So, if the number we are trying to represent is very big, it uses scientific notation to represent those numbers. So, there is no pure "javascript numbers" based solution for this. You may have to look for other BigNum libraries.
As far as your code is concerned, you want only the 500th number, so you don't have to store the entire array of numbers in memory, just previous and current numbers are enough.
function fiblength(nth) {
var previous = 0, current = 1, temp;
for(var i = 2; i<=nth; i++){
temp = current;
current = previous + current;
previous = temp;
}
return current;
};
My Final Solution
function fiblength(nth) {
var a = 0, b = 1, c;
for(var i=2;i<=nth;i++){
c=b;
b=a+b;
a=c;
}
return Math.floor(Math.log(b)/Math.log(10))+1;
}
console.log(fiblength(500));
Thanks for the help!!!
The problem is because the resulting number was converted into a string before any meaningful calculations could be made. Here's how it could have been solved in the original code:
var fiblength = function fiblength(nth) {
var temparr = [0,1];
for(var i = 2; i<=nth; i++){
var prev = temparr[temparr.length-2],
cur = temparr[temparr.length-1],
next = prev + cur;
temparr.push(next);
}
var x = temparr[temparr.length-1];
console.log(x);
var length = 1;
while (x > 1) {
length = length + 1;
x = x/10;
}
return length;
};
console.log ( fiblength(500) );

Categories

Resources