Skip to content

Commit 51b6a37

Browse files
committed
[Hacker Rank]: Minimum Absolute Difference in an Array solved ✓
1 parent 02a69f4 commit 51b6a37

File tree

2 files changed

+81
-0
lines changed

2 files changed

+81
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import logger from '../../logger';
2+
3+
import { minimumAbsoluteDifference } from './minimumAbsoluteDifference';
4+
5+
describe('problem 00XX', () => {
6+
it('Minimum Absolute Difference in an Array border case', () => {
7+
expect.assertions(1);
8+
9+
expect(() => {
10+
minimumAbsoluteDifference([]);
11+
}).toThrow('Empty input');
12+
});
13+
14+
it('Minimum Absolute Difference in an Array Test case 0', () => {
15+
expect.assertions(1);
16+
17+
const input = [3, -7, 0];
18+
const solutionFound = 3;
19+
20+
const calculated = minimumAbsoluteDifference(input);
21+
22+
logger.info(
23+
`Minimum Absolute Difference in an Array Test case 0: ${calculated}`
24+
);
25+
26+
expect(calculated).toStrictEqual(solutionFound);
27+
});
28+
29+
it('Minimum Absolute Difference in an Array Test case 1', () => {
30+
expect.assertions(1);
31+
32+
const input = [-59, -36, -13, 1, -53, -92, -2, -96, -54, 75];
33+
const solutionFound = 1;
34+
35+
const calculated = minimumAbsoluteDifference(input);
36+
37+
logger.info(
38+
`Minimum Absolute Difference in an Array Test case 1: ${calculated}`
39+
);
40+
41+
expect(calculated).toStrictEqual(solutionFound);
42+
});
43+
});
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/**
2+
* Minimum Absolute Difference in an Array
3+
*
4+
* https://www.hackerrank.com/challenges/minimum-absolute-difference-in-an-array
5+
*
6+
* <DESCRIPTION>
7+
*
8+
*/
9+
10+
import { logger as console } from '../../logger';
11+
12+
export function minimumAbsoluteDifference(arr: number[]): number {
13+
if (arr.length == 0) {
14+
throw new Error('Empty input');
15+
}
16+
17+
const sortedNums = arr.splice(0).sort();
18+
console.log(`sortedNums: ${sortedNums}`);
19+
20+
let result: number = Math.abs(sortedNums[0] - sortedNums[1]);
21+
22+
for (let i = 0; i < sortedNums.length - 1; i++) {
23+
const a = sortedNums[i];
24+
const b = sortedNums[i + 1];
25+
26+
const diff = Math.abs(a - b);
27+
28+
console.debug(
29+
`(i: ${i}, i+1: ${i + 1}) => |a - b| = |${a} - ${b}| = ${diff}`
30+
);
31+
32+
result = Math.min(result, diff);
33+
}
34+
35+
return result;
36+
}
37+
38+
export default { minimumAbsoluteDifference };

0 commit comments

Comments
 (0)