-
Notifications
You must be signed in to change notification settings - Fork 139
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
JavaScript 分组 #37
Comments
怎么算尽量平均 @mqliutie |
@longxingren 例子不就能看出来嘛... |
多给几个例子就是这样的
|
function dispatch(n, m) {
let base = Math.floor(n / m)
let extra = n - m * base
return [...Array(m)].map((v, i) => {
let hasExtra = i < extra
let jMax = base + (hasExtra ? 1 : 0)
let baseNum = i * base + 1 + (hasExtra ? i : extra)
return [...Array(jMax)].map((v, j) => j + baseNum)
})
} |
假如对分开后每个组的数字没有顺序要求的话 function dispatch(n, m) {
var i, j, arrays = [];
for (i = 0; i < m; i++)
arrays.push([]);
for (i = 1, j = 0; i <= n; i++, j = (j+1) % m)
arrays[j].push(i);
return arrays;
}
|
@Wang-NQXB 我记得 |
感觉这个答案比较啰嗦,有什么可优化的,欢迎指出,谢谢
function dispatch (n, m) {
// 每个框子至少可以放几个球
var least = Math.floor(n / m);
// 剩下多少个球
var left = n % m;
// 框子
var buckets = [];
var last = 1;
for (var i = 0; i < m; i++) {
let bucket;
if (left-- > 0) {
bucket = generateArray(last, least + 1);
} else {
bucket = generateArray(last, least);
}
buckets.push(bucket);
last = getMaxOfArray(buckets[i]) + 1;
}
// console.log(buckets, least, left);
return buckets;
}
/**
* 生成数组
* 感觉有更 hack 的方法
* @param base {number} 基址
* @param offset {number} 偏移量
* @return Array
* eg: generateArray(3, 2) => [3, 4]
*/
function generateArray(base, offset) {
var end = base + offset;
var target = [];
for (base; base < end; base++) {
target.push(base);
}
return target;
}
/**
* 获取数组中的最大值
*/
function getMaxOfArray(arr) {
return Math.max.apply(null, arr);
}
// dispatch(10, 6);
// dispatch(4, 5);
dispatch(5, 4); |
这个可以按照顺序分割
|
按自己的思路写个顺序分割,仅供参考可能还有更好的思路。
(6) [Array(4), Array(4), Array(3), Array(3), Array(3), Array(3)] |
|
// 场景化为手持n张牌轮流派给m个人
function dispatch(n, m) {
const arrays = Array(m).fill('').map(() => []);
for (let i = 1; i <= n; i++) {
const flag = (i-1) % m;
arrays[flag].push(i);
}
return arrays;
};
dispatch(10, 6);
dispatch(5, 2); |
|
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
蚂蚁的笔试题
给定整数
n
和m
,写一个函数dispatch
,把1-n
尽量平均地分成m个组如
我自己实现的太烂了,所以想看看大家有没有什么好的实现方式
The text was updated successfully, but these errors were encountered: