Dictionary не находит ключи в коллекции - C#
Формулировка задачи:
Всем привет. Прошу помощи. Пишу программу, которая ищет все возможные повторы. Столкнулся с проблемой, когда программа рассматривает по второму кругу, например, 0х0405 байты, метод ContainsKey не определяет этот ключ в коллекции, а заводит новую запись.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.CompilerServices;
namespace Povtor
{
internal class Program
{
public static int ibytecmp(byte[] data, int fileLength, byte[] key, int lenkey, int startPos) {
int count;
for (int pos = startPos; pos <= fileLength - lenkey; pos++) {
count = 0;
for (int i = 0; i < lenkey; i++){
if (data[pos + i] == key[i])
count++;
else break;
}
if (count == lenkey)
return pos;
}
return -1;
}
private static void Main(string[] args)
{
int fileLength;
bool repeatYes = false;
if (!File.Exists(Convert.ToString(args[0]))){
Console.WriteLine("Povtor.exe <file.in>");
return;
}
Byte[] data;
data = File.ReadAllBytes(Convert.ToString(args[0]));
fileLength = data.Length;
Dictionary<byte[], int> arraysCount = new Dictionary<byte[], int>();
for (int i = 2, n = data.Length / 2; i < n; i++){
for (int k = 0, m = data.Length - i; k < m; k++){
Byte[] repeat = new byte[i];
for (int j = 0; j < i; j++)
repeat[j] = data[j + k];
int startFrom = 1 + k;
int result = ibytecmp(data, fileLength, repeat, repeat.Length, startFrom);
while (result != -1){
if (arraysCount.ContainsKey(repeat))
arraysCount[repeat]++;
else
arraysCount.Add(repeat, 2);
startFrom = result + 1;
repeatYes = true;
result = ibytecmp(data, fileLength, repeat, repeat.Length, startFrom);
}
}
}
StreamWriter sr1 = new StreamWriter(System.IO.Path.GetFileNameWithoutExtension(Convert.ToString(args[0])) + ".povtor", false, Encoding.Default);
foreach (KeyValuePair<byte[], int> item in arraysCount.OrderByDescending(x => x.Value)){
string hex = null;
foreach (byte bt in item.Key)
hex += String.Format("{0:x2}", bt);
sr1.WriteLine("0x" + hex + "\t" + item.Value.ToString() + " раз " + hex.Length/2 + " байт ");
}
sr1.Close();
}
}
}Решение задачи: «Dictionary не находит ключи в коллекции»
textual
Листинг программы
using System;
using System.Collections.Generic;
class Program
{
public static void Main()
{
string s;
while (!String.IsNullOrEmpty(s = Console.ReadLine()))
{
Dictionary<string, bool> multiplicity = new Dictionary<string, bool>();
for (int i = 0; i < s.Length - 1; i++)
{
for (int j = 2; j <= Math.Min(s.Length - i, s.Length / 2); j++)
{
string t = s.Substring(i, j);
multiplicity[t] = multiplicity.ContainsKey(t);
}
}
foreach (var kvp in multiplicity)
{
if (kvp.Value) Console.WriteLine(kvp.Key);
}
Console.WriteLine();
}
}
}