How do I join this numbers together? - javascript

function expandedForm(num) {
let len = num.toString().length;
let n = num.toString().split("");
let result = "";
for (let i = 0; i < len; i++) {
result += n[i] + "0".repeat(len -1 -i).join(" + ");
}
return result;
}
What I am trying to do is to separate numbers like this:
1220 = "1000 + 200 + 20"
221 = "200 + 20 + 1"
I have written the code (not the perfect one) where it gets me all the necessary values but I struggle with joining them together with "+". I tried using .join() but it did not work.

.join works on arrays only
function expandedForm(num) {
let len = num.toString().length;
let n = num.toString().split("");
let result = "";
let arr=[];
for (let i = 0; i < len; i++) {
arr[i] = n[i] + '0'.repeat(len-1-i);
console.log(arr[i]);
}
let ans=arr.join('+');
return ans;
}
console.log(expandedForm(1220))

Although there are a variety of approaches, here are some general tips for you:
Probably don't want to output a 0 term unless the input number is exactly 0 (only a leading 0 term is relevant, because it will be the only such term)
str.split('') can also be [...str]
No need to split a string into an array to access a character str.split('')[0] can also be just str[0]
Might want to assert that num is a whole number.
Make sure you provide enough test cases in your question to fully define the behaviour of your function. (How to handle trailing zeros, interstitial zeros, leading zeros, etc. Whether the input can be a string.)
function expandedForm(num) {
const s = num.toString();
const n = s.length - 1;
const result = [...s]
.map((char, index) => char + '0'.repeat(n - index))
.filter((str, index) => !index || +str)
.join(' + ');
return result;
}
console.log(expandedForm(1220));
console.log(expandedForm(221));
console.log(expandedForm(10203));
console.log(expandedForm(0));
console.log(expandedForm(2n**64n));

Join works with an array, not string. It stringifies two subsequent indexes for all indexes and you can decide what to add between them.
function expandedForm(num) { // num = 321
let len = num.toString().length; // len = 3
let n = num.toString().split(""); // [3,2,1]
let result = [];
for (let i = 0; i < len; i++) {
result.push(n[i] + "0".repeat(len -1 -i)); // pushing till result = ['300','20','10']
}
return num + ' = ' + result.join(' + ');
// connection result[0] + ' + ' result[1] + ' + ' result[2]
}
expandedForm(321); // output: "321 = 300 + 20 + 1"

Here's one way of doing it
let num = 221;
function expandedForm(num) {
let len = num.toString().length;
let n = num.toString().split("");
let result = "";
for (let i = 0; i < len; i++) {
let t = "0"
t = t.repeat(len-1-i)
if(result.length > 0){
n[i] !== '0'? result += '+'+ n[i] + t : result
} else {
n[i] !== '0'? result += n[i] + t : result
}
}
return result;
}
console.log(expandedForm(2200))
console.log(expandedForm(num))

