【问题标题】:Multiplying elements of a list in Netlogo starting from a listentry greater than 0从大于0的listentry开始,将Netlogo中列表的元素相乘
【发布时间】:2018-04-18 07:44:59
【问题描述】:

我想从列表中的特定元素开始将列表中的元素相乘。这是一个伪代码示例:

set mylist (list 1 2 3 4)
let j 0
while [ j < 4 ] [
  ; set desired_product multiplication of element j with element j+1
]

使其得到 1*2*3*4。我知道我可以用reduce 做到这一点,但我并不总是想从第一个元素开始。有时我只需要计算从第一个元素 (2*3*4) 开始的乘积,或者我只需要计算每个乌龟的元素一和二 (2*3) 的乘积。例如

if age of turtle x = 50 [
   ; start the multiplication from element 1 and stop it before element 3
]

这样我得到 2*3。

【问题讨论】:

    标签: list netlogo multiplication


    【解决方案1】:

    我知道我可以通过 reduce 做到这一点,但我并不总是想从第一个元素开始。

    问题不在于reduce,而在于你的列表!幸运的是,有一种简单的方法可以从列表中只获取您需要的元素:sublist

    我有时只需要从第一个元素(2*3*4)开始计算乘积

    print reduce * sublist mylist 1 length mylist
    

    或者我只需要计算元素一和二的乘积(2*3)

    print reduce * sublist mylist 1 3
    

    作为更一般的评论:在 NetLogo 中很少需要使用while 循环。每当您处理列表时,通常有一种方法可以使用基本列表原语的组合来做任何您需要的事情,例如 reducemapfiltersublistlput 等。这些更少容易出错并更清楚地表达意图。

    【讨论】:

      猜你喜欢
      • 2017-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多