Im wondering how I could split a 1d array into a 2d array in java?
I know how to set up both of them and i know that I have to iterate over both of them using for loops im just not sure how I would go about it.
I have an array of students names and i want the first 5 to go on the top line and then the next 5 on the bottom line of the 2d array so as to create groups of 5 students.
so far I have:
public void main(String[] args)
{
for (int x=0; x<5;x++)
{
for (int y=0; y<5;y++)
{
board[x][y] = (letters)y;
System.out.print(board[x][y]);
System.out.print("");
}
}
}
How to I tell the it that i want this to be connected to the arrays
So, it sounds like your only problem is the calculation of the letters index. Try this:
for (int x = 0; x < 2; x++) {
for (int y = 0; y < 5; y++) {
board[x][y] = letters[x * 5 + y];
System.out.print(board[x][y]);
System.out.print("");
}
}
This will create 2 "rows" of 5 students each.
You can make the 2d array 5x(number of students / 5) or number of people per group by number of student / people per group /* number of groups */ so it is more dynamic.
You will only need one loop to achieve this. The loop goes through each of the names in the 1d array, get the names one by one and assign it to and appropriate index in the 2d array.
To figure out the index one of them could be just the counter of the loop mod(%) people per group this will keep the index between 0 to 4. To figure out the other index you could mod(%) the loop counter with (number of student / people per group)
so it will look like board[i%ppg][i%nog] ppg being people per group and nog being number of groups. You can easily calculate number of groups.
EDIT: 2d arrays are easy if you have a really simple way to visualize them. The trick I did when I was learning 2d arrays was to think of them as chess boards. Chess boards got vertical and horizontal indices represented by letters and number just like 2d arrays except in programming it is just numbers.
Take a closer look at this code, it's also computing the indexes even if your 1D array has a number of elements which is not divisible by 5.
String[] names = new String[104];
double size = names.length;
String[][] yetAnother = new String[(int) Math.ceil(size / 5)][5];
for (int i = 0; i < size; i++)
yetAnother[(int) Math.ceil(i / 5)][i % 5] = names[i];
Related
So I have a really basic coding question, I just started learning this year, and I have an assignment for a code that is supposed to
flip a fair coin n times and count how many heads it gets. The program will do m experiments and then
print out the results as a (vertical) histogram. The program will first ask the user to input the number of
experiments to perform (m) and the number of coin flips in each experiment (n). n can be at most 79. The
output will be a histogram made up of spaces and asterisks (*), with n+1 columns (for the number of heads
which can go from 0 to n)
I have the code for the histogram all done, but the problem I have is how to store the number of heads as it's own variable. For example, if it flipped the coin 80 times and 40 of them were heads, I would want it to create an int for 40 flips, then add one to it. I just don't know how to go about initializing 80 variables without writing out int one = 0; int two = 0, int three = 0; until the end of time, then writing 80 if statements until it finds the right integer to add one to. Is there an easy way to do this or should there be a different approach I should be taking? Here is the code, please be gentle, literally only a month or so into an extremely basic java class
for(m=m; m>0; m--) { //runs m number of experiments of n coinflips, keeping track of total heads
n = o; // when N gets set to 0 through the while loop, o resets it back to it's original so it can loop again
while(n>0) {
n--;
if(random.nextBoolean()) {
heads++;
total++;
/** here is where I want the number of heads saved to a
variable, so that way later I can run a loop to put as many *'s as I need in the histogram later */
Just use an array for the 80 (or n) experiments:
I don't understand, this would just count how many heads/tails there are right? This doesn't save them (ie it flipped 5 heads 6 times, 4 heads 3 times, 3 heads twice, ect) unless I'm misunderstanding
If you are storing the number of head m times (where m is < 80), you can:
1) print the histogram as you generate the results (no array needed) OR
2) store the 80 results in an array
Example for 1 (no array):
for(int x=0; x<experiments; x++){
int heads = 0;
for(int y=0; y<flips; y++){
if(rnd.nextInt(2) == 0) //assume 0 is head
heads ++;
}
//print histogram
for(int y=0; y<heads; y++)
System.out.print("*");
System.out.println();
}
Example for 2 (with array):
int[] expr = new int[80]; //store results for 80 experiments
for(int x=0; x<expriments; x++)
for(int y=0; y<flips; y++)
if(rnd.nextInt(2) == 0)
expr[x] ++;
Use an array:
int n = 80;
// space for n integers, with indexes 0..n
int[] histogram = new int[n + 1];
for (int i = 0; i < experiments; i++) {
// flip coin n times, counting heads
int heads = ...;
histogram[heads] = histogram[heads] + 1;
}
for (int i = 0; i < histogram.length; i++) {
printStars(histogram[i]);
}
If you're unfamiliar with arrays, the Java Tutorial has a good explanation.
I am looking for a less complicated way (if possible) to insert elements to the next empty vertical index of a two dimensional array, while randomly looping through horizontal indices.
For Example:
Making a table that shows 32 players from 8 teams distributed randomly into 4 rounds. So, we want to put 8 players in each round.
consider the following: roundsTable[x][y] is the table, whereas x represent the round each player enrolled in, and y represent the players within each round. The players will be collected from another two dimensional array players[t][p] and they will be collected in index order t(0,1,2,3,4,5,6,7) p(0,1,2,3). However, they will be stored in roundsTable[][] in a random round x each time. The question is, how can I put each player in the next empty spot of y in each random x that been selected.
//playersRoundOrder[] is 32 long and contains the random rounds in a range of 1-4. It looks something like that: {1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,3,3,3...} then I shuffle it to become something like this: {4,1,1,3,2,3,4...}. Then, I take the first index of that array and I set it as the round for the first index of player in the first team, then the second index to the second player of the first team...etc
private void example(int[] playersRoundOrder) {
String[][] roundsTable = new String[4][8]; //The table that I will use to store each player based on their round. So, the player whose round is 3, will be stored at roundsTable[3][*Here is where I need the solution. I want to insert each player in round three in the next available spot etc.*]
int t = 0; //count the index of each team. So, it will only increase when I set a random round for each player in the first team.
int p = 0; //count the index of each player in t. So, it will increase after each 1 loop, and it returns to zero when t increase.
for (int i = 0; i < playersRoundOrder.length; i++) {// loop 32 times
//String players[][] is the other two dimensional array that contains 32 players
//(8 teams - 4 players for each)
if ((p + 1) == players[t].length) { //If there is no more players in this team t, go to the next team and start from the index of the first player
roundsTable[playersRoundOrder[i]] [**PROBLEM**] = players[++t][p = 0];
} else { //If there is still players on the team, go to the next player
roundsTable[playersRoundOrder[i]] [**PROBLEM**] = players[t][p++];
}
}
}
If I understand your question correctly, you have the following holding players' names:
String players[8][4]; // first dim team, second dim player number
And you want to fill the following with names for all players in each round:
String roundsTable[4][8]; // first dim round, second dim participant in round
In such a way that
each player appears once
each team has one player in each round
the order the players appear in each round is randomised
the team assigned to each place in the round is randomised
Please correct me if I'm wrong. If not then here's a potential solution:
String[][] generateRoundsTable(String[][] players) {
String[][] roundsTable = new String[ROUND_COUNT][TEAM_COUNT];
List<Integer>[] assignment = new List<>[ROUND_COUNT];
for (int r = 0; r < ROUND_COUNT; r++) {
assignment[r] = IntStream.range(0, TEAM_COUNT).collect(Collectors.toList());
Collections.shuffle(assignment[r]);
}
for (int t = 0; t < TEAM_COUNT; t++) {
List<String> team = Arrays.asList(players[t]);
Collections.shuffle(team);
for (int r = 0; r < ROUND_COUNT; r++) {
roundsTable[r][assignment[r].get(t)] = team.get(r);
}
}
return roundsTable;
}
I have two containers: a 2-dimensional NxN matrix and a 1-dimensional array which is the transposed 1D "version" of the matrix (so for a 5x5 array, I will have a 25 element array with the same values). I want to implement a query function that will take 2D coordinates as arguments but will be doing work on the equivalent 1D array.
In order to keep algorithm efficiency strictly non-quadratic I want to access only the array and not the matrix.
I've checked other questions but they all talk about converting the whole matrix to an array through nested for-loops. I don't want to do this, as that would take quadratic time to run. Instead, I want the conversion to be on-demand for a given coordinate through a query function/method. In other words for a given number of N columns/rows:
transpose(int i, int j) {
int result;
result = i * N + j;
return result;
}
This is the formula I'm using but it is not correct. For example if I want to access the element in the {5,5} position the result would be 5*5 + 5 = 30, which is greater than 25 (which would be the total number of elements for 5x5 matrix).
Thanks in advance.
If you have a 2d array and a 1d array having same elements,then the following will be true
2d[i][j]=1d[i*number_of_columns+j]
I am assuming from your post that you already have created a 1d array out of a 2d one.
Note i and j are indices and rememeber indices begin from 0
EDIT:If you are accessing an element at [5][5] (as last element)it means your array is of order 6 by 6 and not 5 by 5.So your 1d array will have 6*6=36 elements and not 25.
You can use the deepToString() method to output a 2D array to a String. This can make it easier to do things such as sort() for example.
Assuming a declared int mat2d[m][n]; with m rows and n columns, you can convert it like
int * mat1d = new int[m * n];
int k = 0;
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++i)
mat1d[k++] = mat2d[i][j];
If you just want to convert between 1D and 2D coordinates, serve yourself and make functions from this:
const int width = 10;
// from 1D coordinate to 2D coordinate
int coord_1d = 25;
int coord_x = coord_1d % width;
int coord_y = coord_1d / width;
// from 2D coordinate to 1D coordinate
coord_1d = coord_x + coord_y * width;
Your question is quite confusing, you said that you don't want nested loops, here is a just-one-loop conversion
int[][] a={
{1,2,3,4,5,6},
{4,5,6,7,8,9},
{7,8,9,1,2,3},
{1,2,3,4,5,6}
};
int[]b=new int[a.length*a[0].length];
int x=0;
for(int i=0, j=0;i<a.length&&j<a[0].length;i=(j==a[0].length-1?i+1:i),j=(j+1)%a[0].length)
b[x++]=a[i][j];
System.out.println(Arrays.toString(b));
If you want the conversion to be based on coordinates, by changing i and j values in the for loop to such coordinates will allow you to convert to array only a subset of your matrix
I need help, I am trying to make use of Lattice Multiplication in java for use in a BigInt class I am having to write for a class.
Right now I have the code storing the digits needed for the adding part of the algorithm in a 2 dimensional array. From there though I am at a lose as to how to make a loop to go through the array and add the numbers in what would be a diagonal.
For instance here is the test numbers etc:
200
*311
= 62200
The array is holding:
6 0 0
2 0 0
2 0 0
6 is (2,2) in the array and the bottom right is (0,0)
I need to add in a diagonal, such as (1,0) + (0,1) = 0
The issue is how do I do this, since not only is it moving up and left in different ways, but it goes from 1 element to 2 elements to 3 elements, then back the other way, and of course this will get bigger the longer the number is.
This is the code that I have:
public int multiply(BigInt val){
int[] bigger;
int[] smaller;
int[] dStore;
int lengthMax = (val.getSize()+this.getSize()) - 1;
int first = 0;
int second = 0;
int[][] tempResult;
//Checks to see which is bigger and then adds that to bigger
if(val.getSize() >= this.getSize()){
bigger = val.getData();
smaller = this.getData();
dStore = new int[val.getSize()+this.getSize()];
}else{
bigger = this.getData();
smaller = val.getData();
dStore = new int[val.getSize()+this.getSize()];
}
tempResult = new int[smaller.length][bigger.length];
for(int i=0;i < smaller.length;i++){
for(int j = 0;j < bigger.length;j++){
tempResult[i][j] = smaller[i] * bigger[j];
}
}
** there is the return statement etc below
This might help as to explain lattice multi better: Lattice Multi Video
I would try a different approach. Look at the lattice in the video and imagine that you rotates the array a little bit to the left so that the diagonals becomes vertical. The array would then look like this:
2 3 5
8 3
2 4 0
Now, just summarize the columns and you would have the total.
You would of course have to split the numbers into arrays of digits first. The easiest way to do that (but not the most efficient) is to convert them into strings ...
Good luck!
To move diagonally, you'd increment both x and y:
// Loop though the diagonal of an array
x = 0;
y = 0;
while (x < ARR_X_SIZE && y < ARR_Y_SIZE) {
// Do something with arr[x][y]
x++;
y++;
}
This is the basic loop; you can change the x and y increments to determine the direction you need to go. The key to going through the whole array is the value of the coordinates going into the loop. Array:
1 2 3
4 5 6
7 8 9
If you set x = 1; y=0 at the beginning of the loop, you'll get 2 6. Set x = 0, y = 1 and you'll get 4 8.
I hope this helps you with your assignment. Good luck on the rest! That is definately an interesting algorithm to implement.
I'm new to java programming and I can't wrap my head around one final question in one of my assignments.
We were told to create a static method that would search a 2-D array and compare the numbers of the 2-D array to an input number...so like this:
private static int[] searchArray(int[][] num, int N){
Now, the part what we're returning is a new one-dimensional array telling the index of the first number in each row that is bigger than the parameter variable N. If no number is bigger than N, then a -1 is returned for that position of the array.
So for example a multi-dimensional array named "A":
4 5 6
8 3 1
7 8 9
2 0 4
If we used this method and did searchArray(A, 5) the answer would be "{2,0,0,-1)"
Here is a very good explanation about Java 2D arrays
int num[][] = {{4,5,6},{8,3,1},{7,8,9}};
int N = 5;
int result[] = new int[num.length];
for(int i=0; i<num.length; i++){
result[i] = -1;
for(int j=0; j<num[0].length; j++){
if( N < num[i][j] ){
result[i] = j;
break;
}
}
}
for(int i=0; i<result.length; i++){
System.out.println(result[i]);
}
The first for loop(The one with a for inside it) traverses the 2D array from top to bottom
in a left to right direction. This is, first it goes with the 4 then 5,6,8,3,1,7,8,9.
First the result array is created. The length depends of the number of rows of num.
result[i] is set to -1 in case there are no numbers bigger than N.
if a number bigger than N is found the column index is saved result[i] = j and a break is used to exit the for loop since we just want to find the index of the first number greater than N.
The last for loop just prints the result.
Generally when using multi-dimensional arrays you are going to use a nested for loop:
for(int i = 0; i < outerArray.length; i++){
//this loop searches through each row
for(int j = 0; j < innerArrays.length; j++) {
//this loop searches through each column in a given row
//do your logic code here
}
}
I won't give you more than the basic structure, as you need to understand the question; you'll be encountering such structures a lot in the future, but this should get you started.