JavaScript pattern to display in browser [closed] - javascript

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 1 year ago.
Improve this question
I am trying to make a Javascript pattern that accepts a user input in the form of a digit and returns the below output:
******1
****1 2 1
***1 2 2 1
**1 2 3 2 1
*1 2 3 3 2 1
1 2 3 4 3 2 1
*1 2 3 3 2 1
**1 2 3 2 1
***1 2 2 1
****1 2 1
*****1
However I am stuck at the a pattern that looks like this:
1
1 2 1
1 2 3 2 1
1 2 3 4 3 2 1
1 2 3 2 1
1 2 1
1
This is the code I wrote until now.
function selectNo() {
var selectedNo = document.getElementById("select-number").value;
for (var i = 1; i <= selectedNo; i++) {
for (var l = 0; l < (selectedNo - i); l++)
document.write(" ")
for (var j = 1; j <= i; j++)
document.write(" " + j)
for (var k = i - 1; k >= 1; k--)
document.write(" " + k)
document.write("<br>");
}
for (var i = 1; i <= selectedNo; i++) {
for (var l = 0; l < i; l++)
document.write(" ")
for (var j = 1; j <= (selectedNo - i); j++)
document.write(" " + j)
for (var k = selectedNo - i - 1; k >= 1; k--)
document.write(" " + k)
document.write("<br>");
}
}
<input type="number" id="select-number" placeholder="Select your number">
<button onclick="selectNo()">Print the pattern</button>
Any suggestions on how to reach the target pattern? Thank you!

Create a function that returns the array of the next numbers and then you can loop from 1 to the input number.
Then you just need to join the arrays.
function line(len) {
const middle = (len - 1) / 2;
const a = [];
for(let i = 0; i < len; i++) {
if(i < middle) {
a.push(i + 1);
}
else {
a.push(len - i);
}
}
return a;
}
function diamond(len) {
l = len * 2 - 1;
const d = [];
for(let i = 0; i < l; i++) {
const a = line(i + 1).map(v => `${v} `);
const b = new Array(l - a.length).fill(' ').concat(a).join('');
d.push(b);
}
for(let i = l - 2; i >= 0; i--) {
const a = line(i + 1).map(v => `${v} `);
const b = new Array(l - a.length).fill(' ').concat(a).join('');
d.push(b);
}
return d.join('<br/>');
}
function main() {
document.getElementById("result").innerHTML = diamond(document.getElementById("val").value);
}
<input id="val" type="number" placeholder="Select your number">
<button onclick="main()">Print the Pattern</button>
<div id="result" style="font-family: monospace;"></div>

Related

How does this specific nested for loop work in vanilla JavaScript?

I got a quiz question in my Full Stack Web Development online course that states the following:
let sum = 0;
for (let i = 0; i < 5; i++) {
for (let j = 0; j < 2; j++) {
sum = sum + i + j;
continue;
}
}
console.log(sum);
Now, the correct answer to the question is 25 according to the answer of the quiz, but I have no idea how it gets to 25? The closest I get when writing it out on paper to try and visualize it, is either 15 / 16.
Could someone please write a visualization that would make it clearer for me on how this nested loop gets to 25?
Thanks in advance.
Add a console after second for, you should see the visualization
let sum = 0;
for (let i = 0; i < 5; i++) {
for (let j = 0; j < 2; j++) {
console.log(`sum=${sum} i=${i} j=${j}`)
sum = sum + i + j;
continue;
}
}
console.log(sum);
//output
// sum=0 i=0 j=0
// sum=0 i=0 j=1
// sum=1 i=1 j=0
// sum=2 i=1 j=1
// sum=4 i=2 j=0
// sum=6 i=2 j=1
// sum=9 i=3 j=0
// sum=12 i=3 j=1
// sum=16 i=4 j=0
// sum=20 i=4 j=1
// 25
Here are all the iterations of the loops, and the value of sum after each.
i = 0 j = 0 sum = 0 + 0 + 0 = 0
i = 0 j = 1 sum = 0 + 0 + 1 = 1
i = 1 j = 0 sum = 1 + 1 + 0 = 2
i = 1 j = 1 sum = 2 + 1 + 1 = 4
i = 2 j = 0 sum = 4 + 2 + 0 = 6
i = 2 j = 1 sum = 6 + 2 + 1 = 9
i = 3 j = 0 sum = 9 + 3 + 0 = 12
i = 3 j = 1 sum = 12 + 3 + 1 = 16
i = 4 j = 0 sum = 16 + 4 + 0 = 20
i = 4 j = 1 sum = 20 + 4 + 1 = 25
This loop is calculated like this.
(1+2+3+4) * 2 = 20
(0+1) * 5 = 5
So sum = 20 + 5 = 25
Perhaps this will give you more visualization of on what's going on:
let sum = 0;
for (let i = 0; i < 5; i++) {
console.log("loop start");
console.log("i", i);
for (let j = 0; j < 2; j++) {
console.log("sum", sum);
console.log("j", j);
sum = sum + i + j;
continue;
}
console.log("loop end");
}
console.log(sum);
The left side would be the values of i and j:
0 // i
0 1 // j // sum = 0 | sum = 1 + (0) <-- () is previous value of sum
1
0 1 // sum = 1 + (1) | sum = 2 + (2)
2
0 1 // sum = 2 + (4) | sum = 3 + (6)
3
0 1 // sum = 3 + (9) | sum = 4 + (12)
4
0 1 // sum = 4 + (16)| sum = 5 + (20)

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>

Print mirror numbers triangle in JS

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

JavaScript (for/while)

In result I should get a spiral matrix but it's not working.The problem is somewhere in the 3rd or 4th for from while
The for loop is just not working. I think, logically, the problem is solved and I have just a syntax problem but I can't find it.
For example the matrix should look like this:
n=3 n=5
1 2 3 1 2 3 4 5
8 9 4 16 17 18 19 6
7 6 5 15 24 25 20 7
14 23 22 21 8
13 12 11 10 9
n = parseInt(prompt('N:', '5'));
A = new Array();
for (i = 0; i < n; i++) {
A[i] = new Array();
for (j = 0; j < n; j++) A[i][j] = 0;
}
DIM = parseInt(n * n);
//A[i][j]=1;
//==========================
document.write("<br>Matrix: <table border='2'>".fontcolor('red'));
for (i = 0; i < n; i++) {
document.write("<tr>");
for (j = 0; j < n; j++) {
document.write("<td >" + A[i][j] + " ");
}
document.write("<br>");
}
document.write("</table>");
document.write("========================================== <br>");
//===========================
k = 1;
nr = 1;
f = true;
while (f) {
i = k - 1;
for (j = k - 1; j <= n - k; j++) {
if (nr <= DIM) {
A[i][j] = nr;
nr++;
document.write(A[i][j] + ' ');
} else {
f = false;
};
};
document.write('<br>');
for (i = k; i <= n - k; i++) {
if (nr <= DIM) {
A[i][j] = nr;
nr++;
document.write(A[i][j] + ' ');
} else {
f = false;
};
};
document.write('<br>');
for (j = (n - k - 1); j >= (k - 1); j--) {
if (nr <= DIM) {
A[i][j] = nr;
nr++;
document.write(A[i][j] + ' ');
} else {
f = false;
};
};
document.write('<br>');
for (i = (n - k - 1); i >= k; i--) {
if (nr <= DIM) {
A[i][j] = nr;
nr++;
document.write(A[i][j] + ' ');
} else {
f = false;
};
};
document.write('<br>');
k++;
};
//=====================================
document.write("<br>Matrix: <table border='2'>".fontcolor('red'));
for (i = 0; i < n; i++) {
document.write("<tr>");
for (j = 0; j < n; j++) {
document.write("<td >" + A[i][j] + " ");
}
document.write("<br>");
}
document.write("</table>");
document.write("========================================== <br>");
It's not a syntax error. It's crashing on A[i][j] = nr; in the for (j = (n - k - 1); j >= (k - 1); j--) { for loop when you try to set A[5][3] = 10; because A[5] is undefined.
That should solve you immediate problem though I doubt that helps much... This is a legitimately tricky programming problem. A spiral seems so simple but it's actually quite hard. I'd highly recommend you take Quince's advice and improve your variable names. Trying to get this code to work would give anyone a headache.

Categories