From 201e4b52b2753240dcd2daa8c90064c27fe28cfa Mon Sep 17 00:00:00 2001 From: Hidemichi Shimura Date: Fri, 30 Dec 2022 20:34:33 -0800 Subject: [PATCH 1/2] solve 1636. Sort Array by Increasing Frequency --- 1636.sort-array-by-increasing-frequency.js | 35 ++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 1636.sort-array-by-increasing-frequency.js diff --git a/1636.sort-array-by-increasing-frequency.js b/1636.sort-array-by-increasing-frequency.js new file mode 100644 index 00000000..d0f8b004 --- /dev/null +++ b/1636.sort-array-by-increasing-frequency.js @@ -0,0 +1,35 @@ +/* URL of this problem + * https://leetcode.com/problems/sort-array-by-increasing-frequency/description/ + * + * @param {number[]} nums + * @return {number[]} + */ + +var frequencySort = function(nums) { + const UniqueNums = [...new Set(nums)]; + const SortedNums = []; + + // Make an array of each unique number and push the array to SortedNums + for (let i = 0; i < UniqueNums.length; i++) { + const CurrNums = nums.filter(num => num === UniqueNums[i]); + + SortedNums.push(CurrNums); + } + SortedNums.sort((currNums, nextNums) => { + const CurrLen = currNums.length; + const NextLen = nextNums.length; + const CurrNum = currNums[0]; + const NextNum = nextNums[0]; + + // Sort the arrays in a descending order by its number if the arrays have the same occurrence + if (CurrLen === NextLen) { + return NextNum - CurrNum; + } + // Sort the arrays in an ascending order by occurrence + return CurrLen - NextLen; + }); + + return SortedNums.flat(); +}; + +module.exports = frequencySort; \ No newline at end of file From 05fae689c73501a8d5dccd6af52f932e6f15952b Mon Sep 17 00:00:00 2001 From: Hidemichi Shimura Date: Fri, 30 Dec 2022 20:34:55 -0800 Subject: [PATCH 2/2] test function frequencySort --- frequencySort.test.js | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 frequencySort.test.js diff --git a/frequencySort.test.js b/frequencySort.test.js new file mode 100644 index 00000000..a25218a7 --- /dev/null +++ b/frequencySort.test.js @@ -0,0 +1,14 @@ +const frequencySort = require("./1636.sort-array-by-increasing-frequency"); + +test("Return the array sorted by increasing frequency and decreasing value for the same frequency", () => { + expect(frequencySort([1,1,2,2,2,3])).toEqual([3,1,1,2,2,2]); +}); + +test("Return the array with negative values sorted by increasing frequency and decreasing value for the same frequency", () => { + expect(frequencySort([-1,1,-6,4,5,-6,1,4,1])).toEqual([5,-1,4,4,-6,-6,1,1,1]); +}); + +test("Return the array with Infinity and -Infinity sorted by increasing frequency and decreasing value for the same frequency", () => { + expect(frequencySort([1,1,1,-Infinity,-Infinity,Infinity,Infinity])) + .toEqual([Infinity,Infinity,-Infinity,-Infinity,1,1,1]); +}); \ No newline at end of file