簡體   English   中英

比較兩個列表或C#中任意長度的數組; 順序很重要

[英]Compare two lists or arrays of arbitrary length in C#; order is important

說我有兩個列表或字符串數​​組。 例如:

清單1:“ a”,“ c”,“ b”,“ d”,“ f”,“ e”

清單2:“ a”,“ d”,“ e”,“ f”,“ h”

列表1和列表2具有任意長度。 列表1可能包含不在列表2中的元素,反之亦然。

我想知道何時在列表2中找到列表1中的項目,更具體地說,我想知道何時在列表2中找到列表1中的項目,但發現順序與在列表2中找到的順序不同。 ,相對於列表2中的項目。(希望下面的示例闡明此聲明)。

例如,在兩個列表中都找到“ a”,並且“ a”是兩個列表中的第一項。 因此,到目前為止一切正常。 “ c”和“ b”僅在第一列表中找到,因此可以忽略。 “ h”僅在第二個列表中找到,因此也可以忽略。

在第一和第二列表中都找到“ d”。 在原始列表的“ a”(第一項)之后找到它。 即使第一個列表中的位置與第二個列表中的位置不同,也可以,因為它的相對順序在兩個列表中是相同的(第二個匹配在列表之間是相同的)。

在上面的示例中,“ f”和“ e”在列表1中的順序為“錯誤”,因為在第二個列表中,“ e”出現在“ f”之前。 因此,我想在第一個列表中報告“ e”和“ f”的順序錯誤。 我該怎么做?

解決方案應該在C#中。 謝謝!


string[] list1 = {"a", "c", "b", "d", "f", "e"};
string[] list2 = {"a", "d", "e", "f", "h"};
int i = 0;
var list1a = list1.Intersect(list2).Select(l=> new { item = l, order= i++});
int j = 0;
var list2a = list2.Intersect(list1).Select(l=> new { item = l, order= j++});

var r = from l1 in list1a join l2 in list2a on l1.order equals l2.order
        where l1.item != l2.item
        select new {result=string.Format("position {1} is item [{0}] on list1  but its [{2}] in list2", l1.item, l1.order, l2.item )};

r.Dump();

結果

位置2是list1上的項目[f],但它是list2上的[e]

位置3是list1上的[e]項目,但在list2中是[f]項目

Levenshtein距離? 我認為您已經接受的第一個解決方案存在缺陷。 即使插入了一件小東西,它也會告訴您一切都亂七八糟:

      string[] list1 = { "a", "c", "b", "d", "j", "e", "f" };
      string[] list2 = { "a", "d", "e", "f", "h", "j" };

表示j,e,f亂序,因為插入了j。

這指出了您面臨的問題。 對於什么是亂序的問題,有多種解決方案,甚至不止一種最佳解決方案。 是J順序還是e和f? 他們都亂了嗎? 有一種稱為Levenshtein距離算法的東西,它找到從集合A開始到集合B結束所需的最少插入和刪除操作。有多種最佳解決方案,這里只是找到其中一種。

下面的算法正確輸出了在list1中插入的​​j和e,f的移位,但順序仍然正確。

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using Math = System.Math;

namespace LevCompareLists {

  class Program {

    static void Main(string[] args) {

      string[] list1 = { "a", "c", "b", "d", "j", "e", "f" };
      string[] list2 = { "a", "d", "e", "f", "h", "j" };

      int?[] aMap21 = Levenshtein(list2, list1);
      int?[] aMap12 = Levenshtein(list1, list2);

    }

    public static int?[] Levenshtein(string[] Src, String[] Dst) {
      // this finds a minimum difference solution of inserts and deletes that maps Src to Dst
      // it returns the map from the perspective of Dst, i.e.:
      //   each element of the return array contains the Src index of the corresponging element in B 
      //   a null value means the element in B was inserted, and never existed in A
      //
      // Given A = {"a", "c", "b", "d", "j", "e", "f"}
      //       B = {"a", "d", "e", "f", "h", "j"};
      //
      // Levenshtein(B, A):
      //  a c b d j e f     <-- A
      //  0     1   2 3     <-- aMap
      //  a     d   e f h j <-- B
      //
      // Levenshtein(A, B):
      //  a     d   e f h j  <-- B   
      //  0     3   5 6      <-- aMap
      //  a c b d j e f      <-- A
      //
      // see: http://en.wikipedia.org/wiki/Levenshtein_distance

      int cSrc = Src.Length; //length of s
      int cDst = Dst.Length; //length of t
      if (cSrc == 0 || cDst == 0) return null;

      //**** create the Levenshtein matrix 
      // it has at 1 extra element in each dimension to contain the edges
      int[,] aLev = new int[cSrc + 1, cDst + 1]; // the matrix
      int iSrc, iDst;
      // Load the horizontal and vertical edges
      for (iSrc = 0; iSrc <= cSrc; aLev[iSrc, 0] = iSrc++) ;
      for (iDst = 0; iDst <= cDst; aLev[0, iDst] = iDst++) ;
      // load the interior
      for (iSrc = 1; iSrc <= cSrc; iSrc++)
        for (iDst = 1; iDst <= cDst; iDst++)
          aLev[iSrc, iDst] = Math.Min(Math.Min(aLev[iSrc - 1, iDst] + 1, aLev[iSrc, iDst - 1] + 1),
           aLev[iSrc - 1, iDst - 1] + ((Dst[iDst - 1] == Src[iSrc - 1]) ? 0 : 2));

      DumpLevMatrix(aLev, Src, Dst);  // Debug

      //**** create the return map, using the Levenshtein matrix
      int?[] aMap = new int?[cDst];  // this is the return map
      iSrc = cSrc;  // start in lower right corner of the Levenshtein matrix
      iDst = cDst;  // start in lower right corner of the Levenshtein matrix
      // work backwards to pick best solution
      while ((iSrc >= 0) || (iDst >= 0)) {
        if ((iSrc > 0) && (iDst > 0)) {
          // enter here if iSrc and iDst are in the lev matrix and not on its edge
          int nCur = aLev[iSrc, iDst];
          int nIns = nCur - aLev[iSrc, iDst - 1];  // if move along B to find match, it was an insert
          int nDel = nCur - aLev[iSrc - 1, iDst];  // if move along A to find match, it was a deletion
          if (nIns == 1)                 // this char was NOT in A, but was inserted into B
            iDst--;                         //   Leave map of B[j] to nowher, scan to previous B (--j)
          else if (nDel == 1)            // this char was in A, but is missing in B
            iSrc--;                         //   Don't map any B, scan to previous A (--i)
          else                           // Match
            aMap[iDst-- - 1] = iSrc-- - 1;       //   After map B[j] to A[i], scan to prev A,B (--i, --j)
        } else {
          if (iDst > 0)       // remaining chars are inserts, Leave map of B[j] to nowher, scan to previous B (--j)
            iDst--;
          else if (iSrc > 0)  // Delete to the end, deletes do nothing
            iSrc--;
          else
            break;
        }
      }

      DumpMap(aMap, Dst); // Debug

      return aMap;

    }

