Related
I have to implement a function which, given a matrix of 0s and 1s, returns a new matrix that contains the coordinates of the 1s. For example: if matrix is 3x3 and the output is:
1 0 1
0 1 1
0 0 1
New matrix will be 5x2 and the output will be:
0 0
0 2
1 1
1 2
2 2
Some advice? My method would be this:
int matrix[3][3];
for (int i = 0; i < 3; i++){
for (int j = 0; j < 3; j++){
if (matrix[i][i] == 1){
//Code i need
}
}
}
The solution really depends on the requirement:
Is it allowed to allocate result matrix with the maximum size possible (in this case 9 x 2).
If point 1 is not allowed, is it strictly required to use fixed size array (no dynamic allocation). If this is the case then may need to pass the matrix twice to allocate the right size of array.
Other solution is of course by using dynamic allocation (using malloc etc).
The simplified version of option 1 & 2 is shown below:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int matrix[3][3];
matrix[0][0] = 1;
matrix[0][1] = 0;
matrix[0][2] = 1;
matrix[1][0] = 0;
matrix[1][1] = 1;
matrix[1][2] = 1;
matrix[2][0] = 0;
matrix[2][1] = 0;
matrix[2][2] = 1;
//Solution 1 - If allowed to allocate matrix with size more than the result,
//i.e. if input is 3x3 matrix, then the maximum size of result matrix is 9 x 2
int resultMatrix1[9][2];
int usedCount1=0;
for (int i = 0; i < 3; i++){
for (int j = 0; j < 3; j++) {
if (matrix[i][j] == 1) {
resultMatrix1[usedCount1][0] = i;
resultMatrix1[usedCount1][1] = j;
usedCount1++;
} //end if
} //end for
} //end for
//Print the result
printf("\nSolution 1\n");
for (int i = 0; i < usedCount1; i++){
printf("%d %d\n", resultMatrix1[i][0], resultMatrix1[i][1]);
} //end for
//Solution 2 - strictly allocate matrix with size equal to the result.
//Without using dynamic allocation, meaning we need to have two passes.
//1st pass is to count the element which satisfy the criteria
int usedCount2=0;
for (int i = 0; i < 3; i++){
for (int j = 0; j < 3; j++) {
if (matrix[i][j] == 1) {
usedCount2++;
} //end if
} //end for
} //end for
int resultMatrix2[usedCount2][2]; //allocate the right size
int idx=0;
//2nd pass is to fill in the result matrix
for (int i = 0; i < 3; i++){
for (int j = 0; j < 3; j++) {
if (matrix[i][j] == 1) {
resultMatrix2[idx][0] = i;
resultMatrix2[idx][1] = j;
idx++;
} //end if
} //end for
} //end for
//Print the result
printf("\nSolution 2\n");
for (int i = 0; i < usedCount2; i++){
printf("%d %d\n", resultMatrix2[i][0], resultMatrix2[i][1]);
} //end for
return 0;
}
Results are the same for both solution:
Solution 1
0 0
0 2
1 1
1 2
2 2
Solution 2
0 0
0 2
1 1
1 2
2 2
If matrix[i][j] == 1 what do you know about the coordinates [i,j] ? That they are the coordinates of a 1 :)
Secondly, will the input matrix always be 3x3? If not, you'll want to store the dimensions of the matrix in variables, and use theses variables for your for loops.
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 ;
}
I cannot understand what this for-loop does by reading the code. I know how a for-loop works though. By reading this code I literally gain no insight into what the program could be doing.
I'm coming from python to C, if that matters.
#include <stdio.h>
int main (void)
{
int numbers[10] = {1,0,0,0,0,0,0,0,0,0};
int i, j;
for (j = 0; j < 10; ++j)
for (i = 0; i < j; ++i)
numbers[j] += numbers[i];
return 0;
}
for (j = 0; j < 10; ++j)
This just means iterate through each element of the array. It is easy to understand.
for (i = 0; i < j; ++i)
numbers[j] += numbers[i];
This is much harder! I think it is because I cannot figure out in my head what j would be equal to. I cannot follow the two loops properly.
I would specifically like to know how I can read and understand this nested for-loop in C.
(I know what this snippet does because I compiled and ran the code.)
First of all, let's translate it into Python:
numbers = [1,0,0,0,0,0,0,0,0,0]
for j in range(10):
for i in range(j):
numbers[j] += numbers[i]
The outer loop iterates through all ten elements of numbers and, for each item, adds all previous elements in numbers to the current one. It's easier to follow if you add a few print statements.
for (j = 0; j < 10; ++j) doesn't mean "iterate through each element of the array". It means "for each value of j from 0 to 9, execute the code within the loop".
The code within the loop includes another loop:
for (i = 0; i < j; ++i)
numbers[j] += numbers[i];
So, for each value of j from 0 to 9, that inner loop will be executed. In effect, it would be like executing the inner loop sequentially 10 times:
for (i = 0; i < 0; ++i)
numbers[0] += numbers[i];
for (i = 0; i < 1; ++i)
numbers[1] += numbers[i];
for (i = 0; i < 2; ++i)
numbers[2] += numbers[i];
... and so on
(As a side note, the first execution of the inner loop does nothing, since 0 is not less than 0. So the initial value of the outer loop might as well be 1.)
To return to your original phrasing, if the outer loop essentially iterates over all elements of the array, the inner loop does a second iteration over all elements of the array prior to the current element in the outer loop.
Some times it is helpful to just write out what is happening along the way. Also, adding braces might help a little bit as well:
for (j = 0; j < 10; ++j)
{
for (i = 0; i < j; ++i)
{
numbers[j] += numbers[i];
}
}
(A) The first time through the outer loop, j will be zero, thus the inner loop will read:
for (i=0; i < 0; ++i)
because 0 is not less than 0, we skip the body of the inner loop (and numbers remains unchanged).
(B) The second time through the outer loop, j will be one, thus the inner loop will read:
for (i=0; i < 1; ++i)
So we will go through the body of the inner-loop once with i being zero, thus we will execute this
command; numbers[1] = numbers[1] + numbers[0]; (I expanded += for added clarity) which will now make the numbers array look like this: 1,1,0,0,0,0,0,0,0,0
(C) The third time through the outer loop, j will be two, thus the inner loop will read:
for(i=0; i < 2; ++i)
SO we will go through the body of the inner-loop twice with i being first zero, and then one. Thus
we will execute the following commands:
numbers[2] = numbers[2] + numbers[0];
numbers[2] = numbers[2] + numbers[1];
which will transform the numbers array into 1,1,2,0,0,0,0,0,0,0
and so on.
Hope this helps.
The jth element in the numbers array is the sum of all preceding elements in the array. Technically, the preceding elements gets added to the jth element, but numbers[j] is 0 to begin with.
When j equals 1,
numbers[1] = numbers[1] + numbers[0]
which makes numbers[1] == 1. (because i can only be 0 and numbers[0] is 1)
When j equals 2,
numbers[2] = numbers[2] + numbers[1] + numbers[0]
which makes numbers[2] == 2. (because i can be 0 and 1, and numbers[0] and numbers[1] are both 1)
When j equals 3,
numbers[3] = numbers[3] + numbers[2] + numbers[1] + numbers[0]
which makes numbers[3] == 4. (because i can be 0, 1 and 2, and numbers[2] is 2)
As such, any j - 1th (j > 1) element equals the sum of all of its preceding elements. Hence, as the loop goes on, the jth element would end up becoming the double of the j - 1th element.
At the end of the program, each value in the array would be 1 1 2 4 8 16 32 64 128 256
here is the value of your array after each outer loop
1 0 0 0 0 0 0 0 0 0
1 0 0 0 0 0 0 0 0 0
1 1 0 0 0 0 0 0 0 0
1 1 2 0 0 0 0 0 0 0
1 1 2 4 0 0 0 0 0 0
1 1 2 4 8 0 0 0 0 0
1 1 2 4 8 16 0 0 0 0
1 1 2 4 8 16 32 0 0 0
1 1 2 4 8 16 32 64 0 0
1 1 2 4 8 16 32 64 128 0
1 1 2 4 8 16 32 64 128 256
as generated by this
#include <stdio.h>
#define SIZE_ARRAY 10
void show_numbers(int size_array, int index, int given_array[]) {
int i = 0;
for (; i < size_array; i++) {
printf("%3d ", given_array[i]);
}
printf("\n");
}
int main (void) {
// static const int size_array = 10;
int numbers[SIZE_ARRAY] = {1,0,0,0,0,0,0,0,0,0};
int i, j;
show_numbers(SIZE_ARRAY, 0, numbers);
for (j = 0; j < SIZE_ARRAY; ++j) {
for (i = 0; i < j; ++i) {
numbers[j] += numbers[i];
}
show_numbers(SIZE_ARRAY, j, numbers);
}
return 0;
}
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;
}
}
}
#include <stdio.h>
int main(int argc, char **argv) {
int x[5][5] = {{0,1,2,3,4},{5,6,7,8,9}};
for (int i = 0; i < 4; i++) {
for (int j = 0; i < 4; i++) {
printf("%d\n", x[i][j]); } }
return 0; }
This was supposed to give me: 0 1 2 3 4 5 6 7 8 9
And the result is: 0 5 0 0
And then, when I change them to chars:
#include <stdio.h>
int main(int argc, char **argv) {
char x[5][5] = {{'0','1','2','3','4'},{'5','6','7','8','9'}};
for (int i = 0; i < 4; i++) {
for (int j = 0; i < 4; i++) {
printf("%d\n", x[i][j]); } }
return 0; }
I get 48 53 0 0.
Why? The code is pretty clear for me, but it seems that is happening something obscure on background (Or my brain works in a very "pythonic" way...)
Like #Keith Thompson said, you didn't initialize all 25 elements. So the remaining elements are initialized to 0. As a result, the data will be stored this way:
0 | 1 | 2 | 3 | 4 // Row 0
5 | 6 | 7 | 8 | 9 // Row 1
0 | 0 | 0 | 0 | 0 // Row 2
0 | 0 | 0 | 0 | 0 // Row 3
0 | 0 | 0 | 0 | 0 // Row 4
You only initialized the first two rows of your array. This is the reason why you got 0 5 0 0 as your output.
To get the correct output, you need to loop through the first two rows of your array.
Steps to fix this :
First
You need to change your first for-loop from:
for (int i = 0; i < 4; i++)
to
for (int i = 0; i < 2; i++)
Reason: Because you only want to loop through the first two rows (row 0 and row 1).
Second
You need to change your second for-loop from:
for (int j = 0; i < 4; i++)
to:
for (int j = 0; j < 5; j++)
Reason: You need variable j for your loop condition, not i. You also need to change from 4 to 5; because in an array, the index starts with 0. So, the indexes of each columns are 0,1,2,3,4 , respectively.
To sum up, your code supposed to be...
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 5; j++)
{
printf("%d\n", x[i][j]);
}
}
Additionally, when you are changing to char x[5][5], you need to use %c, to print a character, instead of %d.
Moreover, the reason you are getting weird numbers like 48 because when you print a char with %d, you are actually printing its ASCII values. Referring to the ASCII table below, number 48 represents character '0'.
Image from http://www.asciitable.com/
for(i = 0 ; i < 2 ; i++)
for(j = 0 ; j < 5 ; j++)
printf("%d\n",x[i][j]);
i dont know why you initialized only 2 1-d arrays. but changing the bounds in the for loop should suffice your needs