【问题标题】:Getting the highest value from 3 arrays从 3 个数组中获取最大值
【发布时间】:2013-11-18 16:37:07
【问题描述】:

首先感谢您的宝贵时间。

我有一个程序,我掷 2 个骰子 3 次,它们的值存储在 2 个数组中。

    Dim Attacker(3) As Integer
    Dim Defender(3) As Integer
    Dim i As Integer = 0

    For Each pb As PictureBox In New PictureBox() {Steen1, Steen2, Steen3}

        i += 1

        Select Case RandomNumber.Next(1, 7)
            Case 1 : pb.Image = Game.My.Resources.Een
                Attacker([i]) = 1
            Case 2 : pb.Image = Game.My.Resources.Twee
                Attacker([i]) = 2
            Case 3 : pb.Image = Game.My.Resources.Drie
                Attacker([i]) = 3
            Case 4 : pb.Image = Game.My.Resources.Vier
                Attacker([i]) = 4
            Case 5 : pb.Image = Game.My.Resources.Vijf
                Attacker([i]) = 5
            Case 6 : pb.Image = Game.My.Resources.Zes
                Attacker([i]) = 6
        End Select

    Next

    i = 0

    For Each pb As PictureBox In New PictureBox() {Steen4, Steen5, Steen6}

        i += 1

        Select Case RandomNumber.Next(1, 7)
            Case 1 : pb.Image = Game.My.Resources.Een
                Defender([i]) = 1
            Case 2 : pb.Image = Game.My.Resources.Twee
                Defender([i]) = 2
            Case 3 : pb.Image = Game.My.Resources.Drie
                Defender([i]) = 3
            Case 4 : pb.Image = Game.My.Resources.Vier
                Defender([i]) = 4
            Case 5 : pb.Image = Game.My.Resources.Vijf
                Defender([i]) = 5
            Case 6 : pb.Image = Game.My.Resources.Zes
                Defender([i]) = 6
        End Select

    Next

现在我想让最高的第二高和最低的价值互相“战斗”:

最高价值的攻击者对抗最高价值的防守者, 第二高价值攻击者对抗第二高价值防御者, 最低...

是否有标准方法可以做到这一点,还是我必须使用“一百”个 if 语句?

再次感谢! P.S:我是一名 17 岁的休闲程序员,所以我可能还没有所有的基础知识。

【问题讨论】:

  • 哈哈哈应该是vb.NET谢谢你告诉我
  • 因为明明是VB,所以换了标签。

标签: arrays vb.net visual-studio


【解决方案1】:

您可以对列表进行排序,然后使用Zip 一起遍历它们。

Attacker = Attacker.OrderByDescending(Function(x) x).ToArray()
Defender = Defender.OrderByDescending(Function(x) x).ToArray()

For Each pair In Attacker.Zip(Defender, Function(attack, defend) _
                                      New With { attack, defend })
    ' have the numbers "fight"
Next

分解订购行中的各个部分:

  • OrderByDescending 根据给定选择的元素对数组进行排序 功能。
  • Function(x) x 是一个简单地返回什么的函数 传入其中。因为我们想通过Integers 订购 数组(而不是,例如 Integer 上的某些属性),这是 我们要使用的函数。
  • 由于OrderByDescending 返回一个新的 IEnumerable(Of Integer) 当我们想要修改我们的数组时,我们然后 使用ToArray进行转换
  • 然后我们存储 它(Attacker = 部分)。

【讨论】:

  • 我的大脑无法处理这个问题,我在 (function(x) x).ToArray() 部分中丢失了你的代码我根本不明白这个(什么函数?)我会非常感谢您能向我解释这一点。 (但考虑到我的基础知识和你的时间,我不希望你这样做)
  • @fox125 我已经为答案添加了解释。
  • 我要感谢你(虽然我刚读过我不应该因为我达到 10 声望)这解释了很多!
【解决方案2】:

您可以对数组进行排序。

Array.Sort(Attacker)
Array.Sort(Defender)

然后你可以比较两个数组的索引 0 并继续索引 1 和 2。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-03
    相关资源
    最近更新 更多