I want to create dynamic matrix 2d using loop in java. My code is
class Mat {
public static void main (String[] args) throws java.lang.Exception {
List<List<Integer>> group = new ArrayList<>();
List<Integer> single = new ArrayList<>();
for (int i=0; i < 3; i++){
for (int j=0; j < 3; j++){
single.add(i);
}
group.add(single);
}
group.remove(3);
System.out.println(group);
}
}
First question, how to create dynamic matrix 2D with loop? I want an output like [[0,1,2], [0,1,2], [0,1,2]] and the matrix value saved in the variable group.
Second question, after being saved in the variable group, how about if I want to remove list (number 3) in the variable? So, output is [[0,1,2], [0,1,2]].
Thanks.
For the rest of your code creates a list List<List<Integer>> by changing
single.add(i);
to
single = new ArrayList<>(); // reset every iteration
for (int j=0; j < 3; j++) {
single.add(j); // add 0,1,2
}
how if i want remove list (number 3) in the variable?
group.remove(2); //removes the element at index 2
Related
I'm having a pratice to create a n matrices with the same size. And I want to put it in a loop. Each matrix have a name.
So I decided to use OOP to implement these matrices:
In class matrix:
public class Matrix
{
static double mat[][] = null;
public matrix(int size)
{
mat = new double[size][size];
for (int i = 0; i< size; i++)
{
for(int j = 0 ; j< size;j++)
{
mat[i][j] = 0;
}
}
}
}
I have sucessfully create a loop but now the problem is I can't control the matrix. Like I want to change values in each matrix.
In main class:
for(int i = 0 ; i<n ;i++)
{
Matrix m = new Matrix(4);
m.print(plan);
System.out.println( );
}
My expectation is:
input: n = 4
output: 4 matrices
Using your class, here's some pseudo-code to help you:
-- Read user desired size
-- create a list of Matrix objects (List<Matrix> matrixList = new ArrayList<>();)
-- loop over the user input : for(int cur =0; cur<desiredNumberOfMatrices; cur++)
-- in each loop initiate a new matrix and add it to the list:
Matrix mat = new Matrix(size);
matrixList.add(mat);
-- do whatever you want next
I don't see why you might be stuck.
Write the code required to allocate a ragged 2-D int array such that the first row has space to store 1 value, the second row can store 2 values, the third row has space to store 3 values, etc. up until the 50th row which has space to store 50 values.
I know for the above question I have to essentially create a pyramid with a 2 dimensional array. I don't really know how to manipulate 2D arrays, any help will be great. This is my code thus far, not sure how to allocate space like the question above says:
import java.util.Arrays;
public class Ragged2D {
public static void main(String[] args) {
int[][] boo = new int[50][];
for(int i = 0; i < boo.length; i++){
for(int k = 0; k< boo[i].length; k++){
}
}
System.out.println(Arrays.toString(boo));
}
}
This is how you initialize a row of the 2D array:
public static void main(String[] args) {
int[][] boo = new int[50][];
for(int i = 0; i < boo.length; i++){
boo[i] = new int[i+1]; // initialize the i'th row to have i+1 elements
for(int k = 0; k< boo[i].length; k++){
boo[i][k] = ...
}
}
System.out.println(Arrays.deepToString(boo)); // this change is required to print 2D array
}
I guess this is what you need
int[][] boo = new int[50][];
for (int i=0;i<50;i++) {
boo[i] = new int[i+1];
}
This way boo[0] can contain 1 element (boo[0][0]), boo[1] can contain 2 elements (boo[0][0] and boo[0][1]) etc.
So, I have a method like this
public String[][] getArgs(){
And, I want it to get results out of a for loop:
for(int i = 0; i < length; i++){
But how do I append them to the array instead of just returning them?
Create a String[][] array inside your method, fill this array inside a loop (or in any other way) and return that array in the end.
If you are sure you want to have only one for loop (instead of two, typical for 2-dimensional array), ensure your loop will go through the number of examples equal to the number of fields in your String[][] array. Then you can calculate the double-dimension array indexes from your single loop-iterator, for example:
for(int i = 0; i < length; i++){
int a = i % numberOfCollumnsInOutput;
int b = i / numberOfCollumnsInOutput;
String[a][b] = sourceForYourData[i];
}
(Of course which array dimension you treat as collumns (and which to be rows) depends on yourself only.) However, it is much more typical to go through an n-dimensional array using n nested loops, like this (example for 2d array, like the one you want to output):
for(int i = 0; i < dimensionOne; i++){
for(int j = 0; j < dimensionTwo; j++){
array[i][j] = someData;
}
}
For your interest. A sample code according to Byakuya.
public String[][] getArgs(){
int row = 3;
int column =4;
String [][] args = new String[row][column];
for(int i=0;i<row;i++)
for(int j=0;j<column;j++)
args[i][j] = "*";
return args;
}
You can make a LinkedList from that array, and then append the elements to it, and then create a new array from it. If you are not sure i'll post some code.
I'm trying to create a 2D array of lists for a Sudoku. Essentially 81 lists each containing possible solutions to that box in the Sudoku grid. I've tried multiple declarations so far, but whenever I try to add values to a list it returns a null pointer exception. Here is an example, simply populating each of the lists with the numbers 1-9.
List<Integer>[][] sudoku = (List<Integer>[][]) new List[9][9];
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
for (int k = 1; k < 10; ) {
sudoku[i][j].add(k);
}
}
}
I'm not even positive a 2D array of lists is the optimal way to go about this, but I've done everything from scratch (with a relatively low knowledge of java) so far so I'd like to follow through with this method. The original code looked as follows:
List[][] sudoku = new List[9][9];
Research quickly revealed that this wouldn't cut it.
Thank you in advanced for any help!
Try this one. The general idea, create a master list and while you loop through it, create one inner list.
/* Declare your intended size. */
int mainGridSize = 81;
int innerGridSize = 9;
/* Your master grid. */
List<List<Integer>> mainList = new ArrayList<List<Integer>>(mainGridSize);
/* Your inner grid */
List<Integer> innerList = null;
/* Loop around the mastergrid */
for (int i=0; i<mainGridSize; i++) {
/* create one inner grid for each iteration of the main grid */
innerList = new ArrayList<Integer>(innerGridSize);
/* populate your inner grid */
for (int j=0; j<innerGridSize; j++)
innerList.add(j);
/* add it to your main list */
mainList.add(innerList);
}
Illustrated:
If you need to vary your grid, just change the values of the gridSize.
You cannot create array of generic lists.
You can create List of Lists:
List<List<List<Integer>>> soduko = new ArrayList<>();
And then populate it as you wish.
or use casting:
List[][] soduko = (List<IntegerNode>[][]) new LinkedList[9][9];
You have create the array of Lists but you did not initialize it. Insert this in the second line an the problem should be solved.
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++){
sudoku[i][j]=new ArrayList<Integer>();
}
}
Or to do it all in one go do it like this:
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
sudoku[i][j]= new ArrayList<Integer>();
for (int k = 1; k < 10; ) {
sudoku[i][j].add(k);
}
}
}
If you know that you need exactly 81 2D arrays, you can create 3D array:
int[][][] sudoku = new int[81][9][9];
The way you did it now would produce compilation error.
I have an arraylist populated by four elements, the order of which is random (they are put here by random from another arraylist). I then have a for loop that repeats 10 times, at the end of each repetition I use the clear methods to clear all the elements of the arraylist. However, when I start a new repetition, I would like to repopulate my arraylist with the old (previously worked with) elements that were members of the list in the previous repetition, so that I can use the elements again. And I would like to repeat that until I get out of my 10-repetition for loop. Is there any way to achieve this at all?
Code in addition to my question:
ArrayList<String> answerPegs = new ArrayList<String>();
// add element to ArrayList
ArrayList<String> mySecretAnswer = new ArrayList<String>();
for (int n = 4; n > 0; n--)
{
//populate mySecretAnswer with elements from answerPegs
}
ArrayList<String> clone1 = mySecretAnswer;
for (int q = 0; q < 10; q++) {
for (o = 0; o < 4; o++)
{
}
// called clear() method here
} // END OF 10-ROW LOOP
I would suggest simply having 2 lists - keep a pristine copy of the original list, and then iterate over + clear a copy of that list.
public void doRepetitions(List<Object> original)
{
for( int i=0; i<10; i++ )
{
List<Object> working = new ArrayList<Object>( original );
doStuffWithList(working);
}
}
Edit:
Since you've posted your code, I can give a more specific answer:
You can change your clone to be:
ArrayList<String> clone1 = new ArrayList<String>(mySecretAnswer);
And then move that to be inside your for loop:
for (int q = 0; q < 10; q++)
{
ArrayList<String> clone1 = new ArrayList<String>(mySecretAnswer);
// ....
}
Could you use 2 loops nested and just have the inner loop be the for loop 10 times then clear once at the end