impact_Sv
impact_Sv

Reputation: 49

How to map this character array to integers?

I have a character Array which i have to map these characters into integers. It works like this. - The final character in the array has to be 0, followed by the next distinct character = 1 and so on.

I already have the characters in the array i just cant seem to Map them correctly

This is what i have tried

public void generate(String first, String second) {
    letters = new char[(first+second).length()];

    for(int i = 0; i < letters.length; i ++) { //Getting the string as characters into array
        letters = (first+second).toCharArray();
    }

    for(int j = 0; j < letters.length; j++) {
        for(int m = letters.length; m > 0; m--) {
            letters[m] = (char) j;
        }
    }

}

which gives me this error

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7
at PuzzleGenerator.generate(PuzzleGenerator.java:21)
at test.main(test.java:7)

Upvotes: 0

Views: 88

Answers (2)

Sergey Tselovalnikov
Sergey Tselovalnikov

Reputation: 6036

You answer is unclear, but maybe this is what you want:

  public static int[] generate(String first, String second) {
    return (first + second)
      .chars()
      .flatMap(i -> IntStream.range(0, i)
                      .boxed()
                      .sorted(Collections.reverseOrder())
                      .mapToInt(Integer::valueOf))
      .toArray();
  }

Upvotes: 1

ydemartino
ydemartino

Reputation: 242

    for(int m = letters.length; m > 0; m--) {
        letters[m] = (char) j;
    }

This loop starts at letters.length this gives you the exception. You should write it like this:

    for(int m = letters.length; m-- > 0; ) {
        letters[m] = (char) j;
    }

I do not really understand what you are trying to do but the first loop should be replaced with just

letters = (first+second).toCharArray();

Doing it once is enough.

Upvotes: 0

Related Questions