扑克牌问题

题目

有一堆扑克牌,将牌堆第一张放到桌子上,再将接下来的牌堆的第一张放到牌底,如此往复;

最后桌子上的牌顺序为: (牌底) 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 ]

心灵鸡汤

某剧中的台词:“伤感思念留到胜利后到坟上去说,现在依旧要把上级的任务给完成!”

猜你喜欢

转载自blog.csdn.net/XINpxXIN/article/details/104792457