20200622招银网络提前批Java第三题洗牌问题

题目简述
牌面有0,1,2,3,4,5,6,7,8,9;
现在需要洗n张牌,从上到下依次是第1张,第二张,…,第n张。
首先把n张牌平均分两堆,左手上半堆,右手下半堆,若n为奇数,则左手比右手多一张。
奇数次洗牌:先放下右手最后一张牌,再放下左手最后一张牌…
偶数次洗牌:先放下左手最后一张牌,再放下右手最后一张牌…

如:1 2 3 4 5 6
分牌:左手:1,2,3 右手:4,5,6
第1次洗牌变为:1,4,2,5,3,6
第2次洗牌变为:5,1,3,4,6,2

输入描述:
给出牌数n,空格后为洗牌次数k,空格后从上到下给出牌序列
输出描述:
k次洗牌后的牌序列,空格隔开
实例:
input:
7 2 1 2 3 4 5 6 7
output:
1 6 2 4 5 7 3

实例解释:
7张牌为1到7,洗2次。
分牌:左手1234,右手567;
第一次洗牌先放右手7,再放左手4,最后为7463521。
注意:先放的牌在下面,后放的在上面,因此牌序列为1253647
再分牌:左手1253,右手647
第二次洗牌先放左手3,再放右手7,最后为3754261,牌序列从上到下为1624573。

import java.util.Scanner;
public class CMBC {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();//牌数
        int k = sc.nextInt();//洗牌次数
        int[] cards = new int[n];//牌序列
        for (int i = 0; i < n; i++) {
            cards[i] = sc.nextInt();
        }

        int[] leftHand = new int[n/2+n%2];//左手牌
        int[] rightHand = new int[n/2];//右手牌
        for (int i = 1; i <= k; i++) {
            //分牌
            System.arraycopy(cards, 0, leftHand, 0, leftHand.length);
            System.arraycopy(cards, leftHand.length, rightHand, 0, rightHand.length);
            //洗牌并合并
            cards = shuffleCards(leftHand, rightHand, i);
        }

        for (int card : cards) {
            System.out.print(card + " ");
        }
    }

    private static int[] shuffleCards(int[] LH, int[] RH, int k) {
        int[] res = new  int[LH.length+RH.length];
        int l = LH.length-1, r = RH.length-1;
        int i = res.length-1;

        if(k % 2 != 0){//奇数次洗牌
            while (r >= 0){
                res[i--] = RH[r--];
                res[i--] = LH[l--];
            }
        }else {//偶数次洗牌
            while (r >= 0){
                res[i--] = LH[l--];
                res[i--] = RH[r--];
            }
        }

        //牌为奇数
        if(l == 0){
            res[0] = LH[0];
        }

        return res;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值