Why does method return 0? - javascript

Using the object and methods below, why does console.log(FizzBuzzPlus.getFizzBuzzCount(20)) print 0?
var FizzBuzzPlus = {
isFizzBuzzie: function(a) {
if(a%5 === 0 || a%3 === 0) {
if (a%5 === 0 && a%3 === 0) {
return false;
}
return true;
} else {
return false;
}
},
isFizzBuzzieChecker: function(c) {
var theFizzBuzzes = [];
for (var i = 0; i < c; i++) {
if (this.isFizzBuzzie(i)) {
theFizzBuzzes += i + " ";
}
}
return theFizzBuzzes;
},
getFizzBuzzSum: function(b) {
var sum = 0;
for (var i = 0; i < b; i++) {
if (this.isFizzBuzzie(i)) {
sum += i;
}
}
return sum;
},
getFizzBuzzCount: function(c) {
var count = 0;
for (var i = 0; i < c; i++) {
if (this.isFizzBuzzie(i)) {
count++;
}
return count;
}
}
};
console.log(FizzBuzzPlus.isFizzBuzzieChecker(20));
console.log(FizzBuzzPlus.getFizzBuzzSum(20));
console.log(FizzBuzzPlus.getFizzBuzzCount(20));
Some may recognize that this is FizzBuzz from Codecademy. I'm playing with the object using their online JavaScript editor. The printed result of the method is always 0. It should be returning the amount of numbers between 0 and 20 that are divisible by 3 or 5, but not both 3 and 5.

At this point in your code you have your return statement inside your for loop:
getFizzBuzzCount: function(c) {
var count = 0;
for (var i = 0; i < c; i++) {
if (this.isFizzBuzzie(i)) {
count++;
}
return count; //<-- this return is INSIDE the for loop
}
}
Move that return outside the for loop:
getFizzBuzzCount: function(c) {
var count = 0;
for (var i = 0; i < c; i++) {
if (this.isFizzBuzzie(i)) {
count++;
}
}
return count;
}
Fiddle:http://jsfiddle.net/hVf9n/

You have the return statement inside the for loop, also there is a syntax error in isFizzBuzzieChecker, where the closing ) is missing in the if condition
getFizzBuzzCount: function(c) {
var count = 0;
for (var i = 0; i < c; i++) {
if (this.isFizzBuzzie(i)) {
count++;
}
}
return count;
}
Demo: Fiddle

Related

When i pass 1 into n i do not get [0,1] i get [1]?

This is Fibonacci Generator function that i have created but for some reason i can't seem to get the output for 1 = [0,1] . While it works alright for other conditions.If somebody can point me at what i am doing wrong here.
function bl(n) {
var output = [];
var firstNo = 0;
var secondNo = 1;
if (n === 0) {
output.push(0);
}
if (n === 1) {
output.push(0);
output.push(1);
} else {
for (var i = 0; i < n; i++) {
var sum = firstNo + secondNo;
firstNo = secondNo;
secondNo = sum;
output.push(sum);
}
return output;
}
}
console.log(bl(1));
return output had to be executed for all conditions so just execute it at end of your function.
function bl(n) {
var output = [];
var firstNo = 0;
var secondNo = 1;
if (n === 0) {
output.push(0);
}
if (n === 1) {
output.push(0);
output.push(1);
} else {
for (var i = 0; i < n; i++) {
var sum = firstNo + secondNo;
firstNo = secondNo;
secondNo = sum;
output.push(sum);
}
}
return output;
}
console.log(bl(1));

pathfinding in a 2d matrix using js

hey I have been trying this problem from the past few hours. i just can't get 10 random test cases right out of 100
it would be great if anyone would help me out
problem - https://www.codewars.com/kata/59604925a68b04598e00001e/train/javascript
ps there might be better way to solve the problem I just went with whatever came up in my mind.
code-
function conquerIsland(map) {
let path=[];
let mar=[];
let len=0,len1=0;
for(let i=1;i<8;i++)
{
for( let j=0;j<i;j++)
{
if(map[j][i]=='u')
{
if(len1===0 || len1==i+j)
{
path.push([j,i]);
len1=i+j;
}
}
if(map[i][j]=='u')
{
if(len1===0 || len1==i+j)
{
path.push([i,j]);
len1=i+j;
}
}
if(map[j][i]=='m')
{
if(len==0 || len==i+j)
{
mar.push([j,i]);
len=i+i;
}
}
if(map[i][j]=='m')
{
if(len==0 || len==i+j){
mar.push([i,j]);
len=i+j;
}
}
}
if(map[i][i]=='m')
{
if(len==0 || len==i+i)
{
mar.push([i,i]);
len=i+i;
}
}
if(map[i][i]=='u')
{
if(len1==0 || len1==i+i)
{
path.push([i,i]);
len1=i*2;
}
}
}
if(path.length>0)
{
if(path.length==1)
{ let path1;
path1 = [].concat.apply([], path);
return path1;
}
else
{
path.sort(sortFunction);
function sortFunction(a, b) {
if (a[0] === b[0]) {
return 0;
}
else {
return (a[0] < b[0]) ? -1 : 1;
}
}
return path;
}
}
else
if(mar!=[])
{
if(mar.length==1)
{ let mar1;
mar1 = [].concat.apply([], mar);
return mar1;
}
else
{
mar.sort(sortFunction);
function sortFunction(a, b) {
if (a[0] === b[0]) {
return 0;
}
else {
return (a[0] < b[0]) ? -1 : 1;
}
}
return mar;
}
}
else {
return [];
}
}
Please refer to the following code (hopefully the comments are enough, if you're still confused feel free to ask):
function conquerIsland(map) {
// a list of all the us
var us = [];
// a list of all the ms
var ms = [];
// our position
var pos;
for (var i = 0; i < map.length; i ++) {
for (var j = 0; j < map.length; j ++) {
if (map[i][j] == "u") {
// found a u: push to us
us.push([i, j]);
} else if (map[i][j] == "m") {
// found an m: push to ms
ms.push([i, j]);
} else if (map[i][j] == "p") {
// found ourselves: update our position
pos = [i, j];
}
}
}
// figure out which array to search from
var search;
if (us.length > 0) {
search = us;
} else if (ms.length > 0) {
search = ms;
} else {
// no us or ms, return empty array
return [];
}
var mindist = Infinity;
var coords = [];
for (var i = 0; i < search.length; i ++) {
// manhattan distance since no diagonals
var dist = search[i][0] - pos[0] + search[i][1] - pos[1];
if (dist == mindist) {
// multiple things tied for shortest distance
coords.push(search[i]);
} else if (dist < mindist) {
// new shortest distance, reset array
mindist = dist;
coords = [search[i]];
}
}
if (coords.length == 1) {
return coords[0];
}
return coords.sort(function(a, b) {
// this basically accomplishes the sort they want
for (var i = 0; i <= 1; i ++) {
if (a[i] > b[i]) {
return -1;
}
if (b[i] > a[i]) {
return 1;
}
}
return 0;
});
}

How to make this function print 10 prime numbers instead of numbers between 2 to 10

It currently prints numbers between 2 and 10.
I tried it with while(n) loop but it doesn't work. https://jsfiddle.net/xv2qjkm8/6/
function prime(n) {
for (var i = 2; i < n; i++) {
if (isPrime(i)) {
document.write(i + " ");
}
}
}
prime(10);
function isPrime(k) {
for (var i = 2; i < k; i++) {
if (k % i == 0) {
return false;
}
}
return true;
}
You need to count how many primes you have found, so use the while(n) but do not forget to decrease it only when a prime is found.
function prime(n) {
var i = 2;
while (n) {
if (isPrime(i)) {
document.write(i + " ");
n--;
}
i++;
}
}
prime(10);
function isPrime(k) {
for (var i = 2; i < k; i++) {
if (k % i == 0) {
return false;
}
}
return true;
}
Here you go the loop whill run while n is true(0 is false) and everytime we find a prime we decrement n
function prime(n) {
for (var i = 2;n; i++) {
if (isPrime(i)) {
document.write(i + " ");
n--;
}
}
}
function isPrime(k) {
for (var i = 2; i < k; i++) {
if (k % i == 0) {
return false;
}
}
return true;
}
prime(10);
You can you use a tactic like this to both write to the document and check for how many numbers have been found by making a separate function
function print_primes(array, size) => {
if (array.length == size) { document.write(array.join(" ")); return true; }
return false;
}
function prime(n) {
let array = [];
let i = 1;
while (print_primes(array,n) == false) {
while (isPrime(i) == false) {
i++;
}
array.push(i);
}
}
function isPrime(k) {
for (var i = 2; i < k; i++) {
if (k % i == 0) {
return false;
}
}
return true;
}
prĂ­me(10);

Check password strength against an API value

I get my password spec from an API which then I split the object into the needed fields and check that I have the required number of lower, upper, special and length of my password.
function isStrong(passwordChecker) {
if (!passwordChecker) {
return false;
}
debugger;
var securityOption = JSON.parse(localStorage.getItem("Security"));
var MinLength = securityOption.PasswordMinRequiredLength;
var SpecialChars = securityOption.PasswordMinRequiredNonalphanumericCharacters;
var MinLowercase = securityOption.PasswordMinRequiredLowercase;
var MinUppercase = securityOption.PasswordMinRequiredUppercase;
//LenghtCheck
if (passwordChecker.length < MinLength);
return false;
if (!CountSpecialChars(passwordChecker) > SpecialChars) {
return false;
}
if (MinLowercase > 0) {
if (!CountLowerCase(passwordChecker) > MinLowercase) {
return false;
}
}
if (MinUppercase > 0) {
if (!CountUpperCase(passwordChecker) > MinLowercase) {
return false;
}
}
}
function CountSpecialChars(text) {
var Count = 0;
for (var i = 0; i < text.length; i++) {
var c = text[i];
if (text[i] >= 33 && text[i] <= 63){
Count++;
}
}
}
function MinLowercase(text) {
var Count = 0;
for (var i = 0; i < text.length; i++) {
var c = text[i];
if (text[i] >= 97 && text[i] <= 122) {
Count++;
}
}
}
function MinUppercase(text) {
var Count = 0;
for (var i = 0; i < text.length; i++) {
var c = text[i];
if (text[i] >= 65 && text[i] <= 90) {
Count++;
}
}
}
Now what I want to do is, check the different conditions as a whole and if all of the conditions are true then change the class to green..
$(pageId + ' #password').bind('keyup', function () {
var currentpassword = $(pageId + ' #password').val();
if (isStrong(currentpassword)) {
$(pageId + ' #password').addClass('green');
} else {
$(pageId + ' #password').addClass('red');
}
});
I am not sure how to check the conditions as a whole and return an overall true because as I start trying in my password it instantly changes to green as in my password spec you do not need any UpperCase or LowerCase letters so on any input of a char it returns true..
You should refactor your functions so that they accept both the string and the parameter and return true or false. For example:
function CountSpecialChars(text) {
var Count = 0;
for (var i = 0; i < text.length; i++) {
var c = text[i];
if (text[i] >= 33 && text[i] <= 63){
Count++;
}
}
}
if (!CountSpecialChars(passwordChecker) > SpecialChars) {
return false;
}
Should instead be:
function CountSpecialChars(text, min) {
var count = 0;
for (var i = 0; i < text.length; i++) {
var c = text[i];
if (text[i] >= 33 && text[i] <= 63){
count++;
}
}
return count > min;
}
return CountSpecialChars(passwordChecker, SpecialChars);
Also, as a bonus, you could also avoid that for loop for those functions by using replace, like so:
function MinChars(text, min) {
return text.length > min;
}
function MinUppercase(text, min) {
var non_uppers = /[^A-Z]/g;
var uppers = text.replace(non_uppers, text);
return uppers.length > min;
}
function MinLowercase(text, min) {
var non_lowers = /[^a-z]/g;
var lowers = text.replace(non_lowers, text);
return lowers.length > min;
}
function MinSpecialChars(text, min) {
var non_specials = /[^!-\?]/g;
var specials = text.replace(non_specials, text);
return specials.length > min;
}
Now with those functions, you can have:
if !MinChars(pw, MinLength) return false;
if !MinSpecialChars(pw, SpecialChars) return false;
if !MinLowercase(pw, MinLowercase) return false;
if !MinUppercase(pw, MinUppercase) return false;
return true;

javascript array not defined

Working on a project for school and arrays are causing me a serious problem. They are returning the error:
Uncaught ReferenceError: oddNumbers is not defined.
I did exactly what every other question on this site asked and to no avail. You can see in the ScriptManager "class" (as I am used to Java and C#) the oddNumbers and evenNumbers can't be pushed into. Please tell me whats wrong.
var manager = new ScriptManager();
function enterNumber() {
var number = prompt("Enter a number");
if (manager.addNumber(number)) {
document.getElementById("even").innerHTML = manager.getEvenNumbers();
document.getElementById("odd").innerHTML = manager.getOddNumbers();
document.getElementById("sum").innerHTML = manager.sum;
document.getElementById("average").innerHTML = manager.average;
}
}
function ScriptManager() {
this.count = 0;
this.oddCount = 0;
this.evenCount = 0;
this.sum = 0;
this.average = 0;
this.oddNumbers = [];
this.evenNumbers = [];
this.addNumber = function(number) {
if (!isNaN(parseInt(number))) {
number = parseInt(number);
if (number % 2 == 0) {
evenNumbers.push(number);
evenCount++;
count++;
} else {
oddNumbers.push(number);
oddCount++;
count++;
}
} else {
alert(number + " is not a valid number.");
return false;
}
for (var x = 0; x < oddCount; x++) {
sum += oddNumbers[x];
}
for (var x = 0; x < evenCount; x++) {
sum += evenNumbers[x];
}
average = sum / count;
return true;
};
this.getEvenNumbers = function() {
var stream = "";
var first = true;
for (var x = 0; x < evenCount; x++) {
if (!first) {
stream + ", ";
}
stream += String.valueOf(evenNumbers[x]);
if (first) {
first = false;
}
}
return stream;
}
this.getOddNumbers = function() {
return "bleh";
}
}
You need to use the this. prefix before all the object properties.
this.addNumber = function(number) {
if (!isNaN(parseInt(number))) {
number = parseInt(number);
if (number % 2 == 0) {
this.evenNumbers.push(number);
this.evenCount++;
this.count++;
} else {
this.oddNumbers.push(number);
this.oddCount++;
this.count++;
}
} else {
alert(number + " is not a valid number.");
return false;
}
for (var x = 0; x < oddCount; x++) {
this.sum += this.oddNumbers[x];
}
for (var x = 0; x < evenCount; x++) {
this.sum += this.evenNumbers[x];
}
this.average = this.sum / this.count;
return true;
};
In javascript, you have to use this in front of member variables to access them. So:
oddNumbers.push(number);
needs to be:
this.oddNumbers.push(number);
And, similarly for all the other member variables.

Categories