vertical output and horizontal output to console.log - javascript

I'm new to programming and am curious so I thought I'd reach out.
I have tested myself with 2 outputs to the console, one being FizzBuzz and the other being a chessboard.
My question is why does my chessboard naturally (without "\n") print horizontally and FizzBuzz print out vertically even though they both use the same for loops?
Thanks, Luke.
FizzBuzz,
for(let i= 1; i<= 100; i++){
let message= "";
if(i %3 === 0 && i%5 === 0){
message= "FizzBuzz"
}else if(i % 3 === 0){
message = "Fizz";
}else if(i % 5 === 0){
message = "Buzz"
}
console.log(message || i);
};
Chessboard
let size= 8;
let board= '';
for (let x = 0; x < size; x++){
for (let y= 0; y < size; y++){
if((x+y) %2 == 0){
board += '#';
}else{
board += " ";
}
}
board += "\n"
}
console.log(board);

I think I have the answer.
(A) The code,
console.log("Fizz");
console.log("Buzz");
gives output
"Fizz"
"Buzz"
(B) But,
console.log("Fizz " + "Buzz");
gives output
"Fizz Buzz"
What you are doing with the FizzBuzz is similar to case (A) and in chessboard is similar to case (B). You are logging in every iteration of the for loop in case (A), but only once for every row in case (B).
Since you are new to programming, remember that each console.log("whatever"); logs "whatever" in a new line every time it is run.

Related

Print a list of number using While loop and Do While loop

I am trying to implement the while and do while loop without using an actual array to print an list of number. Here is my code and the output I want.
My code
console.log("While Loop")
let j = 0;
while(j < 5){
j += 1;
console.log (j);
}
console.log("Do While Loop")
var i = 0; //set varible i = 0
do {
i += 1; //return i + 1 to i
console.log (i);
}
while (i < 5); //where i suppose to less than 5
Actual Output I want:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
5 4 3 2 1
4 3 2 1
3 2 1
2 1
1
There is two things here:
You need an inner loop to create the countdown of numbers.
If you are only using JavaScript, you need to form a string with your output and then use console.log() to print. This is because console.log() will append a newline.
The example below will print the first half of the triangle.
console.log("While Loop")
let j = 1;
while (j <= 5) {
let k = 1;
let str = "";
while (k <= j) {
str += k + " ";
k++;
}
j += 1;
console.log(str);
}
If you are using Node.js you can use process.stdout.write to print to the same line and then explicitly write the newline character when needed.
console.log("While Loop")
let j = 1;
while (j <= 5) {
let k = 1;
while (k <= j) {
process.stdout.write(k + " ");
k++;
}
j += 1;
process.stdout.write("\n");
}

Why code works when I write myArray[i] and not when I save myArray[i] in a variable?

