Can't make pyramid of numbers - javascript

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));

Related

How to push both sum of even and odd result from for loop into an array?

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);

Two Sum Leetcode

I wrote the code, but for some reason it displays the index 1, 2, 3, while 3 + 4 will in no way be equal to target (6).
var twoSum = function(nums, target) {
let sum = [];
var n = 2;
for(let i = 0; i < nums.length; i++) {
for(let a = 1; a < nums.length; a++) {
if(nums[i] + nums[a] == target) {
sum.push(i);
sum.push(a);
}
}
}
let unique = sum.filter((e, i) => sum.indexOf(e) === i )
return unique/* .slice(0, n); */
};
console.log(twoSum([1,3,4,2],6))
Input
[1,3,4,2]
6
Output
[1,2]
Expected
[2,3]
As per my comment, start the inner loop at a = i + 1 to avoid summing numbers with themselves as well as to avoid checking the same combination twice, e.g (1, 2) and (2, 1):
var twoSum = function(nums, target) {
let sum = [];
let n = 2;
for (let i = 0; i < nums.length; i++) {
for (let a = i + 1; a < nums.length; a++) {
if (nums[i] + nums[a] === target) {
sum.push(i);
sum.push(a);
}
}
}
let unique = sum.filter((e, i) => sum.indexOf(e) === i )
return unique/* .slice(0, n); */
};

Not able to get value after Do...While loop

Question: Create a function that takes a positive integer and returns the next bigger number that can be formed by rearranging its digits. For example:
12 ==> 21
513 ==> 531
2017 ==> 2071
//nextBigger(num: 12) // returns 21
//nextBigger(num: 513) // returns 531
//nextBigger(num: 2017) // returns 2071
I am trying to compare two Array and get correct array as answer. In do...while loop I am comparing the two array by increment second array by one.
function nextBigger(n){
let nStrg = n.toString();
let nArr = nStrg.split('');
function compareArr(Ar1,Ar2){
if(Ar2.length>Ar1.length){
return false;
}
for(let i=0; i<Ar1.length; i++){
let num = Ar1[i];
for(let j=0; j<Ar2.length; j++){
if(Ar2.lastIndexOf(num) !== -1){
Ar2.splice(Ar2.lastIndexOf(num), 1);
break;
}
else{
return false;
break;
}
}
}
return true;
}
let nextNumArr;
let m = n;
do{
let nextNum = m+1
m=nextNum
let nextNumStrg = nextNum.toString();
nextNumArr = nextNumStrg.split('')
console.log(compareArr(nArr, nextNumArr))
}
while(compareArr(nArr, nextNumArr) == false)
console.log(nextNumArr)
return parseInt(nextNumArr.join())
}
nextBigger(12);
This gives me empty array at the end;
[2,0,1,7].join() will give you '2,0,1,7', can use [2,0,1,7].join('') and get '2017'
All looks a bit complicated. How about:
const nextLarger = num => {
const numX = `${num}`.split(``).map(Number).reverse();
for (let i = 0; i < numX.length; i += 1) {
if ( numX[i] > numX[i + 1] ) {
numX.splice(i, 2, ...[numX[i+1], numX[i]]);
return +(numX.reverse().join(``));
}
}
return num;
};
const test = [...Array(100)].map(v => {
const someNr = Math.floor(10 + Math.random() * 100000);
const next = nextLarger(someNr);
return `${someNr} => ${
next === someNr ? `not possible` : next}`;
}).join('\n');
document.querySelector(`pre`).textContent = test;
<pre></pre>
See also
function nextbig(number) {
let nums = []
number.toString().split('').forEach((num) => {
nums.push(parseInt(num))
})
number = nums
n = number.length
for (var i = n - 1; i >= 0; i--) {
if (number[i] > number[i - 1])
break;
}
if (i == 1 && number[i] <= number[i - 1]) {
return 'No greater possible'
}
let x = number[i - 1];
let smallest = i;
for (let j = i + 1; j < n; j++) {
if (number[j] > x &&
number[j] < number[smallest])
smallest = j;
}
let temp = number[smallest];
number[smallest] = number[i - 1];
number[i - 1] = temp;
x = 0
for (let j = 0; j < i; j++)
x = x * 10 + number[j];
number = number.slice(i, number.length + 1);
number.sort()
for (let j = 0; j < n - i; j++)
x = x * 10 + number[j];
return x
}
console.log(nextbig(12))
console.log(nextbig(513))
console.log(nextbig(2017))
In compareArr you are deleting elements as you find them, which is correct to do, to make sure duplicates actually occur twice etc. However, that also deletes the elements from nextNumArr in the calling context, because the array is passed by reference and not by value. You need to do a manual copy of it, for example like this: compareArr(nArr, [...nextNumArr]).
I have used a different approach, first I search for all possible combinations of the given numbers with the permutator function. This function returns an array of possible numbers.
Then I sort this array of combinations and look for the index of the given number in the main function.
Once I have this index I return the position before the given number.
function nextbig(num){
function permutator(inputArr){
let result = [];
const permute = (arr, m = []) => {
if (arr.length === 0) {
result.push(m)
} else {
for (let i = 0; i < arr.length; i++) {
let curr = arr.slice();
let next = curr.splice(i, 1);
permute(curr.slice(), m.concat(next))
}
}
}
permute(inputArr)
return result;
}
let arrNums = num.toString().split('')
let combinations = permutator(arrNums).map(elem => parseInt(elem.join("")))
combinations.sort((a, b) => {
return b - a
})
let indexOfNum = combinations.findIndex(elem => elem === num)
let nextBigIndex = indexOfNum <= 0 ? 0 : indexOfNum - 1
return (combinations[nextBigIndex])
}
console.log(nextbig(12))
console.log(nextbig(517))
console.log(nextbig(2017))

Getting values higher than average in Array - JS

I'm trying to get all the numbers that are higher than the average of a given Array.
(this goes into an HTML page so it's with document.write
this is what I wrote:
sumAndBigger(arrayMaker());
function sumAndBigger(array) {
for (i = 0; i < array.length; i++) {
sum += array;
}
var equalAndBigger = []
var avg = sum / array.length;
for (i = 0; i < array.length; i++) {
if (array[i] > avg) {
equalAndBigger.push(array[i])
}
}
document.write('The numbers are: ' + equalAndBigger)
}
function arrayMaker() {
var array = [];
for (i = 0; i < 5; i++) {
var entrie = +prompt('Enter a number: ');
array.push(entrie)
}
return array;
}
This doesn't seem to work.. what am I doing wrong here?
Thanks in advance!
Ok so here I am giving you a one-liner code to get all the elements from the array that are "strictly greater than" the average value
let array = [1, 2, 3, 4, 5]
let allNums = array.filter(v => v > array.reduce((x, y) => x + y) / array.length);
Explanation
array.reduce((x, y) => x + y) → sum of all elements in the array
array.reduce((x, y) => x + y) / array.length → getting the average
Output
[4, 5]
MORE DETAILED CODE
function getAverage(arr) {
let sum = 0;
for (let i = 0; i < arr.length; i++) {
sum += arr[i];
}
return sum / arr.length;
}
function getGreaterThanAverage(arr) {
let avg = getAverage(arr);
let numbers = [];
for (let i = 0; i < arr.length; i++) {
if (arr[i] > avg) {
numbers.push(arr[i]);
}
}
return numbers;
}

Separator only between operations

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(' | ')));

Categories

Resources