C programming. Sorting rows in a 2D array - c

I'm trying to sort the elements within the individual rows of a 2D array. I understand how to sort the elements inside a 1D array, but I am having serious trouble getting it to sort the 2D.
Code for the 1D array:
for (i = 0; i < size; i++)
{
for (j = i +1; j < size; ++j)
{
if (array2[i] > array2[j])
{
swap = array2[i];
array2[i] = array2[j];
array2[j] = swap;
}
}
}
What I want to do: 2D Array before sorting
9 2 0 1 6 3
0 9 1 2 3 8
4 2 5 4 3 6
3 6 4 3 9 3
0 2 1 2 0 4
4 1 9 4 2 7
2D array after sorting:
0 1 2 3 6 9
0 1 2 3 8 9
2 3 4 4 5 6
3 3 3 4 6 9
0 0 1 2 2 4
1 2 4 4 7 9
My code for the 2D so far:
size: the user defined dimensions (in the above case it is 6)
for (i = 0; i < size; i++)
{
for (j = 0; j < size; j++)
{
if(array[i][j] > array[i][j+1])
{
swap = array[i][j];
array[i][j] = array[i][j+1];
array[i][j+1] = swap;
}
}
}
Any help or advice would be much appreciated. Thank you all.

If you want to use your single array sorting algorithm (bubble sort) to sort the two dimensional array then you have to add the another for loop: An outer for loop which will take care of each row. Let's say m is number of row and n is number of column.
for(k=0; k< m; k++) {
for (i = 0; i < n; i++) {
for (j = i +1; j < n; ++j) {
if (array2[k][i] > array2[k][j]) {
int swap = array2[k][i];
array2[k][i] = array2[k][j];
array2[k][j] = swap;
}
}
}
}
But this is not an efficient approach to sort the array, it's time complexity will be O(mn^2)

copy all the elements of the 2d array into an 1d array
then apply any sorting algorithm on 1d array & then copy back the sorted 1d array to the 2d array.
please don't mind
if you have a better solution then post it that will be helpfull for me.

You can simply use STL to sort 2D array row-wise..
for (i=0;i<n;i++){
for ( j=0;j<n;j++){
cin>>a[i][j];
}
sort(a[i],a[i]+n);
}

int tmp,l;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
tmp = a[i][j];
l = j + 1;
for (int k = i; k < 2; k++) {
while (l < 2) {
if (tmp < a[k][l]) {
tmp = a[k][l];
a[k][l] = a[i][j];
a[i][j] = tmp;
}
l++;
}
l = 0;
}
}
}

Related

Right rotation for 2D array

I tried to code a right rotation for a 2D array.
Here is the main code:
for (int k = 0; k < rotate; k++) { //rotate is the no of times to shift right
for (int i = 0; i < n1; i++) { //n1 is no: of rows
for (int j = 0; j <n2; j++) { //n2 is no: of columns
//Shifting right
int temp = A[i][n2 - 1];
A[i][n2 - 1] = A[i][j + 1];
A[i][j + 1] = A[i][j];
A[i][j] = temp;
}
}
}
for (int i = 0; i < n1; i++) {
for (int j = 0; j < n2; j++) {
printf("%d", A[i][j]);
}
printf("\n");
}
It is working for size 2x2 where:
Input:
1 2
3 4
Output:
2 1
4 3
But it's not working for size 3x3 and above.
Input:
1 2 3
4 5 6
7 8 9
Output:
3 2 1
6 5 4
9 8 7
Where expected output is:
3 1 2
6 4 5
9 7 8
Please guide me about where I'm wrong and I apologize for any mistakes in my question.
See:
https://www.programiz.com/c-programming/examples/matrix-transpose ;)
You can change that solution to use one array.
In your code you are referring to both left and right neighbours (though left one is wrongly referred because it should be last cell only for first interation) and don't keep value for next iteration.
It should be implemented as follows:
For each row left is initalized with the value of very last item in the row, because it is on the left of 0th item. Then while iterating over row items we first save current value to temp to use it later, then save left to current item, and then use previosly saved temp as new left for next iteration.
for (int k = 0; k < rotate; k++) { //rotate is the no of times to shift right
for (int i = 0; i < n1; i++) { //n1 is no: of rows
int left = A[i][n2 - 1];
for (int j = 0; j < n2; j++) { //n2 is no: of columns
//Shifting right
int temp = A[i][j];
A[i][j] = left;
left = temp;
}
}
}

Sorting a 2D Array c++

I am bubble sorting a 2D array that looks like this. I am confuse on how to make my largest value as 1 and make the 2nd row's value follow to 1st row's counterpart.
Input:
13 9 1 8 5
1 2 3 4 1
Actual output:
1 5 8 9 13
1 2 3 4 1
This is the expected output that i am trying to make.
Output:
5 8 9 13 1
1 4 2 1 1
Here is my code for sorting the cards (col = 5 and row = 2):
void sortedCards(int card[][col])
{
int i, j, k, temp;
printf("\n\nSorted Cards\n");
for (k = 0; k < 10; k++)
{
for (i = 0; i < row - 1; i++)
{
for (j = 0; j < col - 1; j++)
{
if (card[i][j] > card[i][j + 1])
{
temp = card[i][j];
card[i][j] = card[i][j + 1];
card[i][j + 1] = temp;
}
}
}
}
for (i = 0; i < row; i++)
{
if (i == 1)
{
printf("\n");
}
for (j = 0; j < col; j++)
{
printf("%i ", card[i][j]);
}
}
}
If your sorting is only dependent on the first row, there is no need to iterate through the second row. Just set both rows at the same time while checking the first row.
Also, if you want 1 to be treated as larger than all other numbers, you need to add that to your Boolean logic. Adjusting your for loop like below should do it.
int j, k, temp, temp2;
for (k = 0; k < 10; k++)
{
for (j = 0; j < col-1; j++)
{
//here we only test row 0, and we check if the value is 1
if (card[0][j] == 1 || (card[0][j] > card[0][j+1] && card[0][j+1] != 1))
{
//all other reassignment is the same but you do both rows at the same time
temp = card[0][j];
temp2 = card[1][j];
card[0][j] = card[0][j + 1];
card[1][j] = card[1][j + 1];
card[0][j + 1] = temp;
card[1][j + 1] = temp2;
}
}
}

How to print backwards column of matrix represented by array in C?

