// GA constructor public GA(Initializer init, Fitness fit, Mutate mutater, CrossOver crossOver) { computeFitness = fit; initChromo = init; crossoverProc = crossOver; mutateProc = mutater; }
public GeneticAlgorithm() { crossover = CrossOverPMX; selection = Tornament; CrossOverRate = ConfigurationGA.rateCrossOver; MutationRate = ConfigurationGA.rateMutation; }
private void Init( int numberOfGenerations, CompareEvaluate compareTwo, Evaluate evaluate, CrossOver crossoverOp, Generate generator, List <IIndividual> population) { Maximize = false; EliminatedPercent = 0.2f; ElitismPercent = 0.1f; _NumberOfGenerations = numberOfGenerations; if (population != null) { _Population = population .Select(i => i.ToEI()) .ToList(); _PopSize = population.Count; } _Tournament = null; _GenerationCount = 0; _Compare = compareTwo; _Eval = evaluate; _Generate = generator; _Crossover = crossoverOp; _Champions = new List <EvaluatedIndividual>(_NumberOfGenerations); VariationSettings = new VariationSettings(6, 4, 2); _Rng = new Random(); _mutationProbability = 0.6f; _mutationSigma = 1; Threads = 4; }
public StraightThrough(StraightConveyorInfo info, ThreeWaySwitch _threeWaySwitch) : base(info) { straightConveyorInfo = info; threeWaySwitch = _threeWaySwitch; _threeWaySwitch.AllRoutes.Add(this); WaitingConveyors.Add(ThreeWayRoutes.Left, waitingForLeft); WaitingConveyors.Add(ThreeWayRoutes.Right, waitingForRight); WaitingConveyors.Add(ThreeWayRoutes.Center, waitingForCenter); Length = threeWaySwitch.threeWaySwitchInfo.threeWayLength; endAP = TransportSection.Route.InsertActionPoint(Length - 0.3f); startAP = TransportSection.Route.InsertActionPoint(0.3f); startAP.OnEnter += startAP_OnEnter; endAP.OnEnter += endAP_OnEnter; crossOverX = new CrossOver(Core.Environment.Scene.DefaultColor, 1, 0.05f, 0.3f, _threeWaySwitch) { straightThrough = this }; crossOverY = new CrossOver(Core.Environment.Scene.DefaultColor, 1, 0.05f, 0.3f, _threeWaySwitch) { straightThrough = this }; Add(crossOverX); Add(crossOverY); RouteAvailable = RouteStatuses.Request;//3 way will control the release of loads onto the transfer _threeWaySwitch.OnDimensionsChanged += threeWaySwitch_OnDimensionsChanged; StartFixPoint.OnSnapped += StraightStartFixPoint_OnSnapped; StartFixPoint.OnUnSnapped += StraightStartFixPoint_OnUnSnapped; OnNextRouteStatusAvailableChanged += StraightThrough_OnNextRouteStatusAvailableChanged; }
public override int GetHashCode() { int hash = 17; hash = hash * 23 + CrossOver.GetHashCode(); hash = hash * 23 + Mutate.GetHashCode(); return(hash); }
public GeneticAlgo(Fitness fitness, Population population, Selection selection, CrossOver crossover, Mutation mutation) { Population = population; _fitness = fitness; _selection = selection; _crossover = crossover; _mutation = mutation; }
public State <T> Step() { State = Killer.Kill(State); State = CrossOver.CrossOver(State); //State = Mutator.Mutate(State); return(State); }
public void Test_That_Genetic_Algorithm_On_Sphere_Works() { GeneticAlgorithm <double[]> garden = new GeneticAlgorithm <double[]>((double[] sol1, double[] sol2) => { return(CrossOver.CutAndSplice <double>(sol1, sol2)[0].ToArray()); }); Sphere sphere = new Sphere(); garden.create(sphere.getConfiguration()); garden.fullIteration(); }
public void Test_That_Knapsack_Genetic_Algorithm_Works() { this.Load(Constants.SAMPLE_MKNAPCB4_DATASET); Console.WriteLine($"Goal:\t{this.goal}"); GeneticAlgorithm <List <int> > ga = new GeneticAlgorithm <List <int> >((List <int> sol1, List <int> sol2) => { return(CrossOver.CutAndSplice <int>(sol1.AsEnumerable(), sol2.AsEnumerable())[0].ToList()); }); ga.create(this.getConfiguration()); List <int> finalSolution = ga.fullIteration(); }
public Ages( int numberOfGenerations, Evaluate eval, CrossOver crossOverOp, Generate generator, List <IIndividual> individuals) { Init(numberOfGenerations, null, eval, crossOverOp, generator, individuals); }
public Ages( int numberOfGenerations, CompareEvaluate compareTwo, CrossOver crossoverOp, Generate generator, List <IIndividual> population) { Init(numberOfGenerations, compareTwo, null, crossoverOp, generator, population); }
public Ages( int numberOfGenerations, CompareEvaluate compareTwo, CrossOver crossoverOp, Generate generator, int popSize) { Init(numberOfGenerations, compareTwo, null, crossoverOp, generator, null); _PopSize = popSize; }
public Ages( int numberOfGenerations, Evaluate eval, CrossOver crossOverOp, Generate generator, int popSize) { Init(numberOfGenerations, null, eval, crossOverOp, generator, null); _PopSize = popSize; }
public static void NextGen() { Genome c1 = new Genome(false); Genome c2 = new Genome(false); RouletteWheelSelection select = new RouletteWheelSelection(); CrossOver cross = new CrossOver(); cross.SinglePointCrossOver(select.RouletteWheelSelect(), select.RouletteWheelSelect(), ref c1, ref c2); Mutate(ref c1); Mutate(ref c2); genome.Add(c1); genome.Add(c2); if (genome.Count == DNAattributes.PopulationSize) { DNAattributes.pop = genome; } }
//sets up the initial GA public GeneticAlgo CreateGA(string[][] _sampleGenomes) { System.Random r = new System.Random(Time.frameCount); //specify the numbers of genes to the population. string selectType = "god mode"; string mutateType = "randomChoice"; string crossType = "OnePt"; Encoder encoder = _encode; Fitness fitness = new Fitness(""); Population population = new Population(_childCount, encoder._symbols, samplePopulation: _sampleGenomes, variableGenomeLength: true); Selection selection = new Selection(selectType); CrossOver crossover = new CrossOver(crossType); Mutation mutation = new Mutation(mutateType, _mutationRate); return(new GeneticAlgo(encoder, fitness, population, selection, crossover, mutation)); }
public void CreateGA() { System.Random r = new System.Random(Time.frameCount); string selectType = "god mode"; string mutateType = "randomChoice"; string crossType = "OnePt"; Encoder encoder = new Encoder(); string target = encoder.Encode(TextureNoise.CreateNoise(width, height, r)); Fitness fitness = new Fitness(target); Population population = new Population(20, fitness._targetString) { _name = "images" }; Selection selection = new Selection(selectType); CrossOver crossover = new CrossOver(crossType); Mutation mutation = new Mutation(mutateType); geneticAlgo = new GeneticAlgo(encoder, fitness, population, selection, crossover, mutation); }
private void btnSearch_Click(object sender, EventArgs e) { isInSearch = true; if (!isValidNumberOfCities()) { MessageBox.Show("Số thành phố tối thiểu phải bằng 4 !", "Cảnh báo"); return; } distanceMatrix = ComputeDistances(points); // tính ma trận khoảng cách từ ma trận điểm đã cho Initializer khoitaomoi = new Initializer(InitialGA.khoitaoNST); Mutate dotbien = new Mutate(InitialGA.Compraror_NST); Fitness phepthichnghi = new Fitness(InitialGA.Thichnghi); CrossOver pheplaighep = new CrossOver(InitialGA.Laighep); //tao doi tuong moi GA GeneticSolver = new GA(khoitaomoi, phepthichnghi, dotbien, pheplaighep); GeneticSolver.Generations = (long)numGenLimit.Value; GeneticSolver.PopulationSize = (ushort)numPopSize.Value; GeneticSolver.Mutation = (double)numMutation.Value; GeneticSolver.CrossOver = (double)numCrossOver.Value; // Khoi tao thuat toan GeneticSolver.Initialize(); // kiem tra dieu kien dung // chua thoa man thuc hien tao the he moi while (!GeneticSolver.IsStop()) { GeneticSolver.CreateNextGeneration(); } // Lay ra phan tu co do thich nghi tot nhat trong quan the solutionChromo = GeneticSolver.GetBestChromosome(); // Vẽ phương án lên bản đồ ptbMap.Refresh(); DrawPath(solutionChromo); DrawPoints(); }
void Cross() { newIndividuals = new Individual[individuals.Length]; if (CrossOver == null || Selection == null) { return; } int length = Selection.Selected.Length % 2 == 0 ? Selection.Selected.Length : Selection.Selected.Length - 1; int index = 0; // Offsprings for (int i = 0; i < length; i += 2) { CrossOver.Cross( individuals[Selection.Selected[i]], individuals[Selection.Selected[i + 1]]); newIndividuals[index++] = CrossOver.Offspring1.Clone(); newIndividuals[index++] = CrossOver.Offspring2.Clone(); } // Parents for (int i = 0; i < length && index < newIndividuals.Length; i++) { newIndividuals[index++] = individuals[Selection.Selected[i]].Clone(); } // XXX: for safety while (index < newIndividuals.Length) { int i = random.Next(individuals.Length); newIndividuals[index++] = individuals[i].Clone(); } }
public void OnClickAdd() { string selectType = dSelect.options [dSelect.value].text; string mutateType = dMutate.options [dMutate.value].text; string crossType = dCross.options [dCross.value].text; if (geneticAlgos.Count < maxPops) { Fitness fitness = new Fitness(targetString); Population population = new Population(popSize, fitness._targetString) { _name = (geneticAlgos.Count + 1).ToString() }; Selection selection = new Selection(selectType); CrossOver crossover = new CrossOver(crossType); Mutation mutation = new Mutation(mutateType); geneticAlgos.Add(new GeneticAlgo(fitness, population, selection, crossover, mutation)); } else { Debug.Log("Population Limit Reached : 5 is the Maximum Number of geneticAlgos"); } }
static void Main(string[] args) { List <Vehicle> vehicles = new List <Vehicle>(); List <Driver> drivers = new List <Driver>(); Driver erez = new Driver(200, "Erez"); Driver ron = new Driver(130, "Ron"); Driver ido = new Driver(220, "Ido"); SportCar mazdaCar = new SportCar(0, "Toyota", "Red", 150); CrossOver suzukiCrossOver = new CrossOver(1, "suzuki", "black", 100); Bicycle bmx = new Bicycle(2, "BMX", "white"); mazdaCar.FirstDriver = erez; mazdaCar.SecondDriver = ron; bmx.FirstDriver = ido; drivers.Add(erez); drivers.Add(ron); drivers.Add(ido); vehicles.Add(mazdaCar); vehicles.Add(suzukiCrossOver); vehicles.Add(bmx); string quit; string assignVehicle; string assignDriver; string position; string id; string carType; string input = "-1"; while (input != "8") { Console.WriteLine( "Please input your option -> \n\n" + "1- Add new vehicle \n" + "2- Show vehicle list \n" + "3- Delete a vehicle\n" + "4- Add new driver \n" + "5- show driver list \n" + "6- Delete a driver\n" + "7- Assign a driver\n" + "8- Exit\n" ); input = (Console.ReadLine()); if (!IsNumeric(input)) { InvalidKey(); } else { switch (input) { case "1": Console.Write( "Please choose your option-> \n" + "1- Bicycle \n" + "2- Sport Car \n" + "3- CrossOver\n" ); carType = (Console.ReadLine()); if (!IsNumeric(carType) && carType != "1" && carType != "2" && carType != "3") { InvalidKey(); } else { Vehicle temp = AddVehicleHandler(vehicles[vehicles.Count - 1].Id + 1, carType); if (temp != null) { vehicles.Add(temp); } } PressAnyKey(); break; case "2": foreach (Vehicle element in vehicles) { Console.WriteLine(element.ToString()); } PressAnyKey(); break; case "3": bool flag = true; foreach (Vehicle element in vehicles) { Console.WriteLine(element.ToString()); } Console.Write("Choose ID to remove ->"); id = Console.ReadLine(); if (!IsNumeric(id)) { InvalidKey(); PressAnyKey(); break; } else { flag = false; foreach (Vehicle element in vehicles) { if (element.Id == int.Parse(id)) { vehicles.Remove(element); flag = true; break; } } if (flag) { Console.WriteLine("Vehicle removed successfully!"); } else { Console.WriteLine("ID not found. Nothing removed."); } } PressAnyKey(); break; case "4": drivers.Add(AddDriverHandler()); PressAnyKey(); break; case "5": foreach (Driver element in drivers) { Console.WriteLine(element.ToString()); } PressAnyKey(); break; case "6": flag = true; foreach (Driver element in drivers) { Console.WriteLine(element.ToString()); } Console.Write("Choose ID to remove ->"); id = Console.ReadLine(); if (!IsNumeric(id)) { InvalidKey(); break; } else { flag = false; foreach (Driver element in drivers) { if (element.Id == int.Parse(id)) { drivers.Remove(element); flag = true; break; } } if (flag) { Console.WriteLine("Driver removed successfully!"); } else { Console.WriteLine("ID not found. Nothing removed."); } } PressAnyKey(); break; case "7": foreach (Vehicle element in vehicles) { Console.WriteLine(element.ToString()); } Console.Write("Choose Vehicle ID to assign a driver to ->"); assignVehicle = Console.ReadLine(); flag = false; foreach (Vehicle element in vehicles) { if (element.Id == int.Parse(assignVehicle)) { flag = true; Vehicle vehicle = element; break; } } if (!flag) { Console.WriteLine("ID not found, please try again."); break; } else { foreach (Driver element in drivers) { Console.WriteLine(element.ToString()); } Console.Write("Choose Driver ID to assign to the selected vehicle ->"); assignDriver = Console.ReadLine(); foreach (Driver element in drivers) { if (element.Id == int.Parse(assignDriver)) { flag = true; Driver driver = element; break; } } if (!flag) { Console.WriteLine("ID not found, please try again."); break; } else { foreach (Vehicle vehicle in vehicles) { if (vehicle.Id == int.Parse(assignVehicle)) { foreach (Driver driver in drivers) { if (driver.Id == int.Parse(assignDriver)) { if (vehicle.AmoutOfDrivers == 1) { vehicle.FirstDriver = driver; } else { Car carVehicle = (Car)vehicle; Console.Write("Which Driver position do you want to assign to? (1/2) ->"); position = Console.ReadLine(); if (!IsNumeric(position)) { InvalidKey(); flag = false; break; } else { switch (position) { case "1": carVehicle.FirstDriver = driver; break; case "2": carVehicle.SecondDriver = driver; break; default: break; } } } Console.WriteLine("Driver assigned successfully!"); PressAnyKey(); break; } } } if (!flag) { break; } } } } PressAnyKey(); break; case "8": Console.Write("Are you sure you want to quit? (y/n) ->"); quit = Console.ReadLine(); if (quit == "y") { break; } else if (quit == "n") { input = "-1"; break; } InvalidKey(); PressAnyKey(); break; default: break; } } Console.Clear(); } }
public void Run() { for (int i = 0; i < Generations; i++) { if (BeforeRun != null) { BeforeRun(this, new GeneticEventArgs(i)); } foreach (var chromosome in Population.Chromosomes) { chromosome.Fitness = Evaluator.ComputeFitness(chromosome.Genes); } Population.Chromosomes = Population.Chromosomes.OrderByDescending(x => x.Fitness).ToList(); if (BeforeKill != null) { BeforeKill(this, EventArgs.Empty); } Killer.Kill(Population); if (AfterKill != null) { AfterKill(this, EventArgs.Empty); } var selected = Selector.Select(Population.Chromosomes); if (BeforeCrossOver != null) { BeforeCrossOver(this, EventArgs.Empty); } foreach (var pair in selected) { var offspring = CrossOver.CrossOver(pair.Item1, pair.Item2); Population.AddChromosome(offspring); } if (AfterCrossOver != null) { AfterCrossOver(this, EventArgs.Empty); } if (BeforeMutate != null) { BeforeMutate(this, EventArgs.Empty); } MutateStep(Population); if (AfterMutate != null) { AfterMutate(this, EventArgs.Empty); } if (AfterRun != null) { AfterRun(this, new GeneticEventArgs(i)); } if (Solution.IsSolution(Population.Best)) { if (OnSolution != null) { OnSolution(this, EventArgs.Empty); } return; } } }
public EvaluationTrain(GettingStarted gettingStarted) { _randomSelection = new RandomSelection(gettingStarted.EarlyPopulation); _rouletteWeelSelection = new RouletteWeel2Selection(); _crossOver = new CrossOver(gettingStarted.Items, gettingStarted.KnapsakCapacity); }
private void Test_PolynomialGA(Func <double, double> func) { //Settings bool adaptive = false; int seed = 0; Utils.SetRandomSeed(seed); var rng = new Random(seed); PolynomialOrder = 5; int populationSize = 100; //number of samples to use the in the polynomial approx // to test the differnce double start = -10, end = 10; //Step between the samples double step = 0.02; //Number of generations to bundle int genBundleCount = 10; //Stop at Gen GenerationStop = 500; //Get Data for tests double[] xRange, expectedValues; GetFofXForRange(func, start, step, end, out xRange, out expectedValues); double[][] allPowsOfX = GetPowersOfX(xRange, PolynomialOrder); ExpectedValsX = xRange; ExpectedValsY = expectedValues; PowsOfXForAllX = allPowsOfX; //Create Delegates Evaluate eval = (i) => ((CartesianIndividual)i).PolynomialEval(allPowsOfX, expectedValues); CrossOver crossOver = adaptive ? AdaptiveCartesianIndividual.CrossOver : (CrossOver)CartesianIndividual.CrossOver; Generate generate = adaptive ? (Generate)((r) => new AdaptiveCartesianIndividual(PolynomialOrder, 1, r: r, emptySigma: true)) : (r) => new CartesianIndividual(PolynomialOrder, 1, r); // Generate Population List <IIndividual> pop; pop = Enumerable .Range(0, populationSize) .Select(i => generate(rng)) .Cast <IIndividual>() .ToList(); Ages = new Ages(genBundleCount, eval, crossOver, generate, pop); Ages.SetRandomSeed(seed); Ages.NicheStrat = new NicheDensityStrategy( Ages, (l, r) => CartesianIndividual.Distance((CartesianIndividual)l, (CartesianIndividual)r)); }
static void Main(string[] args) { Console.Write("Enter a Number: "); string userInput = Console.ReadLine(); Console.WriteLine("Your Number is: {0}", userInput); var dictionary = new Dictionary <string, string>(); dictionary["apple"] = "A fruit or a computer company"; Console.WriteLine(dictionary["apple"]); var someList = new List <int>(); someList.Add(1); someList.Add(2); someList.Add(3); someList.Add(5); someList.Add(8); someList.Add(11); someList.RemoveAt(0); someList.RemoveAt(2); for (int i = 0; i < someList.Count; i++) { Console.WriteLine(someList[i]); } foreach (int number in someList) { Console.WriteLine(number); } someList.ForEach(number => Console.WriteLine(number)); someList.ForEach(Console.WriteLine); string[] names = { "John", "Daryl", "Mike", "Sarah", "Michele" }; string[] moreNames = new string[5]; moreNames[0] = "John"; moreNames[1] = "Daryl"; Console.WriteLine("Size of names: {0}\nSize of moreNames: {1}", names.Length, moreNames.Length); // and so on string student = "John Smith"; char firstCharacter = student[1]; // ---- Exercise for loops ---- var animals = new List <string>(); animals.Add("Lion"); animals.Add("Tiger"); animals.Add("Bird"); animals.Add("Cat"); animals.Add("Dog"); animals.Add("Leopard"); string favoriteAnimal = "Bird"; foreach (string animal in animals) { Console.WriteLine(animal); } if (animals.Contains(favoriteAnimal)) { Console.WriteLine("I love {0} and also every other animal, including {1}", favoriteAnimal, animals[2]); // same as the above line, but without the placeholder Console.WriteLine("I love " + favoriteAnimal + "and also every other animal, including " + animals[2]); } else { Console.WriteLine("No, I don't care for those"); } // dictionary looping var person = new Dictionary <string, int>(); person.Add("Joan", 22); person.Add("Daniel", 42); person.Add("Anna", 34); // person = {Joan=22, Daniel=42, Anna=34} // loop through the hash map and return each key/value pair for (int i = 0; i < person.Count; i++) { Console.WriteLine("Key: {0}, Value: {1}", person.Keys.ElementAt(i), person[person.Keys.ElementAt(i)]); } foreach (var peep in person) { // print out the key (their name) and their value Console.WriteLine("Name: {0}, Age: {1}", peep.Key, peep.Value); } var studentData = new Dictionary <string, string>(); studentData["name"] = "Fred"; studentData["age"] = "20"; studentData["hometown"] = "Seattle"; studentData["favorite_food"] = "Pizza"; Console.WriteLine("This is {0}", studentData["name"]); Console.WriteLine("They are {0} years old", studentData["age"]); Console.WriteLine("from {0}", studentData["hometown"]); Console.WriteLine("and their favorite food is {0}", studentData["favorite_food"]); var students = new Dictionary <string, Dictionary <string, string> >(); students["Fred"] = new Dictionary <string, string>(); students["Fred"].Add("name", "Fred"); students["Fred"].Add("age", "20"); students["Fred"].Add("hometown", "Seattle"); students["Fred"].Add("favorite_food", "Pizza"); Console.WriteLine("This is {0}", students["Fred"]["name"]); var students2 = new Dictionary <string, Student>(); var someStudent = new Student("Fred", 20, "Seattle", "Pizza"); students2.Add("Fred", someStudent); var anotherStudent = new Student("Sally", 21, "Columbus", "Pasta"); students2.Add("Sally", anotherStudent); var studentWithNoData = new Student(); var sedan = new Car("blue", 4); sedan.Start(); sedan.Stop(); sedan.Drive(); Console.WriteLine("Car color: {0}", sedan.Color); Console.WriteLine("Number of Doors: {0}", sedan.NumberOfDoors); var coup = new Car("red", 2); var compact = new Car("blue"); Car.Compare(sedan, new Car()); int maxDoors = Car.MAX_DOORS; coup.Type = CarType.SPORTY; coup.NumberOfDoors = 4; if (coup == sedan) { Console.WriteLine("not sure how, but a coup and sedan are the same?"); } if (coup.Equals(sedan)) { Console.WriteLine(""); } Console.WriteLine(coup.ToString()); var vehicle = new Vehicle(); var genericAnimal = new Animal(0, "amoeba"); genericAnimal.Announce(); var bear = new Bear(1, "Yogi", 9999); bear.Announce(); var vehicles = new List <Vehicle>(); vehicles.Add(new Truck()); vehicles.Add(sedan); vehicles.Add(coup); vehicles.Add(compact); var vehicles2 = new List <IVehicle>(); var rallyCar = new RallyCar(); vehicles2.Add(new Truck()); vehicles2.Add(new Motorcycle()); vehicles2.Add(sedan); vehicles2.Add(coup); vehicles2.Add(compact); vehicles2.Add(rallyCar); var crossOver = new CrossOver(); // this won't work, because crossover doesn't implement // the IVehicle interface //vehicles2.Add(crossOver); foreach (var v in vehicles2) { v.Accelerate(10); } Drive(rallyCar); Drive(sedan); Drive(new Truck()); var pupil = new Student("John Smith", 19, "Columbus", "Pizza"); var teacher = new Teacher("Jane Doe", 31); PrintInfo(pupil); PrintInfo(teacher); // Page 21 in interfaces and extension methods example Console.WriteLine("-----------------------"); }
static void Main(string[] args) { Console.Write("Enter a Number: "); string userInput = Console.ReadLine(); Console.WriteLine("Your Number is: {0}", userInput); var dictionary = new Dictionary <string, string>(); dictionary["apple"] = "A fruit or a computer company"; Console.WriteLine(dictionary["apple"]); var someList = new List <int>(); someList.Add(1); someList.Add(2); someList.Add(3); someList.Add(5); someList.Add(8); someList.Add(11); someList.RemoveAt(0); someList.RemoveAt(2); for (int i = 0; i < someList.Count; i++) { Console.WriteLine(someList[i]); } foreach (int number in someList) { Console.WriteLine(number); } someList.ForEach(number => Console.WriteLine(number)); someList.ForEach(Console.WriteLine); string[] names = { "John", "Daryl", "Mike", "Sarah", "Michele" }; string[] moreNames = new string[5]; moreNames[0] = "John"; moreNames[1] = "Daryl"; Console.WriteLine("Size of names: {0}\nSize of moreNames: {1}", names.Length, moreNames.Length); // and so on string student = "John Smith"; char firstCharacter = student[1]; // ---- Exercise for loops ---- var animals = new List <string>(); animals.Add("Lion"); animals.Add("Tiger"); animals.Add("Bird"); animals.Add("Cat"); animals.Add("Dog"); animals.Add("Leopard"); string favoriteAnimal = "Bird"; foreach (string animal in animals) { Console.WriteLine(animal); } if (animals.Contains(favoriteAnimal)) { Console.WriteLine("I love {0} and also every other animal, including {1}", favoriteAnimal, animals[2]); // same as the above line, but without the placeholder Console.WriteLine("I love " + favoriteAnimal + "and also every other animal, including " + animals[2]); } else { Console.WriteLine("No, I don't care for those"); } // dictionary looping var person = new Dictionary <string, int>(); person.Add("Joan", 22); person.Add("Daniel", 42); person.Add("Anna", 34); // person = {Joan=22, Daniel=42, Anna=34} // loop through the hash map and return each key/value pair for (int i = 0; i < person.Count; i++) { Console.WriteLine("Key: {0}, Value: {1}", person.Keys.ElementAt(i), person[person.Keys.ElementAt(i)]); } foreach (var peep in person) { // print out the key (their name) and their value Console.WriteLine("Name: {0}, Age: {1}", peep.Key, peep.Value); } var studentData = new Dictionary <string, string>(); studentData["name"] = "Fred"; studentData["age"] = "20"; studentData["hometown"] = "Seattle"; studentData["favorite_food"] = "Pizza"; Console.WriteLine("This is {0}", studentData["name"]); Console.WriteLine("They are {0} years old", studentData["age"]); Console.WriteLine("from {0}", studentData["hometown"]); Console.WriteLine("and their favorite food is {0}", studentData["favorite_food"]); var students = new Dictionary <string, Dictionary <string, string> >(); students["Fred"] = new Dictionary <string, string>(); students["Fred"].Add("name", "Fred"); students["Fred"].Add("age", "20"); students["Fred"].Add("hometown", "Seattle"); students["Fred"].Add("favorite_food", "Pizza"); Console.WriteLine("This is {0}", students["Fred"]["name"]); var students2 = new Dictionary <string, Student>(); var someStudent = new Student("Fred", 20, "Seattle", "Pizza"); students2.Add("Fred", someStudent); var anotherStudent = new Student("Sally", 21, "Columbus", "Pasta"); students2.Add("Sally", anotherStudent); var studentWithNoData = new Student(); var sedan = new Car("blue", 4); sedan.Start(); sedan.Stop(); sedan.Drive(); Console.WriteLine("Car color: {0}", sedan.Color); Console.WriteLine("Number of Doors: {0}", sedan.NumberOfDoors); var coup = new Car("red", 2); var compact = new Car("blue"); Car.Compare(sedan, new Car()); int maxDoors = Car.MAX_DOORS; coup.Type = CarType.SPORTY; coup.NumberOfDoors = 4; if (coup == sedan) { Console.WriteLine("not sure how, but a coup and sedan are the same?"); } if (coup.Equals(sedan)) { Console.WriteLine(""); } Console.WriteLine(coup.ToString()); var vehicle = new Vehicle(); var genericAnimal = new Animal(0, "amoeba"); genericAnimal.Announce(); var bear = new Bear(1, "Yogi", 9999); bear.Announce(); var vehicles = new List <Vehicle>(); vehicles.Add(new Truck()); vehicles.Add(sedan); vehicles.Add(coup); vehicles.Add(compact); var vehicles2 = new List <IVehicle>(); var rallyCar = new RallyCar(); vehicles2.Add(new Truck()); vehicles2.Add(new Motorcycle()); vehicles2.Add(sedan); vehicles2.Add(coup); vehicles2.Add(compact); vehicles2.Add(rallyCar); var crossOver = new CrossOver(); // this won't work, because crossover doesn't implement // the IVehicle interface //vehicles2.Add(crossOver); foreach (var v in vehicles2) { v.Accelerate(10); } Drive(rallyCar); Drive(sedan); Drive(new Truck()); var pupil = new Student("John Smith", 19, "Columbus", "Pizza"); var teacher = new Teacher("Jane Doe", 31); PrintInfo(pupil); PrintInfo(teacher); // Page 21 in interfaces and extension methods example Console.WriteLine("-----------------------"); var dbMigrator = new DbMigrator(new ConsoleLogger()); var dbMigrator2 = new DbMigrator(new FileLogger("migrator.log")); dbMigrator.Migrate(); dbMigrator2.Migrate(); Console.WriteLine("-----------------------"); // event stuff (week 6 day 2) ProcessBusinessLogic bl = new ProcessBusinessLogic(); bl.ProcessCompleted += bl_ProcessCompleted; // register with an event bl.ProcessCompleted += bl_ProcessUpdated; bl.StartProcess(); var myProcess = new PhotoProcessor(); var filters = new PhotoFilters(); Action <Photo> filterHandler = filters.ApplyContrast; filterHandler += filters.ApplyBrightness; filterHandler += RemoveRedEyeFilter; myProcess.Process("pic.jpg", filterHandler); // lambda function takes in a number and then squares it Func <int, int> squareFunction = num => num * num; // in our case, it passes in 3 and returns 9 Console.WriteLine(squareFunction(3)); const int factor = 5; Func <int, int> multiplier = num => num * factor; int result = multiplier(10); Console.WriteLine(multiplier(6)); Console.WriteLine(result); Func <int, int, int, double> pythagoreanTheorem = (a, b, c) => Math.Pow(a, 2) + Math.Pow(b, 2) + Math.Pow(c, 2); double result2 = pythagoreanTheorem(1, 2, 3); Console.WriteLine(pythagoreanTheorem(2, 3, 4)); Console.WriteLine(result2); var library = new BookRepository(); List <Book> books = library.Books; List <Book> cheapBooks = books.FindAll(book => book.Price < 10); foreach (var book in cheapBooks) { Console.WriteLine(book.Title); } Console.ReadKey(); }