Removing duplicates in a C array - arrays

I am writing a program which determines the intersection of 2 integer arrays (size of 10 elements). I think I got every other parts covered except for sorting out duplicates. Does anyone know a way of checking duplicates without making a function or using an external C library?
#include <stdio.h>
#define SIZE 10
int main(void){
//Initialization
int array1[SIZE];
for (int i = 0; i < SIZE; i++)
{
printf("Input integer %d of set A: ", i + 1);
scanf("%d", &array1[i]);
}
int array2[SIZE];
for (int i = 0; i < SIZE; i++)
{
printf("Input integer %d of set B: ", i + 1);
scanf("%d", &array2[i]);
}
int intersection[SIZE];
for (int i = 0; i < SIZE; i++)
{
intersection[i] = '\0';
}
//Intersection check
for (int i = 0; i < SIZE; i++)
{
for (int j = 0; j < SIZE; j++)
{
if (array1[i] == array2[j])
{
intersection[i] = array1[i];
break;
}
}
}
//duplicate check
int count = SIZE;
for (int i = 0; i < count; i++)
{
for (int j = i + 1; j < count; j++)
{
if (intersection[i] == intersection[j])
{
for (int k = j; j < count; i++)
{
intersection[k] = intersection[k + 1];
}
count--;
}
}
}
//printing set
for (int i = 0; i < SIZE ; i++)
{
//printf("%d\n", intersection[i]);
if (intersection[i] != '\0')
{
printf("%d\n", intersection[i]);
}
}
return 0;
}
In the code above i was trying one method although it didn't work and instead made the program stuck after inputting all the elements. I am open to other methods as long it doesn't require an external library to run. Thanks

As i see it now , in the third loop where you checking your duplicates i thing that you have to increese k not i :
for (int k = j; j < count; k++), also you must decrise the size of j in your code under the count--;.So your code for checking duplicates seems right but , you want the intersection of this two arrays you made , so you dont have to check for duplicates because in the array intersection[SIZE] you will put only one number from the two arrays, so you will not have duplicates .You should check for duplicates if you wanted to make the union of this two arrays .I make some changings to your code acording what you want to create and this code here find the intersection from two arrays.Try this and delete the duplicate check because that makes your code to run to infinity . One last thing your intersection check must be replace whith this :
//Intersection check
int i = 0, j = 0,k=0; // k is for the intersection array !
while (i < SIZE && j < SIZE) {
if (array1[i] < array2[j])
i++;
else if (array2[j] < array1[i])
j++;
else if(array1[i]==array2[j]) // if array1[i] == array2[j]
{
intersection[k]=array2[j];
//printf("intersection[%d]=%d\n",i,intersection[i]);
intersectCount++;
k++;
i++;
j++;
}
}
printf("intersectCount=%d\n",intersectCount);

Related

c : How to generate random numbers without duplication in a two-dimensional array of languages

I want to put random numbers from 1 to 16 in a two-dimensional array without duplication.
I made a code that eliminates duplicates and puts new random numbers back into the array, but it keeps printing duplicate numbers.
Which part is wrong and why?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int A[4][4];
int i, j, k, l;
int num;
srand(time(NULL));
int count;
for(i = 0; i < 4; i++)
{
for(j = 0; j < 4; j++)
{
//Re:
num = rand() % 16 + 1;
A[i][j] = num;
for(k = 0; k <= i; k++)
{
count = 0;
for(l = 0; l <= j; l++)
{
if(A[k][l] == num)
{
if(k != i && l != j)
{
j--;
count = 1;
break;
// goto Re;
}
}
}
if(count == 1)
break;
}
}
}
for(i = 0; i < 4; i++)
{
for(j = 0; j < 4; j++)
{
printf("%3d", A[i][j]);
}
printf("\n");
}
}
I want to put random numbers from 1 to 16 in a two-dimensional array without duplication. I made a code that eliminates duplicates and puts new random numbers back into the array, but it keeps printing duplicate numbers.
Put the numbers 1,…,16 into an array tmp.
Perform a Fisher-Yates shuffle on tmp.
Iterate through tmp to copy its elements to A using the mapping A[i/4][i%4] = tmp[i].
If you’re not convinced, try a few values of i by hand to assure yourself this works.

How to randomize a to p without repitition

I want to randomize a to p without repetition.
int main(){
int array2[4][4];
bool arr[100]={0};
int i;
int j;
srand(time(NULL));
for(i=0; i<=3; i++){
for(j=0; j<=3; j++){
int randomNumber1;
randomNumber1 = (rand() % (82-65+1))+65;
if (!arr[randomNumber1])
{
printf("%c ",randomNumber1);
array2[i][j]=randomNumber1;
}
else
{
i--;
j--;
arr[randomNumber1]=1;
}
}
printf("\n");
}
return;
the output still has repeat alphabet. I want to have the output in 4x4 with with all a to p without it repeating.
There are some errors in your code. IMHO the most serious is that arr[randomNumber1]=1; is is the wrong branch of the test. That means that your current code does not invalidate once a number was used but only if it has already been invalidated => if you control the arr array at the end of the program all value are still 0.
That is not all. When you get a duplicate, you should only reset the inner loop, and you are currently off by 2 in your maximum ascii code: you go up to R when you want to stop at P.
Your code should be:
for (i = 0; i <= 3; i++) {
for (j = 0; j <= 3; j++) {
int randomNumber1;
randomNumber1 = (rand() % (81 - 65)) + 65;
if (!arr[randomNumber1])
{
printf("%c ", randomNumber1);
array2[i][j] = randomNumber1;
arr[randomNumber1] = 1;
}
else
{
//i--;
j--;
}
}
printf("\n");
}
But this kind of code is terribly inefficient. In my tests it took 30 to 60 steps to fill 16 values, because random can return duplicates. This is the reason why you were advised in comments to use instead the modern algorithm for Fisher-Yates shuffle:
int main() {
int array2[16];
unsigned i, j, k=0;
// initialize array with alphabets from A to P
for (i = 0; i < sizeof(array2); i++) {
array2[i] = 'A' + i;
}
// Use Fisher-Yates shuffle on the array
srand(time(NULL));
for (i = 15; i > 0; i--) {
j = rand() % (i + 1);
if (j != i) {
int c = array2[i];
array2[i] = array2[j];
array2[j] = c;
}
}
// Display a 4x4 pattern
for (i = 0; i < 4; i++) {
for (j = 0; j < 4; j++) {
printf("%c ", array2[k++]);
}
printf("\n");
}
return 0;
}
Which shuffles the array in only 16 steps.
Here is the outline
// Need some #includes here - exercise for the reader
char items[] = "abcdefghijklmnopqrstuvwxyz";
int len = sizeof(items);
srand(time(NULL));
while (len > 0) {
int r = rand() % len;
printf("%c", items[r]);
len--;
items[r] = items[len];
}
This should do the trick to print the whole alphabet in random order without repeats. Modify to do what you need it to do

How to implement check for distinctness

I have a function that reads in a line of ints as an array. I would like to implement an additional check for distinctness in the elements. I am already checking to make sure the array values don't equal the element number.
I tried nesting another for loop to run the check within the other check but I couldn't get it to work properly.
int readArray(int r[SIZE]) {
int i;
for (i = 0; i < SIZE; i++) {
scanf("%d", r + i);
// check for error element number
if (i == r[i]) {
printf("Error: element[%d] == %d\n", i, i);
return 0;
}
}
return 1;
}
I expect the function to output an error if there is a duplicate value or if the element number and value are equal.
My working solution is listed below I would like to make it a bit more concise is possible.
int i,j;
for (i = 0; i < SIZE; i++) {
scanf("%d", r + i);
// check for error
if (i == r[i]) {
printf("Error: Element[%d] == %d\n", i, i);
return 0;
}
}
// check for distinctness
for (i = 0; i < SIZE; i++)
{
for (j = 0; j < SIZE; j++)
{
if(i != j)//check indexes
{
if (r[i] == r[j])
{
printf("Two elements repeat to %d" , i);
printf("\nBad input exiting program");
return 0;
}
}
}
}
return 1;
}
Maybe it's not more concise, but if you want something more efficient, how about this:
...
for (i = 0; i < SIZE; i++)
{
for (j = i; j < SIZE; j++)
...
That way, you skip the comparisons you already made ;)
EDIT: Oh, even better:
...
for (j = i+1; j < SIZE; j++)
...
That way, you get rid of the:
if(i != j)

Printing Two C Columns One Sorted

