Aug. 13th, 2015

madbernard: a long angled pier (Default)
Just did a Coderbyte challenge that was, "given an array of numbers that could be positive or negative but which will not include 0, return 'Arithmetic' for arrays where there's the same distance between all the numbers, 'Geometric' for arrays where there's the same multiple between all the numbers, and -1 for everything else." My answer isn't the best it could possibly be (I feel that I'm using Math.abs poorly, and I should have taken a moment more to make the reduce part bring back the biggest number in the difference array... averages can be deceiving), but looking at answers from unnamed other people, several of them don't even work. This one only compares the gap in numbers of the first two and last two in the array:
function ArithGeo(arr) { 
  var isArithmetic=(arr[1]-arr[0]==arr[arr.length-1]-arr[arr.length-2]);
  var isGeometric=(arr[1]/arr[0]==arr[arr.length-1]/arr[arr.length-2]);
  // code goes here  
  if(!isArithmetic&&!isGeometric){//is not special
    return -1;
  }else{
    return (isArithmetic)?'Arithmetic':'Geometric';
  }
}
It can be defeated with [1,2,45,99,100]. I saw this same pattern three times in like six answers I looked over. Interesting to catch stuff that the tests don't. When I started this post I was feeling a cheerful about not being at the bottom of the heap, but now I'm a bit sad. Anyway, here's my answer. Tell me about better ways of checking that every number in an array is the same... I could have done another for loop, "if difference array [i] !== difference array [0] return false"...
function ArithGeo(arr) { 
  var geo = [];
  var arith = [];
  for (var i = 0; i < arr.length - 1; i++) {
    geo.push(Math.abs(arr[i + 1] / arr[i]));
    arith.push(Math.abs(arr[i + 1] - arr[i]));
  }
  var sumGeo = geo.reduce(function(prev, curr){
    return prev + curr;
  });
  var sumArith = arith.reduce(function(prev, curr){
    return prev + curr;
  });
  if (sumGeo / geo.length === geo[0]) {return 'Geometric';}
  if (sumArith / arith.length === arith[0]) {return 'Arithmetic';}
  return -1; 
}

November 2022

S M T W T F S
  12345
6789101112
1314 1516171819
20212223242526
27282930   

Most Popular Tags

Style Credit

Expand Cut Tags

No cut tags
Page generated Jun. 23rd, 2025 03:34 pm
Powered by Dreamwidth Studios