How to print Odd and Even numbers in Javascript [duplicate] - javascript

This question already has answers here:
How to determine if a number is odd in JavaScript
(31 answers)
Closed 1 year ago.
I'm trying to merge this two codes to run as a working function that print out odd and even numbers.
but I don't know on how to use a var
let num = [1,2,3,4,5,6,7,8,9,];
console.log('even numbers are');
for (var i = 1 ; i < 10 ; i += 2 ) {
console.log(i);
}
console.log('odd numbers are ');
for (var i = 2 ; i < 10 ; i += 2 ) {
console.log(i);
}
Help. Thanks

const isOdd = (n) => (n & 1) === 1;
const num = [1,2,3,4,5,6,7,8,9];
console.log( `Odd numbers are ${ num.filter( n => isOdd(n))}` );
console.log( `Even numbers are ${ num.filter( n => !isOdd(n))}`);
const
Arrow functions
Bitwise AND (&)
Logical NOT (!)
Array.prototype.filter()

Use below code to print out Even Numbers and in the same way you can get Odd numbers list given in an Array
var arr = [1, 2, 3, 4, 5, 6];
for (var i = 0; i < arr.length; i++) {
if (arr[i] % 2 === 0) {
console.log(arr[i] + "");
}
}
If you are trying to put your JS code inside HTML Page, refer to the link for more details Find Even Numbers in JS

Related

find the number of unique numerical elements in any array [duplicate]

This question already has answers here:
Get all unique values in a JavaScript array (remove duplicates)
(91 answers)
Count unique elements in array without sorting
(9 answers)
Closed 14 days ago.
have made some code but it is broken and gives errors. the code is supposed to find the number of unique numerical elements in any array. So far, i created the following code snippet which contains a uniqueLength() function to return the number of unique elements.
function uniqueLength(nums) => {
if(nums.length === 0) {
return 0;
}
let i=0;
while(j>nums.lengths) {
if(nums[j]] ==! nums[i]) {
i++;
nums[i] = nums[j];
j++;
} else {
j++;
}
}
give i+1;
}
// Should return 5
const result = uniqueLength([1,1,2,3,4,5,5]);
console.log(result);
// Should return 1
const result2 = uniqueLength([1,1,1,1]);
console.log(result2);
where there is dashes one of these hints should go there
return
nums[j]
!=
nums[j] == nums[i]
nums[i]
give
j > nums.length
returns
let j=1;
=
**!==
j < nums.length**

Why function returns wrong array of numbers if that number is big

I am working to solve a problem, I have an array of numbers for example [1, 2, 3] and I need to make from that array number 123 and add 1 and than return it like [1, 2, 4]. My code work with small numbers but with big it returns wrong number. Why?
var plusOne = function(digits) {
let num = parseInt(digits.join(''))
num = num + 1
let arr = num.toString().split().join(',')
let incrementedArr = []
for (let i = 0; i < arr.length; i++) {
incrementedArr.push(arr[i])
}
return incrementedArr;
};
When input is
[6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,3]
my function returns
[6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,0,0,0]
instead of
[6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,4]
why I have three zeros in the end? Thank you!
The problem is with the way you are converting the number back to an array. Your code is using the split() method, which expects a separator as the argument, but you are passing an empty string. This causes the method to split the number into an array of characters, rather than numbers.
You should use the map() method instead, like this:
let incrementedArr = Array.from(num.toString()).map(Number);
This will convert the number back to a string, and then use the map() method to convert each character back to a number.
Another issue is with the way you are incrementing the number. You are incrementing the number after converting the array to a number. Instead of that you should use the last element of the array and increment it by 1 and use the rest of the array as it is.
let incrementedArr = digits.slice()
incrementedArr[incrementedArr.length-1] += 1
Also, you can use spread operator to return the incremented number.
return [...incrementedArr];
Here is the final code:
var plusOne = function(digits) {
let incrementedArr = digits.slice()
incrementedArr[incrementedArr.length-1] += 1
return [...incrementedArr];
};
I hope this helps!
As the maximum JavaScript precision would be exceeded by a number of this size, see #Barmar's comment, you may have to perform the addition and the carry-over manually and below is one approach:
const
d0 = [6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,3],
d1 = [6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,9],
d2 = [6,1,4,5,3,9,0,1,9,5,1,8,6,7,9,9,9,9,9],
plusOne = d => {
let adds = d.map((n,i,a) => i === a.length - 1 ? 1 : 0), newd = d;
do {
newd = newd.map((n,i) => n + adds[i]);
adds = newd.map((n,i) => n > 9 ? 1 : 0);
adds.push( adds.shift() );
newd = newd.map(n => n > 9 ? 0 : n);
} while( !adds.every(e => e === 0) );
return newd;
};
console.log( plusOne( d0 ) );
console.log( plusOne( d1 ) );
console.log( plusOne( plusOne( d1 ) ) );
console.log( plusOne( d2 ) );
This is probably what was meant to be done in the exercise
function plusOne(digits) {
const copy = [...digits]
for (let i = copy.length - 1; i >= 0; i -= 1) {
if (copy[i] < 9) {
copy[i] += 1
for (let j = i + 1; j < copy.length; j += 1) {
copy[j] = 0
}
return copy
}
}
return [1, ...'0'.repeat(copy.length)]
}
console.log(plusOne([6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,3]).join(''))
console.log(plusOne([6,1,4,5,3,9,0,1,9,5,1,8,6,7,9,9,9,9,9]).join(''))
console.log(plusOne([9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9]).join(''))

how to build count and say problem in javascript

I am trying to solve the below problem in JavaScript
The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, ...
1 is read off as one 1 or 11.
11 is read off as two 1s or 21.
21 is read off as one 2, then one 1 or 1211.
Given an integer n, generate the nth sequence.
Note: The sequence of integers will be represented as a string.
Example:
if n = 2,
the sequence is 11.
So I want to create a function which pass N integer and gives it value
Here is my code:
let countAndSay = function (A) {
if (A == 1) return "1"
if (A == 2) return "11"
let str ="11"
if(A > 2){
// count
}
}
I don't understand the logic for how to build this.
You need to be able to dynamically determine the number and type of chunks a string has, which can be done pretty concisely with a regular expression. To come up with the string to deconstruct on index n, recursively call countAndSay to get the result of n - 1:
let countAndSay = function (count) {
if (count === 1) {
return '1';
}
const digitsArr = countAndSay(count - 1).match(/(\d)\1*/g);
// You now have an array of each chunk to construct
// eg, from 1211, you get
// ['1', '2', '11']
return digitsArr // Turn the above into ['11', '12', '21']:
.map(digitStr => digitStr.length + digitStr[0])
.join(''); // Turn the above into '111221'
};
console.log(
countAndSay(1),
countAndSay(2),
countAndSay(3),
countAndSay(4),
countAndSay(5),
);
Here's a function that generates the next string of numbers based on the previous string you feed it:
function next(s) {
s = s + "*"; // add a flag value at the end of the string
var output = "";
var j = 0;
for (var i = 1; i < s.length; i++) {
if (s.charAt(i) != s.charAt(i - 1)) { // if the character changes, concatenate the amount (i - j) and the digit
output += (i - j) + s.substring(j, j+1);
j = i;
}
}
return output;
}
Then you'd need to recursively run next N times.

Multiplicative Persistence Codewars Challenge

