Thread: i seriously need help for my assignment :(

  1. #1
    Registered User
    Join Date
    Nov 2011
    Posts
    8

    i seriously need help for my assignment :(

    my program is about the sliding puzzle game...
    Firstly, I need to generate a random number from 0-15 randomly and each of them are unique(no repeat) assign into a 2D-array..
    Code:
    #include <stdio.h>
    #include <time.h>
    #include<string.h>
    #include <stdlib.h>
    
    
    #define sizex 4
    #define sizey 4
    
    
    void getrand(int ar[sizex][sizey]);
    
    
    
    
    
    
    int main(void)
    {
    
    
    int puzzle[sizex][sizey];
    printf("************************WELCOME TO SLIDDING PUZZLE GAME*************************\n\n");
    getrand(puzzle);
    
    
    }
    
    
    
    
    
    
    void getrand(int ar[sizex][sizey])
    {
    int x,y;
    int count = 0;
    srand((unsigned)time(NULL));
    
    
    for (x=0; x<sizex; x++)
    {
        for (y=0; y<sizey; y++)
        {
        ar[x][y] = rand()%15;
        printf("|\t%i\t",ar[x][y]);    
        }
    
    
        printf("|");
        printf("\n");
    }
    
    
    }
    the codes above are what i've done so far and stuck in random it uniquely... sorry if my english is poor...

  2. #2
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    I'm not sure what your problem is, but don't call srand() over and over. Just call it once in main() when the program starts, that's enough.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  3. #3
    Programming Wraith GReaper's Avatar
    Join Date
    Apr 2009
    Location
    Greece
    Posts
    2,738
    Well, for each number to be unique you could use an array with boolean values, but I guess that wouldn't apply on larger ranges...
    I'm talking about something like this:
    Code:
    int randFlags[16] = { 0 };
    int temp;
    
    temp = rand() % 16;
    if (!randFlags[temp])
    {
        printf("%d", temp);
        randFlags[temp] = 1;
    }
    Devoted my life to programming...

  4. #4
    Registered User
    Join Date
    Nov 2011
    Posts
    8
    Quote Originally Posted by GReaper View Post
    Well, for each number to be unique you could use an array with boolean values, but I guess that wouldn't apply on larger ranges...
    I'm talking about something like this:
    Code:
    int randFlags[16] = { 0 };
    int temp;
    
    temp = rand() % 16;
    if (!randFlags[temp])
    {
        printf("%d", temp);
        randFlags[temp] = 1;
    }
    hi there, it doesn't work for me
    Is there any other method that can randomly generate the unique number(no need in ascending or descending order) just messy and put inside 4 by 4 array...
    beside using my loop, any other way to assign it into array???
    im using quincy2005...

    example :
    [1][12][11][5]
    [13][2][10][7]
    [14][ 3][ 9][8]
    [ 4][15][ 6][0]

  5. #5
    Registered User
    Join Date
    Nov 2011
    Posts
    29
    how come it didn't work?
    Maybe you didn't see the output, because it only printed one number.
    In order to get all 15 numbers, you could add a counter variable, which you increment by one each time you found another unique number.
    Like this:
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    
    int main() {
        srand(0);
        int randFlags[16] = { 0 };
        int cnt = 0;    // count how many unique random numbers you have so far
        int temp;
        do {
            temp = rand() % 16;
            if (randFlags[temp] == 0) {
                cnt++;    // yay, found one!
                printf("%d ", temp);
                randFlags[temp] = 1;
            }
        } while (cnt < 15);
    }

  6. #6
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    You don't want random values for your sliding puzzle.

    You want randomized POSITIONS for your sliding puzzle game. (and I have a bit of bad news for you about that, later on).

    So to answer your question:
    Code:
    1) set up your 2D array with 1 to 15:
    for(r=0;r<4;r++) {
       for(c=0;c<4;c++) { //r=row, c=column
          puz[r][c]=r*4+c+1;
       }
    }
    Now generate some random INDEX between and swap the values around - like you might shuffle cards, but use something like:

    Use srand() once, up here first, then

    Code:
    for(r=0;r<4;r++) {
       for(c=0;c<4;c++) {
          //generate a random index between 0 and 14, putting it
          //r1 and c1 variables. Now swap puz[r1][c1] with puz[r][c].
          //using a temp value, of course.
      }
    }
    There are more randomized ways to do this, but this is quite serviceable.
    It's easy, and you'll have no repeating numbers in the puzzle.

    The way this sliding puzzle works, it has "hands" property. To be solvable, your original layout of numbers, must be (call it right handed, I'm not sure what the experts call it now, right or left handedness).

    So half the layouts you might give a puzzle, will not be solvable, no matter what you do. Half will be solvable.

    Google "15 sliding puzzle", and you can read up on how to ensure your original puzzle has the right "hand" layout.

  7. #7
    Registered User
    Join Date
    Nov 2011
    Posts
    8
    Quote Originally Posted by naturegirl View Post
    how come it didn't work?
    Maybe you didn't see the output, because it only printed one number.
    In order to get all 15 numbers, you could add a counter variable, which you increment by one each time you found another unique number.
    Like this:
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    
    int main() {
        srand(0);
        int randFlags[16] = { 0 };
        int cnt = 0;    // count how many unique random numbers you have so far
        int temp;
        do {
            temp = rand() % 16;
            if (randFlags[temp] == 0) {
                cnt++;    // yay, found one!
                printf("%d ", temp);
                randFlags[temp] = 1;
            }
        } while (cnt < 15);
    }
    howi if it's 2d- array?
    how do i shuffle it??

  8. #8
    Registered User
    Join Date
    Nov 2011
    Posts
    29
    Quote Originally Posted by Adak View Post
    You don't want random values for your sliding puzzle.

    You want randomized POSITIONS for your sliding puzzle game. (and I have a bit of bad news for you about that, later on).
    But for the array, you could also see the values as the original positions (how they should be, once solved) and the index as the current position. Then latter for the shuffling, we can employ the switch as you proposed to exchange two neighboring positions.

    Quote Originally Posted by tianwu
    howi if it's 2d- array?
    how do i shuffle it??
    You don't really need a 2d array.
    For example to suppose you already have them randomized in a one dimensional array, say it's called a, you would just need to do:
    Code:
        // print result
        for (x=0; x<sizex; x++) {
            for (y=0; y<sizey; y++) {
                printf("|\t%i\t",a[4*x+y]);  // u don't even need a 2D array!
            }
            printf("|");
            printf("\n");
        }
    Try to think about the shuffling by yourself first ;-)

  9. #9
    Registered User
    Join Date
    Nov 2011
    Posts
    8
    Quote Originally Posted by naturegirl View Post
    But for the array, you could also see the values as the original positions (how they should be, once solved) and the index as the current position. Then latter for the shuffling, we can employ the switch as you proposed to exchange two neighboring positions.


    You don't really need a 2d array.
    For example to suppose you already have them randomized in a one dimensional array, say it's called a, you would just need to do:
    Code:
        // print result
        for (x=0; x<sizex; x++) {
            for (y=0; y<sizey; y++) {
                printf("|\t%i\t",a[4*x+y]);  // u don't even need a 2D array!
            }
            printf("|");
            printf("\n");
        }
    Try to think about the shuffling by yourself first ;-)

    what i mean is, let say now im doing my 4by4 array,and then i want to generate the number from 0 - 15 without repeating, how do i generate it in C?
    everytime i restart the program it will be different, i mean the number generated

    example :
    [1][12][11][5]
    [13][2][10][7]
    [14][ 3][ 9][8]
    [ 4][15][ 6][0]

  10. #10
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by tianwu View Post
    what i mean is, let say now im doing my 4by4 array,and then i want to generate the number from 0 - 15 without repeating, how do i generate it in C?
    everytime i restart the program it will be different, i mean the number generated

    example :
    [1][12][11][5]
    [13][2][10][7]
    [14][ 3][ 9][8]
    [ 4][15][ 6][0]
    Please don't use microscopic fonts in your messages...

    You need to listen to Adak on this one...

    The classic 15 tile slider has a whole mess of unsolvable combinations, so your starting positions cannot be truly random. You have to start from a solvable setup or you'll never win the game...

    If you're looking for a simple way to shuffle a list of unique numbers, you can probably work up a modification of this:
    Code:
    // card shuffle demonstration
    
    #include <stdio.h>
    #include <time.h>
    #include <stdlib.h>
    
    #define RANDS 52
    
    int main (void)
      {
        int Nums[RANDS];  // the array
        int item = 0;     // swaps
        int temp;         
        int idx = 0;      // loops
    
        srand(time(NULL));
    
        for(idx = 0; idx < RANDS; idx++)
          Nums[idx] = idx + 1;
    
    
        // unshuffled array
        for (idx = 0; idx < RANDS; idx++)
          printf("[%d] = %d \t", idx, Nums[idx]);
    
        // shuffle the array
        for (idx = RANDS - 1; idx > 0; idx--)
          { item = rand() % idx;
            temp = Nums[idx];
            Nums[idx] = Nums[item];
            Nums[item] = temp; }
    
        // shuffled array
        printf("\n\n");
        for (idx = 0; idx < RANDS; idx++)
          printf("[%d] = %d \t", idx, Nums[idx]);
    
        printf("\n\nPress Enter to exit...");
        getchar();
        return 0;
      }
    The trick is to set your values into the array in order first, using a simple loop or loops... then randomly exchange values, just like shuffling a deck of cards.

  11. #11
    Registered User
    Join Date
    Nov 2011
    Posts
    8
    Quote Originally Posted by CommonTater View Post
    Please don't use microscopic fonts in your messages...

    You need to listen to Adak on this one...

    The classic 15 tile slider has a whole mess of unsolvable combinations, so your starting positions cannot be truly random. You have to start from a solvable setup or you'll never win the game...

    If you're looking for a simple way to shuffle a list of unique numbers, you can probably work up a modification of this:
    Code:
    // card shuffle demonstration
    
    #include <stdio.h>
    #include <time.h>
    #include <stdlib.h>
    
    #define RANDS 52
    
    int main (void)
      {
        int Nums[RANDS];  // the array
        int item = 0;     // swaps
        int temp;         
        int idx = 0;      // loops
    
        srand(time(NULL));
    
        for(idx = 0; idx < RANDS; idx++)
          Nums[idx] = idx + 1;
    
    
        // unshuffled array
        for (idx = 0; idx < RANDS; idx++)
          printf("[%d] = %d \t", idx, Nums[idx]);
    
        // shuffle the array
        for (idx = RANDS - 1; idx > 0; idx--)
          { item = rand() % idx;
            temp = Nums[idx];
            Nums[idx] = Nums[item];
            Nums[item] = temp; }
    
        // shuffled array
        printf("\n\n");
        for (idx = 0; idx < RANDS; idx++)
          printf("[%d] = %d \t", idx, Nums[idx]);
    
        printf("\n\nPress Enter to exit...");
        getchar();
        return 0;
      }
    The trick is to set your values into the array in order first, using a simple loop or loops... then randomly exchange values, just like shuffling a deck of cards.
    how if i want to make it only 4by4 2D-array? i tried your code it works but it doesn't print me a 4by4 2D-array... could you give an example of 2d 4x4 array code? thank you

  12. #12
    Registered User
    Join Date
    Nov 2011
    Posts
    29
    Read and try the code I posted. It will print it out the way you wanted.
    Just because what's printed out is 2 dimensional, doesn't mean your array has to be...

    Quote Originally Posted by tianwu View Post
    what i mean is, let say now im doing my 4by4 array,and then i want to generate the number from 0 - 15 without repeating, how do i generate it in C?
    everytime i restart the program it will be different, i mean the number generated

    example :
    [1][12][11][5]
    [13][2][10][7]
    [14][ 3][ 9][8]
    [ 4][15][ 6][0]

  13. #13
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by tianwu View Post
    how if i want to make it only 4by4 2D-array? i tried your code it works but it doesn't print me a 4by4 2D-array... could you give an example of 2d 4x4 array code? thank you
    Tell you what... put on your thinking cap and *work on the problem*...
    If you put half as much effort into actually solving the problem as you put into begging for help, you'd have this finished by now.

  14. #14
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    If you don't want to use Naturegirl's idea of a 1D array, (just printing it out like a 2D array), then to use a shuffle type solution (which all of us have suggested to you, I believe), then you'll need to:

    First, assign the initial value to the tiles, like I showed you, in my last post, up above.

    Second, get ready to shuffle the tile values around, in a for loop:
    You'll need a random r1 (row1 variable value), (0,1,2,3), and a c1 (column1 variable value), also between 0 and 3.

    r1 = rand() % 4
    c1 = rand() % 4

    I didn't make that part clear (the range of the r1 and c1 variables), in my first post in this thread.

    Now you can use a temp, variable, in a for loop, to help with the swaps. I didn't make this part clear either.
    Code:
    for(r=0;r<4;r++) {
       for(c=0;c<4;c++) {
          r1 = rand() % 4;
          c1 = rand() % 4;       
          temp = puzzle[r][c];
          puzzle[r][c] = puzzle[r1][c1];
          puzzle[r1][c1] = temp;
       }
    }
    And now your puzzle is randomized. Unfortunately, half of the puzzles created this way, can't be solved - no matter what, without cheating.

    Why do I know that? Because I'm an old guy, and had one of these to play with, as a kid. It had been produced by a famous puzzler solver, but he'd cleverly set them up so it could NOT be solved. He (Lloyd), even tried to patent the puzzle. The patent guys knew his little trick, and said "You can patent it, if you can solve it."

    He could not solve it, of course, so his patent application, was denied.

    Here is what I did, when I wrote my program:

    1) I went to several sites that had 15 tile program information, on them (getting their url from Google).

    2) I copied down several of their known good starting positions.

    3) and put them into a data file. The file is read by the program, and the puzzle position is set from the file.

    I STRONGLY suggest you do the same thing.

  15. #15
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    If you want to generate a valid starting board then the best way is to work backwards. randomly pick one of the 2, 3, or 4 squares next to the hole and swap it with the hole. Then repeat this 100, 1000, or 10000 times etc and then you've easily got your guaranteed solvable board.
    That is precisely what I would actually do if I were writing this for real myself, possibly with an optimisation that prevents a swap from exactly undoing the previous swap.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Need help with assignment
    By C_Davis in forum C Programming
    Replies: 4
    Last Post: 03-11-2010, 12:49 AM
  2. Replies: 3
    Last Post: 04-26-2009, 08:54 AM
  3. OOP assignment
    By mike_g in forum A Brief History of Cprogramming.com
    Replies: 1
    Last Post: 10-23-2007, 07:09 PM
  4. help on assignment
    By robasc in forum C Programming
    Replies: 12
    Last Post: 07-08-2005, 05:37 AM
  5. Assignment
    By cYou in forum C++ Programming
    Replies: 4
    Last Post: 06-12-2003, 07:57 AM