Skip to content
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

day-19-数组分块 #19

Open
H246802 opened this issue Dec 14, 2018 · 1 comment
Open

day-19-数组分块 #19

H246802 opened this issue Dec 14, 2018 · 1 comment

Comments

@H246802
Copy link
Owner

H246802 commented Dec 14, 2018

给定整数 nm,写一个函数 dispatch(n, m),把 1~n 尽量平均地分成 m 个组

dispatch(6, 3)
// [[1, 2], [3, 4], [5, 6]]
dispatch(9, 2)
// [[1, 2, 3, 4, 5], [6, 7, 8, 9]]
@H246802
Copy link
Owner Author

H246802 commented Dec 14, 2018

function dispatch(n, m) {
  // 首先根据n创建数组
  // 其次,划分数组,将长度为 n 的数组 分成 m 个
  // 分情况 n 是奇数还是偶数,m 是奇数还是偶数,n%m 余数是奇数还是偶数
  let arr = [];
  for (let i = 0; i < n; i++) {
    arr[i] = i + 1;
  }

  // console.log(arr)

  // 求模
  var param = n % m;
  // console.log(param)
  // 每块的长度
  var olength = Math.floor(n / m);
  // console.log(olength)
  var result = [];
  for (let j = 0; j < m; j++) {
    // result[j] = j === 0 ? arr.splice(0, fLength) : arr.splice(0, olength)
    // 不能简单地把余数全部放到第一个位置,应该把余数一个接一个的放在前排子数组中
    if (param > 0) {
      result[j] = arr.splice(0, olength + 1);
      param--;
    } else {
      result[j] = arr.splice(0, olength);
    }
  }
  return result;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant