Skip to content

Commit

Permalink
normaliseSequenceDiff
Browse files Browse the repository at this point in the history
  • Loading branch information
ogroppo committed Apr 5, 2024
1 parent 728a521 commit 04b4d3c
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
25 changes: 25 additions & 0 deletions src/math/normaliseSequenceDiff.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { describe, expect, test } from "@jest/globals";
import { normaliseSequenceDiff } from "./normaliseSequenceDiff";

describe("normaliseSequenceDiff", () => {
test("simple", async () => {
expect(normaliseSequenceDiff([])).toStrictEqual([]);
expect(normaliseSequenceDiff([1])).toStrictEqual([0]);
expect(normaliseSequenceDiff([2])).toStrictEqual([0]);
expect(normaliseSequenceDiff([2], { startFrom: -1 })).toStrictEqual([-3]);
expect(normaliseSequenceDiff([1, 2, 3])).toStrictEqual([0, 0, 0]);
expect(normaliseSequenceDiff([1, 2, 4])).toStrictEqual([0, 0, -1]);
expect(normaliseSequenceDiff([2, 4, 6])).toStrictEqual([0, -1, -2]);
expect(normaliseSequenceDiff([2, 2, 6])).toStrictEqual([0, 1, -2]);
expect(normaliseSequenceDiff([-1, 2, 6], { startFrom: 0 })).toStrictEqual([
1, -1, -4,
]);
// untidy sequence
expect(
normaliseSequenceDiff([-1, -10, 6, 4], { startFrom: 0 })
).toStrictEqual([2, 10, -3, -2]);
expect(normaliseSequenceDiff([-1, -10, 6, 4])).toStrictEqual([
-8, 0, -13, -12,
]);
});
});
25 changes: 25 additions & 0 deletions src/math/normaliseSequenceDiff.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { min } from "./min";

export const normaliseSequenceDiff = (
sequence: number[],
options: { startFrom?: number } = {}
): number[] => {
const base = options?.startFrom ?? min(sequence);

const sortedIndexes = getIndexesOfSortedArray(sequence);

return sortedIndexes.reduce((diffArray, sortedIndex, index) => {
diffArray[sortedIndex] = base + index - sequence[sortedIndex];
return diffArray;
}, [] as number[]);
};

const getIndexesOfSortedArray = (arr: number[]): number[] => {
// Create an array of indexes
const indexes = arr.map((_, index) => index);

// Sort the indexes based on the corresponding values in the original array
indexes.sort((a, b) => (arr[a] < arr[b] ? -1 : arr[a] > arr[b] ? 1 : 0));

return indexes;
};

0 comments on commit 04b4d3c

Please sign in to comment.