below would be my approach in a more mathimatical but clean code that you can adjust to your needs.
let result = parseInt(num / 1000);
return result ;
}
function x100( num ) {
num = num % 1000;
let result = parseInt( num / 100);
return result;
}
function x10(num ) {
num = num % 1000;
num = num % 100;
let result = parseInt(num /10);
return result;
}
function x1( num ) {
num = num % 1000;
num = num % 100;
num = num % 10;
return num
}
num = 12150
console.log(num = `1000 x ${x1000(num)}, 100 x ${x100(num)}, 10 x ${x10(num)}`)```

Related

Repeat String Infinitely - Return Count of Specific Character Within N Length of Infinite String - JavaScript

Trying to solve this HackerRank challenge:
Lilah has a string, s, of lowercase English letters that she repeated infinitely many times.
Given an integer, n, find and print the number of letter a's in the first letters of Lilah's infinite string.
For example, if the string s = abcac and n = 10, the substring we consider is abcacabcac, the first 10 characters of her infinite string. There are 4 occurrences of "a" in the substring.
I wrote:
function repeatedString(s, n) {
s = s.repeat(n);
s = s.slice(0, n);
let array = Array.from(s);
let count = 0;
for (let i = 0; i < array.length; i++) {
let char = array[i];
if (char.match(/[a]/gi)) {
count++;
}
}
return count;
}
console.log(repeatedString("abcac", 10));
But HackerRank does not like s = s.repeat(n);, apparently:
I'm not sure how else to generate a string of an appropriate length to slice from. s = s.repeat(Infinity) does not work, and s is not already repeated an infinite number of times when it's passed in as a parameter.
I.e. console.logging(s), initially, logs
abcac
In this case.
I also tried:
function repeatedString(s, n) {
let j = n;
let newString = "";
while (n > 0) {
newString += s;
n--;
}
newString = newString.slice(0, j);
let count = 0;
let array = Array.from(newString);
for (let i = 0; i < array.length; i++) {
let char = array[i];
if (char.match(/[a]/gi)) {
count++;
}
}
return count;
}
console.log(repeatedString("abcac", 10));
But this caused a timeout error.
Any other ideas for how to create a string of valid length to slice from?
EDIT:
Constraints:
1 <= |s| <= 100
1 <= n <= 10^12
For 25% of the test cases, n <= 10^6
actually repeating the string n times is a tremendous waste of memory and runtime.
just compute how often the entire string would be repeated times how many as the string has plus the number of as in the part of s.slice(0, n%s.length)
And your runtime goes down to s.length instead of n
function repeatedString(s, n) {
var r = n % s.length,
m = (n - r) / s.length,
count = 0;
for (var i = 0; i < s.length; ++i) {
if (s[i] === "a") {
count += m + (i < r);
}
}
return count;
}
console.log(repeatedString("abcac", 1234567890));
function repeatedString(s, n) {
var r = n % s.length,
m = (n - r) / s.length,
count = 0;
for (var i = 0; i < s.length; ++i) {
if (s[i] === "a") {
count += m + (i < r);
}
}
return count;
}
console.log(repeatedString("abcac", 1234567890));
I tested this and knows it works. Essentially, I'm not creating a new string, I just find out how many times I have to multiply the original string in order to be able to truncate it. Then I multiply that number by how many a's there were in the original string.
function repeatedString(s, n) {
var charLength = s.length;
var repeat = Math.floor(n/charLength);
var remainder = n%(charLength);
var strCut = s.slice(0, remainder);
let count = 0;
let arrayX = Array.from(s);
for (let i = 0; i < arrayX.length; i++) {
let char = arrayX[i];
if (char.match(/[a]/gi)) {
count++;
}
}
count = count * repeat;
let arrayY = Array.from(strCut);
for (let i = 0; i < arrayY.length; i++) {
let char = arrayY[i];
if (char.match(/[a]/gi)) {
count++;
}
}
return count;
}
console.log(repeatedString("abcac", 10));
I tried a small solution with .repeat but as Thomas said, it's expensive and was taking ages to run tests.
function repeatedString(s, n) {
const allAs = s.match(/a/g);
if (!allAs) {
return 0;
}
if (s === 'a') {
return n;
}
const reps = s.repeat(Math.ceil(n/s.length)).slice(0, n).match(/a/g)
if (!reps) return 0;
return reps.length;
};
console.log(repeatedString('abc', 10));
console.log(repeatedString('abcde', 10));
But I followed Thomas idea and came up with a simpler solution
function repeatedString(s, n) {
const allAs = s.match(/a/g);
if (!allAs) {
return 0;
}
if (s === 'a') {
return n;
}
const rem = n % s.length;
const reps = (n-rem)/s.length;
let count = reps * allAs.length;
if (rem) {
const rest = s.slice(0, rem).match(/a/g);
if (rest) count = count + rest.length
}
return count;
}
console.log(repeatedString('a', 100000));
console.log(repeatedString('abcde', 10000000000));
You could use while loop to repeat original string until length is matched and then match to count the numbers of a.
function repeatedString(s, n) {
let i = 0, l = s.length;
while (s.length < n) s += s[i++ % l]
return s.match(/a/g).length;
}
console.log(repeatedString("abcac", 10));
I did this code and it worked well.
function repeatedString(s, n) {
let modulus = n % s.length;
let repetition = (n - modulus) / s.length;
let remainCounts = s.slice(0, modulus).split("").filter((item) => item == "a").length
return (s.split("").filter((item) => item == "a").length * repetition) + remainCounts
}
enter image description here

How do you iterate over an array every x spots and replace with letter?

/Write a function called weave that accepts an input string and number. The function should return the string with every xth character replaced with an 'x'./
function weave(word,numSkip) {
let myString = word.split("");
numSkip -= 1;
for(let i = 0; i < myString.length; i++)
{
numSkip += numSkip;
myString[numSkip] = "x";
}
let newString = myString.join();
console.log(newString);
}
weave("weave",2);
I keep getting an infinite loop. I believe the answer I am looking for is "wxaxe".
Here's another solution, incrementing the for loop by the numToSkip parameter.
function weave(word, numToSkip) {
let letters = word.split("");
for (let i=numToSkip - 1; i < letters.length; i = i + numToSkip) {
letters[i] = "x"
}
return letters.join("");
}
Well you need to test each loop to check if it's a skip or not. Something as simple as the following will do:
function weave(word,numSkip) {
var arr = word.split("");
for(var i = 0; i < arr.length; i++)
{
if((i+1) % numSkip == 0) {
arr[i] = "x";
}
}
return arr.join("");
}
Here is a working example
Alternatively, you could use the map function:
function weave(word, numSkip) {
var arr = word.split("");
arr = arr.map(function(letter, index) {
return (index + 1) % numSkip ? letter : 'x';
});
return arr.join("");
}
Here is a working example
Here is a more re-usable function that allows specifying the character used for substitution:
function weave(input, skip, substitute) {
return input.split("").map(function(letter, index) {
return (index + 1) % skip ? letter : substitute;
}).join("");
}
Called like:
var result = weave('weave', 2, 'x');
Here is a working example
You dont need an array, string concatenation will do it, as well as the modulo operator:
function weave(str,x){
var result = "";
for(var i = 0; i < str.length; i++){
result += (i && (i+1)%x === 0)?"x":str[i];
}
return result;
}
With arrays:
const weave = (str,x) => str.split("").map((c,i)=>(i&&!((i+1)%x))?"x":c).join("");
You're getting your word greater in your loop every time, so your loop is infinite.
Try something like this :
for(let k = 1; k <= myString.length; k++)
{
if(k % numSkip == 0){
myString[k-1]='x';
}
}
Looking at what you have, I believe the reason you are getting an error is because the way you update numSkip, it eventually becomes larger than
myString.length. In my code snippet, I make i increment by numSkip which prevents the loop from ever executing when i is greater than myString.length. Please feel free to ask questions, and I will do my best to clarify!
JSFiddle of my solution (view the developer console to see the output.
function weave(word,numSkip) {
let myString = word.split("");
for(let i = numSkip - 1; i < myString.length; i += numSkip)
{
myString[i] = "x";
}
let newString = myString.join();
console.log(newString);
}
weave("weave",2);
Strings are immutable, you need a new string for the result and concat the actual character or the replacement.
function weave(word, numSkip) {
var i, result = '';
for (i = 0; i < word.length; i++) {
result += (i + 1) % numSkip ? word[i] : 'x';
}
return result;
}
console.log(weave("weave", 2));
console.log(weave("abcd efgh ijkl m", 5));
You can do this with fewer lines of code:
function weave(word, numSkip) {
word = word.split("");
for (i = 0; i < word.length; i++) {
word[i] = ((i + 1) % numSkip == 0) ? "x" : word[i];
}
return word.join("");
}
var result = weave("weave", 2);
console.log(result);

Trying to write a javascript function that counts to the number inputted

Trying to take an integer and have it return as a
string with the integers from 1 to the number passed.
Trying to use a loop to return the string but not sure how!
Example of how I want it to look:
count(5) => 1, 2, 3, 4, 5
count(3) => 1, 2, 3
Not really sure where to even start
I would do it with a recursive function. Keep concatenating the numbers until it reaches 1.
var sequence = function(num){
if(num === 1) return '1';
return sequence(num - 1) + ', ' + num;
}
Or just:
var sequence = (num) => num === 1 ? '1' : sequence(num - 1) + ', ' + num;
You can use a for loop to iterate the number of times that you pass in. Then, you need an if-statement to handle the comma (since you don't want a comma at the end of the string).
function count(num) {
var s = "";
for(var i = 1; i <= num; i++) {
s += i;
if (i < (num)) {
s += ', ';
}
}
return s;
}
JSBin
Try this:
function count(n) {
var arr = [];
for (var i = 1; i<=n; i++) {
arr.push(i.toString());
}
return arr.toString();
}
Here's a non-recursive solution:
var sequence = num => new Array(num).fill(0).map((e, i) => i + 1).toString();
here is a goofy way to do it
function count(i)
{
while (i--) {
out = (i + 1) + "," + this.out;
}
return (out + ((delete out) && "")).replace(",undefined", "");
}
Quite possibly the most ridiculous way, defining an iterator:
"use strict";
function count ( i ) {
let n = 0;
let I = {};
I[Symbol.iterator] = function() {
return { next: function() { return (n > i) ? {done:true}
: {done:false, value:n++} } } };
let s = "";
let c = "";
for ( let i of I ) {
s += c + i;
c = ", "
}
return s;
}
let s = count(3);
console.log(s);

returning equation with all possible parenthesis combinations and the result of each

On a recent interview, I was asked to return all possible combinations of order of operations on an input string, and the result. you should return all the ways/combinations in which you can "force" operations with parenthesis. I got the result (right hand side of the equation) but got stuck on the left side. how could I have done the left side and the right hand side together? Seems like two problems in one...
//input:
console.log(diffWaysToCompute("2 * 3 - 4 * 5"));
//output:
(2*(3-(4*5))) = -34
((2*3)-(4*5)) = -14
((2*(3-4))*5) = -10
(2*((3-4)*5)) = -10
(((2*3)-4)*5) = 10
'use strict'
function getNumbersAndOperators(str) {
var arr = str.split(" ");
var operators = [];
for (var i = 0; i < arr.length; i++) {
if (arr[i] === "-" || arr[i] === "*" || arr[i] === "+") {
operators.push(arr[i]);
arr.splice(i, 1);
// console.log(operators);
}
}
return [arr, operators];
}
// console.log(getNumbersAndOperators("2 - 1 - 1"))
var diffWaysToCompute = function (input) {
// var numbers = input.split(" ");
// console.log(numbers);
// // console.log(number);
var results = compute(input);
results.sort(function (a, b) {
return a - b;
});
//put the numbers length into valid parenthesis:
var NumbersAndOperators = getNumbersAndOperators(input);
var numbers = NumbersAndOperators[0];
console.log(numbers);
var operators = NumbersAndOperators[1];
console.log(operators);
var parens = validParentheses(numbers.length);
// console.log(numbers);
console.log(operators);
// for (var i = 0; i < parens.length; i++) {
// for (var j = 0; j < parens[i].length; j++) {
// var val = parens[i][j];
// console.log(val);
// if (val === " ") {
// var num = numbers.shift();
// parens.splice(val, 0, num);
// //starting running into infinite loops and out of time.
// j--;
// }
// }
// i--;
// }
console.log(parens);
return results;
};
function validParentheses(n) {
if (n === 1) {
return ['( )'];
}
var prevParentheses = validParentheses(n - 1);
var list = {};
prevParentheses.forEach(function (item) {
list['( ' + item + ' )'] = null;
list['( )' + item] = null;
list[item + '( )'] = null;
});
console.log(Object.keys(list))
return Object.keys(list);
}
function compute(str) {
var res = [];
var i;
var j;
var k;
var left;
var right;
var string = [];
var placed = true;
if (!/[+*-]/.test(str)) { // + - *
return [parseInt(str)];
}
for (i = 0; i < str.length; i++) {
if (/\+|\-|\*/.test(str[i])) { // + - *
left = compute(str.substring(0, i));
right = compute(str.substring(i + 1, str.length));
for (j = 0; j < left.length; j++) {
for (k = 0; k < right.length; k++) {
if (str[i] === '+') {
res.push(parseInt(left[j] + right[k]));
} else if (str[i] === '-') {
// string.push("(" + str[i-2], str[i+2] + ")");
res.push(parseInt(left[j] - right[k]));
} else if (str[i] === '*') {
res.push(parseInt(left[j] * right[k]));
}
}
}
}
}
// console.log(string);
return res;
}
console.log(diffWaysToCompute("2 - 1 - 1"));
console.log(diffWaysToCompute("2 * 3 - 4 * 5"));
I never had to do such silly things, so let me try my teeth at it now.
(Caveat as always: it's highly simplified and without any checks&balances!)
The parser is the simplest thing here:
/*
Use of strings instead of ASCII codes for legibility.
I changed x - y to x + (-y) not only for convenience
but for algebraic correctness, too.
#param a array number nodes
#param o array operator nodes
*/
function parse(s,a,o){
var fnum = 0;
var uminus = false
for(var i=0;i<s.length;i++){
switch(s[i]){
case '-': uminus = true;
a.push(fnum);
o.push('+');
fnum = 0;
break;
case '+':
case '*':
case '/': if(uminus){
uminus = false;
fnum *= -1;
}
a.push(fnum);
o.push(s[i]);
fnum = 0;
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9': fnum = fnum * 10 + parseInt(s[i]);
break;
default: break;
}
}
//assuming symmetry
a.push(fnum);
}
The (-generation took me some time, too much time--I cheated here ;-)
/*
Found in an old notebook (ported from C)
Algo. is O(n^2) and can be done faster but I
couldn't be a...ehm, had no time, sorry.
#idx int index into individual result
#n int number of groups
#open int number of opening parentheses
#close int number of closing parentheses
#a array individual result
#all array space for all results
*/
function makeParens(idx,n,open,close,a,all){
if(close == n){
all.push(a.slice(0));
return;
} else {
if(open > close){
a[idx] = ')';
makeParens(idx+1,n,open,close+1,a,all);
}
if(open < n){
a[idx] = '(';
makeParens(idx+1,n,open+1,close,a,all);
}
}
}
And now? Yepp, that took me a while:
/*
The interesting part
Not very optimized but working
#s string the equation
#return array nicely formatted result
*/
function parenthesing(s){
var nums = [];
var ops = [];
var all = [];
var parens = [];
// parse input into numbers and operators
parse(input,nums,ops);
/*
Rules:
1) out-most parentheses must be open in direction to center
e.g.: (1+2+3), 1+(2+3), 1+(2+3)+4
but not: 1)+(2+3)+(4
so: first parenthesis on the left side must be open and
the last parenthesis on the right side must be close
2) parentheses in direct neighborhood to a number must be
open in direction to the number (multiplication is
not mutual)
e.g.: 1+(2+3)+4, but not: 1+2(+3+4)
3) parentheses in direct neighborhood to an operator must be
closed in direction to the operator (multiplication is
not mutual)
e.g.: 1+(2+3)+4, but not: 1+2(+3+)4
*/
// build combinations separately not in-line
// it's already a mess, no need to add more
makeParens(0,nums.length,0,0,[],parens);
// You may take a look at the raw material here
// console.log(parens.join("\n"));
for(var i= 0;i<parens.length;i++){
var term = [];
// work on copies to reduce pointer juggling
var _ops = ops.slice(0);
var _nums = nums.slice(0);
for(var j=0;j<parens[i].length;j++){
if(parens[i][j] === '('){
term.push("(");
// rule 3
if(parens[i][j+1] === ')'){
term.push(_nums.shift());
}
// rules 1,2
else {
term.push(_nums.shift());
term.push(_ops.shift());
}
}
if(parens[i][j] === ')'){
term.push(")");
// rules 2,3
if(parens[i][j+1] !== ')')
term.push(_ops.shift());
}
}
// some pretty printing
term = term.join("");
// eval() because I didn't want to write a parser
// but if you need one...
all.push(term + " = " + eval(term));
}
return all;
}
I'm not sure if I would get hired with that abomination. Ah, to be honest: I doubt it.
But I hope it is at least a little bit helpful.
Yikes. That was tricky. Good challenge. I'm sure this could be cut way down, but it works. I used lodash and broke the various functions down to make it more flexible. Here's a jsfiddle:
https://jsfiddle.net/mckinleymedia/3e8g22Lk/8/
Oops - had to add parseInt to the addition so it doesn't add as strings.
/*
//input:
diffWaysToCompute("2 * 3 - 4 * 5");
//output:
(2*(3-(4*5))) = -34 - 2,1,0
((2*3)-(4*5)) = -14 - 0,2,1 & 2,0,1
((2*(3-4))*5) = -10 - 1,0,2
(2*((3-4)*5)) = -10 - 1,2,0
(((2*3)-4)*5) = 10 - 0,1,2
*/
'use strict'
var diffWaysToCompute = function(str) {
var opsAvailable = ['+','-','/','*'],
numbers = [],
operators = [],
getNumbersAndOperators = function(str) {
var arr = str.split(" ");
for (var i in arr) {
if ( opsAvailable.indexOf( arr[i] ) > -1 ) {
operators.push( arr[i] );
} else {
numbers.push( arr[i] );
}
};
return;
},
permutator = function(range) {
var results = [];
function permute(arr, memo) {
var cur,
memo = memo || [];
for (var i in arr) {
cur = arr.splice(i, 1);
if (arr.length === 0) results.push(memo.concat(cur));
permute(arr.slice(), memo.concat(cur));
arr.splice(i, 0, cur[0]);
}
return results;
}
return permute(_.range(range));
},
equations = function( perms ) {
var results = [];
_.each(perms, function( perm, k ) {
results[k] = nest ( perm );
});
return results;
},
nest = function( perm ) {
var eqs = eqs || [],
ref = ref || _.range(perm.length).map(function () { return undefined }),
eq,
target = undefined;
for (var i in perm) {
var cur = perm[i],
next = perm[i] + 1,
n1 = numbers[ cur ],
n2 = numbers[ next ],
r1 = ref[ cur ],
r2 = ref[ next ];
if ( r1 !== undefined) n1 = eqs [ r1 ];
if ( r2 !== undefined) n2 = eqs [ r2 ];
var rNew;
rNew = eqs.length;
for (var x in ref ) {
if ( ( ref[ x ] !== undefined ) && ( ref[ x ] == r1 || ref[ x ] == r2 ) ) ref[ x ] = eqs.length;
};
ref[ cur ] = ref[ next ] = eqs.length;
eqs.push({
ops: operators[ cur ],
nums: [ n1, n2 ]
});
};
return eqs[ eqs.length - 1 ];
},
calculations = function ( eqs ) {
var results = []
_.each(eqs, function(equation) {
results.push(calculate( equation ));
});
return results;
},
calculate = function( eq ) {
var result = {
text: ""
};
// result.eq = eq;
result.text += "( ";
result.total = eq.nums[ 0 ];
if ( _.isObject(result.total) ) {
var result1 = calculate( result.total );
result.total = result1.total;
result.text += result1.text;
} else {
result.text += eq.nums[ 0 ];
}
_.each(eq.ops, function (op, k) {
var num = eq.nums[ k + 1 ];
result.text += " " + op + " ";
if ( _.isObject(num) ) {
var result2 = calculate( num );
num = result2.total;
result.text += result2.text;
} else {
result.text += num;
}
if ( op === '+') result.total = parseInt(result.total) + parseInt(num);
if ( op === '-') result.total = result.total - num;
if ( op === '/') result.total = result.total / num;
if ( op === '*') result.total = result.total * num;
});
result.text += " )";
return result;
},
display = function( as ) {
var target = document.getElementById('result');
target.innerHTML += '<h3 class="problem">String given: ' + str + '</h3>';
target.innerHTML += '<h4>Permutations</h4>';
_.each( as, function(a) {
target.innerHTML += '<div class="permutation">';
target.innerHTML += ' <span class="formula">' + a.text + '</span> = ';
target.innerHTML += ' <span class="total">' + a.total + '</span>';
target.innerHTML += '</div>';
});
},
perms,
eqs,
answers;
getNumbersAndOperators(str);
perms = permutator( operators.length );
eqs = equations( perms );
answers = calculations( eqs );
answers = _.uniq(answers, 'text');
display(answers);
return answers;
};
console.log(diffWaysToCompute("2 * 3 - 4 * 5"));

A while loop to add the digits of a multi-digit number together? (Javascript)

I need to add the digits of a number together (e.g. 21 is 2+1) so that the number is reduced to only one digit (3). I figured out how to do that part.
However,
1) I may need to call the function more than once on the same variable (e.g. 99 is 9+9 = 18, which is still >= 10) and
2) I need to exclude the numbers 11 and 22 from this function's ambit.
Where am I going wrong below?
var x = 123;
var y = 456;
var z = 789;
var numberMagic = function (num) {
var proc = num.toString().split("");
var total = 0;
for (var i=0; i<proc.length; i++) {
total += +proc[i];
};
};
while(x > 9 && x != 11 && x != 22) {
numberMagic(x);
};
} else {
xResult = x;
};
console.log(xResult);
//repeat while loop for y and z
Here are the problems with your code
var x = 123;
var y = 456;
var z = 789;
var numberMagic = function (num) {
var proc = num.toString().split("");
var total = 0;
for (var i=0; i<proc.length; i++) {
total += +proc[i]; // indentation want awry
}; // don't need this ; - not a show stopper
// you're not returning anything!!!!
};
while(x > 9 && x != 11 && x != 22) {
numberMagic(x);
}; // ; not needed
// because x never changes, the above while loop would go on forever
} else { // this else has no if
xResult = x; // even if code was right, x remains unchanged
};
console.log(xResult);
Hope that helps in some way
Now - here's a solution that works
var x = 123;
var y = 456;
var z = 789;
var numberMagic = function (num) {
while (num > 9) {
if (num == 11 || num == 22) {
return num;
}
var proc = num.toString().split("");
num = proc.reduce(function(previousInt, thisValueString) {
return previousInt + parseInt(thisValueString);
}, 0);
}
return num;
}
console.log(numberMagic(x));
console.log(numberMagic(y));
console.log(numberMagic(z));
I'm not sure to understand what you want..
with this function you reduce any number to one single digit
while(num > 9){
if(num == 11 || num == 22) return;
var proc = num.toString();
var sum = 0;
for(var i=0; i<proc.length; i++) {
sum += parseInt(proc[i]);
}
num = sum;
}
is it what you are looking at?
I wrote an example at Jsfiddle that you can turn any given number into a single digit:
Example input: 551
array of [5, 5, 1] - add last 2 digits
array of [5, 6] - add last 2 digits
array of [1, 1] - add last 2 digits
array of [2] - output
Here is the actual code:
var number = 1768;
var newNumber = convertToOneDigit(number);
console.log("New Number: " + newNumber);
function convertToOneDigit(number) {
var stringNumber = number.toString();
var stringNumberArray = stringNumber.split("");
var stringNumberLength = stringNumberArray.length;
var tmp;
var tmp2;
var tmp3;
console.log("Array: " + stringNumberArray);
console.log("Array Length: " + stringNumberLength);
while (stringNumberLength > 1) {
tmp = parseInt(stringNumberArray[stringNumberLength - 1]) + parseInt(stringNumberArray[stringNumberLength - 2]);
stringNumberArray.pop();
stringNumberArray.pop();
tmp2 = tmp.toString();
if (tmp2.length > 1) {
tmp3 = tmp2.split("");
for (var i = 0; i < tmp3.length; i++) {
stringNumberArray.push(tmp3[i]);
}
} else {
stringNumberArray.push(tmp2);
}
stringNumberLength = stringNumberArray.length;
console.log("Array: " + stringNumberArray);
console.log("Array Length: " + stringNumberLength);
}
return stringNumberArray[0];
}
function addDigits(n) {
let str = n.toString().split('');
let len = str.length;
let add,
acc = 0;
for (i=0; i<=len-1; i++) {
acc += Number(str[i]);
}
return acc;
}
console.log( addDigits(123456789) ); //Output: 45
Just make it a While loop, remember a While loops it's just the same as a For loop, only you add the counter variable at the end of the code, the same way you can do with a Do{code}while(condition) Only need to add a counter variable at the end and its gonna be the same. Only that the variable its global to the loop, I mean comes from the outside.
Ej.
let i = 0; //it's global to the loop, ( wider scope )
while (i<=x) {
//Code line;
//Code line;
//Code line;
//Code line;
i++
}
Now this is working with an outside variable and it's NOT recommended.. unless that var its local to a Function.
Please look at the this solution also
var x = 123;
var y = 456;
var z = 789;
var numberMagic = function (num) {
var total = 0;
while (num != 0) {
total += num % 10;
num = parseInt(num / 10);
}
console.log(total);
if (total > 9)
numberMagic(total);
else
return total;
}
//Call first time function
numberMagic(z);

Categories

Resources