Language detail: ActionScript

Coverage: 9.14%
number of '+' ratings
contribution for coverage

Unsolved challenges

codes

Feed

Used modules

文字列で+を表示する (Nested Flatten)
せっかくなので動きをつけてみました
(BetweenAS3を使ってみたかっただけとも言う)
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
package {
  import flash.display.Sprite;
  import flash.text.TextField;
  import flash.text.TextFieldType;
  import flash.text.TextFieldAutoSize;
  import flash.events.MouseEvent;
  import org.libspark.betweenas3.BetweenAS3;
  import org.libspark.betweenas3.tweens.ITween;
  import org.libspark.betweenas3.easing.Cubic;
  import org.libspark.betweenas3.events.TweenEvent;

  [SWF(backgroundColor="#ffffff")]
  public class Doukaku291 extends Sprite {
    private var inputArea:TextField;
    private var button:TextField;
    private var chars:Vector.<TextField>;

    private const DIRECTIONS:Array = [
      { x : 1, y : 0 },
      { x : 0, y : 1 },
      { x : 1, y : 0 },
      { x : 0, y : 1 },
      { x : -1, y : 0 },
      { x : 0, y : 1 },
      { x : -1, y : 0 },
      { x : 0, y : -1 },
      { x : -1, y : 0 },
      { x : 0, y : -1 },
      { x : 1, y : 0 },
      { x : 0, y : -1 }
    ];

    public function Doukaku291() {
      inputArea = new TextField();
      inputArea.border = true;
      inputArea.multiline = false;
      inputArea.type = TextFieldType.INPUT;
      inputArea.width = 150;
      inputArea.height = inputArea.textHeight + 5;
      inputArea.x = 20;
      inputArea.y = 10;
      stage.addChild(inputArea);
      
      button = new TextField();
      button.text = "start";
      button.border = true;
      button.background = true;
      button.backgroundColor = 0xffccaa;
      button.autoSize = TextFieldAutoSize.CENTER;
      button.height = inputArea.textHeight + 5;
      button.x = inputArea.x + inputArea.width + 10;
      button.y = inputArea.y;
      stage.addChild(button);

      chars = new Vector.<TextField>();
      button.addEventListener(MouseEvent.CLICK, function(e:MouseEvent):void {
          drawString(inputArea.text,
            stage.stageWidth / 2, inputArea.y + inputArea.height + 10);
        });
    }

    private function drawString(str:String, posX:int, posY:int):void {
      var i:int, c:String;
      var tmp:TextField;
      var strArray:Array = str.split("");
      var tween:ITween;
      var tweens:Array = new Array();

      for (i = 0; i < chars.length; i++) {
        stage.removeChild(chars[i]);
      }
      chars = new Vector.<TextField>();

      for (i = 0; i < 12; i++) {
        for each (c in strArray) {
          tmp = new TextField();
          tmp.text = c;
          tmp.height = tmp.textHeight;
          tmp.width = tmp.textWidth;
          tmp.autoSize = TextFieldAutoSize.CENTER;
          chars.push(tmp);
        }
      }

      chars[0].x = posX;
      chars[0].y = posY;
      stage.addChild(chars[0]);
      for (i = 1; i < chars.length; i++) {
        chars[i].visible = false;
        stage.addChild(chars[i]);
        chars[i].x = chars[i - 1].x + chars[i - 1].width * DIRECTIONS[int((i - 1) / strArray.length)].x;
        chars[i].y = chars[i - 1].y + chars[i - 1].height * DIRECTIONS[int((i - 1) / strArray.length)].y;

        tween = BetweenAS3.tween(chars[i],
          { x : chars[i].x, y : chars[i].y },
          { x : chars[i - 1].x, y : chars[i - 1].y },
          0.1, Cubic.easeOut);

        tween.addEventListener(TweenEvent.UPDATE, function(e:TweenEvent):void {
            e.target.target.visible = true
          });
        tweens.push(tween);
      }

      BetweenAS3.serialTweens(tweens).play();
    }
  }
}
ライフゲーム (Nested Flatten)
ActionScriptでやってみました。間引きは無しで。wonderflにも置いてあります。
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package {
  import flash.display.Sprite;
  import flash.display.Shape;
  import flash.utils.Timer;
  import flash.events.TimerEvent;
  import flash.text.TextField;
  
  public class LifeGame extends Sprite {
    private var table:Vector.<Vector.<Boolean>>; // セルの状態を保持するテーブル
    private var tmpTable:Vector.<Vector.<Boolean>>; // 更新用のテーブル
    private const TABLE_COLS:int = 10;
    private const TABLE_ROWS:int = 10;
    private var field:Shape; // セル表示フィールド
    private const CELL_WIDTH:int = 20;
    private const CELL_HEIGHT:int = 20;
    private var timer:Timer;
    private var tf:TextField; // 経過時間表示用

    public function LifeGame() {
      var i:int, j:int;
      table = new Vector.<Vector.<Boolean>>(TABLE_ROWS);
      for (j = 0; j < TABLE_ROWS; j++) {
          table[j] = new Vector.<Boolean>(TABLE_COLS);
          for (i = 0; i < TABLE_COLS; i++) {
            table[j][i] = Math.random() < 0.3; // 人口密度の初期値は0.3くらい
          }
      }
      // 更新用のテーブルは末端を考えやすいように番兵用の領域も確保
      tmpTable = new Vector.<Vector.<Boolean>>(TABLE_ROWS + 2);
      for (j = 0; j < TABLE_ROWS + 2; j++) {
          tmpTable[j] = new Vector.<Boolean>(TABLE_COLS + 2);
      }

      tf = new TextField();
      tf.width = 200;
      tf.height = 20;
      addChild(tf);

      field = new Shape();
      field.x = 10;
      field.y = tf.y + tf.height;
      drawField();
      addChild(field);

      timer = new Timer(1000);
      timer.addEventListener(TimerEvent.TIMER, onStep);
      timer.start();
    }

    private function onStep(e:TimerEvent):void {
      tf.text = "経過時間: " + timer.currentCount + "秒";
      updateTable();
      drawField();
    }

    private function updateTable():void {
      var i:int, j:int, di:int, dj:int, lives:int;
      // tableの内容をtmpTableにコピー(番兵つき)
      for (j = 0; j < TABLE_ROWS; j++) {
          tmpTable[j + 1][0] = table[j][TABLE_COLS - 1];
          tmpTable[j + 1][TABLE_COLS + 1] = table[j][0];
          for (i = 0; i < TABLE_COLS; i++) {
            tmpTable[j + 1][i + 1] = table[j][i]
          }
      }
      for (i = 0; i < TABLE_COLS; i++) {
          tmpTable[0][i + 1] = table[TABLE_ROWS - 1][i];
          tmpTable[TABLE_ROWS + 1][i + 1] = table[0][i];
      }
      tmpTable[0][0] = table[TABLE_ROWS - 1][TABLE_COLS - 1];
      tmpTable[0][TABLE_COLS + 1] = table[0][TABLE_COLS - 1];
      tmpTable[TABLE_ROWS + 1][0] = table[TABLE_ROWS - 1][0];
      tmpTable[TABLE_ROWS + 1][TABLE_COLS + 1] = table[0][0];

      // コピーしたtmpTableを使ってtableを更新
      for (j = 0; j < TABLE_ROWS; j++) {
          for (i = 0; i < TABLE_COLS; i++) {
            lives = 0;
            for (dj = -1; dj <= 1; dj++) {
              for (di = -1; di <= 1; di++) {
                if (tmpTable[j + 1 + dj][i + 1 + di]) {
                    lives++;
                }
              }
            }
            table[j][i] = ((!tmpTable[j + 1][i + 1] && lives == 3) || // (i, j)が死亡かつ周囲が3つ生きているか、
              (tmpTable[j + 1][i + 1] && (lives == 2 || lives == 3))); // (i, j)が生存かつ周囲が2つか3つ生きて入れば生存
          }
      }
    }
    
    private function drawField():void {
      var i:int, j:int, color:uint;
      field.graphics.clear();
      for (j = 0; j < TABLE_ROWS; j++) {
          for (i = 0; i < TABLE_COLS; i++) {
            color = table[j][i] ? 0xff0000 : 0xffffff;
            field.graphics.beginFill(color);
            field.graphics.drawRect(CELL_WIDTH * i, CELL_HEIGHT * j, CELL_WIDTH, CELL_HEIGHT);
            field.graphics.endFill();
          }
      }
      
      field.graphics.lineStyle(0.1, 0x000000);
      for (j = 0; j < TABLE_ROWS + 1; j++) {
          field.graphics.moveTo(0, CELL_HEIGHT * j);
          field.graphics.lineTo(CELL_WIDTH * TABLE_COLS, CELL_HEIGHT * j);
      }
      for (i = 0; i < TABLE_COLS + 1; i++) {
          field.graphics.moveTo(CELL_WIDTH * i, 0);
          field.graphics.lineTo(CELL_WIDTH * i, CELL_HEIGHT * TABLE_ROWS);
      }
    }
  }
}
ポリゴンを表示するプログラム (Nested Flatten)
Papervision3Dを使用。wonderflにも置いておきました。
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package {
  import flash.events.Event;
  import org.papervision3d.view.BasicView;
  import org.papervision3d.objects.primitives.Cube;
  import org.papervision3d.materials.WireframeMaterial;
  import org.papervision3d.materials.utils.MaterialsList;
  
  [SWF(width="400", height="300", backgroundColor="#eeffee", frameRate="15")] 
  public class RotatePolygon extends BasicView {
    private var cube:Cube;
    
    public function RotatePolygon() {
      super(0, 0, true);
      var wfm:WireframeMaterial = new WireframeMaterial(0x009900);
      var m:MaterialsList = new MaterialsList({all:wfm});
      cube = new Cube(m, 500, 500, 500, 3, 3, 3);
      scene.addChild(cube)
      stage.addEventListener(Event.ENTER_FRAME, enterFrameHandler);
    }

    private function enterFrameHandler(e:Event):void {
      cube.pitch(3);
      cube.yaw(2);
      cube.roll(6);
      startRendering();
    }
  }
}
ストレンジアトラクタの描画 (Nested Flatten)
Clifford Attractorです。描画が遅いですが、BitmapDataとかで高速化が可能かも。wonderflにも置いておきました。
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package {
  import flash.display.Sprite;
  
  [SWF(width="400", height="300", backgroundColor="#ffffff")] 
  public class CliffordAttractor extends Sprite {
    private var a:Number;
    private var b:Number;
    private var c:Number;
    private var d:Number;
    private var scale:Number;
    private const WIDTH:int = 400;
    private const HEIGHT:int = 300;
    private const CENTER_X:int = WIDTH / 2;
    private const CENTER_Y:int = HEIGHT / 2;
    private const DOT_SIZE:Number = 0.3;

    public function CliffordAttractor() {
      a = -1.4;
      b = 1.6;
      c = 1.0;
      d = 0.7;
      scale = Math.max(WIDTH, HEIGHT) / 4;

      Draw(30000);
    }

    private function Draw(n:uint):void {
      var i:uint;
      var x:Number = 0;
      var y:Number = 0;
      var xNext:Number;
      var yNext:Number;
      
      for (i = 0; i < n; i++) {
        xNext = Math.sin(a * y) + c * Math.cos(a * x);
        yNext = Math.sin(b * x) + d * Math.cos(b * y);
        x = xNext;
        y = yNext;
        this.graphics.beginFill(0x0000ff);
        this.graphics.drawCircle(CENTER_X + x * scale, CENTER_Y - y * scale, DOT_SIZE);
        this.graphics.endFill();
      }
    }
  }
}
分数を小数に展開 (Nested Flatten)

ActionScriptのカバレッジ稼ぎ。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class CalcDecimal
{
    public static function getDecimal(a:int, b:int):String {
        var cache:/*Boolean*/Array = new Array();
        var res:String = "";
        while (true) {
            cache[a] = true;
            a *= 10;
            res += String(int(a / b));
            a %= b;
            if (a == 0) {
                break;
            }
            if (cache[a]) {
                res = "{" + res + "}";
                break;
            }
        }
        return "0." + res;
    }
}
指定された日の存在する週 (Nested Flatten)

年/月/日 の値を入力すると結果が表示されます。値を変更すれば、その場で再計算を行います。

週の始まりは日曜と言うことにして計算しています。

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
package 
{
    import flash.display.Sprite;
    import flash.events.Event;
    import flash.text.TextField;
    import flash.text.TextFieldAutoSize;
    import flash.text.TextFieldType;
    
    [SWF(width=465, height=465, frameRate=30, background="#ffffff")]
    
    /**
     * via http://ja.doukaku.org/12/
     */
    public class ExistsWeek extends Sprite 
    {
        private static const DISPLAY_DAY:Array = ["", "月", "火", "水", "木", "金", ""];
        
        private var inputFields:Vector.<TextField> = new Vector.<TextField>();
        private var outputField:TextField = new TextField();
        
        public function ExistsWeek() {
            if (stage) init();
            else addEventListener(Event.ADDED_TO_STAGE, init);
        }
        
        private function init(e:Event = null):void {
            removeEventListener(Event.ADDED_TO_STAGE, init);
            
            drawInputArea();
            drawOutputArea();
        }
        
        public function calcSameWeek():void {
            var year:int = int(inputFields[0].text);
            var month:int = int(inputFields[1].text);
            var date:int = int(inputFields[2].text);
            if (year * month * date == 0) return;
            
            var base:Date = new Date(year, month - 1, date);
            base.date -= base.day;
            outputField.text = "";
            for (var index:int = 1; index <= 5; index++) {
                base.date += 1;
                outputField.appendText(convertString(base));
            }
        }
        private function convertString(d:Date):String {
            return DISPLAY_DAY[d.day] + " " + d.fullYear + "/" + convertDigits(d.month + 1, 2) + "/" + convertDigits(d.date, 2) + "\n";
        }
        private function convertDigits(i:int, count:int):String {
            var res:String = String(i);
            var len:int = count - res.length;
            for (var index:int = 0; index < len; index++) {
                res = "0" + res;
            }
            return res;
        }
        
        private function createInputField(digits:int):TextField {
            var field:TextField = new TextField();
            field.type = TextFieldType.INPUT;
            field.multiline = false;
            field.wordWrap = false;
            field.border = true;
            field.width = digits * 10;
            field.height = 20;
            
            field.addEventListener(Event.CHANGE, function(event:Event):void {
                calcSameWeek();
            });
            return field;
        }
        private function drawInputArea():void {
            var xOffset:int = 10;
            var yOffset:int = 10;
            
            var label:TextField = new TextField();
            label.text = "input date:";
            label.autoSize = TextFieldAutoSize.LEFT;
            label.x = xOffset;
            label.y = yOffset;
            addChild(label);
            xOffset += label.width;
            
            var yearField:TextField = createInputField(4);
            yearField.x = xOffset;
            yearField.y = yOffset;
            inputFields.push(yearField);
            addChild(yearField);
            xOffset += yearField.width;
            
            var sep1:TextField = new TextField();
            sep1.text = "/";
            sep1.autoSize = TextFieldAutoSize.LEFT;
            sep1.x = xOffset;
            sep1.y = yOffset;
            addChild(sep1);
            xOffset += sep1.width;
            
            var monthField:TextField = createInputField(2);
            monthField.x = xOffset;
            monthField.y = yOffset;
            inputFields.push(monthField);
            addChild(monthField);
            xOffset += monthField.width;
            
            var sep2:TextField = new TextField();
            sep2.text = "/";
            sep2.autoSize = TextFieldAutoSize.LEFT;
            sep2.x = xOffset;
            sep2.y = yOffset;
            addChild(sep2);
            xOffset += sep2.width;
            
            var dateField:TextField = createInputField(2);
            dateField.x = xOffset;
            dateField.y = yOffset;
            inputFields.push(dateField);
            addChild(dateField);
            xOffset += dateField.width;
            
        }
        
        private function drawOutputArea():void {
            outputField.autoSize = TextFieldAutoSize.LEFT
            outputField.multiline = true;
            outputField.wordWrap = false;
            
            outputField.x = 10;
            outputField.y = 40;
            addChild(outputField);
        }
    }
}
ピラミッドを作る (Nested Flatten)

