i made by 2 for loop 2d array. if array show a a x x x x x x a a x a a x x x a x
ID: 3758293 • Letter: I
Question
i made by 2 for loop 2d array.
if array show
a a x x x
x x x a a
x a a x x
x a x x a
a a x a x
if i want to make all x is bottom and a is top how i have to make function? result have to be like
a a a a a
a a x a a
x a x x x
x a x x x
x x x x x
like this before 2 d array have to change this 2 d array. i already make before happen. i need to know how i can change like this this is my function it is not working right now
void gravity(char m[N][N]){
int i,j,x,g;
char temp;
char a;
srand((unsigned)time(NULL));
for(j = 0; j<N; j++){
for(i = 0; i <N; i++){
x= rand()%5;
if(x<=1){
a = '.';
m[i][j] = a;
}
if(x == 2){
a = '#';
m[i][j] = a;
}
if(x == 3){
a = '@';
m[i][j] = a;
}
if(x == 4){
a = '&';
m[i][j] = a;
}
}
}
printf("Before gravity ");
for(i = 0; i < N; i ++){
for(j = 0; j <N; j++){
printf("%c", m[i][j]);
}
printf(" ");
}
for(j = 0; j<N; j++){
for(i = 0; i <N; i++){
if(m[i][j] != '.'){
g = i;
g++;
while(m[g][j] == '.'){
g++;
}
temp= m[g-1][j];
m[g-1][j] = m[i][j];
m[i][j] = temp;
i = g -2;
}
}
}
printf("After gravity ");
for(i = 0; i < N; i ++){
for(j = 0; j <N; j++){
printf("%c", m[i][j]);
}
printf(" ");
}
}
as this one all point (.) have to be at top of 2 d array which is same as my example a. all other charactor have to be bottom.
Explanation / Answer
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define N 10
void gravity(char m[N][N])
{
int i,j,x,g, row, col;
char temp;
char a;
srand((unsigned)time(NULL));
for(j = 0; j<N; j++)
{
for(i = 0; i <N; i++)
{
x= rand()%4;
if(x<=0)
{
a = '.';
m[i][j] = a;
}
else if(x == 1)
{
a = '#';
m[i][j] = a;
}
else if(x == 2)
{
a = '@';
m[i][j] = a;
}
else if(x == 3)
{
a = '&';
m[i][j] = a;
}
}
}
printf("Before gravity ");
for(i = 0; i < N; i ++)
{
for(j = 0; j <N; j++)
{
printf(" %c ", m[i][j]);
}
printf(" ");
}
/*for(j = 0; j<N; j++)
{
for(i = 0; i <N; i++)
{
if(m[i][j] != '.'){
g = i;
g++;
while(m[g][j] == '.'){
g++;
}
temp= m[g-1][j];
m[g-1][j] = m[i][j];
m[i][j] = temp;
i = g -2;
}
}
}*/
for(col = 0; col < N; col++) /*For each column*/
{
for(row = N-2; row >= 0; row--) /*Starting from last but one row till the first row.*/
{
for(i = N-2; i >= N-row-2; i--)
if(m[i+1][col] == '.') /*If . is below any character, pop it up.*/
{
temp = m[i][col];
m[i][col] = m[i+1][col];
m[i+1][col] = temp;
}
}
}
printf("After gravity ");
for(i = 0; i < N; i ++)
{
for(j = 0; j <N; j++)
{
printf(" %c ", m[i][j]);
}
printf(" ");
}
}
int main()
{
char m[N][N];
gravity(m);
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.