Skip to content

Commit

Permalink
[Hacker Rank]: Minimum Absolute Difference in an Array solved ✓
Browse files Browse the repository at this point in the history
  • Loading branch information
sir-gon committed Jul 21, 2023
1 parent 02a69f4 commit 51b6a37
Show file tree
Hide file tree
Showing 2 changed files with 81 additions and 0 deletions.
43 changes: 43 additions & 0 deletions src/hackerrank/implementation/minimumAbsoluteDifference.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import logger from '../../logger';

import { minimumAbsoluteDifference } from './minimumAbsoluteDifference';

describe('problem 00XX', () => {
it('Minimum Absolute Difference in an Array border case', () => {
expect.assertions(1);

expect(() => {
minimumAbsoluteDifference([]);
}).toThrow('Empty input');
});

it('Minimum Absolute Difference in an Array Test case 0', () => {
expect.assertions(1);

const input = [3, -7, 0];
const solutionFound = 3;

const calculated = minimumAbsoluteDifference(input);

logger.info(
`Minimum Absolute Difference in an Array Test case 0: ${calculated}`
);

expect(calculated).toStrictEqual(solutionFound);
});

it('Minimum Absolute Difference in an Array Test case 1', () => {
expect.assertions(1);

const input = [-59, -36, -13, 1, -53, -92, -2, -96, -54, 75];
const solutionFound = 1;

const calculated = minimumAbsoluteDifference(input);

logger.info(
`Minimum Absolute Difference in an Array Test case 1: ${calculated}`
);

expect(calculated).toStrictEqual(solutionFound);
});
});
38 changes: 38 additions & 0 deletions src/hackerrank/implementation/minimumAbsoluteDifference.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/**
* Minimum Absolute Difference in an Array
*
* https://www.hackerrank.com/challenges/minimum-absolute-difference-in-an-array
*
* <DESCRIPTION>
*
*/

import { logger as console } from '../../logger';

export function minimumAbsoluteDifference(arr: number[]): number {
if (arr.length == 0) {
throw new Error('Empty input');
}

const sortedNums = arr.splice(0).sort();
console.log(`sortedNums: ${sortedNums}`);

let result: number = Math.abs(sortedNums[0] - sortedNums[1]);

for (let i = 0; i < sortedNums.length - 1; i++) {
const a = sortedNums[i];
const b = sortedNums[i + 1];

const diff = Math.abs(a - b);

console.debug(
`(i: ${i}, i+1: ${i + 1}) => |a - b| = |${a} - ${b}| = ${diff}`
);

result = Math.min(result, diff);
}

return result;
}

export default { minimumAbsoluteDifference };

0 comments on commit 51b6a37

Please sign in to comment.