gpt4 book ai didi

arrays - 按从小到大排列的元素索引

转载 作者:行者123 更新时间:2023-12-04 20:32:24 25 4
gpt4 key购买 nike

我正在尝试为组平衡问题提供初始解决方案,但我似乎陷入了听起来应该很简单的事情上。

基本上我有一个权重数组(随机整数),例如

W() = [1, 4, 3, 2, 5, 3, 2, 1]

我想创建另一个长度相同的数组,其中数字 1 到数组的大小分别代替最小到最大的数字,例如
S() = [1, 7, 5, 3, 8, 6, 4, 2]

对于重复项,第一次出现被视为较小的索引。

我最初使用 BubbleSort 算法,但不幸的是,这不允许我以所需格式提供输出。

我知道这是一个非常具体的问题,但任何帮助将不胜感激。

最佳答案

试试这个,让我知道它是如何为你工作的:

Option Base 0
Option Explicit
Option Compare Text

Sub tmpSO()

Dim tmp As Double
Dim strJoin As String
Dim i As Long, j As Long
Dim W As Variant, S() As Double, X() As Long

'Load W
W = Array(1, 4, 3, 2, 5, 3, 2, 1)

'Set the dimensions for the other arrays
ReDim S(LBound(W) To UBound(W))
ReDim X(LBound(W) To UBound(W))

'Copy W into S
For i = LBound(W) To UBound(W)
S(i) = W(i)
Next i

'Sort S
For i = LBound(S) To UBound(S) - 1
For j = i + 1 To UBound(S)
If S(i) > S(j) Then
tmp = S(j)
S(j) = S(i)
S(i) = tmp
End If
Next j
Next i

'Get the results into X
For i = LBound(S) To UBound(S)
X(i) = WorksheetFunction.Match(W(i), S, 0)
S(WorksheetFunction.Match(W(i), S, 0) - 1) = vbEmpty
Next i

'Print out W (original array)
Debug.Print Join(W, ",")

'Print out x (result array)
For i = LBound(X) To UBound(X)
strJoin = strJoin & "," & X(i)
Next i
Debug.Print mid(strJoin, 2)

End Sub

关于arrays - 按从小到大排列的元素索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43368711/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com