-2

I don't know where to start with this. Am I missing some knowledge I would need to know? Any hints you could give me or a solution I could dissect?

user2562240
  • 49
  • 1
  • 3
  • First define a Geometric Sequence (may want to check out Geometric progression). If you don't know what it is, that would be a good place to start. After that try to implement something on your own. If you get stuck, come back. – travis Jul 23 '13 at 21:22
  • 1
    Get the ratio of the first two elements. Then iterate through the array, checking whether the ration of each successive pair is the same. – Barmar Jul 23 '13 at 21:23

1 Answers1

3

A geometric sequence is ar0, ar1, ar2, ... yes?

function isGeometric(arr) {
    if (arr.length <= 2) return true; // special cases
    var a = arr[1],                   // we dont need to test before this
        r = a / arr[0],               // ratio of first 2
        i;
    for (i = 2; i < arr.length; ++i)
        if ((a *= r) !== arr[i])
            return false;
    return true;
}

isGeometric([2, 4, 8]); // true
isGeometric([2, 4, 5]); // false
Paul S.
  • 64,864
  • 9
  • 122
  • 138
  • If you're wondering why I included a special cases above, it's to avoid a possible division by _undefined_. You might also want to give `false` if `arr[0] === 0` or `arr[1] === 0`. And consider how you want to handle the sequence `[0, 0, 0, 0, 0, ...]` – Paul S. Jul 23 '13 at 21:38
  • This won't work if the sequence is deceasing. Or if integer division messes you up in other ways. Try checking that arr[i]*arr[i]=arr[i+1]*arr[i-1] – Teepeemm Jul 24 '13 at 23:46
  • @Teepeemm I can understand division by zero errors, hence my comment, but can you please give an example of a decreasing sequence that will fail – Paul S. Jul 24 '13 at 23:55
  • It turns out that javascript doesn't do integer division, so this should work after all. But in languages where 5/2==2, [2,5,10] and [4,2,0] would return true, while [4,2,1] would return false. It's better to check arr[i]*arr[i]!=arr[i+1]*arr[i-1]. – Teepeemm Jul 25 '13 at 13:49
  • @Teepeemm this is a question about _JavaScript_ though – Paul S. Jul 25 '13 at 15:35
  • Yes, I incorrectly assumed that Javascript does integer division. On the other hand, if someone tries to convert this to another language where the syntax is close enough, they would run into various problems. – Teepeemm Jul 26 '13 at 00:16