Undefined result from Fizz Buzz game Javascript - javascript

I'm having an assignment where I have to do the FizzBuzz game in Javascript. The problem is I get 'Answer = undefined' when I run the function. I have to print it with a comma separated value but I think I can figure that out for my self though; Thanks in advance. Regards, Thomas.
function fizzBuzz(start, stop) {
for(var i = start; i <= stop; i++) {
if (i % 3 == 0 && i % 5 == 0) {
document.write("Fizz Buzz");
}else if(i % 3 == 0) {
document.write("Fizz");
}else if(i % 5 == 0) {
document.write("Buzz");
}else {
document.write(i);
}
}
}
ANSWER = (fizzBuzz(4, 22));

Because the fizzBuzz function isn't returning anything. You need to return a result from that function. document.write writes out text to the document.

You aren't returning anything from your function.
ANSWER will be what you 'return' in a function.
If you wanted to return all the values you would need to do somthing like
var ans='';
...
if ( whatever) ans+= 'Fizz Buzz,';
....
return ans.substring(0,ans.length-1);

Some modifications to your code...
function fizzBuzz(start, stop) {
var i;
var results = [];
for (i = start; i <= stop; i++) {
if (i % 15 == 0) {
results.push('Fizz Buzz');
} else if (i % 3 == 0) {
results.push('Fizz');
} else if (i % 5 == 0) {
results.push('Buzz');
} else {
// cast to string just so all the results in the array are string
results.push(i + '');
}
}
return results;
}
ANSWER = fizzBuzz(4, 22); // output: [ '4', 'Fizz', 'Buzz', '7', '8', ...etc ]

<html>
<script>
function fizzBuzz(start, stop) {
var str = 'ANSWER = ';
for(var i = start; i <= stop; i++) {
if (i % 3 == 0 && i % 5 == 0) {
str += "Fizz Buzz";
}else if(i % 3 == 0) {
str += "Fizz";
}else if(i % 5 == 0) {
str += "Buzz";
}else {
str += i;
}
if (i<stop)
str += ", ";
}
document.getElementById('writeto').innerHTML += str;
}
fizzBuzz(4, 22);
</script>
<body>
<a id='writeto'></a>
</body>
</html>

Related

How do i return the result of all loops in javascript?

