I am solving this problem on hackerrank. It seems to be a simple problem where I count all the value that are <= 0 in the array and return whether the count equals to k, which is what I have implemented in my code. I pass the test case just fine but fail all other 11 hidden cases. What am I doing wrong?
function angryProfessor(k, a) {
let count = 0;
for (let num of a) {
if (num <= 0) {
count++;
}
}
if (count === k) {
return 'NO'
} else {
return 'YES'
}
}
The question asks a minimum number of students, for e.g. if k=3 then if there are more than 3 students then also the class will happen.So change your if condition i.e. if (count === k) condition to this if (count >= k)
Related
Here is the question.
Find the greatest common divisor of two positive integers. The integers can be large, so you need to find a clever solution.
The inputs x and y are always greater or equal to 1, so the greatest common divisor will always be an integer that is also greater or equal to 1.
Here is my solution.
function mygcd(x, y) {
//your code here
let gcd = [];
let lowestNum;
let bigestNum;
//detect the lowest and bigest numbers
if (x < y) {
lowestNum = x;
bigestNum = y;
} else if (x > y) {
lowestNum = y
bigestNum = x;
} else {
lowestNum = x
}
//check if the bigest num has a modolo == 0
//else loop the lowest num and push in the array
if (bigestNum % lowestNum === 0) {
return gcd += lowestNum;
} else {
let arrNum = []
for (let i = 1; i < lowestNum; i++) {
// console.log(i)
arrNum.push(i)
}
//loop the array backwards
for (i = arrNum.length - 1; i >= 1; i--) {
if (lowestNum % arrNum[i] === 0 && bigestNum % arrNum[i] === 0) {
console.log(arrNum[i])
if (gcd !== 0) {
return
} else {
// gcd += arrNum[i]
let vals = gcd.push(arrNum[i])
console.log(typeof(vals))
}
}
}
}
console.log(gcd)
return gcd[0];
}
console.log(mygcd(30, 12))
The above solution works for the test cases i tried it for, but the issue is that it returns the correct divisor and undefined.
This is what my logs look like
6
undefined
6
undefined
The test cases
test:
Log
6
expected undefined to equal 6
so it gets undefined instead of 6 or the correct divisor.
I also tired a different recursive approach below.
Note: This works well.
function mygcd(x, y) {
if (!x) return y
if (!y) return x
return mygcd(y, x % y)
}
console.log(mygcd(30, 12))
console.log(mygcd(8, 12))
But i am curious to understand why my original solution breaks. Any help would be really appreciated.
Thanks
this code right here does work, but i don't quite understand why.
if i remove the interior return statement and keep only the one at the end, it will return the correct sum (44) for console.log(evenFibonnacisSum(100)), but undefined for console.log(evenFibonnacisSum(4000000)).
if i remove the exterior return statement and keep the one inside the if statement, it will return undefined for console.log(evenFibonnacisSum(100)) but the correct sum (46000000 or so) for console.log(evenFibonnacisSum(4000000)).
function evenFibonnacisSum(upperlimit){
let evenSum = 0
let seq = [0, 1]
for(i=0; i<=upperlimit; i++) {
if(evenSum<upperlimit) {
let next = seq[i]+seq[i+1];
seq.push(next)
if(seq[i]%2 === 0 && seq[i]<upperlimit) {
evenSum += seq[i]
}
} else {
return evenSum
}
}
return evenSum
}
console.log(evenFibonnacisSum(100))
console.log(evenFibonnacisSum(4000000))
it's not a huge problem, but it's really unintuitive. anyone have any insight into why this might be?
If you remove the interior return and pass in a large upperlimit, then it will attempt to execute the loop too many times. Your environment realizes that it is taking too long and aborts the function.
If you remove the external return then for 100 you never hit the interior return because the correct answer has evenSum < upperlimit.
I would suggest coding it like this instead:
function evenFibonnacisSum(upperlimit){
let evenSum = 0
let seq = [0, 1]
i = 0
while(seq[i] < upperlimit) {
let next = seq[i]+seq[i+1];
seq.push(next)
if(seq[i]%2 === 0) {
evenSum += seq[i]
}
i++
}
return evenSum
}
I am stuck with a problem where I am supposed to figure out a mode from an array in typescript.
I am using the program Visual Studio Code and I know that I need a for loop but I am unsure what I should loop through it. I also have to make sure that if the array is empty, the number that always shows up is 0 and if there is two integers that show up the same amount of times, that the smaller number (whether positive or negative) is the number that is put as the mode.
Currently I have this part of the code:
export let mode = (a: number[]): number => {
let mode: number;
mode = a[0];
if (a.length === 0) {
return 0;
}
for (let i = 1; i < a. length; i++) {
if ()
return mode;
};
I know that there needs to be an if statement after the for loop that changes the mode when necessary, but I am unsure beyond that.
As you indicated: your mode should be a function which:
accepts an array of numbers and should return the number with highest occurrence.
if there are two or more numbers that share the highest occurrence, then it should return the number with the least value.
if the given array is empty, it should return 0.
You could do this:
If given array is empty, return 0 right away. Else proceed with the rest of the steps.
Count the occurrences of each number in the array.
Sort the result of #2 by number of occurrence and value. Sort by highest occurrence, then lowest value.
Get the first of the items from #3.
Here's an implementation using reduce() to do step #2, and sort() to do step #3.
let mode = (numbers: number[]): number => {
if (numbers.length === 0) {
return 0;
}
const m = numbers.reduce((items, current) => {
const item = (items.length === 0) ? null : items.find((x) => x.value === current);
(item) ? item.occurrence++ : items.push({ value: current, occurrence: 1 });
return items;
}, [])
.sort((a, b) => {
if (a.occurrence < b.occurrence) {
return 1;
} else if (a.occurrence > b.occurrence || a.value < b.value) {
return -1;
} else {
return (a.value === b.value) ? 0 : 1;
}
});
return m[0].value;
}
I'm having some frustration with this code. I may not be seeing it.
I keep getting either an "Unexpected Token" or "ILLEGAL" error (the latter which completely preplexed me, considering I've never seen an error like that before in my life.
I've been double checking the syntax and I'm thinking it may be something I'm just not catching?
function fizzBuzz(n) {
2 for (i = 0; i<=n; i++) {
3 if (n%3===0) {
4 print ("fizz")
5 }
6 if (n%5===0) {
7 print ("buzz")
8 }
9 if (i%3 !== 0 && i%5 !== 0) {
10 return [i];
11 }
12 }
13 }
14
15
16 fizzBuzz(100);
I'd be thankful for the help! <3
You need some changes:
remove line numbers,
check first for 'fizz buzz' value and use console.log for output. Then use continue statement for jumping to top for next loop,
use i instead of n for checking.
function fizzBuzz(n) {
for (i = 0; i <= n; i++) {
if (i % 3 === 0 && i % 5 === 0) {
console.log("fizz buzz");
continue;
}
if (i % 3 === 0) {
console.log("fizz");
continue;
}
if (i % 5 === 0) {
console.log("buzz");
continue;
}
console.log(i);
}
}
fizzBuzz(100);
function fizzBuzz(n) {
2 for (i = 0; i<=n; i++) {
3 if (n%3===0) { You're checking if the maximum number (n) is divisible by 3.
4 print ("fizz") You should be checking i.
5 }
6 if (n%5===0) { You're checking if the maximum number (n) is divisible by 5.
7 print ("buzz") You should be checking i.
8 }
9 if (i%3 !== 0 && i%5 !== 0) {
10 return [i]; You're returning an array with a single element: i.
11 } You should print i instead.
12 }
13 }
14
15
16 fizzBuzz(100);
The line numbers are what's causing the "ILLEGAL" error. Remove them.
print in JavaScript opens the print dialog to literally print paper out of a printer. Use console.log
If a number is divisible by both 3 and 5, fizzbuzz should be printed. Your code prints fizz and buzz on separate lines.
Working version ( https://www.youtube.com/watch?v=QPZ0pIK_wsc ) :
function fizzBuzz(n) {
for (var i = 0; i <= n; i++) {
var printVal = "";
if (i % 3 === 0) {
printVal += "fizz";
}
if (i % 5 === 0) {
printVal += "buzz";
}
if (printVal === "") {
printVal = i;
}
console.log(printVal);
}
}
fizzBuzz(100);
Lets decrease number of if statements, I have seen many fizzbuzzs - I would like to try another approach
const fizzBuzz = (i = 0, ret) => {
while (++i, ret = '', i <= 100) {
if (i % 3 === 0) {
ret += `fizz`
}
if (i % 5 === 0) {
ret += `buzz`
}
console.log(ret || i)
}
}
fizzBuzz()
The most important part is console.log(ret || i) - empty string is falsy value, so console will log ret if there is some value or current i value
If you're trying to print to your browser's console, use console.log() instead of print(), since print() will open the printer preview in a browser. I'm using Chrome. Remember to check the console by pressing F12 and clicking on "console" in case you've created a html file that includes your javascript script.
Since you are iterating i until it reaches the value of n, you if statements should look like:
if(i%3===0){
// your code...
}
Based on your code, it seems like you want to check for a value that is not a multiple of 3 && a multiple of 5. However, the fizzbuzz challenge requires to print fizzbuzz when encountering a number that is both a multiple of 3 && a multiple of 5. So, you'll need to add the following condition:
if (i%3 === 0 && i%5 === 0) {
console.log("fizzbuzz");
continue; /* Continue may or may not be necessary depending on your program's logic. Continue allows to re-enter the loop
without checking for the remaining if statements. If you use continue, this condition must be the first if statement inside the loop */
}
Your function doesn't need to return anything, since you're using console.log() to visualize the values in each loop iteration. That's why you need to change return [i] for console.log(i).
Don't give up and keep trying!
If you have further questions, I'll be glad to help you.
I'm trying to complete an algorithm challenge to find the largest prime factor of 600851475143. I'm not necessarily asking for the answer. Just trying to figure out why this code isn't working. Why does it return 'undefined' instead of a number?
let isPrime = n => {
let div = n - 1;
while (div > 1) {
if (n % div == 0) return false;
div--;
}
return true;
};
let primeFactor = x => {
for (let i = Math.floor(x / 2); i > 1; i--) {
if (x % i == 0 && isPrime(i) == true) {
return i;
}
}
};
console.log(primeFactor(35)); // 7
console.log(primeFactor(13195)); // 29
console.log(primeFactor(600851475143)); // undefined
The problem is not your algorithm it is perfectly valid, check the below slightly modified algorithm, all I've done is replaced your starting point Math.floor(x/2) with a parameter that you can choose:
let isPrime = n => {
let div = n - 1;
while (div > 1) {
if (n % div == 0) return false;
div--;
}
return true;
};
function primeFactor(x, n){
for (let i = n; i > 1; i--) {
if (x % i == 0 && isPrime(i) == true) {
return i;
}
}
}
console.log(primeFactor(35, 35));
console.log(primeFactor(13195, 13195));
console.log(primeFactor(600851475143, 100000))
Using the above you'll get an answer that proves your implementation works, but the loop is too big to do the entire thing(i.e. from Math.floor(600851475143/2)). Say your computer can do 500million loops per second, going through every one from 300,425,737,571 down to 1 would take 167 hours, even at 5 billion loops per second it would take 16 and a half hours. Your method is extremely inefficient but will return the correct answer. The reason you're not getting an answer on JSBin is more likely to do with browser/service limitations.
Spoilers on more efficient solution below
The following implementation uses a prime sieve(Sieve of Eratosthenes) in order to generate any list of primes requested and then checks if they fully factor into the given number, as long as you use a large enough list of primes, this will work exactly as intended. it should be noted that because it generates a large list of primes it can take some time if ran incorrectly, a single list of primes should be generated and used for all calls below, and the cached list of primes will pay off eventually by having to perform less calculations later on:
function genPrimes(n){
primes = new Uint32Array(n+1);
primes.fill(1)
for(var i = 2; i < Math.sqrt(n); i++){
if(primes[i]){
for(var j = 2*i; j < n; j+=i){
primes[j] = 0;
}
}
}
primeVals = []
for(var i = 2; i < primes.length; i++){
if(primes[i]){
primeVals.push(i);
}
}
return primeVals;
}
function primeFactor(x, primes){
var c = x < primes.length ? x : primes.length
for (var i = c; i > 1; i--) {
if(x % primes[i] == 0){
return primes[i];
}
}
}
primes = genPrimes(15487457);
console.log(primeFactor(35, primes));
console.log(primeFactor(13195, primes));
console.log(primeFactor(600851475143, primes));
console.log(primeFactor(30974914,primes));
let primeFactor = x => {
if (x === 1 || x === 2) {
return x;
}
while (x % 2 === 0) {
x /= 2;
}
if (x === 1) {
return 2;
}
let max = 0;
for (let i = 3; i <= Math.sqrt(x); i += 2) {
while (x % i === 0) {
x /= i;
max = Math.max(i, max);
}
}
if (x > 2) {
max = Math.max(x, max);
}
return max;
};
console.log(primeFactor(35));
console.log(primeFactor(13195));
console.log(primeFactor(27));
console.log(primeFactor(1024));
console.log(primeFactor(30974914));
console.log(primeFactor(600851475143));
Optimizations
Dividing the number by 2 until it's odd since no even number is prime.
The iteration increment is 2 rather than 1 to skip all even numbers.
The iteration stops at sqrt(x). The explanation for that is here.