查找数组是否包含算术级数(序列)的方法是什么

发布于 2024-09-29 20:56:34 字数 206 浏览 5 评论 0原文

我已经对数字数组进行了排序,例如

1, 4, 5 , 6, 8

如何找出该数组是否包含算术级数(序列)?

就像这个例子

4,6,8

 4,5,6

备注:序列中的最小数字是 3

i have sorted array of numbers like

1, 4, 5 , 6, 8

what is the way to find out if this array contain Arithmetic progression (sequence) ?

like in this example

4,6,8

or

 4,5,6

remark : the minimum numbers in sequence is 3

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

夏尔 2024-10-06 20:56:34

您可以通过将其分解为更小的问题来递归地解决此问题,这些问题是:

  • 识别对 {1,4},{1,5}...{6,8}
  • 查找具有相同间隔的序列

对于每对,首先 创建脚手架来运行问题:

Dim number(7) As Integer
Dim result() As Integer
Dim numbers As Integer
Sub FindThem()
number(1) = 1
number(2) = 4
number(3) = 5
number(4) = 6
number(5) = 8
number(6) = 10
number(7) = 15
numbers = UBound(number)
ReDim result(numbers)
Dim i As Integer
For i = 1 To numbers - 2
    FindPairs i
Next
End Sub

现在迭代这些对 边走边

Sub FindPairs(start As Integer)
    Dim delta As Integer
    Dim j As Integer
    result(1) = number(start)
    For j = start + 1 To numbers
        result(2) = number(j)
        delta = result(2) - result(1)
        FindMore j, 2, delta
    Next
End Sub

查找序列

Sub FindMore(start As Integer, count As Integer, delta As Integer)
    Dim k As Integer
    For k = start + 1 To numbers
        step = number(k) - result(count)
        result(count + 1) = number(k) ' should be after the if statement
                                      ' but here makes debugging easier
        If step = delta Then
            PrintSeq "Found ", count + 1
            FindMore k, count + 1, delta
        ElseIf step > delta Then ' Pointless to search further
            Exit Sub
        End If
    Next
End Sub

这只是为了显示结果

Sub PrintSeq(text As String, count As Integer)
    ans = ""
    For t = 1 To count
        ans = ans & "," & result(t)
    Next
    ans = text & " " & Mid(ans, 2)
    Debug.Print ans
End Sub

结果

findthem
Found  1,8,15
Found  4,5,6
Found  4,6,8
Found  4,6,8,10
Found  5,10,15
Found  6,8,10

编辑:哦,当然,数组必须排序!

华泰

You can solve this recursively, by breaking it into smaller problems, which are:

  • Identify the pairs {1,4},{1,5}...{6,8}
  • For each pair, look for sequences with the same interval

First create the scaffolding to run the problems:

Dim number(7) As Integer
Dim result() As Integer
Dim numbers As Integer
Sub FindThem()
number(1) = 1
number(2) = 4
number(3) = 5
number(4) = 6
number(5) = 8
number(6) = 10
number(7) = 15
numbers = UBound(number)
ReDim result(numbers)
Dim i As Integer
For i = 1 To numbers - 2
    FindPairs i
Next
End Sub

Now iterate over the pairs

Sub FindPairs(start As Integer)
    Dim delta As Integer
    Dim j As Integer
    result(1) = number(start)
    For j = start + 1 To numbers
        result(2) = number(j)
        delta = result(2) - result(1)
        FindMore j, 2, delta
    Next
End Sub

Finding sequences as you go

Sub FindMore(start As Integer, count As Integer, delta As Integer)
    Dim k As Integer
    For k = start + 1 To numbers
        step = number(k) - result(count)
        result(count + 1) = number(k) ' should be after the if statement
                                      ' but here makes debugging easier
        If step = delta Then
            PrintSeq "Found ", count + 1
            FindMore k, count + 1, delta
        ElseIf step > delta Then ' Pointless to search further
            Exit Sub
        End If
    Next
End Sub

This is just to show the results

