2
3

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版/ArrayList不使用版)

Last updated at Posted at 2015-09-26

C++14版で書いたのと同じ感じでJava版も書いてみました。
ただし、今回はタイトルの通り、ArrayListを使わないで静的配列で書きました。

はいそこの変態、性的配列じゃなくて静的配列だよ。
てか性的配列ってどんな配列だろうね…。String型のえっちな言葉が入ってる配列かな?まあいいや。

乱数生成器はRandomクラスのを使いました。

MakeRandomArray.java
import java.util.Random;
public class MakeRandomArray {
	public int[] makeArray(Random rand, int size, int randMax, int randMin){
		int[] arr = new int[size];
		for(int i = 0; i <= size - 1; i++){
			arr[i] = random(rand, randMax, randMin);
		}
		boolean isAllNoConflict = false;
		do{
			isAllNoConflict = true;
			for(int j = 0; j <= size - 1; j++){
				for(int k = j + 1; k <= size - 1; k++){
					if(arr[k] == arr[j]){
						arr[k] = random(rand, randMax, randMin);
						isAllNoConflict = false;
					}
				}
			}
		}while(!isAllNoConflict);
		return arr;
	}
	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;
	}
}

使用例

Main.java
import java.util.Random;
public class Main {
	public static void main(String[] args){
		MakeRandomArray mkRandArr = new MakeRandomArray();
		int[] arr = mkRandArr.makeArray(new Random(), 10, 100, 1);
		for(int x = 0; x <= 9; x++) System.out.println(arr[x]);
	}
}

C++のほうが楽だと思いました…。

ArrayList使用版はこちら

ArrayList使用版の改良版みたいにまーぜまーぜってやる方式を取る場合、どうしてもArrayListやListを使わざるを得なくなるみたいです。まあ戻り値の型をただのint配列にしてやることはできますが。
たぶんこれも上に書いたものよりは速く、軽いです。

MakeRandomArray.java

import java.util.ArrayList;
import java.util.Collections;
class MakeRandomArray {
public int[] makeRandomArray(int arraySize, int randMax, int randMin) {
if (randMax < randMin) return this.makeRandomArray(arraySize, randMin, randMax);
ArrayList arr = new ArrayList(randMax - randMin);
for (int i = randMin; i <= randMax; i++) arr.add(i);
Collections.shuffle(arr);
ArrayList newArr = new ArrayList(arr.subList(0, arraySize));
int[] data = new int[arraySize];
for (int i = 0; i < arraySize; i++) data[i] = newArr.get(i);
return data;
}
}

こちらもmainメソッドは同じで大丈夫です。

2
3
1

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
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?