Page 1 of 2 12 LastLast
Results 1 to 20 of 23
  1. #1
    bl00dr3d is offline Member
    Join Date
    Apr 2009
    Posts
    17
    Rep Power
    0

    Default Generate unique letters

    Hi everyone, I am writing code for a program in which i need 4 unique letters..to make sure that I have 4 unique letters here is what I have..

    Java Code:
    int counter = 1;
    if (counter > 0) {
    			String secretCode = generateSecretCode();
    			char a = secretCode.charAt(0);
    			char b = secretCode.charAt(1);
    			char c = secretCode.charAt(2);
    			char d = secretCode.charAt(3);
    
    			if (a != b && a != c && a != d && b != c && b != d && c != d) {
    				counter--;
    			}
    where generateSecretCode() is the method that that generates a secret code with 4 random letters.
    The whole thing compiles without any errors but there is some logical error in it that I cant seem to find due to which I keep getting the secretCode with repeated letters..
    I would be very glad if any of you could spot the error in it and explain why it is not working.

    Thanks.
    Last edited by bl00dr3d; 04-06-2009 at 08:26 AM.

  2. #2
    masijade is offline Senior Member
    Join Date
    Jun 2008
    Posts
    2,571
    Rep Power
    8

    Default

    I would go about it completely differently.

    Create an ArrayList containing the characters to use, generate a random integer with a max of the length of the arraylist, then use "remove" and that index to return that character (and remove it from the arraylist), and repeat this process three more times (adjusting the max each time, of course).

  3. #3
    bl00dr3d is offline Member
    Join Date
    Apr 2009
    Posts
    17
    Rep Power
    0

    Default

    Hey masijade thanks for your help man but I am not sure if I completely understand how its supposed to work because I have never really heard of "remove" before and am not that familiar with arrays either. Is it possible for you to direct me to some reading material on this or can you just explain it a bit more please?

    Thanks.

  4. #4
    masijade is offline Senior Member
    Join Date
    Jun 2008
    Posts
    2,571
    Rep Power
    8

    Default

    First of all here are the API docs for ArrayList
    ArrayList (Java Platform SE 6)

    Second of all, the concept is, you have a list of characters, each character get a number "an index". You then generate a random int with a max value being equal to the highest possible index. Then you remove the character with that index from the list, and every character after that point in the list gets it's index reduced by one. Therefore, the next generated number has a max that is one smaller than the previous run.

  5. #5
    bl00dr3d is offline Member
    Join Date
    Apr 2009
    Posts
    17
    Rep Power
    0

    Default

    Ah thank you. it makes way more sense now. Just one more question. How exactly can I remove that one character from the list? Do I have to do it manually or is there a keyword that I can use to get it done automatically?

  6. #6
    bl00dr3d is offline Member
    Join Date
    Apr 2009
    Posts
    17
    Rep Power
    0

    Default

    Oo I took a look at the API doc for ArrayList and it mentions -

    Java Code:
    remove(int index) 
              Removes the element at the specified position in this list.
    I assume thats the "remove" that you were talking about?

  7. #7
    masijade is offline Senior Member
    Join Date
    Jun 2008
    Posts
    2,571
    Rep Power
    8

    Default

    yes. If you read further, it also says that it returns the removed element, so you get your character and remove it from the list, all in one sweep. ;-)

  8. #8
    bl00dr3d is offline Member
    Join Date
    Apr 2009
    Posts
    17
    Rep Power
    0

    Default

    Right here is what I have done till now but it does not compile for some reason.
    Java Code:
    private String generateSecretCode() {
    		String letters = "ABCDEF";
    
    		int first = (int)(Math.random() * 6);
    		char firstLetter = letters.charAt(first);
    		letters.remove(first);
    
    		int second = (int)(Math.random() * 5);
    		char secondLetter = letters.charAt(second);
    		letters.remove(second);
    
    		int third = (int)(Math.random() * 4);
    		char thirdLetter = letters.charAt(third);
    		letters.remove(third);
    
    		int fourth = (int)(Math.random() * 4);
    		char fourthLetter = letters.charAt(fourth);
    		letters.remove(fourth);
    
    		String secretCode = "firstLetter" + "secondLetter" + "thirdLetter" + "fourthLetter";
    		return secretCode;
    	}
    The errors that I am getting are like this..
    Java Code:
    C:\A1Stage5\MyProgram.java:11: cannot find symbol
    symbol  : method charAt(int)
    location: class java.lang.String[]
    		char firstLetter = letters.charAt(first);
    		                          ^
    C:\A1Stage5\MyProgram.java:12: cannot find symbol
    symbol  : method remove(int)
    location: class java.lang.String[]
    		letters.remove(first);
    Can anyone please point out what is it that I am doing wrong?
    Last edited by bl00dr3d; 04-06-2009 at 03:12 PM.

  9. #9
    masijade is offline Senior Member
    Join Date
    Jun 2008
    Posts
    2,571
    Rep Power
    8

    Default

    ArrayList, not array
    Java Code:
        ArrayList<String> = Arrays.asList(new String[] { "A", "B", "C", "D", "E", "F" } );
        String firstLetter = letters.remove((int)(Math.random() * 6));
        ...

  10. #10
    bl00dr3d is offline Member
    Join Date
    Apr 2009
    Posts
    17
    Rep Power
    0

    Default

    What is the difference between an array and an ArrayList?
    One more thing. Where is the identifier in -
    Java Code:
    ArrayList<String> = Arrays.asList(new String[] { "A", "B", "C", "D", "E", "F" } );
    And when I do include that in my code I get 2 errors -
    Java Code:
    C:\A1Stage5\MyProgram.java:8: not a statement
    		ArrayList<String> = Arrays.asList(new String[] { "A", "B", "C", "D", "E", "F" } );
    		         ^
    C:\A1Stage5\MyProgram.java:8: ';' expected
    		ArrayList<String> = Arrays.asList(new String[] { "A", "B", "C", "D", "E", "F" } );
    		                 ^
    I really appreciate you helping me out masijade and I am sorry for all these dumb little questions of mine but its just that we havent covered arrays and stuff yet so whatever I know about them is very limited :(
    Last edited by bl00dr3d; 04-06-2009 at 03:46 PM.

  11. #11
    masijade is offline Senior Member
    Join Date
    Jun 2008
    Posts
    2,571
    Rep Power
    8

    Default

    Sorry, it should be List (in this case) rather than ArrayList.

    An ArrayList is a collection and can grow and shrink dynamically, as well as being able to insert/remove elements and get the remaining elements' indexes adjusted.

    To tell you the truth though, I am not sure if the remove function will operate properly in this "asList" manner. You may have to read the API docs a bit more and experminet a bit in creating a "real" ArrayList.

  12. #12
    masijade is offline Senior Member
    Join Date
    Jun 2008
    Posts
    2,571
    Rep Power
    8

    Default

    Quote Originally Posted by bl00dr3d View Post
    we havent covered arrays and stuff yet so whatever I know about them is very limited :(
    In this case then, you should post more of your code, as it is probably desired for you to solve it with an if statement/while loop, but we need more of your code to actually say what might be wrong with it.

  13. #13
    bl00dr3d is offline Member
    Join Date
    Apr 2009
    Posts
    17
    Rep Power
    0

    Default

    Yup sure I will post more of my code.
    I am trying to make a game Mastermind for my compsci assignment. In this game the computer is supposed to generate a random 4 letter code with no repeated letters and then the user gets a fixed number of chances to try and guess the code correctly.
    Java Code:
    public class MyProgram {
    
    private String generateSecretCode() {
    		
    ArrayList<String> = Arrays.asList(new String[] { "A", "B", "C", "D", "E", "F" } );
    String firstLetter = lettersList.remove((int)(Math.random() * 6));
    String secondLetter = lettersList.remove((int)(Math.random() * 5));
    String thirdLetter = lettersList.remove((int)(Math.random() * 4));
    String fourthLetter = lettersList.remove((int)(Math.random() * 3));
    String secretCode = "firstLetter" + "secondLetter" + "thirdLetter" + "fourthLetter";
    		return secretCode;
    	}
    
    	private String getGuess() {
    }
    
    private int getExactMatches(String secretCode, String guess) {
    }
    
    private int getApproxMatches(String secretCode, String guess) { }
    
    public void start() {
    
    	int numberOfTurns = 6;
    	int guessNumber = 1;
    	System.out.println("Master Mind by hsha077: Stage 5 completed");
    	String secretCode = generateSecretCode();
    	System.out.println("The secret code is: " + secretCode);
    	while (numberOfTurns > 0) {
    	    System.out.print("\n" + (guessNumber++) + ". " + "Enter your guess (ABCDEF): ");
    	    String guess = getGuess();
    	    int exactMatches = getExactMatches(secretCode, guess);
    	    int approxMatches = getApproxMatches(secretCode, guess);
    	    System.out.println("Exact matches: " + exactMatches);
    	    System.out.println("Approximate matches: " + approxMatches);
    	    numberOfTurns--;
    	    if (numberOfTurns == 0) {
    	       System.out.println("Bad luck. You lose! The code was: " + secretCode);
    	    }
    
    	    if (exactMatches > 3) {
    	       System.out.println("Congratulations. You won!");
    	       numberOfTurns *= 0;
    	    }
            }
    
    
    }
    As far as I know I have managed to fulfill all the requirements of the game reasonably well except for the last one: The generated code should not have repeated letters. I have tried like 10 different ways to try and do that but I think I am just falling short in the logic area somewhere. If you can think of a way to do that using If, while or for loops and give me just a push in the right direction I would be real happy :D
    Last edited by bl00dr3d; 04-07-2009 at 02:51 AM.

  14. #14
    Mr.Beans's Avatar
    Mr.Beans is offline Senior Member
    Join Date
    Apr 2009
    Location
    Virginia Beach, Virginia
    Posts
    149
    Rep Power
    0

    Default

    I didn't go through your entire code, but I did notice one thing major. In
    Java Code:
    String secretCode = "firstLetter" + "secondLetter" + "thirdLetter" + "fourthLetter";
    		return secretCode;
    The value of secretCode will be "firstLettersecondLetterThirdLetterfourthLette r"
    I think you want
    Java Code:
    String secretCode = firstLetter + secondLetter + thirdLetter + fourthLetter;
    return secretCode;
    When you use the " " it creates a string object which contains an array of the characters you typed. However when you don't use the " " it references the variable's value instead.

    As for how to create a string without any duplicate characters. Check out the contains method for the String class.
    Java Code:
    public boolean contains(CharSequence s)
    Returns true if and only if this string contains the specified sequence of char values.
    You could have a loop where you only increment if you add a unique character to the string.
    Java Code:
    while(count < 4) {
        str = a new random character
        if( str is not in  returnString) {
            add str to return String
            count++;
        }
    }
    I hope that helps

  15. #15
    bl00dr3d is offline Member
    Join Date
    Apr 2009
    Posts
    17
    Rep Power
    0

    Default

    Quote Originally Posted by Mr.Beans View Post
    I didn't go through your entire code, but I did notice one thing major. In
    Java Code:
    String secretCode = firstLetter + secondLetter + thirdLetter + fourthLetter;
    return secretCode;
    I was thinking along the same lines as you for this one but when I tried to compile it, it kept giving me some error regarding the concatenation sign that is the + sign. But then when I turned each of them into strings and made an array of string, as you said, it stopped giving me that error. In any case, it does not have an effect on the rest of the program so I guess its fine as it is but still thanks for pointing that out :)

    Java Code:
    public boolean contains(CharSequence s)
    Returns true if and only if this string contains the specified sequence of char values.
    You could have a loop where you only increment if you add a unique character to the string.
    Java Code:
    while(count < 4) {
        str = a new random character
        if( str is not in  returnString) {
            add str to return String
            count++;
        }
    }
    I hope that helps
    Hey that sounds very helpful!:D but I would really appreciate it if you could explain in a bit more detail as to how I am supposed to make it increment only if a unique character is added?
    Thanks a lot! :D

  16. #16
    bl00dr3d is offline Member
    Join Date
    Apr 2009
    Posts
    17
    Rep Power
    0

    Default

    Right so I looked up the contains() method but could not figure out how to use it so I just decided to try and do it using the while loop and here is what I got -
    Java Code:
    private String generateSecretCode() {
            int count = 0;
    	String letters = "ABCDEF";
    	String code = " ";
    	while(count < 4) {
    	    char randomLetter = letters.charAt((int)(Math.random() * 6));
    	    if(code.indexOf(randomLetter) == -1) {
    	        String newCode = code + randomLetter;
    	        newCode = code;
    	        count++;
    	    }
    	}
            return code;
    }
    Now I have a few problems here. Firstly, I don't know where I should initialize the variable code and what to initialize it as. Secondly, this while loop will be inside a method that is supposed to return the final secretCode to my start() method. So if the code will be a local variable inside the loop how can I assign to the secretCode variable outside the loop?
    I am going to try and use the contains() method now but in the meanwhile if any of you can spot a solution for my problem above then please advise me on what I should do.
    Thanks.
    Last edited by bl00dr3d; 04-07-2009 at 04:27 AM.

  17. #17
    bl00dr3d is offline Member
    Join Date
    Apr 2009
    Posts
    17
    Rep Power
    0

    Default

    I was looking over the contains() method and I just realized that using contains() as a condition for my if loop will have the same effect as
    Java Code:
    if(code.indexOf(randomLetter) == -1) 
    //Where code is the identifier for the 4 letter code and 
    //randomLetter is the identifier for the new letter generated
    So this means that I am back to square one. My biggest problem is not knowing how I can do something inside the loop that will change a variable outside it. Is it even possible to do so? or even if I could find out how to assign a string inside a loop to a variable outside the loop, that would be very helpful as well..
    Last edited by bl00dr3d; 04-07-2009 at 04:39 AM.

  18. #18
    rdtindsm is offline Member
    Join Date
    Feb 2009
    Posts
    92
    Rep Power
    0

    Default

    This problem is like shuffling a deck of cards.
    The standard algorithm is

    somearray[SIZE]
    for (i = 0; i < SIZE; i ++){
    swap (somearray[i], somearray[random number[]);
    }

    You will have a randomized array with no duplicates.
    Select your target sequence as e.g. somearry[1], somearray[2], etc. There are a number of containers within java.util that would work.

    The question regarding access to variables outside the loop is handled by the concept of "scope" which you will want to become more familiar with, and will as your studies continue. It's a basic concept that would be covered in any entry level tutorial.

    The short and incomplete answer is yes, you can access a variable outside the scope of your loop as long as the scope of your loop is within the scope of the variable being accessed.

    {
    var x
    {some code}
    {my loop code can see x}
    }

    {
    {var x some code} // x visible only within bracket
    {my loop code cannot see x}
    }

  19. #19
    bl00dr3d is offline Member
    Join Date
    Apr 2009
    Posts
    17
    Rep Power
    0

    Default

    Quote Originally Posted by rdtindsm View Post
    The short and incomplete answer is yes, you can access a variable outside the scope of your loop as long as the scope of your loop is within the scope of the variable being accessed.

    {
    var x
    {some code}
    {my loop code can see x}
    }

    {
    {var x some code} // x visible only within bracket
    {my loop code cannot see x}
    }
    Thanks for the explanation. I understand what you said and in fact I knew that already but I think its the way I have phrased my question that has made the question seem like a totally different one to what I meant to ask lol. What I wanted to know was that if there is a variable inside the loop is it possible for me to somehow get that variable outside and assign it to another variable outside the loop. I hope that makes sense and clarifies what I originally wanted to ask. Once again thanks for your answer.
    Last edited by bl00dr3d; 04-07-2009 at 08:06 AM.

  20. #20
    Singing Boyo is offline Senior Member
    Join Date
    Mar 2009
    Posts
    552
    Rep Power
    6

    Default

    well... reading through the post quickly, I'm not sure how much I can do for the bigger picture, but for your last question...

    you need to declare the variable outside the loop, and then modify it inside the loop. e.g

    var x;
    {
    my loop modifies x
    }
    var x keeps properties from the loop

    or, you can use this

    var x;
    {
    my loop modifies var y;
    x = y
    }
    var x has properties assigned to var y inside the loop


    Hopefully this helps you
    Singing Boyo
    If the above doesn't make sense to you, ignore it, but remember it - might be useful!
    And if you just randomly taught yourself to program, well... you're just like me!

Page 1 of 2 12 LastLast

Similar Threads

  1. Generate a random code 4 letters long
    By bl00dr3d in forum New To Java
    Replies: 9
    Last Post: 04-06-2009, 05:32 AM
  2. Unique Filter on search results
    By selva in forum Lucene
    Replies: 0
    Last Post: 02-17-2009, 07:32 AM
  3. Need help with counting letters
    By mrdestroy in forum New To Java
    Replies: 15
    Last Post: 10-22-2008, 01:33 PM
  4. Letter with Letters
    By elgatoboricua in forum New To Java
    Replies: 7
    Last Post: 09-16-2008, 02:59 PM
  5. Unique element in an array
    By revathi17 in forum New To Java
    Replies: 2
    Last Post: 12-31-2007, 08:44 AM

Posting Permissions

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