SORU
12 Kasım 2008, ÇARŞAMBA


byte[] dizi desen arama

Herkes iyi ve etkili bir bayt bir bayt deseni için eşleşme/arama yapmak için bir yol biliyor musun[] dizi ve pozisyonlar dönüş.

örneğin

= yeni desen byte [], byte[] {12,3,5,76,8,0,6,125};

byte [] = new byte toBeSearched[] {23,36,43,76,125,56,34,234,12,3,5,76,8,0,6,125,234,,211,122,22,4,7,89,76,64, 5612,3,5,76,8,0,6,125}

CEVAP
12 Kasım 2008, ÇARŞAMBA


Olabilir bir şey öneririm dizeleri, diziler kopyalama veya güvenli olmayan kod oluşturma anlamına gelmez:

using System;
using System.Collections.Generic;

static class ByteArrayRocks {

    static readonly int [] Empty = new int [0];

    public static int [] Locate (this byte [] self, byte [] candidate)
    {
        if (IsEmptyLocate (self, candidate))
            return Empty;

        var list = new List<int> ();

        for (int i = 0; i < self.Length; i  ) {
            if (!IsMatch (self, i, candidate))
                continue;

            list.Add (i);
        }

        return list.Count == 0 ? Empty : list.ToArray ();
    }

    static bool IsMatch (byte [] array, int position, byte [] candidate)
    {
        if (candidate.Length > (array.Length - position))
            return false;

        for (int i = 0; i < candidate.Length; i  )
            if (array [position   i] != candidate [i])
                return false;

        return true;
    }

    static bool IsEmptyLocate (byte [] array, byte [] candidate)
    {
        return array == null
            || candidate == null
            || array.Length == 0
            || candidate.Length == 0
            || candidate.Length > array.Length;
    }

    static void Main ()
    {
        var data = new byte [] { 23, 36, 43, 76, 125, 56, 34, 234, 12, 3, 5, 76, 8, 0, 6, 125, 234, 56, 211, 122, 22, 4, 7, 89, 76, 64, 12, 3, 5, 76, 8, 0, 6, 125 };
        var pattern = new byte [] { 12, 3, 5, 76, 8, 0, 6, 125 };

        foreach (var position in data.Locate (pattern))
            Console.WriteLine (position);
    }
}

Düzenle (İAbstract tarafından)-o zamandan beri post buradan hareket içeriğini bir cevap değil

Meraktan soruyorum, farklı cevaplar ile küçük bir kıyaslama yaptım.

Burada bir milyon yineleme için sonuçlar

solution [Locate]:            00:00:00.7714027
solution [FindAll]:           00:00:03.5404399
solution [SearchBytePattern]: 00:00:01.1105190
solution [MatchBytePattern]:  00:00:03.0658212

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • Anthony Cumia

    Anthony Cumi

    5 EYLÜL 2006
  • iNCH

    iNCH

    20 Temmuz 2009
  • Nightmare2005

    Nightmare200

    14 Ocak 2007