Chapter 9 Example 1
♥0 |
Line 60 |
Modified 2009-06-19 20:33:03 |
MIT License
archived:2017-03-09 11:43:46
ActionScript3 source code
/**
* Copyright actionscriptbible ( http://wonderfl.net/user/actionscriptbible )
* MIT License ( http://www.opensource.org/licenses/mit-license.php )
* Downloaded from: http://wonderfl.net/c/tNyc
*/
package {
import com.actionscriptbible.Example;
public class ch9ex1 extends Example {
protected var peopleVector:Vector.<Person>;
protected const roger:Person = new Person("Roger");
protected const sabrina:Person = new Person("Sabrina");
protected const tawnie:Person = new Person("Tawnie");
protected const usman:Person = new Person("Usman");
protected const victoria:Person = new Person("Victoria");
public function ch9ex1() {
peopleVector = new Vector.<Person>();
peopleVector.push(roger, sabrina, tawnie, usman, victoria);
for each (var person:Person in peopleVector) {
roger.addFriendSymmetric(person);
}
sabrina.addFriendSymmetric(tawnie);
var tawniesFriend:Person = new Person("Mary Alice");
tawnie.addFriendSymmetric(tawniesFriend);
var nixon:Person = new Person("Richard Nixon");
trace("is Mary Alice connected to Victoria?");
trace(tawniesFriend.isConnectedTo(victoria)); //true
//Mary Alice -> Tawnie -> Roger -> Victoria
trace("is Roger connected to Richard Nixon?");
trace(roger.isConnectedTo(nixon)); //false
}
}
}
import flash.utils.Dictionary;
class Person {
public var name:String;
private var friends:Vector.<Person>;
public function Person(name:String) {
this.name = name;
friends = new Vector.<Person>();
}
public function addFriend(newFriend:Person):void {
friends.push(newFriend);
}
public function addFriendSymmetric(newFriend:Person):void {
addFriend(newFriend);
newFriend.addFriend(this);
}
public function isFriendsWith(person:Person):Boolean {
return (friends.indexOf(person) != -1);
}
public function isConnectedTo(toFind:Person, met:Dictionary = null):Boolean {
var ret:Boolean = false;
if (met == null) met = new Dictionary(true);
for each (var contact:Person in friends) {
if (!(contact in met)) {
met[contact] = true;
if (contact == toFind) {
return true; //found them!
} else {
ret ||= contact.isConnectedTo(toFind, met);
}
}
}
return ret;
}
}