JAVA-数组乱序

实现步骤

  1. 假设有一组数组numbers
  2. 从数组中最后一个元素开始遍历
  3. 设置一个随机数作为循环中遍历到的元素之前的所有元素的下标,即可从该元素之前的所有元素中随机取出一个
  4. 每次将随机取出的元素与遍历到的元素交换,即可完成乱序

实例如下: 

import java.util.Arrays;
public class R18 {
	public static void main(String[] args) {
		int[] numbers= {12,34,23,56,17,27};
		for(int k=0;k<2;k++) {
		for(int i=numbers.length-1;i>0;i--) {
			int index=(int)(Math.random()*i);
			numbers[index]=numbers[i]^numbers[index];
			numbers[i]=numbers[i]^numbers[index];
			numbers[index]=numbers[i]^numbers[index];
		}
			}
		System.out.println(Arrays.toString(numbers));
		String[] playMusicList = { "1反方向的钟", "2七里香", "3半岛铁盒", "4双节棍", "5晴天", "6青花瓷", "7一路向北", "8稻香" };
		for(int i=playMusicList.length-1;i>0;i--) {
			int index=(int)(Math.random()*i);
			 String temp=playMusicList[i];
			 playMusicList[i]=playMusicList[index];
			 playMusicList[index]=temp;
		}
		System.out.println(Arrays.toString(playMusicList));
		String[] role = { "安琪拉", "白起", "妲己", "狄仁杰", "典韦", "韩信", "老夫子", "刘禅", "鲁班七号", "墨子", "孙膑", "孙尚香", "孙悟空", "项羽",
				"亚瑟", "周瑜", "庄周", "蔡文姬" };
		for(int i=role.length-1;i>0;i--) {
			int index2=(int)(Math.random()*i);
			String temp1=role[index2];
			role[index2]=role[i];
			role[i]=temp1;
		}
		System.out.println(Arrays.toString(role));
		int[] numbers2=new int[7];	
	}	
}

代码执行结果:

[23, 17, 56, 12, 27, 34]
[2七里香, 7一路向北, 8稻香, 3半岛铁盒, 4双节棍, 5晴天, 6青花瓷, 1反方向的钟]
[墨子, 妲己, 庄周, 安琪拉, 孙膑, 周瑜, 孙尚香, 亚瑟, 老夫子, 刘禅, 韩信, 典韦, 项羽, 狄仁杰, 白起, 孙悟空, 蔡文姬, 鲁班七号]

洗牌算法

洗牌算法也是用数组乱序的方法实现 ,实例如下:

import java.util.Arrays;
public class R21 {
	public static void main(String[] args) {
		String[] num= {"A","2","3","4","5","6","7","8","9","10","j","q","k"};
		String[] num1= {"♥","♠","♦","♣"};
		String[] num3=new String[num.length*num1.length];
		String[] num4=new String[num3.length/4];
		String[] num5=new String[num3.length/4];
		String[] num6=new String[num3.length/4];
		String[] num7=new String[num3.length/4];
		int counter=0;
		int index=0;
		for(int i=0;i

执行结果如下: 

玩家1:[10♠, j♣, 4♠, 4♣, 4♥, 6♦, 10♦, j♦, 5♥, A♦, 3♦, k♥, 10♥]
玩家2:[7♣, q♣, 2♣, 6♠, 5♣, 6♥, 9♥, q♠, 9♦, 8♥, 8♦, 7♠, A♠]
玩家3:[A♣, 3♣, 10♣, q♦, j♥, 5♦, 9♣, 7♥, 2♠, 5♠, 8♣, 2♦, 9♠]
玩家4:[k♦, 3♥, q♥, 6♣, 3♠, 7♦, 8♠, j♠, 2♥, 4♦, A♥, k♠, k♣]

 

 

 

 

你可能感兴趣的:(java,python,算法)