Printing '0' even if the number is bigger than 111 - javascript

I have tried so many time to solve this question but I couldn't accomplish the expected outcome.
Here's the question in a nutshell:
Count all the values that are divisible by 11 in a given array
Return 0 if you encounter a number that is greater than or equal 111 regardless of the other divisible numbers of 11.
For example:
Input: [11,12,22,33]
Output: 3
Input: [11,12,22,33,136]
Output: 0
I could solve the first part but failed with the second one.
Here is my code.
function div(list) {
let counter = 0
list.forEach((value) => {
if (value % 11 === 0) {
counter++
return counter
}
if(value>=111){
return 0
}
})
return counter
}
div([11, 22, 33, 44 , 116])
// OUTPUT : 4

Use a for loop instead so you can return inside if the break condition is found. Otherwise, return only at the end, not inside the loop.
function div(list) {
let counter = 0;
for (const value of list) {
if (value % 11 === 0) {
counter++
}
if (value >= 111) {
return 0
}
}
return counter
}
console.log(div([11, 22, 33, 44, 116]));

All the above answers works great, adding a different approach, letting the inbuilt method do the looping
function div(total, value) {
if (value % 11 === 0) {
total++;
}
if(value>=111){
total=0
}
return total;
}
console.log([11,12,22,33].reduce(div,0));

Use for...of loop to iterate over list and return inside loop when value is >= 111, otherwise keep counting the values divisible by 11.
function div(list) {
let count = 0;
for (const value of list) {
if(value >= 111){
return 0;
} else if (value % 11 === 0) {
count++;
}
}
return count;
}
console.log(div([11, 22, 33, 44 , 116]));

All of the other answers are great. Here's a solution that is a bit more condensed and offers a single return statement.
function div(list) {
let counter = 0;
let oversized = false;
for (let i = 0; (i < list.length) && !oversized; i++) {
counter += (list[i] % 11) ? 0 : 1;
oversized = (list[i] >= 111);
}
return oversized ? 0 : counter;
}
console.log(div([11, 22, 33, 44 ]));

Related

Given an circular array calculate the diff between two consecutive number. & if diff is greater than ‘k’, print 1 else print 0

Given an circular array & calculate the diff between two consecutive number. & if diff is greater than ‘k’, print 1 else print 0
Input Description:
You are given two numbers ‘n’, ’m’. Next line contains n space separated integers.
Output Description:
Print 1 if the difference is greater than ‘m’.
Can Anyone help with the code for easy Understanding for beginners
Sample Input :
5 15
50 65 85 98 35
Sample Output :
0 1 0 1 0
Code:
let cirluarArray = (data) => {
let n=data[0].split(" ").map(Number);//(sample input 1)
let arr = data[1].split(" ").map(Number);//(sample input 2)
let i,arr1=[];
for(i=0;i<arr.length-1;i++){
let x=arr[i]-arr[i+1];
if((x>0 && x<n[1])||(x<0 && x>-n[1])){
arr1.push(0);
}
else{
arr1.push(1);
}
}
if(((arr[arr.length-1]-arr[0])>0 && (arr[arr.length-1]-arr[0])<n[1])||((arr[arr.length-1]-arr[0])<0 && (arr[arr.length-1]-arr[0])>-n[1])){
arr1.push(0);
}
else{
arr1.push(1);
}
return arr1.join(" ");
};
console.log(cirluarArray(userInput));
I think that is
const circularArray = (array, k) => {
array.push(array.at(0)); // circular array
let output = [];
for (let i = 1; i < array.length; i++) {
const currentNumber = array[i];
const prevNumber = array[i-1];
let diff = currentNumber - prevNumber;
if (diff < 0) {
diff *= -1; // if negative, change to positive
}
if (diff > k) {
output.push(1);
} else {
output.push(0);
}
}
return output;
}
const result = circularArray([50, 65, 85, 98, 35], 15);
console.log(result);

FizzBuzz is it possible make my solution shorter?

I tried to make 3 conditions in one array.forEach, but this give me incorrect output. Is it possible to short my code to one array.forEach? Have 3 conditions inside it?
var array = []; // create empty array
for (var i = 1; i < 101; i++) {
array.push(i); // write in array all values of i, each iteration
}
array.forEach((number) => {
if (array[number] % 3 === 0 && array[number] % 5 === 0) {
array[number] = "FizzBuzz";
}
});
array.forEach((number) => { //
if (array[number] % 3 === 0) {
array[number] = "Fizz";
}
});
array.forEach((number) => {
if (array[number] % 5 === 0) {
array[number] = "Buzz";
}
});
for (let i = 0; i < array.length; i++) { //output array elements
console.log(array[i]);
}
First pointer: that's a lot of whitespace.
Second pointer, rather than creating an array then cycling through that array, you can do it all in one loop, using the if....else block; something like this:
for (var i = 1; i < 101; 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);
}
}
You are "walking over" the Array multiple times.
IMHO the most important Array Method to learn is Map:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
Which "walks over" the Array and returns a new value for that Array index
let arr = Array(100)
.fill((x, div, label) => x % div ? "" : label) //store Function in every index
.map((func, idx) =>
func(++idx, 3, "Fizz") + func(idx, 5, "Buzz") || idx
);
document.body.append(arr.join(", "));
fill takes a single Object, it is not executed 100 times!
Since JavaScript Functions are Objects this code declares a function once
Note the ++idx because we want to start at 1, not 0
In JavaScript ""+"" is a Falsy value, thus it returns the idx value for non-FizzBuzz numbers
More Array Methods explained: https://array-methods.github.io

