10
7

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.

processingで配列をシャッフル

Last updated at Posted at 2015-11-10

これが正しい方法かどうかわかりませんが、
processingで配列をシャッフルしてみました。


//ベースの配列
String[] base_arr = {"aaa", "bbb", "ccc", "ddd", "eee", "fff", "ggg"};
//シャッフルした配列
String[] rand_arr = new String[base_arr.length];
//いろいろ操作用配列
String[] temp_arr;
//乱数格納用変数
int num = 0;

for (int i = 0; i < rand_arr.length; i++) {

	//要素1個の仮配列を作成
	temp_arr = new String[1];
	//ベース配列のサイズから乱数を作成
	num = int (random (base_arr.length));

	//出来た乱数のインデックスの要素を抜き出して仮配列に入れる
	temp_arr = subset (base_arr, num, 1);
	//シャッフル配列に仮配列0番目を代入
	rand_arr[i] = temp_arr[0];
	//上2行について
	//rand_arr[i] = subset (base_arr, num, 1);
	//としたいところだが、
	//文字 = 配列(エラー)
	//となる(抜き出した要素が1個でもあくまでも配列)ので
	//一旦要素1個の仮配列に入れる

	//次にベース配列より1個少ないサイズの仮配列を作成
	temp_arr = new String[base_arr.length - 1];
	//仮インデックス用の変数
	int count = 0;
	//ベース配列のサイズ分だけループして
	for (int j = 0; j < base_arr.length; j++) {
		//先ほど出た乱数以外の要素をベース配列から抽出
		if (j != num) {
			temp_arr[count] = base_arr[j];
			count += 1;
		}
	}
	//ベース配列と要素が1個抜けた仮配列を入れ替え
	//(ベース配列はサイズが1個減り、抜き出された要素は無くなる)
	base_arr = temp_arr;

}

println (rand_arr);

10
7
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
10
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?