Currently, here's my code and currently stock wit hthis
let star = "*";
let length = 0;
let height = 4;
while(length < 5){
while(height > length){
process.stdout.write(star);
height--;
}
console.log(star);
length++;
}
and its output currently is:
* * * * *
*
*
*
*
the expected output is:
* * * * *
* * * *
* * *
* *
*
In this case it is more suitable the 'for' statement than the 'while' statement. Also, as that triangle has the same sides (height = width), then you can use only one variable (i called 'size'). You can create the line just by adding the characters, including the space, and printing it when completed:
let size = 5;
for (let row = 0; row < size; row++) {
let line = ''
for (let col = 0; col < size; col++) {
line += (col < row) ? ' ' : '*'
}
console.log(line)
}
Related
I have a problem in JavaScript programing. I am beginner and from last 24 hrs I just completed one task that made pyramid star pattern which only work in console but the problem is this, that the same coding doesn't work on browser. In the browser the triangle become 📐 such type of triangle.
I added br to code for the browser but the triangle become 📐 right angle triangle.
use pre tag to render your result, so it doesn't remove extra spaces. most html tag will remove extra spaces because it thinks those are useless.
let starCount = 1;
const row = 35
let result = "";
for (let i = 0; i < row; i++) {
let starString = "";
const p = starCount;
for (let j = 0; j < row; j++) {
if (j >= ((row - p) / 2) && j < (((row - p) / 2) + p)) {
starString += "*";
continue;
}
starString += " "
}
result += starString + "\n";
if (row % 2 == 0) {
if (i < (row / 2) - 1) {
starCount += 2;
}
if (i > ((row / 2) - 1)) {
starCount -= 2;
}
} else {
if (i < Math.floor(row / 2)) {
starCount += 2;
} else {
starCount -= 2;
}
}
}
document.querySelector("pre").innerHTML = result;
<pre></pre>
I want to create a multiple pyramid program using Javascript but I really don't understand from where should I start to create multiple star pyramid program.
Note: I have to create this using For Loop.
Output I want:
* *
* * * *
* * * * * *
Here is my Code:
for(i=1;i<=3;i++){
for(j=1;j<=i;j++){
document.write("*"+ " ")
}
for(k=5;k>=1;k=k-2){
for(m=1;m<=k;m++){
document.write("*")
}
}
document.write("<br>")
}
Try the following:
var allowedIndexes = [];
const columnNum = 6
for(var i=0; i<3 ;i++){
allowedIndexes.push(i)
allowedIndexes.push(columnNum - (i+1))
for(var j=0;j< columnNum ;j++){
if(allowedIndexes.includes(j)){
document.write("* ")
}
else {
document.write(" ")
}
}
document.write("<br>")
}
The following code would draw a double pyramid of N levels, using underscores (_) to depict spaces. You may modify the characters used.
const drawPyramid = length => {
for (let i = 0; i < length; i++) {
const N = 2*(length - i - 1)
, blankValues = [...Array(N+1).keys()].slice(1).map(n => n + i)
for (let j = 0; j < 2 * length; j++) {
if (!blankValues.includes(j)) document.write("* ")
else document.write("_ ")
}
document.write("<br>")
}
}
drawPyramid(3)
document.write("<br>")
drawPyramid(4)
document.write("<br>")
drawPyramid(10)
const writePyramid = (levels, row = 0, level = [], spacers = 0) => {
if (row === levels) return;
document.write("<br>")
if (spacers === 0) spacers = levels + 1;
let stars = new Array(row + 1).fill('*')
level = [...stars, ...new Array(spacers > 1 ? spacers : 0).fill(' '), ...stars]
document.write(level.join(''))
writePyramid(levels, row + 1, level, spacers / 2);
}
writePyramid(3)
I'm confused about why this is not working: when I print the array lengths for two exact arrays, holding graphics objects, they are different. I'm using Javascript. Can someone pls help? Thanks.
Here's the code:
for (var i = 0; i < 4; i++){
for (var j = 0; j < 4; j++){
var tile = new Circle(30);
tile.setPosition(i * 3 * tile.getRadius() + tile.getRadius() * 2, j * 3 * tile.getRadius() + tile.getRadius() * 2);
tile.setColor(colors[Randomizer.nextInt(0, colors.length - 1)]);
add(tile);
} tiles.push(tile);
}
println(tiles.length);
for (var r = 0; r < rows; r++){
for (var c = 0; c < cols; c++){
var black = new Circle(30);
black.setPosition(r * 3 * black.getRadius() + black.getRadius() * 2, c * 3 * black.getRadius() + black.getRadius() * 2);
black.setColor(Color.black);
black.isFilled = false;
after.push(black);
}
}
println(after.length);
I'm trying to produce a function that starts with source image, generates noise, and then uses the noise to distort the image.
I start with creating the noise, and turning it into a vector field, Then I remap the coordinates, and pull the pixels out of the image at the correct coordinates.
Finally I re-combine the extracted pixels into an image.
So far my code is as follows:
function distort(sourceImage){
let vectorField = [];
var amount = 100;
var scale = 0.01;
for (x = 0; x < sourceImage.width; x++){
let row = [];
for (y = 0; y < sourceImage.height; y++){
let vector = createVector(amount*(noise(scale*x,scale*y)-0.5), 4*amount*(noise(100+scale*x,scale*y)-0.5))
row.push(vector);
}
vectorField.push(row);
}
var result = [];
sourceImage.loadPixels();
for (i = 0; i < sourceImage.width; i++){ //sourceImage.width
for (j = 0; j < sourceImage.height; j += 4){ //sourceImage.height
var res = vectorField[i][j];
//console.log(res);
var ii = constrain(floor(i + res.x), 0, sourceImage.width - 1);
var jj = constrain(floor(j + res.y), 0, sourceImage.height - 1);
//console.log(ii, jj);
result[i * sourceImage.width + j] = color(sourceImage.pixels[ii * sourceImage.width + jj], sourceImage.pixels[ii * sourceImage.width + jj + 1], sourceImage.pixels[ii * sourceImage.width + jj + 2], sourceImage.pixels[ii * sourceImage.width + jj + 3]);
}
}
//console.log(result)
//console.log(sourceImage.pixels[0 + sourceImage.width * 0])
for (n=0; n<sourceImage.width; n++) {
for(m=0; m<sourceImage.height; m++){
index = (n * sourceImage.width + m) * 4;
if (index >= 4194300){
index = 4194300;
}
sourceImage.pixels[index] = red(result[index]);
sourceImage.pixels[index + 1] = green(result[index]);
sourceImage.pixels[index + 2] = blue(result[index]);
sourceImage.pixels[index + 3] = alpha(result[index]);
}
}
sourceImage.updatePixels();
image(sourceImage, 0, 0, size, size);
}
Except that as a result, I'm getting 4 panels of noise across the top 4th of the canvas. The noise notably includes a lot of pixels that I know weren't in the source image, too (namely blue pixels; the image I'm trying to distort is red and white). The noise is sort of identifiable as having started as the source image, but distorted and with the aforementioned artefacts.
For comparison:
You do not process the vector field completely, you have to read each vector from the field. Actually you read just each 4th element of the vector
for (j = 0; j < sourceImage.height; j += 4)
for (j = 0; j < sourceImage.height; j++)
Further the computation of the source index is wrong. Note the control variable for the row (jj) has to be multiplied by the height. The index of the pixel in the array has to be multiplied by 4, because each pixel consists of 4 color channels:
ii * sourceImage.width + jj
(jj * sourceImage.width + ii) * 4
The computation of the target index is wrong, too:
index = (n * sourceImage.width + m) * 4;
index = (m * sourceImage.width + n) * 4;
Note, result contains 1 element for each pixel, byut sourceImage.pixels contains 4 elements for each pixel. Thus the index which reads from result and the index which access the target are different:
let result_i = m * sourceImage.width + n;
let target_i = result_i * 4;
For instance:
let result = [];
for (let j = 0; j < sourceImage.height; j++) {
for (let i = 0; i < sourceImage.width; i++) {
let res = vectorField[i][j];
let ii = constrain(floor(i + res.x), 0, sourceImage.width - 1);
let jj = constrain(floor(j + res.y), 0, sourceImage.height - 1);
let source_i = (jj * sourceImage.width + ii) * 4;
let col = color(
sourceImage.pixels[source_i],
sourceImage.pixels[source_i + 1],
sourceImage.pixels[source_i + 2],
sourceImage.pixels[source_i + 3]);
result.push(col);
}
}
for(let m = 0; m < sourceImage.height; m++) {
for (let n = 0; n < sourceImage.width; n++) {
let result_i = m * sourceImage.width + n;
let target_i = result_i * 4;
let col = result[result_i];
sourceImage.pixels[target_i] = red(col);
sourceImage.pixels[target_i + 1] = green(col);
sourceImage.pixels[target_i + 2] = blue(col);
sourceImage.pixels[target_i + 3] = alpha(col);
}
}
I'm learning basics of JavaScript. I try to code a program that logs the following scheme to the console:
*
* *
* * *
* * * *
* * * * *
* * * * *
* * * *
* * *
* *
*
I managed to get first half of the task by the code:
var x = 5;
var line;
for(var i = 0; i<x; i=i+1){
line = "";
for(var j=0; j<x; j=j+1){
if(j <= i){
line = line + " * ";
}
}
console.log(line);
}
So it looks like:
*
* *
* * *
* * * *
* * * * *
Could anybody give me a hint how to get the secod part of the scheme? I'd like to use another loop like the one I have but to revert it's action so that there would be less and less stars in each line.
Hints: You need to decrement i and j in the for loop and turn-around the <. instead of starting var i = 0 start at the end with 5.
With two for loops after another. The first one adds stars and the second one removes stars:
var line = "";
for (var i = 0; i < 5; i += 1) {
line += "*";
console.log(line);
}
for(var j = 5; j > 0; j -= 1) {
line = line.replace(line[j], "");
console.log(line);
}
spoiler:
What about just using a while loop?
var count = 0,
i = 1,
addition = 1,
str = null;
while (i) {
str = new Array(i+1).join('*');
console.log(str);
if (i === 5) {
console.log(str);
addition = -1;
}
i += addition;
}
You can, as one possible solution, put another if clause inside of your loop (read carefully):
If the line index reached half of the pyramid (maximum line length), start printing maximumLineLength * 2 - index - 1 instead.
This will essentially change the behaviour of the loop after the half is reached, so that the number of starts will start to decrease instead of increasing.
Another solution, if you're keeping the number of stars in the string, would be to add them until maxLineLength is reached, and then subtract them until you go back to 0 (you can use a boolean flag for that).
I'm not posting actual code to avoid spoiling the solution.
I think the solution with the conditionals and the one with the two loops are the ones you should use but you can compute the number of asterisks with a bit of modular arithmetic directly:
var x = 5;
var line;
for(var i = 1;i < x * 2;i++){
line = '';
for(var j = 0;j < Math.abs( (i+3) % 8 - 4) + 1;j++){
line = line + ' * ';
}
console.log(line);
}
I used a trick that will most probably be seen here as a little bit dirty but it works. The sequence I use here is 1,2,3,4,5,4,3,2 and to get the last 1 I just run it one more time.
In general:
To get a sequence from 1 to x and back to 1 again (with x > 1) run the outer loop x*2 times with Math.abs( (i+(x - 2)) % (2*x - 2) - (x - 1)) + 1 as the upper limit for the inner loop with i going from 1 to 2x-1.
Proof is left as an exercise for the student.
It's anti-pattern; why would you want this?
Nevertheless - accumulative variable:
var x = 5,
y,
line,
result = [];
while (x--) {
y = 5 - x;
line = '';
while (y--) {
line = line + '*';
}
result.push(line);
}
document.write(result.join('<br>'));
document.write('<br>');
document.write(result.reverse().join('<br>'));
Many solutions are possible but the simplest, like you suggest, is reverting the loop; this is what loop statement should look like:
for(var i = x-1 ; i>=0 ; i--)
Basically you have to change the for-loop conditions that will go backwards starting from the max-value , this is the first statement part and is called initializer ;
the loop must stop/break at 0 , second part of statement called test (until the loop satisfies this condition it will go on in next iteration );
the last part of statement is the iteration update (how the state should change in next loop);
that said changing the statement you should be able to keep your body unchanged :
var x = 5;
for (var i = x - 1; i >= 0; i--) {
line = "";
for (var j = 0; j < x; j = j + 1) {
if (j <= i) {
line = line + " * ";
}
}
console.log(line);
}