I am trying to insert dashes ('-') between each two odd numbers and insert asterisks ('*') between each two even numbers, but I am only getting the last result.
I want to print out all the elements in the array.
For example: if num is 4546793 the output should be 454*67-9-3. I Did not count zero as an odd or even number.
function StringChallenge(num) {
let result = "";
for (let i = 0; i < num.length; i++) {
if (num[i] === 0) {
continue;
}
if (num[i - 1] % 2 == 0 && num[i] % 2 == 0) {
result = num[i - 1] + "*" + num[i];
continue;
}
if (num[i - 1] % 2 == !0 && num[i] % 2 == !0) {
result = num[i - 1] + "-" + num[i];
continue;
}
}
return result;
}
console.log(StringChallenge([4,5,4,6,7,9,3]));
You do not need to check as if&continue. Inserting given numbers to the result string and only adding "-" when index and previous are odd, and "*" when index and previous are even.
function StringChallenge(num) {
let result = "";
for (let i = 0; i < num.length; i++) {
if (num[i]%2 ===0) {// even
if(i !== 0 && num[i-1]%2===0){// previous is even either
result+="*"+num[i];
}else{
result+=num[i];
}
}else{// odd
if(i !== 0 && num[i-1]%2===1){// previous is odd either
result+="-"+num[i];
}else{
result+=num[i];
}
}
}
return result;
}
console.log(StringChallenge([4,5,4,6,7,9,3]));
Try this :)
function test(a){
let result=""
for(let i=0; i < a.length; i++){
if(a[i] != 0 && a[i-1] % 2 == 0 && a[i] % 2 == 0){
result = result + '*' + a[i]
}
else if (a[i] != 0 && a[i-1] % 2 != 0 && a[i] % 2 != 0){
result = result + '-' + a[i]
}
else{
result = result + a[i]
}
}
return result
}
console.log(test([4,5,4,6,7,9,3]));
As everyone has identified, the problem is you are not adding to result.
But here is a suggestion to make your code easier to read
// These one line functions make your code easier to read
function IsEven(num){
return num % 2 === 0;
}
function IsOdd(num){
return num % 2 !== 0;
}
function StringChallenge(numArray) {
// return empty string if not an array or empty array
if(!Array.isArray(numArray) || numArray.length === 0) return "";
let result = "" + numArray[0]; // use "" to coerce first element of numArray from number to string
for (let i = 1; i < numArray.length; i++) {
// focus on the conditions to determine the separator you want between each element
separator = "";
if (numArray[i] !== 0) {
if (IsEven(numArray[i]) && IsEven(numArray[i - 1])) {
separator = "*";
} else if (IsOdd(numArray[i]) && IsOdd(numArray[i - 1])){
separator = "-";
}
}
// build the result
result += separator + numArray[i];
}
return result;
}
I will do that this way :
== some advices for 2 cents ==
1 - try to make your code as readable as possible.
2 - use boolean tests rather than calculations to simply do a parity test
3 - ES7 has greatly improved the writing of JS code, so take advantage of it
console.log(StringChallenge([4,5,4,6,7,9,3])); // 454*67-9-3
function StringChallenge( Nums = [] )
{
const
isOdd = x => !!(x & 1) // Boolean test on binary value
, isEven = x => !(x & 1) && x!==0 // zero is not accepted as Even value
;
let result = `${Nums[0]??''}`; // get first number as
// result if Nums.length > 0
for (let i=1; i<Nums.length; i++)
{
if ( isOdd(Nums[i-1]) && isOdd(Nums[i]) ) result += '-';
if ( isEven(Nums[i-1]) && isEven(Nums[i]) ) result += '*';
result += `${Nums[i]}`; // same as Nums[i].toString(10);
}
return result
}
I hope this helps. I tried to keep it as simple as possible.
function StringChallenge(num) {
//start with a string to concatenate, or else interpreter tries to do math
operations
let result = num[0].toString();
function checkOdd(num){ //helper function to check if odd
return num % 2
}
for (let i = 0; i < num.length - 1; i++) {
if (checkOdd(num[i]) && checkOdd(num[i+1])) { //checks if both odd
result += `-${num[i+1]}`; //adds - and next number
} else if (!checkOdd(num[i]) && !checkOdd(num[i+1])) { //checks if both even
result += `*${num[i+1]}`; //adds * and next number
} else { //otherwise
result += num[i+1]; //just add next number
}
}
return result;
}
console.log(StringChallenge([4,5,4,6,7,9,3]));
Use +=. And, change your logic, your code prints out "4*67-99-3".
The zero check was pretty hard for me I hope the variables in my code explain itself. If not, let me know.
function even(num) {
return num % 2 === 0;
}
function odd(num) {
return num % 2 !== 0;
}
function StringChallenge(num) {
let result = "";
for (let i = 0; i < num.length; i++) {
var currentZero = num[i] === 0
var previousZero = num[i-1] === 0
var bothEven = even(num[i]) && even(num[i-1])
var bothOdd = odd(num[i]) && odd(num[i-1])
var firstNumber = (i === 0)
if (!currentZero) {
if (firstNumber) {
result += num[i]
} else {
if (bothEven && !previousZero) {
result += "*" + num[i]
} else if (bothOdd && !currentZero) {
result += "-" + num[i]
} else {
result += num[i]
}
}
}
}
return result;
}
console.log(StringChallenge([0,4,5,0,4,6,7,9,3]));

Having problems with output

