在一系列数字中查找第一个和最后一个数字

时间:2019-04-30 09:52:53

标签: vb.net math mod

想象一下从-133到+71的数字范围。

我想找到除以20的范围内的第一个和最后一个数字:在这种情况下,它将是-120和+60。

我可以编写一个For循环来测试每个值并存储所需的值:

Dim resultFirst, resultLast As Integer
Dim FirstFound As Boolean = False
For a As Integer = -133 To 71
    If a Mod 20 = 0 Then
        If FirstFound = False Then
            resultFirst = a
            FirstFound = True
        End If
        resultLast = a
    End If
Next

但是我怀疑有一个更简单的公式。

3 个答案:

答案 0 :(得分:4)

您可以使用Enumerable.Range()和LINQ方法WhereMinMax

Dim resultFirst As Integer
Dim resultLast As Integer
Dim min As Integer = -133
Dim max As Integer = 71
Dim div As Integer = 20

resultFirst = Enumerable.Range(min, max - min + 1).Where(Function(x) x Mod div = 0).Min()
resultLast = Enumerable.Range(min, max - min + 1).Where(Function(x) x Mod div = 0).Max()

答案 1 :(得分:1)

您可以使用以下命令获取第一个和最后一个可被20整除的值:

Dim fromValue As Integer = -133
Dim first As Integer = (fromValue - (fromValue Mod 20)) + IIf(fromValue > 0 And fromValue Mod 20 <> 0, 20, 0)

Dim toValue As Integer = 71
Dim last As Integer = (toValue - (toValue Mod 20)) - IIf(toValue < 0 And toValue Mod 20 <> 0, 20, 0)

您还可以使用上面的公式创建一个函数:

Private Function GetResult(ByVal fromInt As Integer, ByVal toInt As Integer, ByVal divider As Integer) As Integer()

    'set the real from and to value from parameter.
    Dim fromValue As Integer = Math.Min(fromInt, toInt)
    Dim toValue As Integer = Math.Max(fromInt, toInt)

    'get the first and last number dividable by divider between numbers.
    Dim first As Integer = (fromValue - (fromValue Mod divider)) + IIf(fromValue > 0 And fromValue Mod divider <> 0, divider, 0)
    Dim last As Integer = (toValue - (toValue Mod divider)) - IIf(toValue < 0 And toValue Mod divider <> 0, divider, 0)

    If first > toValue Or last < fromValue Then
        Return {}
    Else
        Return {first, last}
    End If
End Function

上述功能的一些测试用例:

GetResult(-133, 71, 20)   '0: -120; 1: 60
GetResult(71, -133, 20)   '0: -120; 1: 60
GetResult(100, 119, 20)   '0: 100;  1: 100
GetResult(-113, -112, 20) 'empty array
GetResult(120, 140, 20)   '0: 120;  1: 140

答案 2 :(得分:1)

尝试这个

  Dim s As IEnumerable(Of Integer) =
                Enumerable.Range(-133, 133 + 72)

        Dim minV As Integer = s.AsEnumerable().Where(Function(n) n Mod 20 = 0).Min(Function(n) n)

        Dim maxV As Integer = s.AsEnumerable().Where(Function(n) n Mod 20 = 0).Max(Function(n) n)

        Console.WriteLine(minV.ToString() & " " & maxV.ToString())
        Console.ReadLine()