• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

M面经prepare: Shuffle a deck

设计一个shuffle card

用了java. Random Class

 1 package Random;
 2 import java.util.*;
 3 
 4 public class Solution {
 5     static int cardNum = 10;
 6     public int[] shuffle(int[] cards) {
 7         //ArrayList<Integer> res = new ArrayList<Integer>();
 8         Random rnd = new Random();
 9         for(int i=0; i<cardNum; i++){
10             int rand = rnd.nextInt(cardNum-i)+i;
11             int temp = cards[i];
12             cards[i] = cards[rand];
13             cards[rand] = temp;
14         }
15         return cards;
16     }
17 
18     /**
19      * @param args
20      */
21     public static void main(String[] args) {
22         // TODO Auto-generated method stub
23         Solution sol = new Solution();
24         int[] array = new int[cardNum];
25         for (int i=0; i<cardNum; i++) array[i] = i;
26         int[] res = sol.shuffle(array);
27         System.out.println(Arrays.toString(res));
28     }
29 
30 }

 

posted @ 2016-02-17 04:50  neverlandly  阅读(613)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3