How to randomly choose a number of rectangles to change colour - java

i want my program to randomly change the colour of around 50% of the rectangles within my grid, this is done using jframe.
i have an array with the length of the board and i want 50% of these numbers to be blue.
FALSE = grey
TRUE = blue
Note: this is within paint method using Graphics g
grid = new boolean[board.length];
Random r = new Random();
for(int i = 1;i <grid.length;i++){
int rand = r.nextInt(i);
}

Take the number of squares on the board and multiply by the target percent.
Assume 8x8 board, so 64 squares * .50 = 32.
I would create a List of all the rectangles.
Begin a loop. Generate a random number from 0 to the size of the rectangle list. Remove that position and make it blue. End loop if all 32 rectangles are identified.
//Pseudo code
java.util.Random random = new Random();
List<Integer> rectangles = new ArrayList<Integer>();
for(int i = 0; i < grid.length; i++)
{
rectangles.add(i);
}
//Fill the rectangles
for(int i = 0; i < 32; i++)
{
int position = random.nextInt(rectangles.size());
Integer toConvert = rectangles.remove(position);
//perform operation to make toConvert blue.
grid[toConvert] = true;
}

Related

How do I populate a three-dimensional array with randomly placed predefined integers?

I am new to programming and I have an assignment in Java that asks the user to navigate a 10X10X10 cubic maze, where there must be 500 monsters randomly generated, 499 open cells, and 1 treasure chest. The treasure chest must also be randomly generated, but it cannot occur within the same spot as a monster. The program I have to write asks for user input to check a cell in the array to see if its the treasure chest. If the cell is empty, I have to give a hint as to where the treasure chest is (how many cells away and if you're in the same row, column, or page). The user gets three tries to find the treasure chest. At the end of the three tries, or if they hit a monster, the user loses and is told in what cell the chest was placed. For the purposes of the assignment, an empty cell = 0, the only cell with the treasure chest = 1, and the monster cell = 2.
I am having trouble populating the cells with only 500 monsters and one chest. My code below populates all the cells with a random amount of 0's, 1's and 2's. I need to limit the 2's to five-hundred instances, the 1's to one instance (and check beforehand to make sure a monster isn't in the cell), and keep the rest 0. I also need to make sure I'm not populating the same cell with more than one monster. This is as far as I've got:
import java.util.Random;
public class FindTheCheese
{
public static void main(String args[ ])
{
int size = 10;
int[][][] maze = new int[10][10][10];
Random gen = new Random();
for(int i = 0; i < 10; i++){
for(int j = 0; j < 10; j++) {
for(int k = 0; k <10; k++) {
maze[i][j][k] = gen.nextInt(3);
System.out.print(maze[i][j][k] + ", "); // this won't be part of the final code, just used to check if I'm populating correctly
}
System.out.println();
}
}
}//closing main
}//closing class FindTheCheese
Create a one-dimensional array of length 1000 to hold all the values to go into the maze. Set 500 elements to 2 (the monsters), one element to 1 (the treasure chest) and 499 elements to 0 (the free cells).
Shuffle the array using Collections.shuffle(Arrays.asList(yourOneDimArray)).
Now fill the values from the shuffled array into your 3-dimensional matrix in turn. Underway when you encounter the chest, record its coordinates in the maze. You will need this for reporting back to the user.
When you first create the maze, all cells will be zero by default. Next, add the single treasure to a random spot. Finally, pick a random cell and see if it's empty. If it isn't, pick another random cell. If it is, place a monster. Repeat that 500 times with a for loop:
public static void main(String[] args) {
int size = 10;
int[][][] maze = new int[10][10][10]; // every cell is zero by default!
Random gen = new Random();
// place the treasure
maze[gen.nextInt(size)][gen.nextInt(size)][gen.nextInt(size)] = 1;
// place 500 monsters
for(int monsters = 1; monsters <= 500; monsters++) {
int i, j, k;
do {
i = gen.nextInt(size);
j = gen.nextInt(size);
k = gen.nextInt(size);
} while (maze[i][j][k] != 0);
maze[i][j][k] = 2;
}
// display the results
for(int i = 0; i < size; i++){
for(int j = 0; j < size; j++) {
for(int k = 0; k < size; k++) {
System.out.print(maze[i][j][k] + " ");
}
System.out.println();
}
}
}

Simulated Annealing for Sudoku Solving

