I am trying to write code for a poker game to delete cards at certain indices using an array.
The code i have so far is the following and is not working.
ncard is the number of cards currently in the hand. any help would be appreciated.
/**
* discard the indexed cards from the Hand.
* #param indices the indices of cards to delete.
* #return true if all Cards deleted, false if not.
*/
public boolean discard(int[] indices){
int i = 0;
while (i < indices.length){
if (indices[i] < 0 || indices[i] >= ncard)
{
return false;
}
for (int in = indices[i]; in < ncard; in++){
cards[in] = null;
ncard--;
}
i++;
}
return true;
}
It looks like you have the cards in a static array, and are setting the discarded indices to null. If you discard n cards and then try to discard a card at index 52-n, the method will return false and not discard any more cards.
You should probably use some dynamic data structure, such as a stack or a list, to store the cards. If you must use an array, here's how to go about fixing your problem:
You are not discarding cards at the indices, you are discarding every card between each given index and ncard (which doesn't represent the index of the last card since the nulls are at arbitrary locations). That for-loop should be replaced with
cards[indices[i]] = null
deletedCards++;//You should initialize this before the loop
After the loop, you should put this code:
Arrays.sort(cards, new Comparator<Card>(){
public int compare(Card a, Card b){
return Boolean.compare(a==null,b==null);
}
});
It sorts the nulls to the back of the array, and keeps the order otherwise same. Then you decrement ncards by deletedCards.
I highly reccomend for-loops in this case, since all this i++ stuff makes the code hard to understand
public boolean discard(int[] indices) {
// check if all indices consumed are valid
for(int index : indices) {
// i just use your validation, don't know, if this is correct though
if(index < 0 || index >= ncard)
return false;
}
// remove cards
for(int index : indices) {
cards[index] = null;
ncard--;
}
return true;
}
My guess is that the problem comes from the validation, but I would need more information to really solve that problem...
Maybe this would be a better validation sorting out indexOutOfBounds (negative and positive) and the attempt to discard more cards than ncard:
if(index < 0 || index > (cards.length -1) || indices.length > ncard)
return false;
EDIT: I assume that cards is an array that has the size of your card deck and all cards that the player does not have are null values?
Related
I am trying to write a program that will iterate through all possible permutations of a String array, and return a two dimensional array with all the permutations. Specifically, I am trying to use a String array of length 4 to return a 2D array with 24 rows and 4 columns.
I have only found ways to print the Strings iteratively but not use them in an array. I have also found recursive ways of doing it, but they do not work, as I am using this code with others, and the recursive function is much more difficult.
For what I want the code to do, I know the header should be:
public class Permutation
{
public String[][] arrayPermutation(String[] str)
{
//code to return 2D array
}
}
//I tried using a recursive method with heap's algorithm, but it is very //complex with its parameters.
I am very new to programming and any help would be greatly appreciated.
Your permutation-problem is basically just an index-permutation problem.
If you can order the numbers from 0 to n - 1 in all possible variations, you can use them as indexes of your input array, and simply copy the Strings. The following algorithm is not optimal, but it is graphic enough to explain and implement iteratively.
public static String[][] getAllPermutations(String[] str) {
LinkedList<Integer> current = new LinkedList<>();
LinkedList<Integer[]> permutations = new LinkedList<>();
int length = str.length;
current.add(-1);
while (!current.isEmpty()) {
// increment from the last position.
int position = Integer.MAX_VALUE;
position = getNextUnused(current, current.pop() + 1);
while (position >= length && !current.isEmpty()) {
position = getNextUnused(current, current.pop() + 1);
}
if (position < length) {
current.push(position);
} else {
break;
}
// fill with all available indexes.
while (current.size() < length) {
// find first unused index.
int unused = getNextUnused(current, 0);
current.push(unused);
}
// record result row.
permutations.add(current.toArray(new Integer[0]));
}
// select the right String, based on the index-permutation done before.
int numPermutations = permutations.size();
String[][] result = new String[numPermutations][length];
for (int i = 0; i < numPermutations; ++i) {
Integer[] indexes = permutations.get(i);
String[] row = new String[length];
for (int d = 0; d < length; ++d) {
row[d] = str[indexes[d]];
}
result[i] = row;
}
return result;
}
public static int getNextUnused(LinkedList<Integer> used, Integer current) {
int unused = current != null ? current : 0;
while (used.contains(unused)) {
++unused;
}
return unused;
}
The getAllPermutations-method is organized in an initialization part, a loop collecting all permutations (numeric), and finally a convertion of the found index-permutation into the String-permutations.
As the convertion from int to String is trivial, I'll just explain the collection part. The loop iterates as long, as the representation is not completely depleted, or terminated from within.
First, we increment the representation (current). For that, we take the last 'digit' and increment it to the next free value. Then we pop, if we are above length, and look at the next digit (and increment it). We continue this, until we hit a legal value (one below length).
After that, we fill the remainder of the digits with all still remaining digits. That done, we store the current representation to the list of arrays.
This algorithm is not optimal in terms of runtime! Heap is faster. But implementing Heap's iteratively requires a non-trivial stack which is tiresome to implement/explain.
I am working on a homework assignment involving array sorting methods, we are given the methods, and I'm having a little trouble understanding how this insertion sort method functions. More specifically, the role the two variables passed to the method play.
As I understand, the Key variable describes the index of the array that you'd like to place your inserted number in and the item is the number itself. Within main, I simply request the user to enter two numbers and pass them to the method, one for the key and the other for the item. Here is the given code for this segment:
public final void insertion(double Key, double Item)
{
if (arraySize == 0)
{
arr[0] = Item;
}
/* find the position for inserting the given item */
int position = 0;
while (position < arraySize & Key > arr[position])
{
position++;
}
for (int i = arraySize; i > position; i--)
{
arr[i] = arr[i - 1];
}
arr[position] = Item;
arraySize = arraySize + 1;
}
However, when I pass doubles to the method as I have explained, I get an error stating that index (array length) is out of bounds for length (array length).
Clearly, I am misunderstanding the purpose or structure of this method and I can't figure it out. Any help would be appreciated. I know this is a very simple problem.
EDIT: Here is how I initialize my array, the given code is in a separate class from my main method:
public static double[] arr;
private int arraySize;
public sortedArrayAccess(int scale)
{
arr = new double[scale];
arraySize = arr.length;
}
Within my main method:
System.out.print("Enter an array size: ");
int d = sc.nextInt();
sortedArrayAccess test = new sortedArrayAccess(d);
for(int i=0;i<test.arr.length;i++)
{
System.out.print("Enter a number for index " + i + ": ");
double c = sc.nextDouble();
test.arr[i] = c;
}
How do you initialize ‘arr’ variable?
Anyway the problem is that when you create the array - you should specify initial capacity. And every time when you add the element into array you are about to increase it.
When you try to ask for for a cell of array indexed i if array capacity is less then I - you’ll be given the arrayOutOfBoundsException.
Your problem is here:
if (arraySize == 0)
{
arr[0] = Item;
}
You are assigning the Item to the first element in the array. But the array size must be empty as stated by the if (arraySize == 0)
So you have two options:
adjust the size of the array (by creating a new one)
or return an error
if (arraySize == 0)
{
arr[0] = Item;
}
As you know, in computer science, indices starts from 0. Which means arr[0] here is the first slot of your array. if arraySize is 0, there is no such index arr[0]. Your code tries to insert the Item to zero sized array. This causes Index out of bound exception.
By the way, If it is a sorting algorithm for the values, "Key" variable is not required. You can delete it. But if it is required, you should sort the elements by their key values.
For example if we have:
element 1 -> key= 101 , value= 6
element 2 -> key= 201 , value= 9
element 3 -> key= 301 , value= 2
you should not sort them as element 3 < element 1 < element 2
you should sort them like: element 1 < element 2 < element 3 in order to their key values.
In other words, if you want to sort them by their values, passing key values as a parameter is meaningless.
I want to check if all "zero's" in my array have been selected/clicked on.
I've created two separate arrays:
the original array where you can't see the elements (need to be clicked on first) this is an int[][] array.
The clicked on array that shows the board with the elements that have been clicked on. This is a boolean[][] array.
I have tried various methods, the one shown below is the closest I've gotten.
But Java shows this as an error: "operator <= is undefined for argument type int, boolean". Gives error if I use == too.
private boolean win(int row, int col) {
if(mazegame.board[row][col] = mazegame.clickedBoard[row][col]){
return true;
}
}
Have tried casting...but this doesn't seem like a good idea.
This code will iterate through the elements in your board.
If the element is a 0, it will check if the element at the same position in the clicked board is true (it has been clicked), if it is not, the loop will be interrupted and false will be returned.
If all zeroes are true in the corresponding clicked board, the loops will run through completely and the method will return true.
Code:
private boolean isSolved() {
for(int i = 0; i < mazegame.board.length; i++) {
for(int j = 0; j < mazegame.board[i].length; j++) {
if(mazegame.board[i][j] == 0 && !mazegame.clickedBoard[i][j]) {
return false;
}
}
}
return true;
}
The purpose of this method is to return the position (subscript index) of the largest element in the array (not its value, but its position). If the same maximum value appears more than once in the array, then it should return the position of the first or earliest on. If the array has no elements it should just return -1.
The solution:
public static int maxPos(int[] arr) {
int pos = 0;
if(arr.length > 0 ) {
for(int i = 0; i < arr.length; i++) {
if(arr[i] > arr[pos]) {
pos = i;
} else {
pos = - 1;
}
}
return pos;
}
I understand setting up a dummy variable "pos" to represent the index position of the maximum value of the array. And having the check point with if(arr.length > 0) then proceed. And the for-loop to sift through the entire array checking one-by-one which index has the greatest number value and after each iteration either re-assigning dummy variable or carrying onward.
The part where I get lost is when using things within the array [ ]'s, it throws me off. I don't think anywhere else in java there is such notation. For example with arrayList wouldn't that just be nameOfAL . get();
So the equivalent of that for an array is using the []'s?
I am a bit confused by arr[i] > arr[pos].
Is this to say when we are at the i'th index in the for-loop, we can then use arr[] and put something within that box, and when we do it outputs the value of that index. So anytime we put something within that array box it's always going to output an index position? is that the purpose of putting things inside the [] box? it will output the value of whatever is put inside it's brackets.
the next part that confuses me is why pos = i?
I understand if the if-statement fails then the else is - 1. but why return pos; after each iteration?
Thank you
Your posted code contains a few bugs, you should start with pos at -1 (instead of resetting it when a given value isn't greater then the current max). Also, I would check for null. Then you can start your loop with the second element. Something like,
public static int maxPos(int[] arr) {
int pos = -1; // <-- indicates no elements.
if (arr != null && arr.length > 0) {
pos = 0; // <-- there is at least one element.
for (int i = 1; i < arr.length; i++) {
if (arr[i] > arr[pos]) {
pos = i; // <-- update the max position
}
}
}
return pos;
}
First, so what you're putting in the square braces are variables named i and pos that hold the values of the numerical positions you're accessing in the array. It's like the get method of the arrayList class like that.
It's not returning pos until it finishes the for loop. In general it's returning pos because that's the index of the largest number, which is the point of the program. I think you're just missing a bracket somewhere, you have 5 {'s and 4 }'s.
I am making a method to return an array of integers of the total of all the cards and the total number of jokers and aces in the users 'cards' array. It uses a for loop and finds the value of the card in an array containing the cards in their order. If the card's value is greater than 10, the value 10 should be added to the total.
Here is the index array:
static String[] cardOrder = {"A","2","3","4","5","6","7","8","9","10","J","Q","K"};
And here is the method:
public static int[] total(ArrayList<String> cards){
int total = 0;
int aces = 0;
int jokers = 0;
for(int i = 0; i < cards.size(); i++){
System.out.println(i);
System.out.println(cards.size());
System.out.println("One of your cards is " + cards.get(i));
if(cards.get(i).equals("A")){
aces = aces + 1;
}else if(cards.get(i).equals("Joker")){
jokers = jokers + 1;
}else{
if(Arrays.asList(cardOrder).indexOf(cards.get(i)) <= 10){
total = total + Arrays.asList(cardOrder).indexOf(cards.get(i)) + 1;
}else{
total = total + 10;
}
}
System.out.println(total);
i++;
}
int[] intArray = {total, aces, jokers};
return intArray;
}
However, strange things appear to be happening. I get out of bounds exceptions when I change the greater than sign in the for loop to greater than or equal to, but when I do not do this, only the first value of the cards array is counted.
Sorry that this looks like a 'fix my code' type of thread. I think it will be useful to the Java beginner community in terms of enhancing their understanding of the use of arrays and arraylists within Java methods.
You have i++ in your for loop AND at the end of your for loop. Remove the bottom one
The important thing that you need to remember about java Arrays is that, their indexing starts from '0' but not from '1'. When you create an array of size '2', to access the first array element you need to use index '0' (something like arr[0]) and to access the second array element you need to use the index '1'.
This understanding would be good enough to overcome the out of bounds exceptions. Just go through the code carefully and see when ever you are accessing the array element, you are not using the index which is less than '0' (or) greater than 'size-1' (i.e if you create an array of size 'N', the index can not be less than '0' and can not be greater than N-1).