最近开发中,需要随机从好友列表取出指定数字的好友,然后推荐给用户关注,在网上找到了类似的算法,给大家分享下:
01 | package com.zuidaima.util.random; |
03 | import java.util.Random; |
05 | public class TestRandomArray { |
07 | public static void main(String[] args) { |
08 | String[] ids = new String[] { "zuidaima.com" , "javaniu.com" , |
09 | "zuidaima" , "最代码" , "java牛" , "netbeans" , "eclipse" , "jsp" , |
10 | "jstl" , "javaniu" , "jgroups" , "java" , "spring" , "freemarker" , |
11 | "hibernate" , "struts" }; |
12 | Random r = new Random(); |
13 | String strarray[] = new String[ 5 ]; |
15 | for ( int i = 0 ; i < 5 ; i++) { |
19 | index = r.nextInt(ids.length - i); |
20 | strarray[i] = ids[index]; |
22 | for ( int j = index; j < ids.length - i - 1 ; j++) { |
26 | for (String str : strarray) { |
27 | System.out.print(str + " " ); |
运行如下图:
第二种算法:
01 | public static void r2() { |
02 | List<String> ids = new ArrayList<String>(); |
03 | ids.add( "zuidaima.com" ); |
07 | ids.add( "javaniu.com" ); |
08 | ids.add( "www.zuidaima.com" ); |
09 | Random r = new Random(); |
10 | List<String> ret = new ArrayList<String>(); |
12 | for ( int i = 0 ; i < 3 ; i++) { |
13 | index = r.nextInt(ids.size() - i); |
14 | ret.add(ids.get(index)); |
17 | for (String str : ret) { |
18 | System.out.print(str + " " ); |
借助java的list数据结构来实现!