扑克牌问题 | 刷题打卡

560 阅读1分钟

一、题目描述💯

  • 有一堆扑克牌,将牌堆第一张放到桌子上,再将接下来的牌堆的第一张放到牌底,如此往复; 最后桌子上的牌顺序为: (牌底) 1,2,3,4,5,6,7,8,9,10,11,12,13 (牌顶);
  • 问:原来那堆牌的顺序,用函数实现

二、代码实现🌂

function sortPuke(arr) {
    let keyList = [];//arr对应的key
    let alenList = [];
    let result = [];//最终结果
    let spot = true;
    if (arr.length === 1) {
        return arr
    }
    if (arr.length > 1) {
        for (let index = 0; index < arr.length; index++) {
            alenList.push(index)
        }
        while (alenList.length) {
            if (alenList.length === 1) {
                keyList.push(alenList.shift())
            }
            if (spot && alenList.length > 1) {
                keyList.push(alenList.shift())
            }
            if (!spot && alenList.length > 1) {
                alenList.push(alenList.shift())
            }
            spot = !spot
        }
    }
    for (let j = 0; j < arr.length; j++) {
        result[keyList[j]] = arr[j]
    }
    return result;
}
console.log(sortPuke([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]));
//[ 1, 12, 2, 8, 3, 11, 4, 9, 5, 13, 6, 10, 7 ]

代码下载地址

感谢🙇‍

点赞支持👍