簡體   English   中英

需要幫助來了解此特定代碼

[英]Need help understanding this particular code

int distance = s.ToCharArray()
                .Zip(t.ToCharArray(), (c1, c2) => new { c1, c2 })
                .Count(m => m.c1 != m.c2);

此代碼ID用於計算漢明距離,但似乎無法理解它的工作方式(我是c#的初學者)

給定兩個長度相同的字符串,漢明距離定義為每個位置的不同字符數,例如最佳測試的距離為1。您提供的代碼使用Zip函數為每個位置創建一個字符對列表(索引)。 讓我們一步一遍地檢查代碼:

假設您有以下兩個字符串:

string s = "test";  
string t = "best";

string.ToCharArray()將它們轉換為char數組:

char[] sChars = ['t', 'e', 's', 't'];
char[] tChars = ['b', 'e', 's', 't'];

然后,對sChars.Zip(tChars, (c1, c2) => new { c1, c2 }) ,創建一個字符對列表(實際上是包含兩個chars匿名類):

var zippedChars = [
     {c1 = 't', c2 = 'b'},
     {c1 = 'e', c2 = 'e'},
     {c1 = 's', c2 = 's'},
     {c1 = 't', c2 = 't'}
];

然后zippedChars.Count(m => m.c1 != m.c2)計算該對中的第一個字符不等於另一個字符的位置:

var distance = 1;

暫無
暫無

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

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