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 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace RenduDeMonaie
{
class Program
{
static void Main( string[] args )
{
int somme = 400;
int[] monaies = { 200, 100, 50, 20, 10, 5, 2, 1 };
AfficherObjectif( somme, monaies );
int numero = 1;
foreach ( int[] combinaison in Combinaisons( somme, monaies ) )
{
AfficherSolution( numero, monaies, combinaison );
numero++;
}
}
static void AfficherObjectif( int somme, int[] monaies )
{
Console.WriteLine( "Objectif : {0}", somme );
Console.Write( "Monaie : " );
for ( int i = 0 ; i < monaies.Length ; i++ )
{
Console.Write( monaies[i] );
Console.Write( '/' );
}
Console.WriteLine();
}
static void AfficherSolution( int numero, int[] monaies, int[] combinaison )
{
Console.Write( " >{0} : ", numero );
for ( int i = 0 ; i < monaies.Length ; i++ )
{
Console.Write( combinaison[i] );
Console.Write( "(" );
Console.Write( monaies[i] );
Console.Write( ")/ " );
}
Console.WriteLine();
}
static IEnumerable<int[]> Combinaisons( int somme, int[] monaies )
{
int positionUnite = monaies.Length - 1;
int[] cumuls = new int[monaies.Length];
int[] valeurs = new int[monaies.Length];
cumuls.Initialize();
valeurs.Initialize();
bool continuer = true;
while ( continuer )
{
valeurs[positionUnite] = somme - (cumuls[positionUnite - 1] / monaies[positionUnite]);
cumuls[positionUnite] = cumuls[positionUnite - 1] + (valeurs[positionUnite] * monaies[positionUnite]);
if ( cumuls[positionUnite] == somme )
yield return valeurs;
continuer = Suivant( valeurs, cumuls, monaies, somme, positionUnite );
}
}
static bool Suivant( int[] valeurs, int[] cumuls, int[] monaies, int somme, int positionUnite )
{
int index = positionUnite - 1;
while ( index >= 0 )
{
valeurs[index]++;
cumuls[index] = (index == 0 ? 0 : cumuls[index - 1]) + valeurs[index] * monaies[index];
if ( cumuls[index] > somme )
{
cumuls[index] = 0;
valeurs[index] = 0;
index--;
}
else
return true;
}
return false;
}
}
} |
Partager