How to compare jagged array to another array in C? - c

I've been trying to use a jagged array for a project of mine, meanwhile this is just a test furthermore I'll use it in my project. The question is the following How could I compare each element from each array, so in the code below I have three arrays, after them, I have one more which will be used to compare to the first ones,here what I have so far.
#include <stdio.h>
#include <stdlib.h>
int main(){
int row0[4] = {0,1,3,0};
int row1[4] = {5,6,9,10};
int row2[4] = {9,0,1,10};
int aux[4] = {9,6,9,10};
int *result[3] = {row0,row1,row2};
int size[3] = {4,4,4}, k =0;
for (int i = 0; i < 3; i++) {
int *ptr = result[i];
for (int j = 0; j < size[k]; j++) {
if(ptr[j] == aux[j])
{
printf("%d\n",ptr[j]);
}
ptr++;
}
printf("\n");
k++;
result[i]++;
}
return 0;
}
The result of it is 5, but I'd like to loop over all the values from the array that starts with 5, to find out if the all the other values are equal, in other words I want to know which array is equal to the "aux" array.

You have the (inner) loop:
int *ptr = result[i];
for (int j = 0; j < size[k]; j++)
{
if(ptr[j] == aux[j])
{
printf("%d\n",ptr[j]);
}
ptr++;
}
Since you increment both j and ptr, you're doing far too much incrementing. It's probably best to remove the ptr++; line.

Related

Replacing all duplicate numbers in an Array, so that every element is unique in C

The elements in the array are created using rand().
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main(void){
int array[6] = { 0 };
srand(time(NULL));
for(int i = 0; i < 6; i++){
array[i] = rand() % 49 + 1;
}
/*
Code to check for duplicates
if duplicate found
duplicate = rand(49);
*/
for(int i = 0; i<6; i++){
printf("[%d]",array[i]);
}
return 0;
}
I don´t really want to sort the array if it makes it easier to find duplicates because the array is for a lottery ticket.
I have tried different methods, but all of them are inefficient and includes a lot of loops.
I had different approaches, but all of them didn´t really work, because what if, the newly created number, is yet again a duplicate? Or if the last number in the array is a duplicate.
So I came with the following approach: The algorithm will create as many areas, as long no number in the array is a duplicate
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#define TRUE 1
int main(void) {
int a[6] = {0};
srand(time(NULL));
while (TRUE) {
int c = 0;
for (int i = 0; i < 6; i++) {
a[i] = rand() % 49 + 1;
}
for (int i = 0; i < 6; i++) {
for (int j = i + 1; j < 6; j++) {
if (a[i] == a[j]) {
c++;
}
}
}
if (c == 0) {
break;
}
}
for (int i = 0; i < 6; i++) {
printf("%d\n", a[i]);
}
return 0;
}
Any Ideas, how to make an easy, efficient, but not so complex algorithm for a beginner?
Thanks :)
There's two sort of problems here. Firstly, if you find a duplicate number, you wish it to be replaced by another number. However, it is also possible that the new number could be a duplicate to some other value. I'd suggest adding the following code to your program to check for duplicacy
for(int i = 0; i<6; i++)
{
for(int k=0; k<6; k++)
{
if(i==k)
{
continue;
}
if(array[i] == array[k])
{
array[i]=rand()%49+1;
}
}
}
There is an outer loop to rotate between the 6 elements of the array, and an inner loop to test that element against all other elements of that array. However, you should note that it is entirely possible that the elements 1-5 may end up being duplicated to some other value again.
Edit: The continue; statement iterates the loop for the next value. Its there to make sure no element is tested against itself.

Have I written the Selection Sort Algoithm in C the right way?

A question in my book explained selection sort in three lines and then asked the reader to write CODE for it in C. I have written the code here and it is working fine, but I am a little confused whether I have written it in the right way or not. Please read the code, I have even added comments and correct me if needed.
#include <stdio.h>
#define VALUESIZE 10
int main(void)
{
int temp;
int value[VALUESIZE] = {3, 5, 46, 89, 72, 42, 312, 465812, 758, 1};
// Printing array just for the user to see.
for (int k=0; k<VALUESIZE; k++)
{
printf("[");
printf("%d", value[k]);
printf("] ");
}
printf("\n");
// Sorting algo begins
for (int i=0; i < VALUESIZE - 1; i++) // This will obviously loop through each element in our array except the last element as it will automatically be sorted after n-1 steps
{
for (int j= i+1; j <= VALUESIZE; j++) // This nested loop will go through each element which appears after ith element. For e.g. If i = 2, then j will loop through entire array starting from j = 3
{
if (value[i] > value[j]) // This basic if statement will compare our ith and following jth value
{
temp = value[i]; // If the program finds any value[j] greater than value[i], then the values will be swapped.
value[i] = value[j];
value[j] = temp;
}
}
}
// Now after sorting, print the new sorted array.
for (int l=0; l<VALUESIZE; l++)
{
printf("[");
printf("%d", value[l]);
printf("] ");
}
printf("\n");
}
Select sort needs to iterate through the array to compare the ith value. At the end of this pass it will swap the 2 values. This is a reason why its not a very good sort algorithm for medium or large arrays.
I have changed your code a bit below
Untested but should work:
// Sorting algo begins
for (int i = 0; i < arr_length - 1; i++)
{
int min = i;
for (int j = i + 1; j <= arr_length; j++)
{
if (value[j] < value[min])
{
min = j;
}
}
//now swap
int cache = value[min];
value[min] = value[i];
value[i] = cache;
}

Printing unique values of the array in C

I wrote a function creating a dynamic array of random values and another function creating a new array consisting of unique values of the previous array. The algorithm used counts unique values correctly. However, I faced a problem in printing all values. In the example below the program printed 7 2 12714320 4 5 instead of 7 2 4 5 6 .
This is the program which can be tested:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int *delduplicate(int *v, int size_old, int *size_new);
main()
{
int n;
int *norepeat;
float *results;
int dim, size_norepeat, i;
int a[7] = {7,2,2,4,5,6,7};
norepeat = delduplicate(a, 7, &size_norepeat);
for (int i = 0; i < size_norepeat; i++)
printf("%d ", norepeat[i]);
}
// delduplicate function
int *delduplicate(int *v, int size_old, int *size_new)
{
int i, j, k = 1, uniques = 1, repeats, *new_v, temp;
// count the number of unique elements
for (i = 1; i < size_old; i++)
{
int is_unique = 1;
for (j = 0; is_unique && j < i; j++)
{
if (v[i] == v[j])
is_unique = 0;
}
if (is_unique)
uniques++;
}
*size_new = uniques;
// create new array of unique elements
new_v = (int*) malloc(*size_new * sizeof(int));
// fill new array with unique elements
new_v[0] = v[0];
for (i = 1; i < size_old; i++)
{
int is_unique = 1;
for (j = 0; j < i; j++)
{
if (v[i] == v[j])
is_unique = 0;
}
if (is_unique)
new_v[k] = v[i];
k++;
}
return new_v;
}
The problem should be happening here:
// fill new array with unique elements
new_v[0] = v[0];
for (i = 1; i < size_old; i++)
{
int is_unique = 1;
for (j = 0; j < i; j++)
{
if (v[i] == v[j])
is_unique = 0;
}
if (is_unique)
new_v[k] = v[i];
k++;
}
Your problem is probably occurring in the following section -
if (is_unique)
new_v[k] = v[i];
k++;
Here you are incrementing k at each iteration. However, you only want to increment it whenever you have found a unique element. if() without brackets only considers the first statement. So change it to this -
if (is_unique){
new_v[k] = v[i];
k++;
}
This change should make your program run fine.
Side Note : If you do not want to use brackets for an if() , for() , etc, you can separate the statements by commas and use without having the brackets. Like this -
if (is_unique)
new_v[k] = v[i],
k++;

check 2d array diagonally?

I'm trying to search a 3x3 2d array diagonally, like this:
I want to check if all boxes in the diagonal have the same value. Here is how I try to do it:
thisOne = board[0][2]; //set to 'X'
for(i = 0; i<3; i++) {
for(j = 3; j>0; j--){
if(board[i][j-1] != thisOne) {
thisOne= '\0';
}
}
}
//since all boxes were 'X', thisOne is still set to 'X'
if(thisOne != '\0') {
winner = thisOne;
printf("vinnare på nördöst\n");
}
So after running this code, winner should be 'X', if all boxes are X's. But the code does not do that, why is that?
You need to check only diagonal cells instead of checking all the cells.
You are not breaking/exiting the check loop when the first not matching char is retrieved.
Moreover your nested for does not what you guess: inner one loops into all columns of each row, but you want to che only the diagonal values...
You can easily a simple while
int i=0;
int j=2;
while ((i<3) && (j>=0) && (board[i][j] == thisOne))
{
i++;
j--;
}
// if i<3 the diagonal is not full of thisOne char
if ( i < 3)
{
}
As said by #BLUEPIXY, the problem is that the j loop is nested inside the i loop. So for every iteration in the i loop, the j loop runs 3 times on every column, instead of just working on the minor diagonal. There are several ways to fix this, although the most optimal way would be to use only one single loop and only one variable i.
for(i=0;i<3;i++) {
if(board[i][2-i]!=thisOne) {
thisOne='\0'
break;
}
}
To achieve your goal you'd simply need to decrement X iterator & Y iterator when going through your array.
Here is a simple example:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int arr[3][3];
int it_y;
int it_x;
it_y = 0;
it_x = 2;
arr[0][0] = 0;
arr[0][1] = 1;
arr[0][2] = 2;
arr[1][0] = 3;
arr[1][1] = 4;
arr[1][2] = 5;
arr[2][0] = 6;
arr[2][1] = 7;
arr[2][2] = 8;
while (it_x < 3 && it_x >= 0)
{
printf("[%d][%d]: '%d'\n", it_y, it_x, arr[it_y][it_x]);
--it_x;
++it_y;
}
return EXIT_SUCCESS;
}
You can do like
for(int row=0,col=2; row<3; row++,col--)
{
if(board[row][col] != thisOne)
{
thisOne= '\0';
}
}
You can only check diagonal elements like this
for(i = 0, j = 3-1; i < 3; i++, j--) {
if(board[i][j] != thisOne) {
thisOne = '\0';
}
}

How to make strings stick together while radix sorting?

I have to make a program that sort strings (with exact length 7 chars) by using radix sort. I already made a function that sort each column separately. My problem is how to make the whole string move, not just one char. It's really problematic for me to see how should it work in C.
I made one array "char strings[3][8]" and "char output[3][8]" to get sorted 3 strings with exact 7 chars in each one. For example sorting these strings:
strcpy(strings[0], "kupbars");
strcpy(strings[1], "daparba");
strcpy(strings[2], "jykaxaw");
In output I get:
dakaaaa
juparbs
kypbxrw
Each column is sorted correctly but chars don't stick together. I tried many ways for 3 hours but nothing works.
My code looks like this:
void countingSort(char a[][8], char b[][8]) {
int c[123];
for (int pos = 6; pos >= 0; pos--) {
for (int i = 0; i < 123; i++)
c[i] = 0;
for (int i = 0; i < 3; i++)
c[(int)a[i][pos]]++;
for (int i = 1; i < 123; i++)
c[i] += c[i - 1];
for (int i = 2; i >= 0; i--) {
b[--c[(int)a[i][pos]]][pos] = a[i][pos];
}
}
}
(There are constants limiting string length etc. because it's easy to change it to variable - I just focused on getting this program work properly.)
Try changing the loop to move an entire string:
for (int i = 2; i >= 0; i--) {
int k = --c[(int)a[i][pos]];
for(int j = 0; j < 8; j++) {
b[k][j] = a[i][j];
}
}
You could do a circular list but it's a little overhead. I propose you to use memmove().
#include <string.h>
void array_move_forward(char array[3][8]) {
for (int i = 0; i < 3; i++) {
char tmp = array[i][6];
memmove(array[i] + 1, array[i], 6);
array[i][0] = tmp;
}
}
void array_move_rewind(char array[3][8]) {
for (int i = 0; i < 3; i++) {
char tmp = array[i][0];
memmove(array[i], array[i] + 1, 6);
array[i][6] = tmp;
}
}
A other solution would be to manipulate your string yourself and using a index, that indicate the first letter of your string.
{
char str[7];
int i = 0;
...
int j = i;
for (int k = 0; k < 7; k++) {
char tmp = str[j++ % 7];
}
}
With that you could rotate your string just with i++ or i--.
struct my_string_radix {
char str[7];
int begin;
}

Resources