Skip to content

Commit c9a5acb

Browse files
committed
solve arith_geo challenge
1 parent cbf5d1d commit c9a5acb

File tree

1 file changed

+24
-27
lines changed

1 file changed

+24
-27
lines changed

Arith Geo renamed to arith_geo.js

Lines changed: 24 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -35,32 +35,29 @@
3535
* *
3636
***************************************************************************************/
3737

38-
function ArithGeo(arr) {
38+
const ArithGeo = (arr) => {
39+
if (!arr || !arr.length || arr.length <= 2) return false
3940

40-
var arithFlag = true, geoFlag = true;
41-
var diff = arr[1] - arr[0];
42-
43-
for (var i = 2; i < arr.length; i++) {
44-
if ((arr[i] - arr[i-1]) !== diff) {
45-
arithFlag = false;
46-
}
47-
}
48-
if (arithFlag) {
49-
return "Arithmetic";
50-
}
51-
else { // check for geometric pattern
52-
diff = arr[1] / arr[0];
53-
for (var i = 2; i < arr.length; i++) {
54-
if ((arr[i] / arr[i-1]) !== diff) {
55-
geoFlag = false;
56-
}
57-
}
58-
if (geoFlag) {
59-
return "Geometric";
60-
}
61-
else {
62-
return "-1";
63-
}
64-
}
65-
41+
let arith = 0
42+
let geo = 0
43+
44+
arr.forEach((_, i) => {
45+
// (arr[i] - arr[i - 1]) === (arr[i + 1] - arr[i])
46+
if ((arr[i] - arr[i - 1]) === (arr[i + 1] - arr[i])) arith++
47+
48+
// arr[i] * (arr[i] / arr[i - 1]) === arr[i + 1]
49+
if (arr[i] * (arr[i] / arr[i - 1]) === arr[i + 1]) geo++
50+
})
51+
52+
if (arr.length - 2 === arith) return 'Arithmetic'
53+
if (arr.length - 2 === geo) return 'Geometric'
54+
55+
return false;
6656
}
57+
58+
console.log(ArithGeo([2, 4, 6, 8]) === 'Arithmetic') //true
59+
console.log(ArithGeo([2, 4, 5, 8]) === 'Arithmetic') //false
60+
console.log(ArithGeo([2, 4, 8]) === 'Arithmetic') //false
61+
console.log(ArithGeo([2, 6, 18, 54]) === 'Geometric') //true
62+
console.log(ArithGeo([2, 6]) === 'Geometric') //false
63+
console.log(ArithGeo([2, 6, 3]) === 'Geometric') //false

0 commit comments

Comments
 (0)