Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Linq;
- using System.Collections.Generic;
- using System;
- using System.Collections;
- using System.Diagnostics;
- using System.Threading;
- using System.Threading.Tasks;
- using System.Collections.Concurrent;
- static class PExt {
- //param parametro inicial de recursion
- //expand Debe expandir un nivel de soluciones
- //mutateParam Tomando cada elemento de solucion y el parametro del nivel actual, debe crear un parametro para la recursion
- public static IEnumerable<T> FlatRecursive<T, P>(P param, Func<P, IEnumerable<T>> expand, Func<T, P, P> mutateParam) {
- var s = new Stack<Tuple<P, IEnumerable<T>>>();
- s.Push(Tuple.Create(param, expand(param)));
- while(s.Any()) {
- var curr = s.Pop();
- foreach(var x in curr.Item2) {
- yield return x;
- var newParam = mutateParam(x, curr.Item1);
- s.Push(Tuple.Create(newParam, expand(newParam)));
- }
- }
- }
- }
- namespace ParallelTest {
- class Program {
- //Esto algo mejora el uso de CPUs lo que paraleliza es el procesamiento de un segmento de rama del árbol de soluciones
- // a diferencia de lo que realmente sería poderoso, que es sobre la expansión misma y concatenacion de las ramas
- static IEnumerable<string> AllCombinationsNoRepeat_Stack(string prefix, int length) {
- return
- PExt.FlatRecursive(
- Tuple.Create(prefix, length)
- , p =>
- p.Item2 == 0
- ? new string[] { } //Cambia la semantica, porque el último trabaría en loop infinito
- // (igual llega porque la condicion de corte sucede después del pop)
- : new[] { p.Item1 }.Concat(
- Enumerable.Range(0, 9)
- .AsParallel()
- .Select(n => p.Item1+n)
- .Where(s => s.GroupBy(ch=>ch).All(g=>g.Take(2).Count() < 2))
- )
- , (x, p) => Tuple.Create(x, p.Item2-1)
- )
- ;
- }
- static void Main(string[] args) {
- foreach(var x in AllCombinationsNoRepeat_Stack("", 9))
- Console.WriteLine(x);
- Console.ReadKey();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment