Given [10, 20, 20, 30] best = [] bestCount = 0 first group (10) has count of 1 1 > 0, so we have new best best = [10] bestCount = 1 next group (20) has count of 2 2 > 1, so we have new best best = [20] bestCount = 2 next group (30) has count of 1 1 < 2, so no action
Given [10, 20] best = [] bestCount = 0 first group (10) has count of 1 1 > 0, so we have new best best = [10] bestCount = 1 next group (20) has count of 1 1 == 1, so we have another best which we append to best best = [10, 20]
testModeOneResult() { //Two "30" elements const unit = new Stats([40, 10, 30, 20, 30]); this.assertEquals([30], unit.mode()); } testModeTwoResults() { //Two "10" elements, and two "30" elements const unit = new Stats([10, 40, 10, 30, 20, 30]); this.assertEquals([10, 30], unit.mode().sort()); } testModeUniqueValues() { const unit = [20, 10, 30]; //If all elements are unique (no duplicates) then result incudes all elements. this.assertEquals(unit.sort(), unit.mode().sort()); } testModeEmptyCase() { const unit = new Stats([]); assertEquals(null, unit.mode()); }
nums -- list of numbers
let count = this.count() if (count == 0) return null if (count == 1) return this.nums
nums = this.nums nums.sort() len = nums.length first = nums[0] bestMode = [] bestCount = 0 groupMode = first groupCount = 1
let i = 1 While i <= len let next = i < len ? nums[i] : null if (next !== groupMode) if (groupCount === bestCount) bestMode.push(groupMode) else if (groupCount > bestCount) bestMode = [groupMode] bestCount = groupCount groupMode = next groupCount = 1 else groupCount++ i = i + 1 return bestMode
let count = this.count(); if (count == 0) return null; if (count == 1) return this.nums; //...