Okay probably it's a very easy solution, but I can't seem to find it. I've got two ArrayLists:
ArrayList<Candidate>partyList and ArrayList<Party>electoralList
Now I want to make a 2d int array that represents the parties and candidates like this:
p c
1 1
1 2
1 3
2 1
2 2
3 1
3 2
3 3
etc.
I think I already have the right for-loop to fill the array but I only miss the correct formula to do it.
int[][]ArrList;
for (int i=0; i<parties.size(); i++){
for(int j=0; j<parties.get(i).getPartyList().size(); j++){
ArrList[i][j]=
Is the for-loop indeed correct? And what is the formula to fill the array then?
I will try and answer the question from how I understood what you are looking for here.
You should understand this first:
A 2D array consists of a nestled array i.e. ArrList[2][3] = [ [1,2,3], [1,2,3] ] -> The first digit declares How many arrays as elements, the second digit declares Size or if you like: length, of the array elements
If you are looking for to represent the candidates and parties as numbers. Here is my solution:
int[][]ArrList = new int[parties.size()][electoral.size()]
for (int depth=0; depth < parties.size(); depth++){
for(int itemIndex=0; itemIndex<parties.get(depth).getPartyList().size(); itemIndex++){
ArrList[depth][itemIndex]= itemIndex;
I hope this is what you were looking for.
First of all, ArrList should not have a starting capital letter (it is not a class but an object).
Second point (I think what troubles you) is that you are not initializing the matrix and the parties.size() are always 0. I am not sure since there is not enough code though.
You could do something like this
int ROWS = 10;
int COLS = 2;
int [][] matrix = new int[ROWS][];
for(int i=0; i< matrix.length; i++){
matrix[i] = new int[COLS];
}
or, with lists
int ROWS = 10;
int COLS = 2;
List<List<Object>> matrix = new ArrayList<>(ROWS);
for (int i = 0; i < ROWS; i++) {
ArrayList<Object> row = new ArrayList<>(COLS);
for (int j = 0; j < COLS; j++) {
row.add(new Object());
}
matrix.add(row);
}
int[][] arrList=new int[parties.size()][2];
int i=0,j=0,k=0;
for(;i<parties.size();i++,j++){
if(j==1){
arrList[k][j]=electoralList .get(--i);
j=-1;
k++;
}
else{
arrList[k][j]=parties.get(i);
}
}
arrList[k][j]=aarM.get(electoralList .size()-1);
System.out.println(Arrays.deepToString(arrList));
Related
So, I am building a method to check a 2d array for a target value and replace each adjacent element with that target value. I have literally tried to brainstorm the solution to this for about an hour and I just want to know if anyone can help me with this, this is the code I have so far
public int[][] replaceValue(int n, int[][]y){
int [][]temp0 = new int[y.length][y[0].length];
int[]top, down ,left, right = new int[y[0].length];
for(int row = 0; row < y.length; row++){
for(int col = 0; col < y[row].length; col++){
temp0[row][col] = y[row][col];// new array so I wouldn't mess with the array passed in
}
}
for(int row = 0; row < temp0.length; row++){
for(int col = 0; col < temp0[row].length; col++){
top[row] = temp0[row-1][col];
down[row] = temp0[row+1][col];
right[row] = temp0[row][col+1];
left[row] = temp0[row] [col-1];
}
}
I got error messages such as I didn't initialize my top and left and right and down variables but I simply don't understand how the logic works for checking the adjacent elements and making sure the whole array is not replaced with the target value. Thanks
The question is a little confusing so I will try to interpret it.
What you are given is a 2-dimensional array with some integer values. Your function should scan the 2-d array, and if you find some target value,
return a 2-d array with the adjacent indices as the target value as well.
For example, if we have a 3x3 array and the target is 2...
1 1 1 1 2 1
1 2 1 ====> 2 2 2
1 1 1 1 2 1
Your problem is that you can't think of a way to change the value without changing the entire array to 2.
Solution One: You scan for the target value in the given array, but you update the values in the temporary array.
Solution Two: You scan the temporary array, and store whether or not it should be changed using a 2-d boolean array.
Solution One is much better in terms of efficiency (both memory and time), so I'll just give you my solution #2, and leave you to do Solution One on your own.
Also, please use more descriptive variable names when it matters :P (why is the input called temp??)
public static int[][] replaceValue(int target, int[][] currArray){
int[][] temp = new int[currArray.length][];
//get a boolean array of same size
//NOTE: it is initialized as false
boolean[][] needsChange = new boolean[currArray.length][currArray[0].length];
//copy the current array into temp
for(int i = 0; i < currArray.length; i++){
temp[i] = currArray[i].clone();
}
//Go through each value in the 2d array
for(int i = 0; i < temp.length; i++){
for(int j = 0; j < temp[0].length; j++){
//if it is the target value, mark it to be changed
if(temp[i][j] == target){
needsChange[i][j] = true;
}
}
}
//Go through each value in the 2d array
for(int i = 0; i < temp.length; i++){
for(int j = 0; j < temp[0].length; j++){
if(needsChange[i][j]){ //NOTE: same as "needsChange[i][j] = true;"
//Now, we will check to make sure we don't go out of bounds
//Top
if(i > 0){
temp[i-1][j] = target;
}
//Bottom
if(i + 1 < temp.length){
temp[i+1][j] = target;
}
//Left
if(j > 0){
temp[i][j-1] = target;
}
//Right
if(j + 1 < temp[0].length){
temp[i][j+1] = target;
}
}
}
}
//return the new array we made
return temp;
}
You have not initialized your local variables before first use. So you need to change your 3rd line to some thing like the below code:
int[] top = new int[temp[0].length], down = new int[temp[0].length],
left = new int[temp[0].length], right = new int[temp[0].length];
After that your code is compiled and you can check your logic.
My task is to take the original 2D array, and calculate the weight of each index and create a new array with the new values. I just can't output the final column of the new array
Thank you!
Your loops should look like this:
for (int i = 0; i < calcWeight.length; i++) {
// note the calcWeight[i], you´ll get the first dimension length
// if you leave out the [i] part
// This way your inner loop would stop at 4 (rather 5 because <=)
// instead of its actuall length, 6
for (int j = 0; j < calcWeight[i].length; j++) {
...
}
}
I'm having a hard time figuring out how to fill my 2D array with random numbers without duplicates. I currently have it filed with random numbers within the correct range, but I just cant think of a solution to have non duplicates. How could i do this using very basic java methods? I have not yet learned anything such as arraylists, or anything like that, only the very basic methods.
Given a MxN integer array, you could fill the array with numbers from 1 to M*N using two for-loops, and then swap them using the Fisher-Yates algorithm.
EDIT:
I changed the algorithm so that it now does not create a new integer-array every time the algorithm is called. It uses one loop, and calculates m, n, i j from a random value and the iterating varaible l. Assuming the given array is not null, rectangular and at least 1x0 in size:
public static void fillRandomlyUniqe(int[][] a) {
/*
fill up the array with incrementing values
if the values should start at another value, change here
*/
int value = 1;
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++)
a[i][j] = value++;
}
// swap them using Fisher-Yates algorithm
Random r = new Random();
int max = a.length * a[0].length;
for (int l = max - 1; l > 0; l--) {
//calculate a two dimensional index from random number
int index = r.nextInt(l + 1);
int m = index % a.length;
int n = index / a.length;
//calculate two dimensional index from the iterating value
int i = l % a.length;
int j = l / a.length;
int temp = a[i][j];
a[i][j] = a[m][n];
a[m][n] = temp;
}
}
If your 2D array is NxM, and you want numbers from (say) 1 to NxM randomly placed in your 2D array, the simplest is to create an array/list with the numbers from 1 to NxM, shuffle it, then fill in your 2D array sequentially from the shuffled data. You are guaranteed to not have any duplicates because the original non-shuffled data is full of unique values.
List<Integer> data = IntStream.rangeClosed(1, M * N).boxed().collect(Collectors.toList());
Collections.shuffle(data);
Iterator<Integer> iter = data.iterator();
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
array[i][j] = iter.next();
}
}
There is probably a way to do the second half with the stream API too, but it escapes me at the moment.
I'm trying to make an encryption program where the user enters a message and then converts the "letters into numbers".
For example the user enters a ABCD as his message. The converted number would be 1 2 3 4 and the numbers are stored into a one dimensional integer array. What I want to do is be able to put it into a 2x2 matrix with the use of two dimensional arrays.
Here's a snippet of my code:
int data[] = new int[] {10,20,30,40};
*for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
for (int ctr=0; ictr<data.length(); ictr++){
a[i][j] = data[ctr];}
}
}
I know there's something wrong with the code but I am really lost.
How do I output it as the following?
10 20
30 40
(instead of just 10,20,30,40)
Here's one way of doing it. It's not the only way. Basically, for each cell in the output, you calculate the corresponding index of the initial array, then do the assignment.
int data[] = new int[] {10, 20, 30, 40, 50, 60};
int width = 3;
int height = 2;
int[][] result = new int[height][width];
for(int i = 0; i < height; i++) {
for(int j = 0; j < width; j++) {
result[i][j] = data[i * width + j];
}
}
Seems like you want to output a 2xn matrix while still having the values stored in a one-dimensional array. If that's the case then you can to this:
Assume the cardinality m of your set of values is known. Then, since you want it to be 2 rows, you calculate n=ceil(m/2), which will be the column count for your 2xn matrix. Note that if m is odd then you will only have n-1 values in your second row.
Then, for your array data (one-dimension array) which stores the values, just do
for(i=0;i<2;i++) // For each row
{
for(j=0;j<n;j++) // For each column,
// where index is baseline+j in the original one-dim array
{
System.out.print(data[i*n+j]);
}
}
But make sure you check the very last value for an odd cardinality set. Also you may want to do Integer.toString() to print the values.
Your code is close but not quite right. Specifically, your innermost loop (the one with ctr) doesn't accomplish much: it really just repeatedly sets the current a[i][j] to every value in the 1-D array, ultimately ending up with the last value in the array in every cell. Your main problem is confusion around how to work ctr into those loops.
There are two general approaches for what you are trying to do here. The general assumption I am making is that you want to pack an array of length L into an M x N 2-D array, where M x N = L exactly.
The first approach is to iterate through the 2D array, pulling the appropriate value from the 1-D array. For example (I'm using M and N for sizes below):
for (int i = 0, ctr = 0; i < M; ++ i) {
for (int j = 0; j < N; ++ j, ++ ctr) {
a[i][j] = data[ctr];
}
} // The final value of ctr would be L, since L = M * N.
Here, we use i and j as the 2-D indices, and start ctr at 0 and just increment it as we go to step through the 1-D array. This approach has another variation, which is to calculate the source index explicitly rather than using an increment, for example:
for (int i = 0; i < M; ++ i) {
for (int j = 0; j < N; ++ j) {
int ctr = i * N + j;
a[i][j] = data[ctr];
}
}
The second approach is to instead iterate through the 1-D array, and calculate the destination position in the 2-D array. Modulo and integer division can help with that:
for (int ctr = 0; ctr < L; ++ ctr) {
int i = ctr / N;
int j = ctr % N;
a[i][j] = data[ctr];
}
All of these approaches work. Some may be more convenient than others depending on your situation. Note that the two explicitly calculated approaches can be more convenient if you have to do other transformations at the same time, e.g. the last approach above would make it very easy to, say, flip your 2-D matrix horizontally.
check this solution, it works for any length of data
public class ArrayTest
{
public static void main(String[] args)
{
int data[] = new int[] {10,20,30,40,50};
int length,limit1,limit2;
length=data.length;
if(length%2==0)
{
limit1=data.length/2;
limit2=2;
}
else
{
limit1=data.length/2+1;
limit2=2;
}
int data2[][] = new int[limit1][limit2];
int ctr=0;
//stores data in 2d array
for(int i=0;i<limit1;i++)
{
for(int j=0;j<limit2;j++)
{
if(ctr<length)
{
data2[i][j] = data[ctr];
ctr++;
}
else
{
break;
}
}
}
ctr=0;
//prints data from 2d array
for(int i=0;i<limit1;i++)
{
for(int j=0;j<limit2;j++)
{
if(ctr<length)
{
System.out.println(data2[i][j]);
ctr++;
}
else
{
break;
}
}
}
}
}
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.