Unidirectional List
forked from Observer and simple Console (diff: 125)
Выполнено для gamind в качестве тестового задания.
ActionScript3 source code
/**
* Copyright Cheshir ( http://wonderfl.net/user/Cheshir )
* MIT License ( http://www.opensource.org/licenses/mit-license.php )
* Downloaded from: http://wonderfl.net/c/nseY
*/
// forked from Cheshir's Observer and simple Console
package {
import flash.ui.Keyboard;
import flash.events.KeyboardEvent;
import flash.filters.GlowFilter;
import flash.text.TextField;
import flash.display.Sprite;
public class FlashTest extends Sprite {
private var myConsole:Console;
private var list:Node;
public function FlashTest() {
// write as3 code here..
myConsole = new Console(stage);
this.graphics.beginFill(0);
this.graphics.drawRect(0,0,600,600);
// формируем однонаправленный список // create undirectional list
createSimpleList(5);
// теперь распечатаем его // now, print it!
printReversed(list);
// myConsole.addComand('-n',this.newNodes,'добавить 5 узлов и распечатать, и нажмите Enter');
// конечно можно добавить команду в консоль но...
myConsole.help();
stage.addEventListener(KeyboardEvent.KEY_DOWN,newNodes);
}
// добавим 5 узлов для наглядности
private function newNodes(e:KeyboardEvent):void {
if(e.keyCode != Keyboard.ENTER){
return;
}
for( var i:int = 0; i < 5; i++ )
{
lastNode.next = new Node("node num "+num);
lastNode = lastNode.next;
num++;
}
printReversed(list);
}
// храним последний узел чтобы привязывать следующий к нему, а не искать каждый
// раз последний
private var lastNode:Node;
private var num:int=1; // храним нумерацию узлов чтобы именовать их
private function createSimpleList(length:int):void{
list = new Node("first node");
lastNode = list;
for (var i:int = 0; i < length; i++){
lastNode.next = new Node("node num "+num);
lastNode = lastNode.next;
num++;
}
}
// напечатать однонаправленный список в обратном порядке
private function printReversed(node:Node):void {
if(node){
printReversed(node.next); // уходим в рекурсию
myConsole.log(node.value); // после печатаем
} else
myConsole.log('Сложность алгоритма по времени O ( N ) \n по памяти O ( N ) \n линейная зависимость от входных данных \n');
}
}
}
import flash.geom.Point;
import flash.events.Event;
import flash.utils.Dictionary;
import flash.ui.Keyboard;
import flash.events.FocusEvent;
import flash.text.TextFieldType;
import flash.events.TextEvent;
import flash.events.KeyboardEvent;
import flash.display.Stage;
import flash.text.TextField;
import flash.display.Sprite;
Class {
class Node {
public var next:Node;
public var value:String;
public function Node(value:String, next:Node=null){
this.value = value;
if(next){
this.next = next;
}
}
}
}
Class
{
class Console extends Sprite {
private var consoleField:TextField = new TextField();
private var descript:Array = ['help', 'clear console'];
private var diction:Dictionary = new Dictionary();
public function Console(stage:Stage) {
consoleField.background = true;
consoleField.type = TextFieldType.INPUT;
consoleField.backgroundColor = 0x333333;
consoleField.alpha = .6;
consoleField.textColor = 0xf2f9ff;
consoleField.width = stage.stageWidth;
consoleField.height = 300;
consoleField.scaleX = consoleField.scaleY = 1.4;
stage.addChild(consoleField);
//log(this);
consoleField.addEventListener(FocusEvent.FOCUS_IN, clear);
consoleField.addEventListener(KeyboardEvent.KEY_UP, upKey);
//diction['-h'] = {func: help, descript: 'help function trace'};
//diction['-c'] = {func: clear, descript: 'clear work zone'};
}
public function log(str:Object):void {
if(!str is String){
str.toString();
}
consoleField.appendText(str+'\n');
}
public function addComand(comand:String, toCall:Function, desc:String="no descript"):void{
diction[comand] = {func: toCall, descript: desc};
}
private function upKey(e:KeyboardEvent):void{
if(e.keyCode == Keyboard.ENTER){
// parse
var key:String = '';
for(var i:int = 1; i<=4; i++){
key = consoleField.text.charAt(consoleField.text.length-i)+key;
if(diction[key] != null){
(diction[key].func as Function).call();
return;
}
}
}
}
public function clear(event:FocusEvent = null):void{
consoleField.text = '';
}
public function help():void {
log('\nЧтобы добавить 5 узлов и напечатать нажмите Enter');
for (var key:Object in diction)
{
log(key +"\t "+ diction[key].descript);
}
}
}
}