package test.ms;
import java.util.Random;
public class Redistribute2 {
public static void main(String[] args) {
//define the array
int[] s = {1,5,4,3,6,9,8,7,0,8,5,6,7,2};
// before redistribute output
System.out.println("before redistribute:");
for(int i = 0 ; i<s.length; i++){
System.out.print(s[i]+" ");
}
// invoke the method
shuffle(s,new Random());
System.out.println();
// after redistribute output
System.out.println("after redistribute:");
for(int i = 0 ; i<s.length; i++){
System.out.print(s[i]+" ");
}
}
// using the random get the random number
public static void shuffle(int[] array, Random random){
for(int i = array.length; i >= 1; i--){
swap(array,i-1,random.nextInt(i));
}
}
// the two number swap in the array
public static void swap(int[] array, int i , int j){
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
before redistribute: 1 5 4 3 6 9 8 7 0 8 5 6 7 2 after redistribute: 9 8 7 8 0 6 1 6 5 5 2 3 7 4
package test.ms;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Random;
import java.util.Set;
public class Redistribute {
public static void main(String[] args) {
int[] s = {1,5,4,3,6,9,8,7,0,8,5,6,7,2};
redistribute(s);
}
public static void redistribute(int[] s){
Random random = new Random();
Set<Integer> set = new LinkedHashSet<Integer>();
// redistribute the index
while(true){
int t =random.nextInt(s.length);
set.add(t);
if(set.size()== s.length)
break;
}
System.out.println("before redistribute:");
for(int i = 0 ; i<s.length; i++){
System.out.print(s[i]+" ");
}
System.out.println();
System.out.println("redistribute the index ");System.out.println(set);
int [] out = new int[s.length];
int count = 0;
for(Iterator<Integer> iterator = set.iterator(); iterator.hasNext();){
out[count] = s[iterator.next()];
count++;
}
// out the result;
System.out.println("after redistribute:");
for(int i = 0 ; i<s.length; i++){
System.out.print(out[i]+" ");
}
}
}
before redistribute: 1 5 4 3 6 9 8 7 0 8 5 6 7 2 redistribute the index [6, 2, 9, 1, 10, 5, 11, 4, 12, 3, 7, 8, 0, 13] after redistribute: 8 4 8 5 5 9 6 6 7 3 7 0 1 2
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有