How to remove duplicate elements from random array I generated? - c

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.

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.

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]);
}
}

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

Related

reverse array in range in C

I have to solve it in C language. I have arrays with n integers. L and U are lower and upper bound. I have to reverse numbers in array which is in [L,U]. I tried it by this way, but in some cases the answer is wrong. What mist be changed in the code? Or is there any other logic to complete the task?
#include <stdio.h>
int main() {
int x, arr[100], n, l, u, a, temp, temp1;
scanf("%d%d%d", &n, &l, &u);
for (int i = 0; i < n; i++) {
scanf("%d", &x); // read elements of an array
arr[i] = x;
}
a = n / 2;
for (int i = 0; i < a; i++) {
for (int j = a; j < n; j++) {
if (arr[i] >= l && arr[i] <= u) {
if (arr[j] >=l && arr[j] < u) {
temp = arr[j];
temp1 = arr[i];
arr[i] = temp;
arr[j] = temp1;
}
}
}
}
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
}
sample input:
10(number of integers) -7(lower bound) 5(upper bound)
-10 -9 5 -2 -3 7 10 6 -8 -5
sample output:
-10 -9 -5 -3 -2 7 10 6 -8 5
my output:
-10 -9 -5 -2 -3 7 10 6 -8 5
There is an O(N) solution that does not require nesting of loops.
First, with the code as you as you have it, declare an additional array and some other helper variables that keeps track of what indices need to be swapped.
int left, right;
int swaplist[100] = {0};
int swapcount = 0;
Your can keep your initial intake loop exactly as you have it, but amended to append the index of the newly scanned value to the swaplist array if the value is between the lower and upper bounds.
for (int i = 0; i < n; i++) {
scanf("%d", &x); // read elements of an array
arr[i] = x;
if ((x >= l) && (x <= u)) {
swaplist[swapcount++] = i;
}
}
Then a single loop to iterate over "swaplist" and do the swaps against the original array.
left = 0;
right = swapcount-1;
while (left < right) {
int leftindex = table[left];
int rightindex = table[right];
int tmp = arr[leftindex];
arr[leftindex] = arr[rightindex];
arr[rightindex] = tmp;
left++; right--;
}
You made a valiant attempt. Your nested for() loops are appropriate for some kinds of sorting algorithms, but not for what seems to be the purpose of this task.
From the sample input and desired output, you really want to establish a 'bracket' at either end of the array, then shift both toward the centre, swapping elements whose value happens to satisfy low <= n <= high value. (In this case, -7 <= n <= 5).
Here's a solution:
#include <stdio.h>
int swap( int arr[], size_t l, size_t r ) { // conventional swap algorithm
int t = arr[l];
arr[l] = arr[r];
arr[r] = t;
return 1;
}
int main() {
int arr[] = { -10, -9, 5, -2, -3, 7, 10, 6, -8, -5, }; // your data
size_t i, sz = sizeof arr/sizeof arr[0];
for( i = 0; i < sz; i++ ) // showing original version
printf( "%d ", arr[i] );
putchar( '\n' );
#define inRange( x ) ( -7 <= arr[x] && arr[x] <= 5 ) // a good time for a macro
size_t L = 0, R = sz - 1; // 'L'eft and 'R'ight "brackets"
do {
while( L < R && !inRange( L ) ) L++; // scan from left to find a target
while( L < R && !inRange( R ) ) R--; // scan from right to find a target
} while( L < R && swap( arr, L, R ) && (L+=1) > 0 && (R-=1) > 0 );
for( i = 0; i < sz; i++ ) // showing results
printf( "%d ", arr[i] );
putchar( '\n' );
return 0;
}
-10 -9 5 -2 -3 7 10 6 -8 -5
-10 -9 -5 -3 -2 7 10 6 -8 5
If I have understood the assignment correctly you need to reverse elements of an array that satisfy some condition.
If so then these nested for loops
for (int i = 0; i < a; i++) {
for (int j = a; j < n; j++) {
if (arr[i] >= l && arr[i] <= u) {
if (arr[j] >=l && arr[j] < u) {
temp = arr[j];
temp1 = arr[i];
arr[i] = temp;
arr[j] = temp1;
}
}
}
}
do not make sense.
It is enough to use only one for loop as shown in the demonstration program below.
#include <stdio.h>
int main( void )
{
int a[] = { 1, 10, 2, 3, 20, 4, 30, 5, 40, 6, 7, 50, 9 };
const size_t N = sizeof( a ) / sizeof( *a );
for (size_t i = 0; i < N; i++)
{
printf( "%d ", a[i] );
}
putchar( '\n' );
int l = 10, u = 50;
for (size_t i = 0, j = N; i < j; i++ )
{
while (i < j && !( l <= a[i] && a[i] <= u )) ++i;
if (i < j)
{
while (i < --j && !( l <= a[j] && a[j] <= u ));
if (i < j)
{
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
}
}
for (size_t i = 0; i < N; i++)
{
printf( "%d ", a[i] );
}
putchar( '\n' );
}
The program output is
1 10 2 3 20 4 30 5 40 6 7 50 9
1 50 2 3 40 4 30 5 20 6 7 10 9
You could write a separate function as for example
#include <stdio.h>
void reverse_in_range( int a[], size_t n, int low, int upper )
{
for (size_t i = 0, j = n; i < j; )
{
while (i < j && !( low <= a[i] && a[i] <= upper )) ++i;
if (i < j)
{
while (i < --j && !( low <= a[j] && a[j] <= upper ));
if (i < j)
{
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
++i;
}
}
}
}
int main( void )
{
int a[] = { 1, 10, 2, 3, 20, 4, 30, 5, 40, 6, 7, 50, 9 };
const size_t N = sizeof( a ) / sizeof( *a );
for (size_t i = 0; i < N; i++)
{
printf( "%d ", a[i] );
}
putchar( '\n' );
reverse_in_range( a, N, 10,50 );
for (size_t i = 0; i < N; i++)
{
printf( "%d ", a[i] );
}
putchar( '\n' );
}
Thanks for everyone help. I read all of them, but I found another way to solve this problem. I will write it just in case. (some variable names are random, so in case of questions, comment).
#include <stdio.h>
int main() {
int x, main[100], n, l, u, a = 0, arr[100], temp, m = 0,f=0,c,d;
scanf("%d%d%d", &n, &l, &u);
for (int i = 0; i < n; i++) {
scanf("%d", &x); // read elements of an array
main[i] = x;
if (x >= l && x <= u) {
a++; //check if element is in range [l,u] and increasing a. later "a" will be used a length of the array "arr". this array cootains elements, which in in [u,l].
}
}
//add [u,l] elements in new array "arr"
for (int i = 0; i < n; i++) {
if (main[i] >= l && main[i] <= u) {
arr[m] = main[i];
m++; //index counter of "arr",
}
}
d=0;
for(int i=0;i<n;i++){
if(main[i]==arr[d]){
c=arr[a-d-1];
main[i]=c;
d++;
}
}
for(int i=0;i<n;i++){
printf("%d ",main[i]);
}
}
My best guess is that scanf is very annoying, on top of that, your format is ambiguous.
How will %d%d%d read 1234? Will it give you 12 3 and 4? 1 23 and 4? ...
try to do
scanf("%d %d %d" ...); // or
scanf("%d, %d, %d" ...);
something like that. Note that scanf is not recommended to be used, getc is a neat alternative, though also annoying when you want to read numbers with more than one digit, but you could create a function read_number, which, based on getc, will read a number as a string and return the int value with stoi.

Pyramid patterns using C

I need to do the following pattern using do-while, while or for.
I tried the following code but it prints the pattern only 1-5
I also tried to alter the n being 10 but then the spacing goes nuts.
#include <stdio.h>
int main(void)
{
int n = 5, i, j, num = 1, gap;
gap = n - 1;
for ( j = 1 ; j <= n ; j++ )
{
num = j;
for ( i = 1 ; i <= gap ; i++ )
printf(" ");
gap --;
for ( i = 1 ; i <= j ; i++ )
{
printf("%d", num);
num++;
}
num--;
num--;
for ( i = 1 ; i < j ; i++)
{
printf("%d", num);
num--;
}
printf("\n");
}
return 0;
}
Try replacing both occurences of:
printf("%d", num);
with
printf("%d", num % 10);
Now only the last digit will be shown.
After the change, for n set to 10 the program produces:
1
232
34543
4567654
567898765
67890109876
7890123210987
890123454321098
90123456765432109
0123456789876543210

Runtime error: insertatIndex

#include <stdio.h>
#include <malloc.h>
int insertAt(int *Arr, int len, int num) {
for (int i = 0; i < len; ++i) {
if (num <= Arr[0])
return 0;
else if (num >= Arr[len])
return len + 1;
else if (num >= Arr[i - 1] && num <= Arr[i])
return i;
}
}
int * sortedArrayInsertNumber(int *Arr, int len, int num){
int *output = (int *)malloc((len + 1)*sizeof(int));
if (len <= 0)
return NULL;
for (int i = 0, j = 0; j <= len+1; ++i, ++j) {
if (i == insertAt(Arr, len, num) && j==i) {
output[j] = num;
--i;
}
else if(insertAt(Arr,len,num)==len+1) {
output[j] = num;
}
else {
output[j] = Arr[i];
}
}
return output;
}
int main() {
int input[5] = {2,4,6,8,10};
int *out = (int*)malloc(6*sizeof(int));
out = sortedArrayInsertNumber(input, 5, 12);
for(int i=0;i<6;++i) {
printf("%d\n", out[i]);
}
}
When I try out this test case, it gives me a runtime error sometimes. Other times, it outputs:
2
4
6
8
10
12
Which makes no sense?
Also, is there a way to make my code better?
The question requires me to insert a value num at its appropriate index.
In the function insertAt there is at least two attempts to access memory beyond the array. The first one is in the statement
else if (num >= Arr[len])
^^^^
And the second one is in the statement
else if (num >= Arr[i - 1] && num <= Arr[i])
^^^^^^
when the variable i is equal to 0.
The function sortedArrayInsertNumber starts with a potential memory leak when the variable len is equal at least 0 because at first a memory is allocated and then there is exit from the function with A NULL pointer.
int * sortedArrayInsertNumber(int *Arr, int len, int num){
int *output = (int *)malloc((len + 1)*sizeof(int));
if (len <= 0)
return NULL;
// ...
Also it is a bad idea when the length of an array has type int instead of type size_t.
To call several times the function insertAt in the function sortedArrayInsertNumber does not make sense and breaks the loop.
In the main there is again a memory leak
int *out = (int*)malloc(6*sizeof(int));
out = sortedArrayInsertNumber(input, 5, 12);
The program can look the following way.
#include <stdio.h>
#include<stdlib.h>
size_t insertAt( const int *a, size_t n, int num )
{
size_t i = 0;
while ( i < n && !( num < a[i] ) ) i++;
return i;
}
int * sortedArrayInsertNumber( const int *a, size_t n, int num )
{
int *b = malloc( ( n + 1 ) * sizeof( int ) );
if ( b )
{
size_t pos = insertAt( a, n, num );
size_t i = 0;
for ( ; i < pos; i++ ) b[i] = a[i];
b[i] = num;
for ( ; i < n; i++ ) b[i+1] = a[i];
}
return b;
}
int main(void)
{
int input[] = { 2, 4, 6, 8, 10 };
const size_t N = sizeof( input ) / sizeof( *input );
int *out = sortedArrayInsertNumber( input, N, 12 );
if ( out )
{
for ( size_t i = 0; i < N + 1; i++ )
{
printf( "%d ", out[i] );
}
putchar( '\n' );
}
free( out );
return 0;
}
Its output is
2 4 6 8 10 12
Instead of the loops in the function sortedArrayInsertNumber you can use standard C function memcpy declared in header <string.h>.

Cicle FOR to generate two sequences of numbers

I use this code to create a number sequence, but what i want is increment a second sequence of numbers(each 1000 times 'i' increment, 'j' the second increment of 1)
for (i=0;i<5000;i++)
{
printf("/sample/%d/%d\n",j,i+1);
}
what i want is this:
/sample/0005/0005000
Please try this
#include <usual.h>
int main( )
{
int i = 0;
int j = 0;
int ticker = 1000;
for ( i = 0; i < 5001; i++ )
{
if ( i && i % ticker == 0 )
{
j++;
ticker += 1000;
printf( "\n sample i== %d j== %d ", i, j );
}
}
}

What is wrong with this insertion sort in C?

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <assert.h>
#include <stddef.h>
void insertionSort(int ar_size, int* ar) {
int i, j;
int temp = 0;
for (i = 1; i < ar_size; i++) {
j = i;
while (j > 0 && ar[i - 1] > ar[i]) {
temp = ar[i - 1];
ar[i - 1] = ar[i];
ar[i] = temp;
j--;
}
}
for (j = 0; j < ar_size; j++) {
printf("%d", ar[j]);
printf(" ");
}
}
int main(void) {
int _ar_size;
scanf("%d", &_ar_size);
int _ar[_ar_size], _ar_i;
for (_ar_i = 0; _ar_i < _ar_size; _ar_i++) {
scanf("%d", &_ar[_ar_i]);
}
insertionSort(_ar_size, _ar);
return 0;
}
I have been trying to look for the error. I cannot see any. What is wrong with this code?
For input as 6 and 4 1 3 5 6 2 , it gives output as 1 3 4 5 2 6. There is one less iteration of the loop but I cannot see why? Please help. Thanks.
You are using index i instead of index j in the internal loop of the function.
while(j>0 && ar[i-1]>ar[i])
{
temp = ar[i-1];
ar[i-1] = ar[i];
ar[i] = temp;
j--;
}
Here everywhere index j has to be used.
Also it is a bad idea that the function also outputs the sorted array. It should do only sorting.
The other bad idea is to use identifiers that start with undescores.
It is better when the first parameter is an array and the second parameter is the size of the array.
The code could look the following way
#include <stdio.h>
void InsertionSort( int *a, int n )
{
int i;
for ( i = 1; i < n; i++ )
{
int j = i;
while ( j > 0 && a[j-1] > a[j] )
{
int tmp = a[j-1];
a[j-1] = a[j];
a[j] = tmp;
--j;
}
}
}
int main(void)
{
int size;
scanf( "%d", &size );
int a[size];
int i;
for ( i = 0; i < size; i++ ) scanf( "%d", &a[i] );
for ( i = 0; i < size; i++ )
{
printf( "%d ", a[i] );
}
puts( "" );
InsertionSort( a, size );
for ( i = 0; i < size; i++ )
{
printf( "%d ", a[i] );
}
puts( "" );
return 0;
}
If the input is
10
2 7 5 4 9 1 4 8 3 5
then output is
2 7 5 4 9 1 4 8 3 5
1 2 3 4 4 5 5 7 8 9
You seem to be using the wrong iterator when pushing the value to the front.
while(j>0 && ar[j-1]>ar[j]) {
temp = ar[j-1];
ar[j-1] = ar[j];
ar[j] = temp;
j--;
}
Try performing a dry run on a piece of paper, it's easy to spot the problem.
for (i = 1; i < ar_size; i++) {
j = i;
while (j > 0 && ar[i-1] > ar[i]) { // problem begins here
temp = ar[i-1];
ar[i-1] = ar[i];
ar[i] = temp;
j--;
}
}
i does not change in the inner loop.
At some point your program swaps 6 with 2 and your sample input list becomes 1 3 4 5 2 6, a[i-1] is 2 and a[i] is 6 and because of ar[i-1] > ar[i] condition the program's flow does not go into the inner loop.
Try this fix:
for (i = 1; i < ar_size; i++) {
j = i;
while (j > 0 && ar[j-1] > ar[j]) {
temp = ar[j-1];
ar[j-1] = ar[j];
ar[j] = temp;
j--;
}
}
The problem with your insertion-sort is you have your j indexes replaced with i indexes in the following code:
while(j>0 && ar[j-1]>ar[j])
{
temp = ar[j];
ar[j] = ar[j-1];
ar[j-1] = temp;
j--;
}
Just a note, when requesting input, it is good practice to print a brief statement describing the input expected. (yes, quick a dirty testing is an exception) It makes if much easier to avoid mistakes with something like:
printf ("enter array size: ");
scanf ("%d", &_ar_size);
int _ar[_ar_size], _ar_i;
for (_ar_i = 0; _ar_i < _ar_size; _ar_i++) {
printf ("enter array element[%d] : ", _ar_i);
scanf ("%d", &_ar[_ar_i]);
}

Resources