Shuffling elements in a Typed Array - java

I have a typed array with 4 elements and I'm trying to shuffle them. How would I go about it? I'm really close but I think the only problem is I don't know the syntax with dealing with Typed Array.
Here is the code so far:
int correctIndex=0;
for(int i=0; i<4; i++){
int randomShuffle = random.nextInt(4);
if(i==correctIndex){//keep track of the correct answer (which always starts at 0)
correctIndex=randomShuffle;
}
else if(randomShuffle==correctIndex){
correctIndex=i;
}
Drawable hold= questionAnswers.getDrawable(i);
questionAnswers.getDrawable(i)=questionAnswers.getDrawable(randomShuffle);
questionAnswers.getDrawable(randomShuffle)=hold;
}
The problem is only with the last two lines. That obviously doesn't work. Is there a
typedArray.setIndex(index,value)
kind of call?

Related

Where is the Data Changing? - Permutations in Java

So for this extra credit problem in my calculus class, my other nerdy classmates and I decided that we would build a program to brute force a solution. One of these steps involves permutations. Through this algorithm, I managed to get it to work (I think):
public void genPermutations(int[] list, int k){
System.out.println("List: " + Arrays.toString(list));
System.out.println("----------------------");
if(k > list.length){
System.out.println("Not enough elements!");
return;
}
int[] counts = new int[list.length];
for(int i = 0; i < counts.length; i++){
counts[i] = 1;
}
int[] data = new int[k];
permutationHelper(list, counts, data, 0, k);
}
public void permutationHelper(int[] list, int[] counts, int[] data, int index, int k){
if(index == k){
//System.out.println(Arrays.toString(data));
permutations.add(data);
}else{
for(int i = 0; i < list.length; i++){
if(counts[i] == 0){
continue;
}
data[index] = list[i];
counts[i]--;
permutationHelper(list, counts, data, index + 1, k);
counts[i]++;
}
}
}
I have an ArrayList that stores all of the possible permutations (as integer arrays) that can be made from k elements of the list that I pass into the function. The problem is that if I print all of these permutations outside of the function, say after I call the genPermutations function, every permutation now is the same. But, when I print out the data where the comment is in the permutationHelper function, it correctly lists every possible permutation; I'm just unable to access them within the program later. My question is why are the values changing when I exit the function? Any help would be greatly appreciated.
Here are some pictures:
What is printed where the comment is.
What is printed later in the program.
The code used to print everything outside of the function is:
for(int i = 0; i < permutations.size(); i++){
System.out.println(Arrays.toString(permutations.get(i)));
}
I don't really know if that's necessary to know, but I just thought I'd include it just in case. Thanks in advance.
You're constantly modifying the same array object. Instead of adding different arrays to your list, you're in fact adding a reference to the same array over and over again.
To fix, instead of adding the data array to your list, you would have to add a copy of it, e.g. using Arrays.copyOf():
permutations.add(Arrays.copyOf(data, data.length));
Here the problem is that you are modifying the array after adding it to the list, you are modifying the same object again and again in different iterations. You were getting [3,2,1] in the list is because that was the outcome from last iteration. So as a fix you can use the following code. What it does is it will create a copy of data array and add that to the list.
int[] temp = Arrays.copyOf(data, data.length);
permutations.add(temp);
OR you can use clone() from array as follows.
int[] temp = data.clone();
permutations.add(temp);

I have the method below that gets a two-dimensional array and a value. The method check if the value be in the array or not

I have the method below that gets a two-dimensional array and a value. The method check if the value be in the array or not.
I don't understand why do I need the line of code that I highlighted in bold (if (m[i][m[i].length-1] <= val).
It Looks that the code works without this line as well... Why do I still need this line, can someone explain me please? thanks
public static boolean findValWhat (int[][] m, int val)
{
for (int i = 0; i < m.length; i++) {
**if (m[i][m[i].length-1] <= val){**
if (binarySearch(m[i], val) == val){
return true;
}
}
}
return false;
}
The code will still work without it but is makeing it run faster.
Lets say you have this sorted 2d array:
[[1,2,3],[4,5,6],[7,8,9]]
Then you can see that if you are searching for 8 you don't need to do binary search for the first line because 3 is smaller then 8 and he is the biggest number in there.
You can even make this code batter by doing binary search instead of the loop.

Putting unique random number in array

i want to try to put a unique random number from shuffled list to array but keep failing.
im using this answer with little modification.
this is my method
ArrayList<Integer> list = new ArrayList<>();
for(int i=0;i<10;i++) {
list.add(i);}
Collections.shuffle(list);
for(int x=0;x<3;x++){
RNGee=RNG.nextInt(9);
RN[x]=list.get(RNGee);
if(RN[x]==QNum){
x=0;
}
}
When i print out the RN array, some of it have a chance to get same value.
Is there something wrong with my code ?
Please explain it to me.
Thank you.
Your easiest way of doing this would just be to use list.get(0), list.get(1) and list.get(2). The list is shuffled, so the three elements at the head of the list will be random and different.
for(int x=0;x<3;x++){
RN[x]=list.get(x);
if(RN[x]==QNum) { //but this is very unclear
x=0;
}
}
There's part of your code that you haven't explained, though, which is the bit that sets the loop variable back to 0 if the random number you choose is equal to QNum. It's not at all clear what that's there for, but I suspect you will need to remove QNum from the list beforehand, so that it never turns up:
for(int i=0;i<10;i++) {
if (i!=QNum) {
list.add(i);
}
}
Despite the fact that your solution, as chiastic-security said, is unneccessary your mistake is that your list still contains 10 elements and that you are randomly picking from.
To be able to use your solution you would need to remove the element that you did select from the list and generate your random number in the range of 0-list.size-1.
ArrayList<Integer> list = new ArrayList<>();
for(int i=0;i<10;i++) {
list.add(i);}
Collections.shuffle(list);
for(int x=0;x<3;x++){
RNGee=RNG.nextInt(list.size()); // You collection gets smaller after each itteration so be sure to not run into a OutOfBound
RN[x]=list.get(RNGee);
list.remove(RNGee); // Remove the duplicate to be sure that the element doesn´t get picked twice
if(RN[x]==QNum){
x=0;
}
}
Edit: also make sure to follow the java convention, which says that methods and variables should start lowercase and classes uppercase. That will make you code more readable to us and yourself in the end.

How to check all array indexes in one while loop at the same time Java

I have an array with 5 size , and I want to assign value from random function if any index doesn't have it.
while(positionXtoStart==array1[0] || positionXtoStart==array1[1] ||
positionXtoStart==array1[2] || positionXtoStart==array1[3] ||
positionXtoStart==array1[4])
{
positionXtoStart = (rand1.nextInt(400) + 1)+30;
}
this solution is ok for small size of array but if i have array with size of 1000, I cant enter 1000 conditions in the while loop.
I tried For-loop with if-else condition in it but the
problem is, I want to check all array indexes at the same time.
Please try to understand what i am asking. I want to check all array index values at the same time (in one shot).
in For-loop, we can check only one value at a time.
If I understand correctly, you just need to loop through the array, checking each value.
for (int i = 0; i < array1.length; i++)
{
if (array1[i] == positionXtoStart)
{
positionXtoStart = (rand1.nextInt(400) + 1)+30;
break; // exit the loop
}
}
are you looking for something like this?
for(int i=0; i<array1.length; i++)
if(array[i] == whatever)
{
// do stuff
}
unfortunately, what you're asking is not possible. Even in your code:
while(positionXtoStart==array1[0] || positionXtoStart==array1[1] ||
positionXtoStart==array1[2] || positionXtoStart==array1[3] ||
positionXtoStart==array1[4])
the computer is checking one condition at a time. It's not doing all the conditions at once, like you may think it is. The code you posted is equivalent to the code #Supericy and #Samiam posted.
Unless there's a reason the forloops doesn't work for your case, I would say go with the answers that are posted here.
If you have to check each entry you have to go trough the whole array. An unordered array in not really suitable for searching trough it. Maybe you should think of changing your data structure into something like a BST so you have a guarantied O(logn) search.
To compare all elements in an unordered array you need linear time.

Reassigning values in an array

Im trying to write a game of Yahtzee as part of an online course (not actually enrolled, just playing along at home) I have hit a bit of a wall manipulating values in the array that keeps track of the dice values. This is the section of code that seems to be causing trouble;
for (int i=0; i<N_DICE; i++){ //goes through each die.
if (display.isDieSelected(i) == false){ //checks if player wants to reroll the die.
dice [i] = dice[i];//problem line-should reassign the same value back to the die.
}
else {
dice [i] = rgen.nextInt(1, 6);
}
}
Assigning a new random number works, and if I roll all 5 dice every turn its happy.
I've changed the offending line to dice[i]=1 for testing purposes and while it takes some fun out of the game, the program works, so I'm thinking its something simple I'm doing wrong with that line.
I've tried assigning dice[i] to a temp variable (inside and out of the if loop) and then assigning temp back to dice[i].
I've tried just leaving the if loop empty.
I've tried setting it up as a multi dimesional array with a seperate array for each roll.
I've tried adding a cast (didnt think that'd do it but I was out of ideas).
All of these have had the same results.
Only been programming a few weeks, I'd be very gratefull if someone could tell me what I'm doing wrong.
Not sure what you're trying to do with that line:
dice[i] = dice[i];
Since it's a NOP, why not just omit it?
I don't really see the purpose of:
dice[i] = dice[i]
Can't you just use something like:
for (int i=0; i<N_DICE; i++){
if (display.isDieSelected(i)){
dice [i] = rgen.nextInt(1, 6);
}
}
The code looks completely correct, although I would write it a bit more compactly:
for (int i = 0; i < N_DICE; i++) {
if (display.isDieSelected(i)) {
dice[i] = rgen.nextInt(1, 6);
}
}
So your problem probably lies somewhere else. Is dice a new array, or is it always the same in the program? If it is a field in some class, it should have the final modifier, like this:
public class YahtzeeState {
private final int[] dice = new int[N_DICE];
}
This declaration makes sure that the dice array cannot be replaced later with a completely different array. The values in the array can still be changed though.
How is the dice-array initialized? I don't know your entire code but I could imagine that it doesn't work because the dice-array gets it values only in this loop?
Maybe you should try something like:
for (int i=0; i<N_DICE; i++){
if (display.isDieSelected(i) || dice[i] == null)
dice [i] = rgen.nextInt(1, 6);
}

Categories