プロが教える店舗&オフィスのセキュリティ対策術

お世話になります。

配列scoreに格納された値の大きさを比較して、
その順位を取得する(配列rankingに順位を入れる)方法を探しています。
何かいい方法はないでしょうか?


score(4) = (10, 5, 10, 2, 10)
ranking(4) = (1, 4, 1, 5, 1)

A 回答 (2件)

次のコードはscoreの件数が多い場合は処理が遅いですが仕組みは簡単です。


score(i)の値がscore配列内で何回抜かれるかをカウントすることでrankを求めます。たとえば5の場合は10に3回抜かれるのでカウンタ回数は3です。カウンタはランクが1から始まる関係で初期値を1とします。
結果は1+3=4とrankの値となります。

Sub Main()
Dim score() As Integer = {10, 5, 10, 2, 10}
Dim rank(4) As Integer

For i = 0 To 4
rank(i) = 1
For k = 0 To 4
If score(i) < score(k) Then
rank(i) = rank(i) + 1
End If
Next
Next
For i = 0 To 4
Debug.Print("rank(" & i & ") = " & rank(i) & ", ")
Next
End Sub
    • good
    • 0
この回答へのお礼

回答ありがとうございます。
大変、助かりました

お礼日時:2009/08/03 22:48

'個人的にはラムダ式よりC#の匿名メソッドのほうが好きだが,VB.NETにはラムダ式しかない



'行数を減らすのにラムダ式が大活躍したが,反面下手すると初心者お断りのコードになった気がする。

Option Explicit On
Option Strict On
Option Compare Binary
Option Infer Off

Class Q5172313
Shared Sub Main()

Dim x As System.Collections.Generic.List(Of Integer) = new System.Collections.Generic.List(Of Integer)(New Integer(){10, 5, 10, 2, 10})

Dim arr As Integer() = RankArray(x)

For Each i As Integer in arr
System.Diagnostics.Debug.Print(i.ToString())
Next



End Sub

Shared Function RankArray(x As System.Collections.Generic.List(Of Integer)) As Integer()

Dim y As System.Collections.Generic.List(Of Integer) = new System.Collections.Generic.List(Of Integer)(x)

'lambda expression

y.Sort(Function(i As Integer,j As Integer) j - i )

Dim z As Integer() = x.ConvertAll(Function(i As Integer) y.IndexOf(i) + 1).ToArray()

return z

End Function

End Class
    • good
    • 0
この回答へのお礼

VB.NET初心者の自分には難しかったです・・・;
回答ありがとうございました。

お礼日時:2009/08/03 22:50

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!