0

I have a sample array as

const arr=[0,2,4,6]

I want to check if they have a common difference in them, which is 2 and yes in above array.

There could be more efficient way to do this. I tried using a simple for loop as:

const arr = [0,2,4,6];
for(let i=0;i<arr.length-1;i++){
  if(arr[i]+2==arr[i+1]){
    console.log(true);
   }
   else{
     console.log(false);   
   }
}

This could give me result as true,true,true and push all values to a new array then check if all are true and finally I would get true

It would be helpful if there is a more efficient way to do this; any help appreciated.

sbolel
  • 3,486
  • 28
  • 45
KcH
  • 3,302
  • 3
  • 21
  • 46
  • https://codereview.stackexchange.com/ – adiga Jun 12 '20 at 06:32
  • Does this answer your question? [JS how to find the greatest common divisor](https://stackoverflow.com/questions/17445231/js-how-to-find-the-greatest-common-divisor) – Justinas Jun 12 '20 at 06:32
  • 1
    @Justinas I don't think OP wants to check if the array has a common divisor. They want to check if the difference between the consecutive items is same through the array. – adiga Jun 12 '20 at 06:33
  • as per eg concerned i would say the difference is `2` i want to check , in more mathematical way ,an arithmetic sequence with difference as `2` hope its clear , `a+(n-1)*d` , `d=2` – KcH Jun 12 '20 at 06:35
  • if any of them don't match just return false immediately – user120242 Jun 12 '20 at 06:36
  • @user120242 yes exactly – KcH Jun 12 '20 at 06:37

4 Answers4

3

Assuming the array is sorted, you can do it pretty simply with .every().

const arr = [0,2,4,6];
const itvl = arr[1] - arr[0];
const result = arr.slice(0, -1).every((n, i) =>
  itvl === arr[i + 1] - n
)
console.log(result);

This starts off by calculating the first interval, then it iterates the array (except the last index) using .every() to test that the next index minus the current one is equal to that pre-calculated index.

  • 1
    In terms of performance, you don't stop as soon as you found a "false", so that's not optimized. – djcaesar9114 Jun 12 '20 at 06:41
  • 3
    @djcaesar9114: It does stop. That's one of the benefits of using `.every()`; it stops as soon as it is proven that not every iteration returns `true`. –  Jun 12 '20 at 06:42
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every , https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some , probably the cleanest way to express this ( – user120242 Jun 12 '20 at 06:45
  • @dj No problem. The `.some()` method is optimized that way too. –  Jun 12 '20 at 06:45
  • so `every` would check for all ? as per links – KcH Jun 12 '20 at 06:46
  • every call to the function in every must return true for every to return true, otherwise false. – user120242 Jun 12 '20 at 06:47
  • +1 for being the only solution using higher a order function instead of explicit looping. And even if it wasn't optimal, it honestly wouldn't invalidate the answer. – gyohza Jun 12 '20 at 06:47
  • @gyohza OP explicitly asked for optimal solution, so likely it's part of the assignment and would invalidate the answer – user120242 Jun 12 '20 at 06:48
  • Optimization is a question of individual implementations. That's pretty tough to track consistently. –  Jun 12 '20 at 06:51
  • For a simple problem like this? If I gave a student an assignment like this and said, find the most efficient way to do this problem, would you really be expecting anything else? Obviously the only thing expected from this is knowing you can terminate the loop early. – user120242 Jun 12 '20 at 06:52
  • I get that @user120242 , thanks again for more exp indeed – KcH Jun 12 '20 at 06:53
  • I was thinking more along the lines of "efficient" != "optimal". But yeah, I guess it always makes sense to go for an optimal solution (if they exist) when you want to improve efficiency. – gyohza Jun 12 '20 at 07:04
  • i have one more q, may i know how to check all this after first values sum to 4 , e.g. `arr=[1,3,4,6,8]` , here check only `4,6,8` excluding `1,3` – KcH Jun 12 '20 at 07:13
  • change slice(0, to slice(indextostartat [slice](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice) – user120242 Jun 12 '20 at 07:13
  • `indextostartat` can be known as ? sorry confused , because it may [0,4,....],[1,3...],[1,0,2,1...] – KcH Jun 12 '20 at 07:16
  • 1
    read what slice does at the link. it'll be good to know anyways – user120242 Jun 12 '20 at 07:27
  • slice i understood , but in my comment may i know how could i get `indextostart` value for diff scenarios mentioned – KcH Jun 12 '20 at 07:37
  • add a condition for sum<=4, or do another check first, and use the index in the slice – user120242 Jun 12 '20 at 07:45
1

You can do this. It's better to stop as soon as you find a false rather than testing all the values.

const arr=[0,2,4,6]

var r = true
for (var i=1; i<arr.length-1 && r; i++) {
  r = ((arr[i+1] - arr[i]) == (arr[i] - arr[i-1]))
}

console.log(r)
djcaesar9114
  • 1,880
  • 1
  • 21
  • 41
1

Checks if numbers sum up to desired sum and if rest of numbers have same difference as desired in comments. (This should be a separate question.)

add up until s >= sum. return false if s isn't equal to set sum
if numbers left <= 2 return true
get difference of first 2 numbers
check difference of numbers, if not same difference return false
differences all same, return true

let arr = [0, 1, 3, 4, 6, 8, 10, 12];
const sum = 4

check = arr => {
let s = 0,
    idx = arr.findIndex(x => (s+=x) >= sum ) + 1

if(s !== sum) return false
if(arr.length - idx < 3) return true

const diff = arr[idx+1] - arr[idx]

while(++idx<arr.length-1)
 if(arr[idx+1] - arr[idx] !== diff) return false
return true
}


arr = [0, 1, 3, 4, 6, 8, 10, 12]
console.log(
check(arr)
)

arr = [0, 1, 3]
console.log(
check(arr)
)

arr = [0, 1, 3, 4, 6, 8, 10, 12, 11]
console.log(
check(arr)
)
user120242
  • 14,918
  • 3
  • 38
  • 52
1

I assume what you mean by difference is the step value. For that, first find the difference between the first two elements ; then check whether the same difference holds for all consecutive values.

const arr = [0, 2, 4, 6];
let flag = true;
diff = arr[1] - arr[0];
for(let i = 1; i < arr.length-1; i++){
           if(arr[i+1] - arr[i]  != diff ){
              flag = false;
              break;
           } 


     }
console.log(flag)

The code assumes the array size is atleast 2. Add an if guard if this is not always guaranteed.

Amal K
  • 4,359
  • 2
  • 22
  • 44
  • 1
    nice (and upvoted!) solution, though you don't need the `else` part, and you're logging twice in case of falsehood – malarres Jun 12 '20 at 07:18