Arithmetic Progressions
October 24, 2017
I continue today working through my backlog of homework problems:
Given an array of at least three distinct positive integers sorted in ascending order, find all triples of array elements that form an arithmetic progression, so that the difference between the first and second elements is the same as the difference between the second and third elements. For instance, in the array (1 2 3 4 6 7 9) there are five triplets in arithmetic progressions: (1 2 3), (2 3 4), (2 4 6), (1 4 7), and 3 6 9).
Your task is to write a program that finds all the arithmetic progressions in an array; for extra credit, do the same thing for geometric progressions, where the ratios of the first to second element and the second to third elements are the same. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
It’s an interesting problem indeed.
It makes me wonder – can one formulate a program to find harmonic progressions of a similarly created array?
Here’s a solution in C++11.
Build/Run:
Output:
Here’s my updated, code, fixing a bug in my last post. My bug arises from checking if unsigned int i is less than 0. I changed size_t to int for that variable.
I originally used ints and my program worked. I changed to size_t and didn’t check if the output was still correct, which led to the bug in my earlier post.
Build/Run:
Output:
Great puzzle! My solution in Python:
@DavidLiu: Your solution takes cubic time to find the triples, the suggested solution takes linear time.
@programmingpraxis, quadratic time, as you mention in the solution.
@Daniel. You are correct. I correctly stated the time complexity of the suggested solution as quadratic in the text of the exercise, but incorrectly stated that it is linear in my comment.
My comment about the time complexity of David Liu’s solution stands: the triply-nested loops
in
array_threes
take cubic time.In Python.
Another Python solution. Using set is convenient. Bisection on x[j+1:] would also work.
Another version. This is faster (in Python) than doing the scan.
That’s a nifty little problem. Here is my take on it, using Julia…
IsArithmetic{T <: Real}(x::Array{T, 1}) = (2x[2] == x[1] + x[3])
IsGeometric{T <: Real}(x::Array{T, 1}) = (x[2]^2 == x[1] * x[3])
IsHarmonic{T <: Real}(x::Array{T, 1}) = (x[2] == (2x[1]*x[3] / (x[1] + x[3])))
function main{T <: Real}(x::Array{T, 1}, pt::AbstractString = “a”)
pt = lowercase(pt)
n = length(x)
end
BTW, I figured it would be nice to include the Harmonic progression option, since that’s an interesting series to consider…