CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 11 of 11
  1. #1
    Join Date
    Aug 2011
    Posts
    0

    Unhappy Anyone can help me with my code pleasee?

    Alright so im supposed to make a java app that tells you where to stand on this "game". This "game" is determined by how many people are in a circle. The game proceeds by a person holding a sword, passing it to the left to another person, and he passes it again, and the guy who has the sword kills the guy to his right. I have to create a java app which determines where to stand. I have this so far and i have no idea what to do

    import java.util.Scanner;

    public class thegame {
    public static void main(String args[])
    int total_peeps;

    int win_position;
    Scanner myInput = new Scanner(System.in);
    System.out.println("How many people are playing the game?");
    total_peeps = myInput.nextInt();
    win_position = 0;
    for(int n=1; n<=total_peeps; n++){
    if (win_position == 0) {
    /*im not sure about this part*/
    } else {
    total_peeps %= n/5;
    System.out.println("If there are " + total_peeps
    + " Twilight fans, stand " + win_position
    + " to the left of the one with the sword.");
    }

    }

  2. #2
    Join Date
    Mar 2010
    Location
    Melbourne Australia
    Posts
    454

    Re: Anyone can help me with my code pleasee?

    the way to get started , is to have a define a class circle it should have the following proprieties radius diameter and circumference , then person ( with reference to set position) , finally sowrd class. the cirlcle class should be able to add persons with there position ( as vector 2D) X, y position ,

    Object oriented is not hard , just have to write class which mimic real world objects and the interaction

  3. #3
    Join Date
    Jun 2011
    Posts
    35

    Re: Anyone can help me with my code pleasee?

    @kyonaya Just FYI, it makes people's job much easier to help you when you format the code properly. Just embed the Java code in the [ code ] ... [ /code ] tags...Thanks

  4. #4
    Join Date
    Aug 2011
    Posts
    2

    Re: Anyone can help me with my code pleasee?

    Hello, this is an interesting little app you need to make. I am new, but I believe I may be of some help.

    First off I am going to make some assumptions based on your description of the app's functionality.
    1. It is not necessary to create a circle class so long as you know which position each 'person' is in.
    2. There is more than likely a mathematical solution to which 'person' is left standing.
    3. Assuming the sword starts with person1 it would be passed twice, ending up at person3 who then removes person2; and this is where I am kinda guessing but the next move would be passing it twice again to person5 and then person4 is removed. Hopefully that is correct.
    4. It would seem that if you do not have some math formula for figuring out who is in the winning spot then an array would be the way to go. This would essentially have the app 'manually' figure out the correct position; the downside to this method is the more people there are the longer the process would take. (NOTE: I say 'manual' because the app with go through iterations one at a time instead of using a single mathematical formula)

    I will give you advice on how to have the app do the 'manual' method of figuring the answer. Through this method you will be able to gather data on the outcome of different numbers and try to derive a formula on your own. Then again you could just call it good unless you are going to input something like 10,000 people.

    Ok, now for some useful stuff. You will want to start by creating a simple 'person' class. In the person class you will want to create a Boolean variable to keep track of if they are alive or not (this value would be true by default). After receiving input to get your total_peeps value, you can define a 'person' array of the size total_peeps. You know have your array of people to play the game with. This next part may be a bit tricky but it should work out fine. The game you described is just a loop that steps twice instead of once. (e.g n+=2 instead of n++) The next question is "What kind of loop do I use?". Any loop could do the trick but I would suggest using a while() loop, but it's just personal preference. A nice way to exit this loop would be to make another Boolean variable within main() called something like game_won or w/e really (Default value of false of course). An integer value, lets say 'i', will also be needed to traverse through the person array you created. So, if i begins as 1 the first loop iteration would add 2 (i+=2) and then you could just subtract 1 from i and use that value to select the specific array object (e.g. personArray[i-1] : going further personArray[i-1].alive = False). That first iteration would kill person 2. The iterations would keep going in the same fashion until you got to the end of the array, which is where you need to figure out how to skip the 'person'(s) that are not alive and also go back to 1 if you are at the end of the array. When only 1 person is alive then game_won would become true and whichever position in the array has a living person would be the winner. So viola, I didn't give you a step-by-step answer but hopefully it is enough to help you figure it out. Keep in mind you may need more variables than I listed.

    Sorry for the lengthy text, I am quite new to this, but if you have questions please ask.

  5. #5
    Join Date
    May 2006
    Location
    UK
    Posts
    4,473

    Re: Anyone can help me with my code pleasee?

    Your quite right in that you don't need a circle class but rather than using an array it would be better to use a linked list and set the last node to point to the first node. You then have a circular list.

    In the crudest form you just need to add an integer to each linked list node to denote it's starting position. Then starting at position 1, move forward 2 nodes and remove the last node you left. Because you have a linked list it's easy to remove each player (node) as you kill them and the list will naturally resize itself and remain circular so you just have to keep doing the move forward 2 nodes and remove the last node you left action until there's only one node left. This surviving node will contain the number of the ideal starting position.
    Posting code? Use code tags like this: [code]...Your code here...[/code]
    Click here for examples of Java Code

  6. #6
    Join Date
    Aug 2011
    Posts
    2

    Re: Anyone can help me with my code pleasee?

    Keang, that sounds so much easier than using an array. I didn't realize how useful a linked list would be, it seems I have a lot to learn. However, I can shed some light on a mathematical solution. There is a pattern based off of the factors of 2. This would require a little knowledge of logarithms, but it is pretty simple. Here is what you need to find:

    1. Get the power of 2 that total_peeps is closest to (NOTE: you can just cast to an int to get a whole number; this is where the logarithms come in which return a double)

    2. Get the difference between total_peeps and 2 to the power of what you got in step 1

    3. I will leave this step for you to figure out, it is only simple addition to get the answer. (Hint: it has to do with the difference found in step 2)

    This will give you the numerical position of the person who will be left.

  7. #7
    Join Date
    May 2006
    Location
    UK
    Posts
    4,473

    Re: Anyone can help me with my code pleasee?

    However, I can shed some light on a mathematical solution...
    Nice one.
    Posting code? Use code tags like this: [code]...Your code here...[/code]
    Click here for examples of Java Code

  8. #8
    Join Date
    Aug 2011
    Location
    West Yorkshire, U.K.
    Posts
    54

    Cool Re: Anyone can help me with my code pleasee?

    Didn't quite believe the mathematical solution so I had to code it .... so thought I might as well share it.
    Code:
    public class CircularElimination {
    
        /**
         * Very simple linked list implementation.
         */
        public static class Member {
            Member previous; // Reference to previous member
            Member next;     // Reference to next member
            int id;          // An identifier
    
            // Override toString so we can use the class thus:
            // System.out.println("blah " + class) rather than System.out.println("blah " + class.getId()
            public String toString() {
                return "Player-" + id;
            }
    
            // The remainder are simply generated getters and setters
            public Member getPrevious() {
                return previous;
            }
    
            public void setPrevious(Member previous) {
                this.previous = previous;
            }
    
            public Member getNext() {
                return next;
            }
    
            public void setNext(Member next) {
                this.next = next;
            }
    
            public int getId() {
                return id;
            }
    
            public void setId(int id) {
                this.id = id;
            }
    
        }
    
    
        public static void main(String args[]) {
            CircularElimination ce = new CircularElimination();
            for( int players = 2; players < 2000; players++) {
                int predicted = ce.predictWinner(players);
                int winner = ce.play(players, false, false);
    
                if(predicted == winner) {
                    System.out.println("Players: " + players + " winner: " + winner + " [predicted: " + predicted + "]");
                }
                else {
                    System.err.println("Players: " + players + " winner: " + winner + " [predicted: " + predicted + "]");
                }
            }
        }
    
    
        // Predict the winner
        public int predictWinner(int players) {
            double logBase2 = Math.log((double)players)/Math.log(2.0);
            int rounded = (int)logBase2;
            int pow = (int) Math.pow(2, rounded);
            int predicted = ((players - pow) * 2) + 1;
            return predicted;
        }
    
    
        public int play(int players, boolean output, boolean debug) {
            Member start= null;
            Member previous = null;
            Member current = null;
    
            // Initialise circle of players
            for(int i = 1; i <= players; i++) {
                current = new Member();
                current.setId(i);
                // Set start position at the first
                if (i==1) {
                    start = current;
                }
                else {
                    // If second or subsequent, set up forward and backward links
                    // Link this member to previous
                    current.setPrevious(previous);
                    // Link previous to this one
                    previous.setNext(current);
                }
                previous = current;
            }
            // Set the current member's next reference to be the start
            // and the start member's prev reference to be the current.
            // This makes the loop circular.
            current.setNext(start);
            start.setPrevious(current);
    
            if(debug) {
                // Debug code to prove this list is indeed circular both ways ...
                Member temp = start;
                System.out.println("Start: " + temp);
                while(temp.getNext() != null) {
                    temp = temp.getNext();
                    System.out.println("Next:  " + temp);
                    if(temp == start) {
                        System.out.println("Forward links are circular.");
                        break;
                    }
                }
    
                temp = start;
                System.out.println("Start: " + temp);
                while(temp.getPrevious() != null) {
                    temp = temp.getPrevious();
                    System.out.println("Next:  " + temp);
                    if(temp == start) {
                        System.out.println("Backward links are circular.");
                        break;
                    }
                }
            }
    
            // Now play ....
            Member temp = start;
            Member lastManStanding = null;
            int memberCount = countMembers(temp);
            if(output) {
                System.out.println("Start Count: " + memberCount);
            }
    
            while(memberCount > 1) {
                if(output) {
                    System.out.println(temp + " passes to " + temp.getNext());
                }
                temp = temp.getNext();
                Member removeMe = temp;
                if(output) {
                    System.out.println(temp + " passes to " + temp.getNext());
                }
                temp = temp.getNext();
                lastManStanding = temp;
                if(output) {
                    System.out.println(lastManStanding + " eliminates " + removeMe);
                }
                removeMe.getPrevious().setNext(removeMe.getNext());
                removeMe.getNext().setPrevious(removeMe.getPrevious());
                memberCount = countMembers(temp);
            }
    
            if(output) {
                System.out.println(lastManStanding + " Wins");
            }
            return lastManStanding.getId();
        }
    
    
        public int countMembers(Member m) {
            int result = 0;
            if(null != m) {
                result++;
                Member temp = m;
                while(temp.getNext() != null) {
                    temp = temp.getNext();
                    if(temp == m) break;
                    result++;
                }
            }
            return result;
        }
    
    }

  9. #9
    Join Date
    May 2006
    Location
    UK
    Posts
    4,473

    Re: Anyone can help me with my code pleasee?

    We normally discourage such posting as you have in effect done the OP's homework for them, however, as the OP hasn't added anything to the discussion since their first post they've probably either solved it for themselves or got a solution from elsewhere, so thanks for adding the code.

    BTW:
    You don't need a double linked list to solve this. You can just point the current node's next pointer to the node that is 2 places on.
    You don't need to count the number of nodes in the list you just loop until the current node's next pointer points to itself.
    Posting code? Use code tags like this: [code]...Your code here...[/code]
    Click here for examples of Java Code

  10. #10
    Join Date
    Aug 2011
    Location
    West Yorkshire, U.K.
    Posts
    54

    Re: Anyone can help me with my code pleasee?

    Keang - point taken about the homework.
    Chose doubly linked list as an example - it seems more natural to "kill" ones predecessor than to advance 1 node, retain a reference to it then advance again.
    Like your suggested replacement for the node count though - very neat.

  11. #11
    Join Date
    May 2006
    Location
    UK
    Posts
    4,473

    Re: Anyone can help me with my code pleasee?

    Chose doubly linked list as an example - it seems more natural to "kill" ones predecessor than to advance 1 node, retain a reference to it then advance again.
    Fair point. Where your solution would definitely be a lot better is if you needed to vary the number of passes before making the kill.
    Posting code? Use code tags like this: [code]...Your code here...[/code]
    Click here for examples of Java Code

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured