In case Flash no longer exists; a copy of this site is included in the Flashpoint archive's "ultimate" collection.

Dead Code Preservation :: Archived AS3 works from wonderfl.net

forked from: 1行でArrayをシャッフルする

オリジナルでは0のところは-1と1どっちかと同じ扱いにされて偏るんじゃないかと思ったので
/**
 * Copyright uwi ( http://wonderfl.net/user/uwi )
 * MIT License ( http://www.opensource.org/licenses/mit-license.php )
 * Downloaded from: http://wonderfl.net/c/nGtg
 */

// forked from nemu90kWw's 1行でArrayをシャッフルする
// オリジナルでは0のところは-1と1どっちかと同じ扱いにされて偏るんじゃないかと思ったので
package {

	import flash.display.*;
	import flash.text.*;

	public class Shuffle extends Sprite
	{
		private var textfield:TextField;
		
		function Shuffle()
		{
			var i:int, array:Array, text:String = "";
			
			text += "Array.sort(function():int{return Math.random() > 0.5 ? 1 : -1;});\nで、もっとランダムに配列をシャッフルできる。\n";
			
			text += "◆シャッフルのテスト\n";
			array = new Array();
			for(i = 1; i <= 16; i++) {array.push(i);}
			text += "array = ["+array+"]\n\n";
			
			text += shuffle(array)+"\n";
			text += shuffle(array)+"\n";
			text += shuffle(array)+"\n";
			text += shuffle(array)+"\n";
			text += shuffle(array)+"\n";
			
			text += "\n◆分布のテスト\n";
			array = new Array();
			for(i = 1; i <= 3; i++) {array.push(i);}
//			text += "array = ["+array+"]\n\n";
			
			var result:Object = {"1,2,3":0,"1,3,2":0,"2,1,3":0,"2,3,1":0,"3,1,2":0,"3,2,1":0};
			
			var N : int = 100000;
			for(i = 0; i < N; i++) {result[shuffle(array)]++;}
			
			var xi2 : Number = 0.0;
			for(var str:String in result) {
			    text += "["+str+"] = "+result[str]+"\n";
			    xi2 += (result[str] - N/6) * (result[str] - N/6) / (N/6);
			}
			text += "χ^2=" + xi2 + "\n";
			
			text += "\n◆オリジナル分布のテスト\n";
			result = {"1,2,3":0,"1,3,2":0,"2,1,3":0,"2,3,1":0,"3,1,2":0,"3,2,1":0};
			
			for(i = 0; i < N; i++) {result[shuffle_original(array)]++;}
			
			xi2 = 0.0;
			for(str in result) {
			    text += "["+str+"] = "+result[str]+"\n";
			    xi2 += (result[str] - N/6) * (result[str] - N/6) / (N/6);
			} 
			text += "χ^2=" + xi2 + "\n";
			
			textfield = new TextField();
			textfield.x = textfield.y = 0;
			textfield.width = textfield.height = 465;
			textfield.text = text;
			addChild(textfield);
		}
		
		public function shuffle_original(array:Array):Array
		{
			return array.sort(function():int{return int(Math.random() * 3) - 1;});
		}
		
		public function shuffle(array:Array):Array
		{
			return array.sort(function():int{return Math.random() > 0.5 ? 1 : -1;});
		}
	}
}