    // just for debugging
    static void DumpLevMatrix(int[,] aLev, string[] Src, string[] Dst) {

      StringBuilder sb = new StringBuilder();
      int cSrc = Src.Length;
      int cDst = Dst.Length;
      int iSrc, iDst;
      sb.Length = 6;
      for (iDst = 0; iDst < cDst; ++iDst)
        sb.AppendFormat("{0,-3}", Dst[iDst]);
      Console.WriteLine(sb.ToString());
      for (iSrc = 0; iSrc <= cSrc; ++iSrc) {
        if (iSrc == 0)
          sb.Length = 3;
        else {
          sb.Length = 0;
          sb.AppendFormat("{0,-3}", Src[iSrc - 1]);
        }
        for (iDst = 0; iDst <= cDst; ++iDst)
          sb.AppendFormat("{0:00}", aLev[iSrc, iDst]).Append(" ");
        Console.WriteLine(sb.ToString());
      }

    }

    // just for debugging
    static void DumpMap(int?[] aMap, string[] Dst) {

      StringBuilder sb = new StringBuilder();
      for (int iMap = 0; iMap < aMap.Length; ++iMap)
        sb.AppendFormat("{0,-3}", Dst[iMap]);  // dst and map are same size
      Console.WriteLine(sb.ToString());
      sb.Length = 0;
      for (int iMap = 0; iMap < aMap.Length; ++iMap)
        if (aMap[iMap] == null)
          sb.Append("   ");
        else
          sb.AppendFormat("{0:00}", aMap[iMap]).Append(" ");
      Console.WriteLine(sb.ToString());

    }

  }
}

我沒有代碼,但這應該是兩個主要步驟:

  • 僅刪除一個列表中的所有項目(縮短其中一個列表或創建第三個“干凈”列表)
  • 某種差異-搜索第一個不匹配的項目,然后報告下一個項目,直到兩個列表再次“同步”為止。

也許它甚至有助於清理兩個列表。 然后,您可以為每個列表使用一個指針,將其設置為第一項,並增加它們直到不匹配為止。

怎么樣

list1.Intersect(list2).SequenceEquals(list2.Intersect(list1))

這個怎么樣:

string[] list1 = { "a", "c", "b", "d", "f", "e" };
string[] list2 = { "a", "d", "e", "f", "h" };

var indexedList1 = list1.Select((x, i) => new
{
    Index = i,
    Item = x
});

var indexedList2 = list2.Select((x, i) => new
    {
        Index = i,
        Item = x
    });

var intersectedWithIndexes = indexedList2
    .Join(indexedList1,
          x => x.Item,
          y => y.Item,
          (x, y) => new
        {
            ExpectedIndex = x.Index,
            ActualIndex = y.Index,
            x.Item
        })
    .Where(x => x.ActualIndex != x.ExpectedIndex)
    .ToArray();

var outOfOrder = intersectedWithIndexes
    .Select((x, i) => new
        {
            Item = x,
            index = i
        })
    .Skip(1)
    .Where(x => x.Item.ActualIndex < intersectedWithIndexes[x.index - 1].ActualIndex ||
            x.Item.ExpectedIndex < intersectedWithIndexes[x.index - 1].ExpectedIndex)
    .Select(x => new
        {
            ExpectedBefore = x.Item,
            ExpectedAfter = intersectedWithIndexes[x.index - 1]
        });

foreach (var item in outOfOrder)
{
    Console.WriteLine("'{0}' and '{1}' are out of order at index {2}",
              item.ExpectedBefore.Item,
              item.ExpectedAfter.Item,
              item.ExpectedBefore.ActualIndex);
}

輸出:

'f' and 'e' are out of order at index 4

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM