Home > OS >  Is it possible to reduce the number of assignment operations in array exchange?
Is it possible to reduce the number of assignment operations in array exchange?

Time:10-22

This method has a very simple behavior, as you can see. However, I was wondering if there's a way to simplify this code even further, since it's only doing assignment operations in order to exchange values from the array.

private Board exch(Board a, int i, int j) { // exchange two elements in the array
    int temp = a.board[i];
    a.board[j] = a.board[i];
    a.board[i] = temp;
    return a;
}

CodePudding user response:

In this particular case that you are using ints, there is a way to do this without using a temp variable, by using math expressions, but I wouldn't recommend it just because it makes the code less readable.

private Board exch(Board a, int i, int j) {
    a.board[i] = a.board[i]   a.board[j];
    a.board[j] = a.board[i] - a.board[j];
    a.board[i] = a.board[i] - a.board[j];
    return a;
}

Anyway, doing swaps the way you did is pretty common, so I am not sure why are you expecting to simplify even further

CodePudding user response:

Algorithmically there is no better way, but if you are just trying to save lines of coding you can always do this:

import java.util.Collections

//define your array

Collections.swap(arr, i, j);

after this arr will have the values swapped

CodePudding user response:

// exchange two elements in the array
private Board exch(Board a, int i, int j) { 
    
    a.board[i]=a.board[i] a.board[j];
    a.board[j]=a.board[i]-a.board[j];
    a.board[i]=a.board[i]-a.board[j];
    return a;

}
  • Related