I'm trying to solve a 9x9 sudoku puzzle using Simulated Annealing, but my implementation doesn't seem to be working correctly. It does not even get closer to a lower-cost solution but instead keeps circling around results that cost between 60 and 80.
My cost function returns the sum of three things: Number of repeating digits in each row, column and block (3x3).
And the successor (neighbour) function i implemented changes two randomly selected digits from the 9x9 grid with random values.
And here is my SA function that doesn't work as expected:
public static void simulatedAnnealing() {
Sudoku neighbour; // candidate successor object
final Double temperature = 2.0; // initial temperature
final Double coolingFactor = 0.999; // cooling constant
final int maxIterations = 1000; // number of iterations
for(Double t = temperature; t>1; t*=coolingFactor) {
for(int i = 0; i < maxIterations; i++) {
neighbour = sudoku.generateSuccessor(); // set random neighbour
int delta = neighbour.cost() - sudoku.cost(); // calculate delta
if (delta <= 0) {
sudoku = neighbour; // always accept good step.
} else {
if (Math.exp(-delta / temperature) > Math.random()) { // Simulated annealing
sudoku = neighbour;
}
}
}
System.out.println(sudoku.cost());
if(sudoku.cost() == 0) { break; } // if puzzle is solved
} }
Function for generating successors:
public Sudoku generateSuccessor() {
int[][] newGrid = new int[9][9];
for(int o = 0; o < 9; o ++) { // cloning current grid array
for(int g = 0; g < 9; g ++) {
newGrid[o][g] = grid[o][g];
}
}
Sudoku rndm = new Sudoku(newGrid); // random Sudoku object.
for (int i = 0; i < 2; i++) { // will randomize 2 cells in 9x9 grid.
int rndmCell = rndmValue(); // random digit for randomizing.
int randomRow = rndm(); // random row that will be randomized
int randomCol = rndm(); // random column that will be randomized
// prevent randomizing given cells in sudoku (in problem definition)
boolean shouldContinue = false;
for (Coordinate c : SudokuSolver.concreteCoordinates) {
if (c.row == randomRow && c.col == randomCol) {
shouldContinue = true;
break;
}
}
if (shouldContinue) {
i--;
continue;
}
// prevention end.
rndm.grid[randomRow][randomCol] = rndmCell;
}
return rndm;
}
Cost function:
public int cost() {
if(hasZeros()) { // if grid is not totally filled with numbers don't calculate its cost.
return -1;
}
int cost = 0;
for(int i = 0; i< 9; i++) { // find total collusions in rows&columns.
cost += findNumberOfCollusions(grid[i]); // find collustions at row 'i'.
cost += findNumberOfCollusions(getColumn(grid,i)); // find collustions at column 'i'.
}
for(int r = 0; r < 9; r += 3) { //find total colusions in blocks (3x3).
for(int c = 0; c < 9; c += 3) {
int[] block = new int[9];
int ctr = 0;
for (int i = r; i < r + 3; i++) {
for (int y = c; y < c+ 3; y++) {
block[ctr] = grid[i][y];
ctr++;
}
}
cost += findNumberOfCollusions(block);
}
}
return cost;
}
When i run the program the output is costs between 60 and 80. After that the temperature goes below the limit and the program outputs a solution that costs around that interval. Can anyone tell me what am i doing wrong? Thanks in advance.
I also had a similar problem to the one you describe, my fitness remained stuck (actually though, my problem was with not copying lists in Python). I can't really assure why your code gets stuck, but if I had to guess: the neighbor generation (int rndmCell = rndmValue(); int randomRow = rndm(); int randomCol = rndm();) may be actually doing more harm than good. Imagine that you have a nearly complete sudoku, but out of the blue two of the correct cells that you had now change their value to a complete opposite one, which is not only wrong on the cell itself but also on the row, column and/or 3x3 square. I'm no mathematician, but logic tells me that the more fitting the sudoku is (i.e. the closer its fitness is to 0), the more chances there are to mess up the sudoku by randomly changing cells. This approach may get you stuck on a local minimum easily.
A more "informed" solution for this problem would be to keep one of the three basic restrictions of the sudoku puzzle fixed by, for instance, generating rows that are permutations of the values [1..9], swapping two cells of a random row (thus still fulfilling the restriction), and calculating the fitness only on the columns and on the 3x3 squares. This choice of neighbor generation is usually more effective. If you are interested, this idea comes from the paper Metaheuristics can solve Sudoku puzzles. I can say that this idea helped me a lot and now the algorithm completes sudokus that I provide :)

2D array that player can move around

