Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

264
Visualizações
Creating a 2D table of chars with unique characters in every line and column

I am trying to make a 2D table in which characters cannot repeat in column or line. I am trying to do at least 2 lines of arrays. I can do the first one, but I have a problem with other lines. On second line it throws an error - ArrayIndexOutOfBoundsException -11. Can someone help me?

Main class:

import java.util.ArrayList;
import java.util.Random;

public class Main {

char[][] table = new char[26][26];
Random r;

public static void main(String[] args) {
    new Main();
    new GlobalVars();
}

public Main() {
    r = new Random();
    createFirstLine();
    createOtherLine(1);
}

public void createFirstLine() {
    ArrayList<Integer> intLeft = GlobalVars.cIntToArrL();

    int counter = 0;
    for(int i = intLeft.size(); i > 0; i--) {
        int charPosChosen = r.nextInt(intLeft.size());
        int charPosGot = intLeft.get(charPosChosen);

        table[0][counter] = GlobalVars.getCharValue(charPosGot);
        counter ++;
        intLeft.remove(charPosChosen);
    }

    System.out.println(table[0]);
}

public void createOtherLine(int n) {
    ArrayList<Integer> intLeft = GlobalVars.cIntToArrL();
    for(int i = 0; i < 26; i++) {
        ArrayList<Integer> intLeftForCell = intLeft;
        for(int column = 0; column < n; column ++) {
            intLeftForCell.remove(
                    GlobalVars.getNumericValue(table[n][i])
                    );
        }
        int charPosChosen = r.nextInt(intLeftForCell.size());
        int charPosGot = intLeftForCell.get(charPosChosen);

        table[1][i] = GlobalVars.getCharValue(charPosGot);
        intLeft.remove((Integer)charPosGot);
    }
    System.out.println(table[1]);
}
}

The GlobalVars class :

import java.util.ArrayList;

public class GlobalVars {

public static String alphStr = "abcdefghijklmnopqrstuvwxyz";
public static char[] alphArr;
public static int[] intArr = new int[26];

public GlobalVars() {
    // Changing alphabet String to alphabet Array
    alphArr = alphStr.toCharArray();

    for(int i = 0; i < 26; i++) {
        intArr[i] = i;
    }
}

public static ArrayList<Integer> cIntToArrL() {
    ArrayList<Integer> list = new ArrayList<Integer>();
    for(int i = 0; i < 26; i++) {
        list.add(i);
    }
    return list;
}

public static int getNumericValue(char c) {
    return Character.getNumericValue(c) - 10;
}

public static char getCharValue(int i) {
    return Character.forDigit(i + 10, i + 11);
}

}
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

I got kind of lost in your code. If I understand what you want to accomplish correctly, you want to randomly generate 2D (square) array where in every row and column is every char exactly once(not duplicate and not missing from alphabet). Is that right? If yes here is my approach how to tackle this problem:

  1. Create pattern from alphabet (with that unique chars rule)
  2. Shuffle all rows (randomly, possibly using seed)
  3. Shuffle all columns (randomly, possibly using seed)

Step 1 - create table:

char alphabet[] = {'a','b','c', ...}; // Set of chars that will be used in table
char table[][] = new char[26][26]; // Size must be same as size of alphabet

private void prepareTable() {
    for (int x = 0; x < table.length; x++) {
        for (int y = 0; y < table[x].length; y++) {
            // Copy alphabet to row in table but offset it each row by 1
            table[x][y] = alphabet[(x + y) % alphabet.length];
        }
    }
    // Now table looks like this:
    // 'a' 'b' 'c'
    // 'b' 'c' 'a'
    // 'c' 'a' 'b
}

Step 2 - shuffle rows: For actual shuffling I am using Fisher-Yates Shuffle

Random r = new Random( /* seed */ );
void shuffleRows() {
    int items = table.length;

    while (items > 0) { // While there is something to shuffle
        int index = r.nextInt(items);

        // Simple swap
        char[] tmp = table[index];
        table[index] = table[items - 1];
        table[items - 1] = tmp;

        items --; // Move on to the next
    }
}

Step 3 - shuffle columns:

void shuffleColumns() {
    int items = table[0].length;

    while (items > 0) {
        int index = r.nextInt(items);

        // Swap chars in each row
        for (int i = 0; i < table.length; i++) {
            char tmp = table[i][index];
            table[i][index] = table[i][items - 1];
            table[i][items - 1] = tmp;
        }

        items --;
    }
}

And thats it. I hope it helps.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda