I have to make multiplication table, which for n = 3 look like this:
1 x 1 = 1 | 1 x 2 = 2 | 1 x 3 = 3
2 x 1 = 2 | 2 x 2 = 4 | 2 x 3 = 6
3 x 1 = 3 | 3 x 2 = 6 | 3 x 3 = 9
For now my code look like this:
var n = 3;
var result;
for (i = 1; i <= n; i++) {
var result = '';
for(j = 1; j <= n; j++) {
result += ` ${i} * ${j} = ${i * j}`;
}
console.log(result);
}
My result is:
1 x 1 = 1 1 x 2 = 2 1 x 3 = 3
2 x 1 = 2 2 x 2 = 4 2 x 3 = 6
3 x 1 = 3 3 x 2 = 6 3 x 3 = 9
And I have no idea how to add "|" separate only between math operation. If I add "|" at the end of result variable, I will get it also after last operation, but i don't want it.
You can append the | to the end when it is not the last row.
var n = 3;
var result;
for (i = 1; i <= n; i++) {
var result = '';
for(j = 1; j <= n; j++) {
result += ` ${i} * ${j} = ${i * j}`;
if(j != n)
{
result += ' |';
}
}
console.log(result);
}
You can add check using modulo operator % or just j != n to see if its the last part in row and add | based on that condition.
var n = 3;
var result;
for (i = 1; i <= n; i++) {
var result = '';
for (j = 1; j <= n; j++) {
result += ` ${i} * ${j} = ${i * j}`;
result += j % n ? ' |' : ''
}
console.log(result);
}
You could do this with Array.from() method and join.
var n = 4;
const result = Array.from(Array(n), (e, i) => {
i += 1
return Array.from(Array(n), (a, j) => {
j += 1
return `${i} * ${j} = ${i * j}` + (j != n ? ' | ' : '')
}).join('')
}).join('\n')
console.log(result)
You could add a check with a logical AND && and the string. It returns either the empty string, or the separator.
var n = 3,
result,
i, j;
for (i = 1; i <= n; i++) {
result = '';
for (j = 1; j <= n; j++) {
result += result && ' |';
result += ` ${i} * ${j} = ${i * j}`;
}
console.log(result);
}
Rather than add the pipe to the end of each item, it is simpler to add it to the start of each item except for the first item:
var n = 3;
var result;
for (i = 1; i <= n; i++) {
var result = '';
for(j = 1; j <= n; j++) {
if(j !== 1)
{
result += ' | ';
}
result += `${i} * ${j} = ${i * j}`;
}
console.log(result);
}
I would probably do this with some range function (such that range(3, 7) //=> [3, 4, 5, 6, 7], for instance) and then map over an outer and an inner range, something like this:
const range = (b, e) => Array.from({length: e - b + 1}, (_, i) => b + i)
const multTable = (m, n) => range(1, n).map(i => range(1, m).map(
j => `${i} x ${j} = ${i * j}`
).join(' | ')).join('\n')
console.log(multTable(3, 3))
This will stop lining up well as soon as your products or factors hit double-digits. If that's a concern, you might replace join(' | ') with join('\t|\t'). It won't be perfect, but it'll likely be better.
Try like this
var n = 3;
var result;
for (i = 1; i <= n; i++) {
var result = '';
for(j = 1; j <= n; j++) {
if(j!=n)
result += ` ${i} * ${j} = ${i * j}` + '|';
else
result += ` ${i} * ${j} = ${i * j}`;
}
console.log(result);
}
It should be:
var n = 3;
var result = '';
for (i = 1; i <= n; i++) {
var result = '';
for(j = 1; j <= n; j++) {
result.length && result += '|';
result += ` ${i} * ${j} = ${i * j}`;
}
console.log(result);
}
For all n :
function table(n){
var i, j;
for (i = 1; i <= n; i++) {
var result = '';
for(j = 1; j <= n - 1; j++)
result += ` ${i} x ${j} = ${i * j} |`;
result += ` ${i} x ${j} = ${i * j}`
console.log(result);
}
}
table(1);
table(2);
table(3);
Simply use an array to collect the results, then join the parts with |
var n = 3;
var result;
for (let i = 1; i <= n; i++) {
result = [];
for (let j = 1; j <= n; j++) {
result.push(`${i} * ${j} = ${i * j}`);
}
console.log(result.join(' | '));
}
Another approach would be to remove the last occurence of "|" in the loop with slice():
var n = 3;
var result;
for (var i = 1; i <= n; i++) {
var result = '';
for (var j = 1; j <= n; j++) {
result += ` ${i} * ${j} = ${i * j} |`;
}
result = result.slice(0, -1);
console.log(result)
}
Try
let n =3;
[...Array(n)].map((_,i,a)=>
console.log(a.map((_,j)=>`${i+1} * ${++j} = ${(i+1)*j}`).join(' | ')));
let n =3;
[...Array(n)].map((_,i,a)=>console.log(a.map((_,j)=>`${i+1} * ${++j} = ${(i+1)*j}`).join(' | ')));
Related
Use for loop to iterate from 0 to 100 and print the sum of all evens and the sum of all odds. Print sum of evens and sum of odds as array
Output: [2550, 2500]
let sumOfEven = 0;
let EvenOddArr = [];
for (let i = 0; i <= 100; i += 2) {
sumOfEven += i;
}
console.log(sumOfEven);
let sumOfOdd = 0;
for (let i = 1; i <= 100; i += 2) {
sumOfOdd += i;
}
console.log(sumOfOdd);
console.log(EvenOddArr);
You could take the remainder of two as index for the array.
const evenOddArr = [0, 0];
for (let i = 0; i <= 100; i++) evenOddArr[i % 2] += i;
console.log(evenOddArr);
You're nearly there - all you need is a couple of pushes
let sumOfEven = 0;
let EvenOddArr = [];
for (let i = 0; i <= 100; i += 2) {
sumOfEven += i;
}
EvenOddArr.push(sumOfEven)
let sumOfOdd = 0;
for (let i = 1; i <= 100; i += 2) {
sumOfOdd += i;
}
EvenOddArr.push(sumOfOdd)
console.log(EvenOddArr);
console.log(Array(101).fill().reduce((a,_,i)=>(a[i%2]+=i,a),[0,0]))
Here is an alternative for when you have studied JS a bit more
let sumArr = Array.from({ length: 101 })
.reduce((acc,_,i) => (acc[i % 2] += i, acc), [0, 0]);
console.log(sumArr);
An easy-to-understand version:
let sumOfEven = 0;
let sumOfOdd = 0;
for (let i = 0; i <= 100; i++) {
if (i % 2 === 0) {
sumOfEven += i;
} else {
sumOfOdd += i;
}
}
let evenOddArr = [sumOfEven, sumOfOdd];
console.log(evenOddArr);
I Need to get this output:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
What I've tried so far:
function getPyramid() {
let nums = 0;
for (let i = 1; i <= 15; i++) {
for (let n = 1; n < i; n++) {
console.log(n);
}
console.log('<br/>');
}
return nums;
}
getPyramid();
It is possible to do with one single loop
function getPyramid() {
let nums = 0;
let count = 1;
let numbers = ''
for (let i = 0; i <= 15; i++) {
if(count === nums){
count++
nums = 0;
console.log(numbers)
numbers = ''
}
nums ++
numbers += ' ' + (i +1)
}
}
getPyramid();
Or like this you can specify amount of rows..
function getPyramid(rows) {
let nums = 0;
let count = 1;
let numbers = ''
let i = 1
while (count < rows + 1 ) {
if(count === nums){
count++
nums = 0;
console.log(numbers)
numbers = ''
}
nums ++
numbers += ' ' + i
i++;
}
}
getPyramid(5);
for (let i = 1 ; i <= 5; i++)
{
let s = []
for (let x = i * (i - 1) / 2 + 1; x <= i * (i + 1) / 2; x++)
{
s.push(x)
}
console.log(s.join(" "))
}
Apart from notes given by jnpdx in the comments, I'd add some:
for better convention between programmers we tend to name varible nested in for-loop: i, j
<br/> for HTML new line, In JS we do \n for that!
number++ is same number += 1
Conditional_Operator (expression)?true:false instead of if/else
function getPyramid(Lines) {
let number = 1; // the counter to display on each line of pyramid!
for (let i = 1; i <= Lines; i++) {
let str = '';//line to display
for (let j = 1; j <= i; j++) {
str += number++;//incrementing counter
str += j!=i ? ' ' : ''; //to make space, but not at the end of line.
}
console.log(str);//display that line
}
}
getPyramid(5);
A completely unnecessary attempt to do this in a functional style:
const ranged_array = (from, to) =>
Array.from({ length: to - from + 1 }, (_, i) => i + from);
const pyramid = (lines) =>
ranged_array(1, lines)
.reduce((a, v, i) => {
const prev = a[i - 1];
const last_num = prev && prev[prev.length - 1] || 0;
a.push(ranged_array(last_num + 1, last_num + v));
return a;
}, [])
.map((v) => v.join(' '))
.join("\n");
console.log(pyramid(5));
So heres the problem:
Write a program using TypeScript that prints an X constructed from the letter X and uses the underscore as a space. The size of the x is based on a variable n that will indicate the size of the letter to print (in a matrix of n x n). For example, for n: = 5 you get:
X___X_
_X_X_
__X__
_X_X_
X___X
and for n: = 6 we obtain:
X____X_
_X__X_
__XX__
__XX__
_X__X_
X____X
this is my code:
var n = 5;
var space = "";
for(var i = 2; i < n; i++){
space = space + "_";
for(var k = 1; k < i * 1; k++){
space = space + "X";
}
console.log(space);
}
And the ouput is:
_X
_X_XX
_X_XX_XXX
Check if the index of the outer loop is equal to the index of the inner loop, OR if the index of the outer loop is equal to (the index of the inner loop minus the line length) to decide on whether a square should have an X or not:
const makeX = n => {
for (let i = 0; i < n; i++) {
let line = '';
for (let j = 0; j < n; j++) {
line += i === j || j === (n - i - 1) ? 'X' : '_';
}
console.log(line);
}
};
makeX(5);
console.log('');
makeX(6);
let x = 5;
for(let i=0; i<x; i++) {
let str = "";
for(let k=0; k<x; k++) {
if(k==i || k==x-1-i) {
str+='X'
}
else {
str+='_'
}
if(k==x-1) {
console.log(str)
}
}
}
const X = n => new Array(n).fill(n).forEach(
(_,j,a) => console.log(a.map(
(_,i) => i == j || i == (n-j-1) ? 'X' : '_'
).join(''))
);
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.
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);