1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
| int[] array = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// Au passage, j'utilise un Dictionary typé, infiniment plus pratique qu'une Hashtable
Il me semble que je te l'avais déjà fait remarquer
// Cf. https://stackoverflow.com/questions/301371/why-is-dictionary-preferred-over-hashtable
IDictionary<int, string> dictionary = new Dictionary<int, string> {
{ 1, string.Empty },
{ 2, string.Empty },
{ 3, string.Empty },
{ 6, string.Empty },
{ 7, string.Empty },
{ 8, string.Empty },
{ 9, string.Empty },
{ 10, string.Empty },
{ 11, string.Empty },
{ 12, string.Empty }
};
// Version boulot en Linq (t'as vu c'est clean et rapide)
var inBoth = array.Intersect(dictionary.Keys);
var inArrayOnly = array.Except(dictionary.Keys);
var inDictionaryOnly = dictionary.Keys.Except(array);
// Version scolaire (on considère toujours que le tableau et le dictionnaire sont triés par ordre croissant, et sans doublons)
int arrayIndex = 0;
int dictionaryIndex = 0;
int[] dictionaryKeysArray = dictionary.Keys.ToArray();
while (arrayIndex < array.Length || dictionaryIndex < dictionaryKeysArray.Length) {
if (arrayIndex >= array.Length) {
// Cas où le dictionnaire contient des valeurs plus grandes que le tableau
Console.WriteLine($"{dictionaryKeysArray[dictionaryIndex]} is only in the dictionary");
dictionaryIndex++;
}
else if (dictionaryIndex >= dictionaryKeysArray.Length) {
// Cas où le tableau contient des valeurs plus grandes que le dictionnaire
Console.WriteLine($"{array[arrayIndex]} is only in the array");
arrayIndex++;
}
else {
// Cas "normal" où on compare
if (array[arrayIndex] == dictionaryKeysArray[dictionaryIndex]) {
Console.WriteLine($"{array[arrayIndex]} is both in the array and in the dictionary");
arrayIndex++;
dictionaryIndex++;
}
else if (array[arrayIndex] > dictionaryKeysArray[dictionaryIndex]) {
Console.WriteLine($"{dictionaryKeysArray[dictionaryIndex]} is only in the dictionary");
dictionaryIndex++;
}
else {
Console.WriteLine($"{array[arrayIndex]} is only in the array");
arrayIndex++;
}
}
} |
Partager