How to implement check for distinctness - c

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)

Related

Removing duplicates in a C array

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

Finding duplicate value in a row (2D array)

I would like to know how to find duplicate values in the 1st row of my 2d array.
I thought that by setting array[0][0] == array[i][j], it would check if the array[0][0] equals to the number of array[0][rest of the column]. But my code is just popping up my try again message whenever I put my first value.
Here's what I've tried so far.
void main(void)
{
int array[2][5];
int i, j, l, k;
printf("\Please enter 10 values\n");
for (j = 0; j < 5; j++)
{
for (i = 0; i < 2; i++)
{
scanf("%i", &array[i][j]);
for (k = 0; k < 2; k++)
{
for (l = 0; l < 5; l++)
{
while (array[0][0] == array[i][j])
{
printf("You entered 2 identical numbers in the first row, try again:\n");
scanf("%i", &array[i][j]);
}
}
}
}
}
}
// this isn't the fastest algorithm but it works because of the small length
int check_duplicates(int arr[], int len) {
// iterate through the array
for (int i = 0; i < len; i++) {
// only need to check to the right
// since the left elements have been checked previously
for (int j = i + 1; j < len; j++) {
if (arr[i] == arr[j]) {
// there's a duplicate, return
return 1;
}
}
}
// no duplicates found
return 0;
}
int main(void) {
int array[2][5];
int i, j, l, k;
printf("Please enter 10 values\n");
for (j = 0; j < 5; j++) {
for (i = 0; i < 2; i++) {
scanf("%i", &array[i][j]);
// a duplicate has been found
if (check_duplicates(array[0], j + 1)) {
printf("You entered a duplicate, try again.\n");
// undo one loop to read back into that position
i --;
}
}
}
return 0;
}

C programming two-hop neighbors

I am not sure how to get my two-hop neighbors correctly. It's almost correct but on my output, I don't want to include the same vertex. For my output now if vertex 0 is 0, it says "vertex 0: 0.....
I want to skip the vertex it is currently looking at.
Please help me, are my codes for two hop wrong?
this is my codes:
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
#include<time.h>
#define M 20
#define N 20
int main()
{
int i, j, x, a, b;
int G[20][20] = { { 0 } };
/*creaate random adjaceney matrix*/
printf("==================================================\n");
printf("Welcome to my Graph Processing tool!\n\n");
srand(time(NULL));
for (i = 0; i < M; i++) {
for (j = 0; j < N; j++) {
if (i == j) {
G[i][j] = 0;
}
else {
G[i][j] = rand() % 2;
G[j][i] = G[i][j];
}
}
}
/*check whether the whole row equals to 0*/
for (j = 0; j < N; j++) {
if (G[j] == 0) {
x = rand() % 20 + 1;
G[x][j] = G[j][x] = 1;
}
/*print the matrix G*/
else
{
printf("The adjacency for graph G is\n");
for (i = 0; i < M; i++) {
for (j = 0; j < N; j++) {
printf("%d ", G[i][j]);
}
printf("\n");
}
}
}
/*all one-hop neighbors*/
printf("\nList of one-hop neighbors:");
for (i = 0; i < M; i++) {
printf("\nVertex %d: ", i);
for (j = 0; j < N; j++) {
if (G[i][j] == 1) {
printf("%d ", j);
}
}
}
printf("\n===================================\n\n");
/*two-hop neighbors*/
for (i = 0; i < M; i++) {
printf("\nVertex %d: ", i);
for (j = 0; j < N; j++) {
if (G[i][j] == 0) {
printf("%d ", j);
}
}
}
}
printf("\n============================================\n");
system("pause");
return 0;
}
This is my output:
One hop
Two hop
The answer provided by #Jake only works for node 0. For only looking at different nodes you need to do
for (j = 0; j < N; j++) {
if (i != j && G[i][j] == 0) {
printf("%d ", j);
}
}
Furthermore, you are assuming that all nodes without an edge are two-hop neighbors. This is not correct. One way to calculate the actual two-hop neighbors would be ((A + I)^2 > 0) - ((A + I) > 0), where I is the identity matrix.
Also, you can code this via a three-layer loop:
int node, neighbor, neighbor2;
for (node = 0; node < N; node++) {
printf("\nVertex %d: ", node);
for (neighbor = 0; neighbor < N; neighbor++) {
if (G[node][neighbor] == 1) {
for (neighbor2 = 0; neighbor2 < N; neighbor2++) {
if (node != neighbor2 && G[neighbor][neighbor2] == 1) {
printf("%d ", neighbor2);
}
}
}
}
}
Note that per definition M=N, so I've just used N. Also, this might print some 2-hop neighbors twice. You might want to do some filtering before printing.
Couple things to note here.
Be more descriptive with your variable naming, it would have made this a lot easier to read.
M-ROWS, N-COLS, G-Graph
When you loop through each row, you initialize j to 0. This includes the vertex that you are wanting to leave out.
for (j = 1; j < N; 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]);
}

I want to know how I am reading (or writing) elements in an array wrong in C?

I am trying to draw pascal's triangle in C using a 2D array.
I think what is going wrong is something to do with how I am reading or writing to the array. When I look for a number in the (1st) for loop, what I'm doing seems to work but doesn't outside it?
I am coming at this after some coding in Python and am new to C
This is my code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void main()
{
int n, i , j;
int x[n][n];
n = 4;
for (j=0; j<n; j++)
{
for(i=0; i<n; i++)
{
if (i == 0)
{
x[0][j] = 1;
printf("\n(%d, %d)", i,j);
}
if (i != 0)
{
x[i][j] = 0;
}
printf("%d", x[i][j]);
}
}
printf("\n\n(x[0][0]) %d", x[0][0]);
printf("\n");
for(i = 0; i < n; i++)
{
for(j = 0; j < (n); j++)
{
if (j == 0)
{
printf("\n%d ", x[i][j]);
}
else
{
x[i][j] = x[i-1][j-1] + x[i][j-1];
printf("%d ", x[i ][j ]);
}
}
}
printf("\n");
return;
}
any help would be very appreciated
One key issue I see in your second set of loops is the line that reads:
x[i][j] = x[i-1][j-1] + x[i][j-1];
You avoid this if j == 0, but not if i == 0. For example when j == 1 but i == 0, you will try to access a position in the array at x[-1][0] which is outside of the memory allocated by your array.
I think in particular you want to change your second set of loops to something like this:
for(i = 0; i < n; i++)
{
for(j = 0; j < (n); j++)
{
if ((i == 0) || (j == 0))
{
printf("\n%d ", x[i][j]);
}
else
{
x[i][j] = x[i-1][j-1] + x[i][j-1];
printf("%d ", x[i ][j ]);
}
}
}
Note that the inner if condition has been changed from if (j == 0) to if ((i == 0) || (j == 0)) to prevent indexing outside of your array bounds.
Correction:
without assigning n a value
x[n][n] will not function
or try using dynamic allocation for using such runtime array.
I hope this is helpful. thanks

Resources