How to create ArrayAddition function using dart

Viewed 33

What is the right syntax in dart for the below js code:

I am trying to create a function ArrayAddition(arr) take the array of numbers stored in arr and return the string true if any combination of numbers
in the array can be added up to equal the largest number in the array, otherwise
return the string false. For example: if arr contains [4, 6, 23, 10, 1, 3] the
output should return true because 4 + 6 + 10 + 3 = 23.

function ArrayAddition(arr) { 

  arr.sort(function(a,b){return a - b});
  var maxNum = arr.pop();
  var tot = 0;
    
  for (var i = 0; i < arr.length; i++){
    tot += arr[i];
    for (var j = 0; j < arr.length; j++){
      if (i != j) {
        tot += arr[j];
        if (tot == maxNum) {
          return true;
        }
      }
    }
      
    for (var k = 0; k < arr.length; k++) {
      if (i != k) {
        tot -= arr[k];
        if (tot == maxNum) {
          return true;
        }
      }
    }
    tot = 0;
  }
    
  return false; 
         
}

So what is the rightt syntax for this in dart language?

1 Answers

It's almost the exact same code, just change the following lines:

function ArrayAddition(arr) { 

to

bool ArrayAddition(List<int> arr) {

arr.sort(function(a,b){return a - b});

to

arr.sort((a, b) => a - b);

var maxNum = arr.pop();

to

var maxNum = arr.removeLast();
Related