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 !
Related
Here's my code:
function sumDigits(num) {
var string = num.toString();
var result = 0;
for (let i = 0; i < string.length; i++) {
if (string[i] === '-') {
var negative = Number(string[i + 1]) * -1
result = result + negative
} else {
result = result + Number(string[i])
}
}
return result;
}
console.log(sumDigits('-316'))
When I add -316 as an argument, my output is 7. Why is it not taking -3 into the equation? As an FYI, I am still new to coding, and not sure this is even the correct route to take. All input is appreciated.
Learn to debug, console.log and debugger are your friend.
function sumDigits(num) {
var string = num.toString();
var result = 0;
console.log("my string:", string);
for (let i = 0; i < string.length; i++) {
console.log("in loop", i, string[i]);
if (string[i] === '-') {
var negative = Number(string[i + 1]) * -1
console.log("in if ", result, "+", negative);
result = result + negative
console.log("updated result", result);
} else {
console.log("in else ", result, "+", Number(string[i]));
result = result + Number(string[i])
console.log("updated result", result);
}
}
console.log("final result", result);
return result;
}
sumDigits(-317);
Looking at the results you can see you find a negative and you get the next number. On the next iteration you read that same number again. So -3 + 3 is zero. So you cancel it out. You need to skip your loop ahead by one.
function sumDigits(num) {
var string = num.toString();
var result = 0;
for (let i = 0; i < string.length; i++) {
if (string[i] === '-') {
var negative = Number(string[i + 1]) * -1
result = result + negative
// bump i
i++;
} else {
result = result + Number(string[i])
}
}
return result;
}
console.log(sumDigits(-317));
I am checking whether the number is greater than 0 or less than zero.
Then if the number is less than zero, then I am merging the first element of array which will be (-digit) digits[0] = digits[0] + digits[1];.
-then I am removing 2nd element from digits array. digits.splice(1, 1);
And At the end I am lopping through all the digits using forEach loop and returning total of the dum digits to total.
const digitsSum = (number) => {
let total = 0;
if (number < 0) {
let digits = number.toString().split('');
digits[0] = digits[0] + digits[1];
digits.splice(1, 1);
digits.forEach(digit => total += parseInt(digit));
console.log(total);
return total;
} else {
let digits = number.toString().split('');
digits.forEach(digit => total += parseInt(digit));
console.log(total);
return total;
}
}
function calculateDigitSumLogic(number) {
}
digitsSum(-1203);
digitsSum(1203);
digitsSum(-201);
I am stuck in summing up to number 10. Can't get it right.
What i am getting is the total sum from 10 digits (after filtering odd only 7). Where should i make <= num ?
function sumFibs(num) {
var fib = [1, 1];
for (var i = 2; i < num; i++) {
var next = fib[i - 1] + fib[i - 2];
var fibi = fib.push(next);
}
return fib.filter(function(a) {
return (a % 2 != 0);
})
.reduce(function(a, z) {
return a + z;
})
}
console.log(sumFibs(10));
Expected output 10, but getting 99
Add a < num to your filter callback test, so you get a % 2 && a < num
function sumFibs(num) {
var fib = [0, 1];
for (var i = 2; i < num; i++) {
var next = fib[i - 1] + fib[i - 2];
var fibi = fib.push(next);
}
return fib.filter(function (a) {
return a % 2 && a < num;
}).reduce(function (a, z) {
return a + z;
}, 0);
}
console.log(sumFibs(0))
console.log(sumFibs(1))
console.log(sumFibs(10))
console.log(sumFibs(9000))
You don't need to use array at all if you need only sum of those numbers
function sumFibs(num) {
if(num <= 1) return 0;
var a = 0, b = 1, sum = a + b;
while(true) {
var next = a + b;
if(next >= num) {
break;
}
if(next % 2) {
sum += next;
}
a = b;
b = next;
}
return sum
}
console.log(sumFibs(0))
console.log(sumFibs(1))
console.log(sumFibs(10))
console.log(sumFibs(9000))
You need to change the loop condition. Loop till the last value of fib is less than num
function sumFibs(num) {
var fib = [1, 1];
for (var i = 2; fib[fib.length - 1] < num; i++) {
var next = fib[i - 1] + fib[i - 2];
fib.push(next);
}
return fib
.filter(x => !(x % 2))
.reduce((ac,a) => ac + a,0)
}
console.log(sumFibs(10));
If you want to retain your code for the most part, you can add an if statement that breaks the loop once your next number goes beyond your num:
function sumFibs(num) {
var fib = [1, 1];
for (var i = 2; i < num; i++) {
var next = fib[i - 1] + fib[i - 2];
if ( next > num ) { // not >= assuming you want to include your num
break;
}
fib.push(next);
}
console.log({fib});
return fib.filter(function(a) {
return (a % 2 != 0);
})
.reduce(function(a, z) {
return a + z;
})
}
console.log(sumFibs(10));
Your code is summing the first N Fibonacci numbers that are odd. You seem to be looking for the first odd Fibonacci numbers that sum to N:
function oddFibsThatAddTo(target)
{
let currentFib = 1;
let lastFib = 1;
let sum = 2;
const outs = [1,1];
while(sum < target)
{
let nextFib = currentFib + lastFib;
if(nextFib % 2 == 1)
{
sum += nextFib;
outs.push(nextFib);
}
lastFib = currentFib;
currentFib = nextFib;
}
if(sum > target)
{
throw 'can\'t find perfect sequence';
}
return outs;
}
console.log(oddFibsThatAddTo(10))
function sumFibs(num) {
var fib=[1,1];
for(var i=2; i<num; i++){
var next=fib[i-1]+fib[i-2];
var fibi=fib.push(next);
}
return fib.filter(function(a){
return(a%2!=0 && a<=num);
})
.reduce(function(a,z){
return a+z;
})
}
console.log(sumFibs(10));
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
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");
}
I wrote a JavaScript function to find the number of odd integers, number of negative integers, average, and median value.
The code is accomplishing everything that I wanted it to, however, I am wondering if I can rewrite it to get the function to return an object rather than just the console log values. I've also included a link to my JS Bin (https://jsbin.com/digagozuru/edit?html,css,js,console,output)
Any advice or suggestions would be appreciated! Thanks.
var arrayAnalyzer = function(myArray) {
var odds = 0;
var negatives = 0;
var avg;
var median;
for (var i = 0; i < myArray.length; i++) {
if (myArray[i] % 2 !== 0) {
odds += 1;
}
if (myArray[i] < 0) {
negatives += 1;
}
}
console.log("There are " + odds + " odd numbers.");
console.log("There are " + negatives + " negative numbers.");
var sum = myArray.reduce(function(previousValue, currentValue) {
return previousValue + currentValue;
});
avg = sum / myArray.length;
console.log("The average is " + avg.toFixed(2));
var orderedArray = myArray.sort(function(a, b) {
return a - b;
});
if (orderedArray.length % 2 === 0) {
var position1 = orderedArray.length / 2;
var position2 = position1 - 1;
median = (orderedArray[position1] + orderedArray[position2]) / 2;
} else {
var position = Math.floor(orderedArray.length / 2);
median = orderedArray[position];
}
console.log("The median is " + median);
};
arrayAnalyzer([7, -3, 0, 12, 44, -5, 3]);
var arrayAnalyzer = function(myArray) {
var odds = 0;
var negatives = 0;
var avg;
var median;
for (var i = 0; i < myArray.length; i++) {
if (myArray[i] % 2 !== 0) {
odds += 1;
}
if (myArray[i] < 0) {
negatives += 1;
}
}
console.log("There are " + odds + " odd numbers.");
console.log("There are " + negatives + " negative numbers.");
var sum = myArray.reduce(function(previousValue, currentValue) {
return previousValue + currentValue;
});
avg = sum / myArray.length;
console.log("The average is " + avg.toFixed(2));
var orderedArray = myArray.sort(function(a, b) {
return a - b;
});
if (orderedArray.length % 2 === 0) {
var position1 = orderedArray.length / 2;
var position2 = position1 - 1;
median = (orderedArray[position1] + orderedArray[position2]) / 2;
} else {
var position = Math.floor(orderedArray.length / 2);
median = orderedArray[position];
}
console.log("The median is " + median);
// Returns an object with named attributes
return {
odds:odds,
negatives:negatives,
avg:avg,
median:median
};
};
var myArray = arrayAnalyzer([7, -3, 0, 12, 44, -5, 3]);
console.log("Odds: " + myArray.odds +
"\nNegatives: " + myArray.negatives +
"\nAverage:" + myArray.avg +
"\nMedian: " + myArray.median);
I'm not sure if I get your question right, but why dont create an object at the beginning of your method and then write the values in the object as soon as you calculated them?
var arrayAnalyzer = function(myArray) {
var odds = 0;
var negatives = 0;
var avg;
var median;
var result = {};
for (var i = 0; i < myArray.length; i++) {
if (myArray[i] % 2 !== 0) {
odds += 1;
}
if (myArray[i] < 0) {
negatives += 1;
}
}
result.negatives = negatives;
result.odds = odds;
var sum = myArray.reduce(function(previousValue, currentValue) {
return previousValue + currentValue;
});
avg = sum / myArray.length;
result.avg = avg;
var orderedArray = myArray.sort(function(a, b) {
return a - b;
});
if (orderedArray.length % 2 === 0) {
var position1 = orderedArray.length / 2;
var position2 = position1 - 1;
median = (orderedArray[position1] + orderedArray[position2]) / 2;
} else {
var position = Math.floor(orderedArray.length / 2);
median = orderedArray[position];
}
result.median = median;
return result;
};
console.log(arrayAnalyzer([7, -3, 0, 12, 44, -5, 3]));