PDA

View Full Version : Loop Through an Array and Get Smallest Distance

lauranicole1122
09-30-2015, 11:19 AM
I have four spheres and a fish. I would like to assign each sphere distance to an array, run through the array of distances, and have the fish move to the one with the smallest distance. Once it moves to the first object I would then like to repeat the process without the first sphere that the fish already travelled to. I would like to have the fish travel to all four spheres by the end. I am having a hard time figuring out how to do this other then a massive program of if/else statements. If someone would please show me what it would look like in Alice 3 I would appreciate it.

MrMoke
09-30-2015, 12:45 PM
Use a list instead of an array.

If you make a "list" of spheres, then the collision method can check the distance to each one to find the closest. At that point, you can simultaneously move the fish there, and remove the selected sphere from the list so it won't be found again.

lauranicole1122
09-30-2015, 04:36 PM
Thank you for your reply. Will you please tell me how a list is created in Alice 3.2? I haven't been able to find it. I see it in the older versions but not in 3.2.

MrMoke
09-30-2015, 06:34 PM
Oops- Sorry, I didn't see the 3.2 reference, and Alice3 doesn't use lists.:(

Assuming that you are going with the original distances of the objects at the start, there several solutions.

1) Newby Solution- Build an array of spheres. Have the fish say the distances to each array entry, and write them down. Manually change the positions of the spheres in the array to match the distances.

2) Advanced Solution- Create two arrays, one to hold the spheres, and one for distance. When the world starts, first perform a loop that loads the distance to each sphere into the distances array.
Next, sort both the distArray and sphereArray entries into ascending order based on the values in the distArray.

Option 1 will work if you never modify the positions of your objects.

Option 2 is obviously more complicated because it involves a sort routine, but will also allow all of the objects to be moved to random locations when the world starts, and still accomplish the task.

Problem solved, just loop through, and move to, the sphereArray objects in order.

lauranicole1122
10-02-2015, 09:05 AM
Thank you, I have it figured out now!

MrMoke
10-02-2015, 04:43 PM
No Problem. It was actually fun getting it to work with option 2:)