|
-
Jul 27th, 2014, 04:32 PM
#1
Re: How to order array results??
Well, it looks like you need to keep track of the index of the cars, when you sort.
You only have a single variable that you are trying to use to track two things,
It looks like you are using index + 1 as the car number and setting car(i) to that in this line
VehicleAdding: Car(i) = i + 1
but later set Car(i) to the computed value, and you have different versions of that.
Car(i) = POP * LPA 'PricePerAnnum (in pence) = PriceOfFuel x LitresUsedPerYear
So, one way you can sort the values and keep track of the index, is to use put the indexes in an array and move them around in order based on the values the indexes point to.
Ident is excellent at lambda and LinQ, whereas I am not, so there are probably several ways to improve this basic example, but this is a quick off the cuff example where you sort the indexes to order the array, thus you keep the index numbers (car number) and the values associated with them, so you can use them, as is printed out in the last loop.
Code:
Public Class Form1
Dim cars() As Single = {4.23, 7.23, 2.58, 5.67, 3.28, 9.12, 7.25, 8.15, 4.36}
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
'An index array to keep track of car number to car value association
'Initialize the array
Dim idx(UBound(cars)) As Integer 'I should learn linq/lambda to make some of these tasks simpler
For i As Integer = 0 To idx.Count - 1
idx(i) = i
Next
'simple, unoptimized bubble sort (sorts the index (car number) based on car value the index points to)
For i = UBound(idx) To 1 Step -1
For j = 0 To i - 1
If cars(idx(j)) > cars(idx(j + 1)) Then 'if this car's value is greater than the one following
idx(j) = idx(j) Xor idx(j + 1) 'swap the two indexes (using 3 xor operations)
idx(j + 1) = idx(j) Xor idx(j + 1)
idx(j) = idx(j) Xor idx(j + 1)
End If
Next
Next
'Display order in the output window of the IDE (sometimes in the Immediate window if that option is selected)
For i As Integer = 0 To UBound(idx)
Debug.Print(String.Format("Car {0}, {1}", idx(i), cars(idx(i))))
Next
End Sub
End Class
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|