Skip to content

Commit

Permalink
Merge pull request #131 from MikeBeloborodov/8_kyu_sum_of_differences…
Browse files Browse the repository at this point in the history
…_in_array

8 kyu sum of differences in array
  • Loading branch information
MikeBeloborodov committed Apr 8, 2024
2 parents 811f247 + 5c14715 commit 777d44d
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 2 deletions.
17 changes: 17 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,17 @@
### 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).
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { sumOfDifferences } from "./sum_of_differences_in_array";

describe("test cases", () => {
it("should return 9", () => expect(sumOfDifferences([1, 2, 10])).toBe(9));
it("should return 2", () => expect(sumOfDifferences([-3, -2, -1])).toBe(2));
it("should return 0", () => expect(sumOfDifferences([])).toBe(0));
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
export const sumOfDifferences = (arr: number[]): number => {
return [...arr]
.sort((a, b) => b - a)
.reduce(
(sum, next, indx, array) => (!indx ? 0 : sum + (array[indx - 1] - next)),
0,
);
};
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,9 +50,9 @@ npm run push "$description"

### Katas solved

`Total`: 133
`Total`: 134
\
`8_kyu`: 43
`8_kyu`: 44
\
`7_kyu`: 44
\
Expand Down

0 comments on commit 777d44d

Please sign in to comment.