java面试题公平算法打乱数组(两种实现方式)_第1页
java面试题公平算法打乱数组(两种实现方式)_第2页
java面试题公平算法打乱数组(两种实现方式)_第3页
java面试题公平算法打乱数组(两种实现方式)_第4页
java面试题公平算法打乱数组(两种实现方式)_第5页
已阅读5页,还剩1页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

Java 面试题:公平算法打乱数组(两种实现方式) 公平算法,打乱数组 这是前几天面试的时候遇见的一道题目,看到这个题首先想到了洗牌程序: 方法一:洗牌程序原理 在 Java.util 包中的 Collections 类中的 shuffle 方法,现在手工实现以下代码如下: 01.package test.ms; 02. 03.import java.util.Random; 04. 05.public class Redistribute2 06.public static void main(String args) 07. 08./define the array 09.int s = 1,5,4,3,6,9,8,7,0,8,5,6,7,2; 10. 11./ before redistribute output 12.System.out.println(“before redistribute:“); 13.for(int i = 0 ; i= 1; i-) 33. 34.swap(array,i-1,random.nextInt(i); 35. 36. 37. 38./ the two number swap in the array 39.public static void swap(int array, int i , int j) 40. 41.int temp = arrayi; 42. 43.arrayi = arrayj; 44. 45.arrayj = temp; 46. 47. 48. 49. swap 方法用于交换数组中的两个数, shuffle 方法 用于 根据随机源 生成的随机数进行交 换。 输出结果如下: 1.before redistribute: 2.1 5 4 3 6 9 8 7 0 8 5 6 7 2 3.after redistribute: 4.9 8 7 8 0 6 1 6 5 5 2 3 7 4 方法二:生成随机索引交换 该方法利用 Set 集合的特性: Set 集合中的数据不重复,生成数组的索引,根据生成的索引 进行交换数据。 实现方式如下: 01.package test.ms; 02. 03.import java.util.Iterator; 04.import java.util.LinkedHashSet; 05.import java.util.Random; 06.import java.util.Set; 07. 08.public class Redistribute 09. 10.public static void main(String args) 11.int s = 1,5,4,3,6,9,8,7,0,8,5,6,7,2; 12.redistribute(s); 13. 14.public static void redistribute(int s) 15.Random random = new Random(); 16. 17.Set set = new LinkedHashSet(); 18. 19./ redistribute the index 20.while(true) 21.int t =random.nextInt(s.length); 22.set.add(t); 23.if(set.size()= s.length) 24.break; 25. 26.System.out.println(“before redistribute:“); 27.for(int i = 0 ; i iterator = set.iterator(); iterator.hasNext(); ) 38.outcount = siterator.next(); 39.count+; 40. 41. 42./ out the result; 43.System.out.println(“after redistribute:“); 44.for(int i = 0 ; is.length; i+) 45.System.out.print(outi+“ “); 46. 47. 48. 49. 这个方法首先生成索引,然后根据新索引进行数据交换,代码都写在 main 方法里了,不是 太好。 生成结果如下: 1.before redistribute: 2.1 5 4 3 6 9 8 7 0 8 5 6 7 2 3.redistribute the index 4.6, 2, 9, 1, 10, 5, 11, 4, 12, 3, 7, 8, 0,

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论