From 3b7d0b4574fbbe8c3bd0fdcc58dc5133edb90c6f Mon Sep 17 00:00:00 2001 From: Lorenzo Iovino Date: Wed, 24 Jan 2024 18:55:09 +0100 Subject: [PATCH] challenge ctci-array-left-rotation --- .gitignore | 3 ++- .../ctci-array-left-rotation.spec.ts | 17 +++++++++++++++++ .../ctci-array-left-rotation.ts | 15 +++++++++++++++ 3 files changed, 34 insertions(+), 1 deletion(-) create mode 100644 src/ctci-array-left-rotation/ctci-array-left-rotation.spec.ts create mode 100644 src/ctci-array-left-rotation/ctci-array-left-rotation.ts diff --git a/.gitignore b/.gitignore index a375727..0573864 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ node_modules build -.idea \ No newline at end of file +.idea +.DS_STORE \ No newline at end of file diff --git a/src/ctci-array-left-rotation/ctci-array-left-rotation.spec.ts b/src/ctci-array-left-rotation/ctci-array-left-rotation.spec.ts new file mode 100644 index 0000000..97b60fc --- /dev/null +++ b/src/ctci-array-left-rotation/ctci-array-left-rotation.spec.ts @@ -0,0 +1,17 @@ +import {describe, it} from "node:test"; +import assert = require("node:assert"); +import {rotLeft} from "./ctci-array-left-rotation"; + +describe("Ctci Array Left Rotation", () => { + describe("rotLeft", () => { + it("an empty array return itself ", () => { + assert.deepStrictEqual(rotLeft([], 100), []) + assert.deepStrictEqual(rotLeft([], 1), []) + assert.deepStrictEqual(rotLeft([], 0), []) + }) + + it("rotate an array of X position should return the array rotated left by X position", () => { + assert.deepStrictEqual(rotLeft([1, 2, 3, 4, 5], 4), [5, 1, 2, 3, 4]); + }) + }); +}) \ No newline at end of file diff --git a/src/ctci-array-left-rotation/ctci-array-left-rotation.ts b/src/ctci-array-left-rotation/ctci-array-left-rotation.ts new file mode 100644 index 0000000..0bb9f89 --- /dev/null +++ b/src/ctci-array-left-rotation/ctci-array-left-rotation.ts @@ -0,0 +1,15 @@ +export function rotLeft(a: Array, d: number): Array { + if(a.length === 0) { + return []; + } + + if(a.length == d) { + return a.reverse(); + } + + const firstElements = a.slice(0, d) + a.splice(0, d); + a = a.concat(firstElements); + + return a; +} \ No newline at end of file