Square every digit of a number - javascript

I am trying to learn JavaScript but find it to be a bit confusing. I am trying to square every digit of a number
For example: run 9119 through the function, 811181 will come out, because 9^2 is 81 and 1^2 is 1.
My code:
function squareDigits(num){
return Math.pow(num[0],2) && Math.pow(num[1],2);
}
Correct code:
function squareDigits(num){
return Number(('' + num).split('').map(function (val) { return val * val;}).join(''));
}
I do not know why .map, .split, and .join was used to answer the question.

.split takes a string and splits it into an array based on the character(s) passed to it '' in this case.
So
("9119").split('') === ["9", "1", "1", "9"]
.map works like a for loop but takes a function as an argument. That function is applied to every member of the array.
So
["9", "1", "1", "9"].map(function(val) { return val * val;}) === ["81", "1", "1", "81"]
.join does the opposite of .split. It takes an Array and concatenates it into a string based on the character(s) passed to it.
So
["81", "1", "1", "81"].join('') === "811181"
Additionally, the && operator checks to see if the expressions on either side of it evaluate to true. If both expressions evaluate to true, only then will it return true. It always returns a Boolean though. I think you wanted to convert your values to string first using Number.toString() and then append them together using the + operator
return Math.pow(num[0],2).toString() + Math.pow(num[1],2).toString();

function squareDigits(num) {
// Convert the result to a number. "252525" -> 252525
return Number(
num.toString() // num === "555"
.split('') // ["5", "5", "5"]
.map(elem => elem * elem) "5" * "5" === 25 (Type coversion)
// Now we have [25, 25, 25]
.join('') // "252525"
);
}
squareDigits(555);

There are several methods of this, but the first that comes to mind is to pass the number as a string, split it, then parse the numbers, square them individually, make them strings, and paste them back together, it sounds complex but makes sense once you see it
//function takes number as an argument
function convertNumber(num){
//the toString method converts a number into a string
var number = num.toString();
//the split method splits the string into individual numbers
var arr = number.split("");
//this variable will hold the numbers that we square later
var squaredArr = [];
//the for loop iterates through everything in our array
for(var i=0; i<arr.length; i++){
//parseInt turns a string into a number
var int = parseInt(arr[i]);
//Math.pow raises integers to a given exponent, in this case 2
int = Math.pow(int, 2);
//we push the number we just made into our squared array as a string
squaredArr.push(int.toString());
}
//the function returns the numbers in the squared array after joining
//them together. You could also parseInt the array if you wanted, doing
//this as parseInt(squaredArr[0]); (this would be done after joining)
return squaredArr.join('');
}

Basically you need single digits for getting squared values.
You could take Array.from, which splits a string (which is a type with an implemented Symbol.iterator) into characters and uses an optional maping for the values.
function sqare(number) {
return +Array.from(number.toString(), v => v * v).join('');
}
console.log(sqare(9119));

try these code..
function squareDigits(n) {
return +(n.toString().split('').map(val => val * val).join(''));
}
console.log(squareDigits(4444));
here + sign is convert the string into an integer.

Related

Generate minimum number of sets of substrings with max substring length

