java的random數字問題

2007-07-03 2:15 am
如果我有1至20的數字
之後要random出5個數字
但該5個數字內不可出現重覆
例如:5, 7, 11, 14, 2
不能:6, 3, 18, 10, 6
要怎樣寫呢?

回答 (2)

2007-07-03 4:24 am
✔ 最佳答案
try following:

public class GenNum
{
public static void main(String[] args)
{ int iMin = 1;
int iMax = 20;
int iTeam = 5;
int iNum[ ] = iGenNum( iMin, iMax, iTeam, false );
for ( int i = 0; i < iTeam; i++ )
System.out.println( String.valueOf( iNum[ i ] ) );
}

public static int [ ] iGenNum( int piMin, int piMax,
int piTeam, boolean pbRepeat )
{ int iRange = piMax - piMin;
int iReturn[ ] = new int [ iRange ];
int iPtr = 0;
int iPtr1 = 0;

for ( iPtr = 0; iPtr < piTeam; )
{
iReturn[ iPtr ] = ( int ) Math.floor( ( iRange + 1 ) * Math.random( ) ) + piMin;
if ( ! pbRepeat )
{ if ( iPtr > 0 )
{ for ( iPtr1 = 0; iPtr1 < iPtr; iPtr1++ )
if ( iReturn[ iPtr ] == iReturn[ iPtr1 ] )
iPtr--;
}
}
iPtr++;
}

return iReturn;
}
}

for the function iGenNum
piMin : integer parameter to set the minimum generated value.
piMax: integer parameter to set the maximum generated value.
piTeam: integer parameter to set how many team generate.
pbRepeat: boolean parameter to check the generated number can repeat or not.

assumption:
in function iGenNum, the parameter piTeam would not be large than the value of ( piMax - piMin ).

OK?
2007-07-03 4:37 am
java.util.List<Integer> numberList = new java.util.Vector<Integer>();

for ( int i = 1 ; i &lt;= 20 ; i++ )
{
numberList.add( i );
}

// randomly select number from the list without replacement
for ( int i = 1 ; i &lt;= 20 ; i++ )
{
int randomIndex = (int)( Math.random() * numberList.size() );
int randomNum = numberList.remove( randomIndex );
System.out.println( randomNum );
}

註:若使用舊版本的 java compile 會出現問題,因為舊 version 不支援 Generics。


收錄日期: 2021-05-03 05:44:29
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20070702000051KK03217

檢視 Wayback Machine 備份