From 45021efd308fe81fe6d4227cf6258bc46615f135 Mon Sep 17 00:00:00 2001 From: Hidemichi Shimura Date: Mon, 9 Jan 2023 13:59:44 -0800 Subject: [PATCH 1/2] solve 1437. Check If All 1's Are at Least Length K Places Away --- ...ll-1s-are-at-least-length-k-places-away.js | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 1437.check-if-all-1s-are-at-least-length-k-places-away.js diff --git a/1437.check-if-all-1s-are-at-least-length-k-places-away.js b/1437.check-if-all-1s-are-at-least-length-k-places-away.js new file mode 100644 index 00000000..4ecfb1b6 --- /dev/null +++ b/1437.check-if-all-1s-are-at-least-length-k-places-away.js @@ -0,0 +1,29 @@ +/* URL of this problem + * https://leetcode.com/problems/check-if-all-1s-are-at-least-length-k-places-away/description/ + * + * @param {number[]} nums + * @param {number} k + * @return {boolean} + */ + +var kLengthApart = function(nums, k) { + const OneIdxes = []; + let IsKLenApart = true; + + // Create an array of 1's indexes in nums in an order of occurrence + nums.forEach((num, idx) => { + if (num === 1) { + OneIdxes.push(idx); + } + }); + for (let i = 0; i < OneIdxes.length - 1 && IsKLenApart; i++) { + // Caluculate the distance between two of 1 + const Distance = Math.abs(OneIdxes[i] - OneIdxes[i + 1]) - 1; + + IsKLenApart = Distance >= k ? true : false; + } + + return IsKLenApart; +}; + +module.exports = kLengthApart; \ No newline at end of file From c32d1078e8870c48ae98784a986e4dee9440d5e6 Mon Sep 17 00:00:00 2001 From: Hidemichi Shimura Date: Mon, 9 Jan 2023 14:00:00 -0800 Subject: [PATCH 2/2] test function kLengthApart --- kLengthApart.test.js | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 kLengthApart.test.js diff --git a/kLengthApart.test.js b/kLengthApart.test.js new file mode 100644 index 00000000..8effbeda --- /dev/null +++ b/kLengthApart.test.js @@ -0,0 +1,13 @@ +const kLengthApart = require("./1437.check-if-all-1s-are-at-least-length-k-places-away"); + +test("Return true if all 1's are at least k places away from each other", () => { + expect(kLengthApart([1,0,0,0,1,0,0,1], 2)).toBeTruthy(); +}); + +test("Return false if any pair of 1's has less than k places in between", () => { + expect(kLengthApart([1,0,0,1,0,1], 2)).toBeFalsy(); +}); + +test("Return true if the argument nums comprises only 1s and the argument k is 0", () => { + expect(kLengthApart([1,1,1,1,1], 0)).toBeTruthy(); +}); \ No newline at end of file