Thread: Swapping positions of random number in Arrays

  1. #1
    Registered User l2krence's Avatar
    Join Date
    Nov 2010
    Posts
    24

    Unhappy Swapping positions of random number in Arrays

    How to swap the postions of a certain object in Array?
    Like this>>>>
    http://i235.photobucket.com/albums/e...0/untitled.jpg

    i want to make that '!' move but HOW?

    Help mi please~~ T-T

  2. #2
    Registered User Swarvy's Avatar
    Join Date
    Apr 2008
    Location
    United Kingdom
    Posts
    195
    What code do you have for this?

  3. #3
    Registered User l2krence's Avatar
    Join Date
    Nov 2010
    Posts
    24
    well,, to be honest this is the picture taken by my lecturer and he ask me to do this as assignment ......
    So , basically i have no idea how to start...
    i juz know how to construct an array of random number and print out the array in "%c" format

  4. #4
    Registered User
    Join Date
    Aug 2010
    Posts
    230
    basically,
    I would make an array lets say 10 x 10.
    then i would save in each cell #
    then i would put ! at [0,0] just to exist.
    then i would read (a, b) the new location of !.

    just put at the Array[a][b] the ! and at the old A[old_a][old_b] the #..
    and print it...

  5. #5
    Registered User
    Join Date
    Aug 2010
    Posts
    230
    Hey, it is a bit tricky...be carefull to check so as NOT to be out of range of the array, cause then -> Segmentation fault is waiting...

  6. #6
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    l2krence -- Welcome to the forum!

    I can tell you need a bit of a boost - but you won't get this every time you're here!

    Study this very hard!! and have fun!

    Code:
    #include <stdio.h>
    
    #define ROWS 3
    #define COLS 3
    #define UP  2
    #define RIGHT 3
    #define DOWN 4
    #define LEFT 5
    
    void makeMove(char grid[ROWS][COLS], int move, int *row, int *col);
    
    int main(void) {
      int r, c, done=0, row, col, move;
    
      char grid[ROWS][COLS];
      for(r=0;r<ROWS;r++) {
        for(c=0;c<COLS;c++) {
          grid[r][c]='#';
        }
      }
      grid[0][0]='!';  
      row=0;  //location of !
      col=0;  //  ditto
    
      while(!done) {
        printf("\n\n");
        //print out the grid 
        for(r=0;r<ROWS;r++) { 
          for(c=0;c<COLS;c++) {
            printf(" %c",grid[r][c]);
          }
          putchar('\n');
        }
        printf("\n Choose a move: UP=2, RIGHT=3, DOWN=4, and LEFT is 5 (Quit=0): ");
        
        scanf("%d", &move);
        (void) getchar();
        //get their input (be sure they have a quit number)
        if(move==0)
          break;
        makeMove(grid, move, &row, &col);
      }
      printf("\n\n\t\t\t    press enter when ready");
      (void) getchar();
      return 0;
    }  
    void makeMove(char grid[ROWS][COLS], int move, int *row, int *col) {
      int r, c;
    
      /* weed out the illegal moves */
      if((*row==0 && move==UP) || (*row==2 && move==DOWN)) {
        printf("\n that's illegal, try again");
        return;
      }
      if((*col==0 && move==LEFT) || (*col==2 && move==RIGHT)) {
        printf("\n that's illegal, try again");
        return;
      }
      /* two examples of moves */
      grid[*row][*col]='#';  //common line of code for all moves
    
      //if(move==etc
    
      if(move==RIGHT) 
        ++(*col);
      
      if(move==DOWN) 
        ++(*row);
    
      //if(move==etc
    
      grid[*row][*col]='!'; //common line of code for all moves
    
    }
    Last edited by Adak; 11-08-2010 at 04:21 AM.

  7. #7
    Registered User l2krence's Avatar
    Join Date
    Nov 2010
    Posts
    24
    thx Adak!
    but well, i feel a bit depressed when programming was come to me.
    problems like "hmm, what is the 1st step i shuld do" and "Hmmmm.. how to actually make this move // how to make this become that // and so on~~~~"
    yea... kinda like "no idea" and it make my life miserable~
    if i fail this course, another 2000 bucks to the univ again.. haiz.. draining my money
    i wish there's one pro tutor guiding me on this @_@ as the final exam is COMING!!

  8. #8
    Registered User l2krence's Avatar
    Join Date
    Nov 2010
    Posts
    24
    Quote Originally Posted by Adak View Post
    l2krence -- Welcome to the forum!

    I can tell you need a bit of a boost - but you won't get this every time you're here!

    Study this very hard!! and have fun!

    Code:
    #include <stdio.h>
    
    #define ROWS 3
    #define COLS 3
    #define UP  2
    #define RIGHT 3
    #define DOWN 4
    #define LEFT 5
    
    void makeMove(char grid[ROWS][COLS], int move, int *row, int *col);
    
    int main(void) {
      int r, c, done=0, row, col, move;
    
      char grid[ROWS][COLS];
      for(r=0;r<ROWS;r++) {
        for(c=0;c<COLS;c++) {
          grid[r][c]='#';
        }
      }
      grid[0][0]='!';  
      row=0;  //location of !
      col=0;  //  ditto
    
      while(!done) {
        printf("\n\n");
        //print out the grid 
        for(r=0;r<ROWS;r++) { 
          for(c=0;c<COLS;c++) {
            printf(" %c",grid[r][c]);
          }
          putchar('\n');
        }
        printf("\n Choose a move: UP=2, RIGHT=3, DOWN=4, and LEFT is 5 (Quit=0): ");
        
        scanf("%d", &move);
        (void) getchar();
        //get their input (be sure they have a quit number)
        if(move==0)
          break;
        makeMove(grid, move, &row, &col);
      }
      printf("\n\n\t\t\t    press enter when ready");
      (void) getchar();
      return 0;
    }  
    void makeMove(char grid[ROWS][COLS], int move, int *row, int *col) {
      int r, c;
    
      /* weed out the illegal moves */
      if((*row==0 && move==UP) || (*row==2 && move==DOWN)) {
        printf("\n that's illegal, try again");
        return;
      }
      if((*col==0 && move==LEFT) || (*col==2 && move==RIGHT)) {
        printf("\n that's illegal, try again");
        return;
      }
      /* two examples of moves */
      grid[*row][*col]='#';  //common line of code for all moves
    
      //if(move==etc
    
      if(move==RIGHT) 
        ++(*col);
      
      if(move==DOWN) 
        ++(*row);
    
      //if(move==etc
    
      grid[*row][*col]='!'; //common line of code for all moves
    
    }
    Hmm, i tried to compiled and saw something. umm, u missed out the flipping progress~
    it can move to left and down but once i want it to move back it cant move.
    and the flipping means like
    errr,
    when u move the '!' and wants to make it to other symbols like '^' rather than '!' n '#' .
    Tats the big dilemma im facing..
    http://i235.photobucket.com/albums/e...untitled-1.jpg
    see this picture above? when i press '5' which stands for 'flip' it flipped to another number (like displaying another number) >(Like this one)
    http://i235.photobucket.com/albums/e.../untitled2.jpg
    the code for this is printf("IT'S %c! PRESS ANY KEY TO CONTINUE \n");

    and umm, some more ideas about the content of the array.
    Yes, it need to display '#' with the '!' at arr[0][0],
    but when we flip it , we will need the use of ASCII to display the random figure inside the array , so
    one part of my question {
    how we will insert the rand(number) inside the array?
    the random code given to me was
    {void srand(unsigned seed);

    To generate a random integer between 0 and 8:
    x = rand()%9;
    To generate a random integer between 2 and 78:
    x = rand()%77 + 2;

    To generate a random integer between -21 and 48:
    x = rand()%(48-(-21)+1)-21;

    To generate a random double value between 0 and 1:
    x = (double)rand()/RAND_MAX;

    To generate a random double value between a and b:
    x = ((double)rand()/RAND_MAX*(b-a))+a;
    }
    hope you can understand >_<
    Last edited by l2krence; 11-09-2010 at 01:57 AM.

  9. #9
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    I didn't forget anything. I left that part of it, for you to work on.

    You won't get good at programming without practice - and lots of it. That's why I said "study hard!", and "two examples of moves". Not four examples plus the flip move.

    Look at how I coded up those two examples, and code up the other two examples, in a similar way.

    Then try to figure out the flip move.

    Good luck!

    Your random number info sounds right, but here's a bit more info. Other compilers have a bit easier way of doing this, but this is the basics for Turbo C:
    Code:
    srand   Initializes random number generator.
    
     Syntax:
       void srand(unsigned seed);
    
     Prototype in:
     stdlib.h
    
     Remarks:
    The random number generator is reinitialized
    by calling srand with an argument value of 1.
    
    It can be set to a new starting point by
    calling srand with a given seed number.
    
     Return Value: None.
    
     Portability:
    srand is available on UNIX systems and is
    defined in ANSI C.
    
     See Also:
      rand    random    randomize
    
     Example:
     #include <stdlib.h>
     #include <stdio.h>
     #include <time.h>
    
     int main(void)
     {
        int i;
        time_t t;
    
        srand((unsigned) time(&t));
        printf("Ten random numbers from 0 to 99\n\n");
        for(i=0; i<10; i++)
            printf("%d\n", rand() % 100);
        return 0;
     }
    Note that srand should be used just ONCE, before any random numbers are created, in your program.

    You should download a copy of the ASCII chart (just google it), and make a shortcut to it, and put it right on your desktop. Very handy reference.

    You put the random number into the array by assigning it:

    array[r][c] = rand() % //etc..... whatever you need here. Where r and c represent the indeces for your array's row and column.
    Last edited by Adak; 11-09-2010 at 05:33 AM.

  10. #10
    Registered User l2krence's Avatar
    Join Date
    Nov 2010
    Posts
    24
    Aww, well.. Adak.. im back again... i manage to do the move part done but i couldnt do a 'flip'
    ..
    what i done is trying to make (move=flip) and print out a certain value, example
    Code:
    /*on top*/
    #define FLIP 8
    /*at makeMove function*/
    if(move=FLIP)
    grid[*row][*col]= '%';
    and another try i make was
    [code]
    /*declare a function flip and insert a random number function*/
    #define <stdio.h> //top
    //then i declare the srand function below the makeMove function
    void srand(unsigned seed);
    //and next at makeMove function, i declare the grid, flip = printf("%c\n", rand()%45 + 35)

    but it didnt work and show only the move part when i run it.
    Please hel[p~
    and can someone explain more on the break?
    my lecturer didnt teach me tis. :X

  11. #11
    Registered User VirtualAce's Avatar
    Join Date
    Aug 2001
    Posts
    9,607
    And thus we see that spoon feeding code only leads to more questions. It's a good bet that if someone cannot come up with the code on their own they also won't be able to understand or use someone else's code.

  12. #12
    Registered User l2krence's Avatar
    Join Date
    Nov 2010
    Posts
    24
    ah, well perhaps there's online tutoring on programming~ i really couldnt get a clear mind on programming.. even with tons of textbooks i borrowed.. :X
    haiz~

  13. #13
    Registered User l2krence's Avatar
    Join Date
    Nov 2010
    Posts
    24
    well, this is my friend teach me one. but unluckily, my lecturer didnt allow me to use window because he says i only learn begineer things // im still a begineer.

    Code:
    #include<stdio.h>
    #include<conio.h>
    #include<windows.h>
    
    /* To specific the coordinate x and coordinate y for text */
    void gotoxy(int x, int y)
    {
    	COORD coord;
     	coord.X = x;
      	coord.Y = y;
     	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
    }
    
    /* To delay the certain process */
    void delay(unsigned int k)
    {
    	unsigned int z;
    	for(z = 0; z <= k; z++)
    	{
    		gotoxy(0,0);
    		printf("");	   	   
    	}
    }
    
    /* Main Function */
    int main()
    {
    	char c, compare;
    	int i,j,x,y, tempi, tempj, step;
    	int counter;
    	
    	/* Define 2 dimensional array */
    	char a[6][6] ={ {'a','b','c','d','e','f'},
    					{'g','h','i','j','k','l'},
    					{'m','n','o','p','q','r'},
    					{'a','b','c','d','e','f'},
    					{'g','h','i','j','k','l'},
    					{'m','n','o','p','q','r'},
    					};
    					
    	i = j = counter = step = 0;
    	
    	
    	for (x=0;x<6;x++)
    	{
    		for(y=0;y<6;y++)
    		{
    			gotoxy((y+1)*2,(x+1)*2);
    			printf("#");
    		}
    		printf("\n\n");
    	}
    
    	printf("press '1' to move up \n");
    	printf("press '2' to move down \n");
    	printf("press '3' to move left \n");
    	printf("press '4' to move right \n");
    	printf("press '5' to open \n");
    	printf("press '6' to quit the program \n");
    	
    	gotoxy(0,20);
    	printf("Please key in your selection: ");
    	
    	gotoxy(28,3);
    	printf("You are now at:");
    		
    	gotoxy(28,4);
    	printf("Column    Row");
    	gotoxy(30,5);
    	printf("0        0");
    	gotoxy(28,7);
    	printf("STEP");
    	gotoxy(30,8);
    	printf("0");
    		   
    	do{
    		
    		c = getch();
    	
    		switch (c)
    		{
    			/* To control the directions */ 
    			case '1':
    					i--;
    					if (i<0)
    					{
    						i = 0;
    					}
    
    					break;
    			case '2':
    					i++;
    					if (i>5)
    					{
    						i = 5;
    					}
    					break;
    			case '3':
    					j--;
    					if (j<0)
    					{
    						j = 0;
    					}
    					break;
    			case '4':
    					j++;
    					if (j>5)
    					{
    						j = 5;
    					}
    					break;	  
    			case '5':
    									
    					if (a[i][j] != ' ' && (tempi != i || tempj != j))
    					{
    						counter ++;
    						gotoxy((j+1)*2,(i+1)*2);
    						printf("%c",a[i][j]);
    					
    						if(counter == 1)
    						{
    							tempi = i;
    							tempj = j;
    							compare = a[i][j];
    						}	 	 	 	 	 
    								
    						if (counter == 2)
    						{
    							step ++;
    							gotoxy(30,8);
    							printf("%d", step);
    							if(a[i][j] == compare)
    							{
    								gotoxy((j+1)*2,(i+1)*2);
    								printf(" ");											
    								gotoxy((tempj+1)*2,(tempi+1)*2);
    								printf(" ");											
    								a[i][j] = ' ';
    								a[tempi][tempj] = ' ';
    							}
    								else
    							{
    								delay(20000);
    								gotoxy((j+1)*2,(i+1)*2);
    								printf("#");											
    								gotoxy((tempj+1)*2,(tempi+1)*2);
    								printf("#");											
    								tempi = tempj = -1;
    							}
    								counter = 0;
    						}
    					}	
    					break; 	   
    			default: 
    					gotoxy(0,20);
    					printf("Please key in your selection: ");
    		}
    		gotoxy(30,20);
    /*	  	  printf ("%c", a[i][j]);*/
    		
    		gotoxy(30,5);
    		printf("%d        %d",i+1, j+1);
    		
    	}while (c!='6');
    	return 0;
    }
    
    and he says " did i ever teach u case?? " =_= dang.. strict lecturer T-T

  14. #14
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    The break command "breaks" the program control, out of the for or do while, or while loop. Just one loop though. If you instructor only wants you using what he's taught you, and he hasn't taught you the break command yet, I wouldn't suggest using it.

    Use srand() *ONCE* only, near the top of your program.

    You know how to assign a char to the array.
    Code:
      for(r=0;r<ROWS;r++) {
        for(c=0;c<COLS;c++) {
          grid[r][c]='#';
        }
      }
      grid[0][0]='!';  
      row=0;  //location of !
      col=0;  //  ditto
    All you have to do is generate a random char, and you already posted code for how to do that. Did you get your ASCII chart downloaded yet?

    Set your upper limit to 126 and your lower limit to 36. Outside that range, printing up a random char can be very confusing (you might print up the DELETE key or something really odd looking.

    Work with that, and see what you can do. If you get stuck, post up just WHAT has you stuck, particularly.

  15. #15
    Registered User l2krence's Avatar
    Join Date
    Nov 2010
    Posts
    24
    Great news and im feeling happy that im done with the flip part and understand all the code!
    this is wad i done [the latest one from me ^^ ]

    Code:
    #include <stdio.h>
    
    #define ROWS 6
    #define COLS 6
    #define UP 2
    #define RIGHT 3
    #define DOWN 4
    #define LEFT 5
    #define FLIP 6
    
    int main(void) {
    
    int x, y, a, b, row, col, done = 0;
    int move;
    char puzzle[ROWS][COLS];
    char name;
    
    printf("@@@@@@@@@@ WELCOME TO FLIP' EM! @@@@@@@@@@\n\n");
    
    printf("Please enter your name to continue: \n");
    scanf("%s", &name);
    system("cls");
    printf("Good Day, %s!! Now, let's start a new game!\n");
    
    
    for (x = 0; x < ROWS ; x++) {
    	for(y = 0; y < COLS ; y++){
    	puzzle[x][y] = '#';
    	}
    	}
    puzzle[0][0] = '!';
    row = 0;
    col = 0;
    
    while(!done) {
    printf("\n\n");
    
    for (x = 0; x < ROWS ; x++) {
    	for(y = 0; y < COLS ; y++){
    	printf(" %c", puzzle[x][y]);
    	}
    	printf("\n");
    	}
    
    
    printf("\n Choose a move:\n Press 2 to go UP\n Press 3 to go RIGHT\n Press 4 to go DOWN\n Press 5 to go LEFT\n Press 6 to flip\n Press 0 to quit: \n");
    
    scanf("%d", &move);
    system("cls");
    
    (void) getchar();
    
    
    if(move == 0) /* To enable the player to quit the game*/
    break;
    
    puzzle[row][col] = '#'; 
    
    if(move == UP)
    --(row);
    
    if(move == RIGHT)
    ++(col);
    
    if(move == DOWN)
    ++(row);
    
    if(move == LEFT)
    --(col);
    
    puzzle[row][col] = '!';
    
    if(move == FLIP) {
    
    puzzle[row][col] = rand()% 126 + 35;
    puzzle[x][y] = puzzle[row][col];
    
    }
    
    }
    
    }
    but the problem is i cant make the flipped character to remain it position at there when i want to go on to the next move :C like this >
    http://i235.photobucket.com/albums/e.../untitled4.jpg
    - like umm, having the flipped character shows up and the '!' sign together in the maze~
    O..o
    wow, a big dilemma.
    but i tried to use the temporary but have tons of errors after i did tat.. and was not sure like
    - my question is - (briefly)
    do i need to create a temporary array to store the '!' and point the "arrays with '!' movement command" to temporary and carry out the arrays with ! movement again by using 'continue'?
    if yes, where shuld i put my temporary array? do i declare tis temporary to "temparr[6][6] or temparr[a][b]- with creating another array of a and b ?"
    hmmmmmmmm... @3@

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. random number problems
    By lespaul5895 in forum C Programming
    Replies: 3
    Last Post: 07-05-2007, 02:16 AM
  2. Counting number from a random file
    By kamisama in forum C Programming
    Replies: 42
    Last Post: 02-22-2005, 05:16 PM
  3. random number
    By mrukok in forum C++ Programming
    Replies: 7
    Last Post: 03-16-2003, 08:04 PM
  4. Random number generator
    By Caze in forum C++ Programming
    Replies: 6
    Last Post: 12-03-2002, 08:10 AM
  5. Ask about generate Random number
    By ooosawaddee3 in forum C Programming
    Replies: 2
    Last Post: 07-01-2002, 04:30 AM