0

I am trying to find a solution for this:

Users are asked to type in a random set of numbers sequentially:

var num1 = prompt("Enter 1st set of numbers");
var num2 = prompt("Enter 2nd set of numbers"); 
var num3 = prompt("Enter 3rd set of numbers");

var myNumbers =[num1, num2, num3];

Now I am trying to take compare the sum of the digits in each element of the array. For instance, if myNumbers[0] = 32, myNumber[1] = 45, what's the function to compare 5 (3+2) and 9 (4+5)?

I am trying to compare the sum of each elements by adding the numbers in that element, and return the largest number. So if num1= 1234, then the sum of myNumbers[0] should be 10. By comparing , if num2 = 3456, then the sum should be 18, the function should return num2.

6
  • you want "myNumbers" array to be sorted in an order? What do you refer by "method to compare"? And num1 ,num2 are each numbers or they can be an array of numbers? Commented Jul 20, 2016 at 2:58
  • What is your required outcome? A method like reduce will traverse the members, apply a function and return a single result. But you haven't said how the numbers should be compared or what the actual comparison is (larger, smaller, odd, even, …). Commented Jul 20, 2016 at 3:05
  • Thanks for the comments. I am trying to compare the sum of each elements by adding the numbers in that element, and return the largest number. So if num1= 1234, then the sum of myNumbers[0] should be 10. By comparing , if num2 = 3456, then the sum should be 18, the function should return num2. Commented Jul 20, 2016 at 3:10
  • Do you want to return the input with the largest sum of the individual digits, or the input with the largest sum of the digits multiplied by the original input? Commented Jul 20, 2016 at 3:22
  • Hi @larz, I would like return the input with the largest sum of the individual digits. Thanks! Commented Jul 20, 2016 at 3:24

3 Answers 3

1

var num1 = prompt("Enter 1st set of numbers");
var num2 = prompt("Enter 2nd set of numbers"); 
var num3 = prompt("Enter 3rd set of numbers");

// finds the sum of your array, parsing each element as an integer
var sum = function(array){
  var digits = array.split("")
  return digits.reduce(function(a, b) {return parseInt(a, 10) + parseInt(b, 10)})
}

var myNumbers =[num1, num2, num3]
var findLargest = function(array){
  var answer
  var largest = 0
  array.forEach(function(input){
        // check if this is the largest sum
        if (sum(input) == largest){
          // check if there is already a running set of equal sums
  	  if (typeof(answer) == Object) answer.push(input)
          // create set of equal sums if not
          else answer = [answer, input]
        }
        else if (sum(input) > largest) {
          largest = sum(input)
          answer = input
        }
      })
      return answer
    }

alert(findLargest(myNumbers))

https://jsfiddle.net/gmebk2Ly/7/

This also checks to see if there are multiple inputs that are equal

Sign up to request clarification or add additional context in comments.

9 Comments

Is there some particular reason you are not using Math.max?
@torazaburo no but that sounds like a great recommendation :)
You surely meant to pass 10 not 0 to parseInt?
@Bergi yep. Thanks!
Thank you @larz. The way you wrote the code is actually really comprehensible.
|
0

If you want to sort the list by the sums of the digits, you can do the following. The comparator function finds the sum of the digits in the members of the list, then compares them. If you just wanted to sum the digits in the string, you can just extract the code that does this from this solution too.

myNumbers.sort(function(a,b) {
    var sumA = 0;
    var sumB = 0;
    a.split("").forEach(function(digit) {
        sumA+=parseInt(digit);
    });
    b.split("").forEach(function(digit) {
        sumB+=parseInt(digit);
    });
    return sumA-sumB;
});

1 Comment

Computing the sum of the digits over and over again each time the comparison function is called does not seem that elegant.
0

Let's break this down into two sub-problems: first, finding the sum of digits; second, finding the maximum value of an array. For the second, we already have Math.max.

For the first, we'll break it down even further and first write a function just to get the digits:

function digits(x) { return String(x).match(/\d/g).map(Number); }

To sum up the digits, we just say

function sumDigits(x) { return sum(digits(x)); }

For sum, you can find many examples here on SO, but the simplest one is

function sum(array) { return array.reduce(add, 0); }

add is easy enough:

function add(a, b) { return a + b; }

Now, to get the maximum sum of digits from each element of an array:

function maxSumDigits(array) { return Math.max(...array.map(sumDigits)); }

The above uses ES6 spread operator. In ES5:

return Math.max.apply(0, array.map(sumDigits));

The advantage of writing your code this way is first, you end up with useful little utility routines that you can re-use; second, the code is easier to read and prove to yourself that it's right; and third, it's easier to deal with spec changes, such as wanting to find the minimum instead of the maximum, of the product of digits instead of the sum.

function digits(x)           { return String(x).match(/\d/g) . map(Number); }
function sumDigits(x)        { return sum(digits(x)); }
function sum(array)          { return array . reduce(add, 0); }
function add(a, b)           { return a + b; }
function maxSumDigits(array) { return Math.max(...array . map(sumDigits)); }

console.log(maxSumDigits([1234, 3456]));

This returns the largest sum. To find the element whose digits have the largest sum, the easiest way would be to remember the array of sums of digits, then look that up:

function maxSumDigits(array) { 
  var sums = array . map(sumDigits);
  var max = Math.max(...sums);
  return array[sums.indexOf(max)];
}

2 Comments

Much more eloquent and well explained than my answer. Just a quick note - I think they are looking for which original item provided the highest sum, not the sum itself
Really appreciate it @torazaburo. Just learned about map.() and math.max() here today.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.