NetLogo:如何根据从另一个向量中随机选择的值构建一个新向量?

NetLogo: How do I build a new vector based on randomly chosen values from another vector?

我有一个包含 10 位数字的向量 'original'。现在我想基于 'original' 创建向量 'adapted'。 'adapted'应该从'original'的同一位置取n个大于0的随机值,其余用0补齐,例如:

原始 = [2 3 6 2 0 5 7 2 4 8] 适应 = [2 0 0 0 0 5 0 2 0 0]

to go

  let n 3
  let vector-dimension 10

  let original []
  repeat vector-dimension
    [set original lput random 10 original]

   print original

   
   let adapted []

   while [sum (map [ [v1] -> ifelse-value (v1 > 0) [1] [0] ] (adapted)) != n]
     [set adapted (map [ [v1] -> ifelse-value ( (vector-dimension / n) * (100 / vector-dimension) > random-float 100) [v1] [0] ] (original)) ]
    
   print adapted
   
end

此代码有效但速度较慢。我怎样才能做得更快?

怎么样:

to-report report-rand-n [ base n ]
  let indices ( range 0 (length base)) 
  let subset n-of n indices
  let out ( map [ [ i v ] -> ifelse-value ( member? i subset ) [v] [0] ] indices base)
  report out
end

这位记者制作了一个索引列表(0 到 base 传递的长度),然后随机选择 n 个索引传递给 ifelse-value 到 return base 中的原始值(如果 i 是选定的 indices 之一)或 0.

测试:

to test
  let original [2 3 6 2 0 5 7 2 4 8]
  print report-rand-n original 3
  print report-rand-n original 3
  print report-rand-n original 5
  print report-rand-n original 5
end

observer> test
[2 0 6 0 0 0 0 0 4 0]
[2 0 0 0 0 0 0 2 0 8]
[2 0 0 0 0 5 0 2 4 8]
[0 0 6 2 0 5 0 0 0 8]

编辑:

to test
  let original [2 3 6 2 0 5 7 2 4 8]
  print word "testing: " original
  print report-rand-n original 3
  
  let few-digits [ 0 0 0 1 0 0 0 ]
  print word "testing: " few-digits
  print report-rand-n few-digits 3
  print ""

end

to-report report-rand-n [ base n ]
  ; create list of indices
  let indices ( range 0 (length base)) 
  
  ; To address point 1) in your comment:
  ; keep only indices that correspond to a value > 0 in base
  let indices-over-zero filter [ i -> item i base > 0 ] indices
  
  ; To address point 2 in your comment:
  ; If the length of indices over zero is less than n, replace n
  ; with the length of indices over zero
  if length indices-over-zero < n [
    set n length indices-over-zero
  ]
  let subset n-of n indices-over-zero
  let out ( map [ [ i v ] -> ifelse-value ( member? i subset ) [v] [0] ] indices base)
  report out
end