trying to make a Sudoku game, but stuck at checking (and fixing) duplicates in rows and columns
if (buttons.getSource().equals(newGame)) {
String diffic = JOptionPane.showInputDialog("Choose difficulty, ranging from 1-3 where 1 is easy");
int difficulty = Integer.parseInt(diffic);
ArrayList<Integer> allnumbers = new ArrayList<Integer>(Arrays.asList(1,2,3,4,5,6,7,8,9));
if (difficulty == 1) {
for (int i = 0; i < 81; i++) {
fields.get(i).setEditable(true);
fields.get(i).setText("");
double d = Math.random();
if (d < 0.6) {
random = new Random();
Integer randomInt = allnumbers.get(random.nextInt(allnumbers.size()));
fields.get(i).setText(randomInt + "");
fields.get(i).setEditable(false);
}
}
}
As of now, it prints and stuff works, but it prints duplicated numbers.
My pseudo-way right now:
1. Find a way to print the arraylist in random order for each row. The random part is done, but it still prints duplicated numbers (im thinking to print numbers 1-9 in random order 9 times, 1 time for each row)
2. Find a way to check columns afterwards. No clue how yet, taking one problem at a time
Anyone here been around the same problems, got some tips?
Thank you :)
Create an ArrayList with the nine number.
Use Collections.shuffle(...) to shuffle the numbers in random order.
Related
I got the 2d array to print but with all zero's and the only random number comes up on the bottom right corner
How do I get the code to print random numbers in all the elements of the 2d array?
Here is my code:
public static void main(String[] args) {
int columns = 8;
int rows = 4;
int rLow = 2;
int rHigh = 9;
printRandos(columns, rows, rLow, rHigh);
}
public static void printRandos(int clmn, int rws, int rlow, int rhigh) {
Random rando = new Random();
int randoNum = rlow + rando.nextInt(rhigh);
int[][] randoArray = new int[rws][clmn];
for (int i = 0; i < rws; i++) {
for (int k = 0; k < clmn; k++) {
randoArray[rws - 1][clmn - 1] = randoNum;
System.out.print(randoArray[i][k] + " ");
}
System.out.print("\n");
}
}
for (int i = 0; i < rws; i++)
{
for (int k = 0; k < clmn; k++)
{
int randoNum = rlow + rando.nextInt(rhigh);
randoArray[i][k] = randoNum;
System.out.print(randoArray[i][k]+" ");
}
System.out.print("\n");
}
your mistake inside the inner for loop of the printRandos method. Firstly your random number is outside the loop so your array elements were receiving the same number all the time. Another mistake is that you are assigning the value to the same array element all the time i.e rws-1 and clmn-1 .
inside your inner loop replace it with this:
int randoNum = rlow + rando.nextInt(rhigh);
randoArray[i][k] = randoNum;
System.out.print(randoArray[i][k]+" ");
Your bug is in this line:
randoArray[rws-1][clmn-1] = randoNum;
This stores your random number into randoArray[rws-1][clmn-1] each time, which as you noticed, is the bottom right corner. rws is always 4, and clmn is always 8. So you store the same number there 32 times, which gives the same result as storing it only once.
In the following line you are correctly printing the number from the current array location:
System.out.print(randoArray[i][k]+" ");
An int array comes initialized with all zeroes, and since except for the last corner you have not filled anything into your array, 0 is printed.
Also if you want different random numbers in all the cells, you would need to call rando.nextInt() inside your innermost for loop.
Unless you need this 2-D array for some purpose (which doesn't show from the minimal example code that you have posted), you do not need it for printing a matrix of random numbers, i.e., you may just print the numbers form within your loop without putting them into the array first.
Finally if rhigh should be the highest possible random number in the array, you should use rando.nextInt(rhigh - rlow + 1). With rlow equal to 2 and rhigh equal to 9 this will give numbers in the range from 0 inclusive to 9 - 2 + 1 = 8 exclusive, which means that after adding to rlow = 2 you will get a number in the range from 2 to 10 exclusive, in other words, to 9 inclusive.
I am on purpose leaving to yourself to fix your code based on my comments. I believe your learning will benefit more from working it out yourself.
Your assign the array value outside the array length
int[][] randoArray = new int[rws][clmn];
randoArray[rws][clmn] = randoNum;
Here randoArray[rws] is out of bounds.
I am developing a snakes and ladders game. I'm having trouble to include a dice roll that determines which player goes first before the game starts.
Any help would be much appreciated.
This is what I have attempted:
Random rand = new Random();
int result = rand.nextInt(3); // a random number, either 0 or 1, see http://docs.oracle.com/javase/6/docs/api/java/util/Random.html#nextInt(int)
if (result == 0) {
Player 1 goes first
}
else {
Player 2 goes first
}
You are off by 1 when you generate a random number.
result = rand.nextInt(2) //will return 0 or 1
You can create an ArrayList to hold all the rolls, then create a temporary arraylist to hold the rolls. Sort the temp list to get the max value, and then find the index of the max value in the original list.
If you also store your players in an array or list you can use the index you just found to determine which player had the max value
for (int i = 0; i < n; i++)
roll.add(rand.nextInt(n+1));// this will add n random integers to the arraylist
ArrayList<Integer> tmp = roll;
tmp.sort(null);
int index = roll.indexOf(tmp.get(n));
if you are going with max of 4 players then n value would be 2<=n<=4.
List<Integer> decideDiceRollingOrder(int n)
{
ArrayList<Integer> playingOrder=null;
if(n<=1 || n>4)
{
System.out.println("Please check the players count");
playingOrder=Collection.emptyList(); // for not throwing the null pointer Exception
}
else
{
Random rand = new Random();
playingOrder=new ArrayList<Integer>();
for(i=1;i<=n;i++)
{
playingOrder(i,rand.nextInt(n);// n number of players
}
//Sort the ArrayList for deciding the order
}
return playingOrder//sorted list;
}//method
I hope this gives you the major idea on the solution.
I would do it this way:
import java.lang.Math;
int diceRoll = (int) ((6*Math.random())+1);
if(diceRoll <= 3){
player1 goes first;
}
else{
player2 goes first;
}
Something along those lines. The line: 6*Math.random() will give you a number 0-5 and the +1 makes it a dice roll of 1-6 if that is what you're looking for.
Edit to add: forgot to cast it to an int for you. Also, if you want the number to be from 0 to n, just change the number in front of Math.random() to n+1 (example: you want 0 to 100... 101*Math.random). Casting to an int isn't necessary if you give the if/else a range instead of an equality...
I need to complete this task. But I am not entirely sure how to get the range into the array. I think I am supposed to use a loop somehow but I do not get it to work.
This is what I have so far:
import java.util.*;
public class A2_1
{
static Scanner x = new Scanner(System.in);
public static void main(String[] args)
{
int [] myArray = new int [1000000];
int x;
for ( x = 0; x <= 100; x++)
{
myArray [x] = x+1;
}
System.out.println(myArray);
}
}
This is the task:
"Create a program that generates 1,000,000 integer random values in the range of [1,..,100] and for any given x (between 1 and 100) taken from the user input computes "(๐๐๐ก๐๐ ๐๐ข๐๐๐๐ ๐๐ ๐๐๐๐๐๐๐ก๐ ๐๐๐ ๐ ๐กโ๐๐ ๐๐ ๐๐๐ข๐๐ ๐ก๐ ๐ฅ)/1,000,000".
This value must be comparable to the CDF of a uniform distribution U[1,100] at point x."
Im not going to give you the answer since this sounds like homework but I will help you break it down into manageable chunks.
First, generate 1000000 random numbers between 1 and 100. You were on the right track and combine it with Dawnkeepers hint. int[] randoms = new int[1000000]; is an int array with a size of 1000000. Now iterate over each index and assign it a random number(see above). Now you have an array with a million random numbers. Generating a million randoms can be a lengthy procedure depending on you machine, so yea.
Next, use the Scanner class to get the users input.(pro tip: dont use the same variable name for your scanner as your variable in the for loop lol). Now do an if check to make sure they enter a number between 1 and 100. if(val > 0 && val <= 100). If this passes, move on, else quit or prompt for user to give a new input. Using the scanner is pretty trivial so I wont go into this.
Finally, iterate through your list of randoms and keep a counter of how many numbers less then or equal to x.
int counter = 0;
for(int i = 0; i < randoms.length; i++) {
//if randoms[i] is less then or equal x, counter++
}
Take that counter and do your math, int final_answer = counter/randoms.length;
That's all that is to it. There are more efficient ways of doing this but I tried to make it simple to follow. If I misread the question, sorry.
I don't really understand what's happening, if someone could explain this to me that would be great.
So, here's my code:
public static ArrayList<Integer> numbers = new ArrayList<Integer>();
public static void main(String[] args){
for(int i =0; i != 90; i++){
System.out.println(generate());
}
}
public static int generate(){
Random random = new Random();
int rand = random.nextInt(89)+1;
while(numbers.contains(rand)){ //<---Here seems to be my problem
rand = random.nextInt(89)+1;
System.out.println("Number: " + rand + " already exists!");
}
numbers.add(rand);
return rand;
}
I am writing a program that generates a random number from 0-90, each of which are different to the last. Unfortunately, it seems that the while loop only returns true.
You're picking from 89 random numbers (1-89 inclusive) and trying to find a unique number each time... but you're calling that 90 times. What do you expect the last iteration to do? (To put it another way - you're trying to squeeze 90 numbers into 89 slots. That's not going to work.) On the last iteration, all the possible values will already be in the list, so the condition of your while loop will always be met, whatever value is randomly chosen on each iteration.
If you wanted the numbers to be between 1 and 90 inclusive, you should be using random.nextInt(90) + 1. The argument to nextInt is the maximum number exclusive to generate - so if you call random.nextInt(3) for example, it will generate 0, 1 or 2.
(There are better ways of doing this, by the way - such as populating the list and then using Collections.shuffle - but I've concentrated on explaining the behaviour of your current code.)
You can do it easily by using collections shuffle
public static ArrayList<Integer> numbers = new ArrayList<Integer>();
for(int i =1; i <= 90; i++){
number.add(i)
}
Collections.shuffle(numbers); // at this point the number are shuffled.
Read about shuffle.
I'm a newbie in java. I was going through some tutorials and came across this code I was not able to understand the code. Please explain what it means.
class Randoms
{
public static void main(String[] args)
{
Random rand = new Random();
int freq[] = new int[7];
for(int roll = 1; roll < 10; roll++)
{
(++freq[1 + rand.nextInt(6)]);
}
...
Line by line:
Random rand = new Random(); create new instance of the Random object, this is responsible for the creation of random numbers.
int[] freq = new int[7]; create a new int array that can store 7 elements, with indices from 0...6. It is worth noting that in Java, the ints stored in the array are initialized to 0. (This is not true for all languages, an example being C, as in C the int arrays initially store memory junk data, and must be explicitly initialized to zero).
for(int roll = 1; roll < 10; roll++) this rolls 9 times (because 1...9, but it's better practice to go from 0)
(++freq[1 + rand.nextInt(6)]); this line is something that you shouldn't ever do in this sort of fashion, because it's a monstrosity as you can see.
Do something like this:
for(int roll = 0; roll < 9; roll++)
{
int randomNumber = rand.nextInt(6); //number between 0...5
int index = 1 + randomNumber; //number between 1...6
freq[index]++; //increment the number specified by the index by 1
//nearly equivalent to freq[index] += 1;
}
So basically it randomizes the number of 9 dice throws, and stores the dice throw count (or so it calls it, frequency) in the array.
Thus, it's simulating 9 dice throws (numbers from 1...6), and each time it "rolls" a particular number, it increases the number stored in the array at that specific location.
So in the end, if you say:
for(int i = 1; i <= 6; i++)
{
System.out.println("Thrown " + freq[i] + " times of number " + i);
}
Then it will be clearly visible what's happened.
(++freq[1 + rand.nextInt(6)]); // this line of code.
The above line of code is pre-incrementing the value of freq[] array at the specified position,i.e., 1+rand.nextInt(6) --- referred value is ++freq[some-position to be evaluated] which we will evaluate below.
This rand.nextInt(6) will generate an integer number lesser than 6 and greater than 0,as it is a pre-defined method of Random Class ,randomly.We can't predict it.
And,then say number generated is 4. SO, 1+rand.nextInt(6)=5.
Hence,your code would simplify to (++freq[1 + rand.nextInt(6)]) OR `(++freq[5]).
So,simplification of this code will be equivalent to a number which equals 1 more than 6th element of array freq[].
// as freq[5] is the 6th element of the array freq[].
Also,there are some other points which SIR David Wallace suggested me to include which I would like to explain a bit more.It goes below :-
++a here ++ is called pre-increment operator and it increases the value of a by 1. There also exists an altered reverse version of it.
a++ here this ++ is called post-increment operator and it also increases the value of a by 1.But,WAIT,you might have thought that there aren't differences,but there are.
For the differences potion,I'd like to suggest to have a reading of What is the difference between pre-increment and post-increment in the cycle (for/while)?, though it is questioned in sense of C++,the same is in Java too!
// Create a new Random Object, this helps you generate random numbers
Random rand = new Random();
// create a integer array with 7 integers
int freq[] = new int[7];
// loop 9 times
for(int roll = 1; roll < 10; roll++)
{
// rand.nextInt(6) generates a number between 0 and 5 (<6). add one to it
// ++ adds one to the integer in the array that is at the index of 1-6.
(++freq[1 + rand.nextInt(6)]);
}
Some strange things about this code:
Roll loop starts at 1 then goes to 10 so at first glance it would seem to loop 10 times but actually runs 9 times.
The ++ inside the loop would generally be located on the right and could lead to some confusion among newer programmers.
freq[1 + rand.nextInt(6)] causes freq[0] to never be used.
At first a new object of the Random-Class and an array with 7 elements are created. Each element of the Array has the value 0. Inside the for-loop you randomly pick element 2 to 7 of the Array and increase its current value by 1. This is done 9 times.
Your code will never pick the first element of the Array which has the index 0.
I would rewrite the code to make it more clear:
Random rand = new Random();
int freq[] = new int[6];
int randomIndex = 0;
for(int roll = 0; roll < 9; ++roll)
{
randomIndex = rand.nextInt(6);
freq[randomIndex] = freq[randomIndex] + 1;
}
This code has not been tested, but it should basicly do the same.