To create an array of 100 different car models, we can use the following code:
main.m276 chars9 lines
In this code, we first define an array of possible car models, and then loop through 100 iterations to randomly assign a car model and a color (represented by a number between 1 and 5) to each element in the cars
array.
To sort the cars
array by color, we can use the sort
function:
main.m89 chars4 lines
In this code, we first extract the color values from each element in the cars
array and store them in a separate array called colors
. We then use the sort
function to sort the colors
array in ascending order, and store the sorted color values in a new array called sorted_colors
. The second output of the sort
function is an array of indices that tells us the order in which the elements in the original colors
array were sorted. We use this array to sort the cars
array in the same order as the sorted_colors
array.
Now the sorted_cars
array contains the same car models as the original cars
array, but they are sorted by color.
gistlibby LogSnag