I have to simulate a contagious disease spread where the world is of NxN countries. Initially there are going to be P people in the world and then we have to assign the people uniformly at random to each country.
The problem I am having is that how do I go about assigning a number of people to each country?
If I have an array such as
String[][] world = new String[2][2];
I have 4 countries now and I can show them as a grid using for loops.
Now world[0][0] which is a country should point to a list which has people in it.
I tried list within a list
ArrayList<ArrayList<human>> world2 = new ArrayList<ArrayList<human>>();
ArrayList<human> country1 = new ArrayList<human>();
for(int i=0; i<5; i++){
human h = new human();
country1.add(i,h);
}
world2.add(country1);
ArrayList<human> country2 = new ArrayList<human>();
human h = new human();
country2.add(h);
world2.add(country2);
for (int i=0; i<world2.size(); i++){
System.out.println(world2.get(i));
}
But how do i print it in a grid format ?
EDIT1:
String[][] world = new String[2][2];
for (int row = 0; row < world.length; row++) {
System.out.print("|");
for (int col = 0; col < world.length; col++) {
System.out.print(world[row][col] + "| ");
}
System.out.println();
}
OUTPUT:
|null| null|
|null| null|
This will loop through a 3D arraylist of Integers and print the contents of all the Integer per [row][col] of the world grid. All you have to do is supplement your Human object into wherever I have Integer.
public ArrayList<ArrayList<ArrayList<Integer>>> create3D()
{
ArrayList<ArrayList<ArrayList<Integer>>> world = new ArrayList<ArrayList<ArrayList<Integer>>>();
for (int row = 0; row < 3; row++)
{
world.add(new ArrayList<ArrayList<Integer>>());
for (int col = 0; col < 3; col++)
{
world.get(row).add(new ArrayList<Integer>());
Random rand = new Random();
int randomNum = rand.nextInt((20 - 1) + 1) + 1;
for(int humanNumber = 0; humanNumber < randomNum; humanNumber++)
world.get(row).get(col).add(humanNumber);
}
System.out.println();
}
return world;
}
public void printHumanGrid(ArrayList<ArrayList<ArrayList<Integer>>> world)
{
for (int row = 0; row < world.size(); row++)
{
for (int col = 0; col < world.get(row).size(); col++)
{
System.out.print("|");
for(int humanNumber = 0; humanNumber < world.get(row).get(col).size(); humanNumber++)
System.out.print(world.get(row).get(col).get(humanNumber) + ",");
System.out.print("|");
}
System.out.println();
}
}
So I ahve two functions, one to fill a 3D arraylist and the other to print it out. Running the following
printHumanGrid(create3D());
Outputs:
|0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,||0,1,2,3,4,5,6,7,8,9,||0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,|
|0,1,2,3,4,5,6,7,8,9,||0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,||0,1,2,3,|
|0,1,2,3,4,5,6,7,8,9,||0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,||0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,|
Each line is a row in the grid. You can now add onto it, perhaps adding functionality to format it and whatnot. Good luck!
Related
I need help completing one task from Java book that I read. I need to create a 3-dimentional array of int that will be able to store 30 values.
It's described as cuboid containing cubes. Each cube is supposed to be a cell and they should store ints from 30 to 59. How should it look like? I try to draw it but it's pretty hard for me. Here is what I've tried.
public class cw124{
public static void main (String[]args){
int tab[][][]=new int[31][30][30];
int wypelniacz=30;
for (int i=0; i<tab.length; i++){
for (int j=0; j<tab[j].length; j++){
wypelniacz=30;
for (int k=0; k<tab[k].length; k++){
tab[i][j][k]=wypelniacz++;
}
}
}
for (int i=0; i<tab.length; i++) {
for (int j=0; j<tab[j].length; j++){
for (int k=0; k<tab[k].length; k++){
wypelniacz=30;
tab[i][j][k]=wypelniacz++;
System.out.println("Row "+i+" Cell 1 "+j+" Cell 2 "+k+" "+tab[i][j][k]);
}
}
}
}
}
Your 3D array currently has 31*30*30 = 27,900 cells. If you need a 3D array with 30 cells, you can do this:
int tab[][][]=new int[5][3][2];
This will give you a 3D array with 5*3*2 = 30 cells.
You can imagine each value in square brackets to be the length of one side of the cuboid.
The next step would be:
int counter = 30;
for(int i = 0; i < tab.length; i++)
{
for(int j = 0; j < tab[0].length; j++)
{
for(int k = 0; k < tab[0][0].length; k++)
{
tab[i][j][k] = counter;
counter++;
}
}
}
This will populate all the cells with numbers from 30 to 59.
I think the following code may help you understand the task.
You have to think of the 3 dimensions as a cube, the cube contains grids, each grid has rows which then have multiple columns)
(imagine a Rubik's cube, which has 3 layers=grids, each grid then has 3 rows and each of those rows again has 3 columns)
final int gridCount = 5;
final int rowCount = 5;
final int colsPerRow = 15;
final int[][][] cube = new int[gridCount][rowCount][colsPerRow];
for (final int[][] grid : cube) {
for (int col = 0; col < grid.length; col++) { //just to show the two different versions of 'for'
final int[] row = grid[col];
row[col] = 42+ col; //set it to whatever number
}
}
I have this array here that takes strings values this is my Puzzle Board View,
Right now everything works but the array is hard coded and i need the strings to be generated randomly from 0-4.
I have tried to get a random char and put it is as a string but this didn't work. Any tips would be nice.
Random rand = new Random();
char c = (char)(rand.nextInt(5) + '0');
StringBuilder sb = new StringBuilder();
sb.append(c);
String[] debug_board_state = new String[7];
debug_board_state[0] = "0,3,0,0,3,0,2";
debug_board_state[1] = "1,0,2,0,0,1,2";
debug_board_state[2] = "0,2,0,0,0,0,0";
debug_board_state[3] = "0,0,3,0,3,0,4";
debug_board_state[4] = "2,0,0,0,0,1,0";
debug_board_state[5] = "0,1,0,0,1,0,2";
debug_board_state[6] = "2,0,3,0,0,2,0";
UPDATE.
Thanks to user Answer i was able to get the random matrix, although i ran into another problem, I need do more stuff to the matrix so i don't want to print it out. here is the code
static private final int WIDTH_EASY = 7;
protected void InitializeEasy() {
Random rand = new Random();
String[][] debug_board_state = new String[7][7];
for (int row = 0; row < debug_board_state.length; row++) {
for (int column = 0; column < debug_board_state[row].length; column++) {
debug_board_state[row][column] = String.valueOf(rand.nextInt(5));
}
}
for (int row = 0; row < debug_board_state.length; row++) {
for (int column = 0; column < debug_board_state[row].length; column++) {
System.out.print(debug_board_state[row][column] + " ");
}
};
for (int i = 0; i < WIDTH_EASY; ++i) {
StringTokenizer tokenizer = new StringTokenizer (debug_board_state[i][i], ",");
int column = 0;
while(tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();
getCurrentState().board_elements[i][column] = new BoardElement();
getCurrentState().board_elements[i][column].max_connecting_bridges = Integer.parseInt(token);
getCurrentState().board_elements[i][column].row = i;
getCurrentState().board_elements[i][column].col = column;
if (getCurrentState().board_elements[i][column].max_connecting_bridges > 0) {
getCurrentState().board_elements[i][column].is_island = true;
}
++column;
}
}
}
The string Tokenizer works with 1d array but not with 2d, i need something that will do the same thing as StringTokenizer and apply it to the matrix. I am getting the following error
java.lang.NullPointerException: Attempt to read from field Island_and_Bridges.Hashi.BoardElement[][] Island_and_Bridges.Hashi.BoardState$State.board_elements on a null object reference
Although I think int[][] is a better idea, here is the String[][] solution. You can use String.valueOf(rand.nextInt(5)) to generate element in the matrix:
import java.util.Random;
public class Main {
public static void main(String[] args) {
Random rand = new Random();
String[][] matrix = new String[7][7];
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length; column++) {
matrix[row][column] = String.valueOf(rand.nextInt(5));
}
}
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length; column++) {
System.out.print(matrix[row][column] + " ");
}
System.out.println();
}
}
}
Update:
for (int row = 0; row < WIDTH_EASY; ++row) {
for (int column = 0; column < WIDTH_EASY; ++column) {
getCurrentState().board_elements[row][column] = new BoardElement();
getCurrentState().board_elements[row][column].max_connecting_bridges = Integer.parseInt(debug_board_state[row][column]);
getCurrentState().board_elements[row][column].row = row;
getCurrentState().board_elements[row][column].col = column;
if (getCurrentState().board_elements[row][column].max_connecting_bridges > 0) {
getCurrentState().board_elements[row][column].is_island = true;
}
}
}
Something like this?
Pseudo-code:
String[][] debug_board_state = new String[7][7];
for (int x = 0; x < debug_board_state.size(); x++) {
for (int y = 0; y < debug_board_state[x].size(); y++) {
debug_board_state[x][y] = new_random_character();
}
}
0-4 lies from 49 to 52 on the ASCII scale:
Random rand = new Random();
char c = (char)(rand.nextInt(4)+49);
StringBuilder sb = new StringBuilder();
sb.append(c+'0');
Maybe, you want something like this:
public void initBoard() {
Random random = new Random();
String[][] board = new String[7][7];
for (int i=0; i < board.size(); i++) {
for (int j=0; j < board[].size(); j++) {
board[i][j] = String.valueOf(random.nextInt() % 5);
}
}
}
It will initialize your board with random number of String.
I have this static method created for a Bingo game.
public static void bingoCard(){
int [][]card = new int [5][5];
ArrayList<Integer> alreadyUsed = new ArrayList<Integer>();
boolean valid = false;
// First row
for(int row = 0; row < card.length; row++){
int tmp = 0;
while(!valid){
tmp = (int)(Math.random()*15)+1;
if(!alreadyUsed.contains(tmp)){
valid = true;
alreadyUsed.add(tmp);
}
}
card[row][0] = tmp;
valid = false;
}
// Second row
for(int row = 0; row < card.length; row++){
int tmp = 0;
while(!valid){
tmp = (int)(Math.random()*15)+1;
if(!alreadyUsed.contains(tmp)){
valid = true;
alreadyUsed.add(tmp);
}
}
card[row][1] = tmp;
valid = false;
}
// Third row
for(int row = 0; row < card.length; row++){
int tmp = 0;
while(!valid){
tmp = (int)(Math.random()*15)+1;
if(!alreadyUsed.contains(tmp)){
valid = true;
alreadyUsed.add(tmp);
}
}
card[row][2] = tmp;
valid = false;
}
card[2][2] = 0; // The 3rd matrix to the left and right is a 0.
// Fourth row
for(int row = 0; row < card.length; row++){
int tmp = 0;
while(!valid){
tmp = (int)(Math.random()*15)+1;
if(!alreadyUsed.contains(tmp)){
valid = true;
alreadyUsed.add(tmp);
}
}
card[row][3] = tmp;
valid = false;
}
// Fifth row
for(int row = 0; row < card.length; row++){
int tmp = 0;
while(!valid){
tmp = (int)(Math.random()*15)+1;
if(!alreadyUsed.contains(tmp)){
valid = true;
alreadyUsed.add(tmp);
}
}
card[row][4] = tmp;
valid = false;
}
// Creates an array to make title
String title[] = {"B","I","N","G","O"};
for(int i = 0; i < title.length;i++){
System.out.print(title[i] + "\t");
}
System.out.println();
for(int row = 0; row < card.length; row++){
for(int col = 0; col < card[row].length; col++){
System.out.print(card[row][col] + "\t");
}
System.out.println();
}
}
In the output, this piece of code outputs to this console bingo card: http://puu.sh/487mz/939c8d7a59.png
My main issue is that repeating digits. I am interested in knowing how to get rid of the repeating digits within the 5x5 arrays. Thank you!
Second EDIT: I am also interested in having the game play by itself. Meaning, it would pull out random numbers and correspond to whether or not the digits are on the board. If the condition is met for a BINGO condition, then do something. Does anyone have suggestions in regards to this?
When I've written BINGO boards, I have made an ArrayList containing all possible unique values, then made a call to Collections.shuffle( mylist) which will randomly re-order the values. Then you can iterate over the list to populate your matrix.
Just make sure you re-shuffle for each new board you make
One solution would be to have another data structure that holds all random numbers that have been generated and added into the 2D array that represents the card.
After creating a random number you could check to see if that number already exists in the data structure. If it does then generate a different number. If it doesn't then add it to the card and the data structure.
An ArrayList would be good to use here since it has a nice contains method already written for you. Here's an example.
import java.util.ArrayList;
int [][]card = new int [5][5];
ArrayList<Integer> alreadyUsed = new ArrayList<Integer>();
boolean valid = false;
for(int row = 0; row < card.length; row++){
int tmp = 0;
while(!valid){
tmp = (int)(Math.random()*15)+1;
if(!alreadyUsed.contains(tmp)){
valid = true;
alreadyUsed.add(tmp);
}
}
card[row][0]= tmp;
valid = false;
}
Also in all of your nested for loops you never use the variable col. You could simply get rid of the inner for loop in each of these nested loops.
for(int row=0; row < card.length; row++){
for(int col=0; col < card[row].length; col++){
card[row][0]=(int)(Math.random()*15)+1;
}
}
Could be changed to
for(int row=0; row < card.length; row++){
card[row][0]=(int)(Math.random()*15)+1;
}
Also card[2][2]=0; only needs to happen once, here you're setting it multiple times. This could be changed from
for(int row=0;row<card.length;row++){
for(int col=0;col<card[row].length;col++){
card[row][2]=(int)(Math.random()*15)+31;
card[2][2]=0;
}
}
To
for(int row=0;row<card.length;row++){
card[row][2]=(int)(Math.random()*15)+31;
}
card[2][2]=0;
Don't use the random function like that - instead, fill up an array or ArrayList with all of the potential random numbers. Then randomly remove numbers from that - that will ensure that you cannot get repeated numbers, as only one of each exists.
Fill an ArrayList with numbers from 1 to N, then use a java.util.Random to pick/remove numbers (shuffle is not necessary):
ArrayList<Integer> card = new ArrayList<Integer>(N);
for (int i = 0; i < N; i++)
card.add(i + 1);
Random random = Random();
int pick = card.remove(random.nextInt(card.size()));
You could easily wrap this into a class to organize things.
Here's the way I would have implemented it.
int[][] board = new int[5][5];
ArrayList<Integer> list = new ArrayList<Integer>();
int number = 0;
int index = 0;
int increment = 1;
int col = 0;
//Run a loop until you're at your last column.
while (col < board.length) {
//Ensure uniqueness of your numbers
while (list.size() < 5) {
number = (int) (Math.random() * 15) + increment;
if (!list.contains(number))
list.add(number);
}
//Add elements to the array.
for (int i : list)
board[index++][col] = i;
//Set values for the next iteration.
index = 0;
increment += 15;
list.clear();
col++;
}
board[2][2] = 0;
//Print the board.
System.out.println("B\tI\tN\tG\tO\n");
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
System.out.print(board[i][j] + "\t");
System.out.println("");
}
Results:
B I N G O
9 29 34 59 62
8 23 44 52 64
7 16 0 53 63
1 19 33 46 71
15 17 41 58 61
Create a class which represents a bingo table. Populate an array with numbers from 0 to 99. When generating a new table, shuffle this array and pull numbers from it in order.
public class BingoBoard{
Integer[] randomNumbers;
int[][] grid = new int[5][5];
public BingoBoard(){
randomNumbers = new Integer[100];
for(int i=0;i<randomNumbers.length;i++)
randomNumbers[i] = i;
populateCard();
}
public void set(int x, int y, int value){
grid[x][y] = value;
}
public void populateCard(){
//randomize the numbers you'll pull from.
//Array.asList will be backed by randomNumbers, so this works.
Collections.shuffle(Arrays.asList(randomNumbers));
for(int x=0;x<5;x++){
for(int y=0;y<5;y++){
int num = randomNumbers[x+y*5];
set(x,y,num);
}
}
}
}
This is a very efficient way to populate your grid with random values.
you could keep a list of visited random numbers generated and check it before adding this number to the game like this
boolean[] visited = new boolean[100];
for(int i = 0; i < 100; i ++) visited[i] = false;
and inside each loop use this
for(int row=0; row < card.length; row++){
int num = (int)(Math.random()*15)+1;
if visited[num]{
row --;
continue;
}
visited[num] = true;
card[row][0] = num;
}
Its simple, just use this.
int element = 5;
List<Integer> numbers = new ArrayList<Integer>(element);
for (int i = 1; i <= element * element; i++)
numbers.add(i);
Collections.shuffle(numbers);
int[][] numArr = new int[element][element];
for (int i = 0, counter = 0; i < element; i++)
for (int j = 0; j < element; j++, counter++)
numArr[i][j] = numbers.get(counter);
for (int i = 0; i < numArr.length; i++) {
for (int j = 0; j < numArr[i].length; j++) {
System.out.printf("%-5d", numArr[i][j]);
}
System.out.println();
}
I'm struggling to finish a java exercise, it involves using 2d arrays to dynamically create and display a table based on a command line parameter.
Example:
java table 5
+-+-+-+-+-+
|1|2|3|4|5|
+-+-+-+-+-+
|2|3|4|5|1|
+-+-+-+-+-+
|3|4|5|1|2|
+-+-+-+-+-+
|4|5|1|2|3|
+-+-+-+-+-+
|5|1|2|3|4|
+-+-+-+-+-+
What i have done so far:
public static void main(String[] args) {
int num = Integer.parseInt(args[0]);
String[][] table = new String[num*2+1][num];
int[] numbers = new int[num];
int temp = 0;
for(int i=0; i<numbers.length; i++)
numbers[i] = i+1;
// wrong
for(int i=0; i<table.length; i++){
for(int j=0; j<num;j++){
if(i%2!=0){
temp=numbers[0];
for(int k=1; k<numbers.length; k++){
numbers[k-1]=numbers[k];
}
numbers[numbers.length-1]=temp;
for(int l=0; l<numbers.length; l++){
table[i][j] = "|"+numbers[l];
}
}
else
table[i][j] = "+-";
}
}
for(int i=0; i<table.length; i++){
for(int j=0; j<num; j++)
System.out.print(table[i][j]);
if(i%2==0)
System.out.print("+");
else
System.out.print("|");
System.out.println();}
}
This doesn't work, since it prints 1|2|3|4 in every row, which isn't what I need. I found the issue, and it's because the first for loop changes the array order more times than needed and basically it returns as it was at the beginning.
I know that probably there's a way to achieve this by writing more code, but I always tend to nest as much as possible to "optimize" the code while I write it, so that's why I tried solving this exercise by using less variables and loops as possible.
You are too complex. Hard to find your error. Straight code follows:
public static void main(String[] args) {
//int num = Integer.parseInt(args[0]);
int num = 5; // for test
// creating 2d array
int[][] figures = new int[num][num];
// filling the array
for(int row=0; row<figures.length; ++row) {
for(int col=0; col<figures[row].length; ++col) {
figures[row][col] = (row + col) % num + 1;
}
}
// printing the array
for(int row=0; row<figures.length; ++row) {
// printing border
for(int col=0; col<figures[row].length; ++col) {
System.out.print("+-");
}
System.out.println("+");
// printing data row
System.out.print("|");
for(int col=0; col<figures[row].length; ++col) {
System.out.print(figures[row][col]);
System.out.print("|");
}
System.out.println();
}
// printing final border
for(int col=0; col<figures[0].length; ++col) {
System.out.print("+-");
}
System.out.println("+");
}
public static void main(String args[]){
int dimension = Integer.valueOf(args[0]);
int[][] twoDimArray = new int[dimension][dimension];
for(int i=0;i<dimension;i++){
for(int j=0;j<dimension;j++){
System.out.print("|"+((i+1)%(dimension+1)));
} //end of j loop
} //end of i loop
} //end of main
The above is only the logic for printing the numbers in the specified sequence.
The other design pattern ( +-+ ) thing i guess u can manage.
the following codes will initialize a 2d int array for the data (1-5 in your example). and print the table. note that the table structure was not save in a String 2d-array. just print the table out. see comments in line.
public static void main(String[] args){
final int num = 5; //hardcoded 5, just for testing.
final int[][] data = new int[num][num];
for (int r = 0; r < data.length; r++) {
for (int c = 0; c < data[r].length; c++) {
final int t = r + c + 1;
data[r][c] = t <= num ? t : t - num;
}
}
// now we have all int data in data 2D-array
// here is the +-+- line
final StringBuilder sb = new StringBuilder("+");
for (int i = 0; i < data.length; i++)
sb.append("-+");
// now print the table
for (int r = 0; r < data.length; r++) {
System.out.println(sb.toString());
for (int c = 0; c < data.length; c++)
System.out.print("|" + data[r][c]);
System.out.println("|");
}
System.out.println(sb.toString());
}
output:
if you give num=9 as argument. the codes above will print:
+-+-+-+-+-+-+-+-+-+
|1|2|3|4|5|6|7|8|9|
+-+-+-+-+-+-+-+-+-+
|2|3|4|5|6|7|8|9|1|
+-+-+-+-+-+-+-+-+-+
|3|4|5|6|7|8|9|1|2|
+-+-+-+-+-+-+-+-+-+
|4|5|6|7|8|9|1|2|3|
+-+-+-+-+-+-+-+-+-+
|5|6|7|8|9|1|2|3|4|
+-+-+-+-+-+-+-+-+-+
|6|7|8|9|1|2|3|4|5|
+-+-+-+-+-+-+-+-+-+
|7|8|9|1|2|3|4|5|6|
+-+-+-+-+-+-+-+-+-+
|8|9|1|2|3|4|5|6|7|
+-+-+-+-+-+-+-+-+-+
|9|1|2|3|4|5|6|7|8|
+-+-+-+-+-+-+-+-+-+
you have make it more complicated try this Simple code :
enter code here
public static void main(String[] args)
{
int n = 5 ;
for(int i = 1 ; i <= n ;i++)
{
for(int l = 0 ; l < n;l++)
System.out.print("+-");
System.out.print("\n|");
for(int j = i ; j <=n;j++ )
{
System.out.print(j+"|");
}
for(int k = 1 ; i >= 2 && k <=i-1;k++)
{
System.out.print(k+"|");
}
System.out.println();
}
}
I have 2 1d arrays and im trying to populate them into a single 2d array in JAVA.
For instance:
x[] = {2,5,7,9}
y[] = {11,22,33,44}
The results should then be:
result[][] = {{2,5,7,9}, {11,22,33,44}}
How do I go about this? I currently have something like this:
for(int row = 0; row < 2; row++) {
for(int col = 0; col == y.length; col++) {
???
}
}
Im sort of stuck from there...
2D array is an array of arrays. So why don't you try this?
int result[][] = {x,y};
And to make sure that it is so simple and works, test this:
for(int i=0; i<result.length; i++)
{
for(int j=0; j<result[0].length; j++)
System.out.print(result[i][j]+ " ");
System.out.println();
}
Try this:
ArrayList<Integer[]> tempList = new ArrayList<Integer[]>();
tempList.add(x);
tempList.add(y);
Integer result[][] = new Integer[tempList.size()][];
result = tempList.toArray(tempList);
You have to revert the row and column indices
for(int row = 0; row < 2; row++)
{
for(int col = 0; col = y.length; col++)
{
....
}
}