I am working on program that takes matrix from input file like this. where first row represents parameters of matrix - rows,cols,0 for changing odd cols and 1 for changing even cols
5 5 0
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
and now I have to take odd clomuns (example: 7 4 1) and print it backwards so it will look like this ( 1 4 7 ) if I had 3x3 matrix it would looks like:
1 2 3
4 5 6
7 8 9
output matrix with odd cols printed backwards
7 2 9
4 5 6
1 8 3
and this is code I have so far
int r = 0, c = 0, odds = 0,n = 0,i,j;
FILE *fp,*fp2;
fp = fopen(argv[1],"r");
fp2 = fopen(argv[2],"w");
if(!fp){
printf("file doesnt exist\n");
}
if(!fp2){
printf("file doesnt exist\n");
}
fscanf(fp,"%d %d %d", &r, &c, &odds);
n = r *c;
int* matrix= (int*)malloc(r*c* sizeof(int));
for(int i = 0; i < n; i++)
{
fscanf(fp,"%d",&matrix[i]);
}
if(odds == 0){
for(int i = 0; i < n; i++){
if(i%2==0){
matrix[i] = i;
}
}
}else if(odds == 1){
for(int i = 0; i < n; i++){
if(i%2!=0){
matrix[i] = ;
}
}
}
for(i = 0;i < n; i++)
{
if(i % s == 0 ){
fprintf(fp2,"\n");
}
fprintf(fp2,"%d ",matrix[i]);
}
fclose(fp);
fclose(fp2);
return 0;
}
and my problem is with backwarding the cols, which is supposed to happen here
if(odds == 0){
for(int i = 0; i < n; i++){
if(i%2==0){
matrix[i] = i;
}
}
}else if(odds == 1){
for(int i = 0; i < n; i++){
if(i%2!=0){
matrix[i] = ;
}
}
}
1st if is for printing even cols backwards and 2nd is for odd cols
and as you can see the matrix is in my program represented by normal array
which wasn't my idea, but teachers, so its supposed to work like this
1 2 3|4 5 6|7 8 9 ----> 7 2 9|4 5 6|1 8 3
ok I just found out about map indexing, so now each position in array is presented as matrix[j+(i*r)] so for example 1st position in the 3x3 matrix above would be something like this: matrix[1+(0*3)], 4th pos would be matrix[1+(1*3)] etc...
So now my question is how to index the opposite postion in the column.
code update:
for(int i = 0; i < r; i++){
for(int j = 1; j < c; j++){
if(i%2!=0){
matrix[j+i*r] = ....;
}
}
}
In both instances you want to replace matrix[i] with an element further up in the matrix.
n n
1 2 3
4 5 6
7 8 9
In this example for replacing odd values, 1 and 7 should be switched. The difference in the indices is 6. However this is dependent on the matrix dimensions. The general formula would be:
n^2 - n - r*(2n) + i
where r is the row you are on. Since you are flipping the matrix you only have to do rows up to (n-n%2)/2.
Here is some python code to clarify
for i in range(0,int((matrixdim-matrixdim%2)/2)*matrixdim):
if ((i-r)%2) == 0:
temp = matrix[i]
matrix[i] = matrix[matrixdim*matrixdim - matrixdim - r*2*matrixdim + i]
matrix[matrixdim*matrixdim - matrixdim - r*2*matrixdim + i] = temp
if ((i+1)%matrixdim) == 0:
r += 1
Using i,j notation
for i in range(0,int((matrixdim-matrixdim%2)/2)):
for j in range(0, matrixdim):
pos = j + matrixdim*i
temp = matrix[pos]
if j%2 == even:
matrix[pos] = matrix[matrixdim*matrixdim - matrixdim - i*2*matrixdim + pos]
matrix[matrixdim*matrixdim - matrixdim - i*2*matrixdim + pos] = temp

2d-arrays in bubble sorting

I'm trying to create a 2d-array in bubble sort, arranged 25 numbers 5 by 5 in ascending order
my inputs
Enter 25 integers:
Input No.[0][0]: 4
Input No.[0][1]: 5
Input No.[0][2]: 8
Input No.[0][3]: 9
Input No.[0][4]: 4
Input No.[1][0]: 2
Input No.[1][1]: 1
Input No.[1][2]: 0
Input No.[1][3]: 2
Input No.[1][4]: 4
Input No.[2][0]: 6
Input No.[2][1]: 7
Input No.[2][2]: 4
Input No.[2][3]: 5
Input No.[2][4]: 5
Input No.[3][0]: 4
Input No.[3][1]: 8
Input No.[3][2]: 9
Input No.[3][3]: 1
Input No.[3][4]: 2
Input No.[4][0]: 4
Input No.[4][1]: 5
Input No.[4][2]: 2
Input No.[4][3]: 1
Input No.[4][4]: 9
my output shows
Ascending:
4 4 5 8 9
0 1 2 2 4
4 5 5 6 7
1 2 4 8 9
1 2 4 5 9
as you can see its not in proper arranged, it only arranged the 5 numbers each lines not the whole numbers
can anybody help arranged my integers like this
Ascending:
0 1 1 1 2
2 2 2 4 4
4 4 4 4 5
5 5 5 6 7
8 8 9 9 9
this is my code so far
int main(){
int rows = 5, cols = 5;
int arr[rows][cols];
int i,j,k,swap;
printf("Enter 25 integers:\n");
for(i = 0; i < rows; i++){
for(j = 0; j < cols; j++){
printf("Input No.[%d][%d]: ", i+0,j+0);
scanf("%d", &arr[i][j]);
}
}
for(k = 0; k < rows; k++){
for(i = 0 ; i < cols; i++){
for(j = i + 1; j < cols; j++){
if(arr[k][i] > arr[k][j]){
swap = arr[k][i];
arr[k][i] = arr[k][j];
arr[k][j] = swap;
}
}
}
}
printf("Ascending:\n");
for( i = 0 ; i < rows; i++){
for( j = 0 ; j < cols; j++){
printf("%3d", arr[i][j]);
}
printf("\n");
}
getch();
}
Improving on Ahmad's answer, I would like to add the following code (for shorting the table in ascending order):
#include <stdio.h>
#define COL 5
#define ROW 6
int main()
{
int temp, t, i, j;
int arr[ROW][COL]={30,29,28,27,26,25,24,23,22,21,20,19,18,17,16,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1};
for(t=1; t<(ROW*COL); t++)
{
for(i=0; i<ROW; i++)
{
for(j=0; j<COL-1; j++)
{
if (arr[i][j]>arr[i][j+1])
{
temp=arr[i][j];
arr[i][j]=arr[i][j+1];
arr[i][j+1]=temp;
}
}
}
for(i=0; i<ROW-1; i++)
{
if (arr[i][COL-1]>arr[i+1][0])
{
temp=arr[i][COL-1];
arr[i][COL-1]=arr[i+1][0];
arr[i+1][0]=temp;
}
}
}
for(i=0; i<ROW; i++)
{
printf("\n");
for(j=0; j<COL; j++)
printf("%3d", arr[i][j]);
}
return 0;
}
replace the input with your table and the definitions with the size of your given array and you're done.
output of the above when executed:
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
26 27 28 29 30
void twoDimBubbleSort(int** arr, int row, int col) {
for (int i = 0; i < (row * col); ++i) {
for (int j = 0; j < (row * col) - 1; ++j) {
int cr = j / col; // current row
int cc = j % col; // current column
int nr = (j + 1) / col; // next item row
int nc = (j + 1) % col; // next item column
if (arr[cr][cc] > arr[nr][nc])
swap(&arr[cr][cc], &arr[nr][nc]); // any way you want to swap variables
}
}
}
You don't necessarily need to create a 1D array, you can consider your 2D array is a 1D array and transform coordinates when you set/get them.
Consider a structure point with x and y, and ARR_LEN is 5.
int from2Dto1D(point p){ return p.x+ p.y*ARR_LEN;}
Point from1Dto2D(int i){ Point p; p.x = i%ARR_LEN; p.y=i/ARR_LEN; return p;}
Now you can use the normal bubble sorting algorithm with a 1D index on 2D squares array, you just need to convert your index into 2 Point and access/switch data using these Point. (2 because you need a Point with index and a Point with index+1
Put all the array elements from 2-D array to 1-D array then
sort that 1-D array and then put 1-D array in the matrix format
Try this code ....works according to the above given logic
#include<stdio.h>
int main(){
int arr[5][5],l=0;
int result[25],k=0,i,j,temp;
arr[0][0]= 4;
arr[0][1]= 5;
arr[0][2]= 8;
arr[0][3]= 9;
arr[0][4]= 4;
arr[1][0]= 2;
arr[1][1]= 1;
arr[1][2]= 0;
arr[1][3]= 2;
arr[1][4]= 4;
arr[2][0]= 6;
arr[2][1]= 7;
arr[2][2]= 4;
arr[2][3]= 5;
arr[2][4]= 5;
arr[3][0]= 4;
arr[3][1]= 8;
arr[3][2]= 9;
arr[3][3]= 1;
arr[3][4]= 2;
arr[4][0]= 4;
arr[4][1]= 5;
arr[4][2]= 2;
arr[4][3]= 1;
arr[4][4]= 9;
//convert 2 D array in 1 D array
for(i=0;i<5;i++){
printf("\n");
for(j=0;j<5;j++){
printf(" %d",arr[i][j]);
result[k++]=arr[i][j];
}
}
// sort 1 D array
for(i=0;i<25;i++){
for(j=0;j<24;j++){
if(result[j] > result[j+1]){
temp=result[j];
result[j]=result[j+1];
result[j+1]=temp;
}
}
}
/*
for(i=0;i<25;i++){
printf("\n%d",result[i]);
}*/
// convert 1 D array to 2 D array
i=0;
l=0;k=0;
while(i<25){
for(j=0;j<5;j++){
arr[k][j]=result[l];
l++;
}
k++;
i=i+5;
}
//Print matrix i.e 2D array
for(i=0;i<5;i++){
printf("\n");
for(j=0;j<5;j++){
printf(" %d",arr[i][j]);
}
}
}
This works !
#define COL 5
#define ROW 2
int main(){
int temp ;
int arr[2][5]= {2,15,26,14,12,18,1,2,3,4 };
int arr2[10] = {0};
int index = 0 ;
for(int t = 0 ; t<50 ; t++ ){
for (int i =0 ; i < ROW ; i++){
for( int j = 0; j < 5-1 ; j++){
if (arr[i][j] > arr[i][j+1]){
temp = arr[i][j];
arr[i][j] = arr[i][j+1];
arr[i][j+1] = temp;
}
}
//checking for
for( int k = 0 ; k < ROW-1 ; k++){
if (arr[k][COL-1] > arr[k+1][0]){
temp = arr[k][COL-1];
arr[k][COL-1] = arr[k+1][0];
arr[k+1][0] = temp ;
}
}
//---------
}
}
return 0 ;
}

Sudoku code checker in c [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I'm writing a Sudoku solution checker for a class and I've hit a wall.
I'm at the point where I'm checking if I can see whether or individual columns and rows are unique. For some reason the code works on 4x4 grids but as soon as I get up to a 5x5 grid or higher (goal is to get to a 9x9 grid) the program starts to print out that it had failed even when it should succeed.
Any help would be much needed, I want need a point in the right direction or where I should look into
Here's the code:
#include <stdio.h>
#include <stdlib.h>
int main ()
{
int i, j, n, k, p, q;
int fail;
int array[5][5];
int check[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int a = 0;
char *output = NULL;
scanf("%d", &n);
// memory allocated for yes or no at end
output = malloc(sizeof(int) * (n));
while (a < n)
{
fail = 0;
// create this 2D array
for (i = 0; i < 5; i++)
{
for (j = 0; j < 5; j++)
{
scanf("%d", &(array[i][j]));
}
}
// seeing if row is unique
for (i = 0; i < 5; i++)
{
for (j = 0; j < 5; j++)
{
for (k = 0; k < 5; k++)
{
if (array[i][k] == array[i][k+1])
fail += 1;
}
}
}
// seeing if column is unique
for (i = 0; i < 5; i++)
{
for (j = 0; j < 5; j++)
{
for (k = 0; k < 5; k++)
{
if (array[k][j] == array[k+1][j])
fail += 1;
}
}
}
/* for (WHAT DO I DO FOR ROWS)
{
for (WHAT DO I DO FOR ROWS AGAIN BUT REPLACE ROWS WITH COLUMNS)
{
for (NOW IM LOST)
}
}
*/
// success or failure? 0 success, 1 failure
if (fail >= 1)
output[a] = 1;
else
output[a] = 0;
a++;
}
// print out yah or nah
for (i = 0; i < n; i++)
{
if (output[i] == 0)
printf("YES\n");
else
printf("NO\n");
}
return 0;
}
Forget my for loop for the grids, I'll work on that once I figure out how to get the columns and rows working correctly.
Thanks for the help!
Here is an input that would cause the program to fail when it should succeed
1
1 2 3 4 5
2 3 4 5 1
3 4 5 1 2
4 5 1 2 3
5 1 2 3 4
output would be
NO
EDIT: It is now working with a 9x9 grid! Thanks for the help!
#include <stdio.h>
#include <stdlib.h>
#define SIDE_LENGTH 9
int main ()
{
int i, j, n, k, p, q;
int fail;
int array[SIDE_LENGTH][SIDE_LENGTH];
int check[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int a = 0;
char *output = NULL;
scanf("%d", &n);
// memory allocated for yes or no at end
output = malloc(sizeof(int) * (n));
while (a < n)
{
fail = 0;
// create this 2D array
for (i = 0; i < SIDE_LENGTH; i++)
{
for (j = 0; j < SIDE_LENGTH; j++)
{
scanf("%d", &(array[i][j]));
}
}
// seeing if row is unique
for (i = 0; i < SIDE_LENGTH; i++)
{
for (j = 0; j < SIDE_LENGTH; j++)
{
for (k = 0; k < SIDE_LENGTH - 1; k++)
{
if (array[i][k] == array[i][k+1])
fail += 1;
}
}
}
// seeing if column is unique
for (i = 0; i < SIDE_LENGTH; i++)
{
for (j = 0; j < SIDE_LENGTH; j++)
{
for (k = 0; k < SIDE_LENGTH - 1; k++)
{
if (array[k][j] == array[k+1][j])
fail += 1;
}
}
}
/* for (WHAT DO I DO FOR ROWS)
{
for (WHAT DO I DO FOR ROWS AGAIN BUT REPLACE ROWS WITH COLUMNS)
{
for (NOW IM LOST)
}
}
*/
// success or failure? 0 success, 1 failure
if (fail >= 1)
output[a] = 1;
else
output[a] = 0;
a++;
}
// print out yah or nah
for (i = 0; i < n; i++)
{
if (output[i] == 0)
printf("YES\n");
else
printf("NO\n");
}
return 0;
}
input:
1
1 2 3 4 5 6 7 8 9
2 3 4 5 6 7 8 9 1
3 4 5 6 7 8 9 1 2
4 5 6 7 8 9 1 2 3
5 6 7 8 9 1 2 3 4
6 7 8 9 1 2 3 4 5
7 8 9 1 2 3 4 5 6
8 9 1 2 3 4 5 6 7
9 1 2 3 4 5 6 7 8
#ameyCU helped find the error in my code
Setting k to one less than what i and j were set to allowed the code to successfully run on any X*X sized grid. Because k is one less than i and j, it won't try to access a part of the array that hasn't been allocated yet which is where my problem lied.
for (i = 0; i < 5; i++)
{
for (j = 0; j < 5; j++)
{
for (k = 0; k < 5; k++)
{
if (array[i][k] == array[i][k+1])
fail += 1;
}
}
}
Despite the overwriting of the array as already pointed out, your logic is flawed. You don't use j at all. You are just comparing the same values five times.
The problem is the comparison.
if (array[i][k] == array[i][k+1])
I think you are using i as row and column index, then using j to iterate for duplicates. k will be what you compare against so ...
/* compare if j'th value is same as k'th value */
if (j != k && array[i][j] == array[i][k]) /* Don't check same against same */
the second comparison should be
/* compare if j'th value is same as k'th value */
if (j != k && array[j][i] == array[k][i]) /* Don't check same against same */
That would fix your overflow (k+1) bug, and get you going.
The squares could be fixed with
struct co_ords {
int x;
int y;
};
struct co_ords boxes[][9] = {{ {0,0}, {0,1}, {0,2},
{1,0}, {1,1}, {1,2},
{2,0}, {2,1}, {2,2}
},
{ {3,0}, {3,1}, {3,2},
{4,0}, {4,1}, {4,2},
{5,0}, {5,1}, {5,2} },
... /* more boxes go here */
{ {6,6}, {6,7}, {6,8},
{7,6}, {7,7}, {7,8},
{8,6}, {8,7}, {8,8} }};
for( i = 0; i < 9; i++ ){
struct co_ords current_box * = boxes[i];
for( j = 0; j < 9; j++ ) {
for( k = 0; k < 9; k++ ){
if( j != k && array[ current_box[j].x ][ current_box[j].y] == array[ current_box[k].x ][ current_box[k].y] )
fail += 1;
}
}
}
int array[5][5];
so the array is allocated as 5x5
for (i = 0; i < 5; i++)
{
for (j = 0; j < 5; j++)
{
scanf("%d", &(array[i][j]));
}
}
and you are indexing from 0 to 5 ..
to use larger, please do replace all those "5"s with a precompiler definition.
#define SUDOKU_SIDE_LENGTH 5
...
int array[SUDOKU_SIDE_LENGTH ][SUDOKU_SIDE_LENGTH ];
...
for (i = 0; i < SUDOKU_SIDE_LENGTH ; i++)
{
for (j = 0; j < SUDOKU_SIDE_LENGTH ; j++)
{
scanf("%d", &(array[i][j]));
}
}
etc.. that will ensure that you always allocate enough space for the array.
adjust size on the definition, not in the code..

Resources