사용 collection.shuffle() 및 지정된 크기의 하위 목록을 선택하거나 목록에서 값을 넣어 X 시간에 대한 지수
found.add (list.remove (random.nextInt (list.size()));
에서 요소를 제거합니다. 각 단계에서 목록의 크기가 줄어들며 요소가 두 번 나타나지 않습니다.
그러나 매우 큰 범위의 경우 - 유효한 길이의 범위를 말하고, 셔플 또는 값을 선택하는 목록을 작성하는 것은 적절하지 않습니다.
그래서 Set을 만들고 임의의 Values를 선택하고 set.size()가 필요한 크기와 같을 때까지 목록에 추가하십시오.
의 Runnable 예 : 숫자가 설정에없는 경우
import java.util.*;
public class Empty {
static Random random = new Random();
public static void main (String args [])
{
show (pick (10, 100));
show (securePick (10, 100000));
}
static public List <Integer> pick (int n, int max) {
List <Integer> result = new ArrayList <Integer>();
List <Integer> range = new ArrayList <Integer> (max);
for (int i= 0; i < max; ++i)
range.add (i);
for (int i= 0; i < n; ++i)
result.add (range.remove (random.nextInt (range.size())));
return result;
}
static public Set <Integer> securePick (int n, int max) {
Set <Integer> result = new HashSet <Integer>();
while (result.size() < n)
result.add (random.nextInt (max));
return result; // <Integer>
}
public static void show (List <Integer> liste)
{
System.out.print ("[");
for (int i : liste)
System.out.print (i + ", ");
System.out.println ("\b\b]");
}
public static void show (Set <Integer> liste)
{
System.out.print ("[");
for (int i : liste)
System.out.print (i + ", ");
System.out.println ("\b\b]");
}
}
사용 HashSet에, 그것은 그렇지 않으면 재생 사용할 수 있습니까? – DarthVader
관련없는 팁 : 지금 int 배열을 사용하는 대신 ArrayList을 사용할 수 있습니다. –
AHungerArtist
@DarthVader는 해시 설정을하지 않습니다 (일반적인 해시와 동일). 자동으로 반복되는 항목이 삭제됩니다. –