Error when adding value in array, repeated values

Asked

Viewed 219 times

6

I have two arrays, A and B.

I created 3 functions in which I take a value from the beginning of array A and array B, remove the values, compare the values and if the value of A is greater than that of B, I add the 2 values at the end of array A, or else I add it to the list B. The problem is that one of the functions is giving error and I can not find the error. When I print the array, the arrays that had unique values have repeated values.Someone can help me find and fix the error?

This function takes a card from the beginning of the array. IF it is -1, it is because the index is empty, and then should take the next available card.

  int getValorInicio (int[] arrCards, int topPonteiro) { 
    int card=0;

    if (arrCards[topPonteiro]!=-1) {
       card=arrCards[topPonteiro];
    }else{
       for(int i=0; i<arrCards.length; i++){
          if (arrCards[i]!=-1){
             card=arrCards[i];
             break;
          }
       }
     }
     return card;
}

This function removes the card, and indicates the next empty tile.:

int removeCard(int[] arrCards, int topPonteiro) { 
  if(arrCards[topPonteiro] != -1){
    arrCards[topPonteiro]=-1; 
    topPonteiro=(topPonteiro+1)%arrCards.length;    
  } 
  return topPonteiro;
}

And finally this function adds and returns the next free position, but it seems that it adds several times the same value, when it should not.

    int addFinalArr(int [] arrCards, int ultimoPonteiro, int card) {
       int nextPosition=0;
       if (arrCards[ultimoPonteiro]==-1 && ultimoPonteiro!=ultimoPonteiro+1) {
         arrCards[ultimoPonteiro]=card; 
       }
       else{
          for(int i=0; i<arrCards.length; i++){   
             if (arrCards[i]==-1 && arrCards[i]!=arrCards[0]){
                nextPosition=i;
                break;
             }
             nextPosition=i;
          }
      }   
   return nextPosition;  
}
  • You remove read values from arrays before making your comparisons?

  • Yes. I take the values, compare and then add to the list that had the highest value letter.

1 answer

1


I understood your problem but looking at your code things got a little confusing, what you need and understand the concepts of queue, stack and data structure list and implement them (give a studied and very useful).

Remove from the first and insert into the last element is the concept of QUEUE(First Login Last Exit), however your QUEUE is customized because it takes an element from the first of each array and inserts it into the last of the array1 or array2 as per its rule.

In Java you will have to do the methods by returning the new arrays since this language does not work with pointers (you cannot access an array from within an invoked method), summarizing would look like this.

 public static void main(String[] args) {
    //o zero(0) representa casas vazias repare que o 
    //cartasA tem o primeiro elemento maior (5).
    int[] cartasA = {5,3,4,5,10,2,2,5,6,5,5,4,6,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
    int[] cartasB = {3,3,4,5,10,2,2,5,6,5,5,4,6,0,0,0,0,0,0,0,0,0,0,0,0,0,0};

    //imprime array cartasA antes de processar
    for (int i : cartasA) {
        System.out.print(i+",");
    }

    //armazena os dois primeiros elementos para adicionar mais tarde
    int tmpA = cartasA[0];
    int tmpB = cartasB[0];

    //remove o primeiro elemento
    cartasA = removerPrimeiro(cartasA);
    cartasB = removerPrimeiro(cartasB);

    //identifica qual array deve inserir os elementos no fim
    if(tmpA > tmpB){
        cartasA = inserirFim(cartasA, tmpA, tmpB);
    }else{
        cartasB = inserirFim(cartasB, tmpB, tmpA);
    }

    //imprime array cartasA depois de processar        
    System.out.println("");
    for (int i : cartasA) {
        System.out.print(i+",");
    }

}

static int[] removerPrimeiro(int[] cartas){
    //se o array estiver vazio retorna ele mesmo
    if(cartas[0] == 0)
       return cartas;

    //percorre o array deslocando os elementos para esquerda
    for (int i = 0; i < cartas.length - 1; i++) {
        cartas[i] = cartas[i+1];
    }
    //remove o ultimo elemento que o for não pode alcançar
    cartas[cartas.length - 1] = 0;
    return cartas;//retorna o novo array sem o primeiro valor
}

static int[] inserirFim(int[] cartas, int a, int b){
    //percorre o array em busca do ultimo elemento
    for (int i = 0; i < cartas.length - 1; i++) {
        if(cartas[i] == 0){
            //insere os dois valores nas duas ultimas posições
            cartas[i] = a;
            cartas[i + 1] = b;
            break;
        }
    }
    return cartas;//retorna o novo array
}

Output of card array:

before executing

[5,3,4,5,10,2,2,5,6,5,5,4,6,0,0,0,0,0,0,0,0,0,0,0,0,0,0] (Note the 5)

after executing

[3,4,5,10,2,5,6,5,5,4,6,5,3,0,0,0,0,0,0,0,0,0,0,0,0,0] (Note that 5 left and entered 5 at the end along with 3 of the cartasB array)

I hope it helped.

UPDATE

Try this remove

/**
 * neste caso os arrays cartasA e cartasB devem estar declarados static
 * para o metodo conseguir acessar nele, e fazer os metodos separados
 * um para cada baralho
 * @param cartas
 * @return 
 */
static int removeCartasA(){
    int resp = -1;
    for (int i = 0; i < cartasA.length; i++) {
        //procura valor -1
        if(cartasA[i] != -1){
            resp = cartasA[i];//armazena valor para retornar
            cartasA[i] = -1;//remove substituindo com -1
            break;//sai do loop
        }
    }
    return resp;//retorna o valor removido
}

static int removeCartasB(){
    int resp = -1;
    for (int i = 0; i < cartasB.length; i++) {
        //procura valor -1
        if(cartasB[i] != -1){
            resp = cartasB[i];//armazena valor para retornar
            cartasB[i] = -1;//remove substituindo com -1
            break;//sai do loop
        }
    }
    return resp;//retorna o valor removido
}
  • You have dimmed the size of the array, and I do not do that. I put -1 where there is no card. Then at the end I compare.

  • The array width and constant (which should be the total size of your deck ok?), where there is no card I put zero(0) you can replace with -1, so that your deck works correctly when removing a top card, you must shift the values from right to left ( position value [1] goes to [0], position value [2] goes to [1], ...) so you remove the first letter, and to add letter at the end you must locate where this empty and add the two cards, this is the concept of working with FILA.

  • Look at the example I made for you. element [0] =5 (Top) came out and elements 5 (first of the deckA) and 3 (first of the deckBs) came out at the end of the deckA. where you have Zeros(0) consider empty in your case you can replace with -1 without problems and only change in the code where it is 0 by -1.

  • Your array (deck) should keep the elements always grouped on the left, and the empty ones always on the right, so your application will work correctly.

  • The remove function only removes if the letter is not -1. It removes the letter and returns the next position that is not -1.

  • I did an update see if it fits now

  • I used a print to get the values and the remove function picks up -1 if cartsA have values and cartsB have -1. How do I stop when I get to the end of the array to return and check if there are more values to remove?

  • Thanks @Luciano, I managed to fix my code. Your tips helped me a lot.

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.