Last active
October 7, 2017 03:56
-
-
Save tsuyoshicho/1a280561dd0188692234 to your computer and use it in GitHub Desktop.
重複しない乱数配列(Java版/コレクション活用?版) ref: http://qiita.com/tsuyoshi_cho/items/2c10819b9f667e41dfe2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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)); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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)); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment