1

I'm trying to select a random set of three unique elements from an array. I'm newish to JS, and I'm constantly tripping over reference behavior that is unexpected (Python is my best language). I think that's happening here, too. This is P5.JS.

Here's my attempt:

var points = [[0,0],[.5*w,0],[w,0],
[0,.5*h],[.5*w,.5*h],[w,.5*h],
[0,h],[.5*w,h],[w,h]];

var vert = [];
var start = int(random(0,8));
vert.push(points[start].slice());
points.splice(start,1);

var middle = int(random(0,7));
vert.push(points[middle].slice());
points.splice(middle,1);

var end = int(random(0,6));
vert.push(points[end].slice());

When I look at the contents of vert, it's clear that I'm not getting the elements that I expected. In particular, I'm never getting any of the last three elements in the original array.

DeltaG
  • 760
  • 2
  • 9
  • 28
  • Can you explain exactly what you're trying to do with the `slice()` and `splice()` functions? Can you please post a [mcve] that demonstrates the problem? (A print statement or something would help show what you're expecting vs what's happening.) – Kevin Workman Mar 07 '18 at 17:54
  • With 'splice()', I'm removing the element that was just randomly chosen, so that I don't select it twice. With 'slice()', I'm making new copies of those elements, because without that, the reference was changing when elements were removed from the array. That's why I was never getting the last three elements. – DeltaG Mar 07 '18 at 18:09
  • So wait, did you already figure this out? If so, please post an answer below so this question stop showing up as needing an answer. – Kevin Workman Mar 07 '18 at 20:51

1 Answers1

1

As noted above, the int() and random() are p5.js functions, and fine. The issue was fixed by removing the .slice() instances in the push() statements:

var vert = [];

var start = int(random(0,8));
vert.push(points[start]);
points.splice(start,1);

var middle = int(random(0,7));
vert.push(points[middle]);
points.splice(middle,1);

var end = int(random(0,6));
vert.push(points[end]);
DeltaG
  • 760
  • 2
  • 9
  • 28