ActionScript のカバレッジ上げ

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Pyramid
{
    public static function print(n:int):void {
        var duplicate:Function = function(s:String, count:int):String {
            var res:String = "";
            for (var i:int = 0; i < count; i++) res += s;
            return res;
        };
        for (var i:int = 1; i <= n; i++) {
            var line:String = duplicate(" ", n - i) + duplicate("*", 2 * i - 1);
            trace(line);
        }
    }
}
道順を数える (Nested Flatten)

ActionScriptがなかったので、書いてみました。

動かすには FlashPlayer10が必要になります。wonderflにも投稿してあるので、そちらで実際の動きが見れます。

左上の数字が道順の数になります。経路上の線をクリックすると、ON/OFFが切り替えられるようになっています。

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
package 
{
    import flash.display.Sprite;
    import flash.events.Event;
    import flash.events.MouseEvent;
    import flash.geom.Point;
    import flash.text.TextField;
    import flash.text.TextFieldAutoSize;
    
    [SWF(width=465, height=465, frameRate=30, backgroundColor="#ffffff")]
    
    /**
     * via http://ja.doukaku.org/221/
     * 左上の点から右下の点までいくのに何通りの経路があるかを数えて、左上に表示します。
     *  定数になっている、X_COUNT と Y_COUNT の値を変更すると経路の数が変更できます。
     * 経路上の線をクリックすると、通行止めにできます。その時経路の数も変更されます。
     */
    public class CountPath extends Sprite 
    {
        public static const X_COUNT:int = 3;
        public static const Y_COUNT:int = 4;
        
        public static const OFFSET:Point = new Point(40, 20);
        
        private var answer:TextField = new TextField();
        private var nodeMap:Array = new Array();
        
        public function CountPath() {
            if (stage) init();
            else addEventListener(Event.ADDED_TO_STAGE, init);
        }
        
        private function init(e:Event = null):void {
            removeEventListener(Event.ADDED_TO_STAGE, init);
            
            var maxCount:int = (X_COUNT > Y_COUNT)? X_COUNT: Y_COUNT;
            var scale:Number = 420.0 / maxCount;
            var offset:Point = new Point(OFFSET.x, OFFSET.y);
            
            offset.x += Number(maxCount - X_COUNT) * scale / 2;
            offset.y += Number(maxCount - Y_COUNT) * scale / 2;
            
            for (var y:int = 0; y <= Y_COUNT; y++) {
                nodeMap[y] = new Array();
                for (var x:int = 0; x <= X_COUNT; x++) {
                    var node:Node = new Node(x, y);
                    node.draw(this.graphics, scale, offset);
                    nodeMap[y][x] = node;
                    if (y > 0) {
                        var yEdge:Edge = new Edge(nodeMap[y - 1][x], nodeMap[y][x]);
                        yEdge.draw(scale, offset);
                        addChild(yEdge);
                    }
                    if (x > 0) {
                        var xEdge:Edge = new Edge(nodeMap[y][x - 1], nodeMap[y][x]);
                        xEdge.draw(scale, offset);
                        addChild(xEdge);
                    }
                }
            }
            
            answer.autoSize = TextFieldAutoSize.LEFT;
            answer.x = 10;
            answer.y = 10;
            addChild(answer);
            
            displayCount();
            this.addEventListener(MouseEvent.CLICK, function(event:MouseEvent):void {
                displayCount();
            });
        }
        
        public function displayCount():void {
            answer.text = String(calcRouteCount());
        }
        
        public function calcRouteCount():int {
            clearCount();
            var startNode:Node = nodeMap[0][0];
            var endNode:Node = nodeMap[Y_COUNT][X_COUNT];
            
            startNode.nodeCount = 1;
            calcCount(startNode);
            return endNode.nodeCount;
        }
        private function calcCount(start:Node):void {
            for each(var edge:Edge in start.getEdges()) {
                if (edge.passable) {
                    var node:Node = edge.end;
                    node.nodeCount += start.nodeCount;
                    calcCount(node);
                }
            }
        }
        
        private function clearCount():void {
            for each(var array:Array in nodeMap) {
                for each (var node:Node in array) {
                    node.nodeCount = 0;
                }
            }
        }
    }
}

import flash.display.Graphics;
import flash.display.Sprite
import flash.events.MouseEvent;
import flash.geom.Point;

class Node {
    private var x_:int;
    private var y_:int;
    private var edges:Vector.<Edge> = new Vector.<Edge>();
    private var count:int = 0;
    
    public function Node(x:int, y:int) {
        this.x_ = x;
        this.y_ = y;
    }
    public function get X():int { return this.x_; }
    public function get Y():int { return this.y_; }
    public function getViewX(scale:Number, offset:Point):Number {
        return this.X * scale + offset.x;
    }
    public function getViewY(scale:Number, offset:Point):Number {
        return this.Y * scale + offset.y;
    }
    
    public function get nodeCount():int { return count; }
    public function set nodeCount(count:int):void { this.count = count; }
    
    public function getEdges():Vector.<Edge> {
        return edges;
    }
    public function addEdge(e:Edge):void {
        edges.push(e);
    }
    
    public function draw(g:Graphics, scale:Number, offset:Point):void {
        g.lineStyle();
        g.beginFill(0x000000, 0.9);
        g.drawCircle(getViewX(scale, offset), getViewY(scale, offset), 10);
        g.endFill();
    }
}

class Edge extends Sprite {
    private var startNode:Node;
    private var endNode:Node;
    private var pass:Boolean = true;
    
    public function Edge(start:Node, end:Node) {
        this.startNode = start;
        this.endNode = end;
        this.addEventListener(MouseEvent.CLICK, function(event:MouseEvent):void {
            alpha = 1.0 - alpha;
            pass = !pass;
        });
        this.startNode.addEdge(this);
    }
    public function get start():Node { return this.startNode; }
    public function get end():Node { return this.endNode; }
    public function get passable():Boolean { return this.pass; }
    
    public function draw(scale:Number, offset:Point):void {
        var g:Graphics = this.graphics;
        g.lineStyle(5, 0x000000, 0.8);
        g.moveTo(startNode.getViewX(scale, offset), startNode.getViewY(scale, offset));
        g.lineTo(endNode.getViewX(scale, offset), endNode.getViewY(scale, offset));
        this.alpha = 0.8;
    }
}
バイナリクロック (Nested Flatten)

まだなかったので、習作として作ってみました。

また、Wonderflにもあるので良かったら動作するのも見てみてください。

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
package 
{
    import flash.display.Sprite;
    import flash.events.Event;
    import flash.events.TimerEvent;
    import flash.geom.ColorTransform;
    import flash.text.TextField;
    import flash.text.TextFieldAutoSize;
    import flash.utils.Timer;
    
    [SWF(width = 140, height = 80, backgroundColor = 0xCCCCCC, frameRate = 30)]
    
    public class BinaryClock extends Sprite 
    {
        private const UNIT_LENGTH:int = 20;
        
        private var hourPoints:Vector.<Sprite> = new Vector.<Sprite>();
        private var minutePoints:Vector.<Sprite> = new Vector.<Sprite>();
        private var secondPoints:Vector.<Sprite> = new Vector.<Sprite>();
        private var timeTexts:Vector.<TextField> = new Vector.<TextField>();
        
        public function BinaryClock():void
        {
            init();
        }
        
        private function init():void
        {
            (function(points:Vector.<Sprite>):void {
                for (var index:int = 0; index < 5; index++) {
                    var point:Sprite = createPoint();
                    point.x = index * UNIT_LENGTH + UNIT_LENGTH;
                    point.y = 0;
                    points.push(point);
                }
            })(hourPoints);
            var initPoints:Function = function(points:Vector.<Sprite>, y:int):void {
                for (var index:int = 0; index < 6; index++) {
                    var point:Sprite = createPoint();
                    point.x = index * UNIT_LENGTH;
                    point.y = y;
                    points.push(point);
                }
            }
            initPoints(minutePoints, UNIT_LENGTH);
            initPoints(secondPoints, UNIT_LENGTH * 2);
            
            (function(fields:Vector.<TextField>):void {
                for (var index:int = 0; index < 3; index++) {
                    var field:TextField = new TextField();
                    field.width = UNIT_LENGTH;
                    field.height = UNIT_LENGTH;
                    field.x = UNIT_LENGTH * 6;
                    field.y = index * UNIT_LENGTH;
                    field.autoSize = TextFieldAutoSize.CENTER;
                    timeTexts.push(field);
                }
            })(timeTexts);
            
            (function():Vector.<TextField> {
                var result:Vector.<TextField> = new Vector.<TextField>();
                for (var index:int = 0; index < 6; index++) {
                    var field:TextField = new TextField();
                    field.width = UNIT_LENGTH;
                    field.height = UNIT_LENGTH;
                    field.x = UNIT_LENGTH * (5 - index);
                    field.y = 3 * UNIT_LENGTH;
                    field.autoSize = TextFieldAutoSize.CENTER;
                    field.text = String(Math.pow(2, index));
                    result.push(field);
                }
                return result;
            })().map(function(field:TextField, i:int, a:*):void {
                addChild(field);
            });
            
            hourPoints = hourPoints.reverse();
            for each (var hp:Sprite in hourPoints) {
                addChild(hp);
            }
            minutePoints = minutePoints.reverse();
            for each (var mp:Sprite in minutePoints) {
                addChild(mp);
            }
            secondPoints = secondPoints.reverse();
            for each (var sp:Sprite in secondPoints) {
                addChild(sp);
            }
            for each (var field:TextField in timeTexts) {
                addChild(field);
            }
            
            var timer:Timer = new Timer(500);
            timer.addEventListener(TimerEvent.TIMER, setBinaryTime);
            timer.start();
        }

        private function createPoint():Sprite
        {
            var point:Sprite = new Sprite();
            point.graphics.beginFill(0xFFFFFF, 0.6);
            point.graphics.drawRoundRect(0, 0, UNIT_LENGTH, UNIT_LENGTH, UNIT_LENGTH / 2.0, UNIT_LENGTH / 2.0);
            point.graphics.endFill();
            return point;
        }
        
        private function setBinaryTime(event:TimerEvent):void
        {
            var now:Date = new Date();
            
            ([now.hours, now.minutes, now.seconds]).forEach(function(value:int, index:int, a:*):void {
                timeTexts[index].text = ((value < 10)? "0": "") + value;
            });

            var changeColorTime:Function = function(points:Vector.<Sprite>, value:int):void {
                for (var index:int = 0; index < points.length; index++) {
                    var mask:int = (1 << index);
                    changeColor(points[index], (~value & mask) >> index);
                }
            }
            changeColorTime(hourPoints, now.hours);
            changeColorTime(minutePoints, now.minutes);
            changeColorTime(secondPoints, now.seconds);
        }
        
        private function changeColor(s:Sprite, i:Number):void
        {
            s.transform.colorTransform = new ColorTransform(i, i, i, 1, 1, 1, 1, 0);
        }
    }
}
ダブルクリックの取得 (Nested Flatten)

