2

here is my code. I am trying generate random alphabet but i see same letters. example: (YHTGDHFBSHXCHFYFUXZWDYKLXI) How can i fix it? just i need mixed alphabet not same letters. Thank you so much.

#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

void random_string(char * string, unsigned length)
{
    /* Seed number for rand() */
    srand((unsigned int) time(0));


    int i;
    for (i = 0; i < length; ++i)
    {
        string[i] = rand() % 26 + 'A';
    }

    string[i] = '\0';
}

int main(void)
{
    char s[26];
    random_string(s, 26);
    printf("%s\n", s);
    return 0;
}
misshyde
  • 45
  • 1
  • 8
  • 1
    so you're actually after [an algorithm for pemutations](https://ericlippert.com/2013/05/02/producing-permutations-part-six/)? – Rowland Shaw Nov 23 '16 at 16:45
  • See [`srand()` — why call it only once](http://stackoverflow.com/questions/7343833/srand-why-call-it-only-once/). Since you only generate one random string, you won't observe the problem. If you try to generate a second one, you will. – Jonathan Leffler Nov 23 '16 at 16:49
  • yes actually i want encrypt a plaintext and i need random character key. i posted as an answer my code. – misshyde Nov 23 '16 at 16:51
  • Possible duplicate of [Shuffle array in C](http://stackoverflow.com/questions/6127503/shuffle-array-in-c) – Random Davis Nov 23 '16 at 17:00
  • Just as a sidenote, when you say "encryption", I hope this is just for fun and games, since that kind of encryption can be cracked very easily. – sapanoia Nov 23 '16 at 20:30
  • just for learning C language. – misshyde Nov 23 '16 at 20:32

4 Answers4

7

The operation you are looking for is called a shuffle or a permutation. It is not sufficient to call a random-letter function 26 times, since, as you see, you can generate duplicates.

Instead, start with the string "ABCDEFGHIJKLMNOPQRSTUVWXYZ" and perform a shuffle operation. If you want to learn by doing such things from scratch, I recommend reading about the Fisher-Yates Shuffle then crafting an implementation on your own.

Ray Toal
  • 86,166
  • 18
  • 182
  • 232
  • yes actually i encrypted a plaintext and i need random character key and yes i need shuffle. Ok i will write my codes as answer: – misshyde Nov 23 '16 at 16:48
1

You can do this by having a pool of available characters, and taking one from the pool. Please note that your target string was too short to accomodate the string terminator. Similar to Fisher Yates shuffle.

Edit: changed the types to size_t.

#include <time.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define LENGTH  26                       // the cipher key length

void random_string(char * string, size_t length)
{
    char pool[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    size_t poolsize = strlen(pool);
    size_t index;
    size_t i;

    srand((unsigned)time(NULL));

    for(i = 0; i < length && poolsize > 0; ++i)
    {
        index = rand() % poolsize;       // a random index into the pool
        string[i] = pool[index];         // take that character
        pool[index] = pool[--poolsize];  // replace it with the last pool ...
    }                                    // ... element and shorten the pool

    string[i] = '\0';
}

int main(void)
{
    char s[LENGTH + 1];                  // adequate length
    random_string(s, LENGTH);
    printf("%s\n", s);
    return 0;
}

Program output:

QYMUSFALIZCXGONBJRETHPVKDW
Weather Vane
  • 33,872
  • 7
  • 36
  • 56
  • weather thank you so much, but i got errors this line: `unsigned poolsize = strlen(pool);` **implicit conversion loses integer precision: 'unsigned long' to 'unsigned int'** and i couldnt implement inside in your code, not yet :) – misshyde Nov 23 '16 at 17:09
  • Well just change the types appropriately. `strlen` actually returns `size_t`. – Weather Vane Nov 23 '16 at 17:12
  • I have changed the types to `size_t`. – Weather Vane Nov 23 '16 at 17:14
  • Didn't you get the same thing with your own `i – Weather Vane Nov 23 '16 at 17:23
  • actually i was asking now how could i implement you code? i mean in my code inside :D – misshyde Nov 23 '16 at 17:25
  • I don't understand you: this is an alteration to the code you posted in the question, which now does what you asked: no duplicate letters. If you want a key of 3 letters, change to `#define LENGTH 3`. – Weather Vane Nov 23 '16 at 17:37
0

// why program get errors this line? (unused variable cipher_text)

char *cipher_text, msg[255]; 

You declare cipher_text but you only use msg.

You could declare only:

char msg[255];
Eliot B.
  • 162
  • 11
  • thank you Eliot i changed but now i got errors this line `scanf ("%[^\n]", msg);` **format specified type 'char*' but the argument has type 'char**'** and this line `encryption(msg);` **incompatible pointer types passing 'char *[255]' to parameter of type 'char *'** – misshyde Nov 23 '16 at 17:06
0

Copy paste from cplusplus.com/reference

The pseudo-random number generator is initialized using the argument passed as seed.

For every different seed value used in a call to srand, the pseudo-random number generator can be expected to generate a different succession of results in the subsequent calls to rand.

Two different initializations with the same seed will generate the same succession of results in subsequent calls to rand.

If seed is set to 1, the generator is reinitialized to its initial value and produces the same values as before any call to rand or srand.

In order to generate random-like numbers, srand is usually initialized to some distinctive runtime value, like the value returned by function time (declared in header ). This is distinctive enough for most trivial randomization needs.

/* srand example */
#include <stdio.h>      /* printf, NULL */
#include <stdlib.h>     /* srand, rand */
#include <time.h>       /* time */
int main ()
{
  printf ("First number: %d\n", rand()%100);
  srand (time(NULL));
  printf ("Random number: %d\n", rand()%100);
  srand (1);
  printf ("Again the first number: %d\n", rand()%100);

  return 0;
}
jurhas
  • 613
  • 1
  • 4
  • 12
  • sorry for my bad english, but I cannot understand what you are asking for. If you do not get the answer, because may be I let something in my head. It means that in C and C++ the function srand() gives ever the same sequence. To avoid it you should call srand() with a random value, for trivial useses the function time() does his job perfectly. than you call rand(). And you are getting a nice random sequence – jurhas Nov 23 '16 at 17:36