-
-
Notifications
You must be signed in to change notification settings - Fork 44
/
distributing-candies-fairly.js
69 lines (64 loc) · 2.21 KB
/
distributing-candies-fairly.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
function distribute(m, n) {
if (n <= 0) return [];
// need an n length array to store the candies filled with zeros
// const candies = Array.from({ length: n }).fill(0);
// const candies = Array.from({ length: n }, () => 0);
const candies = Array(n).fill(0);
if (m <= 0) return candies;
const fillCandies = () => {
// iterate up to number of children (n)
for (let i = 0; i < candies.length; i++) {
// increment the current value at the current index by 1
candies[i]++;
// decrement the number of candies left
m--;
// if number of candies is zero // break
if (m === 0) break;
}
};
while(m > 0) {
fillCandies();
}
// if we reach the end of the array and still have candies left, do it again
return candies;
}
function distribute(m, n) {
if (n <= 0) return [];
const candies = Array(n).fill(0);
if (m <= 0) return candies;
while(m > 0) {
for (let i = 0; i < candies.length; i++) {
candies[i]++;
m--;
if (m === 0) break;
}
}
return candies;
}
function distribute(m, n) {
if (n <= 0) return [];
const candies = Array(n).fill(0);
if (m <= 0) return candies;
const minCandies = Math.floor(m / n);
return candies.map((_, i) => {
return i < m % n ? minCandies + 1 : minCandies;
});
}
function distribute(m, n) {
return n <= 0 ? [] : m <= 0 ? Array(n).fill(0) : Array.from({ length: n }, (_, i) => i < m % n ? Math.floor(m / n) + 1 : Math.floor(m / n));
}
console.log(distribute(-5, 10).sort((a,b)=>a-b), [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
console.log(distribute( 0, 10).sort((a,b)=>a-b), [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
console.log(distribute( 5, 10).sort((a,b)=>a-b), [0, 0, 0, 0, 0, 1, 1, 1, 1, 1]);
console.log(distribute(10, 10).sort((a,b)=>a-b), [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]);
console.log(distribute(15, 10).sort((a,b)=>a-b), [1, 1, 1, 1, 1, 2, 2, 2, 2, 2]);
console.log(distribute(-5, 0), []);
console.log(distribute( 0, 0), []);
console.log(distribute( 5, 0), []);
console.log(distribute(10, 0), []);
console.log(distribute(15, 0), []);
console.log(distribute(-5, -5), []);
console.log(distribute( 0, -5), []);
console.log(distribute( 5, -5), []);
console.log(distribute(10, -5), []);
console.log(distribute(15, -5), []);