Given a string, I'd like to create the minimum number of sets of substrings where:
substrings have a length up to x
if two sets differ when a substring in one set can be composed of smaller substrings in the other set, the second set can be excluded
For example, the substring "abcdef" with max substring length of 3 would result in the following:
[
['abc','def'],
['ab','cde','f'],
['ab','cd','ef'],
['a','bcd','ef'],
]
['abc','de','f'] is not included because of condition (2). eg, 'def' is compsed of 'de','f'
The following recursive allSubstrings() method isn't quite right and doesn't feel like the right approach. Also has the problem of being slow with longer strings.
const allSubstrings = (input,max_len = 3) => {
if( input.length === 1) return [[input]];
let result = [];
const start = input.substring(1);
allSubstrings(start).forEach(function(subresult) {
let tmp = subresult.slice(0);
if( tmp[0].length < max_len ){
tmp[0] = input.charAt(0) + tmp[0];
result.push(tmp);
}
if( subresult.length > 1 ){
if( subresult.slice(0,2).join('').length <= max_len ){
return;
}
if( subresult.slice(subresult.length-2).join('').length <= max_len ){
return;
}
}
tmp = subresult.slice(0);
tmp.unshift(input.charAt(0));
result.push(tmp);
});
return result;
}
Here's one possible approach using recursion, not optimized for performance (e.g., there's no memoization):
function splits(s: string, maxLen: number, minInitLen: number = 1): string[][] {
const ret: string[][] = s.length ? [] : [[]];
for (let i = Math.min(maxLen, s.length); i >= minInitLen; i--) {
for (const r of splits(s.slice(i), maxLen, maxLen + 1 - i)) {
ret.push([s.slice(0, i), ...r]);
}
}
return ret;
}
The idea is that splits() takes not just the string s to split and the maximum length maxLen of substrings, but also the minimum allowable length minInitLen for the first substring. When you start splitting the string this initial length is 1, but inside the recursion it could be larger. After all, let's say that you've split "abcdef" into "a" so far. Now you need to split "bcdef", but the next substring has to have length 3 ("bcd"), since "b" would collapse into "ab" and "bc" would collapse into "abc". If you've split it into "ab" so far, then the next substring has to have length at least 2 ("cd" or "cde"), since "c" would collapse into "abc". The relevant math is that if the current substring is of length i, then the next substring must have at least length maxLen + 1 - i.
The base case for the recursion is when you are asked to split an empty string. In this case you want to return [[]]; there is exactly one way to split an empty string. If you are splitting a non-empty string then you want to iterate your first substring length i between minInitLen and maxLen (well, you can't exceed s.length either), and calculate the recursive result splits(s.slice(i), maxLen, maxLen + 1 - i), and then for each set of strings in the result, prepend the initial substring s.slice(0, i) to it.
Let's see if it works:
console.log(splits("abcdef", 3))
// [["abc", "def"], ["ab", "cde", "f"], ["ab", "cd", "ef"], ["a", "bcd", "ef"]]
console.log(splits("abcdefgh", 5))
// [["abcde", "fgh"], ["abcd", "efgh"], ["abc", "defgh"], ["ab", "cdefg", "h"],
// ["ab", "cdef", "gh"], ["a", "bcdef", "gh"]]
It looks good, at least for your example input. I'm not sure if there are edge cases, or if performance becomes a problem for large strings (it probably depends very much on what "large" means). And one could certainly refactor to use functional programming array methods instead of for loops if one wanted. But at least it works.
Playground link to code

Palindrome creator using javascript and recursion

I need to create a function that takes a number and returns palindrome of this number, by summing its reverse number. For example 312 + 213 = 525. But what's more important, I must use recursion in this situation.
And, for example, number 96 needs like 4 iterations to become 4884.
The strategy is already explained in other comments. Here is a sample recursive JS-implementation that accomplishes your goal:
// Keeps recursively addding the reverse number until a palindrome
// number is obtained
function findPalindrome(num) {
numStr = num.toString();
revNumStr = numStr.split("").reverse().join("");
if (numStr === revNumStr) { // True if palindrome
return num;
} else { // Recursive part
return findPalindrome(num + parseInt(revNumStr))
}
}
console.log(findPalindrome(312));
console.log(findPalindrome(213));
console.log(findPalindrome(96));
You could
get number
convert number to string
get an array of digits
reverse the array
join the array
convert to number
add to original number
convert sum to string
iterate string and check if the value from the beginning is equal to the one at the end
if true return with sum
if false call function again with sum <-- This is the recursion part.

Sum Strings as Numbers

I am trying to solve a kata that seems to be simple on codewars but i seem to not be getting it right.
The instruction for this is as simple as below
Given the string representations of two integers, return the string representation of the sum of those integers.
For example:
sumStrings('1','2') // => '3'
A string representation of an integer will contain no characters besides the ten numerals "0" to "9".
And this is what i have tried
function sumStrings(a,b) {
return ((+a) + (+b)).toString();
}
But the results solves all except two and these are the errors i get
sumStrings('712569312664357328695151392', '8100824045303269669937') - Expected: '712577413488402631964821329', instead got: '7.125774134884027e+26'
sumStrings('50095301248058391139327916261', '81055900096023504197206408605') - Expected: '131151201344081895336534324866', instead got: '1.3115120134408189e+29'
I don't seem to understand where the issues is from. Any help would help thanks.
The value you entered is bigger than the int type max value. You can try changing your code to:
function sumStrings(a,b) {
return ((BigInt(a)) + BigInt(b)).toString();
}
This way it should return the right value
You could pop the digits and collect with a carry over for the next digit.
function add(a, b) {
var aa = Array.from(a, Number),
bb = Array.from(b, Number),
result = [],
carry = 0,
i = Math.max(a.length, b.length);
while (i--) {
carry += (aa.pop() || 0) + (bb.pop() || 0);
result.unshift(carry % 10);
carry = Math.floor(carry / 10);
}
while (carry) {
result.unshift(carry % 10);
carry = Math.floor(carry / 10);
}
return result.join('');
}
console.log(add('712569312664357328695151392', '8100824045303269669937'));
console.log(add('50095301248058391139327916261', '81055900096023504197206408605'));
The problem is that regular javascript integers are not having enough space to store that much big number, So it uses the exponential notation to not lose its precision
what you can do is split each number into parts and add them separately,
one such example is here SO answer
My solution is:
function sumStrings(a,b) {
return BigInt(a) + BigInt(b) + ''
}
Converting from a string to a number or vice versa is not perfect in any language, they will be off by some digits. This doesn't seem to affect small numbers, but it affects big numbers a lot.
The function could go like this.
function sumStrings(a, b) {
return (BigInt(a) + BigInt(b)).toString() // or parseInt for both
}
However, it's still not perfect since if we try to do:
console.log((4213213124214211215421314213.0 + 124214321214213434213124211.0) === sumStrings('4213213124214211215421314213', '124214321214213434213124211'))
The output would be false.

Sum of all Object Keys returns a String, not a Number as expected

I'm trying to add all the values of an object into one variable for the total, but I seem to be concatenating them instead?
binance.depth("BNBBTC", (error, depth, symbol) => {
a = 0;
for (value in depth.bids){
a += value;
};
console.log(a);
});
This is the output:
00.001081000.001080900.001080800.001080200.001080000.001079700.001079600.001079100
Any help would be much appreciated
The unexpected behavior of your code is a side effect of adding a String and a Number together. Unlike other languages that complain about adding a Number to a String or vice versa, JavaScript will implicitly convert a Number to a String and not complain at all.
This is discussed in Section 2 of the 2ality Blog Post, JavaScript quirk 1: implicit conversion of values. See below excerpt:
2. Implicit conversion of strings
In web development, you often get values as strings that are actually numbers or booleans. For example, when users enter this kind of data in a form. If you forget to explicitly convert these strings then JavaScript will surprise you negatively in two ways: First, there will be no warning. Second, the values will be converted automatically, but wrongly. The plus operator (+), for instance, is problematic, because it concatenates strings as soon as one of its operands is a string. During the following interaction with JavaScript, the assumption is that we are adding 1 to 5. Instead, we are concatenating the strings '5' and '1'.
> var x = '5'; // wrong assumption: x is a number
> x + 1
> '51'
Incorporating the solution of casting value to a Number, the above code can be rewritten more concisely with the help of ES6. Using Array#reduce() the sum can be modularized a bit. I've also included Error-First Callbacks for Error Handling.
const sumArray = values => values.reduce((sum, value) => (sum + Number(value)), 0)
const getDepth = (data, cb) => {
binance.depth(data, (err, {bids}) => {
if (err) {
return cb(err)
}
return cb(null, sumArray(Object.keys(bids)))
})
}
getDepth('BNBBTC', (err, depth) => {
if (err) {
console.log(err)
} else {
console.log(depth)
}
})
thanks guys
i needed to convert to value to a number first
a += Number(value)
maybe converting value to int such as
var v = parseInt(value);
a += value;
Can not post a comment as my reputation is below 50 :(.
Try converting value to a number before adding: a += Number(value)
All need to do is add a + in front of the string
let a = "10"
let b = "20"
let c = +a + +b //c = 30
In your case:
a += +value

Javascript string/integer comparisons

I store some parameters client-side in HTML and then need to compare them as integers. Unfortunately I have come across a serious bug that I cannot explain. The bug seems to be that my JS reads parameters as strings rather than integers, causing my integer comparisons to fail.
I have generated a small example of the error, which I also can't explain. The following returns 'true' when run:
console.log("2" > "10")
Parse the string into an integer using parseInt:
javascript:alert(parseInt("2", 10)>parseInt("10", 10))
Checking that strings are integers is separate to comparing if one is greater or lesser than another. You should always compare number with number and string with string as the algorithm for dealing with mixed types not easy to remember.
'00100' < '1' // true
as they are both strings so only the first zero of '00100' is compared to '1' and because it's charCode is lower, it evaluates as lower.
However:
'00100' < 1 // false
as the RHS is a number, the LHS is converted to number before the comparision.
A simple integer check is:
function isInt(n) {
return /^[+-]?\d+$/.test(n);
}
It doesn't matter if n is a number or integer, it will be converted to a string before the test.
If you really care about performance, then:
var isInt = (function() {
var re = /^[+-]?\d+$/;
return function(n) {
return re.test(n);
}
}());
Noting that numbers like 1.0 will return false. If you want to count such numbers as integers too, then:
var isInt = (function() {
var re = /^[+-]?\d+$/;
var re2 = /\.0+$/;
return function(n) {
return re.test((''+ n).replace(re2,''));
}
}());
Once that test is passed, converting to number for comparison can use a number of methods. I don't like parseInt() because it will truncate floats to make them look like ints, so all the following will be "equal":
parseInt(2.9) == parseInt('002',10) == parseInt('2wewe')
and so on.
Once numbers are tested as integers, you can use the unary + operator to convert them to numbers in the comparision:
if (isInt(a) && isInt(b)) {
if (+a < +b) {
// a and b are integers and a is less than b
}
}
Other methods are:
Number(a); // liked by some because it's clear what is happening
a * 1 // Not really obvious but it works, I don't like it
Comparing Numbers to String Equivalents Without Using parseInt
console.log(Number('2') > Number('10'));
console.log( ('2'/1) > ('10'/1) );
var item = { id: 998 }, id = '998';
var isEqual = (item.id.toString() === id.toString());
isEqual;
use parseInt and compare like below:
javascript:alert(parseInt("2")>parseInt("10"))
Always remember when we compare two strings.
the comparison happens on chacracter basis.
so '2' > '12' is true because the comparison will happen as
'2' > '1' and in alphabetical way '2' is always greater than '1' as unicode.
SO it will comeout true.
I hope this helps.
You can use Number() function also since it converts the object argument to a number that represents the object's value.
Eg: javascript:alert( Number("2") > Number("10"))
+ operator will coerce the string to a number.
console.log( +"2" > +"10" )
The answer is simple. Just divide string by 1.
Examples:
"2" > "10" - true
but
"2"/1 > "10"/1 - false
Also you can check if string value really is number:
!isNaN("1"/1) - true (number)
!isNaN("1a"/1) - false (string)
!isNaN("01"/1) - true (number)
!isNaN(" 1"/1) - true (number)
!isNaN(" 1abc"/1) - false (string)
But
!isNaN(""/1) - true (but string)
Solution
number !== "" && !isNaN(number/1)
The alert() wants to display a string, so it will interpret "2">"10" as a string.
Use the following:
var greater = parseInt("2") > parseInt("10");
alert("Is greater than? " + greater);
var less = parseInt("2") < parseInt("10");
alert("Is less than? " + less);

Categories

Resources