Domanda

Supponi di avere un IEnumerable chiamato S di lunghezza N. Vorrei selezionare tutte le sottosequenze continue di lunghezza n < = N da S.

Se S fosse, diciamo, una stringa, sarebbe abbastanza facile. Ci sono (S.Length - n + 1) sottosequenze di lunghezza n. Ad esempio, " abcdefg " è lunghezza (7), quindi significa che ha (5) sottostringhe di lunghezza (3): "abc", "bcd", "cde", "cit" def "," efg ".

Ma S potrebbe essere qualsiasi IEnumerable, quindi questa route non è aperta. Come posso utilizzare i metodi di estensione per risolvere questo problema?

È stato utile?

Soluzione

F # ha una funzione di libreria chiamata Seq.windowed per questo.

http://research.microsoft.com/en-us/um/cambridge/projects/fsharp/manual/FSharp.Core/Microsoft.FSharp.Collections.Seq.html

// windowed : int -> seq<'a> -> seq<array<'a>>
let windowed n (s: seq<_>) =    
    if n <= 0 then Helpers.invalid_arg2 "n" "the window size must be positive"
    { let arr = Array.zero_create n 
      let r = ref (n-1)
      let i = ref 0 
      use e = s.GetEnumerator() 
      while e.MoveNext() do 
          do arr.[!i] <- e.Current
          do i := (!i + 1) % n 
          if !r = 0 then 
              yield Array.init n (fun j -> arr.[(!i+j) % n])
          else 
              do r := (!r - 1) }

Altri suggerimenti

In realtà, puoi utilizzare LINQ per risolvere questo problema, ad es.

var subList = list.Skip(x).Take(y);

dove list è un IEnumerable

Puoi utilizzare l'estensione Select che fornisce l'indice per creare un oggetto contenente l'indice e il valore, quindi dividere l'indice con la lunghezza per posizionarli in gruppi:

var x = values.Select((n, i) => new { Index = i, Value = n }).GroupBy(a => a.Index / 3);
IEnumerable<IEnumerable<T>> ContiguousSubseqences<T>(this IEnumerable<T> seq, Func<T,bool> constraint)
{
    int i = 0;
    foreach (T t in seq)
    {
        if (constraint(t))
            yield return seq.Skip(i).TakeWhile(constraint);
        i++;
    }
}

Ecco un nuovo metodo di estensione per fare ciò che vuoi in C #

static IEnumerable<IEnumerable<T>> Subseqs<T>(this IEnumerable<T> xs, int n) 
{
  var cnt = xs.Count() - n;  
  Enumerable.Range(0, cnt < 0 ? 0 : cnt).Select(i => xs.Skip(i).Take(n));
} 

Per i futuri lettori.

Ecco un piccolo esempio.

    private static void RunTakeSkipExample()
    {
        int takeSize = 10; /* set takeSize to 10 */

        /* create 25 exceptions, so 25 / 10 .. means 3 "takes" with sizes of 10, 10 and 5 */
        ICollection<ArithmeticException> allArithExceptions = new List<ArithmeticException>();
        for (int i = 1; i <= 25; i++)
        {
            allArithExceptions.Add(new ArithmeticException(Convert.ToString(i)));
        }

        int counter = 0;
        IEnumerable<ArithmeticException> currentTakeArithExceptions = allArithExceptions.Skip(0).Take(takeSize);
        while (currentTakeArithExceptions.Any())
        {
            Console.WriteLine("Taking!  TakeSize={0}. Counter={1}. Count={2}.", takeSize, (counter + 1), currentTakeArithExceptions.Count());

            foreach (ArithmeticException ae in currentTakeArithExceptions)
            {
                Console.WriteLine(ae.Message);
            }

            currentTakeArithExceptions = allArithExceptions.Skip(++counter * takeSize).Take(takeSize);
        }

    }

L'output:

Taking!  TakeSize=10. Counter=1. Count=10.
1
2
3
4
5
6
7
8
9
10
Taking!  TakeSize=10. Counter=2. Count=10.
11
12
13
14
15
16
17
18
19
20
Taking!  TakeSize=10. Counter=3. Count=5.
21
22
23
24
25

Puoi vedere il .Message per ogni eccezione per verificare che ogni eccezione distinta sia stata "presa".

E ora, una citazione di un film!

  

Ma quello che ho sono un insieme molto particolare di abilità; abilità che ho   acquisito nel corso di una lunghissima carriera. Competenze che mi rendono un incubo   piace a te.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top