Skip to content

Instantly share code, notes, and snippets.

@mchambaud
Created March 5, 2022 15:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mchambaud/cdf5d9ef7ffdfa34eb2630e692e3c5e3 to your computer and use it in GitHub Desktop.
Save mchambaud/cdf5d9ef7ffdfa34eb2630e692e3c5e3 to your computer and use it in GitHub Desktop.
Array Challenge Arithmetic / Geometric
function isArithmetic(arr: number[]): boolean {
return arr.every((x: number, i: number) => {
if (i < 2) {
return true;
}
return arr[i] - arr[i-1] === arr[i-1] - arr[i-2];
});
}
function isGeometric(arr: number[]): boolean {
return arr.every((x: number, i: number) => {
if (i < 2) {
return true;
}
if (arr[i-1] == 0 || arr[i-2] == 0) {
return false;
}
return arr[i] / arr[i-1] === arr[i-1] / arr[i-2];
});
}
function arithGeo(arr: number[]): string | -1 {
if (isArithmetic(arr)) {
return 'Arithmetic';
}
if (isGeometric(arr)) {
return 'Geometric';
}
return -1;
}
console.log(arithGeo([5, 10, 15]));
console.log(arithGeo([1,2,4,8]));
console.log(arithGeo([-5, 0, 5]));
console.log(arithGeo([-5, 0, 3]));
console.log(arithGeo([1,2,4,6,8,10]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment