Skip to content

Instantly share code, notes, and snippets.

Created December 3, 2016 08:09
Show Gist options
  • Save anonymous/64c228157fd0df52ee3dbbac3ae24e53 to your computer and use it in GitHub Desktop.
Save anonymous/64c228157fd0df52ee3dbbac3ae24e53 to your computer and use it in GitHub Desktop.
ArithGeo created by wwebby1 - https://repl.it/E5tx/2
//check if a sequence follows an arithmetic or geometric pattern. return -1 if neither
function ArithGeo(arr) {
var arithchecker = false;
var geochecker = false;
for(var i = 1; i < arr.length; i++)
{
var diff1 = arr[i] - arr[i-1];
var diff2 = arr[i+1] - arr[i];
if(diff1 == diff2)
arithchecker = true;
else
arithchecker = false;
break;
}
for(var j = 1; j < arr.length; j++){
var dif1 = arr[j] - arr[j-1];
var dif2 = arr[j+1] - arr[j]
var dif3 = arr[j+2] - arr[j+1];
var ratio1 = dif2/dif1;
var ratio2 = dif3/dif2;
if(ratio1 == ratio2)
geochecker = true;
else
geochecker = false;
break;
}
if(arithchecker===true)
console.log("Arithmetic");
else if(geochecker===true)
console.log("Geometric");
else
console.log(-1);
}
// keep this function call here
ArithGeo([1, 2, 3, 4] ) ;
ArithGeo([2, 4, 8, 16]);
ArithGeo([1, 3, 6, 9]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment