// Returns an ordered array of the instructions sorted by distance between blocks public ArrayList ShortestPath(InstructionBlock origin) { // Find the index of the origin block int? originIndex = instructionBlocks.IndexOf (origin); // Throw an error if it's not found if (originIndex < 0 || originIndex == null) { throw new ArgumentException ("You did not specify a valid origin"); } // Store the blocks that will be removed ArrayList tempBlocks = (ArrayList)instructionBlocks.Clone (); tempBlocks.Insert (0, tempBlocks[originIndex.Value]); tempBlocks.RemoveAt (originIndex.Value + 1); // This is where the ordered blocks will go ArrayList orderedBlocks = new ArrayList (); // Starts at the origin, goes through each block while (tempBlocks.Count > 1) { // Take out the origin, and then insert it into sorted blocks origin = (InstructionBlock)tempBlocks[0]; tempBlocks.RemoveAt (0); orderedBlocks.Add (origin); // Set the current shortest distance to infinity double distance = Double.PositiveInfinity; InstructionBlock shortest = null; // Examine each reamining neighbor ... if it's shorter, it's the new destination foreach (InstructionBlock destination in tempBlocks) { // If a closer block is found, it's the new destination if (origin.Distance (destination) < distance) { shortest = destination; } } // Remove the shortest block, add it to the front tempBlocks.Remove (shortest); tempBlocks.Insert (0, shortest); } // Add the final block with no neighbors orderedBlocks.Add (tempBlocks[0]); return orderedBlocks; }