javascript for (i = 0; i < XXX.length; i++) -> length question - javascript

for (m = 0; m < troopsCount.length; m++) {
//FM_log(7,"i="+i+" m="+m);
//FM_log(7,"tipoTropaPrioritaria[m] = "+tipoTropaPrioritaria[m]);
//FM_log(7,"troopsCount[m] = "+troopsCount[m]);
//FM_log(7,"availableTroops[m] = "+availableTroops[m]);
if ((tipoTropaPrioritaria[m] == null || tipoTropaPrioritaria[m] == "undefined")
|| (troopsCount[m] == null || troopsCount[m] == "undefined") ||
(availableTroops[m] == null || availableTroops[m] == "undefined"))
return "alternaTropas(): ERRO - tipoTropaPrioritaria[m] || troopsCount[m] || availableTroops[m] null ou undefined";
if ((parseInt(tipoTropaPrioritaria[m]) != 0) && (parseInt(troopsCount[m]) != 0)) {
naoServe = true;
break;
}
else {
if ((parseInt(availableTroops[m])) < (parseInt(troopsCount[m]))) {
naoServe = true;
break;
}
else if (m < troopsCount.length) {
naoServe = true;
}
else { //means m >= troopsCount.length
naoServe = false;
}
}
}
my question is: the last statement
else { //means m >= troopsCount.length
naoServe = false;
}
will it ever be evaluated since
for (m = 0; m < troopsCount.length; m++)
???

No, it won't be executed, assuming that m and troopsCount aren't modified in the loop itself (which in this example they don't seem to be).
As I believe you're pointing out, the loop's conditional would prevent the loop from running again if m were greater than or equal to troopsCount.length at the start of the loop.

Nope. It should never happen.
The loop stops immediately once m < troopsCount.length is false. As such, m >= troopsCount.length will never be true inside the loop, unless you change its value inside the loop itself (which you don't, in this sample).

No. The loop is only evaluated as long as m < troopsCount.length. So m will never be >= troopsCount.length as long as you don't modify m or troopsCount.length inside the loop.

let´s assume troopsCount.length = 10
when m = 9 it will execute all the code in the loop right, but when m = 10 it won´t execute anything.
so if I change it this way:
else {
if ((parseInt(availableTroops[m])) < (parseInt(troopsCount[m]))) {
naoServe = true;
break;
}
else if (m < (troopsCount.length - 1)) { // troopsCount.length - 1 = 9, m < 9 = m from 0 to 8
naoServe = true;
}
else { // troopsCount.length = 9
naoServe = false;
}
}
}
it would work, right?

Related

What is wrong with my recursive function?

This recursive function works perfectly when u and v are hardcoded numbers but the moment I subsitute them with letters it stops working and I don't get what the problem is.
function findPath(x,y,u,v) {
if(x < 1 || x > n || y < 1 || y > n) return false;
if(u < 1 || u > n || v < 1 || v > n) return false;
if(x == u && y == v) {
arr[u][v].className = 'marked';
return true;
}
if(arr[x][y].className != 'path')
return false;
else {
arr[x][y].className = 'marked';
if(findPath(x-1,y)) return true;
if(findPath(x+1,y)) return true;
if(findPath(x,y+1)) return true;
if(findPath(x,y-1)) return true;
}
arr[x][y].className = 'path';
}
drawGrid(n);
findPath(1,1,7,4);

Validate hexadecimal color without using RegEx

I am figuring out how to validate hexadecimal color ("#1234a6" and "#1cf") without using regExp. Can anyone please tell me why my code is not working properly
function checkHex(input)
{
var i, code, len;
// If first letter isn't "#" stop executing
if(input.charAt(0) !== "#") return false;
code = input.charCodeAt(i);
for(i = 1; len = input.length, i < len; i++) {
if(len == 3 || len == 6 ) {
if((code > 47 && code < 58) && (code > 96 && code < 103)) {
return true;
}
}
return false;
}
}
checkHex("#1234a6"); // returns false; which should be true;
Thank you.
No loop or charcodeat required
function checkHex(input) {
var check, code, len;
if(typeof input == 'string') { // check it's a string
if(input[0] === "#") { // and it starts with #
len = input.length;
// if (len === 4 || len === 7 || len == 5 || len == 9) { // 5 and 9 for #RGBA and #RRGGBBAA
if (len === 4 || len === 7) { // and it's 4 or 7 characters
input = input.toLowerCase(); // convert to lower case
// parse it as hex and output as hex with # prefix
check = '#' + ('00000000' + parseInt(input.substr(1), 16).toString(16)).substr(1 - len);
// check it's the same number
return check === input;
}
}
}
// all other conditions fall thru to here
return false;
}
console.log(checkHex("#1234a6")); // true
console.log(checkHex("1234a6")); // false
console.log(checkHex("#1234")); // false
console.log(checkHex("#12345t")); // false
console.log(checkHex("#aBc")); // true
console.log(checkHex("#000")); // true
console.log(checkHex("#00001")); // false
console.log(checkHex("#000001")); // true
Let me break down the check = line into it's constituent parts
check = '#' + // start with a '#'
('00000000' + // some leading zeros for profit
parseInt(input.substr(1), 16) // parse the text as a HEX integer - that's the 16 argument
.toString(16) // now, back to a string, in HEX, again 16 argument does that
).substr(1 - len); // we take the last (len-1) characters to match the input length less 1 (the # is the first line)
To break down where your code went wrong
function checkHex(input) {
var i, code, len;
// If first letter isn't "#" stop executing
if(input.charAt(0) !== "#") return false;
// next line should be inside the loop
code = input.charCodeAt(i);
for(i = 1; len = input.length, i < len; i++) {
// you should check for length being 4 or 7, and this check should be outside the loop
if(len == 3 || len == 6 ) {
// a value can not be between 47 and 48 AND between 96 and 103 - so this is never true
if((code > 47 && code < 58) && (code > 96 && code < 103)) {
// returning in a for loop exits the function, so even fixing all of the above this would return true if the first digit was valid
return true;
}
}
return false;
}
}
to do the above loop correctly
function checkHex(input) {
var i, code, len;
if (input[0] === "#") {
len = input.length
if (len == 4 || len == 7 ) {
input = input.toLowerCase(); // rgb hex values are valid in either upper or lower case
for(i = 1; i < len; i++) {
code = input.charCodeAt(i);
// note the ! and the || in the next line
// we want to check that the digit is NOT in 0123456789 OR abcdef
if (!((code > 47 && code < 58) || (code > 96 && code < 103))) {
return false; // not a hex digit, so return false
}
}
//loop has made it all the way through, so it's correct
return true;
}
}
return false;
}
console.log(checkHex("#1234a6")); // true
console.log(checkHex("1234a6")); // false
console.log(checkHex("#1234")); // false
console.log(checkHex("#12345t")); // false
console.log(checkHex("#aBc")); // true
console.log(checkHex("#000")); // true
console.log(checkHex("#00001")); // false
console.log(checkHex("#000001")); // true
Okay so here's a simple code snippet that does that correctly without loops etc.
You'll notice that I created a lambda function in there to deal with s starting with a #
This is to allow you to expand the notion to deal with specifications like rgb(1,2,3) and rgba(4, 5, 6, 1) etc.
isRGB = function(s) {
if(typeof(s) !== "string")
return false;
if(s[0] === '#')
return (function(hexStr) {
if(hexStr.length != 3 && hexStr.length != 6)
return false;
return !isNaN(Number("0x" + hexStr));
})(s.substr(1));
return false;
}
console.log(isRGB('#01a5'));
console.log(isRGB('#0a5'));
console.log(isRGB('#0a5029'));
You may directly parse the value to number and check against the base 10 integer value:
function checkHex(input) {
/*
1193126 = 0x1234a6
463 = 0x1cf
1166591 = 0x11ccff
*/
if(input.charAt(0) == '#') {
var intNumber = Number(input.replace("#","0x"));
return isNaN(intNumber) ? false : (intNumber == 1193126 || intNumber == 463 || intNumber == 1166591);
} else {
return false;
}
}

Third if-clause can't be reached

This probably has an easy solution, but I simply don't see it at the moment.
I have three if-clauses that ashould be activated based on the length of an array. The first two ones seem to work fine, but for some odd reason I can't activate the third one (arr.length === 3). Right before the if clauses I have tried an alert to test whether it gives the right length of the array and it does.
function calculateDistances() {
var arr = [];
arr.push(posM, posL, posR);
alert(arr[1])
for (var i = 0; i < arr.length; i++) {
if (!arr[i]) {
arr.splice(i,1)
}
}
alert(arr.length)
if (arr.length === 0 || 1) {
return true;
}
else if (arr.length === 2 ) {
var diameter = calculateDiameter(arr[0], arr[1])
if (diameter > minDistance) {
return false;
}
else {
return true;
}
}
else if (arr.length === 3) {
alert("hello")
var diameter1 = calculateDiameter(arr[0], arr[1]);
var diameter2 = calculateDiameter(arr[0], arr[2]);
var diameter3 = calculateDiameter(arr[1], arr[3]);
if (diameter1 && diameter2 && diameter3 < minDistance) {
return true
}
else{
return false
}
}
}
Nor can you activate the second.
There's a bug here: if (arr.length === 0 || 1) {
The 1 casts to true.
Perhaps you meant: if (arr.length === 0 || arr.length === 1) {
You need this:
if (arr.length === 0 || arr.length === 1) {
The way you put it, it is equal to
if ((arr.length === 0) || true) {
which is always true.
I think what you are looking for is below condition in the first if condition
if (arr.length === 0 || arr.length === 1) {
return true;
}
this checks whether the length of the array is 1 or it's 0. Your first if condition is always true as it has 1 which is true.
(arr.length === 0 || 1)
is always true.
You could usethis instead
if (arr.length <= 1)
{
return true;
}

Counting number of holes in a number

I'm trying to figure out how to count the number of "holes" in a number. That is, where 8 has two holes and 0, 4, 6, 9 have one hole and the rest have none.
For some reason I'm getting a return of undefined and I'm pulling my hair out over it. Am I missing something?
var numOfHoles = 0;
for (i = 0; i < num.length; i++) {
if (num === 8) {
numOfHoles += 2;
}
else if (num === 0 || num === 4 || num === 6 || num === 9) {
numOfHoles++;
}
else
numOfHoles;
}
console.log(numOfHoles);
}
Simply take the number, split it into an array of ints, and then use an arrow function as the argument for reduce to total the correlating value from the number to holes map.
function numHoles(n){
return (""+n).split('').reduce((t,i) => t+=+"1000101021"[i],0);
}
document.write(numHoles(48488621597));
I guess you are looking for something like this :
var num = [9,4,5];
var numOfHoles = 0;
for (i = 0; i < num.length; i++){
if (num[i] == 8)
{
numOfHoles += 2;
}
else if (num[i]== 0 || num[i]== 4 || num[i]== 6 || num[i]== 9)
{
numOfHoles++;
}
}
console.log(numOfHoles);
You had multiple little error.
First of all you didn't need else { numOfHoles } which dont mean anything.
And you need if you try to check every elements to use the indexation of the element so you need to use num[i].
Unless there was some code missing from the top when you copied this over, it looks like you need to either remove the trailing bracket or declare this as a function (see below).
Edit: This is a strange question. Firstly, the answers referencing using an index on num might not work as expected. The easiest, but possibly not best, answer would be to convert the number to a string, then index and compare to characters instead of numbers.
As everyone else has mentioned, it makes things much easier if you maintain proper code format :)
function countNumHoles(num) {
var numOfHoles = 0;
var numStr = num.toString();
for (i = 0; i < num.toString().length; i++) {
if (numStr[i] === '8') {
numOfHoles += 2;
} else if (numStr[i] === '0' || numStr[i] === '4' || numStr[i] === '6' || numStr[i] === '9') {
numOfHoles++;
}
}
console.log(numOfHoles);
}
The problem is that you idented wrongly the code, so it's harder to see the errors. The correct identation of your code goes like this:
var numOfHoles = 0;
for (i = 0; i < num.length; i++) {
if (num === 8) {
numOfHoles += 2;
} else if (num === 0 || num === 4 || num === 6 || num === 9) {
numOfHoles++;
} else
numOfHoles;
console.log(numOfHoles);
}
So now with the correct identation you can easily see that else numOfHoles; isn't needed, num ins't defined and length is for string or arrays. Also console.log is better outside the loop in order to run only once. Here is a functional version:
var numOfHoles = 0;
limit = 5;
for (num = 0; num <= limit; num++) {
if (num === 8) {
numOfHoles += 2;
} else if (num === 0 || num === 4 || num === 6 || num === 9)
numOfHoles++;
}
console.log(numOfHoles);
Considering all the answers on top, you have some mistakes with braces. But you are counting num of holes in array, but you don't have indexes. Here is my test snippet. And it has nothing to do with empty numOfHoles. But i still recommend to remove it.
var numOfHoles = 0;
var num = [4,0,9,8,5,5,5];
for (i = 0; i < num.length; i++) {
if (num[i] === 8) {
numOfHoles += 2;
}
else if (num[i] === 0 || num[i] === 4 || num[i] === 6 || num[i] === 9) {
numOfHoles++;
}
else
numOfHoles;
}
console.log(numOfHoles);
It's kind of hard to answer. You used the length property in the variable "num". But strictly used the comparison. The rule if always be false, considering that (string "8" !== 8). This type of comparison requires that the variables have the same type.In this case or you use an integer or an Array and uses the variable i to access your elements in the loop for
Solution, or you comes in as a string and uses the following system [if (num === "8")], or working on becoming a int, or work with an array (recommended). To know the best solution we needed to see more of the code.
Your code should stay that way. Of course, if you need something more specific, let us know
var num = [0,2,8,5];
var numOfHoles = 0;
for (i = 0; i < num.length; i++){
if (num[i] == 8)
{
numOfHoles += 2;
}
else if (num[i]== 0 || num[i]== 4 || num[i]== 6 || num[i]== 9)
{
numOfHoles++;
}
}
console.log(numOfHoles);

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