zoukankan      html  css  js  c++  java
  • ShuffleElements(随机打乱数组中的元素)

    给定一个数组,随机打乱数组中的元素,题意很简单直接上代码:

    package Array;
    import java.util.Arrays;
    import java.util.Collections;
    import java.util.Random;
    public class ShuffleElements {
    
    	public static void main(String[] args) {
    		int [] array = {1,2,3,4,5};
    		//随机打乱数组中的元素
    		//int [] result = randomizeArray(1,10);
    		  shuffle();
    		//打印数组中的元素
    		//print(result);
    	}
    	
    	/**
    	 * 打印数组中的元素
    	 * @param result
    	 */
    	private static void print(int[] result) {
    		if (result != null && result.length>0) {
    			for (int i = 0;i<result.length;i++) {
    				System.out.print(result[i]+" ");
    			}
    			System.out.println();
    		}
    		
    	}
    
    	/**
    	 * 随机打乱数组中的数字
    	 * @param array
    	 * @return
    	 */
    	public static int[] randomizeArray(int [] array){
    		Random gen = new Random();
    		for (int i=0;i<array.length;i++) {
    			int randomPosition = gen.nextInt(array.length);//生成0-array.length区间的随机数
    			int temp = array[i];
    			array[i] = array[randomPosition];
    			array[randomPosition] = temp;
    		}
    		
    		return array;
    		
    	}
    	
    	/**
    	 * 随机打乱a-b区间的数据
    	 * @param a
    	 * @param b
    	 * @return
    	 */
    	public static int[] randomizeArray(int a,int b){
    		Random rgen = new Random();
    		
    		int size = b-a+1;//数组的大小
    		int [] array = new int[size];
    		for (int i = a;i<size;i++) {
    			array[i] = a+i;
    		}
    		for (int i=0;i<array.length;i++) {
    			int randomPosition = rgen.nextInt(array.length);//生成0-array.length区间的随机数
    			int temp = array[i];
    			array[i] = array[randomPosition];
    			array[randomPosition] = temp;
    		}
    		
    		print(array);
    		return array;
    	}
    	
    	//jdk中的shuffle方法
    	public static void shuffle(){
    		int[] array = new int[]{1,2,3,4,5};
    		Collections.shuffle(Arrays.asList(array));
    		print(array);
    	}
    	
    	
    	
    	
    	
    	
    	
    	
    	
    	
    	
    	
    	
    	
    	
    	
    	
    }
    

      

  • 相关阅读:
    vue-element-admin 权限的添加
    vue 图标通过组件的方式引用步骤
    linux系统环境下配置vue项目运行环境
    5.5 卷积神经网络(LeNet)
    5.4 池化层
    5.3 多输入通道和多输出通道
    5.2 填充和步幅
    html && CSS
    P2827 [NOIP2016 提高组] 蚯蚓
    5.1 二维卷积层
  • 原文地址:https://www.cnblogs.com/airycode/p/7699819.html
Copyright © 2011-2022 走看看