`

JAVA每日一题01

阅读更多

还是我来继续jythoner的JAVA每日一题吧!最近比较闲哦!希望jythone不要见怪哦!

真是不好意思啊!早上有点忙!呵呵!

 

题目:一项抽奖程序要求读者从整数1-49之间选择6个不同的数字。编写一个程序来完成这项工作,并生成5组结果。

 

package com.tengfei.lesson01;
public class Lottery {
  public static void main(String[]args) {
    int setCount = 5;      // Number of sets of lucky numbers.
    int setSize = 6;       // Number of lucky numbers in the set.
    int range = 49;        // Assume selecting integers between 1 and range.
    int lucky;             // Holds a lucky number candidate.
    int luckyCount;        // Holds count of lucky numbers in a set.

    for(int i = 0; i < setCount; i++) {
      int lucky1 = 0;                  // Lucky numbers for the set of 6.
      int lucky2 = 0;                   
      int lucky3 = 0;                   
      int lucky4 = 0;
      int lucky5 = 0;                   
      int lucky6 = 0;    

      luckyCount = 0;                   // Count of numbers found in the current set
      while(luckyCount < setSize) {
       // Generate a lucky number between 0 and 48 and add 1:
       lucky = (int)(range*Math.random()) + 1;
        switch(luckyCount) {
          case 0:                      // It is the first one 
            lucky1 = lucky;            // so just store it
            luckyCount++;              // and increment the count
            break;
          case 1:                      // For the second we must
            if(lucky != lucky1) {      // check that it is different from the first
              lucky2 = lucky;          // It is, so store it
              luckyCount++;            // and increment the count
            }
            break;
          case 2:                      // For the third we check aginst the previous two
            if(lucky != lucky1 && lucky != lucky2) {
              lucky3 = lucky;
              luckyCount++;
            }
            break;
           case 3:                     // Check against the previous three...
            if(lucky != lucky1 && lucky != lucky2 && lucky != lucky3) {
              lucky4 = lucky;
              luckyCount++;
            }
            break;
           case 4:                     // Check against the previous four...
            if(lucky != lucky1 && lucky != lucky2 && lucky != lucky3 && lucky != lucky4) {
              lucky5 = lucky;
              luckyCount++;
            }
            break;
           case 5:                    // Check against the previous five...
            if(lucky != lucky1 && lucky != lucky2 && lucky != lucky3 && lucky != lucky4 && lucky != lucky5) {
              lucky6 = lucky;
              luckyCount++;
            }
            break;
        }
      }

      System.out.print("\nSet " + (i + 1) + ":");                        // Identify the set

      System.out.print(" " + lucky1 + " " + lucky2  + " " + lucky3  +    // and output the numbers
                       " " + lucky4  + " " + lucky5  + " " + lucky6);

       
      // If you want to be sure the numbers line up in columns you could use a
      // rather more complicated statement here instead of the above:
/*
      System.out.print((lucky1>9 ? " " :"  ") + lucky1 + 
                       (lucky2>9 ? " " :"  ") + lucky2 +
                       (lucky3>9 ? " " :"  ") + lucky3 +
                       (lucky4>9 ? " " :"  ") + lucky4 +
                       (lucky5>9 ? " " :"  ") + lucky5 +
                       (lucky6>9 ? " " :"  ") + lucky6);
*/
      // This makes use of the conditional operator to output an extra space
      // when a lucky number is a single digit.
    }
  }
}



 

 

 

分享到:
评论
23 楼 leelj 2009-04-24  
看看 这里:http://www.iteye.com/topic/373123同类问题
22 楼 lpp333 2009-04-23  
华为的兄弟吧~~!!
21 楼 Hooopo 2009-04-23  
night_stalker 写道
shuffle 犯规呀~~
不过 ruby 实现 shuffle 就一句 sort_by{rand}

5.times{ p((1..49).sort_by{rand}[1..7]) }

后知后觉的补充:嗯…… 和 QuakeWang 的一样

哇,这个sort_by{rand}[1..7]好强大呀!!呼呼~~
20 楼 night_stalker 2009-04-23  
Eastsun 写道

就没有规则,何来犯规?

不好意思,口癖…… 是褒义词…… 譬如我常常说“卡莲萌犯规了”,也是不带规则的
19 楼 Eastsun 2009-04-23  
night_stalker 写道
shuffle 犯规呀~~
不过 ruby 实现 shuffle 就一句 sort_by{rand}

5.times{ p ((1..49).sort_by{rand}[0..6]) }


就没有规则,何来犯规?
18 楼 night_stalker 2009-04-23  
shuffle 犯规呀~~
不过 ruby 实现 shuffle 就一句 sort_by{rand}

5.times{ p((1..49).sort_by{rand}[1..7]) }

后知后觉的补充:嗯…… 和 QuakeWang 的一样
17 楼 Eastsun 2009-04-23  
把Haskell版减少了两行:
import Random
import Data.List
import Control.Monad

shuffle ls@(x:xs) = do
    elm <- liftM (ls !!) (randomRIO(0 ,length xs))  
    liftM (elm:) (shuffle$  delete elm ls)
shuffle _         = return[]

main = sequence [shuffle[1..49] >>= print.take 6 | c <- [1..5]]
16 楼 Eastsun 2009-04-22  
Haskell:
import Random
import Data.List
import Control.Monad 

randomSelectFrom size ls = randomMove size [] ls
    where randomMove 0 rs xs = print rs
          randomMove n rs xs = do
              idx <- randomRIO (0, length xs - 1)
              let em =  xs !! idx
              randomMove (n-1) (em:rs) (delete em xs)

main = sequence$ replicate 5 (randomSelectFrom 6 [1..49])


Scala:
	(1 to 5) foreach { _ =>
		println(List.range(1,50).sort{ (_,_) => Math.random > 0.5}.take(6))
	}


Java:
import static java.util.Collections.*;
import java.util.*;

public class RandomS {
	public static void main(String[] args){
		for(int c = 0; c < 5;c ++){
			List<Integer> lst = new ArrayList<Integer>();
			for(int n = 1;n <= 49;n ++) lst.add(n);
			shuffle(lst);
			System.out.println(lst.subList(0,6));
		}
	}
}
15 楼 Hooopo 2009-04-22  
ruby 代码:
5.times do
 arr=(1..49).to_a
 p (0..5).inject([]){|result,index| result << arr.delete_at(rand(49-index))}
end


result:
[41, 18, 15, 43, 40, 37]
[18, 26, 33, 15, 16, 27]
[14, 44, 49, 42, 8, 20]
[9, 42, 30, 28, 48, 19]
[11, 39, 21, 14, 35, 28]

14 楼 zornschuetze 2009-04-22  
3L的swap是把最后一个数与随机到的数字做个交换,每次循环随机数的范围-1,这样不会选到重复的数字
13 楼 QuakeWang 2009-04-22  
简洁的ruby:
5.times{ p (1..49).to_a.sort_by{rand}[0..5]}
12 楼 njin 2009-04-22  
打酱油~~~~
import random

def gen(n,a=1,b=49):
 	result = []
 	while True:
 		tmp = random.randint(a,b)
 		if tmp not in result:
 			result.append(tmp)
 		if len(result) == n:
 			return result


if __name__ == "__main__":
    for i in xrange(5):
        print gen(6)



btw:为啥javaeye代码标签可以用jython不能用python?
11 楼 ccjsjymg 2009-04-17  
#include <iostream>
#include <math.h>
#include <time.h>
using namespace std;
#define MAX 49
#define PUTVALUE 6
int number[MAX];
int putDigit[PUTVALUE];
void init()
{
     for(int i = 0;i < MAX;i++)
     {
          number[i] = i+1;   
     }
}
void _test()
{
    static int t = 0;
    init();
    int gg[100] = {0};
     for(int i = 0;i <PUTVALUE;)
     {
        int flag = t;
        srand(time(NULL));
        t = rand()%50;
        while(flag == t)
        { 
            srand(time(NULL));
            t = rand()%50;
        }
        //排重 
        for(int j = 0;j < 50;j++)
        {
           while(t == gg[j])
           {
               gg[j] = 0; 
               srand(time(NULL));
               t = rand()%50;
           }   
        }
         gg[i] = t;
         putDigit[i] = number[t];
          cout<<putDigit[i]<<" ";
         i++;
     } 
     cout<<endl;
}
int main()
{
     for(int j = 0;j < 5;j++){
       _test();
       cout<<"----------------------"<<endl;
       for(int i = 0;i < PUTVALUE;i++)
       {
            cout<<putDigit[i]<<" "; 
       }
       cout<<endl;
     }
     system("pause");
}
10 楼 lpingxh 2009-04-16  
groovyzhou 写道
import java.util.Arrays;
import java.util.Random;

public class Lottery {
	private Random rand = new Random();
	private int[] numbers;
	
	public Lottery(int range) {
		numbers = new int[range];
		for(int i=0; i<numbers.length; i++)
			numbers[i] = i+1;
	}
	
	private void swap(int i, int j) {
		if(i==j) return;
		int x = numbers[i];
		numbers[i] = numbers[j];
		numbers[j] = x;
	}
	
	public int[] randomChoose(int setSize)
	{
		int[] rt = new int[setSize];
		for(int i=0; i<setSize; i++)
		{
			int chosenIndex = rand.nextInt(numbers.length-i);
			rt[i] = numbers[chosenIndex];
			swap(chosenIndex, numbers.length-1-i);
		}
		return rt;
	}

	public static void main(String[] args) {
		Lottery l = new Lottery(49);
		for(int i=0; i<5; i++)
			System.out.println(Arrays.toString(l.randomChoose(6)));
	}

}


收藏
9 楼 ccjsjymg 2009-04-15  
groovyzhou 写道



Java代码

import&nbsp;java.util.Arrays; &nbsp;&nbsp;
import&nbsp;java.util.Random; &nbsp;&nbsp;
&nbsp;&nbsp;
public&nbsp;class&nbsp;Lottery&nbsp;{ &nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;private&nbsp;Random&nbsp;rand&nbsp;=&nbsp;new&nbsp;Random(); &nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;private&nbsp;int[]&nbsp;numbers; &nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;public&nbsp;Lottery(int&nbsp;range)&nbsp;{ &nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;numbers&nbsp;=&nbsp;new&nbsp;int[range]; &nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;for(int&nbsp;i=0;&nbsp;i&lt;numbers.length;&nbsp;i++) &nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;numbers[i]&nbsp;=&nbsp;i+1; &nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;private&nbsp;void&nbsp;swap(int&nbsp;i,&nbsp;int&nbsp;j)&nbsp;{ &nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if(i==j)&nbsp;return; &nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;int&nbsp;x&nbsp;=&nbsp;numbers[i]; &nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;numbers[i]&nbsp;=&nbsp;numbers[j]; &nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;numbers[j]&nbsp;=&nbsp;x; &nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;public&nbsp;int[]&nbsp;randomChoose(int&nbsp;setSize) &nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;int[]&nbsp;rt&nbsp;=&nbsp;new&nbsp;int[setSize]; &nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;for(int&nbsp;i=0;&nbsp;i&lt;setSize;&nbsp;i++) &nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;int&nbsp;chosenIndex&nbsp;=&nbsp;rand.nextInt(numbers.length-i); &nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;rt[i]&nbsp;=&nbsp;numbers[chosenIndex]; &nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;swap(chosenIndex,&nbsp;numbers.length-1-i); &nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;rt; &nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;
&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;public&nbsp;static&nbsp;void&nbsp;main(String[]&nbsp;args)&nbsp;{ &nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Lottery&nbsp;l&nbsp;=&nbsp;new&nbsp;Lottery(49); &nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;for(int&nbsp;i=0;&nbsp;i&lt;5;&nbsp;i++) &nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;System.out.println(Arrays.toString(l.randomChoose(6))); &nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;
&nbsp;&nbsp;
}&nbsp;&nbsp;import java.util.Arrays;
import java.util.Random;

public class Lottery {
private Random rand = new Random();
private int[] numbers;

public Lottery(int range) {
numbers = new int[range];
for(int i=0; i&lt;numbers.length; i++)
numbers[i] = i+1;
}

private void swap(int i, int j) {
if(i==j) return;
int x = numbers[i];
numbers[i] = numbers[j];
numbers[j] = x;
}

public int[] randomChoose(int setSize)
{
int[] rt = new int[setSize];
for(int i=0; i&lt;setSize; i++)
{
int chosenIndex = rand.nextInt(numbers.length-i);
rt[i] = numbers[chosenIndex];
swap(chosenIndex, numbers.length-1-i);
}
return rt;
}

public static void main(String[] args) {
Lottery l = new Lottery(49);
for(int i=0; i&lt;5; i++)
System.out.println(Arrays.toString(l.randomChoose(6)));
}

}


你这种做法很聪明,学习了。。。。。。。
8 楼 night_stalker 2009-04-15  
路过...

改了下,更傻的版本如下:
module Main where
import Random
import Data.List

main = do f []; f []; f []; f []; f [] where
	f li 
		|length li == 6 = print li
		|otherwise      = do
			n <- randomRIO (1::Int, 49)
			if elem n li then f li else f (n:li)

7 楼 Joo 2009-04-15  
三楼为什么要swap一下?
6 楼 qiuzhiqing 2009-04-15  
每次运行一下LZ这个程序去买双色球
5 楼 lmlyq 2009-04-08  
不是很明白楼主的意思,一个人猜六次?怎么没显示正确的结果呢??
4 楼 groovyzhou 2009-03-23  
import java.util.Arrays;
import java.util.Random;

public class Lottery {
	private Random rand = new Random();
	private int[] numbers;
	
	public Lottery(int range) {
		numbers = new int[range];
		for(int i=0; i<numbers.length; i++)
			numbers[i] = i+1;
	}
	
	private void swap(int i, int j) {
		if(i==j) return;
		int x = numbers[i];
		numbers[i] = numbers[j];
		numbers[j] = x;
	}
	
	public int[] randomChoose(int setSize)
	{
		int[] rt = new int[setSize];
		for(int i=0; i<setSize; i++)
		{
			int chosenIndex = rand.nextInt(numbers.length-i);
			rt[i] = numbers[chosenIndex];
			swap(chosenIndex, numbers.length-1-i);
		}
		return rt;
	}

	public static void main(String[] args) {
		Lottery l = new Lottery(49);
		for(int i=0; i<5; i++)
			System.out.println(Arrays.toString(l.randomChoose(6)));
	}

}

相关推荐

Global site tag (gtag.js) - Google Analytics