Skip to content

Commit

Permalink
Sum of differences in array
Browse files Browse the repository at this point in the history
  • Loading branch information
PheRum committed Jun 14, 2024
1 parent ef0d2d3 commit 5270b30
Show file tree
Hide file tree
Showing 5 changed files with 34 additions and 3 deletions.
13 changes: 13 additions & 0 deletions 8_kyu/Sum of differences in array/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
## Sum of differences in array

https://www.codewars.com/kata/5b73fe9fb3d9776fbf00009e

Your task is to sum the differences between consecutive pairs in the array in descending order.

Example
[2, 1, 10] --> 9
In descending order: [10, 2, 1]

Sum: (10 - 2) + (2 - 1) = 8 + 1 = 9

If the array is empty or the array has only one element the result should be 0 (Nothing in Haskell, None in Rust).
8 changes: 8 additions & 0 deletions 8_kyu/Sum of differences in array/index.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { sumOfDifferences } from "./index";

describe("Tests", () => {
it("example", () => {
expect(sumOfDifferences([1, 2, 10])).toBe(9);
expect(sumOfDifferences([-3, -2, -1])).toBe(2);
});
});
11 changes: 11 additions & 0 deletions 8_kyu/Sum of differences in array/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
export function sumOfDifferences(arr: number[]): number {
arr.sort((a, b) => b - a);

let sum = 0;

for (let i = 0; i < arr.length - 1; ++i) {
sum += arr[i] - arr[i + 1];
}

return sum;
}
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@

### Katas solved

`Total`: 73 \
`8_kyu`: 56 \
`Total`: 74 \
`8_kyu`: 57 \
`7_kyu`: 13 \
`6_kyu`: 4 \
`5_kyu`: 0 \
Expand Down
1 change: 0 additions & 1 deletion kata.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
8 kyu - Sum of differences in array - https://www.codewars.com/kata/5b73fe9fb3d9776fbf00009e
8 kyu - Duck Duck Goose - https://www.codewars.com/kata/582e0e592029ea10530009ce
8 kyu - You only need one - Beginner - https://www.codewars.com/kata/57cc975ed542d3148f00015b
8 kyu - pick a set of first elements - https://www.codewars.com/kata/572b77262bedd351e9000076
Expand Down

0 comments on commit 5270b30

Please sign in to comment.