lechokapik
Messages postés6Date d'inscriptiondimanche 21 août 2005StatutMembreDernière intervention 7 mai 2007
-
7 mai 2007 à 17:26
SharpMao
Messages postés1024Date d'inscriptionmardi 4 février 2003StatutMembreDernière intervention 7 juin 2010
-
8 mai 2007 à 08:10
Bonjour,
Je m'en remets à vous car je pense que je vais devenir dingue
Je
dois effectuer une simple recherche dans un tableau et si dans ce
tableau il y a deux nombres égaux, une variable retient la valeur qui
est égale et c'est tout...
Donc en gros, je peux avoir un tableau du genre : 3 2 3 4 2 5 6 6 7
Et ma valeur retournée serait 3 (la première valeur en double).
Voici mon code :
Mon tabpaire est composé de valeurs aléatoires.
for (i = 0; i < tabpaire.Length - 1; i++)
{
for (j = 0; j < tabpaire.Length - 1 - i; j++)
{
if (tabpaire[j + 1] < tabpaire[j])
{
tmp = tabpaire[j];
tabpaire[j] = tabpaire[j + 1];
tabpaire[j + 1] = tmp;
}
}
}
for (i 0; i < tabpaire.Length-1 && bol 0; i++)
{
if (tabpaire[i] == tabpaire[i + 1])
{
paire = tabpaire[i];
bol = 1;
}
}
Donc, comme vous pouvez le voir, je fais d'abord un simple tri bulle et ensuite une recherche de deux nombre égaux consécutifs...
Mon problème est qu'il trouve parfois des "paires" qui ne figurent pas dans le tableau et parfois mon algorithme n'en trouve pas alors qu'il en existe... J'ai essayé pas mal de méthodes : avec des boléens, ... mais je ne m'en sors pas alors si vous pouvez m'aider, ce serait bien sympathique
for (int i = 0; i < tabpaire.Length - 1; i++)
{
for (int j = 0; j < tabpaire.Length - 1 - i; j++)
{
if (tabpaire[j + 1] < tabpaire[j])
{
int tmp = tabpaire[j];
tabpaire[j] = tabpaire[j + 1];
tabpaire[j + 1] = tmp;
}
}
}
PrintArray(tabpaire);
int bol = 0;
for (int i 0; i < tabpaire.Length - 1 && bol 0; i++)
{
if (tabpaire[i] == tabpaire[i + 1])
{
Console.WriteLine("Paire trouvée : {0}", tabpaire[i]);
}
}
Console.ReadLine();
}
static void PrintArray(int[] array)
{
if (array != null && array.Length > 0)
{
for (int i = 0; i < array.Length; ++i)
{
Console.WriteLine("{0} à la position {1}", array[i], i);
}
}
else
Console.WriteLine("Null ou vide");
}
}
SharpMao
Messages postés1024Date d'inscriptionmardi 4 février 2003StatutMembreDernière intervention 7 juin 201069 8 mai 2007 à 08:10
Ou alors, si tu ne dois retourner que la première valeur ayant une paire :
public int? GetFirstPair(int[] tabpaire)
{
Dictionary d = new Dictionary();
for( int i=0;i<tabpaire.Length;i++){
if (d.ContainsKey(tabpaire[i]))
return tabpaire[i];
else
d[tabpaire[i]] = true;
}
return null;
}
Juste un détail, si tu n'est pas habitué au C# 2.0, dans "int?", le ? signifie que le type est nullable, ce qui permet de renvoyer un null si aucune paire n'est trouvée.