ダブルクリックをすると、中央付近に座標が表示されます。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package 
{
    import flash.display.Sprite;
    import flash.events.Event;
    import flash.events.MouseEvent;
    import flash.text.TextField;

    [SWF(width = 465, height = 465, backgroundColor = 0xEEEEEE, frameRate = 30)]

    public class DoubleClickEvent extends Sprite
    {
        private var display:TextField = new TextField();
        public function DoubleClickEvent():void 
        {
            display.width = 80;
            display.height = 20;
            display.x = (stage.stageWidth - display.width) / 2;
            display.y = (stage.stageHeight - display.height) / 2;
            display.mouseEnabled = false;
            addChild(display);
            
            stage.addEventListener(MouseEvent.DOUBLE_CLICK, function(event:MouseEvent):void {
                var x:int = event.stageX;
                var y:int = event.stageY;
                display.text = "(" + x + "," + y + ")";
            });
            stage.doubleClickEnabled = true;
        }
    }
}
ラングトンのアリの描画 (Nested Flatten)

ActionScriptで作成してみました。 30Frame/secでは遅かったので、1Frameに10Step進ませています。

ブラウザ上で確認できるようにwonderflにもおいておきます。

http://wonderfl.net/code/519de9f580e291a6309e2e8df3d5e8319a647433

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package {
    // Yet another implimentation of Langton's ant
    // This is made for "どう書く?org", http://ja.doukaku.org/276/
    // This code is written by xsd.
    import flash.display.Sprite;
    import flash.display.BitmapData;
    import flash.display.Bitmap;
    import flash.geom.Rectangle;
    import flash.events.Event;
    import flash.text.TextField;
    import flash.text.TextFormat;

    [SWF(width="465", height="465", backgroundColor="0xFFFFFF", frameRate="30")]
    public class LangtonsAnt extends Sprite {
    private const SCREEN_WIDTH:int = 465;
    private const SCREEN_HEIGHT:int = 465;
    private const CELL_SIZE:int = 4;
    private const STEP:int = 10;

    private var bm:BitmapData;
    private var bmp:Bitmap;
    private var tf:TextField;
    private var xAnt:int = 200;
    private var yAnt:int = 200;
    private var vx:int = 1;
    private var vy:int = 0;
    private var count:int = 0;
        
    public function LangtonsAnt():void {
            bm = new BitmapData(SCREEN_WIDTH, SCREEN_HEIGHT, false, 0xFFFFFF);
            bmp = new Bitmap(bm);
            this.addChild(bmp);

            tf = new TextField();
            tf.defaultTextFormat = new TextFormat("_Serif", 24, 0, true);
            tf.x = 0; tf.y = SCREEN_HEIGHT - 32; tf.width = SCREEN_HEIGHT; tf.height = 32;
            tf.selectable = false;
            this.addChild(tf);
            this.addEventListener(Event.ENTER_FRAME, update);
        }
        
        public function update(event:Event):void {
            bm.lock();
            var t:int, i:int;
    
            for (i = 0; i < STEP; i++) {
                xAnt += vx * CELL_SIZE;
                yAnt += vy * CELL_SIZE;
                var a:int = bm.getPixel(xAnt, yAnt);
                if (a == 0) {
                    bm.fillRect(new Rectangle(xAnt, yAnt, CELL_SIZE, CELL_SIZE), 0xFFFFFF);
                    t = vx; vx = vy; vy = -t;
                } else {
                    bm.fillRect(new Rectangle(xAnt, yAnt, CELL_SIZE, CELL_SIZE), 0x000000);
            t = vy; vy = vx; vx = -t;
                }
                bm.unlock();
                if (xAnt <= CELL_SIZE || xAnt >= SCREEN_WIDTH - CELL_SIZE ||
                    yAnt <= CELL_SIZE || yAnt >= SCREEN_HEIGHT - CELL_SIZE) {
                    this.removeEventListener(Event.ENTER_FRAME, update);
                    break;
                }
                count++;
                tf.text = "Step: "+count;
            }
        }
    }
}
LL Golf Hole 8 - 横向きのピラミッドを作る (Nested Flatten)

