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

实现一个将 52 张牌随机均等的分给四个人,比如输入 [0,1,2,3....51] ,输出[[1,2,16...],[4,3,6..],[....],[....]] #157

Open
lgwebdream opened this issue Jul 6, 2020 · 5 comments
Labels
算法 teach_tag 顺丰 company

Comments

@lgwebdream
Copy link
Owner

No description provided.

@lgwebdream lgwebdream added 算法 teach_tag 顺丰 company labels Jul 6, 2020
@lgwebdream
Copy link
Owner Author

扫描下方二维码,获取答案以及详细解析,同时可解锁800+道前端面试题。

@523451928
Copy link

function shuffle(arr) {
let length = arr.length
while (length > 0) {
const randomIndex = Math.floor(Math.random() * length)
length -= 1;
[arr[length], arr[randomIndex]] = [arr[randomIndex], arr[length]]
}
return arr
}

const arr = Array.from({ length: 52 }).map((item, index) => index)
function generateArr(arr) {
const res = Array.from({ length: 4 }).map(item => [])
const shuffleArr = shuffle(arr)
for (let i = 0; i < shuffleArr.length; i++) {
const item = shuffleArr[i]
if (i <= 12) {
res[0].push(item)
} else if (i <= 25) {
res[1].push(item)
} else if (i <= 38) {
res[2].push(item)
} else {
res[3].push(item)
}
}
return res
}
generateArr(arr)

@qzruncode
Copy link

function deal() {
    const cards = [];
    for(let i = 0; i < 52; i++) {
      cards.push(i);
    }
    cards.sort((a, b) => (Math.ceil(Math.random() * 52) - 1) - b);
    return [cards.slice(0, 13), cards.slice(13, 26), cards.slice(26, 39), cards.slice(39, 52)];
  }

@AAA611
Copy link

AAA611 commented Aug 26, 2022

function genPlayingCards(num = 52) {
  const playingCards = []
  for (let i = 0; i < num; i++) {
    playingCards.push(i)
  }
  return playingCards
}

function licensing(playingCards, persons = 4) {
  const len = playingCards.length
  let temp
  for (let i = 0; i < len; i++) {
    const index = Math.floor(Math.random() * (len - i))
    temp = playingCards[len - i - 1]
    playingCards[len - i - 1] = playingCards[index]
    playingCards[index] = temp
  }

  const n = Math.floor(len / persons)
  return [playingCards.slice(0, n), playingCards.slice(n, 2 * n), playingCards.slice(2 * n, 3 * n), playingCards.slice(3 * n, 4 * n)]
}
console.log(licensing(genPlayingCards()));

@sun-shaohua
Copy link

function deal() {
const cards = [];
for (let i = 1; i < 53; i++) {
cards.push(i);
}
cards.sort((a, b) => (Math.random() - 0.5));
console.log(cards)
return [cards.slice(0, 13), cards.slice(13, 26), cards.slice(26, 39), cards.slice(39, 52)];
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
算法 teach_tag 顺丰 company
Projects
None yet
Development

No branches or pull requests

5 participants