Print mirror numbers triangle in JS - javascript

I need to create java script program who print mirror numbers triangle from N. I tested some ways and get the 50% from task:
let n = 5;
function generatePyramid(num) {
let number = '';
for (let i = 1; i <= num; i += 1) {
console.log(number += i);
}
}
generatePyramid(n);
This code print triangle only from 1 to 5. How to print triangle from 5 to 1?
Also my print need to be with space between 1 2 3 4 5... not 12345.
I have similar code from java with array, but can't transform it to JS: https://pastebin.com/9dqqE8J6
This is the final output:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1

One option would be to add a while loop that slices off characters from the number string until it's empty:
let n = 5;
function generatePyramid(num) {
let number = '';
for (let i = 1; i <= num; i += 1) {
console.log(number += i);
}
while (number.length > 1) {
number = number.slice(0, number.length - 1);
console.log(number);
}
}
generatePyramid(n);
To add spaces as well, one option is:
let n = 5;
const log = str => console.log(str.replace(/.(?!$)/g, '$& '))
function generatePyramid(num) {
let number = '';
for (let i = 1; i <= num; i += 1) {
log(number += i);
}
while (number.length > 1) {
number = number.slice(0, number.length - 1);
log(number);
}
}
generatePyramid(n);

<script>
let n = 5;
function generatePyramid(num) {
let number = '';
for (let i = 1; i <= num; i += 1) {
for (let j = 1; j <= i; j += 1)
document.writeln(j+" ");
document.writeln("<br>")
}
for (let i = 4; i >= 1; i -= 1) {
for (let j = 1; j <= i; j += 1)
document.writeln(j+" ");
document.writeln("<br>")
}
}
generatePyramid(n);
</script>
Try This using the same code but i have taken another loop named j

Related

Trying to solve number of ways of making coins, but I can't figure out where my logic is flawed

am trying to solve this problem.
You are working at the cash counter at a fun-fair, and you have different types of coins available to you in infinite quantities. The value of each coin is already given. Can you determine the number of ways of making change for a particular number of units using the given types of coins?
Sample Input 1
10 4
2 5 3 6
Sample Output 1
5
Explanation 1
There are five ways to make change for n = 10 units using coins with values given by C= [2,5,3,6]:
1) {2,2,2,2,2}
2) {2,2,3,3}
3) {2,2,6}
4) {2,3,5}
5) {5,5}
The code I've written:
const getWays = (n, c) => {
let m = c.length
let matrix = Array.from(new Array(m + 1), () => Array(n + 1).fill(0))
console.log(matrix);
for (let i = 0; i <= m; i++) {
matrix[i][0] = 1
}
for (let j = 1; j <= n; j++) {
matrix[0][j] = 0
}
for (let i = 1; i <= m; i++) {
for (let j = 1; j <= n; j++) {
if (c[i] > j) matrix[i][j] = matrix[i - 1][j]
else {
matrix[i][j] = matrix[i - 1][j] + matrix[i][j - c[i]]
}
}
}
}
console.log(getWays(10, [2, 5, 3, 6])) //5
I can't figure out where my logic is breaking in the assignment of values to the matrix. What am I doing wrong?
Check this recursive algorithm.
function getWays(n, c) {
const len = c.length
if (n < 0 || len < 1) return 0
if (len == 1) {
if (n % c[0] == 0) return 1
return 0
}
let cnt = 0
for (let i = 0; i < len - 1; i++) {
for (let j = c[i]; j <= n; j += c[i]) {
cnt += getWays(n - j, c.slice(i + 1))
}
}
if (n % c[len - 1] == 0) cnt++
return cnt
}
console.log(getWays(10, [2, 5, 3, 6])) //5

Why does the for loop in my code restart automatically?

I'm trying to output the pascal triangle. So i stored the previous output in an array(for ex:1,2,1).Then i'm trying to obtain sum of two elements in array(like array[0]+array[1] then array[1]+array[2]).But the loop which i use for getting the sum restarts on it's own (i.e after o is equal to array.length-1 o becomes equal to zero.
Also any help with proper code formatting and how i could do this in a better way is welcome.
I have tried setting array length to zero when the variable o is equal to array length but then too loop starts to run again from zero.
var count=0,sum=0;
let arr=[],arr1=[],arr2=[];
//For Rows
for (let i = 1; i <= 4; i++) {
//For Spaces
for (var k = 4; k >= i; k--) {
document.querySelector('#a').innerHTML += " ";
}
//For addition logic (This Restarts automatically)
for (let j = 1; j <= i; j++) {
if (j == 1 || j == i) {
document.querySelector('#a').innerHTML += " " + 1;
} else {
for (let o = 0; o < arr2.length; o++) {
sum += parseInt(arr2[o]);
if (o % 2 == 1 && i > 3) {
document.querySelector('#a').innerHTML += " " + sum;
sum = parseInt(arr2[o]);
}
}
document.querySelector('#a').innerHTML += " " + sum;
}
count += 1;
}
if (i > 1) {
sum = 0;
arr.length = 0, arr1.length = 0, arr2.length = 0;
arr.push(document.querySelector('#a').innerText);
arr1 = Array.from(arr[0]);
arr2 = arr1.filter(rem)
function rem(value) {
return value > 0;
}
var temp = 0;
while (temp < count - i) {
arr2.shift();
temp++;
}
}
document.querySelector('#a').innerHTML += "<br/>";
}
<html>
<head></head>
<body>
<div id="a"></div>
</body>
</html>
1
1 1
1 2 1
1 3 3 1
Expected Result
1
1 1
1 2 1
1 3 3 6 3 1
Actual Result
You could take a loop for getting the wanted length of the array and another for calculating the sum of two elements of the array.
This approach starts with a single element and takes for every round one at start and one at the end and all other value from the array.
var length = 4,
array = [1],
temp,
i,
element = document.querySelector('#a');
element.innerHTML += array.join(' ');
while (array.length < length) {
temp = [1];
for (i = 0; i < array.length - 1; i++) {
temp.push(array[i] + array[i + 1]);
}
temp.push(1);
array = temp;
element.innerHTML += '<br>' + array.join(' ');
}
<div id="a" style="text-align: center"></div>

Multiplication table in JavaScript - 2 tables

I'm, starting to learn javascript and I have a problem with this code. The code asks for two numbers (the first must be lower than the second) and then it shows the multiplication from the first to the second number. If you type 5 and 7, it shows the multiplication of 5, 6 and 7.
The problem comes when the second number is typed is 10 (except if you type 1 and 10, it shows all). If I type 2 and 10 it shows nothing.
Thanks in advance.
<script>
function multiply() {
do {
do {
var i1 = prompt("Type first number from 1 to 10", "");
} while (i1 < 1 || i1 > 10);
do {
var i2 = prompt("Type second number from 1 to 10 (number must be higher than the first one", "");
} while (i2 < 1 || i2 > 10);
var check = i2 - i1;
if (check >= 0) {
for (var i = i1; i <= i2 ; i++) {
for (var j = 1; j <= 10; j++) {
document.write("<br>" + i + " x " + j + " = " + i * j);
}
document.write("<p>" );
}
} else {
alert("First number is higher than the second, PLease try again.")
}
} while (check < 0)
}
</script>
The return-value of prompt () is a string. So you need to parseInt() to get integers.
do {
do {
var i1 = parseInt (prompt("Type first number from 1 to 10", ""));
} while (i1 < 1 || i1 > 10);
do {
var i2 = parseInt (prompt("Type second number from 1 to 10 (number must be higher than the first one", ""));
} while (i2 < 1 || i2 > 10);
var check = i2 - i1;
if (check >= 0) {
for (var i = i1; i <= i2 ; i++) {
for (var j = 1; j <= 10; j++) {
document.write("<br>" + i + " x " + j + " = " + i * j);
}
document.write("<p>" );
}
} else {
alert("First number is higher than the second, PLease try again.")
}
} while (check < 0)

Where i make mistake here?

Hello everyone i have a problem with my code and i'm not sure how to do this , i need to write code that draw this in console:
Draw '*' in every even number
For that i need to use nested loops.
So far i have only this:
var n = 5;
var stars = '';
for (var i = 1; i <= n; i++) {
var starsline = '';
for (var j = 1; j <= n; j++) {
console.log(i + j);
}
if ( i % 2 === 0){
starsline += '2';
} else {
starsline += '1'
}
stars += starsline;
}
console.log(stars);
This numbers 2 and 1 are only to check if the number is even or odd.
Just a few things:
1) you got some weird bracket here:
/*}*/ if ( i % 2 === 0){
which causes a syntax error later on.
2) you actually log the right thing:
console.log(i + j)
but you dont use it. Just put that into your condition:
if((i + j) % 2 === 0)
and you are done :)
let size = 5, stars = "";
for (var row = 1; row <= size; row++) {
var starsline = "";
for (var col = 1; col <= size; col++){
if ((row + col) % 2 === 0){
starsline += '*';
} else {
starsline += ' ';
}
stars += starsline + "\n";
}
console.log(stars);
I think what you tried to do is something like this:
var n = 5;
var stars = '';
for (var i = 1; i <= n; i++) {
var starsline = '';
for (var j = 1; j <= n; j++){
if ( (i + j) % 2 === 0){
// used three spaces for consistency in the drawing
starsline += ' ';
} else {
starsline += ' * '
}
}
stars += starsline + '\n';
}
console.log(stars);
Try this:
var n = 5;
var stars = '';
for (var i = 1; i <= n; i++)
{
var starsline = '';//<-- reset the value of line
if ( i % 2 === 0)//<--this identifies which line will the stars be created
{
starsline += '* * *';//<--creating the stars on each line
}
else
{
starsline += ' * * ';//<--creating the stars on each line
}
stars += starsline+'\n';//<-- '\n' add line breaks for each lines
}
console.log(stars);//<-- print the stars

Javascript loop for estructure

i have to solve the following function: "x" represent a number of cycles. One cycle sums +1 and then multiply the result *2. For example:
0 cycles = 0 + 1 = 1 (result)
1 cycles = 1 * 2 = 2 (result)
2 cycles = 2 + 1 = 3 (result)
3 cycles = 3 * 2 = 6 (result)
4 cycles = 6 + 1 = 7 (result) and so on.
I have this function:
function final(x) {
for (var i = 0; i < x; i++) {
var result = x[i] * 2 + 1
}
return result;
}
Can you help me out?
If you want to store the results, you can use answer by #Kornflexx. If not, you can directly calculate the value :
function final (x) {
var t = (4 << (x / 2)) - 2;
return x % 2 ? t : t / 2;
}
Note that if x is large you will quickly pass the int limit and would then need to deal with big integers
This should work if you don't care of the fact that the for start at 1.
function final(x) {
var result = [];
result[0] = 1;
for (var i = 1; i < x; i++) {
result[i] = i % 2 ? result[i - 1] * 2 : result[i - 1] + 1;
}
return result;
}
If you only require the final result of the function then the following will achieve that for you.
function final(x) {
var result = 0;
for (var i = 0; i < x; i++) {
if (x % 2 === 0) {
result = result + 1;
} else {
result = result * 2;
}
}
return result;
}
Thanks for your help, the solution finally was this:
function final(x){
var result = 0;
for (var i = 0; i < x; i++){
if (i % 2 === 0){
result = result * 2 + 1;}
else{
result = (result + 1);}
}
return result+1;
}
Just for variety, you can have this short form
function final(x) {
var result = 0;
for (var i = 0; i < x; i++) {
result = x % 2 == 0 ? result + 1 : result * 2
}
console.log(x,result)
return result;
}
final(3)

Categories