loop three digit numbers where product == sum - javascript

So I have this task where I have to nest three loops together then find out all the three digit numbers where product == sum.
For example:
123
1*2*3 = 6
1+2+3 = 6
This is what I have tried so far:
var summen = a + b + c;
var produktet = a * b * c;
for (var i = 100; i <= 100; i++) {
for (var j = 100; j <= 101; j++) {
for (var e = 100; e < 1000; e++) {
if (summen == produktet) {
pOutput.innerHTML += e + " ";
}
}
}
Thank you in advance and any help is really appreciated!
(i thought that i need to use if and else but i'm basically stuck to be honest)

If you want to do it with three loops, use three that start at 0 and end at 9, and then add and multiply in the inner loop:
let output = [];
for (let a = 0; a < 10; a++) {
for (let b = 0; b < 10; b++) {
for (let c = 0; c < 10; c++) {
if (a * b * c === a + b + c) output.push("" + a + b + c)
}
}
}
console.log(output)

You could iterate from zero to 999 and take the stringed value as array. Then check the sum against the product and store the value if equal.
const
sum = array => array.reduce((a, b) => a + b),
product = array => array.reduce((a, b) => a * b);
var i,
temp,
values = [];
for (i = 0; i < 1000; i++) {
temp = Array.from(i.toString().padStart(3, '0'), Number);
if (sum(temp) === product(temp)) {
values.push(temp.join(''));
}
}
console.log(values);

Related

Javascript : How to retrieve initial value after permutation

Starting with a 6-digits value (i.e "123456") and a [0->9] table, this script (but many other exist...) procuces the 123456th permutation of the table :
let tabl10 = [0,1,2,3,4,5,6,7,8,9],
permut = permutation( 123456 , tabl10 )
console.log(permut) // 0,4,1,6,5,9,2,3,7,8
function permutation(n,a) {
let f, k = [], l = a.length;
a = a.slice();
while (l--) {
f = factorial(l);
k.push(Math.floor(n / f));
n %= f;
}
return k.map(function (i) {
return a.splice(i, 1)[0];
});
}
function factorial(n) {
let r = 1;
while (n) {
r *= n;
n--;
}
return r;
}
My question is : is it possible to retrieve "123456" from the "0,4,1,6,5,9,2,3,7,8" permutation ?
We have 10! (3.6288 million) of possibles permutations and trying all of them one by one till we find the 123456th is painfull: it is possible to explore all permutations and retrieve the nth with a 7-digits table [0,1,2,3,4,5,6]: 7!=5040, but a 8-digits (40320) or higher definively freezes browsers. How to achieve this ?
In a Lehmer code for a permutation perm, the i-th number is the number of the elements on the right of i that are less than perm[i]. So, given a permutation, you can compute its LC first, and then convert the LC from the factorial system to an int, which gives you the index of the permutation.
Complete code:
// int => LC
function int2lc(n, len) {
let lc = []
for (let i = 1; i <= len; i++) {
lc[len - i] = (n % i)
n = (n / i) | 0
}
return lc
}
// LC => int
function lc2int(lc, len) {
let n = 0, f = 1
for (let i = 1; i <= len; i++) {
n += lc[len - i] * f
f *= i
}
return n
}
// LC => permutation
function lc2perm(a, lc) {
let perm = [], copy = [...a]
for (let i = 0; i < lc.length; i++) {
perm[i] = copy[lc[i]]
copy.splice(lc[i], 1)
}
return perm
}
// permutation => LC
function perm2lc(perm) {
let lc = []
for (let i = 0; i < perm.length; i++) {
let c = 0
for (let k = i + 1; k < perm.length; k++)
c += perm[k] < perm[i]
lc[i] = c
}
return lc
}
//
A = [0,1,2,3,4,5,6,7,8,9]
// index to perm
N = 123456
lc = int2lc(N, A.length)
console.log('LEHMER', ...lc)
perm = lc2perm(A, lc)
console.log('PERMUT', ...perm)
// perm to index
lc2 = perm2lc(perm)
console.log('LEHMER', ...lc2)
M = lc2int(lc2, A.length)
console.log('INDEX ', M)

Find largest d in array such that a + b + c = d

Task
You are given a sorted integer array arr. It contains several unique integers(negative, positive, or zero).
Your task is to find the largest d such that a + b + c = d, where a, b, c, and d are distinct elements of arr. If no such an element d found, return null.
Example:
For arr = [2,3,5,7,12], the output should be 12 (this array passes my function correctly)
For arr = [-100,-1,0,7,101], the output should be 0 (this one does not pass)
I could manage the positive numbers check but my function miserably fails with negatives
function findD(arr) {
myArr = arr.sort((a, b) => b - a);
for (var i = 0; i < myArr.length; i++) {
for (var k = i + 1; k < myArr.length - 2; k++) {
var j = k + 1,
d = myArr.length - 1;
while (j < d) {
let sum = myArr[k] + myArr[j] + myArr[d];
if (sum == myArr[i]) {
return myArr[i];
} else if (sum < myArr[i]) {
d--;
} else if (sum > myArr[i]) {
j++;
}
}
}
}
return null
}
how to handle negative values in the array?
Let's imagine there's an array like [-2, -1, 0, 3].
Then, after sorting it in the descending order as per your algorithm it will be [3, 0, -1, -2]. Obviously, your algorithm will pick only 3 as you assume d must be larger than numbers at the remaining 3 positions. That's wrong, of course. You shouldn't assume that a, b and c are necessarily less than d. That's why you must check other cases when d occupies all possible positions in relation to a,b,c. So, first consider a brute force approach that will have O(n^4) time and O(1) space complexity:
...
for (var i = myArr.length; i >= 0 ; i--) {
for (var k = 0; k < myArr.length; k++) {
if (k == i) {
continue
}
for (var j = k + 1; j < myArr.length; j++) {
if (j == i) {
continue
}
for (var d = j + 1; d < myArr.length; d++) {
if (d == i) {
continue
}
if (myArr[i] == myArr[k] + myArr[j] + myArr[d]) {
return myArr[i]
}
}
}
}
}
return null
...
But this problem can be solved in O(n^2) time and O(n^2) space.
First we should realise that a + b = d - c.
So, for the given array arr and every pair of indices i,j: i<j we store arr[i] + arr[j] (a + b) as a key and pair i,j as an item of a value (the value is a list of pairs of indices) in sumsMap. The value must be a list because there can be several pairs of indices corresponding to the same sum a + b.
Then, go through each pair of indices again k,l and check if a key arr[l] - arr[k] (d - c) or arr[k] - arr[l] (c - d) exists in sumsMap. If it does and indices l,k are different from the ones in sumsMap[s] then update the maximum element if it's lower than arr[l].
function solve(arr) {
var sumsMap = {}
for (var i = 0; i < arr.length; i++) {
for (var j = i + 1; j < arr.length; j++) {
var sum = arr[i] + arr[j]
// several pairs of indices can correspond to the same summ so keep all of them
var mappedIndices = sumsMap[sum]
if (typeof mappedIndices == "undefined") {
mappedIndices = []
}
let pair = {}
pair.first = i
pair.second = j
mappedIndices.push(pair)
sumsMap[sum] = mappedIndices
}
}
var maxD = Number.MIN_SAFE_INTEGER
for (var k = 0; k < arr.length; k++) {
for (var l = 0; l < arr.length; l++) {
mappedIndices = sumsMap[arr[l] - arr[k]]
if (mappedIndices != undefined) {
// in the worst case, 4 pairs of indices may contain k or l but the fifth one won't as numbers in the array are unique and hence the same index can occur only twice
var steps = Math.min(5, mappedIndices.length)
for (var s = 0; s < steps; s++) {
var pair = mappedIndices[s]
if (pair.first != k && pair.first != l && pair.second != k && pair.second != l) {
maxD = Math.max(maxD, arr[l])
}
}
}
}
}
if (maxD == Number.MIN_VALUE) {
return -1
} else {
return maxD
}
}
document.write(solve([-100,-1,0,7,101] ))
document.write("<br>")
document.write(solve([-93,-30,-31,-32] ))
I translated the function Renaldo suggested from https://www.geeksforgeeks.org/find-largest-d-in-array-such-that-a-b-c-d/ to JavaScript for you.
function findLargestd(S, n){
var found = false;
// sort the array in
// ascending order
S.sort((a, b) => a - b);
// iterating from backwards to
// find the required largest d
for(var i = n - 1; i >= 0; i--){
for(var j = 0; j < n; j++){
// since all four a, b, c,
// d should be distinct
if(i == j){
continue;
}
for(var k = j + 1; k < n; k++){
if(i == k){
continue;
}
for(var l = k + 1; l < n; l++){
if(i == l){
continue;
}
// if the current combination
// of j, k, l in the set is
// equal to S[i] return this
// value as this would be the
// largest d since we are
// iterating in descending order
if(S[i] == S[j] + S[k] + S[l]){
found = true;
return S[i];
}
}
}
}
}
//if not found, return 0
if(found === false){
return 0;
}
}

NaN out of matrix multiplication?

I have the code below for matrix formation out of an array and its multiplication.
But when I try to multiply two matrices like mtp(matrix(2,2,[1,2,3,4]),matrix(2,2,[1,0,0,1])) it returns NaN in all places.
Please help me out
function matrix(m, n, arr) {
var result = {};
for (t = 1; t <= m; t++) {
result[t] = {};
};
for (i = 1; i <= m; i++)
for (j = 1; j <= n; j++) result[i][j] = arr[m * (i - 1) + j - 1];
return {
"result": result,
"m": m,
"n": n
};
}
function mtp(a, b) {
if (parseInt(a.n) != parseInt(b.m)) {
return;
} else {
var result = [];
var m = parseInt(a.m);
var n = parseInt(b.n);
var k = parseInt(a.n);
for (i = 1; i <= m; i++) {
for (j = 1; j <= n; j++) {
for (p = 1; p <= k; p++) {
result[m * (i - 1) + j - 1] += (parseInt(a.result[i][p]) * parseInt(b.result[p][j]));
console.log(parseInt(a.result[i][p]) * parseInt(b.result[p][j]))
}
}
}
}
console.log(result, matrix(m, n, result).result);
}
mtp(matrix(2,2,[1,2,3,4]),matrix(2,2,[1,0,0,1]));
When you define result it is an array of zero elements
var result = [];
When you try to add a number to an element of the array, that element is not defined, Adding any number to undefined gives you NaN. There are 2 ways to solve this, either initialize your array with the right length of zeros, or default it to zero during the sum. I've chosen the latter below,
result[m * (i - 1) + j - 1] = (result[m * (i - 1) + j - 1]||0) + (a.result[i][p] * b.result[p][j]);
// Note here ---------------------------------------------^
I've got rid of all the unnecessary parseInt calls.
function matrix(m, n, arr) {
var result = {};
for (t = 1; t <= m; t++) {
result[t] = {};
};
for (i = 1; i <= m; i++)
for (j = 1; j <= n; j++) result[i][j] = arr[m * (i - 1) + j - 1];
return {
"result": result,
"m": m,
"n": n
};
}
function mtp(a, b) {
if (a.n != b.m) {
return;
} else {
var result = [];
var m = a.m;
var n = b.n;
var k = a.n;
for (i = 1; i <= m; i++) {
for (j = 1; j <= n; j++) {
for (p = 1; p <= k; p++) {
result[m * (i - 1) + j - 1] = (result[m * (i - 1) + j - 1]||0) + (a.result[i][p] * b.result[p][j]);
console.log(a.result[i][p] * b.result[p][j])
}
}
}
}
console.log(result, matrix(m, n, result).result);
}
mtp(matrix(2,2,[1,2,3,4]),matrix(2,2,[1,0,0,1]));
In your mtp() function the values of the elements inside your result array are uninitialized (that is, you've defined an array, but that array has no actual values or even a determined length), so in your inner loop when you +=, you're referencing a newly created array element which has no default value (and therefore is undefined), and adding some number to that undefined value.
An undefined value plus a number is not a number (NaN). Try preinitializing your result array.

How to add arrays into an array in JavaScript

How could I achieve this below in JavaScript. I tried searching for it on MDN but couldn't find any method for it.
let a, b
let allNumbers = []
for (a = 10; a < 60; a = a + 10) {
for (b = 1; b <= 3; b++) {
allNumbers.push(a + b)
}
}
The desired outcome is an array inside the allNumbers array:
[[11,12,13], [21,22,23], [31,32,33], [41,42,43], [51,52,53]]
Just create a temporary Array in the outer loop and push the elements from the inner loop into it, after the inner Loop is finished, push the temporary array in the main one:
let a, b
let allNumbers = []
for (a = 10; a < 60; a += 10) {
let someNumbers = [];
for (b = 1; b <= 3; b++) {
someNumbers.push(a + b)
}
allNumbers.push(someNumbers)
}
console.log(JSON.stringify(allNumbers))
how about this
var a, b
var allNumbers = []
for (a = 10; a < 60; a = a + 10) {
var part = [];
for (b = 1; b <= 3; b++) {
part.push(a + b)
}
allNumbers.push(part)
}
You have to use one second array.
let a, b
let allNumbers = []
for (a = 10; a < 60; a = a + 10) {
second = [];
for (b = 1; b <= 3; b++) {
second.push(a + b);
}
allNumbers.push(second)
}
console.log(allNumbers);
You can apply a shorted version using ES6 features.
allNumbers = []
for (a = 10; a < 60; a = a + 10) {
allNumbers.push([...Array(3)].map((_, i) => i + a + 1))
}
console.log(allNumbers);
You can try:
const result = Array(5).fill(1).map((a, i) => Array(3).fill(1).map((a, j) => +`${i+1}${j+1}`));
console.log(JSON.stringify(result));
You have to create a new array an add the element to it in the second loop and the add this array to the final one after the second loop.
let a, b
let allNumbers = []
for (a = 10; a < 60; a = a + 10) {
data = []
for (b = 1; b <= 3; b++) {
data.push(a + b)
}
allNumbers.push(data)
}
console.log(allNumbers)
You need to declare a second array inside your loop. Like following:
let a, b
let allNumbers = []
for (a = 10; a < 60; a = a + 10) {
var tempArray = [];
for (b = 1; b <= 3; b++) {
tempArray.push(a + b)
}
allNumbers.push(tempArray);
}
console.log(allNumbers);
Just create an array and push the new array int allNumbers:
...
let c = []
for (b = 1; b <= 3; b++) {
c.push(a + b)
}
allNumbers.push(c)
...

Project Euler JavaScript #2 Can't figure out how to print the total

If I put this in to codeacademy labs, it returns the sum. But I can't figure out why it won't print/log/return the total when I tell it to.
var a = 0,
b = 1,
f = 1,
fibNums = [];
sum = 0;
while (f < 4000000) {
f = a + b;
if ( f > 4000000 ) {
break;
} else {
a = b;
b = f;
fibNums.push(f);
i ++;
}
}
for (i =0; i < fibNums.length; i++) {
if (fibNums % 2 === 0) {
sum += fibNums(i);
}
}
You have several errors in your code.
You need to access array elements using [] and not (). In your case sum is always 0 since you are accessing array in wrong way.
Here is the working code:
var a = 0,
b = 1,
f = 1,
fibNums = [];
sum = 0;
while (f < 4000000) {
f = a + b;
if (f > 4000000) {
break;
} else {
a = b;
b = f;
fibNums.push(f);
}
}
for (var i = 0; i < fibNums.length; i++) {
if (fibNums[i] % 2 == 0) { // access array elements using [] notation
sum += fibNums[i]; // access array using []
}
}
console.log(sum); // Log the sum
console.log(fibNums); //log the fibNums array

Categories

Resources