I am confused on how to print the location of the player in this array and have it update every time an input is plugged in for the direction it is moving? Currently I only get the - symbol in a 10 by 10 pattern but would like (0,0) to be an X where the player starts.
private final static int SIZEX = 10; // Board size
private final static int SIZEY = 10; // Board size
int[][] gameboard = new int[SIZEX][SIZEY];
for(int i=0; i<gameboard.length; i++)
{
for(int j=0; j<gameboard.length; j++)
{
System.out.print("-");
}
System.out.println("");
}
Use an if statement (or ternary operator) in your inner loop to print X if i and j match the x and y coordinate of the player
You could add a KeyListener to your games Component and set the x and y if the input matches the one required to move the player arround and print the position once the key is released.
To really answer your question we would need some sort of fields you have that hold the current players position

Java - Two-Dimensional Arrays - Plotting Points

I have an assignment for a JAVA class I am taking. We are discussing two-dimensional arrays, however on this particular assignment, I can not figure out how to return back specific points and set those points with a specific value. Here is the assignment:
Write a method called create2DArray that will fill, create, and return
a 10 x 10 2d array with random numbers in the range of 1 to 100. Write
a method called print2DArray that will print a 10 x 10 2D array in row
column fashion. Write a method called createCoords that will search
the 2D array looking for any value that is evenly divisible by 3.
Once you have found a number you should log the row, column location.
This means when your method finishes it should produce a list of
coordinates that I can use to plot my graph. This method must also
return the number of coordinates that are divisible by 3 so that I
know how many points there are to plot. I am not particular as to how
the coordinates are returned back as long as I get a list of the row,
column locations. So, I will leave it to you to work out a mechanism
for returning the values. To test that you have logged the
coordinates create another function called fillLocations that will
fill the locations in the array you have logged with
-1. So, your program should flow in this order
create2DArray
print2DArray
createCoords
fillLocations
print2DArray
I understand and have completed create2DArray and print2DArray, but I can not figure out createCoords and fillLocations. Here is what I have so far, but it does not work and there are errors present:
public int createCoords(int row1, int col1){
int[][] coords = new int[row1][col1];
int[][] count = new int[0][0];
int co = 0;
for(int row = 0; row < 10; row++)
{
for(int col = 0; col < 10; col++)
{
if(coords[row][col] % 3 == 0)
co++;
return count[row][col];
}
}
return co;}
public int fillLocations(int[][] count){
int x = 0;
int y = 0;
for(int row = 0; row < 10; row++)
{
for(int col = 0; col < 10; col++)
{
if(count[row][col] % 3 == 0)
x = row;
y = col;
break;
}
}
return (x, y);}
As a programmer you'll nearly always need to research for doing different things. This research will be easier when you divide your problem to smaller problems.
For example you need to generate random numbers? So search on google that and you'll find this: How do I generate random integers within a specific range in Java?.
You need to create and return a 2D array? Google and see Syntax for creating a two-dimensional array
And with your art, put the pieces of the puzzle together in a way that gives your desired result.
public int[][] create2DArray() {
int[][] newArray = new int[10][10];
Random random = new Random();
int range = 100;
for(int i = 0; i < 10; i++)
{
for(int j = 0;j<arr[0].length;j++)
{
newArray[i][j]= (random.nextInt(range) + 1);
}
}
return newArray;
}
This method, creates and returns a 10*10 2D array filled with random generated numbers between 1-100. I'm sure you can write the rest of your program and enjoy from it by yourself.

2d array squares initialization and selection

For code optimization purposes, I want to create a 2d array that contains 40 equal squares (10x10px). Each square represents 1\40 of the displayed window (400x400px).
I populate the 2d array with the standard double for-loop methodology.
int col = 40;
int row = 40;
int boxPosition = 0; //Position of the box (coordinates)
Integer[][] boxes = new Integer[40][40];
for (int i = 0; i < col; i++) {
for (int j = 0; j < row; j++) {
boxes[i][j] = boxPosition;
boxPosition += 10; //Creates a 10px box.
}
boxPosition = 0; //Resets box size for next column
}
There are several circles in this program. We have a ship(circle) that fires missiles(circles) toward enemies(circles).
I want to run collision detection ONLY when there is a bullet + an enemy in one of the squares. This will greatly optimize the code.
The question is... how do I create these squares off of a 2d array? How do I select each square? How do I test if the missiles and the enemies are inside the same square?
Code examples are GREATLY appreicated.
Thanks.
I'm not sure what you're doing with the 2D array or why it contains Integers or why it contains an increasing size in each column, but the general way to do grid-based collision is to have a 2D array of GameObjects. A GameObject in your case could be a Ship, a Missile, or an Enemy.
When one of your GameObjects wants to move, you simply check the 2D array of GameObjects to see what is already in the square you want to move to. If it's empty, you can do the move. If it's not empty, you've got a collision.

Categories