Ce petit problème fort intéressant peut etre résolu de divers manières, mais j’ai voulu montrer comment on pouvait créer un dictionnaire en C# qui contient 2 clés, en utilisant les tuples.
[code language=”csharp”]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Exercises
{
class Program
{
static void ClosestToTarget(int[] array1, int[] array2, int target)
{
int i,
j = 0;
var dictionary = new Dictionary < Tuple ,
int > ();
int x = 0;
int[, ] totals = new int[array1.Length, array2.Length];
for (i = 0; i < array1.Length; i++)
{
for (j = 0; j < array2.Length; j++)
{
int total = array1[i] + array2[j];
totals[i, j] = total;
var key = new Tuple (i, j);
dictionary.Add(key, array1[i] + array2[j]);
}
}
foreach(KeyValuePair < Tuple , int > kvp in dictionary)
{
Console.WriteLine(“Clé = {0},{1}”, kvp.Key, kvp.Value);
}
var bestMatch = dictionary.OrderBy(e = >Math.Abs(e.Value – target)).FirstOrDefault();
i = bestMatch.Key.Item1;
j = bestMatch.Key.Item2;
Console.WriteLine(“Elément issu du premier tableau : {0} , Elément issu du deuxième tableau : {1}, La Somme = {2} qui se rapproche le plus de la cible : {3}”, array1[i], array2[j], array1[i] + array2[j], target);
}
static void Main(string[] args)
{
Console.WriteLine(“Ce programme prend en entré 2 tableau de taille n et vous donne quel pairs d’éléments des 2 tableaux se rapproche le plus d’une cible x”);
Console.WriteLine(“Veuillez entrer la taille des tableaux:”);
int size = 0;
while (!int.TryParse(Console.ReadLine(), out size))
Console.Write(“Attention, la valeur doit être un entier. Veuillez réessayer”);
int[] array1 = new int[size];
int[] array2 = new int[size];
int i;
Console.WriteLine(“Entrez les {0} chiffres pour le premier tableau:”, size);
for (i = 0; i < size; i++)
{
while (!int.TryParse(Console.ReadLine(), out array1[i]))
Console.Write(“Attention, la valeur doit être un entier. Veuillez réessayer”);
}
Console.WriteLine(“Entrez les {0} chiffres pour le deuxième tableau:”, size);
for (i = 0; i < size; i++)
{
while (!int.TryParse(Console.ReadLine(), out array2[i]))
Console.Write(“Attention, la valeur doit être un entier. Veuillez réessayer”);
}
Console.WriteLine(“Entrez la cible:”);
int target = Convert.ToInt32(Console.ReadLine());
ClosestToTarget(array1, array2, target);
Console.ReadLine();
}
}
}
[/code]