`
人帅刀猛
  • 浏览: 38774 次
  • 性别: Icon_minigender_1
  • 来自: 重庆
社区版块
存档分类
最新评论

生成不重复的随机数

阅读更多

今天去烟台杰瑞网络面试,有一道题是把10000个不重复的随机数(0-9999)插入buff[10000]中,其实就是要生成10000个不重复的随机数,这个正好我以前在用android写连连看随机配对的时候写过,于是就写了出来,结果解释了一会面试官才看懂....看来这个方法似乎不是主流的方法,于是回来便搜索了一下生成不重复的随机数的文章,发现一个最简单的(喂,这不算是算法了吧!)... 现在把两个算法一起发出来,大家参考一下:

网上的算法:

List<Integer> list = new ArrayList<Integer>();   
        
        for(int i = 1; i <= 6; i++){   
            list.add(i);   
        }   
  
        Collections.shuffle(list);   
           
        for(Integer i : list){   
            System.out.println(i);   
        }   
}

 自己的算法:

/*
	 * 重新生成map,off数组表示已被占用的点
	 * 并返回随机的目标点
	 */
	private int setmap(List<Integer> off){
		System.out.println("setmap");
		//key用于随机,value表示key代表的点
		Map<Integer,Integer> map=new HashMap<Integer,Integer>();
		map.clear();
		int count=1;
		for(int i=0;count<=60-off.size()&&i<60;i++){
			if(!off.contains(i)){
				map.put(count++, i);
			}
		}
		int randomMap=(int) Math.floor(Math.random()*(60-off.size())+1);
		return map.get(randomMap);
	}

 

private void initialize(){
		List<Integer> off=new ArrayList<Integer>();
		
		int randomPic=1;
		do {
			if(off.size()%2==0)
				randomPic = (int) Math.floor(Math.random() * 10 + 1);
			int randomMap = setmap(off);
			off.add(randomMap);
			int x = randomMap /6+1;
			int y = randomMap %6+1;
			// 取得资源id
			ApplicationInfo appInfo = this.getContext().getApplicationInfo();
			int resID = getResources().getIdentifier("p" + randomPic,
					"drawable", appInfo.packageName);
			System.out.println(x+"-"+y+":"+resID);
			bitmap[x][y] = ((BitmapDrawable) getResources().getDrawable(resID))
					.getBitmap();
			pic[x][y]=new Pic();
//			Game.drawImage(canvas, bitmap[i/6][i%6], posx+(i%6)*25, posy+(i/6)*25);
			Rect rect=new Rect(posx+(randomMap%6+1)*25,posy+(randomMap/6+1)*25,posx+(randomMap%6+1)*25+25,posy+(randomMap/6+1)*25+25);
			pic[x][y].setPosx(x);
			pic[x][y].setPosy(y);
			pic[x][y].setRect(rect);
			pic[x][y].setPicName("p" + randomPic);
			pic[x][y].setFlag(randomPic);
			pic[x][y].setShow(true);
		} while (off.size() < 60);
		//边缘x0=45,y0=30
		for(int i=0;i<12*8;i++){
			int x = i /8;
			int y = i %8;
			if(x==0||x==11||y==0||y==7){
				pic[x][y]=new Pic();
				Rect rect=new Rect(posx+(y)*25,posy+(x)*25,posx+(y)*25+25,posy+(x)*25+25);
				pic[x][y].setPosx(x);
				pic[x][y].setPosy(y);
				pic[x][y].setRect(rect);
//				System.out.println("pic["+x+"]["+y+"]:"+pic[x][y].getRect());
				pic[x][y].setShow(false);
			}
		}
	}

 另外,为什么给代码选了颜色就显示出来就变成代码( <SPAN style="COLOR: #888888">)了啊!!!!

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics