Posts

Showing posts from July, 2017

Obtaining combinations of k elements from n in C#

Image
I needed an algorithm that could return all combinations of k number of elements within a finite set of n elements. Furthermore I wanted the algorithm to work in a non-recursive (iterative) way in C#. Step forward StackOverflow, specifically this answer given by Juan Antonio Cano I've taken his code and just made one or two modifications, as suggested by ReSharper . Full code listing for the console app as shown: Program.cs [code language="csharp"] using System; using System.Collections; using System.Collections.Generic; using System.Linq; namespace Techniques { public static class Program { private static bool NextCombination(IList<int> num, int n, int k) { bool finished; var changed = finished = false; if (k <= 0) return false; for (var i = k - 1; !finished && !changed; i--) { if (num[i] < n - 1 - (k - 1) + i) { num[i]++; ...

Applying the 2-opt algorithm to travelling salesman problems in C# / WPF

Image
For the Java equivalent see this link: https://www.technical-recipes.com/2017/applying-the-2-opt-algorithm-to-traveling-salesman-problems-in-java/ For the C++ equivalent see this link: https://www.technical-recipes.com/2012/applying-c-implementations-of-2-opt-to-travelling-salesman-problems/ This post demonstrates how to apply the 2-opt algorithm to a number of standard test problems in C# while displaying the results in a WPF style window, while using the MVVM design pattern. See this link for an overview of the two opt algorithm. http://en.wikipedia.org/wiki/2-opt But essentially the 2-opt link swapping heuristic can be summarised by the following steps: The actual 2-opt heuristic can be summarised by the following pseudocode steps, repeating for all feasible combinations of I and k: [code language="text"] 1. take route[1] to route[i-1] and add them in order to new_route 2. take route[i] to route[k] and add them in reverse order to new_route 3. take r...

Using the Supervisor Controller Pattern to access View controls in MVVM

Image
As discussed on a StackOverflow post , this is considered bad practice, so only use this when necessary. Step 1: Create a new WPF project Step 2: Add event handling code A number of classes are needed for doing command bindings in MVVM. Create the following classes and add to your Visual Studio project: RelayCommand.cs [code language="csharp"] using System; using System.Windows.Input; namespace SupervisorControllingPattern { public class RelayCommand<T> : ICommand { private readonly Predicate<T> _canExecute; private readonly Action<T> _execute; public RelayCommand(Action<T> execute) : this(execute, null) { _execute = execute; } public RelayCommand(Action<T> execute, Predicate<T> canExecute) { if (execute == null) throw new ArgumentNullException(nameof(execute)); _execute = execute; _canExecute = canExecute; ...