Adrian Lara
Adrian Lara

Reputation: 23

I need to get the sum of each element from a list

I have a list like that:

[[0 1 2] [4 6 9] ... [-1 0 3]]

and I need to get [3 19 ... 2], I mean sum of first element, second and .... n - element.

I´m gonna really appreciate your help.

Update: I tried with that:

to sum-first-item
  let out []
  ask turtles[
    let sum-elem sum map first data-train
    set out lput sum-elem out
  ]
end

Upvotes: 1

Views: 196

Answers (2)

LeirsW
LeirsW

Reputation: 2305

Edit: Matteo's version with map sum the-list is the simpler solution so I suggest sticking with that. Still, it is useful to get to know reduce for when you need to do more complex calculations than summing.

Netlogo offers a few very powerful primitives to work with lists. I see you already use map, which runs a reporter for each item of a list and reports the resulting list. Another one of those is reduce, which combines all items from a list into a single value by applying a reporter to them in turn. I suggest reading up on reduce in the dictionary and playing around with it a bit since it is not immediately obvious how it works (https://ccl.northwestern.edu/netlogo/docs/dictionary.html#reduce).

Combining these two gives you this elegant piece of code:

to try

  let the-list[[0 1 2] [4 6 9] [-1 0 3]]
  show map [ x -> reduce + x] the-list 
  ;observer: [3 19 2]
  
end

Upvotes: 1

Matteo
Matteo

Reputation: 2926

Each list's item (in your case: each inner list) can be accessed by using item (see here, but also know about first and last) or as the current element of foreach (see here).

Here a bunch of ways with which you can accomplish your goal. First showing simply how to operate on each inner list, then showing how to directly build a list containing each inner list's sum:

to play-with-lists
  print "The original list:"
  let list-of-lists [[0 1 2] [4 6 9] [-1 0 3]]
  print list-of-lists
  
  print "Manually reporting sums:"
  print sum item 0 list-of-lists
  print sum item 1 list-of-lists
  print sum item 2 list-of-lists
  
  print "Building a list of sums with while loop using 'while':"
  let list-of-sums []
  let i 0
  while [i < length list-of-lists] [
    set list-of-sums lput (sum item i list-of-lists) (list-of-sums)
    set i i + 1
  ]
  print list-of-sums

  print "Building a list of sums with for loop using 'foreach':"
  set list-of-sums []
  foreach list-of-lists [
    inner-list ->
    set list-of-sums lput (sum inner-list) (list-of-sums)
  ]
  print list-of-sums
  
  print "Building a list of sums using 'map':"
  print map sum list-of-lists
end

Upvotes: 1

Related Questions