How to display list of numbers based on condition in javascript

I would like to know how to get the list of numbers based on two condition
number should be divisible by 3
number should not end with 3
How to implement the list within 50 numbers in javascript
Expected Output
6,9,12,15...45
My attempt
function getNumbers() {
var result = [];
for (var i = 0; i < 50; i++) {
if (i % 2 == 0) {
return
} else {
result.push(i);
return result.toString()
}
}
}
console.log(getNumbers())
This seems to work to specs - your specs says it should start at 6 and not at 1
const numbers = [...Array(50).keys()].
filter(num => num !== 0 && num%3 === 0 && !String(num).endsWith("3"))
console.log(numbers)
NOTE: You can change [...Array(50).keys()] to [...Array(50).keys()].slice(1) if you want to avoid the test for 0
You can do that with a check if the modulo of 3 is 0 and the modulo of 10 is not 3. If you want to beautify the code you can combine this answer with mplungjan answer, but i wanted to show a mathematical alternative of the !String(num).endsWith("3") method provided by mplungjan.
I started your iteration at 1 instead of 0 to avoid 0 being put into the array. I also corrected your return statements.
function getNumbers() {
var result = [];
for (var i = 1; i < 50; i++) {
if (i % 3 === 0 && i % 10 !== 3) {
result.push(i);
}
}
return result;
}
console.log(getNumbers())

Javascript function that finds the next largest palindrome number

I want to write a function that finds the next largest palindrome for a given positive integer. For example:
Input: 2
Output: 3 (every single digit integer is a palindrome)
Input: 180
Output: 181
Input: 17
Output: 22
My try
function nextPalindrome(num) {
let input = num;
let numToStringArray = input.toString().split('');
let reversedArray = numToStringArray.reverse();
if (numToStringArray.length < 2) {
return Number(numToStringArray) + 1;
} else {
while (numToStringArray !== reversedArray) {
// numToStringArray = num.toString().split('');
// reversedArray = numToStringArray.reverse();
num += 1;
}
return numToStringArray.join('');
}
}
As a beginner, I thought that the numToStringArray would constantly increment by 1 and check for whether the while-statement is true.
Unfortunately it doesn't. I commented out two lines in the while-statement because they seemed somewhat redundant to me. Thanks to everyone reading or even helping me out!
The reason your code doesn't work is because you don't have any code updating the conditions of your while loop. So if you enter it once, it will loop indefinitely. You need to do something inside of the while loop that might make the condition false the next time through the loop, like so:
function getReverse(num) {
// get the reverse of the number (in positive number form)
let reversedNum = +Math.abs(num).toString().split("").reverse().join("");
// keep negative numbers negative
if (num < 0) { reversedNum *= -1; }
return reversedNum;
}
function nextPalindrome(num) {
// if single digit, simply return the next highest integer
if (num >= -10 && num < 9) {
return num+1;
}
else {
while(num !== getReverse(num)) {
num += 1;
}
return num;
}
}
console.log(nextPalindrome(3));
console.log(nextPalindrome(17));
console.log(nextPalindrome(72));
console.log(nextPalindrome(180));
console.log(nextPalindrome(1005));
console.log(nextPalindrome(-150));
console.log(nextPalindrome(-10));
You could also solve this pretty cleanly using recursion, like so:
function getReverse(num) {
// get the reverse of the number (in positive number form)
let reversedNum = +Math.abs(num).toString().split("").reverse().join("");
// keep negative numbers negative
if (num < 0) { reversedNum *= -1; }
return reversedNum;
}
function nextPalindrome(num) {
// if single digit, simply return the next highest integer
if (num >= -10 && num < 9) {
return num+1;
}
else if(num === getReverse(num)) {
return num;
}
else {
// if not the same, recurse with n + 1
return nextPalindrome(num + 1)
}
}
console.log(nextPalindrome(3));
console.log(nextPalindrome(17));
console.log(nextPalindrome(72));
console.log(nextPalindrome(180));
console.log(nextPalindrome(1005));
console.log(nextPalindrome(-150));
console.log(nextPalindrome(-10));

Smallest Common Multiple Code produces the wrong answer on one array

[edit]
I should clarify, I am attempting to find the smallest common multiple of a range of numbers. Sorry about that. I have attempted another solution but I still run into an incorrect answer on the last array [23, 18].
function smallestCommons(arr) {
arr = arr.sort(function (a, b) { return a - b; });
var count = 1;
for (var i = arr[0]; i <= arr[1]; i++) {
if (count % i !== 0) {
i = arr[0];
count++;
}
}
return count;
}
smallestCommons([23,18]);
My solution produces 2018940 when it should be 6056820
Your endless loop is becouse of your inner for loop which starts at the value 19 and runs to 22
414 (smallestMultiple of 18 & 23) % 19 == 15
414 % 20 = 14
414 % 21 = 15
414 % 22 = 18
which leads to your statement if(count % i == 0) being false and your for loop goes on with 415 416 ...
if u want to get the
least common multiple
var isSmallestMultipe = 0;
while(isSmallestMultiple == 0)
{
for(var i = 1; i <= arr[1]; i+)
{
if((arr[0]*i) % arr[1] == 0)
{
isSmallestMultiple = arr[0] * i;
}
}
}

Categories

Resources