55 lines
1.2 KiB
JavaScript
55 lines
1.2 KiB
JavaScript
// Write a function solution that gets String as the input and calculates
|
|
// how many times word 'BANANA' could exactly be written with the given letters.
|
|
|
|
function solution(S) {
|
|
let str = (' ' + S).slice(1);
|
|
let flag = true;
|
|
let b = 0;
|
|
let a = 0;
|
|
let n = 0;
|
|
let iterationCount = 0;
|
|
|
|
for (let i = 0; i < str.length; i++) {
|
|
let c = str[i];
|
|
switch (c) {
|
|
case 'B':
|
|
b++;
|
|
break;
|
|
case 'A':
|
|
a++;
|
|
break;
|
|
case 'N':
|
|
n++;
|
|
break;
|
|
}
|
|
}
|
|
|
|
while (flag) {
|
|
b = b - 1;
|
|
a = a - 3;
|
|
n = n - 2;
|
|
if (b < 0 || a < 0 || n < 0) {
|
|
flag = false;
|
|
} else {
|
|
iterationCount++;
|
|
}
|
|
}
|
|
|
|
return iterationCount;
|
|
}
|
|
|
|
|
|
// Function to check if a number is prime
|
|
function isPrime(num) {
|
|
if (num <= 1) return false;
|
|
if (num === 2) return true;
|
|
if (num % 2 === 0) return false;
|
|
for (let i = 3; i <= Math.sqrt(num); i += 2) {
|
|
if (num % i === 0) return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
// Export for testing
|
|
module.exports = {isPrime, solution};
|