0

So I have this code:

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

int main() {

    char a[200], b = 0;
    int x;
    x = 100 + rand() % 200;
    for (int i = 0; i < x; i++) {
        a[i] = 'a' + rand() % 26;
    }

    for (int i = 0; i < x; i++) {
        if (b % 10 == 0) { 
            printf("\n%c ", a[i]); 
            b = 0;
        }
        else {
            printf("%c ", a[i]);
        }
        b++;
    }
    printf("\n");

    return 0;

}

Purpose is that I should generate random array of letters from 'a' to 'z' (which I've managed to do) and after that print new array without elements that repeat in first array. I've tried implementing code from here for removing duplicate elements but it didn't worked in my code.

Sven B
  • 29
  • 1
  • 8

3 Answers3

1

A simple solution is to loop over the array and copy each element to a new array, but first check that the value doesn't already exist in the new array.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

An O(n) solution, assuming your array contains only letters a to z, consists of creating another small array of 26 integers initialized to zeroes, exist[26], then for each letter from the the main array,

  • if exist[letter - 'a'] > 0 don't print it
  • otherwise print it and increment exist[letter - 'a']

for instance,

int exist[26] = { 0 };

for(int i=0 ; i<x ; i++) {
   if (exist[a[i] - 'a'] == 0) {
      exist[a[i] - 'a']++;
      printf("%c ", a[i]);
   }
}
Déjà vu
  • 28,223
  • 6
  • 72
  • 100
0

For starters the program has undefined behavior due to the statement

x = 100 + rand() % 200;

because the calculated value of the variable x can exceed the size of the array.

I think you mean

x = 1 + rand() % 200;
   ^^^

Also it is desirable to call the standard function srand to get different random sequences when the program runs.

The program can look the following way.

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

#define N   200

int main(void) 
{
    char s[N];
    size_t n;

    srand( ( unsigned int )time( NULL ) );

    n = 1 + rand() % N;

    for ( size_t i = 0; i < n; i++ )
    {
        s[i] = 'a' + rand() % ( 'z' - 'a'  + 1 ); 
    }

    for ( size_t i = 0; i < n; i++ )
    {
        putchar( s[i] );
        if ( ( i + 1 ) % 10 == 0 || i + 1 == n ) putchar( '\n' );
    }

    putchar( '\n');

    size_t m = 0;

    for ( size_t i = 0; i < n; i++ )
    {
        size_t j = 0;
        while ( j < m && s[j] != s[i] ) j++;

        if ( j == m )
        {
            if ( m != i ) s[m] = s[i];
            ++m;
        }
    }

    n = m;

    for ( size_t i = 0; i < n; i++ )
    {
        putchar( s[i] );
        if ( ( i + 1 ) % 10 == 0 || i + 1 == n ) putchar( '\n' );
    }

    putchar( '\n');

    return 0;
}

Its output might be like

bimiwgnkew
tphzfidwmn
yqoyoxbbxd
kalxljfyvj
upzdoglrez
edsubgsfjr
kvrvscgadb
lxsmdhuoaz

bimwgnketp
hzfdyqoxal
jvursc
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335