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

随机生成一个长度为 10 的整数类型的数组,将其排列成下面格式的数组。 #33

Open
madfour opened this issue Mar 2, 2021 · 0 comments
Labels

Comments

@madfour
Copy link
Owner

madfour commented Mar 2, 2021

例如:[2, 10, 3, 4, 5, 11, 10, 11, 20]是随机生成的数组,规定形式是[[2, 3, 4, 5], [10, 11], [20]]

/* 生成随机整数数组
 *  length	数组长度
 *  max		取值最大范围
 */
function randomArray(length = 10, max = 20) {
  return Array.from({
    length
  }, () => ~~(Math.random() * max))
}

// 区间分組 (把0-9,10-19这样的区间组成一个数组)
function newArray(array) {
  return array
    .reduce((acc, c) => {
      let i = ~~(c / 10)
      if (!acc[i]) acc[i] = []
      acc[i].push(c)
      return acc
    }, [])
    .filter(c => !!c)
    .map(arr => Array.from(new Set(arr)).sort())
}

// 把连续的元素组成一个数组
function continueArray(array) {
  return Array.from(new Set(array))
    .sort((a, b) => a - b)
    .reduce(
      (acc, c, i, arr) => {
        if (i === 0) acc[0].push(c)
        else {
          if (arr[i - 1] !== c - 1) acc.push([])
          acc[acc.length - 1].push(c)
        }
        return acc
      },
      [
        []
      ]
    )
}

let arr = randomArray(10, 30)
// 生成的数组例如:[5, 15, 14, 20, 17, 18, 25, 21]
newArray(arr)        // [[5], [14, 15, 17, 18], [20, 21, 25]]
continueArray(arr) // [[5], [14, 15], [17, 18], [20, 21], [25]]
@madfour madfour changed the title 随机生成一个长度为 10 的整数类型的数组,将其排列成一个规定形式的数组。 随机生成一个长度为 10 的整数类型的数组,将其排列成下面格式的数组。 Mar 3, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant