Pushing to arrays - javascript

I'm not quite sure why my code is not working here. It is supposed to filter out odd and even numbers and put them into an array but I think my (lack of) understanding is on getting the numbers into the array how I want.
function oddAndEven(numbers) {
var odd = [];
var even = [];
for (num = 0; num < numbers.length; numbers++) {
if (numbers[num] % 2 == 0) {
even.push(numbers[num]);
} else if (numbers[num] % 2 == 1) {
odd.push(numbers[num]);
}
}
console.log(odd + "is odd and " + even + " is even");
}
iqTest(11221122);

function oddAndEven(numbers) {
var odd = [];
var even = [];
for (num = 0; num < numbers.length; num++) { // numbers is array, num is counter variable
if (numbers[num] % 2 == 0) {
even.push(numbers[num]);
} else if (numbers[num] % 2 == 1) {
odd.push(numbers[num]);
}
}
console.log(odd + " is odd and " + even + " is even");
}
oddAndEven([10,5,6,4,5]); // pass array as you are traversing though it

Incrementing the loop variable was not done in your case. Please try this.
function oddAndEven(numbers){
var odd = [];
var even = [];
for(num = 0; num < numbers.length; num++){
if(numbers[num] % 2 == 0){ //Even
even.push(numbers[num]);
}else { // Odd
odd.push(numbers[num]);
}
}
console.log(odd + "is odd and " + even + " is even");
}

Try this,
function oddAndEven(numbers) {
var odd = [];
var even = [];
for (num = 0; num < numbers.length; numbers++) {
if (numbers[num] % 2 == 0) {
even[num]=numbers[num];
} else if (numbers[num] % 2 == 1) {
odd[num]=numbers[num];
}
}
console.log(odd + "is odd and " + even + " is even");
}

You seem to improve your practice more.
function oddAndEven(numbers) {
var odd = [];
var even = [];
console.log ("length is " , numbers.length);
for (num = 0; num < numbers.length; num++) {
if (numbers[num] % 2 == 0) {
even.push(numbers[num]);
} else if (numbers[num] % 2 == 1) {
odd.push(numbers[num]);
}
}
console.log(odd + "is odd and " + even + " is even");
}
oddAndEven("82938411221122919239");
You missed num++, and you may want to send the input "82938411221122919239"
As A.T suggested, you shall send [8,2,9,....] as an input also.

function oddAndEven(numbers) {
var odd = [];
var even = [];
// a bit of optimization here, accessing `length` property only once
for (index = numbers.length - 1 ; index >= 0; index--) {
let current = numbers[index];
if (current%2 == 0) {
even.push(current);
} else {
odd.push(current);
}
}
console.log(odd + "is odd and " + even + " is even");
}

Related

FizzBuzz Javascript in html

so I'm doing this FizzBuzz challenge and I've made a mistake but cannot identify it. I'm wanting numbers from 1-100 to display on a web browser. The numbers that are divisible by 3 should say "fizz", the numbers divisible by 5 should say "buzz", and the numbers divisible by both 5and3 should say "FizzBuzz." I'm unable to get the browser to display the words, and for some reason it only displays the numbers.
function fizzbuzz() {
var display = document.getElementById('display');
var displayHTML = "";
for (i = 1; i < 101; i++) {
if (i % 3 === 0 && i % 5 === 0) {
console.log("FizzBuzz")
} else if (i % 5 === 0) {
console.log("buzz")
} else if (i % 3 === 0) {
console.log("Fizz")
} else {
console.log(i)
}
displayHTML += "<p>" + i + "</p>";
}
display.innerHTML = displayHTML
}
<body onload="fizzbuzz()">
<div id="display">
</div>
</body>
That's because you are concatenating i, the counter to displayHTML here displayHTML += "<p>" + i + "</p>";
Instead save the value you want to print in a variable on conditional check and then concatenate it afterwards
var result = '';
for (i = 1; i < 101; i++) {
if (i % 3 === 0 && i % 5 === 0) {
result = "FizzBuzz";
} else if (i % 5 === 0) {
result = "buzz";
} else if (i % 3 === 0) {
result = "Fizz";
} else {
result = i;
}
displayHTML += "<p>" + result + "</p>";
When a condition is true, you can set the result in a variable and then print your displayHTML element.
function fizzbuzz() {
var display = document.getElementById('display');
var divisible = "";
var displayHTML = "";
for (i = 1; i < 101; i++) {
if (i % 3 === 0 && i % 5 === 0) {
divisible = "FizzBuzz";
} else if (i % 5 === 0) {
divisible = "Buzz";
} else if (i % 3 === 0) {
divisible = "Fizz";
} else {
divisible = "";
}
displayHTML += "<p>" + i + ":" + divisible + "</p>";
}
display.insertAdjacentHTML('afterend', displayHTML);
}
fizzbuzz();
const fancy = function(i, output) {
for (let i = 0; i <= 100; i++) {
let output = '';
if (i % 3 === 0) output += 'fizz';
if (i % 5 === 0) output += 'buzz';
console.log(output || i);
}
};
fancy();

Function isn't giving response

This is my code:
function findTriad(numbers, sum) {
for (let i = 0; i < numbers.length - 1; i++) {
const firstNumber = numbers[i];
const newSum = sum - firstNumber;
let startOfCheckIndex = i + 1;
const endOfCheckIndex = numbers.length - 1;
while (startOfCheckIndex < endOfCheckIndex) {
const possibleAnswer =
numbers[startOfCheckIndex] + numbers[endOfCheckIndex];
if (possibleAnswer === newSum) {
return [
numbers[i],
numbers[startOfCheckIndex],
numbers[endOfCheckIndex]
];
} else if (sum < newSum) {
startOfCheckIndex++;
}
}
}
return ["N/A"];
}
function logFindTriad(numbers, sum) {
const answer = findTriad(numbers, sum);
console.log("Sum required: " + sum);
console.log("Numbers given: " + numbers.join(", "));
console.log("Found: " + answer.join(", ") + "\n");
}
logFindTriad([10, 15, 3, 7], 20);
Does anyone know why this code isn't giving me any value back?
It is supposed to give me back [10, 3, 7] if you find any errors or areas to improve on my code please tell me even if it doesn't resolve the issue.
The first time the code enters the while (startOfCheckIndex < endOfCheckIndex) {
startOfCheckIndex is 1 and endOfCheckIndex is 3
That means possibleAnswer is 10 + 7 = 17.
newSum is 10 and sum is 20
That means that neither
if (possibleAnswer === newSum) {
or
} else if (sum < newSum) {
are true. Resulting in startOfCheckIndex never getting changed.
In turn, while (startOfCheckIndex < endOfCheckIndex) { will always be true, resulting in an infinite loop.
You need to add an else clause or some other leaving condition.
Here is an example to demonstrate the issue.
let loopRestriction = 100
function findTriad(numbers, sum) {
for (let i = 0; i < numbers.length - 1; i++) {
const firstNumber = numbers[i];
const newSum = sum - firstNumber;
let startOfCheckIndex = i + 1;
const endOfCheckIndex = numbers.length - 1;
while (startOfCheckIndex < endOfCheckIndex) {
const possibleAnswer = numbers[startOfCheckIndex] + numbers[endOfCheckIndex];
if (loopRestriction-- <= 0) {
console.log("Stuck in while loop for atleast 100 iterations.")
break
}
console.log({
startOfCheckIndex,
endOfCheckIndex,
possibleAnswer,
sum,
newSum
})
if (possibleAnswer === newSum) {
return [
numbers[i],
numbers[startOfCheckIndex],
numbers[endOfCheckIndex]
];
} else if (sum < newSum) {
startOfCheckIndex++;
}
}
}
return ["N/A"];
}
function logFindTriad(numbers, sum) {
const answer = findTriad(numbers, sum);
console.log("Sum required: " + sum);
console.log("Numbers given: " + numbers.join(", "));
console.log("Found: " + answer.join(", ") + "\n");
}
logFindTriad([10, 15, 3, 7], 20);
First, function findTriad you are not defined
Then, your code has execute to else statement because condition in if and else if is wrong so you go to infinity loop (because you don't update value of startOfCheckIndex after loop, you can debug your code and find a true way to give condition in if elsestatement. I can give code sample here
Happy coding !

Printing out extra 0's while writing numbers in Expanded Form via javascript

Can't seem to figure out why I keep printing out extra 0's.
As of now, if the value was 730, this is what shows up:
Expected: '700 + 30', instead got: '700 + 30 + 0'
Criteria:
"You will be given a number and you will need to return it as a string in Expanded Form. For example:
12 Should return 10 + 2
42 Should return 40 + 2
70304 Should return 70000 + 300 + 4
NOTE: All numbers will be whole numbers greater than 0."
function expandedForm(num) {
var i,
position,
numArr = Array.from(num.toString()).map(Number),
numArrLen = numArr.length,
result = '';
if(num < 10){
return num;
} else {
for(i = 0; i < numArrLen; i++){
position = numArrLen-1-i;
if( i === numArrLen-1 ){
result += numArr[i] * Math.pow(10, position);
console.log('done',result);
} else {
if(numArr[i] !== 0){
result += numArr[i] * Math.pow(10, position) + " + ";
console.log('keep going',result);
} else {
continue;
console.log('zero', result);
}
}
}
return result;
}
}
Well it goes into the first if check which does not account for zero so you need to check if it is zero in that check.
if (i === numArrLen-1 && numArr[i]!==0)
And the issue you will have after that is you will have a trailing +.
What I would do is instead of adding the string, I would push to an array and join
var result = []
result.push(30)
result.push(2)
console.log(result.join(" + ")
and you can use array methods to actually solve it.
(102030).toString().split("").map((n,i,a) => n*Math.pow(10, a.length-i-1)).filter(n => n>0).join(" + ")
This is how I solved the solution.
function expandedForm(num) {
// Convert num to a string array
let numStringArray = Array.from(String(num));
// Get length of string array
let len = numStringArray.length;
let result = '';
// For each digit in array
numStringArray.map( (n,index) => {
// Perform only if n > 0
if( n>0 ) {
// Add plus sign if result is not empty (for the next digits)
if( result ) { result += ' + '; };
// Pad zeros the right limited to array length minus current index
result += new String(n).padEnd(len-index,'0');
}
});
return result;
}
This was my solution, could have been refactored better but it works.
function expandedForm(num) {
let myStr = num.toString().split(''), //convert number to string array
strLength = myStr.length,
arr = new Array();
if (strLength === 1) { /*If array length is one*/
return num;
}
for (let i = 0; i < strLength; i++) { //loop
if (myStr[i] === 0) { //if number starts with 0
arr.push('0')
}
if (i + 1 === strLength) { //if array is close to end
arr.push(myStr[i])
}
// add zero to number by length difference in array
// add number to
if (myStr[i] !== 0 && i + 1 !== strLength) {
for (let x = 1; x < (strLength - myStr.indexOf(myStr[i])); x++) {
myStr[i] += '0'
}
arr.push(myStr[i]);
}
}
return arr.filter((obj) => obj.match(/[1-9]/)) //remove items with just 0s
.map(obj => obj += ' + ') // add '+'
.reduce((a, b) => a + b).slice(0, -2); //remove whitespace
}
function expandedForm(num) {
const arr = num
.toString()
.split('');
for (let i = 0; i < arr.length - 1; ++i) {
if (arr[i] > 0) {
for (let j = i; j < arr.length - 1; ++j) {
arr[i] += '0';
}
}
}
return arr
.join()
.replace(new RegExp(",0", "g"), "")
.replace(new RegExp(",", "g"), " + ");
}
My solution is fairly similar, uses a bit of RegExp at the end in order to strip out the commas and lone zeroes however

Why is my program not working?

I'm trying to write a simple program to calculate the biggest even number from an array.
An array of 10 elements is used.
function biggestEven(array) {
var numberOfNumbers = array.length;
var biggestYet = 0;
var theNumber;
for (var i = 0; i < numberOfNumbers; i++) {
if(array[i] % 2 = 0) {
biggestYet = array[i];
}
if(array[i] % 2 = 0 && array[i] > biggestYet) {
theNumber = biggestYet;
}
}
return theNumber;
}
var myArray = [];
for (var i = 0; i < 10; i++) {
myArray[i] = window.prompt("Enter number " + (i+1) + "of 10:");
}
console.log("The biggest even number is: " + biggestEven(myArray));
Please help I am stuck. The program won't lead in chrome.
You're giving a value, not comparing:
if(array[i] % 2 = 0) {
biggestYet = array[i];
}
And also you were returning the wrong element:
function biggestEven(array) {
var numberOfNumbers = array.length;
var biggestYet = 0;
var theNumber = 0;
for (var i = 0; i < array.length; i++) {
if (array[i] % 2 === 0) {
biggestYet = array[i];
}
if (array[i] % 2 === 0 && array[i] > biggestYet) {
theNumber = biggestYet;
}
}
return biggestYet;
}
var myArray = [];
for (var i = 0; i < 2; i++) {
myArray[i] = window.prompt("Enter number " + (i+1) + " of 10:");
}
console.log("The biggest even number is: " + biggestEven(myArray));
This might help:
console.log(Math.max(...[267, 306, 108, 307].filter(function(value) { return value % 2 === 0 })));
You need to change
if(array[i] % 2 = 0) {
biggestYet = array[i];
}
to
if(array[i] % 2 == 0) {
biggestYet = array[i];
}
Here is a solution for your problem
function biggestEven(array) {
return Math.max(...array.filter(function(num){
return num%2==0;
}));
}
var myArray = [1,2,36,45,51,16,7];
alert(biggestEven(myArray));

Javascript code to find prime numbers doesn't work

I run this function, which i triggered with a button, and it should be printing the prime numbers. Instead, it printed all the numbers that it checked. The user is supposed to enter a number(for example 100) and all the numbers lower than it will be checked if they are prime, and if they are, they will be printed.(i is the number that is being checked)
function findeprime(num) {
for (i = 2; i < num; i++) {
for (coun = 2; coun < i; coun++) {
if (i % coun == 0) continue;
}
document.write(i + " is prime <br/>");
}
}
What am i doing wrong???
Your continue is only breaking out of the inner loop. I'd recommend something like this
function findeprime(num) {
var isPrime;
for (var i = 2; i < num; i++) {
isPrime = true;
for (coun = 2; coun < i; coun++) {
if (i % coun == 0) isPrime = false;
}
if (isPrime) document.write(i + " is prime <br/>");
}
}
It seems like your continue statement is misplaced. It is affecting the inner loop while your code will work properly only if it affected the outer loop.
Since you can't have a continue statement affect an outer loop/block, try the following:
function findeprime(num) {
for (i = 2; i < num; i++) {
var prime = true;
for (coun = 2; coun < i; coun++) {
if (i % coun == 0) {
prime = false;
break;
}
}
if(prime) alert(i + " is prime");
}
}
findeprime(14);
As already pointed out, your continue is breaking the script out of the wrong loop. You can alternatively label the loop you want to break out of:
function findeprime(num) {
checknum: for (i = 2; i < num; i++) {
for (coun = 2; coun < i; coun++) {
if(i % coun == 0) continue checknum;
}
document.write(i + " is prime <br/>");
}
}
findeprime(20);
Apparently everyone already gave you the answer, however i´m gonna post an additional example, for knowledge purposes.
Number.prototype.isPrime = function() {
for (var i = 2; i < this; i++) {
if (this % i == 0) {
return false;
}
}
return true;
};
function findPrimes(num) {
var results = [];
for (var i = 2; i <= num; i++) {
if (i.isPrime()) results.push(i);
}
return results;
}
var primes = findPrimes(1000);
document.write(primes.join(', '));

Categories