Please how can I use the index 0 in a for-loop when testing an empty array for a drumming sum.
Also, the single negative value returns zero
The sum should stop when a negative number is encountered
let sum = 0;
let lenArr = arr.length;
for (let i = 0; i <= lenArr - 1; i++) {
if (lenArr === 0) {
break;
}
if (arr[i] > 0) {
sum = sum + arr[i];
} else {
break;
}
}
return sum;
}
let input = [];
runningSum(input);
For an empty array the for loop would not be executed and it will return 0.
You can remove the if condition to check length of array inside for loop.
Related
Trying to return the highest 5 digit number out of any given number i.e 34858299999234
will return 99999
I think I have it narrowed down to the for loop not iterating the array properly OR the values for 'hold1' and 'hold2' are not updating.
function solution(digits){
//Convert string to array to iterate through
let arr = digits.split("");
let final = 0;
//iterate through the array in 5 sequence steps
for(let i = 0; i < arr.length-1; i++){
let hold1 = arr[i] + arr[i+1] + arr[i+2] + arr[i+3] + arr[i+4];
hold1 = parseInt(hold1,10); //converting string to int so if statement functions correctly
let hold2 = arr[i+1] + arr[i+2]+ arr[i+3] + arr[i+4] + arr[i+5];
hold2 = parseInt(hold2,10);
if(hold1 >= hold2){
final = hold1;
}else{
final = hold2;
}
return final;
}
}
if you need a five digits result you need to change the for loop in something like this:
for (let i = 0; i < arr.length - 5; i++) {
Otherwise you will generate results shorter than 5 digits.
Also, I think you are missing the Math.max method that will compare two numbers to return the bigger one.
I rewrote your function this way:
function solution(digits) {
let op = 0;
let length = 5;
let stringDigits = String(digits); /// <-- I use string instead of array
if (stringDigits.length <= length) {
return digits; /// <-- If input is shorter than 5 digits
}
for (let i = 0; i < stringDigits.length - length; i++) {
const fiveDigitsValue = stringDigits.substr(i, length);
op = Math.max(op, Number(fiveDigitsValue));
}
return op;
}
This function returns the largest number from an array. I need help on understanding the if part: if (arr[i] > maxNumber) {maxNumber = arr[i]}. Using pseudocode or an explanation how exactly does this work?
function max(arr){
let maxNumber = 0
for (i = 0; i < arr.length; i++) {
if (arr[i] > maxNumber){
maxNumber = arr[i]
}
}
return maxNumber
}
console.log(max([1,2,3,40,5]));
function max(array) {
largest number is equal to 0;
for (i is equal to 0; i is less than the length of array; increment i by 1 each time) {
if (the item at the current index is greater than the previous largest number) {
set the largest number to to the item at the current index;
}
}
return largest number which will be 0 if no larger number is found
}
Worth noting that if all values in the array are negative, it will return 0;
This will work for negative numbers too.
function max(arr){
let maxNumber = -Infinity
for (i = 0; i < arr.length; i++) {
if (arr[i] > maxNumber){
maxNumber = arr[i]
}
}
return maxNumber
}
What this part: if (arr[i] > maxNumber) {maxNumber = arr[i]} doing is checking if the current array member is greater than the current maxNumber and if it is changing the maxNumber value to the current array.
In short, max(whatEverArray) will always return zero or the biggest value of the array. and if it return zero, means all the array values are either zero or less than zero.
Here we are. Stuck.
I've decided to create a function that finds the element with the most digits. If two of them have the same length, return the first one. Common sense tells us that it might be the highest number. Here is the code snippet:
function findLongest(array) {
var biggestNum = 0;
for(var i = 0; i < array.length; i++) {
if(array[i] > biggestNum) {
biggestNum = array[i];
}
}
return biggestNum;
}
findLongest([111,1111,5555,10000,1,90000]); //returns 90000 instead of 10000.
However, I can't meet the second condition (if length of two is the same, return the first one).
Any idea?
If you want digit-length comparing, cast the items into string and use length of them.
function findLongest(array) {
var biggestNum = 0;
for(var i = 0; i < array.length; i++) {
if(array[i].toString().length > biggestNum.toString().length) {
biggestNum = array[i];
}
}
return biggestNum;
}
console.log(findLongest([111, 1111, 5555, 10000, 1, 90000]));
You could take the integer value of the logarithm of 10 of the value for checking, because you get the count of digits (minus 1) for comapiring.
function findLongest(array) {
var biggestNum = array[0];
for (var i = 1; i < array.length; i++) {
if (Math.floor(Math.log10(array[i]) || 0) > Math.floor(Math.log10(biggestNum) || 0)) {
biggestNum = array[i];
}
}
return biggestNum;
}
console.log(findLongest([111, 1111, 5555, 10000, 1, 90000, 0]));
The second condition negates the first every time. The "highest number" right?
If you want the highest number why not sort and pop the last element as the returned value?
array[array.sort(function(a,b){return b - a}).length - 1]
Iteration of array is unnecessary
I am attempting to write a single function in javascript that compares credit card numbers listed strings within an array. The function should find the credit card number with the largest sum, and return that number as the original string within the input array. I am completely stuck, and cannot get past this 'undefined' error message. Here is what I have:
function highest(inputArray) {
var sum = 0;
var currentHighest = 0;
var largest = 0;
for (a = 0; a < inputArray.length; a++) {
var tempArray = inputArray[a].replace(/\D/g, '');
}
function sumDigits(str) {
sum = 0;
for (i = 0; i < str.length; i++) {
sum += parseInt(str.charAt(i), 16);
}
return sum;
}
if (sumDigits(tempArray) >= currentHighest) {
currentHighest = sum;
largest = inputArray[a];
return largest;
} else {
return largest;
}
}
var numberArray = [];
console.log(highest(numberArray));
You have a good number of basic errors in your code. Rather than break it down, I will simply put the code revision in here.
var ipa = ['4916-2600-1804-0530', '4779-2528-0088-3972', '4252-2788-0093-7978', '4556-4242-9283-2260'];
function highest(inputArray) {
var currentHighest = 0;
var largest = 0;
var tempArray = [];
for (var a = 0; a < inputArray.length; a++) {
tempArray.push(inputArray[a].replace(/\D/g, ''));
}
function sumDigits(strA) {
var sum = 0;
for (var i = 0; i < strA.length; i++) {
sum += parseInt(strA.charAt(i), 10);
}
return sum;
}
for (var a = 0; a < tempArray.length; a++) {
var csum = sumDigits(tempArray[a]);
if (csum >= currentHighest) {
currentHighest = csum;
largest = inputArray[a];
}
}
return largest;
}
console.log(highest(ipa));
'use strict';
// initial array of numbers
let numbers = ['4916-2600-1804-0530', '4779-2528-0088-3972', '4252-2788-0093-7978', '4556-4242-9283-2260'];
// remove "-" symbol
let normilized = numbers.map(number => number.replace(/-/g, ''));
// get sum for each number
let sums = normilized.map(
number => [].reduce.call(number, (prev, value) => {
prev += +value;
return prev;
}, 0));
// find max sum
let max = Math.max.apply(null, sums);
// find position of that sum
let indexOfMax = sums.indexOf(max);
// get card number
console.log(numbers[indexOfMax]);
Based on my understanding of your question, I hope this is what you are looking for.
In addition to doing a basic loop over the array, you can also sort the array in ascending order and simply pick out the last item of the array for your largest credit card number.
Sample Fiddle here:
https://jsfiddle.net/xxo3m8zf/1/
Sample Function:
function largestSum(arr) {
arr.sort();
return largest = arr[arr.length-1];
}
I am trying to create a single function in Javascript that will take each element of an array of numbers (specifically phone numbers in this case) and determine which element has the highest sum. I have reached a point where I am feeling pretty defeated, yet I think I am very close. Can anyone give some guidance? This is what I have so far:
function highest(inputArray) {
var sum = 0;
var currentHighest = 0;
var largest = 0;
I set the variables I am going to use, then created a for loop to iterate over each element in the array.
for (a = 0; a < inputArray.length; a++)
var tempArray = inputArray[a].replace(/\D/g,'');
I create a place holder string to remove any non integers in the element, then create a function that will sum all the digits of the element.
function sumDigits(str) {
for (i = 0; i < str.length; i++) {
sum += parseInt(str.charAt(i));
return sum;
}
}
Then create an if statement that tests if the sum of the current element is higher or equal to the highest sum element.
if (sumDigits(tempArray) >= currentHighest) {
currentHighest = sum;
largest = inputArray[a];
return largest;
}
else {
return largest;
}
}
var newArray = ['123-456-7777', '963-481-7945', '111-222-3333'];
console.log(highest(newArray));
Here is the entire code block as a whole:
function highest(inputArray) {
var sum = 0;
var currentHighest = 0;
var largest = 0;
for (a = 0; a < inputArray.length; a++)
var tempArray = inputArray[a].replace(/\D/g,'');
function sumDigits(str) {
for (i = 0; i < str.length; i++) {
sum += parseInt(str.charAt(i));
return sum;
}
}
if (sumDigits(tempArray) >= currentHighest) {
currentHighest = sum;
largest = inputArray[a];
return largest;
}
else {
return largest;
}
}
}
var newArray = ['123-456-7777', '963-481-7945', '111-222-3333'];
console.log(highest(newArray));
I get "undefined" as the result when I run the code if that helps. Thank you in advance for your assistance.
If I'm interpreting this question correctly (add each number of a phone number, then print the largest result), you can accomplish it like this:
//Define an array of phone numbers
var numbers = ['123-456-7777', '111-222-3333', '963-481-7945'];
//Map takes an array, does something with each element, then returns that result
var sums = numbers.map(function (m) {
//In this case, we return an object containing the original number, and a score
return {
number: m,
//The score is calculated by adding up each number. The match expression creates an array of all terms (g modifier) matching the expression. \d matches a single digit, so we end up with an array of each digit in the number.
//Reduce applies a function to each item in an array, and adds them up
score: m.match(/\d/g).reduce(function (p, c) {
//This looks like magic, but the + before p and c coerces them to numbers (they're strings right now, since match returns an array of strings)
//Both numbers are then added
return +p + +c;
})
}
}).sort(function (a, b) {
//Now that we have the scores of all numbers, we can sort the array to find the highest score
//To be honest, sort() is mostly trial and error for me to find which values to return 1 and -1 for
if (a.score < b.score) return 1;
if (a.score > b.score) return -1;
return 0;
});
//All together, without comments:
sums = numbers.map(function (m) {
return {
number: m,
score: m.match(/\d/g).reduce(function (p, c) {
return +p + +c;
})
}
}).sort(function (a, b) {
if (a.score < b.score) return 1;
if (a.score > b.score) return -1;
return 0;
});
console.log(sums);
document.write("Number with the highest score: " + sums[0].number);
document.write("<br>");
document.write("It's score is " + sums[0].score);
Which prints the number with the largest sum to the console. The sum of the numbers is also available in the object that is returned in the score property.
In your code, you are not initializing the sum variable here and you are prematurely returning the sum value in this function:
function sumDigits(str) {
for (i = 0; i < str.length; i++) {
sum += parseInt(str.charAt(i));
return sum;
}
}
It should be this:
function sumDigits(str) {
var sum = 0;
for (i = 0; i < str.length; i++) {
sum += parseInt(str.charAt(i), 10);
}
return sum;
}
We can't really see what else is wrong without seeing all the code together in one block so we can see how different parts call each other and interact.
Here's a more compact solution (assuming you're trying to sum the digits in each phone number):
var phoneNumbers = ["123-456-7890", "982-111-9999"];
var sums = phoneNumbers.map(function(p) {
return p.match(/\d/g).reduce(function(sum, num) {
return sum + parseInt(num, 10);
}, 0);
});
var maxSum = Math.max.apply(Math, sums);
// output results in the snippet window
document.write("sums = " + JSON.stringify(sums) + "<br>");
document.write("maxSum = " + maxSum + "<br>");
Here's how it works:
Run .map() on the phone numbers array with the goal of returning an array of sums.
Within the .map() search for all digits, then run .reduce() on that resulting array to accumulate the sum.
Then, to get the max value in the sums array, use Math.max() which can accept the entire array and do the max work for you.