I want to populate an empty array with the classical fizzbuzz game (numbers from 1 to 100, when a number is divisible by 3 print 'Fizz, divisible by 5 print 'Buzz', divisible by both 3 and 5 print 'Fizzbuzz'). The problem is, when I write code like in the first portion of code below saving my array[i] in a more convenient variable my if-else if statement doesn't work, only normal numbers are printed; but when I use array[i] instead of a variable everything works fine, as you can see in the second portion of code, where 'Fizz', 'Buzz', 'FizzBuzz' overwrite the normal numbers. They should be the same thing right?
First portion of code with a variable instead of array[i]
var numberArray = [];
var number = 0
for (var i = 0; i < 100; i++) {
number += 1;
thisNumber = numberArray[i];
numberArray.push(number);
if (number %3 ==0 && number %5 ==0) {
thisNumber = 'FizzBuzz';
} else if ( number %3 ==0 ) {
thisNumber = 'Fizz';
} else if ( number %3 ==0 ) {
thisNumber = 'Buzz';
}
}
console.log(numberArray);
Second portion of code with array[i] instead of a variable
var numberArray = [];
var number = 0
for (var i = 0; i < 100; i++) {
number += 1;
numberArray.push(number);
if (number %3 ==0 && number %5 ==0) {
numberArray[i] = 'FizzBuzz';
} else if ( number %3 ==0 ) {
numberArray[i] = 'Fizz';
} else if ( number %3 ==0 ) {
numberArray[i] = 'Buzz';
}
}
console.log(numberArray);
Reassigning a variable, by itself, never has any side effects (except in the most rare situations which aren't worth worrying about). Doing thisNumber = 'FizzBuzz'; does not change anything about how thisNumber may have happened to be used in the past.
Push after assigning to thisNumber. You also want to push thisNumber, not number.
You also need to change the final % 3 to % 5 - you're currently testing % 3 twice.
var numberArray = [];
for (var i = 0; i < 100; i++) {
let thisNumber = i;
if (i % 3 == 0 && i % 5 == 0) {
thisNumber = 'FizzBuzz';
} else if (i % 3 == 0) {
thisNumber = 'Fizz';
} else if (i % 5 == 0) {
thisNumber = 'Buzz';
}
numberArray.push(thisNumber);
}
console.log(numberArray);
In JavaScript a variable is just a reference to an object and an assignment changes where it points to. In
thisNumber = 'FizzBuzz';
you create a new string object and reference it with thisNumber. In
numberArray[i] = 'FizzBuzz';
you modify the i-th element of the array numberArray.
You can't create a reference to an array element and modify it with an assignment. That's not possible in JavaScript.

Creating a complicated algebra function

Doing an assignment for my JavaScript class that requires me to create a function that adds every other index starting with the first and subtracting all the indexes not previously added and produces the sum. I believe the function below should work but it seems to return undefined.
function questionSix(){
let result = 0;
for(let i = 0; i < arguments.length; i++){
if(i == 0){
result += arguments[i];
}else{
if(i % 2 != 0){
result += arguments[i];
}
if(i % 2 == 0){
result -= arguments[i];
}
}
}
}
Because you aren't returning anything (there is no return statement in your code) :
function questionSix(){
let result = 0;
for(let i = 0; i < arguments.length; i++) {
if(i == 0){
result += arguments[i];
}else{
if(i % 2 != 0){
result += arguments[i];
}
if(i % 2 == 0){
result -= arguments[i];
}
}
}
return result;
}
console.log(questionSix(1,6,5,7,8,9,9,8,4,5));
However, it looks like your code isn't doing exactly what it should, here's a solution to your problem :
function questionSix(){
let result = 0; // the sum
let array = []; // the numbers added
for(let i = 0; i < arguments.length; i++) {
// was the number added ?
if(array.indexOf(i) > -1){ // Yes
result += arguments[i]; // add it to the sum
}else{ // No
result -= arguments[i]; // subtract it from the sum
array.push(arguments[i]); // add it to the array
}
}
return result; // return the sum
}
console.log(questionSix(1,6,5,7,8,9,9,8,4,5));
You haven't included a "return" statement
The clue to this (apart from there being no return statement!) is that you start with a result=0 statement, and yet you are receiving undefined.
You don't have to do a special case for i==0
When i==0, i % 2 will equal 0, so the "inner" if-then-else will do the job adequately, without the if (i==0) segment.
Swap the += and -=
However I wonder whether you have reversed the += and -= ? You want to add the 0th and all even-indexed values, don't you? And subtract the odd ones?

Javascript conditional statement not executing

I'm attempting to make a function that builds a checker board however I can't get my second conditional statement to execute and create a new line.
function grid(size) {
var board = "";
for (i = 0; i <= (size * size); i++) {
if (i % 2 === 0) {
board += ' ';
} else if (i % size === 0) {
board += "\n";
} else {
board += '#';
}
}
console.log(board);
}
grid(8);
It appears the else if statement is not executing because I've tried changing the '\n' and condition to other things but nothing is printed. This question is from Eloquent Javascript and the given solution is this:
var size = 8;
var board = "";
for (var y = 0; y < size; y++) {
for (var x = 0; x < size; x++) {
if ((x + y) % 2 == 0)
board += " ";
else
board += "#";
}
board += "\n";
}
console.log(board);
I'm not sure why the second one works but mine doesn't.
Let´s analyse your code:
if(i % size === 0)
This means, when i is equal to 0 or is a multiple of size. In your case, size is 8.
So for your if to trigger, i should be 0,8,16,32....
In all this cases, it will never fire because when i is 0,8,16,32... i % 2 is 0, so it will run the first if instead and never the second one. You should inverse the order of the ifs or run both
i % 2 will always execute instead of i % (8 * 8). You should swap their order or remove the else from the second if.

How can I optimize (or improve) this Fizz Buzz script?

//Script to find numbers that are the power of 3 and 5 from 1 to 100 using % Modulus operator - when it finds a number that can be the power of 3 or 5 it outupts FizzBuzz... example hosted on my blog http://chadcollins.com/find-numbers-that-are-the-power-of-3-and-5-from-1-to-100/
// this was an interview question, and I want to know how to optimize or improve this with "pure javascript".
<div id=out_put></div>
//from a list of 1 to 100 numbers, find the 3's and 5's using modulus
function findPowerOf(numList) {
//setup the variables
var myModMatch1 = 3; //find numbers that have the power of 3
var myModMatch2 = 5; //find numbers that have the power of 5
var tempCheck1 = ""; //stores true or false based on myModMatch1
var tempCheck2 = ""; //stores true or false based on myModMatch2
var stringOut = ""; //concat string for output
var numListStart = 1; //starting number list index
var numListFinish = 100; //ending list index
var numberList = []; //create the list of numbers
for (var i = numListStart; i <= numListFinish; i++) {
numberList.push(i);
}
for (i = 0; i < numberList.length; i++) { //loop on each number and check the modulus params
console.log(numberList[i]);
if ((numberList[i] % myModMatch1) === 0) { //check first modulus param
console.log('houston, we have a match on a number modulus 3');
tempCheck1 = "Fizz";
}
if ((numberList[i] % myModMatch2) === 0) {
console.log('houston, we have a match on a number modulus 5');
tempCheck2 = "Buzz";
}
if (tempCheck1 === "" && tempCheck2 === "") { //no modulus matches
console.log("no modulus matches");
stringOut += numberList[i] + "\n";
}
stringOut += tempCheck1 + tempCheck2 + "\n";
tempCheck1 = ""; //clear both variables
tempCheck2 = "";
}
//dynamically make a div
var outDiv = document.createElement("div");
outDiv.innerHTML = stringOut; //output the final loop values all at once
document.getElementById('out_put').appendChild(outDiv); //update the view
}
findPowerOf(); // call our function
You can remove pretty much all the variables and the function parameter (especially since you're not using the parameter at all). That will also remove one redundant loop.
You can optimize those three parallel ifs by doing one nested if-else.
With all that, you could reduce the code to about 30% of its current size.
Let me give it a shot:
My optimized version:
var div = document.getElementById('out_put');
for (var i = 1; i <= 100; i++) {
if (i % 3 == 0 || i % 5 == 0) {
if (i % 3 == 0) {
div.innerHTML += "Fizz";
}
if (i % 5 == 0) {
div.innerHTML += "Buzz";
}
} else {
div.innerHTML += i;
}
div.innerHTML += '<br>';
}
<div id=out_put></div>
I've used one variable for the div element because selecting it on every iteration is a waste of resources.
Shorter/less readable version:
Here's an even shorter, commented and slighly less-readable version:
var div = document.getElementById('out_put');
for (var i = 1; i <= 100; i++) {
if (i % 3 == 0 || i % 5 == 0) { // see if there's ANY match
if (i % 3 == 0) // check for 3
div.innerHTML += "Fizz";
if (i % 5 == 0) // check for 5
div.innerHTML += "Buzz";
} else // otherwise just output the number
div.innerHTML += i;
div.innerHTML += '<br>'; // add a new line after each
}
<div id=out_put></div>
Insane version - one-liner:
(just for fun - don't ever do this!)
And if you really REALLY want to go crazy with this, you can do a few nested ternary conditionals inside the loop. Technically, a loop with a single line inside - but pretty much unreadable and will perform worse because I removed the DOM element reference variable, so it will do the element query on every iteration. :)
for (var i = 1; i <= 100; i++)
document.getElementById('out_put').innerHTML += ( (i % 3 == 0 || i % 5 == 0) ? ( ((i % 3 == 0) ? "Fizz" : "") + ((i % 5 == 0) ? "Buzz" : "") ) : i) + '<br>';
<div id=out_put></div>

Categories

Resources