Created
March 5, 2022 15:21
-
-
Save mchambaud/cdf5d9ef7ffdfa34eb2630e692e3c5e3 to your computer and use it in GitHub Desktop.
Array Challenge Arithmetic / Geometric
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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