1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

重複しない乱数配列(Java版/コレクション活用?版)

Last updated at Posted at 2015-09-27

重複しない乱数配列(Java版/ArrayList使用版)を見て、「Collection使うなら、もうちょっと楽になるよな」と思ったので改善を検討。

Ideoneで試行錯誤したので、クラス名などがちょっと違います。

Ideone.java
import java.util.HashSet;
import java.util.ArrayList;
import java.util.Random;

class MakeRandomArray {
    public ArrayList<Integer> makeRandomArray(ArrayList<Integer> array, Random rand, int arraySize, int randMax, int randMin){
	HashSet<Integer> set = new HashSet<>(arraySize);
        for(int i = 1; i <= arraySize; i++){
            set.add(random(rand, randMax, randMin));
        }
        while(set.size() != arraySize){
            set.add(random(rand, randMax, randMin));
        }
        array.addAll(set);
        return array;
    }
    private int random(Random rand, int max,int min){
        if(max < min) return rand.nextInt(min - max) + max;
        else return rand.nextInt(max - min) + min;
    }
}

class Ideone{
    public static void main(String[] args){
        MakeRandomArray mkRandArr = new MakeRandomArray();
        ArrayList<Integer> arr = mkRandArr.makeRandomArray(new ArrayList<Integer>(), new Random(), 10, 100, 1);
        for(int x = 0; x <= 9; x++) System.out.println(arr.get(x));

    }
}

さらにJava8でのラムダを使うなどして処理を整理すると。

Ideone.java
import java.util.*;
import java.util.stream.*;
import java.lang.Math;
 
class MakeRandomArray {
	public List<Integer> makeRandomArray(Random rand, int arraySize, int randMax, int randMin){
		List<Integer> array = rand.ints(Math.min(randMin,randMax),Math.max(randMin,randMax))
				.distinct()
				.limit(arraySize)
				.boxed()
				.collect(Collectors.toList());
 
		return array;
	}
}
 
class Ideone{
	public static void main(String[] args){
		MakeRandomArray mkRandArr = new MakeRandomArray();
		List<Integer> arr = mkRandArr.makeRandomArray(new Random(), 10, 100, 1);
		for(int x = 0; x <= 9; x++) System.out.println(arr.get(x));
     }
}
1
2
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?