ActionScriptですが…。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
var n:Number = 4;
var str:String = "";

for(var i = 1;i<n*2;i++){
    var t:Number = i;
    if(i>n){
        t = (n*2)-i;
    }
    for(j = 0;j<Math.abs(t);j++){
        str += "*";
    }
    str += "\n";
}
trace(str);

ActionScriptですが…。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
var n:Number = 4;
var str:String = "";

for(var i = 1;i<n*2;i++){
    var t:Number = i;
    if(i>n){
        t = (n*2)-i;
    }
    for(j = 0;j<Math.abs(t);j++){
        str += "*";
    }
    str += "\n";
}
trace(str);
議席数をドント方式で (Nested Flatten)

ハッシュを利用しました.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
VOTE_ARY = [123, 4, 56, 78]
N = 100
class Hash
  def gen_vote(ary)
    key = 'a'
    ary.each{|x| self[key.succ!] = x}
  end
  def gen_vote_list
    keys.each{|key|
      2.upto(N){|i| self["#{key}#{i}"] = self[key].quo(i)}
    }  
  end
end
votes, counter = Hash.new, Hash.new
votes.gen_vote(VOTE_ARY)
votes.gen_vote_list
votes.keys.sort{|a, b| -1*(votes[a] <=> votes[b])}.
  map{|x| x.match(/^([a-zA-Z]+)/)[0]}[0..N-1].
  each{|key| eval("counter[key]#{counter.has_key?(key) ? '+' : ''}=1")}
p counter.values
与えられた数字のケタ数 (Nested Flatten)
JS版みてアッと思い、abs追加して晒しです。小数点以下はバッサリいってます。
1
2
3
4
function ketasu(num:Number):Array{
	var keta:Number = Math.abs(Math.floor(num)).toString().length;
	return(new Array(keta,Math.pow(10,keta-1)));
}
HTTPでGET (Nested Flatten)
フレーム1にボタンインスタンスmyBtn_btnを配置。フレーム1にフレームアクションを記述。
1
2
3
4
stop();
myBtn_btn.onRelease = function() {
  getURL("http://ja.doukaku.org/feeds/comments/", "_blank", "GET");
}
倍数になる13進数 (Nested Flatten)

	
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
var numObj = new Number();
for (var i = 10; i<10000; i++) {
  numObj = i;
  // numObjをStringに変換してnum10に格納
  var num10 = numObj.toString(i);
  // num10を13進数に変換してnum13に格納
  var num13 = parseInt(num10, 13);
  if (num13%num10 == 0) {
    trace("10進数:"+num10);
    trace("13進数:"+num13);
    break;
  }
}
n人中m人が当選するくじ (Nested Flatten)
勉強し始めているので、とりあえず投稿
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
private function execute(n:int, m:int):void {
        var res:Array = [];
        for (var i:int = 0; i < m;) {
                var r:int = Math.floor(Math.random() * n);
                if (res.indexOf(r) >= 0) continue;
                i++;
                res.push(r);
        }
        Alert.show(res.toString());
}
Hello, world! (Nested Flatten)
1
trace('Hello, world!');

Index

Feed

Other

Link

Pathtraq

loading...