I have a list List<int[][]> orgnisms = new ArrayList<>();, which I have populated a few empty (only 0 values) tables and I want to set the value of certain cells now. For example, I want the first table from list and cell [1][1] to have a value of 1. How do I accomplish that?
EDIT:
I have a problem because orgnisms.get(0)[1][1] = 1; adds the value 1 to each table in list, not only table which has index 0...
Here is my code to generate a new empty multi-dimensional array which then gets added to the orgnisms list:
private void newEmptyArrays(){
int[][] emptyTable = new int[n][n];
for( int[] ii : emptyTable)
for (int i : ii)
i = 0;
for(int i=0;i<mi;i++)
orgnisms.add(emptyTable);
}
The same 'table' is being added multiple times to the list, but it is just the only one 'table' that was created in following code part (original problem, not the solution):
int[][] emptyTable = new int[n][n];
for(int i=0;i<mi;i++)
orgnisms.add(emptyTable);
since there is only one instance multiple times, there is no difference by which index of the list the table is being changed. orgnism.get(0) is the same (instance) as orgnism.get(1) and so on...
Solution: create a new 'table' for each entry in the list:
for(int i=0;i<mi;i++) {
int[][] emptyTable = new int[n][n];
orgnisms.add(emptyTable);
}
and just a note, the assignment in following code part is not changing the value inside the array - it wouldn't work to clear an array:
for (int i : ii)
i = 0; // this only changes the value of the variable,
// not of the array entry (not written back)
List<int[][]> orgnisms = new ArrayList<>();
each element within the list is a multi-dimensional array, hence if you want to access any of them you'll first need to retrieve it through the List#get method then perform some operations on it i.e
orgnisms.get(0)[1][1] = 1;
orgnisms.get(0) will retrieve the reference to the multi-dimensional array, then [1][1] will index into row 1 and column 1 of the retrieved multi-dimensional array and assign a value 1 to it.
Update
I have a problem because orgnisms.get(0)[1][1] = 1; adds the value 1
to each table in list, not only table which has index 0...
Look carefully at your last loop, you're storing multiple references to the same multi-dimensional array within the orgnisms list thus it makes sense for such behavior to happen.
Also, as per your update, the code is not doing what you think it's. In fact, the nested for loops are not doing anything to the emptyTable multi-dimensional array. However, by default, all the arrays inside emptyTable have a value of 0 set to each element anyway, meaning attempting to set them to 0 again is redundant.
That said, you can change your method accordingly:
private void newEmptyArrays(){
for(int i = 0; i < mi ; i++){
int[][] emptyTable = new int[n][n];
orgnisms.add(emptyTable);
}
}
Related
This is a part of creating a matching game with graphical components. I need to code a class method named randomOrder. I should be able to randomly choose which pictures to be used and I need to place them randomly on the board (for now the board is a 4x4).
I want a method that randomly moves around the elements in an array. For this I wrote
public class Tools {
public static void randomOrder(Object[] f){
Object[] a = new Object[8];
}
}
The only thing I got from the hint is the following:
"Use a temporary array inside the method and take one element at a time from the original array and place it in the temporary array. If the array-position is taken, then you need to randomize a new position. When all the elements are placed, you can copy the temporary array to the original."
I don't understand how to use the hint. I feel this is so complicated that I can't even formulate a proper question.
Can someone translate the hint to me in a more understandable
question?
Is my start okay?
I'm sorry if the question is bad, I don't know how to make it better. Any suggestions are welcome.
Let me try:
Use a temporary array inside the method
You already did that, although the array a should have the same length as f
take one element at a time from the original array and place it in the temporary array
You iterate over a and for each index you do the following:
Create a random integer between 0 and the size of the array, e.g. for a 4x4 grid your array would have length 16 so the index would be between 0 and 15 (both inclusive).
Get the element at that index from f and place it at the current position in a. Then set that index in f to null.
Example:
//iterate
for( int i = 0; i < a.length; i++ ) {
int random = ...; //create the random number here
Object o = f[random];
while( o == null ) {
//see below
}
a[i] = o;
}
If the array-position is taken, then you need to randomize a new position.
If the element in f already is null then either create a new random number (that's what the text hints at) or increment that index until you hit the end or find a non-null element (probably better from a performance point of view, when you hit the end go back to index 0 for f).
When all the elements are placed, you can copy the temporary array to the original.
When you are done filling a you iterate once again and set the elements in f according to their index in a, i.e.
for( int i = 0; i < a.length; i++ ) {
f[i] = a[i];
}
I'm currently working on a homework assignment for a beginner-level class and I need help building a program that tests if a sodoku solution presented as an int[][] is valid. I do this by creating helper methods that check both rows, columns and grids.
To check the column I call a method called getColumn that returns a column[]. When I test it out it works fine. I then pass it out on a method called uniqueEntries that makes sure that there are no duplicates.
Problem is, when I call my getColumn method, it returns an array consisting of only one number (for example 11111111, 22222222, 33333333). I have no idea why it does that. Here is my code:
int[][] sodokuColumns = new int[length][length];
for(int k = 0 ; k < sodokuPuzzle.length ; k++) {
sodokuColumns[k] = getColumn(sodokuPuzzle, k);
}
for (int l = 0; l < sodokuPuzzle.length; l++) {
if(uniqueEntries(sodokuColumns[l]) == false) {
columnStatus = false;
}
}
my helper is as follows
public static int[] getColumn(int[][] intArray, int index) {
int[] column = new int[intArray.length];
for(int i = 0 ; i < intArray.length ; i++) {
column[i] = intArray[i][index];
}
return column;
}
Thanks !
You said:
when I call my getColumn method, it returns an array consisting of only one number (for example 11111111, 22222222, 33333333).
I don't see any issue with your getColumn method other than the fact it's not even needed because getColumn(sodokuPuzzle, k) is the same as sodokuPuzzle[k]. If you're going to conceptualize your 2D array in such a way that your first index is the column then for your purpose of checking uniqueness you only need to write a method to get rows.
The issue you're having would seem to be with another part of your code that you did not share. I suspect there's a bug in the logic that accepts user input and that it's populating the puzzle incorrectly.
Lastly a tip for checking uniqueness (if you're allowed to use it) would be to create a Set of some kind (e.g. HashSet) and add all of your items (in your case integers) to that set. If the set has the same size as your original array of items then the items are all unique, if the size differs there are duplicates.
I have created a list of 2D arrays containing randomly generated number values for different locations.
public static int Prices[][] = new int[Cities.length][ItemNames.length];
public static List<int[][]> CityPrices = new ArrayList<int[][]>();
public static void NewDay()
{
for(int i = 0; i<Cities.length; ++i)
{
Prices[i] = PriceGenerator.ReturnPricesForCity(i);
//This method returns an array of random integers
}
CityPrices.add(Prices);
}
But then later when I want to retrieve the price history for a specific item for the amount of days passed, it returns the same value for each day
int Prices[] = new int[GlobalVariables.CityPrices.size()];
String sTest = "";
for(int i = 0; i < Prices.length; ++i)
{
Prices[i] = GlobalVariables.CityPrices.get(i)[spinCity.getSelectedItemPosition()][spinItem.getSelectedItemPosition()];
sTest = sTest + Prices[i] + ",";
}
In this case, the values returned by sTest was : 6055,6055,6055,6055,6055, for five consecutive days.
If I would for instance add a day, the values would change to a range of a new number, which in this case was : 7294,7294,7294,7294,7294,7294,
Please show me what I am doing wrong, as I have been trying to figure this one out the past 4 days with no luck.
Every element in your CityPrices list is the same: in each case, you are adding the Prices two-dimensional array. Your loop modifies Prices[i], but it doesn't change Prices, which is still a reference to the same two-dimensional array right the way through.
I think you're imagining it will pass the contents of the array in its current state, but it doesn't: it passes a reference to the array to the .add() method, so any subsequent changes to the array will be reflected in the contents of CityPrices.
If at the end of your loop you try
CityPrices.get(0) == CityPrices.get(1)
you'll see it returns true.
In the assignment: Prices[i] = GlobalVariables.CityPrices.get(i)[spinCity.getSelectedItemPosition()][spinItem.getSelectedItemPosition()]; you are basically referencing an int[][] at the same index for both dimensions.
On top of that, the spinCity.getSelectedItemPosition() invocation might be returning the same index at every iteration of your loop, hence your identical values.
It's hard to assume anything further as you haven't posted the code for spinCity.
I want to make a 2D ArrayList, with the number of columns already specified but not the rows.
For example, I want to create a table with 26 columns and 0 or 1 columns at first, then after each loop of doing something else, the number of rows will increase along with that loop.
When I increase the number of rows (length of an ArrayList of ArrayLists), I also want all 26 arrays to increase as well. What is the syntax for it?
And how would I index into, or add a new item into a specific location - say array[2][3] = item?
BTW this is a DFSA table converted from a NFSA table
You could have a list of lists, essentially something like so:
List<List<String>> table = new ArrayList<List<String>>();
Then add the 26 columns:
for(int i = 0; i < 26; i++)
{
table.add(new ArrayList<String>());
}
You can then have a method, called, say, addToColumn(int column, String value, List<List<String>> table) in which you do something like so:
for(int i = 0; i < table.size(); i++)
{
if(i == column)
{
table.get(i).add(value);
}
else
{
table.get(i).add("");
}
}
This should allow you to have lists which grow together. Of course, my assumption in the above is that you will be entering one element at a time.
Alternatively, you can do something like so:
public void addToColumns(Map<int, String> data, List<List<String>> table)
{
for(int key : data.keyset())
{
table.get(key).add(data.get(key));
}
for(int i = 0; i < table.size(); i++)
{
if(!data.containsKey(i))
{
table.get(i).add("");
}
}
}
The above algorithm should allow you to add items to multiple columns, while filling the rest up with empty strings. This should allow you to end up with rows of equal length. Also, the map will be used to store a key-value pair where the key is the column number, and the value will be whatever string you would like to throw in there. This will allow you to populate your table one row at a time.
You can simply create an array by giving only the number of rows:
int[][] array = new int[4][];
Now you may treat your array as the transpose of what you have defined so if you want to enter an element at 3rd column of 2nd row you can enter as transpose i.e.
array[3][2]=5;
Can you create a line of code, within a while-loop, that will create a new array AND change the array's name with each iteration of the while loop?
Example:
int size = 10;
int name_count = 1;
while(size <= 100)
{
//name_count is changing the name of the array by calling it
// "array1", "array2", etc...
//I know this may not be correct code for changing the name of
// the array, but it is suppose to get the point across.
int[] array(name_count) = new int[size];
for (int i = 0; i <= size; i++)
{ /* Adding numbers to an array */ }
size = size + 5;
name_count++;
}
Identifier names need to be defined at compile time. So you can't explicitly use a different variable name on each iteration of the loop.
Another problem with your pseudo-code is that, if the array were to be declared inside the loop, it would fall out of scope when the loop completes, so there wouldn't be much point.
To do something like this you need to use some collection to hold the arrays, and it would be easier to make them explicit objects instead of just arrays. Something like:
List<List<Integer>> listOfArrays = new ArrayList<List<Integer>>();
while (size <= 100) {
List<Integer> listOfNumbers = new ArrayList<Integer>(size);
/* insert loop here to add numbers to listOfNumber */
size += 5;
name_count += 1;
}
Then you can access each list of numbers using an index into listOfArrays -- equivalent to naming each one with the index, but handled at runtime instead of compile time.
You cannot change the array's name, It will just re-declare the array with each successful loop. (It will be a new blank array.) I think what you are looking for is a two dimensional array.
int[][] myArray = new int[3][3];