I build the code, which should return Knick if the number is odd, Knack if it's multiple of five and KnickKnack if it's either odd and multiple of five. The problem is that it returns line to line in console, I want it to concatenate in a string.
Here's the code:
function knickKnack(maxValue) {
const numbers = [];
for (var i = 1; i <=100; i++) {
if (i % 5 === 0 ) {
console.log ('KnickKnack, ');
} else if (i % 10 === 0) {
console.log ('Knack, ');
} else if (i % 2 === 1) {
console.log ('Knick, ');
} else {
console.log (i + ', ');
}
}
return numbers;
}
knickKnack();
function knickKnack(maxValue) {
var knickKnackString = '';
for (var i = 1; i <= maxValue; i++) {
if (i % 5 === 0 && i % 2 === 1)
knickKnackString += 'KnickKnack, ';
else if (i % 10 === 0)
knickKnackString += 'Knack, ';
else if (i % 2 === 1)
knickKnackString += 'Knick, ';
else
knickKnackString += i + ', ';
}
console.log(knickKnackString);
}
Try like this.

Why is my Javascript fizzbuzz code not working?

I am trying to create a JS function that will print Fizz when a number divisible by 3 appears and Buzz if it is divisible by 5 and Fizzbuzz if both 5 and 3 but keeps printing "undefined" on chrome>sources>snippets. I have previously managed to run JS there but now it is just printing "undefined". Please help what is wrong with my code? Thank you in advance
This is my code:
var output = [];
var count = 1;
function fizzBuzz() {
if (count % 3 === 0) {
output.push("Fizz");
}
if (count % 5 === 0) {
output.push("Buzz");
}
if (count % 15 === 0) {
output.push("FizzBuzz");
} else {
output.push(count);
}
count++;
console.log(output);
};
You need to call the function using fizzBuzz(). You'd likely want to do this in a loop until it reaches a certain number.
In the example below, I use a while loop to call the function until count reaches 100. I've also moved the console.log() call to the end of the loop, as it doesn't make sense to log the entire array after each iteration.
Also, consider using else if statements so that Fizz or Buzz are only pushed if FizzBuzz has not been pushed. Otherwise, you may find that all three are pushed instead of just FizzBuzz.
var output = [];
var count = 1;
function fizzBuzz() {
if (count % 15 === 0) {
output.push("FizzBuzz");
}
else if (count % 3 === 0) {
output.push("Fizz");
}
else if (count % 5 === 0) {
output.push("Buzz");
}
else {
output.push(count);
}
count++;
};
while(count < 100) {
fizzBuzz();
}
console.log(output)
Try This
var output = [];
function fizzBuzz(i) {
if (i % 3 == 0 && i % 5 == 0) {
output.push("FizzBuzz");
} else if (i % 3 == 0) {
output.push("Fizz");
} else if (i % 5 == 0) {
output.push("Buzz");
} else {
output.push(i)
}
console.log(output)
};
fizzBuzz(15)
var output = [];
var count = 1;
function fizzBuzz() {
if (count % 3 === 0 && count % 5 === 0) {
output.push("FizzBuzz");
}
else if (count % 3 === 0) {
output.push("Fizz");
}
else if (count % 5 === 0) {
output.push("Buzz");
}
else {
output.push(count);
}
count++;
};
while(count < 100) {
fizzBuzz();
}
console.log(output)

How to reduce the number of if

