IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Algorithmes et structures de données Discussion :

Problème type "le compte est bon" en plus simple


Sujet :

Algorithmes et structures de données

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre chevronné
    Profil pro
    Inscrit en
    Octobre 2002
    Messages
    707
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Octobre 2002
    Messages : 707
    Par défaut Problème type "le compte est bon" en plus simple
    Problème type "le compte est bon" en plus simple... mais qui reste compliqué pour moi !

    Bonjour,

    Voici mon problème:
    - une valeur "objectif" à atteindre
    - un certain nombre de "plaquettes" composées uniquement des chiffres "2" et "3", dont les valeurs ne peuvent être *que* multipliées entre-elles
    -> déterminer le nombre minimum de plaquettes nécessaires pour atteindre ou approcher au mieux la valeur donnée, sans jamais être en-dessous.

    Ex:
    - objectif = 35
    - plaquettes disponibles: 2, 2, 2, 3, 3, 3
    -> solution: 3, 3, 2, 2; car (3 x 3 x 2 x 2) = 36, valeur approchant au mieux l'objectif de 35, sans être en-dessous.

    La valeur de l'objectif peut varier, le nombre de plaquettes de chaque valeur peut varier, mais pas leurs valeurs, toujours 2 ou 3.

    Autre ex:
    - objectif = 6
    - plaquettes disponibles: 2, 3, 3, 3, 3
    -> solution: 3, 2; car (3 x 2) = 6.

    Il faut donc utiliser le moins de plaquettes possibles parmi la liste proposée pour obtenir par la multiplication une valeur au moins égale et la plus proche possible de l'objectif.

    Ça paraît simple à faire de tête, mais je n'arrive pas à convertir l'intuition en algorithme... auriez-vous une piste, une idée ?

    Merci...

  2. #2
    Membre Expert
    Avatar de kwariz
    Homme Profil pro
    Chef de projet en SSII
    Inscrit en
    Octobre 2011
    Messages
    898
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 52
    Localisation : France, Moselle (Lorraine)

    Informations professionnelles :
    Activité : Chef de projet en SSII
    Secteur : Conseil

    Informations forums :
    Inscription : Octobre 2011
    Messages : 898
    Par défaut
    Citation Envoyé par GoustiFruit Voir le message
    Problème type "le compte est bon" en plus simple... mais qui reste compliqué pour moi !

    Bonjour,

    Voici mon problème:
    - une valeur "objectif" à atteindre
    - un certain nombre de "plaquettes" composées uniquement des chiffres "2" et "3", dont les valeurs ne peuvent être *que* multipliées entre-elles
    -> déterminer le nombre minimum de plaquettes nécessaires pour atteindre ou approcher au mieux la valeur donnée, sans jamais être en-dessous.

    [...]

    Merci...

    Hello,

    Le plus simple est de faire un algo force brute du type

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
     
    Meilleure=(0,0,1)
    pour i2=0 jusqu'à Nb2 faire
      pour i3=0 jusqu'à Nb3 faire
        Solution=(i2,i3,2^i2*3^i3)
        si (0<=distance(solution, target)<distance(Meilleure,target)) alors
          Meilleure=solution
        fin si
      fin pour
    fin pour
    où Meilleure sera un objet/record contenant le triplet (nombre de plaquettes de 2 utilisées, id. plaquettes de 3, nombre atteint)
    Nb2 (resp. Nb3) le nombre de plaquettes de 2 (resp. 3) disponibles
    Distance une fonction qui renvoie target-solution.nombreAtteint


    On peut ajouter plusieurs petites optimisations :
    * Si target > produit de toutes les plaquettes alors aucune solution
    * Si il n'y a que des 2 (resp 3), la solution est la partie entière du log2 (resp log3) à un unité près suivant le cas de target
    * sortir des boucles dès que distance(meilleure,target)=0

    La méthode brute est réalisable pour un petit nombre de plaquettes.

  3. #3
    Membre émérite
    Homme Profil pro
    Ingénieur R&D en apprentissage statistique
    Inscrit en
    Juin 2009
    Messages
    447
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Ingénieur R&D en apprentissage statistique

    Informations forums :
    Inscription : Juin 2009
    Messages : 447
    Par défaut
    En fait tu peux rapidement accélérer la méthode de "kwariz" en ne bouclant que sur les 2, et en calculant de façon exacte la puissance de trois nécessaire pour atteindre au plus près target/2^i2.

  4. #4
    Membre chevronné
    Profil pro
    Inscrit en
    Octobre 2002
    Messages
    707
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Octobre 2002
    Messages : 707
    Par défaut
    Merci à tous les 2 !

    @kwariz: de bonnes idées et de bonnes remarques
    * sortir des boucles dès que distance(meilleure,target)=0
    Est-on sûr que la première solution donnant exactement "target" est optimale ? (nombre min. d'éléments la composant ?)

    @Alexis.M: peux-tu élaborer ?

    PS: dans les conditions du problème, le nombre de 2 et/ou de 3 sera toujours suffisant pour atteindre la valeur ciblée.

  5. #5
    Membre Expert
    Avatar de kwariz
    Homme Profil pro
    Chef de projet en SSII
    Inscrit en
    Octobre 2011
    Messages
    898
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 52
    Localisation : France, Moselle (Lorraine)

    Informations professionnelles :
    Activité : Chef de projet en SSII
    Secteur : Conseil

    Informations forums :
    Inscription : Octobre 2011
    Messages : 898
    Par défaut
    Citation Envoyé par GoustiFruit Voir le message
    Merci à tous les 2 !

    @kwariz: de bonnes idées et de bonnes remarques

    Est-on sûr que la première solution donnant exactement "target" est optimale ? (nombre min. d'éléments la composant ?)
    Si tu trouves une solution donnant exactement target alors forcément cela sera une décomposition en facteurs premiers (car 2 et 3 sont premiers) qui est unique. À première vue, mais c'est à confirmer, cela est vrai à condition que les valeurs des plaquettes soit deux à deux premières entre elles (par exemple cela resterait vrai avec des valeurs comme 11,14,15).

    Attention mon pseudo code est approximatif quant à la sélection de la meilleure solution, il faudra préciser ce morceau ; mais c'était pour donner l'idée.

  6. #6
    Membre chevronné
    Profil pro
    Inscrit en
    Octobre 2002
    Messages
    707
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Octobre 2002
    Messages : 707
    Par défaut
    Ça me semble pas mal pour commencer :-) et en attendant les explications éventuelles de Alexis.M.
    Pour l'initialisation de la solution je partirais plutôt de Meilleure(Nb2, Nb3, 2^Nb2*3^Nb3), non ? (c'est-à-dire la plus mauvaise solution possible)

  7. #7
    Membre émérite Avatar de 10_GOTO_10
    Profil pro
    Inscrit en
    Juillet 2004
    Messages
    890
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juillet 2004
    Messages : 890
    Par défaut
    Citation Envoyé par GoustiFruit Voir le message
    Il faut donc utiliser le moins de plaquettes possibles parmi la liste proposée pour obtenir par la multiplication une valeur au moins égale et la plus proche possible de l'objectif.
    Les contraintes sont contradictoires, aussi. Par exemple:

    - objectif = 7
    - plaquettes disponibles: 2, 2, 2, 2, 3, 3, 3


    Première solution: 9 = 3 * 3 (le moins de plaquettes possibles)

    Deuxième solution: 8 = 2 * 2 * 2 (La plus proche possible de l'objectif)

    Mon algorithme donne la seconde solution.

  8. #8
    Membre Expert
    Avatar de Franck Dernoncourt
    Homme Profil pro
    PhD student in AI @ MIT
    Inscrit en
    Avril 2010
    Messages
    894
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 38
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : PhD student in AI @ MIT
    Secteur : Enseignement

    Informations forums :
    Inscription : Avril 2010
    Messages : 894
    Par défaut
    Si intéressé, voici un exemple de code complet de "Le compte est bon" que j'avais écrit il y a quelques années en C++ (à noter que le code pourrait être beaucoup plus compact en utilisant des pointeurs de fonction...) :

    Code C++ : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454
    455
    456
    457
    458
    459
    460
    461
    462
    463
    464
    465
    466
    467
    468
    469
    470
    471
    472
    473
    474
    475
    476
    477
    478
    479
    480
    481
    482
    483
    484
    485
    486
    487
    488
    489
    490
    491
    492
    493
    494
    495
    496
    497
    498
    499
    500
    501
    502
    503
    504
    505
    506
    507
    508
    509
    510
    /****************************************************************************
    **
    ** The Total Is Right Game
    ** Game rules: http://en.wikipedia.org/wiki/Des_chiffres_et_des_lettres#Le_compte_est_bon_.28.22the_total_is_right.22.29
    **
    ** Author: Franck Dernoncourt <franck.dernoncourt@gmail.com> (2009)
    **
    ** Home Page : http://www.francky.me
    **
    ** This program is free software; you can redistribute it and/or
    ** modify it under the terms of the GNU General Public License
    ** as published by the Free Software Foundation; either
    ** version 3 of the License, or (at your option) any later version.
    **
    ** This program is distributed in the hope that it will be useful,
    ** but WITHOUT ANY WARRANTY; without even the implied warranty of
    ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    ** GNU General Public License for more details.
    **
    ****************************************************************************/
     
     
    /** Naming convention for functions and variables: lower CamelCase .**/
     
     
    #include <iostream>     /* cout */
    #include <time.h>       /* To seed the random function */
     
    using namespace std;    /* For sake of laziness & clarity */
     
    /*
     * Constant: NUM_NUMBERS
     * -----------------------
     * This constant determines how many numbers are distributed when the game starts.
     */
    const int NUM_NUMBERS = 6;
     
    /*
     * Constant: MAX_SOLUTIONS
     * -----------------------
     * This constant determines how many solutions can be stored by the solution's set.
     */
    const long int MAX_SOLUTIONS = 1000000;
     
     
    /*
     * Constant: AVAILABLE_NUMBERS_NUMBER
     * -----------------------
     * This constant determines among how many numbers the random function will pick up numbers.
     */
    const int AVAILABLE_NUMBERS_NUMBER = 14;
     
    /*
     * Constant: AVAILABLE_NUMBERS
     * -----------------------
     * This constant determines what numbers can be given when the game starts.
     */
    const int AVAILABLE_NUMBERS[AVAILABLE_NUMBERS_NUMBER] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 25, 50, 75, 100};
     
     
    /*
     * Constant: GOAL_NUMBER_MIN
     * -----------------------
     * This constant determines the minimum goal number
     */
    const int GOAL_NUMBER_MIN = 100;
     
    /*
     * Constant: GOAL_NUMBER_MAX
     * -----------------------
     * This constant determines the maximum goal number
     */
    const int GOAL_NUMBER_MAX = 999;
     
     
    /*
     * Struct / type: SolutionT
     * -----------------------
     * This struct is used to store one solution
     */
    struct SolutionT {
        int depth;
        char operationsUsed[NUM_NUMBERS];
        int usedNumbers[NUM_NUMBERS*2];
    }
    typedef SolutionT;
     
     
    /*
     * Global variable: solutions
     * -----------------------
     * This variable stores all solutions that
     * will be found by the recursive function recSolve
     */
    SolutionT solutions[MAX_SOLUTIONS];
     
    /*
     * Global variable: numOfSolutions
     * -----------------------
     * This variable stores the number of solutions that
     * will be found by the recursive function recSolve
     */
    int numOfSolutions = 0;
     
     
    /*
     * Function: displayArray
     * Usage: displayArray(array)
     * -----------------------------------------
     * This function displays the content of an array
     */
    void displayArray(int numbers[NUM_NUMBERS]) {
        for (int i=0; i<NUM_NUMBERS; i++) {
            cout << "The number " << i + 1 << " is: " << numbers[i] << endl;
        }
    }
     
    /*
     * Function: getArray
     * Usage: getArray(array)
     * -----------------------------------------
     * This function gets the content of an array from the user
     */
    void getArray(int numbers[NUM_NUMBERS]) {
        for (int i=0; i<NUM_NUMBERS; i++) {
            cout << "Enter number " << i + 1 << " : ";
            cin >> numbers[i];
        }
    }
     
    /*
     * Function: recSolve
     * Usage: recSolve(depth, numberToReach, numbers, operationsUsed, usedNumbers, bestDepth)
     * -----------------------------------------
     * This recursive function generates a lot of solutions
     * for the given problem and store them in the global
     * variable SolutionT solutions[MAX_SOLUTIONS].
     * Note that in any case it gives the BEST solution, i.e.
     * the one that use fewest operations as possible, which corresponds
     * to the smallest recursive depth stored in int depth.
     */
    void recSolve(int depth, int goal, int myNumbers[NUM_NUMBERS], char operationsUsed[NUM_NUMBERS], int usedNumbers[NUM_NUMBERS*2], int bestDepth) {
     
        /* BASE CASES - CASE 1 out of 3 */
        /* Goal is reached, which means one of the myNumbers is equal
         * to the goal, and we must stop the recursivity here
         */
        for (int i=0; i < NUM_NUMBERS; i++) {
            if (goal == myNumbers[i] ) {
     
                /* We update bestDepth */
                if (bestDepth > depth) bestDepth = depth;
     
                /* We store the solutions in global variables numOfSolutions and solutions */
                numOfSolutions++;
                solutions[numOfSolutions-1].depth = depth;
                for(int j=0; j < depth; j++) solutions[numOfSolutions-1].operationsUsed[j] = operationsUsed[j];
                for(int j=0; j < depth*2; j++) solutions[numOfSolutions-1].usedNumbers[j] = usedNumbers[j];
                return;
            }
        }
     
        /* BASE CASES - CASE 2 out of 3 */
        /* Depth is > NUM_NUMBERS, therefore there is no solution */
        if (depth >= 6) return;
     
        /* BASE CASES - CASE 3 out of 3 */
        /* We only go into this branch if it's not deeper than the
         * best solution found so far
         */
        if (depth >= bestDepth) return;
     
     
        /* The Total Is Right Game allows 4 operation :
         * Addition, substraction, multiplication and division.
         * We'll generate them all and recursively call recSolve()
         * each time it seems to be necessary.
         */
     
        /* Operation 1 out of 4:
         * ADDITION
         * n*(n-1)/2 possibilities, where n = myNumbers.size() because the addition is commutative
         *Operand1 + Operand2, and we store it in Operand1's former location in the array myNumbers
         */
        operationsUsed[depth]='+';
        for (int indexOperand1=0; indexOperand1 < NUM_NUMBERS; indexOperand1++) {
            if (myNumbers[indexOperand1] == 0) continue;
     
            for (int indexOperand2=indexOperand1+1; indexOperand2 < NUM_NUMBERS; indexOperand2++) {
                if (myNumbers[indexOperand2] == 0) continue;
                usedNumbers[depth*2] = myNumbers[indexOperand1];
                usedNumbers[depth*2+1] = myNumbers[indexOperand2];
     
                myNumbers[indexOperand1] += myNumbers[indexOperand2];
                int tempOperand1 = myNumbers[indexOperand1];
                int tempOperand2 = myNumbers[indexOperand2];
                myNumbers[indexOperand2] = 0; /* we delete the used number */
                recSolve(depth + 1, goal,myNumbers, operationsUsed, usedNumbers, bestDepth);
     
                /* We reverse the operations */
                myNumbers[indexOperand2] = tempOperand2;
                myNumbers[indexOperand1] -= myNumbers[indexOperand2];
     
                /* if we reached the goal, stop recursion */
                if ( tempOperand1 == goal) return;
            }
        }
     
        /* Operation 2 out of 4:
         * SUBSTRACTION
         * n² possibilities, where n = myNumbers.size() because the substraction is not commutative
         * Operand1 - Operand2, and we store it in Operand1's former location in the array myNumbers
         */
     
        operationsUsed[depth]='-';
        for (int indexOperand1=0; indexOperand1 < NUM_NUMBERS; indexOperand1++) {
            if (myNumbers[indexOperand1] == 0) continue;
     
            for (int indexOperand2=0; indexOperand2 < NUM_NUMBERS; indexOperand2++) {
                if (myNumbers[indexOperand2] == 0) continue;
                if ( myNumbers[indexOperand1] == myNumbers[indexOperand2] ) continue;
     
                usedNumbers[depth*2] = myNumbers[indexOperand1];
                usedNumbers[depth*2+1] = myNumbers[indexOperand2];
     
                myNumbers[indexOperand1] -= myNumbers[indexOperand2];
                int tempOperand1 = myNumbers[indexOperand1];
                int tempOperand2 = myNumbers[indexOperand2];
                myNumbers[indexOperand2] = 0; /* we delete the used number */
                recSolve(depth + 1, goal,myNumbers, operationsUsed, usedNumbers, bestDepth);
     
                /* We reverse the operations */
                myNumbers[indexOperand2] = tempOperand2;
                myNumbers[indexOperand1] += myNumbers[indexOperand2];
     
                /* If we reached the goal, stop recursion */
                if ( tempOperand1 == goal) return;
            }
        }
     
     
     
        /* Operation 3 out of 4:
         * MULTIPLICATION
         * n*(n-1)/2 possibilities, where n = myNumbers.size() because the multiplication is commutative
         * Operand1 * Operand2, and we store it in Operand1's former location in the array myNumbers
         */
        operationsUsed[depth]='*';
        for (int indexOperand1=0; indexOperand1 < NUM_NUMBERS; indexOperand1++) {
            if (myNumbers[indexOperand1] == 0) continue;
     
            for (int indexOperand2=indexOperand1+1; indexOperand2 < NUM_NUMBERS; indexOperand2++) {
                if (myNumbers[indexOperand2] == 0) continue;
     
                usedNumbers[depth*2] = myNumbers[indexOperand1];
                usedNumbers[depth*2+1] = myNumbers[indexOperand2];
     
                myNumbers[indexOperand1] *= myNumbers[indexOperand2];
                int tempOperand1 = myNumbers[indexOperand1];
                int tempOperand2 = myNumbers[indexOperand2];
                myNumbers[indexOperand2] = 0; /* we delete the used number */
                recSolve(depth + 1, goal,myNumbers, operationsUsed, usedNumbers, bestDepth);
     
                /* We reverse the operations */
                myNumbers[indexOperand2] = tempOperand2;
                myNumbers[indexOperand1] /= myNumbers[indexOperand2];
     
                /* if we reached the goal, stop recursion */
                if ( tempOperand1 == goal) return;
            }
        }
     
     
        /* Operation 4 out of 4:
         * DIVISION
         * n² possibilities, where n = myNumbers.size() because the division is not commutative
         * Operand1 / Operand2, and we store it in Operand1's former location in the array myNumbers
         */
        operationsUsed[depth]='/';
        for (int indexOperand1=0; indexOperand1 < NUM_NUMBERS; indexOperand1++) {
            if (myNumbers[indexOperand1] == 0) continue;
     
            for (int indexOperand2=0; indexOperand2 < NUM_NUMBERS; indexOperand2++) {
                if (myNumbers[indexOperand2] == 0) continue;
     
                /* Check if division if possible */
                if ( indexOperand1 == indexOperand2
                    || myNumbers[indexOperand2] == 0
                    || myNumbers[indexOperand1] % myNumbers[indexOperand2] != 0 )
                    continue;
     
                usedNumbers[depth*2] = myNumbers[indexOperand1];
                usedNumbers[depth*2+1] = myNumbers[indexOperand2];
     
                myNumbers[indexOperand1] /= myNumbers[indexOperand2];
                int tempOperand1 = myNumbers[indexOperand1];
                int tempOperand2 = myNumbers[indexOperand2];
                myNumbers[indexOperand2] = 0; /* we delete the used number */
                recSolve(depth + 1, goal,myNumbers, operationsUsed, usedNumbers, bestDepth);
     
                /* We reverse the operations */
                myNumbers[indexOperand2] = tempOperand2;
                myNumbers[indexOperand1] *= myNumbers[indexOperand2];
     
                /* If we reached the goal, stop recursion */
                if ( tempOperand1 == goal) return;
            }
        }
     
    }
     
    /*
     * Function: displayBestSolution
     * Usage: displayBestSolution()
     * -----------------------------------------
     * This function displays the best solutions contains in
     * the array solutions. The best solution is defined as the
     * one whose number of operation is the smallest possible.
     * The number of operation is equal to the depth, which refers
     * to the depth of the recursive function that found the solutions.
     */
    void displayBestSolution() {
        int minDepth = NUM_NUMBERS + 1; // i.e. no solution
        long unsigned int bestSolIndex = MAX_SOLUTIONS ;
        for (long unsigned int i=0; i < numOfSolutions ; i++) {
            if (solutions[i].depth < minDepth) {
                minDepth = solutions[i].depth;
                bestSolIndex = i;
            }
        }
     
        /* We display the current solution */
        /* If no solution */
        if (minDepth == NUM_NUMBERS + 1) {
            cout << "There is no solution. Did you find one? If yes, you beat me!!!" << endl;
            return;
        }
     
        /* If solution, which is the case most of the time */
        else {
     
            /* First compute all operations total */
            int totalOperations[NUM_NUMBERS];
            for(int j=0; j < solutions[bestSolIndex].depth; j++) {
                switch (solutions[bestSolIndex].operationsUsed[j]) {
                    case '+':
                        totalOperations[j]=solutions[bestSolIndex].usedNumbers[j*2]+solutions[bestSolIndex].usedNumbers[j*2+1];
                        break;
                    case '-':
                        totalOperations[j]=solutions[bestSolIndex].usedNumbers[j*2]-solutions[bestSolIndex].usedNumbers[j*2+1];
                        break;
                    case '*':
                        totalOperations[j]=solutions[bestSolIndex].usedNumbers[j*2]*solutions[bestSolIndex].usedNumbers[j*2+1];
                        break;
                    case '/':
                        totalOperations[j]=solutions[bestSolIndex].usedNumbers[j*2]/solutions[bestSolIndex].usedNumbers[j*2+1];
                        break;
                }
            }
     
            /* Display all operations */
            for(int j=0; j < solutions[bestSolIndex].depth; j++) {
                cout << solutions[bestSolIndex].usedNumbers[j*2] << " " << solutions[bestSolIndex].operationsUsed[j] << " "
                     << solutions[bestSolIndex].usedNumbers[j*2+1] <<  " = " << totalOperations[j] << endl;
            }
     
            cout << endl << "There are at least " << numOfSolutions - 1 << " other solutions. " << endl;
        }
    }
     
     
    /*
     * Function: solve
     * Usage: solve(numbers, numberToReach)
     * -----------------------------------------
     * This function
     * 1) initializes some variables,
     * 2) calls the recursive function recSolve
     * 3) displays the best solution.
     */
    void solve(int numbers[NUM_NUMBERS], int numberToReach) {
        cout << "Solving..." << endl;
        int depth = 0;
        int bestDepth = NUM_NUMBERS;
        char operationsUsed[NUM_NUMBERS]; /* Store the operations used to find the goal number from the array myNumbers. */
        int usedNumbers[NUM_NUMBERS*2];
        numOfSolutions = 0;
     
        recSolve(depth, numberToReach, numbers, operationsUsed, usedNumbers, bestDepth);
        displayBestSolution();
    }
     
     
    /*
     * Function: playRandomGame
     * Usage: playRandomGame()
     * -----------------------------------------
     * Play a normal game with random numbers
     */
    void playRandomGame() {
     
        cout << endl << endl << "Normal Game." << endl << endl;
        int numbers[NUM_NUMBERS];
        int numberToReach;
     
        /* generate available numbers: */
        for (int i=0; i<NUM_NUMBERS; i++) {
            numbers[i] = AVAILABLE_NUMBERS[rand() % AVAILABLE_NUMBERS_NUMBER];
        }
     
         /* generate number to reach: */
        numberToReach = rand() % (GOAL_NUMBER_MAX - GOAL_NUMBER_MIN) + GOAL_NUMBER_MIN;
     
        /* Display available numbers */
        displayArray(numbers);
     
        cout << endl << "You must reach: " << numberToReach << endl;
        cout << endl << "Wanna see the best solution? " << endl;
        system("pause");
        solve(numbers,numberToReach);
        system("pause");
    }
     
     
    /*
     * Function: userOwnNumberGame
     * Usage: userOwnNumberGame()
     * -----------------------------------------
     * Solve a problem given by the user
     */
    void userOwnNumberGame() {
     
        int numbers[NUM_NUMBERS];
        int numberToReach;
     
        cout << endl << endl;
        getArray(numbers);
        cout << "Enter the goal number: ";
        cin >> numberToReach;
     
     
        solve(numbers,numberToReach);
        system("pause");
     
    }
     
     
     
    /*
     * Function: displayRules
     * Usage: displayRules()
     * -----------------------------------------
     * This function displays the game's rules.
     */
    void displayRules() {
        cout << endl << endl;
        cout << "GAME RULES: (from Wikipedia)" << endl << endl << endl;
        cout << "The goal of this game is to arrive at a chosen number (from 101 to 999) "
        "using the four basic arithmetic operations (+, -, * and /) applied to six numbers "
        "chosen randomly from the following alternatives: 1 to 10; 25; 50; 75; 100 "
        "(each number is drawn from the entire set, so the same number may appear more than once). " << endl << endl <<
        "Once these six numbers are selected, a three-digit target number is generated. "
        "The players combine the numbers arithmetically with the goal of producing the target number. "
        "The player may use each of the six numbers originally selected once, "
        "and the result of each operation performed with them once - for example, "
        "if a player multiplies 4 by 25 to obtain 100, he or she may no longer use the 4 or 25, "
        "but may use the 100 in further calculations. It's not mandatory to use all the numbers. All numbers used must be integers.";
        cout << endl << endl;
        cout << "Example: "<< endl;
        cout << "Numbers given  : 8 ; 4 ; 4 ; 6 ; 8 ; 9" << endl;
        cout << "Target number  : 594" << endl;
        cout << " 8 + 8 = 16" << endl;
        cout << "16 * 4 = 64" << endl;
        cout << " 6 - 4 = 2" << endl;
        cout << "64 + 2 = 66" << endl;
        cout << "66 * 9 = 594" << endl;
        system("pause");
    }
     
     
    /*
     * Function: main
     * Usage: main()
     * -----------------------------------------
     * This is the program's main function: User menu.
     */
    int main()
    {
         /* initialize random seed: */
        srand ( time(NULL) );
     
        cout << "Welcome to The Total is Right game!" << endl;
     
        /* User menu */
        int answer = 1;
        while( answer!=4 ) {
            cout << endl << endl;
            cout << "1) Play normal game." << endl;
            cout << "2) Enter your own numbers." << endl;
            cout << "3) Display rules." << endl;
            cout << "4) Quit." << endl;
            cout << "Enter your choice: " ;
            cin >> answer;
            if (answer==1) playRandomGame();
            if (answer==2) userOwnNumberGame();
            if (answer==3) displayRules();
        }
     
        return EXIT_SUCCESS;
    }

  9. #9
    Membre chevronné
    Profil pro
    Inscrit en
    Octobre 2002
    Messages
    707
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Octobre 2002
    Messages : 707
    Par défaut
    Citation Envoyé par 10_GOTO_10 Voir le message
    Les contraintes sont contradictoires, aussi.
    S'approcher au mieux de l'objectif est la contrainte prioritaire; je pense qu'au vu du caractère "premier" des nombres utilisés, la deuxième contrainte "le moins de plaquettes possibles" est inutile: car s'il était possible d'obtenir la même valeur par différentes combinaisons, il faudrait alors choisir celle utilisant le moins de plaquettes... mais apparemment c'est impossible !?

    Merci @Franck, je n'ai pas l'utilité de ce code, mon problème est un peu plus simple, mais ça pourra servir à d'autres

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Jeu "Le compte est bon" avec récursivité
    Par elvis54 dans le forum Général Java
    Réponses: 1
    Dernier message: 19/11/2008, 07h50
  2. [Jeu "Le Compte est Bon"] Recherche algorithme
    Par Chriss21 dans le forum Algorithmes et structures de données
    Réponses: 3
    Dernier message: 29/10/2005, 16h10

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo