Home > OS >  How can I limit each number of occuring only once, so my secret code won't have double numbers
How can I limit each number of occuring only once, so my secret code won't have double numbers

Time:12-05

The code is supposed to return a secret code in form of colors, which it did do before the if conditions were added. The problem that occures to me, if I don't try to limit the numbers to occuring only once is as follows

Removing the if conditions from the cases makes the code "work" again but it also results in the numbers being repeated and sometimes leads to not even printing a number. Does anybody have an idea how to stop numbers from reoccuring?

int[] secretcode = new int[4];  
String[] farbcode = new String[4];  

public rndmcode() { // array "secretcode" wird definiert
    Arrays.fill(farbcode, "");
    for (int i = 0; i < 4 && farbcode.length < 4; i  ){                                                      
        //Schleife um eine Randomziffer von 1-6 zu erstellen und
        //https://trainyourprogrammer.de/java-203-programmierung-von-mastermind.html    //bis zur 4ten Stelle vom Array, da der Code 4 Zahlen bracht
        Random zufallszahl = new Random();                                      
        int rndnumber = zufallszahl.nextInt(7); //Die Zahlen 1-6 sind meine Farben, die vorrerst nur Zahlen sind
        
        switch(rndnumber) {
        case 1:
            if(Arrays.asList(farbcode).contains("Blau")){
        
            break;
            }
            else
                {farbcode[i]  = "Blau";
            break;}
        case 2:
            if(Arrays.asList(farbcode).contains("Rot")) {
                break;
            
            }
        
            else
                {farbcode[i]  = "Rot";
            break;}
        case 3: 
            if(Arrays.asList(farbcode).contains("Gelb")){
                break;
                }
            else{
                farbcode[i]  = "Gelb";
            
            break;}
        case 4:
            if(Arrays.asList(farbcode).contains("Grün")){
                break;
                }
            else{
                farbcode[i]  = "Grün";
            
            break;
            }
        case 5:
            if(Arrays.asList(farbcode).contains("Lila")){
                break;
                }
            else {farbcode[i]  = "Lila";
            break;}
        
        case 6:
            if(Arrays.asList(farbcode).contains("Orange")){
                break;
                }
            else {
            farbcode[i]  = "Orange";
            break;
            }
        default:
        }
    }
}
public String stringo() {

    String s = "[";
    for (String element:farbcode) {
        s =element;
        s =", ";
    }
    s = "]";
    return s;
}

CodePudding user response:

The big switch/case with duplicate code is not a good idea. I suggest you to use an hashmap.

Also, I change the farbcode object into an hashmap too to check faster is the item is already added. It's better because we don't create a new array each loop iteration.

int[] secretcode = new int[4];
List<String> farbcode = new ArrayList<>();
HashMap<Integer, String> possibleKey = new HashMap<>();

public rndmcode() {
    // firstly define all id/keys
    possibleKey.put(0, "Blau");
    possibleKey.put(1, "Rot");
    possibleKey.put(2, "Gelb");
    possibleKey.put(3, "Grün");
    possibleKey.put(4, "Lila");
    possibleKey.put(5, "Orange");

    while (farbcode.size() < 4) { // until we don't have 4 items
        Random zufallszahl = new Random();
        int rndnumber = zufallszahl.nextInt(6); // find item between 0 and 5

        String choosed = possibleKey.get(rndnumber);
        if(choosed == null) // check if id registered
            System.out.println("Can't found key for ID: "   rndnumber);
        if(!farbcode.contains(choosed)) // don't make switch
            farbcode.add(choosed); // add item
    }
}

public String stringo() {
    StringJoiner sj = new StringJoiner(", ");
    farbcode.forEach(sj::add); // add all element in string
    return "["   sj.toString()   "]"; // format string
}

CodePudding user response:

Following is some code that detects if a digit already exists in a (partial) array of digits.

The idea here is to pass in your index i from your original for loop. The loop in this method will then compare the candidate digit to the digits already in the array.

bool IsDuplicateDigit(int[] code, int digit, int i)
{
    // only one digit, nothing to do.
    if (i == 0) return false;

    for (int j = i - 1; j >= 0; j--)
      if (code[j] == digit)
        return true;

    return false;
}

As an aside, I think your code would be much simpler (and more reliable) if you were using an enumeration for the colors instead of magic strings.

CodePudding user response:

The following sample code includes a method that returns an array of random unique integers

import java.util.Arrays;
import java.util.HashSet;
import java.util.Random;

public class Example {

    // Returns an array of random unique integers 
    public static int[] getArrayOfRandomUniqueIntegers(int length, int bound) {
        HashSet<Integer> hashSet = new HashSet<Integer>();
        Random random = new Random();
        while (hashSet.size() < length) {
            int i = random.nextInt(bound);
            if (!hashSet.contains(i)) {
                hashSet.add(i);
            }
        }
        return hashSet.stream().mapToInt(Integer::intValue).toArray();
    }

    public static void main(String args[]) {
        int[] array = getArrayOfRandomUniqueIntegers(8, 75);
        System.out.println(Arrays.toString(array));
    }

}

Fabio

  •  Tags:  
  • java
  • Related