Sub PrintSeq(text As String, count As Integer)
    ans = ""
    For t = 1 To count
        ans = ans & "," & result(t)
    Next
    ans = text & " " & Mid(ans, 2)
    Debug.Print ans
End Sub

Results

findthem
Found  1,8,15
Found  4,5,6
Found  4,6,8
Found  4,6,8,10
Found  5,10,15
Found  6,8,10

Edit: Oh, and of course, the array MUST be sorted!

HTH

心清如水 2024-10-06 20:56:34

首先,我假设您只需要三项或更多项的算术序列。

我建议检查每个数字 a[i] 作为算术序列的开头,并将 a[i+n] 作为下一个数字。

现在您已经有了系列中的前两个术语,您可以找到下一个术语。一般来说,如果 x 是第一项,y 是第二项,则您的项将为 x + i*(yx),第一项为 i = 0。下一项将为 x + 2*(yx)。在数组中搜索该值。如果该值在您的数组中,则您有一个包含三个或更多项目的算术序列!

您可以继续使用 i=3、i=4 等,直到到达数组中未找到的那个。

如果 l 是数组的大小,请对从 0 到 l-2 的所有 i 以及所有 n 执行此操作code> 从 0li-1

唯一需要注意的是,在示例中,这将找到两个序列 4,6,8以及6,8。从技术上讲,它们都是系列中的算术序列。您必须更具体地定义您想要的内容。就您而言,仅检查并消除完全包含在其他进程中的所有进程可能是微不足道的。

First, I will assume that you only want arithmetic sequences of three terms or more.

I would suggest checking each number a[i] as the start of an arithmetic sequence, and a[i+n] as the next one.

Now that you have the first two terms in your series, you can find the next. In general, if x is your first term and y is your second, your terms will be x + i*(y-x), with the first term at i = 0. The next term will be x + 2*(y-x). Search your array for that value. If that value is in your array, you have an arithmetic sequence of three items or more!

You can continue with i=3, i=4, etc. until you reach one that is not found in your array.

If l is the size of your array, do this for all i from 0 to l-2, and all n from 0 to l-i-1

The only major caveat is that, in the example, this will find both sequences 4,6,8 as well as 6,8. Technically, both of them are arithmetic sequences in your series. You will have to more specifically define what you want there. In your case, it might be trivial to just check and eliminate all progressions that are totally contained inside others.

月牙弯弯 2024-10-06 20:56:34

总体思路是选择一个元素作为 a_1,然后选择该元素之后的任何元素作为 a_2,计算差异,然后查看之后是否有任何其他元素与该差异匹配。只要有至少3个元素具有相同的差异,我们就认为它是一个级数。

progression (A, n)
   for i = 1 ... n - 2
      a_1 = A[i]
      for j = i + 1 ... n - 1
         a_2 = A[j]
         d = a_2 - a_1
         S = [ i, j ]
         for k = j + 1 ... n
            if ( d == ( a[k] - a[S.last] ) )
               /* Append the element index to the sequence so far. */
               S += k
         if ( |s| > 2 )
            /* We define a progression to have at least 3 numbers. */
            return true
   return false

您可以修改算法以在丢失之前存储每个集合 S,以计算给定数组 A 的所有级数。假设追加并获取集合 S 的最后一个元素,该算法的运行时间为 O(n^3)恒定时间。

虽然我觉得可能有更有效的解决方案......

The general idea is to pick an element as your a_1, then any element after that one as your a_2, compute the difference and then see if any other elements afterwards that match that difference. As long as there are at least 3 elements with the same difference, we consider it a progression.

progression (A, n)
   for i = 1 ... n - 2
      a_1 = A[i]
      for j = i + 1 ... n - 1
         a_2 = A[j]
         d = a_2 - a_1
         S = [ i, j ]
         for k = j + 1 ... n
            if ( d == ( a[k] - a[S.last] ) )
               /* Append the element index to the sequence so far. */
               S += k
         if ( |s| > 2 )
            /* We define a progression to have at least 3 numbers. */
            return true
   return false