I've been working on a kata from Codewars, the challenge is to write a function, persistence, that takes in a positive parameter num and returns its multiplicative persistence, which is the number of times you must multiply the digits in num until you reach a single digit.
Example:
persistence(39) === 3 // because 3*9 = 27, 2*7 = 14, 1*4=4
// and 4 has only one digit
persistence(999) === 4 // because 9*9*9 = 729, 7*2*9 = 126,
// 1*2*6 = 12, and finally 1*2 = 2
persistence(4) === 0 // because 4 is already a one-digit number
While trying to figure this out I came across a solution online (shown below) and after trying to understand its logic, I couldn't see why the code didn't work
var count = 0;
function persistence(num) {
if (num.toString().length === 1) {
return count;
}
count++;
var mult = 1;
var splitStr = num.toString().split("");
for (var i = 0; i <= splitStr; i++) {
mult *= parseFloat(splitStr[i])
}
return persistence(parseFloat(mult));
}
The output for any single digit number will be 0 which is correct however for any number that is multiple digits, the persistence always logs as 1 and I can't seem to figure out why, any help would be greatly appreciated.
The posted code has quite a few problems.
for (var i = 0; i <= splitStr; i++) {
But splitStr is an array, not a number; i <= splitStr doesn't make sense. It should check against splitStr.length instead of splitStr.
Another problem is that it should use i <, not i <=, else the final splitStr[i] will be undefined.
Another problem is that the count variable is global, so more than one call of persistence will result in inaccurate results. There's no need for a count variable at all. To fix it:
function persistence(num) {
if (num.toString().length === 1) {
return 0;
}
var mult = 1;
var splitStr = num.toString().split("");
for (var i = 0; i < splitStr.length; i++) {
mult *= parseFloat(splitStr[i])
}
return 1 + persistence(parseFloat(mult));
}
console.log(
persistence(999),
persistence(39),
persistence(4)
);
Or, one could avoid the for loop entirely, and use more appropriate array methods:
function persistence(num) {
const str = num.toString();
if (str.length === 1) {
return 0;
}
const nextNum = str.split('').reduce((a, b) => a * b, 1);
return 1 + persistence(nextNum);
}
console.log(
persistence(999),
persistence(39),
persistence(4)
);
or we can use while loop with reduce array method
const persistence=(num)=>{
let splitNumArr=num.toString().split('')
let newList
let count=0
while(splitNumArr.length>1){
newList=splitNumArr.reduce((acc,curr)=>{
return acc*=curr
})
splitNumArr=newList.toString().split('')
count++
}
return count
}
console.log(persistence(39))===3
console.log(persistence(999))===4
console.log(persistence(9))===0

How to generate random numbers without including a set number? [duplicate]

This question already has answers here:
Unique (non-repeating) random numbers in O(1)?
(22 answers)
Closed 4 years ago.
I'm just trying to generate 8 random numbers from 1 to 25. My issue is that I already have a variable and its value is 14, with that being said my question is how to generate random numbers from 1 to 25 and if one them is equal to 14 then replace it with another random number? at the end, I want to have 8 random numbers in my array and I don't want to include 14 in it. Can anyone tell me what I'm missing or how to make this more accurate? and sometimes I only end up with 7 elements in my array, does anyone knows why?
Here's my code:
var arr = [];
var currentvar = 14;
for(var i = 0 ; i < 9; i++){
var num = Math.floor(Math.random()*25) + 1;
if(num === currentvar){
num = Math.floor(Math.random()*25) + 1;
}else{
arr.push(num);
}
}
console.log(arr);
Study the logic you've implemented more closely. You go through the loop exactly 9 times (not 8), and you have mutually exclusive outcomes for each iteration due to an if...else control flow.
Either you reassign num if it's equal to currentvar (which you should do correctly by removing var from the second assignment), or you add it to the array, never both in one iteration. That's what else means, and you probably want a do...while loop to assign num until it is not equal to currentvar.
var arr = [];
var currentvar = 14;
var num;
for (var i = 0; i < 8; i++) {
do {
num = Math.floor(Math.random() * 25) + 1;
} while (num === currentvar);
arr.push(num);
}
console.log(arr);
Alternatively, if you want to keep your if...else statement, you can decrement the loop counter i instead to repeat the loop an extra time when num === currentvar:
var arr = [];
var currentvar = 14;
for (var i = 0; i < 8; i++) {
var num = Math.floor(Math.random() * 25) + 1;
if (num === currentvar) {
i--;
} else {
arr.push(num);
}
}
console.log(arr);

Categories

Resources