addWithSurcharge exercise alternative answers - javascript

I had this JavaScript exercise from jshero.net:
Write a function addWithSurcharge that adds two amounts with surcharge. For each amount less than or equal to 10, the surcharge is 1. For each amount greater than 10 and less than or equal to 20, the surcharge is 2. For each amount greater than 20, the surcharge is 3. The call addWithSurcharge(10, 30) should return 44.
My solution was :
function addWithSurcharge (a,b){
let myS = a+b
if (myS <10){
return myS +=2} else if (myS >10 && myS <=20){
return myS +=2} else if (myS >20 && myS <30){
return myS +=3} else if (myS >= 30 && myS <40){
return myS +=4} else if(myS >40){
return myS +=5}
}
Somehow it worked, I passed the challenge but I feel like there was an easier way to solve this. Do you know other alternative answers for this exercise?

you could write it as a switch statement. something like this:
function addWithSurcharge (a,b) {
let myS = a+b
switch (true){
case myS < 10:
return myS + 2
case (myS > 10 && myS <= 20):
return myS + 2
case (myS > 20 && myS < 30):
return myS + 3
case (myS >= 30 && myS < 40):
return myS + 4
default:
return myS + 5
}
}

I think you can round to the superior decade and then divide by 10.
I'm surprised you passed the test cause you don't really fit the problem, you forgot every case when equal to 10, 20, 30, ...
By the way, this is my way to answer your problem. With this way it's "infinite" but if you wan't stop adding after 40, just add Math.max(X, (decadeRounded / 10)) where X is your maximum, for example Math.max(5, (decadeRounded / 10))
function addWithSurcharge (a,b) {
let myS = a + b
let decadeRounded = Math.round( (myS/10) ) * 10;
return myS + (decadeRounded / 10);
}
document.getElementById('result').innerHTML = addWithSurcharge(10, 20);
<div id="result"></div>

You can try something like this
function addWithSurcharge(a, b) {
if (a <= 10) {
a += 1
} else if (a > 10 && a <= 20) {
a += 2
} else if (a > 20) {
a += 3
}
if (b <= 10) {
b += 1
} else if (b > 10 && b <= 20) {
b += 2
} else if (b > 20) {
b += 3
}
return a + b;
}

function addWithSurcharge(a, b) {
i = 0;
if (a <= 10) {
i = i + 1;
} else if (a > 10 && a <= 20) {
i = i + 2;
} else if (a > 20) {
i = i + 3;
}
if (b <= 10) {
i = i + 1;
} else if (b > 10 && b <= 20) {
i = i + 2;
} else if (b > 20) {
i = i + 3;
}
return a + b + i;
}

Related

javascript - IF ELSE operators

Learning the basics and had this exercise:
"Write a function addWithSurcharge that adds two amounts with surcharge. For each amount less than or equal to 10, the surcharge is 1. For each amount greater than 10, the surcharge is 2. The call addWithSurcharge(5, 15) should return 23."
I had put:
function addWithSurcharge(num1, num2) {
if (num1 <= 10) {
num1 += 1;
} else {
num1 += 2;
}
if (num2 <= 10) {
num2 += 1;
} else {
num2 += 2;
}
return num1 + num2;
}
Which works, but want to learn better syntax. Could something like
if (num1, num2 <= 10) {...
work? I realize can't do the || operator because it could affect the wrong num.
Put the numbers into an array instead, and iterate over the array so you don't have to repeat both the num1 and num2:
function addWithSurcharge(...nums) {
return nums.reduce((a, num) => {
if (num <= 10) {
num += 1;
} else {
num += 2;
}
return a + num;
}, 0);
}
console.log(addWithSurcharge(5, 15));
Without .reduce, the above is equivalent to:
function addWithSurcharge(...nums) {
nums.forEach((num, i) => {
if (num <= 10) {
nums[i] += 1;
} else {
nums[i] += 2;
}
});
return nums[0] + nums[1];
}
console.log(addWithSurcharge(5, 15));
You can use the conditional operator to make the if/else part more concise without bothering with reassignment, too:
const addWithSurcharge = (...nums) => (
nums.reduce(
(a, num) => a + num + (num <= 10 ? 1 : 2),
0
)
);
console.log(addWithSurcharge(5, 15));
You could also do:
function addWithSurcharge(num1, num2) {
return num1 + num2 + num1<=10?1:2 + num2<=10?1:2;
}
The num1<=10?1:2 basically means if(num1<=10){1} else{2} which works really well!
The most basic improvement is a helper function that you can call twice:
function withSurcharge(num) {
if (num <= 10) return num + 1;
else return num + 2;
}
function addWithSurcharge(num1, num2) {
return withSurcharge(num1) + withSurcharge(num2);
}
You could further shorten the if/else statement to use a conditional expression, but not much is gained by that:
return num + (num <= 10 ? 1 : 2);
One way you could do this would be to use the ternary opertator
function addWithSurcharge(num1,num2)
{
num1 += num1 <= 10 ? 1 : 2;
num2 += num2 <= 10 ? 1 : 2;
return num1 + num2;
}
console.log(addWithSurcharge(10,5));
If you use a ? when assigning a value it'll evaluate whatever is on the left hand side of the ? and either return the left hand side of the : if it's true or the right hand side if it's false.

Similar Javascript and python code does not give same result

I have a problem, I have 2 scripts one is in javascript and one is python.
I want to use python to generate the value so I tried to rewrite javascript code to python
but the output is not the same and I can't seem to figure out what values are incorrect!
Any help is appreciated
I am very bad at javascript, but I have a basic/decent understanding of python.
My javascript Code:
<html><head><script type="text/javascript"><!--
function leastFactor(n) {
if (isNaN(n) || !isFinite(n)) return NaN;
if (typeof phantom !== 'undefined') return 'phantom';
if (typeof module !== 'undefined' && module.exports) return 'node';
if (n==0) return 0;
if (n%1 || n*n<2) return 1;
if (n%2==0) return 2;
if (n%3==0) return 3;
if (n%5==0) return 5;
var m=Math.sqrt(n);
for (var i=7;i<=m;i+=30) {
if (n%i==0) return i;
if (n%(i+4)==0) return i+4;
if (n%(i+6)==0) return i+6;
if (n%(i+10)==0) return i+10;
if (n%(i+12)==0) return i+12;
if (n%(i+16)==0) return i+16;
if (n%(i+22)==0) return i+22;
if (n%(i+24)==0) return i+24;
}
return n;
}
function go() {
var p=2998236216354; var s=1750047503; var n;
if ((s >> 15) & 1)/*
else p-=
*/p+= 80068513*
16; else /*
else p-=
*/p-=
60707526*/*
*13;
*/16;/*
p+= */if ((s >> 7) & 1)/*
else p-=
*/p+=/*
else p-=
*/116987388* 8; else
p-= 172213350*/*
else p-=
*/8;if ((s >> 2) & 1)/*
*13;
*/p+=/*
p+= */54228284*/* 120886108*
*/5;/*
*13;
*/else /*
p+= */p-= 542313502*/* 120886108*
*/3;/*
*13;
*/if ((s >> 10) & 1) p+=66991160*/* 120886108*
*/13;else /*
p+= */p-=
158065083*
11;if ((s >> 2) & 1)/*
else p-=
*/p+=311247981*/*
*13;
*/5;/*
*13;
*/else /*
else p-=
*/p-=
376627923* 3; p-=910005807;
n=leastFactor(p);
{ document.cookie="RNKEY="+n+"*"+p/n+":"+s+":3025753160:1";
}
}
//--></script></head>
<body onload="go()">
Loading ...
</body>
</html>
My Python Code:
import math
def least_factor(n):
if n == 0:
return 0;
if n % 1 or n * n < 2: return 1
if n % 2 == 0: return 2
if n % 3 == 0: return 3
if n % 5 == 0: return 5
m = math.sqrt(n)
for i in range(7, int(m + 1), 30):
if n % i == 0: return i
if n % (i + 4): return i + 4
if n % (i + 6): return i + 6
if n % (i + 10): return i + 10
if n % (i + 12): return i + 12
if n % (i + 16): return i + 16
if n % (i + 22): return i + 22
if n % (i + 24): return i + 24
return n
def go():
p = 2998236216354
s = 1750047503
n = None
if (s >> 15) & 1: p += 80068513 * 16
else: p -= 60707526 * 16
if (s >> 7) & 1: p += 116987388 * 8
else: p -= 172213350 * 8
if (s >> 2) & 1: p += 54228284 * 5
else: p -= 542313502 * 3
if (s >> 10) & 1: p += 66991160 * 13
else: p -= 158065083 * 11
if (s >> 2) & 1: p += 311247981 * 5
else: p -= 376627923 * 3
p -= 910005807
n = least_factor(p)
return f'RNKEY={n}*{p / n}:{s}:3025753160:1'
print(go())
The output on javascript is:
RNKEY=1691507*1771981:1750047503:3025753160:1
But on Python the output is:
RNKEY=11*272483478669.72726:1750047503:3025753160:1
Can someone help me understand where in my python code I am giving the wrong values?
Thanks in advance!
In your Python code, in the for loop, you have a line
if n % (i + 4): return i + 4
This if condition is true if n % (i+4) is not equal to 0, so if n is not divisible by i+4. This is the opposite of what you want, and the opposite of what your JavaScript code does.
It should be, for example,
if not n % (i + 4): return i + 4

Can't get the right result in condition

I can't get theright result, "Weird" on stdin, 18 and 20. Everything looks good to me, however something must be off.
if (N % 2 == 1) {
console.log("Weird");
}
else if ((N % 2 == 0) && (2 >= N <= 5)) {
console.log("Not Weird");
}
else if ((N % 2 == 0) && (5 <= N <= 20)) {
console.log("Weird");
}
else if ((N % 2 == 0) && (N > 20)) {
console.log("Not Weird");
}
else {
console.log("Weird");
}
'use strict';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '';
let currentLine = 0;
process.stdin.on('data', inputStdin => {
inputString += inputStdin;
});
process.stdin.on('end', _ => {
inputString = inputString.replace(/\s*$/, '')
.split('\n')
.map(str => str.replace(/\s*$/, ''));
main();
});
function readLine() {
return inputString[currentLine++];
}
function main() {
const N = parseInt(readLine(), 10);
if (N%2==1) {
console.log("Weird");
}
else if ((N % 2 == 0) && (2 >= N <= 5)) {
console.log("Not Weird");
}
else if ((N % 2 == 0) && (5 <= N && N <= 20)) {
console.log("Weird");
}
else if ((N % 2 == 0) && (N > 20)) {
console.log("Not Weird");
}
else{
console.log("Weird");
}
}
I ve added the whole code. In the main function, in the second else if condition, there seems to be the problem. When n is given 18 or 20, I can not get the right output which should be "Weird"
You can't be doing two conditions in the same time
if (5<=N<=20) {}
Will evaluate 5<=N first which produces either true/false which are when compared to numbers will evaluate to (1/0) respectively. Then the second part ( <= 20) will be evaluated.
Combine two conditions only with AND / OR operators
if (5 <= N && N <= 20) {}
This will solve your problem.

How to 'Pass' on multiple Greater Than Checks

Say you have the number var n = 1,000,000;
I want to check:
n >= 1e3
n >= 1e4
n >= 1e5
n >= 1e6
Doing it exactly as it looks above will cause the statement to return true on the first valid expression, obviously. Which means that it will say n is greater than 1e3 and return the results from there.
How can I get it to instead 'cascade' through the expressions until it hits a false, then use the last statement that was true, without having to go:
if( n >= 1e3 && n >= 1e4 && n >= 1e5 && n >= 1e6 ) {...
You should check the number from the biggest to the smalest:
var n = 1000000;
var r = document.getElementById("result");
if (n >= 1e6) r.innerHTML = "n >= 1e6";
else if (n >= 1e5) r.innerHTML ="n >= 1e5";
else if (n >= 1e4) r.innerHTML ="n >= 1e4";
else if (n >= 1e3) r.innerHTML = "n >= 1e3";
<div id="result"></div>
If you need to have all the diffent sentences, you can do:
var r = document.getElementById("result");
var n = 1000000;
var str = "";
if (n >= 1e6) str += "n >= 1e6 ";
if (n >= 1e5) str += "n >= 1e5 ";
if (n >= 1e4) str += "n >= 1e4 ";
if (n >= 1e3) str += "n >= 1e3 ";
r.innerHTML = str;
<div id="result"></div>
To have something more maintainable and extendable :
var n = 1000000;
var r = document.getElementById("result");
check(n, [1000, 1e4, 1e5, 1e6]);
function check(nb, limits) {
limits.sort(function(a, b){return b-a});
var limitsLength = limits.length;
for (var i =0;i<limitsLength;i++) {
if (nb >= limits[i]) r.innerHTML += "n >= 1e" + Math.log10(limits[i]) + " ";
}
}
<div id="result"></div>
No need for branching.
function yours() {
if (n < 1) return 'n is less than 1e0';
return 'n is greater than 1e' + Math.log10(n);
}
If you must branch (for example if you are actually calculating something more complex than a simple logarithm), add a new function to avoid the "cascading" you mention. The return statements will prevent cascading. The new function defines how much stuff gets skipped.
function yours() {
println(figure(n));
}
function figure(n) {
if (n > 10000) return 'n is greater than 1e4';
if (n > 1000) return 'n is greater than 1e3';
if (n > 100) return 'n is greater than 1e2';
if (n > 10) return 'n is greater than 1e1';
if (n > 1) return 'n is greater than 1e0';
}
I'm using println here as a substitute for whatever you want to do with the result.

FizzBuzz program (details given) in Javascript [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
Can someone please correct this code of mine for FizzBuzz? There seems to be a small mistake. This code below prints all the numbers instead of printing only numbers that are not divisible by 3 or 5.
Write a program that prints the numbers from 1 to 100. But for multiples of three, print "Fizz" instead of the number, and for the multiples of five, print "Buzz". For numbers which are multiples of both three and five, print "FizzBuzz".
function isDivisible(numa, num) {
if (numa % num == 0) {
return true;
} else {
return false;
}
};
function by3(num) {
if (isDivisible(num, 3)) {
console.log("Fizz");
} else {
return false;
}
};
function by5(num) {
if (isDivisible(num, 5)) {
console.log("Buzz");
} else {
return false;
}
};
for (var a=1; a<=100; a++) {
if (by3(a)) {
by3(a);
if (by5(a)) {
by5(a);
console.log("\n");
} else {
console.log("\n");
}
} else if (by5(a)) {
by5(a);
console.log("\n");
} else {
console.log(a+"\n")
}
}
for (let i = 1; i <= 100; i++) {
let out = '';
if (i % 3 === 0) out += 'Fizz';
if (i % 5 === 0) out += 'Buzz';
console.log(out || i);
}
/*Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”*/
var str="",x,y,a;
for (a=1;a<=100;a++)
{
x = a%3 ==0;
y = a%5 ==0;
if(x)
{
str+="fizz"
}
if (y)
{
str+="buzz"
}
if (!(x||y))
{
str+=a;
}
str+="\n"
}
console.log(str);
Your functions return falsy values no matter what, but will print anyway. No need to make this overly complicated.
fiddle: http://jsfiddle.net/ben336/7c9KN/
Was fooling around with FizzBuzz and JavaScript as comparison to C#.
Here's my version, heavily influenced by more rigid languages:
function FizzBuzz(aTarget) {
for (var i = 1; i <= aTarget; i++) {
var result = "";
if (i%3 === 0) result += "Fizz";
if (i%5 === 0) result += "Buzz";
if (result.length ===0) result = i;
console.log(result);
}
}
I like the structure and ease of read.
Now, what Trevor Dixon cleverly did is relay on the false-y values of the language (false , null , undefined , '' (the empty string) , 0 and NaN (Not a Number)) to shorten the code.
Now, the if (result.length ===0) result = i; line is redundant and the code will look like:
function FizzBuzz(aTarget) {
for (var i = 1; i <= aTarget; i++) {
var result = "";
if (i%3 === 0) result += "Fizz";
if (i%5 === 0) result += "Buzz";
console.log(result || i);
}
}
Here we relay on the || operator to say : "if result is false, print the iteration value (i)". Cool trick, and I guess I need to play more with JavaScript in order to assimilate this logic.
You can see other examples (from GitHub) that will range from things like :
for (var i=1; i <= 20; i++)
{
if (i % 15 == 0)
console.log("FizzBuzz");
else if (i % 3 == 0)
console.log("Fizz");
else if (i % 5 == 0)
console.log("Buzz");
else
console.log(i);
}
No variables here, and just check for division by 15,3 & 5 (my above one only divides by 3 & 5, but has an extra variable, so I guess it's down to microbenchmarking for those who care, or style preferences).
To:
for(i=0;i<100;)console.log((++i%3?'':'Fizz')+(i%5?'':'Buzz')||i)
Which does it all in on line, relaying on the fact that 0 is a false value, so you can use that for the if-else shorthanded version (? :), in addition to the || trick we've seen before.
Here's a more readable version of the above, with some variables:
for (var i = 1; i <= 100; i++) {
var f = i % 3 == 0, b = i % 5 == 0;
console.log(f ? b ? "FizzBuzz" : "Fizz" : b ? "Buzz" : i);
}
All in all, you can do it in different ways, and I hope you picked up some nifty tips for use in JavaScript :)
.fizz and .buzz could be CSS classes, no? In which case:
var n = 0;
var b = document.querySelector("output");
window.setInterval(function () {
n++;
b.classList[n%3 ? "remove" : "add"]("fizz");
b.classList[n%5 ? "remove" : "add"]("buzz");
b.textContent = n;
}, 500);
output.fizz:after {
content: " fizz";
color:red;
}
output.buzz:after {
content: " buzz";
color:blue;
}
output.fizz.buzz:after {
content: " fizzbuzz";
color:magenta;
}
<output>0</output>
With ternary operator it is much simple:
for (var i = 0; i <= 100; i++) {
str = (i % 5 == 0 && i % 3 == 0) ? "FizzBuzz" : (i % 3 == 0 ? "Fizz" : (i % 5 == 0) ? "Buzz" : i);
console.log(str);
}
for(i = 1; i < 101; i++) {
if(i % 3 === 0) {
if(i % 5 === 0) {
console.log("FizzBuzz");
}
else {
console.log("Fizz");
}
}
else if(i % 5 === 0) {
console.log("Buzz");
}
else {
console.log(i)
}
}
In your by3 and by5 functions, you implicitly return undefined if it is applicable and false if it's not applicable, but your if statement is testing as if it returned true or false. Return true explicitly if it is applicable so your if statement picks it up.
As an ES6 generator: http://www.es6fiddle.net/i9lhnt2v/
function* FizzBuzz() {
let index = 0;
while (true) {
let value = ''; index++;
if (index % 3 === 0) value += 'Fizz';
if (index % 5 === 0) value += 'Buzz';
yield value || index;
}
}
let fb = FizzBuzz();
for (let index = 0; index < 100; index++) {
console.log(fb.next().value);
}
Codeacademy sprang a FizzBuzz on me tonight. I had a vague memory that it was "a thing" so I did this. Not the best way, perhaps, but different from the above:
var data = {
Fizz:3,
Buzz:5
};
for (var i=1;i<=100;i++) {
var value = '';
for (var k in data) {
value += i%data[k]?'':k;
}
console.log(value?value:i);
}
It relies on data rather than code. I think that if there is an advantage to this approach, it is that you can go FizzBuzzBing 3 5 7 or further without adding additional logic, provided that you assign the object elements in the order your rules specify. For example:
var data = {
Fizz:3,
Buzz:5,
Bing:7,
Boom:11,
Zing:13
};
for (var i=1;i<=1000;i++) {
var value = '';
for (var k in data) {
value += i%data[k]?'':k;
}
console.log(value?value:i);
}
This is what I wrote:
for (var num = 1; num<101; num = num + 1) {
if (num % 5 == 0 && num % 3 == 0) {
console.log("FizzBuzz");
}
else if (num % 5 == 0) {
console.log("Buzz");
}
else if (num % 3 == 0) {
console.log("Fizz");
}
else {
console.log(num);
}
}
for (var i = 1; i <= 100; i++) {
if (i % 3 === 0 && i % 5 === 0) console.log("FizzBuzz");
else if (i%3 === 0) console.log("Fizz");
else if (i%5 === 0) console.log("Buzz");
else console.log(i);
}
One of the easiest way to FizzBuzz.
Multiple of 3 and 5, at the same time, means multiple of 15.
Second version:
for (var i = 1; i <= 100; i++) {
if (i % 15 === 0) console.log("FizzBuzz");
else if (i%3 === 0) console.log("Fizz");
else if (i%5 === 0) console.log("Buzz");
else console.log(i);
}
In case someone is looking for other solutions: This one is a pure, recursive, and reusable function with optionally customizable parameter values:
const fizzBuzz = (from = 1, till = 100, ruleMap = {
3: "Fizz",
5: "Buzz",
}) => from > till || console.log(
Object.keys(ruleMap)
.filter(number => from % number === 0)
.map(number => ruleMap[number]).join("") || from
) || fizzBuzz(from + 1, till, ruleMap);
// Usage:
fizzBuzz(/*Default values*/);
The from > till is the anchor to break the recursion. Since it returns false until from is higher than till, it goes to the next statement (console.log):
Object.keys returns an array of object properties in the given ruleMap which are 3 and 5 by default in our case.
Then, it iterates through the numbers and returns only those which are divisible by the from (0 as rest).
Then, it iterates through the filtered numbers and outputs the saying according to the rule.
If, however, the filter method returned an empty array ([], no results found), it outputs just the current from value because the join method at the end finally returns just an empty string ("") which is a falsy value.
Since console.log always returns undefined, it goes to the next statement and calls itself again incrementing the from value by 1.
A Functional version of FizzBuzz
const dot = (a,b) => x => a(b(x));
const id = x => x;
function fizzbuzz(n){
const f = (N, m) => n % N ? id : x => _ => m + x('');
return dot(f(3, 'fizz'), f(5, 'buzz')) (id) (n);
}
for more options in the above replace dot with dots as below
const dots = (...a) => f0 => a.reduceRight((acc, f) => f(acc), f0);
function fizzbuzz(n){
const f = (N, m) => n % N ? id : x => _ => m + x('');
return dots(f(3, 'fizz'), f(5, 'buzz'), f(7, 'bam')) (id) (n);
}
Reference: FizzBuzz in Haskell by Embedding a Domain-Specific Language
by Maciej Piro ́g
for (i=1; i<=100; i++) {
output = "";
if (i%5==0) output = "buzz";
if (i%3==0) output = "fizz" + output;
if (output=="") output = i;
console.log(output);
}
Functional style! JSBin Demo
// create a iterable array with a length of 100
// and map every value to a random number from 1 to a 100
var series = Array.apply(null, Array(100)).map(function() {
return Math.round(Math.random() * 100) + 1;
});
// define the fizzbuzz function which takes an interger as input
// it evaluates the case expressions similar to Haskell's guards
var fizzbuzz = function (item) {
switch (true) {
case item % 15 === 0:
console.log('fizzbuzz');
break;
case item % 3 === 0:
console.log('fizz');
break;
case item % 5 === 0:
console.log('buzz');
break;
default:
console.log(item);
break;
}
};
// map the series values to the fizzbuzz function
series.map(fizzbuzz);
Another solution, avoiding excess divisions and eliminating excess spaces between "Fizz" and "Buzz":
var num = 1;
var FIZZ = 3; // why not make this easily modded?
var BUZZ = 5; // ditto
var UPTO = 100; // ditto
// and easily extended to other effervescent sounds
while (num < UPTO)
{
var flag = false;
if (num % FIZZ == 0) { document.write ("Fizz"); flag = true; }
if (num % BUZZ == 0) { document.write ("Buzz"); flag = true; }
if (flag == false) { document.write (num); }
document.write ("<br>");
num += 1;
}
If you're using using jscript/jsc/.net, use Console.Write(). If you're using using Node.js, use process.stdout.write(). Unfortunately, console.log() appends newlines and ignores backspaces, so it's unusable for this purpose. You could also probably append to a string and print it. (I'm a complete n00b, but I think (ok, hope) I've been reasonably thorough.)
"Whaddya think, sirs?"
check this out!
function fizzBuzz(){
for(var i=1; i<=100; i++){
if(i % 3 ===0 && i % 5===0){
console.log(i+' fizzBuzz');
} else if(i % 3 ===0){
console.log(i+' fizz');
} else if(i % 5 ===0){
console.log(i+' buzz');
} else {
console.log(i);
}
}
}fizzBuzz();
Slightly different implementation.
You can put your own argument into the function. Can be non-sequential numbers like [0, 3, 10, 1, 4]. The default set is only from 1-15.
function fizzbuzz (set) {
var set = set ? set : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
var isValidSet = set.map((element) => {if (typeof element !== 'number') {return false} else return true}).indexOf(false) === -1 ? true : false
var gotFizz = (n) => {if (n % 3 === 0) {return true} else return false}
var gotBuzz = (n) => {if (n % 5 === 0) {return true} else return false}
if (!Array.isArray(set)) return new Error('First argument must an array with "Number" elements')
if (!isValidSet) return new Error('The elements of the first argument must all be "Numbers"')
set.forEach((n) => {
if (gotFizz(n) && gotBuzz(n)) return console.log('fizzbuzz')
if (gotFizz(n)) return console.log('fizz')
if (gotBuzz(n)) return console.log('buzz')
else return console.log(n)
})
}
var num = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];
var runLoop = function() {
for (var i = 1; i<=num.length; i++) {
if (i % 5 === 0 && i % 3 === 0) {
console.log("FizzBuzz");
}
else if (i % 5 === 0) {
console.log("Buzz");
}
else if (i % 3 === 0) {
console.log("Fizz");
}
else {
console.log(i);
}
}
};
runLoop();
Just want to share my way to solve this
for (i = 1; i <= 100; i++){
if (i % 3 === 0 && i % 5 === 0) {
console.log('fizzBuzz');
} else if (i % 3 === 0) {
console.log('fizz');
} else if (i % 5 === 0){
console.log('buzz');
} else {
console.log(i);
}
}
var limit = prompt("Enter the number limit");
var n = parseInt(limit);
var series = 0;
for(i=1;i<n;i++){
series = series+" " +check();
}
function check() {
var result;
if (i%3==0 && i%5==0) { // check whether the number is divisible by both 3 and 5
result = "fizzbuzz "; // if so, return fizzbuzz
return result;
}
else if (i%3==0) { // check whether the number is divisible by 3
result = "fizz "; // if so, return fizz
return result;
}
else if (i%5==0) { // check whether the number is divisible by 5
result = "buzz "; // if so, return buzz
return result;
}
else return i; // if all the above conditions fail, then return the number as it is
}
alert(series);
Thats How i did it :
Not the best code but that did the trick
var numbers = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];
for(var i = 0 ; i <= 19 ; i++){
var fizz = numbers[i] % 3 === 0;
var buzz = numbers[i] % 5 === 0;
var fizzBuzz = numbers[i] % 5 === 0 && numbers[i] % 3 === 0;
if(fizzBuzz){
console.log("FizzBuzz");
} else if(fizz){
console.log("Fizz");
} else if(buzz){
console.log("Buzz");
} else {
console.log(numbers[i]);
}
}
As much as this is easy logic it can be a daunting task for beginners. Below is my solution to the FizzBuzz problem:
let i = 1;
while(i<=100){
if(i % 3 ==0 && i % 5 == 0){
console.log('FizzBuzz');
}
else if(i % 3 == 0){
console.log('Fizz');
}
else if(i % 5 == 0){
console.log('Buzz');
}
else{
console.log(i);
}
i++;
}
considering performance and readability, please find my take on this problem
way 1: instead of doing a math modules operation in an if loop, which results in performing 3 times taking it a step above reduces the overhead
function fizzBuzz(n) {
let count =0;
let x = 0;
let y = 0;
while(n!==count)
{
count++;
x = count%3;
y = count%5;
if(x === 0 && y ===0)
{
console.log("fizzbuzz");
}
else if(x === 0)
{
console.log("fizz");
}
else if(y === 0)
{
console.log("buzz");
}
else
{
console.log(count);
}
}
}
fizzBuzz(15);
way 2: condensing the solution
function fizzBuzz(n) {
let x = 0;
let y = 0;
for (var i = 1; i <= n; i++) {
var result = "";
x = i%3;
y = i%5;
if (x === 0 && y === 0) result += "fizzbuzz";
else if (x === 0) result += "fizz";
else if (y === 0) result += "buzz";
console.log(result || i);
}
}
fizzBuzz(5)
Here's my favorite solution. Succinct, functional & fast.
const oneToOneHundred = Array.from({ length: 100 }, (_, i) => i + 1);
const fizzBuzz = (n) => {
if (n % 15 === 0) return 'FizzBuzz';
if (n % 3 === 0) return 'Fizz';
if (n % 5 === 0) return 'Buzz';
return n;
};
console.log(oneToOneHundred.map((i) => fizzBuzz(i)).join('\n'));
function fizzBuzz(n) {
for (let i = 1; i < n + 1; i++) {
if (i % 15 == 0) {
console.log("fizzbuzz");
} else if (i % 3 == 0) {
console.log("fizz");
} else if (i % 5 == 0) {
console.log("buzz");
} else {
console.log(i);
}
}
}
fizzBuzz(15);
Different functional style -- naive
fbRule = function(x,y,f,b,z){return function(z){return (z % (x*y) == 0 ? f+b: (z % x == 0 ? f : (z % y == 0 ? b: z))) }}
range = function(n){return Array.apply(null, Array(n)).map(function (_, i) {return i+1;});}
range(100).map(fbRule(3,5, "fizz", "buzz"))
or, to incorporate structures as in above example: ie [[3, "fizz"],[5, "buzz"], ...]
fbRule = function(fbArr,z){
return function(z){
var ed = fbArr.reduce(function(sum, unit){return z%unit[0] === 0 ? sum.concat(unit[1]) : sum }, [] )
return ed.length>0 ? ed.join("") : z
}
}
range = function(n){return Array.apply(null, Array(n)).map(function (_, i) {return i+1;});}
range(100).map(fbRule([[3, "fizz"],[5, "buzz"]]))
OR, use ramda [from https://codereview.stackexchange.com/questions/108449/fizzbuzz-in-javascript-using-ramda ]
var divisibleBy = R.curry(R.compose(R.equals(0), R.flip(R.modulo)))
var fizzbuzz = R.map(R.cond([
[R.both(divisibleBy(3), divisibleBy(5)), R.always('FizzBuzz')],
[divisibleBy(3), R.aklways('Fizz')],
[divisibleBy(5), R.always('Buzz')],
[R.T, R.identity]
]));
console.log(fizzbuzz(R.range(1,101)))

Categories