I'm working on taking 10 numbers as user input and having the input printed in two columns with one sorted column.
#include <stdio.h>
int main(void)
{
int NUM_ELEMENTS = 10;
int list[NUM_ELEMENTS];
int sortedList[NUM_ELEMENTS];
int i, j, temp;
printf("Enter 10 numbers:\n");
for(i = 0; i < NUM_ELEMENTS; i++) {
scanf("%d \n", &list[i]); {
for(j = 0; j < NUM_ELEMENTS; j++){
sortedList[j] = list[i];}
}
}
for(i = 0; i < NUM_ELEMENTS; i++) {
if(list[i] > sortedList[j]) {
temp = list[i];
sortedList[j] = temp;
}
}
for(i = 0; i < NUM_ELEMENTS; ++i){
printf("%d %d\n", list[i], sortedList[j]);
}
return 0;
}
The first column prints correctly but the second column doesn't print the correct numbers. I'm fairly new at coding in C and can't seem to get this to work right. I've tried several variations of the provided code. The columns are also supposed to be side by side and labeled as well.
There are lot of bugs in the above code.
-firstly, looping constraints are wrong in scanning and assigning part
for(i = 0; i < NUM_ELEMENTS; i++) {
scanf("%d \n", &list[i]); {
for(j = 0; j < NUM_ELEMENTS; j++){
sortedList[j] = list[i];} /* for i=0 why list[0] assigned to all sortedList[j] ?
}
}
Replace above one with
for(i = 0; i < NUM_ELEMENTS; i++) {
scanf("%d", &list[i]);
sortedList[i] = list[i];
}
-Secondly,sorting logic is not correct at all.
for(i = 0; i < NUM_ELEMENTS; i++) {
if(list[i] > sortedList[j]) { /* what is sortedList[j] ? */
temp = list[i];
sortedList[j] = temp;
}
}
Replace above one with simple sorting technique logic for now but once become strong with basics check performance view also, which sorting method is better to use.
for(i = 0; i < NUM_ELEMENTS-1; i++) {
for(j = 0;j < NUM_ELEMENTS-1-i; j++) {
if(sortedList[j] > sortedList[j+1]) {
temp = sortedList[j];
sortedList[j] = sortedList[j+1];/* you miss this */
sortedList[j+1] = temp;
}
}
}
-Finally, there is bug in print part also.
for(i = 0; i < NUM_ELEMENTS; ++i){
printf("%d %d\n", list[i], sortedList[j]); /* what is j here ? you can use the same variable i for both. */
}
Replace above one with
for(i = 0; i < NUM_ELEMENTS; ++i){
printf("%d %d\n", list[i], sortedList[i]);
}

Printing a multi dimensional array

I've written a little thing which asks the user for some input (rows and cols), which should then set everything in an array to a dot (".") and print it out, but this crashes my application.
void main()
{
int i,j, m, n;
printf("The number of lines (m): ");
scanf("%d", m );
printf("\nThe number of columns (n): ");
scanf("%d", n);
//create my array
char mineGrid[n][m];
//set all fields in to safe (.)
for (j = 0; j <= n; j++)
{
for (i = 0; i <= m; i++)
{
mineGrid[j][i] = ".";
}
}
//print a grid of dots
for (j = 0; j <= n; j++)
{
for (i = 0; i <= m; i++)
{
printf("%s", mineGrid[j][i]);
}
}
}
Any idea why this is crashing?
On cause of major trouble here is that you have a lot of loop that look like
for (j = 0; j <= n; j++)
/* ^ */
/* | */
/* Look! */
which will run j from 0 to n, but you have declared your array as
char mineGrid[n][m];
which means that space has been allocated for rows numbered 0 to n-1.
All you index loops are wrong in that way. The idomatic way to write those loops is
for (j = 0; j < n; ++j)
where I have fixed the range and also changed the increment from post- to pre- which is an old micro-optimization that generally does not make any difference in c these days (because compilers are smart enough to fix it), but can if you switch to c++ and use a non-trivial class in that way. So I keep it in my list of little things to "fix".
That's because you're putting a string in the array instead of char.
do it like this:
void main()
{
int i,j, m, n;
m = 5;
n = 6;
//create my array
char mineGrid[n][m];
//set all fields in to safe (.)
for (j = 0; j <= n; j++)
{
for (i = 0; i <= m; i++)
{
mineGrid[j][i] = '.';
}
}
//print a grid of dots
for (j = 0; j <= n; j++)
{
for (i = 0; i <= m; i++)
{
printf("%c", mineGrid[j][i]);
}
printf("\n");
}
}
you created n X m elements but used n+1 X m+1 elements in array. use like bellow
a
for (j = 0; j < n; j++)
{
for (i = 0; i < m; i++)
{
mineGrid[j][i] = '.';
}
}
That's because for an array of size N, the valid array indexes 0 to N-1. But you are accessing N th element which is not a valid array index and accessing it invokes undefined behavior.
for (j = 0; j <= n; j++)
{
for (i = 0; i <= m; i++) // Array out of bounds in either condition check
With that said, you have issues with your input as well.
scanf("%d", m ); // Missing & operator before m.

Resources