You can modify the algorithm to store each set S before it is lost, to compute all the progressions for the given array A. The algorithm runs in O(n^3) assuming appending to and getting the last element of the set S are in constant time.

Although I feel like there might be a more efficient solution...

岁月染过的梦 2024-10-06 20:56:34

当然不是解决问题的最佳方法,但您可以执行以下操作:

迭代数组中的所有数字对 - 如果我们假设它们是第一和第二级数成员,则每两个数字都完全定义算术序列。因此,了解这两个数字,您可以构建进一步的级数元素并检查它们是否在您的数组中。

如果你只想找到 3 个形成算术级数的数字,那么你可以迭代所有非相邻数字对 a[i] 和 a[j],j > 。 i+1 并检查它们的算术平均值是否属于数组 - 您可以使用区间 ]i,j[ 上的二分搜索来做到这一点。

Certainly not the optimal way to solve your problem, but you can do the following:

Iterate through all pairs of numbers in your array - each 2 numbers fully define arithmetic sequence if we assume that they're 1st and 2nd progression members. So knowing those 2 numbers you can construct further progression elements and check if they're in your array.

If you want just find 3 numbers forming arithmetic progression then you can iterate through all pairs of non-adjacent numbers a[i] and a[j], j > i+1 and check if their arithmetic mean belongs to array - you can do that using binary search on interval ]i,j[.

逐鹿 2024-10-06 20:56:34

这是 Swift 4 中的代码:

extension Array where Element == Int {

    var isArithmeticSequence: Bool {
        let difference = self[1] - self[0]
        for (index, _) in self.enumerated() {
            if index < self.count-1 {
                if self[index + 1] - self[index] != difference {
                    return false
                }
            }
        }
        return true
    }

    var arithmeticSlices: [[Int]] {

        var arithmeticSlices = [[Int]]()
        var sliceSize = 3
        while sliceSize < self.count+1 {

            for (index, _) in self.enumerated() {

                if (index + sliceSize-1) <= self.count - 1 {

                    let currentSlice = Array(self[index...index + sliceSize-1])
                    if currentSlice.isArithmeticSequence {
                        arithmeticSlices.append(currentSlice)
                    }
                }
            }
            sliceSize+=1
        }
        return arithmeticSlices
    }
}


let A = [23, 24, 98, 1, 2, 5]
print(A.arithmeticSlices) // []

let B = [4, 7, 10, 4,5]
print(B.arithmeticSlices) //[[1, 2, 3], [2, 3, 4], [3, 4, 5], [1, 2, 3, 4], [2, 3, 4, 5], [1, 2, 3, 4, 5]]

let C = [4, 7, 10, 23, 11, 12, 13]
print(C.arithmeticSlices) // [[4, 7, 10], [11, 12, 13]]

Here's the code in Swift 4:

extension Array where Element == Int {

    var isArithmeticSequence: Bool {
        let difference = self[1] - self[0]
        for (index, _) in self.enumerated() {
            if index < self.count-1 {
                if self[index + 1] - self[index] != difference {
                    return false
                }
            }
        }
        return true
    }

    var arithmeticSlices: [[Int]] {

        var arithmeticSlices = [[Int]]()
        var sliceSize = 3
        while sliceSize < self.count+1 {

            for (index, _) in self.enumerated() {

                if (index + sliceSize-1) <= self.count - 1 {

                    let currentSlice = Array(self[index...index + sliceSize-1])
                    if currentSlice.isArithmeticSequence {
                        arithmeticSlices.append(currentSlice)
                    }
                }
            }
            sliceSize+=1
        }
        return arithmeticSlices
    }
}


let A = [23, 24, 98, 1, 2, 5]
print(A.arithmeticSlices) // []

let B = [4, 7, 10, 4,5]
print(B.arithmeticSlices) //[[1, 2, 3], [2, 3, 4], [3, 4, 5], [1, 2, 3, 4], [2, 3, 4, 5], [1, 2, 3, 4, 5]]

let C = [4, 7, 10, 23, 11, 12, 13]
print(C.arithmeticSlices) // [[4, 7, 10], [11, 12, 13]]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文