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

 C Discussion :

Remplir un tableau aléatoirement


Sujet :

C

  1. #1
    Membre habitué Avatar de emprex
    Homme Profil pro
    auto-entrepreneur
    Inscrit en
    Octobre 2007
    Messages
    219
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 47
    Localisation : Royaume-Uni

    Informations professionnelles :
    Activité : auto-entrepreneur
    Secteur : Services à domicile

    Informations forums :
    Inscription : Octobre 2007
    Messages : 219
    Points : 199
    Points
    199
    Par défaut Remplir un tableau aléatoirement
    Bonjour, à tous.

    Je voudrais remplir un grand tableau avec des entiers dans le desordre afin de tester divers algorithmes de tri.
    j'avais pensé à rand mais il semble que ca ne marche pas.
    Que dois-je uitliser ?
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    /* fonction de saisie de tableau */
     
    int SaisieTableau(int tableau[NB_MAXI_ELEMENT],int taille){
    	int i;
    	if(taille > NB_MAXI_ELEMENT){
    		puts("Erreur : Le tableau est trop petit");
    		exit(1);
    	}
    	puts("Saisir les valeurs de votre tableau : ");
    	for(i = 0; i < taille; i++)
    		scanf("%d", &tableau[i]);
    	return taille;
    }

  2. #2
    Expert confirmé

    Inscrit en
    Août 2006
    Messages
    3 950
    Détails du profil
    Informations forums :
    Inscription : Août 2006
    Messages : 3 950
    Points : 5 667
    Points
    5 667
    Par défaut
    Fio,
    Citation Envoyé par emprex Voir le message
    Bonjour, à tous.

    Je voudrais remplir un grand tableau avec des entiers dans le desordre afin de tester divers algorithmes de tri.
    j'avais pensé à rand mais il semble que ca ne marche pas.
    Que dois-je uitliser ?
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    /* fonction de saisie de tableau */
     
    int SaisieTableau(int tableau[NB_MAXI_ELEMENT],int taille){
    	int i;
    	if(taille > NB_MAXI_ELEMENT){
    		puts("Erreur : Le tableau est trop petit");
    		exit(1);
    	}
    	puts("Saisir les valeurs de votre tableau : ");
    	for(i = 0; i < taille; i++)
    		scanf("%d", &tableau[i]);
    	return taille;
    }
    Où est rand dans ton programme ?

  3. #3
    Membre habitué Avatar de emprex
    Homme Profil pro
    auto-entrepreneur
    Inscrit en
    Octobre 2007
    Messages
    219
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 47
    Localisation : Royaume-Uni

    Informations professionnelles :
    Activité : auto-entrepreneur
    Secteur : Services à domicile

    Informations forums :
    Inscription : Octobre 2007
    Messages : 219
    Points : 199
    Points
    199
    Par défaut
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    /* fonction de saisie de tableau */
     
    int SaisieTableau(int tableau[NB_MAXI_ELEMENT],int taille){
    	int i;
    	if(taille > NB_MAXI_ELEMENT){
    		puts("Erreur : Le tableau est trop petit");
    		exit(1);
    	}
    	puts("Saisir les valeurs de votre tableau : ");
    	for(i = 0; i < taille; i++)
    		srand(tableau[i]);
    	return taille;
    }
    Ce systeme fonctionne mais les nombres sont toujours les memes pour chaque indice

  4. #4
    Expert confirmé
    Avatar de Thierry Chappuis
    Homme Profil pro
    Enseignant Chercheur
    Inscrit en
    Mai 2005
    Messages
    3 499
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 47
    Localisation : Suisse

    Informations professionnelles :
    Activité : Enseignant Chercheur
    Secteur : Industrie Pharmaceutique

    Informations forums :
    Inscription : Mai 2005
    Messages : 3 499
    Points : 5 360
    Points
    5 360
    Par défaut
    srand() n'est pas rand(). srand() sert à initialiser le générateur de nombres pseudo-aléatoire. Cette fonction doit être appelée une seule fois au début de ton programme. Ensuite, pour obtenir les nombres pseudo-aléatoires, c'est rand() que tu doit appeler.

    Voir: http://nicolasj.developpez.com/articles/libc/hasard/ et http://c.developpez.com/faq/?page=no..._random_bornes

    Thierry

  5. #5
    Membre habitué Avatar de emprex
    Homme Profil pro
    auto-entrepreneur
    Inscrit en
    Octobre 2007
    Messages
    219
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 47
    Localisation : Royaume-Uni

    Informations professionnelles :
    Activité : auto-entrepreneur
    Secteur : Services à domicile

    Informations forums :
    Inscription : Octobre 2007
    Messages : 219
    Points : 199
    Points
    199
    Par défaut
    Ok , merci je viens de lire le sujet,
    il faut que j'écrive tableau[i] = rand();

  6. #6
    Expert confirmé
    Avatar de Thierry Chappuis
    Homme Profil pro
    Enseignant Chercheur
    Inscrit en
    Mai 2005
    Messages
    3 499
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 47
    Localisation : Suisse

    Informations professionnelles :
    Activité : Enseignant Chercheur
    Secteur : Industrie Pharmaceutique

    Informations forums :
    Inscription : Mai 2005
    Messages : 3 499
    Points : 5 360
    Points
    5 360
    Par défaut
    Ca donne quelque chose comme cela:

    Code : 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
    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
     
    #define NB_MAXI_ELEMENT 15
    #define NB_ALEATOIRE_MAX 100
     
    /* -tc- Voir la FAQ C: http://c.developpez.com/faq/?page=nombres#NOMBRES_random_bornes */
    int alea(int n)
    {
       int partSize   = (n == RAND_MAX) ?        1 : 1 + (RAND_MAX - n)/(n+1);
       int maxUsefull = partSize * n + (partSize-1);
       int draw;
     
       do
       {
          draw = rand();
       } while (draw > maxUsefull);
       return draw/partSize;
    }
     
    void initialiserTableau(int tableau[], size_t taille)
    {
    	if (tableau != NULL && taille > 0)
    	{
    	    size_t i;
     
    	    for (i = 0; i < taille; i++)
    	    {
    	        tableau[i] = alea(NB_ALEATOIRE_MAX);
    	    }
    	}
    }
     
    void afficherTableau(int tableau[], size_t taille)
    {
    	if (tableau != NULL && taille > 0)
    	{
    	    size_t i;
     
    	    for (i = 0; i < taille; i++)
    	    {
    	        printf("%d ", tableau[i]);
    	    }
    	    printf("\n");
    	}
    }
     
    int main(void)
    {
        int tableau[NB_MAXI_ELEMENT] = {0};
     
        /* -tc- Initialisation du generateur de nombres pseudo-aleatoires */
        srand(time(NULL));
     
        initialiserTableau(tableau, NB_MAXI_ELEMENT);
        afficherTableau(tableau, NB_MAXI_ELEMENT);
     
        return 0;
    }
    Thierry

  7. #7
    Membre habitué Avatar de emprex
    Homme Profil pro
    auto-entrepreneur
    Inscrit en
    Octobre 2007
    Messages
    219
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 47
    Localisation : Royaume-Uni

    Informations professionnelles :
    Activité : auto-entrepreneur
    Secteur : Services à domicile

    Informations forums :
    Inscription : Octobre 2007
    Messages : 219
    Points : 199
    Points
    199
    Par défaut
    Le srand je l'ai mis dans la fonction et nom pas dans le main du coup j'ai deux warning.
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    /* fonction de saisie de tableau */
     
    int SaisieTableau(int tableau[NB_MAXI_ELEMENT],int taille){
    	size_t i;
    	srand(time(NULL));
    	if(taille > NB_MAXI_ELEMENT){
    		puts("Erreur : Le tableau est trop petit");
    		exit(1);
    	}
    	for(i = 0; i < taille; i++){
    		tableau[i] = rand();
    	}
    	return taille;
    }

  8. #8
    Expert confirmé
    Avatar de Thierry Chappuis
    Homme Profil pro
    Enseignant Chercheur
    Inscrit en
    Mai 2005
    Messages
    3 499
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 47
    Localisation : Suisse

    Informations professionnelles :
    Activité : Enseignant Chercheur
    Secteur : Industrie Pharmaceutique

    Informations forums :
    Inscription : Mai 2005
    Messages : 3 499
    Points : 5 360
    Points
    5 360
    Par défaut
    En principe, il n'y a pas lieu d'appeler srand() plusieurs fois dans ton programme. Pour être sûr, tu peux éventuellement écrire:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    int SaisieTableau(int tableau[NB_MAXI_ELEMENT], int taille)
    {
     
        static int rand_init = 0;
     
        if (rand_init == 0)
        {
            srand(time(NULL));
            rand_init = 1;
        }
     
        /* ... */
    }
    Thierry

  9. #9
    Membre habitué Avatar de emprex
    Homme Profil pro
    auto-entrepreneur
    Inscrit en
    Octobre 2007
    Messages
    219
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 47
    Localisation : Royaume-Uni

    Informations professionnelles :
    Activité : auto-entrepreneur
    Secteur : Services à domicile

    Informations forums :
    Inscription : Octobre 2007
    Messages : 219
    Points : 199
    Points
    199
    Par défaut
    J'ai testé mais j'ai toujours deux warnings.
    Pouvez-vous jeter un oeil ?
    Code : 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
    /* le tri  strohecker guillaume */
     
    #include <stdio.h>
    #include <stdlib.h>
    #define NB_MAXI_ELEMENT 10000
     
    /* fonction echange */
     
    void Echange(int *T, int i, int j){
    	int temp;
    	temp = T[i];
    	T[i] = T[j];
    	T[j] = temp;
    }
     
    /* Fonction de partionnement */
     
    int Partionnement(int *T, int imin, int imax){
    	int pivot, i, j;
    	pivot = T[imax];
    	i = imin;
    	j = imax - 1;
    	while (i <= j){
    		while ((i < imax) && (T[i] <= pivot))
    			i++;
    		while ((j >= imin) && (T[j] >= pivot))
    			j--;
    		if (i < j)
    			Echange(T, i, j);
    	}
    	T[imax] = T[i];
    	T[i] = pivot;
    	return i;
    }
     
    /* Fonction Tri rapide */
     
    void TriRapide(int *T, int imin, int imax){
    	int i;
    	if (imin < imax){
    		i = Partionnement(T, imin, imax);
    		TriRapide(T, imin, i-1); /* tri de la partie gauche */
    		TriRapide(T, i+1, imax); /* tri de la partie droite */
    	}
    }
     
    /* Fonction QuickSort */
     
    void QuickSort(int *T, int taille){
    	TriRapide(T, 0, taille-1); /* imin = 0 et imax = 1 */
    }
     
    /* algorithme de tri par sélection */
     
    static void TriSelection(int *T, int taille){
    	int k, i, imax;
    	k = taille - 1;
    	while (k > 0){
    		/* recherche de l'indice maximum */
    		imax = 0;
    		for (i = 1; i <= k; i++){
    			if (T[imax] < T[i]){
    				imax = i;
    			}
    		}
    		/* echange */
    		Echange(T, k, imax);
    		k--;
    	}
     
    }
     
    /* Algorithme de tri à bulle */
     
    static void TriBulle(int tableau[], int taille){
    	int i, k;
    	k = taille - 1;
    	/* pour chaque passe */
    	while(k > 0){
    		/* on fait remonter le plus grand */
    		for (i = 1; i <= k; i++){
    			if (tableau[i] < tableau[i-1]){
    				/* échange de T[i-1] et T[i] */
    				Echange(tableau, i, i-1);
    			}
    		}
    		k--;
    	}
    }
     
    /* Algorithme de tri par insertion */
     
    static void TriInsertion(int tableau[], int taille){
    	int k, i, v;
    	for( k = 1; k < taille; k++)
    	{
    		v = tableau[k];
    		i = k - 1;
    	/* on décale les éléments pour l'insertion */
    		while(( i>= 0) && ( v <tableau[i]))
    		{
    		tableau[i+1] = tableau[i];
    		i--;
    		}
    	/* insertion */
    	tableau[i+1] = v;
    	}
    }
     
    /* fonction de saisie de tableau */
     
    int SaisieTableau(int tableau[NB_MAXI_ELEMENT],int taille){
    	size_t i;
    	static int rand_init = 0;
     
        if (rand_init == 0)
        {
            srand(time(NULL));
            rand_init = 1;
        }
     
    	if(taille > NB_MAXI_ELEMENT){
    		puts("Erreur : Le tableau est trop petit");
    		exit(1);
    	}
    	for(i = 0; i < taille; i++){
    		tableau[i] = rand();
    	}
    	return taille;
    }
     
    /* fonction d'affichage */
     
    void AffichageTableau(int tableau[], int taille){
    	int i;
    	for(i = 0; i < taille; i++)
    		printf("%d ", tableau[i]);
    	printf("\n");
    }
     
     
    /* Fonction de choix */
     
    void FaitesVotreChoix(int tableau[], int taille){
    	char choix ;
    	int c;
        while ((c = fgetc(stdin)) != '\n' && c != EOF);
    	puts("Faites votre choix :");
    	puts("Un tri par selection -----> a");
    	puts("Un tri a bulle -----------> b");
    	puts("Un tri par insertion -----> c");
    	puts("Un tri rapide ------------> d");
    	puts("Quitter ------------------> e");
    	choix = (char) getchar();
    	switch(choix){
    	case'a' : 
    		puts("Avant le tri:");
    		AffichageTableau(tableau, taille);
    		TriSelection(tableau, taille);
    		puts("Apres le tri:");
    		AffichageTableau(tableau, taille);
    		break;
    	case'b' : 
    		puts("Avant le tri:");
    		AffichageTableau(tableau, taille);
    		TriBulle(tableau, taille);
    		puts("Apres le tri:");
    		AffichageTableau(tableau, taille);
    		break;
    	case'c' : 
    		puts("Avant le tri:");
    		AffichageTableau(tableau, taille);
    		TriInsertion(tableau, taille);
    		puts("Apres le tri:");
    		AffichageTableau(tableau, taille);
    		break;
    	case'd' :
    		puts("Avant le tri:");
    		AffichageTableau(tableau, taille);
    		QuickSort(tableau, taille);
    		puts("Apres le tri:");
    		AffichageTableau(tableau, taille);
    		break;
    	case'e' :
    		break;
    	default : puts("Erreur de saisie!!");
    	}
    }
     
     /* programme test */
     
    int main(void){
    	int tableau[NB_MAXI_ELEMENT];
    	int taille;
    	puts("Saisir la taille de votre tableau : ");
    	scanf("%d", &taille);
    	SaisieTableau(tableau, taille);
    	FaitesVotreChoix(tableau, taille);
    	return 0;
    }

  10. #10
    Expert confirmé
    Avatar de Thierry Chappuis
    Homme Profil pro
    Enseignant Chercheur
    Inscrit en
    Mai 2005
    Messages
    3 499
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 47
    Localisation : Suisse

    Informations professionnelles :
    Activité : Enseignant Chercheur
    Secteur : Industrie Pharmaceutique

    Informations forums :
    Inscription : Mai 2005
    Messages : 3 499
    Points : 5 360
    Points
    5 360
    Par défaut
    Lorsque j'inclus time.h et que je change size_t i en int i dans le corps de SaisieTableau(), j'obtiens une compilation sans avertissement. Je n'ai pas regardé le code. Je peux juste dire que ça compile sans avertissement avec gcc et les options -ansi -Wall -Wextra -Wwrite-strings -Wstrict-prototypes.

    Thierry

  11. #11
    Membre habitué Avatar de emprex
    Homme Profil pro
    auto-entrepreneur
    Inscrit en
    Octobre 2007
    Messages
    219
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 47
    Localisation : Royaume-Uni

    Informations professionnelles :
    Activité : auto-entrepreneur
    Secteur : Services à domicile

    Informations forums :
    Inscription : Octobre 2007
    Messages : 219
    Points : 199
    Points
    199
    Par défaut
    sous visual c++ 6 aussi
    Merci beaucoup.
    Bonne soirée.

  12. #12
    Débutant  
    Inscrit en
    Novembre 2006
    Messages
    1 073
    Détails du profil
    Informations forums :
    Inscription : Novembre 2006
    Messages : 1 073
    Points : 217
    Points
    217
    Par défaut
    je rajoute un msg a ce thread pour éviter d'ouvrir une nouvelle discussion, mais on est bien d'accord que ce code:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    int main(){
    double t;
    double seed;
     
    srand((int)time(NULL));
    for(int i=0;30;i++){
    t=rand()/ (double) RAND_MAX;
    cout<<t<<endl;
    }
    }
    renvoie une suite de chifre entre 0 et 1?

  13. #13
    Expert confirmé
    Avatar de Thierry Chappuis
    Homme Profil pro
    Enseignant Chercheur
    Inscrit en
    Mai 2005
    Messages
    3 499
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 47
    Localisation : Suisse

    Informations professionnelles :
    Activité : Enseignant Chercheur
    Secteur : Industrie Pharmaceutique

    Informations forums :
    Inscription : Mai 2005
    Messages : 3 499
    Points : 5 360
    Points
    5 360
    Par défaut
    Oui, et ?

    Ce code ne compile pas ni en C90 ni en C99. cout est une fonctionnalité C++.

    Thierry

  14. #14
    Membre émérite Avatar de nicolas.sitbon
    Profil pro
    Inscrit en
    Août 2007
    Messages
    2 015
    Détails du profil
    Informations personnelles :
    Âge : 41
    Localisation : France

    Informations forums :
    Inscription : Août 2007
    Messages : 2 015
    Points : 2 280
    Points
    2 280
    Par défaut
    Citation Envoyé par deubelte Voir le message
    je rajoute un msg a ce thread pour éviter d'ouvrir une nouvelle discussion, mais on est bien d'accord que ce code:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    int main(){
    double t;
    double seed;
     
    srand((int)time(NULL));
    for(int i=0;30;i++){
    t=rand()/ (double) RAND_MAX;
    cout<<t<<endl;
    }
    }
    renvoie une suite de chifre entre 0 et 1?
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    int main (void)
    {
       double t;
       double seed;
     
       srand ((int) time (NULL));
    
       for (int i = 0; 30; i++)
       {
          t = rand () / (double) RAND_MAX;
          cout<<t<<endl;
       }
    }
    Code : 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
    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    #define MAX 30U
    
    int main (void)
    {
       double t;
     
       srand ((unsigned) time (NULL));
    
       for (size_t i = 0; i < MAX; i++)
       {
          t = rand () / (double) RAND_MAX;
          printf ("%g\n", t);
       }
    
       return 0;
    }

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

Discussions similaires

  1. Réponses: 4
    Dernier message: 31/03/2012, 00h30
  2. Remplir un tableau d'img aléatoirement
    Par Invité dans le forum Général JavaScript
    Réponses: 8
    Dernier message: 03/02/2010, 11h39
  3. Réponses: 4
    Dernier message: 12/11/2009, 09h58
  4. remplir un tableau par des nombre aléatoires
    Par logo98 dans le forum Débuter
    Réponses: 7
    Dernier message: 06/03/2009, 23h22
  5. Réponses: 6
    Dernier message: 21/03/2007, 14h59

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