I am currently trying to solve the xmas tree problem, with internal tree-like shape.
issue is with internal spacing, it supposed to be like: 1, 5, 7, 9. Instead it is 1, 3, 4, 5. I do not know, how to increment s loop by 2 in each loop turn.
/*
*********
**** ****
*** ***
** **
* *
*********
*/
function drawTree(h) {
let n = h + 3;
for (var i = 1; i <= 1; i++) {
var temp = "";
for (var j = 1; j <= n; j++) {
temp = temp + "*";
}
console.log(temp);
}
for (var i = 0; i < h - 2; i++) {
var tree = '';
console.log("\n");
for (var k = 3; k <= h - i; k++) {
tree += "*";
};
tree += "s";
for (var k = 1; k <= i; k++) {
for (var k = 1; k <= i; k++) {
tree += "s";
};
tree += "s";
};
for (var k = 3; k <= h - i; k++) {
tree += "*";
};
console.log(tree);
};
console.log("\n");
let g = h + 3;
for (var i = 1; i <= 1; i++) {
var temp = "";
for (var j = 1; j <= g; j++) {
temp = temp + "*";
}
console.log(temp);
}
};
drawTree(6);
function drawTree(stars, rowLength) {
for (let row = 0; row < rowLength; row++) {
if (row === 0) {
console.log("*".repeat(stars));
} else if(row === rowLength - 1) {
console.log("*".repeat(stars));
} else {
let spaces = 2 * row - 1;
if (spaces > stars) {
spaces = stars;
}
let numStarsInRow = "*".repeat((stars - spaces) / 2);
console.log(numStarsInRow + " ".repeat(spaces) + numStarsInRow);
}
}
}
drawTree(9, 5)
You can implement this by nesting loops over the height and the width of the tree, noting that the output is a * whenever:
it's the first or last row; or
the current x position is less than or equal to the halfway point minus the row number; or
the current x position is greater than or equal to the halfway point plus the row number
For all other cases the output is a space. For example:
function drawTree(height) {
// compute the width of the tree from the height
let width = height % 2 ? height + 2 : height + 3;
// find the halfway point
let half = (width - 1) / 2;
for (let i = 0; i < height; i++) {
let l = '';
for (let j = 0; j < width; j++) {
if (i == 0 || // first row
i == height - 1 || // last row
j <= (half - i) || // left side
j >= (half + i) // right side
) {
l += '*';
}
else {
l += ' ';
}
}
console.log(l);
}
}
drawTree(6);
drawTree(5);
Related
Ok so i tried to make conway's game of life in p5.js and i am stuck in some wierd bug .
function make2DArray(cols, rows) {
let arr = new Array(cols);
for (let i = 0; i < arr.length; i++) {
arr[i] = new Array(rows);
}
return arr;
}
function countNeighbors(grid, x, y) {
let sum = 0;
for (let i = -1; i < 2; i++) {
for (let j = -1; j < 2; j++) {
let col = x + i;
let row = y + i;
if (grid[col][row] === undefined){
sum += grid[col][row];
}
}
}
sum-=grid[x][y]
return sum;
}
let grid;
let next;
let cols;
let rows;
let resolution = 20;
let fr = 15;
function setup() {
createCanvas(600, 400);
frameRate(fr);
cols = width / resolution;
rows = height / resolution;
next = make2DArray(cols, rows);
grid = make2DArray(cols, rows);
for (let i = 0; i < cols; i++) {
for (let j = 0; j < rows; j++) {
grid[i][j] = floor(random(2));
}
}
}
function draw() {
background(0);
for (let i = 0; i < cols; i++) {
for (let j = 0; j < rows; j++) {
let x = i * resolution;
let y = j * resolution;
if (grid[i][j] == 1) {
fill(0);
stroke(150);
rect(x, y, resolution - 1, resolution - 1);
} else {
fill(255);
stroke(150);
rect(x, y, resolution - 1, resolution - 1);
}
}
}
for (let i = 0; i < cols; i++) {
for (let j = 0; j < rows; j++) {
let state = grid[i][j];
let neighbors = countNeighbors(grid, i, j);
if (state == 0 && neighbors == 3) {
next[i][j] = 1;
} else if (state == 1 && (neighbors < 2 || neighbors > 3)) {
next[i][j] = 0;
} else {
next[i][j] = state;
}
}
}
grid = next;
}
Soo basically i have function countNeighbors and i think that bug is in there , i tried checking if col and row are i boundaries of array
like this
if (col>-1 && col <grid.length && row>-1 && row < grid[0].length){
//increase sum
}
but its even worse. I am new to js so i figured out that if for example
let x=new Array(10);
//and then when i try this
console.log(c[-1])
//it should give undefined
but program still wont work :(
Thanks!
With a few changes you can make it work:
1) Replace let row = y + i; by let row = y + j; That typo was making most of the counts off.
2) Replace the condition
if (grid[col][row] === undefined){
by
if (0 <= col && col < cols && 0 <= row && row < rows){
The problem with your original condition is that if grid[col] is undefined then grid[col][row] is undefined[row], which doesn't make sense.
3) For consistency sake, add a semicolon to the end of sum-=grid[x][y]
4) Finally, so as to not create an unintended alias, you need to replace grid = next by something like:
for(let i = 0; i < grid.length; i++){
grid[i] = next[i].slice();
}
Alternatively, make next a variable which is local to draw() and place the line let next = make2DArray(cols, rows); to the beginning of draw().
I want to print the following star pattern using JavaScript:
*****
***
*
***
*****
And I am trying this code, where I am getting off a triangle:
for (i = 3; i >= 1; i--) {
/* Printing spaces */
for (j = 0; j <= 3 - i; j++) {
document.write(" ");
}
/* Printing stars */
k = 0;
while (k != (2 * i - 1)) {
document.write("*");
k++;
}
document.write("<br/>")
}
try this code
after i==1 create new pattern inside it
for (i = 3; i >= 1; i--) {
/* Printing spaces */
for (j = 0; j <= 3 - i; j++) {
document.write(" ");
}
/* Printing stars */
k = 0;
while (k != (2 * i - 1)) {
document.write("*");
k++;
}
document.write("<br/>")
if (i == 1) {
for (t = 2; t <= 3; t++) {
for (j = 0; j <= 3 - t; j++) {
document.write(" ");
}
/* Printing stars */
k = 0;
while (k != (2 * t - 1)) {
document.write("*");
k++;
}
document.write("<br/>")
}
}
}
Try this code:-
In this we use outer loop and inner loop.
var i, j;
//outer loop
for(i=1; i <= 5; i++)
{
//inner loop
for(j=1; j<=i; j++)
{
document.write('*');
}
document.write('<br/>');
}
Iteration:-
i j(Repeat)
1 1
2 2
3 3
4 4
5 5
const n = 5
for (var i = 0; i < n; i++) {
var star = '';
for (var j = 0; j < n - i; j++) {
star += ' ';
}
for (var k = 0; k < i; k++) {
star += '* ';
}
console.log(star);
}
for (var i = 0; i < n; i++) {
var star = '';
for (var b = 0; b < i; b++) {
star += ' ';
}
for (var a = 0; a < n - i; a++) {
star += '* ';
}
console.log(star);
}
I'm having a bit of a problem with this function:
function create_enemies(rows, columns) {
var i, j;
var x_position = 0;
var y_position = 0;
var id = 0;
enemies_array = new Array(rows);
for (i = rows - 1; i >= 0; i--) {
enemies_array[i] = new Array(columns);
for (j = columns - 1; j >= 0; j--) {
x_position = j * (enemy_squadron_width / 4) + (ship_width / 2);
y_position = i * (enemy_squadron_height / 4);
enemies_array[i, j] = {
x : x_position,
y : y_position,
width : ship_width,
height : ship_height,
speed : 2,
id : id
};
id++;
console.log("this one's fine: " + enemies_array[i, j].y);
}
}
for (i = rows - 1; i >= 0; i--) {
for (j = columns - 1; j >= 0; j--) {
console.log("This one's not fine: " + enemies_array[i, j].y);
}
}
}
What's happening is that on the first console.log, the Y attribute is being correctly printed, but on the second console.log, every Y in every element of the array is set at 0. Somehow the Y attribute is lost between the first outer for-loop and the second.
I'm surely missing something very obvious, and starting to feel a little insane.
Any ideas?
Thank you very much.
edit - I should mention that every other attribute is fine. Only the Y is being reset
Here you go:
function create_enemies(rows, columns) {
var x_position = 0;
var y_position = 0;
var enemy_squadron_width = 100;
var enemy_squadron_height = 100;
var ship_width = 100;
var ship_height = 100;
var id = 0;
var enemies_array = new Array(rows);
for (var i = rows - 1; i >= 0; i--) {
enemies_array[i] = new Array(columns);
for (var j = columns - 1; j >= 0; j--) {
var x_position = j * (enemy_squadron_width / 4) + (ship_width / 2);
var y_position = i * (enemy_squadron_height / 4);
enemies_array[i][j] = {
x : x_position,
y : y_position,
width : ship_width,
height : ship_height,
speed : 2,
id : id
};
id++;
console.log("this one's fine: " + enemies_array[i][j].y);
}
}
for (var i = rows - 1; i >= 0; i--) {
for (var j = columns - 1; j >= 0; j--) {
console.log("This one's not fine: " + enemies_array[i][j].y);
}
}
}
create_enemies(10,10);
You need to acces the elements of the array by a[i][j].
Fiddle: http://jsfiddle.net/bL4mwgez/1/
I was trying to find the Rank of the given string in the list of permutations and was hoping someone can find the bug.
function permute() {
var W = $('input').val(),
C = [];
for (var i = 0; i < 26; i++) C[i] = 0;
var rank = 1;
for (var i = 0; i < W.length; i++) {
C[W.charCodeAt(i) - 'a'.charCodeAt(0)]++;
}
var repeated= 1;
for (var i = 0; i < C.length; i++) {
if(C[i] > 0) {
repeated *= fact(C[i]);
}
}
if (W !== '') {
for (var i = 0; i < W.length; i++) {
//How many characters which are not used, that come before current character
var count = 0;
for (var j = 0; j < 26; j++) {
if (j == (W.charCodeAt(i) - 'a'.charCodeAt(0))) break;
if (C[j] > 0) count++;
}
C[W.charCodeAt(i) - 'a'.charCodeAt(0)] = 0;
rank += ( count * fact(W.length - i - 1) );
}
rank = rank/ repeated;
}
var pp = 'Rank of :: ' + W + ' -- ' + rank;
$('div').append('<p>' + pp + '</p>');
}
function fact(n) {
if (n == 0 || n == 1) return 1;
else return fact(n - 1) * n;
}
$('button').click(permute);
Check Fiddle
A use case for this might be
bookkeeper is supposed to give a rank of 10743.
Here's the demo:
For each position check how many characters left have duplicates, and use the logic that if you need to permute n things and if 'a' things are similar the number of permutations is n!/a!
So I am trying to model Gram-Schmidt for any size N×N matrix, and I have officially hit a roadblock I can't get past. I know it's a matter of looping this correctly, but I can't figure out what the problem is. Remember I do not want to just pass in a 3×3 matrix, but any size N×N.
The course notes QR Decomposition with Gram-Schmidt explains exactly what I want to do. Very simple calculation by the way. In the course notes ||u|| means that it is the sum of the square of the elements, so sqrt(x12 + x22 + x32 + .... + xn2).
The multiplication symbol is actually the dot product.
The code I wrote so far is listed below. What is wrong with it?
function qrProjection(arr) {
var qProjected = [];
var tempArray = [];
var aTemp = arr;
var uTemp = new Array(arr.length);
var uSquareSqrt = new Array(arr.length);
var eTemp = [];
var sum = 0;
var sumOfSquares = 0;
var breakCondition = 0;
var secondBreakCondition = 0;
var iterationCounter = 0;
//Build uTemp Array
for (i = 0; i < arr.length; i++) {
uTemp[i] = new Array(arr[i].length);
}
for (i = 0; i < arr.length; i++) {
eTemp[i] = new Array(arr[i].length);
}
uTemp[0] = aTemp[0];
for (j = 0; j <= arr.length; j++) {
for (l = 0; l < arr[j].length; l++) {
if (breakCondition == 1) break;
sumOfSquares = Math.pow(uTemp[j][l], 2) + sumOfSquares;
}
if (breakCondition == 0) {
uSquareSqrt[j] = Math.sqrt(sumOfSquares);
sumOfSquares = 0;
}
for (i = 0; i < arr[j].length; i++) {
if (breakCondition == 1) break;
eTemp[j][i] = (1 / (uSquareSqrt[j])) * (uTemp[j][i]);
}
breakCondition = 1;
if (iterationCounter == 0) {
for (m = 0; m < arr[j].length; m++) {
matrixDotProduct = aTemp[j + 1][m] * eTemp[j][m] + matrixDotProduct;
}
}
else {
for (m = 0; m < arr[j].length; m++) {
for (s = 0; s <= iterationCounter; s++) {
matrixDotProduct = aTemp[j + 1][s] * eTemp[m][s] + matrixDotProduct;
}
for (t = 0; t < arr[j].length; t++) {
uTemp[j + 1][t] = aTemp[j + 1][t] - eTemp[j][t] * matrixDotProduct;
}
}
}
if (iterationCounter == 0) {
for (m = 0; m < arr[j].length; m++) {
uTemp[j + 1][m] = aTemp[j + 1][m] - eTemp[j][m] * matrixDotProduct;
}
}
matrixDotProduct = 0;
for (l = 0; l < arr[j].length; l++) {
sumOfSquares = Math.pow(uTemp[j + 1][l], 2) + sumOfSquares;
}
uSquareSqrt[j + 1] = Math.sqrt(sumOfSquares);
sumOfSquares = 0;
for (i = 0; i < arr[j].length; i++) {
eTemp[j + 1][i] = (1 / (uSquareSqrt[j + 1])) * (uTemp[j + 1][i]);
}
iterationCounter++;
}
qProjected = eTemp;
return qProjected;
}
I must apologize that instead of tweaking your code, I wrote my own from scratch:
/* Main function of interest */
// Each entry of a matrix object represents a column
function gramSchmidt(matrixA, n) {
var totalVectors = matrixA.length;
for (var i = 0; i < totalVectors; i++) {
var tempVector = matrixA[i];
for (var j = 0; j < i; j++) {
var dotProd = dot(matrixA[i], matrixA[j], n);
var toSubtract = multiply(dotProd, matrixA[j], n);
tempVector = subtract(tempVector, toSubtract, n);
}
var nrm = norm(tempVector, n);
matrixA[i] = multiply(1 / nrm, tempVector, n);
}
}
/*
* Example usage:
* var myMatrix = [[1,0,0],[2,3,0],[5,4,7]];
* gramSchmidt(myMatrix, 3);
* ==> myMatrix now equals [[1,0,0],[0,1,0],[0,0,1]]
* 3 here equals the number of dimensions per vector
*/
/* Simple vector arithmetic */
function subtract(vectorX, vectorY, n) {
var result = new Array(n);
for (var i = 0; i < n; i++)
result[i] = vectorX[i] - vectorY[i];
return result;
}
function multiply(scalarC, vectorX, n) {
var result = new Array(n);
for (var i = 0; i < n; i++)
result[i] = scalarC * vectorX[i];
return result;
}
function dot(vectorX, vectorY, n) {
var sum = 0;
for (var i = 0; i < n; i++)
sum += vectorX[i] * vectorY[i];
return sum;
}
function norm(vectorX, n) {
return Math.sqrt(dot(vectorX, vectorX, n));
}
Note that the algorithm above computes the Gram-Schmidt orthogonalization, which is the matrix [e1 | e2 | ... | en], not the QR factorization!