Is there a way to reduce the number of "if" in this code?
function test(input) {
if ((input % 3 == 0) && (input % 5 == 0)) {
return 'fizzbuzz';
} else if (input % 3 == 0) {
return 'fizz';
} else if (input % 5 == 0) {
return 'buzz';
} else {
return '' + input;
}
}
for (var i = 1; i < 100; i++) {
console.log(test(i));
}
You can avoid that by storing the comparison values:
var mod3 = input % 3 == 0;
var mod5 = input % 5 == 0;
... creating a lookup table ...
var outs = [input, "fizz", "buzz", "fizzbuzz"];
... and indexing it ...
return outs[(+mod3) + 2 * (+mod5)];
... no ifs!
You can use the ternary operator:
return ((input%3==0)&&(input%5==0)) ? 'fizz buzz'
: (input%3==0) ? 'fizz'
: (input%5==0) ? 'buzz'
: '' + input;
If you don't want to use if's why not try case syntax?
http://www.w3schools.com/js/js_switch.asp
Alternatively use the JS shorthand for if
so that:
var something;
if (2 + 2 === 4){
something = "Yup!"
} else {
something = "Nope"
}
becomes
var something = 2 + 2 === 4 ? "Yup!" : "Nope";
You can get rid of the first "if" altogether, because 3 and 5 and "fizz" and "buzz" are used in the later ones. You can also wait to return until the end. Something like:
var str = "";
if (input % 3 === 0){
str +="fizz";
}
if (input % 5 === 0 ){
str +="buzz";
} else {
str = input;
}
return str;

Javascript Fizzbuzz Issue

I'm trying to do some simple tests to help further my javascript knowledge (which is quite fresh). Goal 1 is to print numbers from 1-100 that aren't divisible by 5 or 3.
I tried the following:
for (var i = 1; i <= 100; i ++)
{
if (i%3 !== 0 || i%5 !== 0){
console.log(i);
}
}
This logs EVERY number from 1-100, and I can't tell why. Probably the simplest simplest questions here but it's doing my head in!
I think you mean &&, not ||. With ||, you're basically testing to see if the number is not divisible by 3 or by 5 - only if a number is divisible by both do you reject it (in other words, multiples of 15).
The typical answer to FizzBuzz is:
if( i%3 == 0 && i%5 == 0) FizzBuzz
elseif( i % 3 == 0) Fizz
elseif( i % 5 == 0) Buzz
else number
So to get directly to the number you need for i%3==0 to be false AND i%5==0 to be false. Therefore, you want if( i%3 !== 0 && i%5 !== 0)
Here's a quite simple FizzBuzz function that accepts a range of numbers.
function fizzBuzz(from, to) {
for(let i = from; i <= to; i++) {
let msg = ''
if(i % 3 == 0) msg += 'Fizz'
if(i % 5 == 0) msg += 'Buzz'
if(msg.length == 0) msg = i
console.log(msg)
}
}
fizzBuzz(1, 25)
As for a more complex solution, that's one way you could define a higher order function which generates customized FizzBuzz functions (with additional divisors and keywords)
function fizzBuzzFactory(keywords) {
return (from, to) => {
for(let i = from; i <= to; i++) {
let msg = ''
Reflect.ownKeys(keywords).forEach((keyword) => {
let divisor = keywords[keyword]
if(i % divisor == 0) msg += keyword
})
if(msg.length == 0) msg = i
console.log(msg)
}
}
}
// generates a new function
const classicFizzBuzz = fizzBuzzFactory({ Fizz: 3, Buzz: 5 })
// accepts a range of numbers
classicFizzBuzz(1, 25)
const extendedFizzBuzz = fizzBuzzFactory({ Fizz: 3, Buzz: 5, Bazz: 7, Fuzz: 11 })
extendedFizzBuzz(1, 25)
I attacked this the same was as Niet the Dark Absol:
for (var n = 1; n <= 100; n++) {
if (n % 3 == 0 && n % 5 == 0)
console.log("FizzBuzz");
else if (n % 3 == 0)
console.log("Fizz");
else if (n % 5 == 0)
console.log("Buzz");
else
console.log(n);
}
However, you can also do it this way:
for (var n = 1; n <= 100; n++) {
var output = "";
if (n % 3 == 0)
output += "Fizz";
if (n % 5 == 0)
output += "Buzz";
console.log(output || n);
}
One of the hardest parts of learning JavaScript - or any language - for me is understanding solutions can come in many ways. I like the first example more, but it's always good to keep thinking and look at other options.

Categories

Resources