Print the lower half of a 2D Array? - java

I'm trying to figure out one of my homework assignments. I'm not looking for anyone to give me the answers, just some guidance please.
My professor gave me a 2D array that is 5x5 and wants us to print the lower triangular half of the array.
I created the array:
Public static void main(String[] args) {
Int array1 [5][5] = {
{2,3,1,5}
{7,1,5,3,1}
{2,5,7,8,1}
{3,4,9,1,5}
};
This prints the 2D Array:
2 3 1 5 0
7 1 5 3 1
2 5 7 8 1
0 1 5 0 1
3 4 9 1 5
He wants us to print the lower triangular half though, so I believe he wants us to write a method that prints the jagged array of the 2D array, and I don't know where to start.
Can someone help me with this?

I don't know how your print method for the whole matrix works, but you probably are supposed to print the first element of the first row, the first 2 elements of the second row, etc.

Basically, here you should iterate from i = 0 to i = 4 for rows, and j = 4-i to j = 4 for columns and print out in the desired format.

To print a lower triangular half, at each row (starting from 1) it should have same number of columns.
There use two nested for loops to get the lower triangular half of the array, one loop that iterates over the row and another loop that iterates through the column printing only the desired values as output.
Although I am not sure, it seems that your array declaration has also some error.

Related

Generating all possible Permutation matrices [duplicate]

This question already has answers here:
All possible permutations of a NxN matrix in Java
(2 answers)
Closed 1 year ago.
Permutation matrices are matrices with exactly one 1 on each line and column.
Example:
(1 0 0)
(0 1 0)
(0 0 1)
I am trying to generate all possible permutations of a n-sized matrix but this seems harder to solve than expected. I tried swapping rows at first, but if you only swap rows of one initial matrix, you can't generate all possibilities. So I tried some recursion, but sadly I can't get my head through recursion. Does somebody have some advice?
I think you could make an algorithm based on recursion, with this design:
public Collection<Matrix> permute(int n)
Base case is n=1: It returns a single matrix {1}.
The rest of cases must iterate from i=0 to n-1. On eeach iteration:
Call to permute(n-1) and iterate the returned list. On each iteration:
Convert the n-1 matrix to a n x n matrix, inserting a row at position 0 and a column at position 0 (filled with 0).
Set an 1 in the (0,0) position.
Move the first column to the i position.
I suggest you could also make a battery of unit tests. Each one should check, at least, that the size of the collection returned by permute(n) has n! elements:
1->1
2->2
3->6
4->24

Return integer index of 1D array for 2D array of coordinates pairs

After reading 10+ threads about converting an entire array from 2D to 1D and vice versa, I'm wondering if there is a mathematical formula, requiring no iteration to return the index position of a pair of integers for a sorted 2D array.
My "grid" is always square, can be any size (it's 3x3 in this example), and I've got a sorted block of human friendly values from which I need to retrieve what I'm calling "True 1D indices" like this:
"Human-friendly" coordinates| Java 2D Indices | True 1D indices
[1,1],[1,2],[1,3], ==> [0,0],[0,1],[0,2], ==> 0 , 1 , 2
[2,1],[2,2],[2,3], ==> [1,0],[1,1],[1,2], ==> 3 , 4 , 5
[3,1],[3,2],[3,3], ==> [2,0],[2,1],[2,2], ==> 6 , 7 , 8
So I need a method for my class to give me the following results:
I enter 1,1 and get back 0,
I enter 3,2 and get back 7,
I enter 2,3 and get back 5,
etc etc...
I've played around with half a dozen equations where I try things like adding the coordinates to the previous row index squared, and I can never get the right result for every cell in the grid. Is there some special operator or Math function I'm missing?
Thanks.
let the matrix be of 3*3 ,3 rows and 3 column and we have to find the indices of (i,j) then the formula will be.
indices= 3*(i-1)+j;
Note :- here 3*3 and i,j are not it java 2d array format it is in human friendly coordinates.
Example (i,j)=(2,3)
indices=3*(2-1)+3 =6
And since your indices starts from 0 you could simply subtract one from 6 i.e. 5.
If the indices are named [index1,index2],
1DIndex = (rowNumber*index1) + index2
Where rowNumber starts at 1 for the first row, and index1 and index2 are the Java indices.

2D Array containing Arrays

I'm working on a discrete math problem in Java where I'm trying to find r-permutations up to n with repetition. This means if r = 4, n = 2 we can have:
1 1 1 1
1 1 1 2
1 1 2 1
1 1 2 2, etc.
Repetition means 1112 is a unique combination, however 1211 is not because 1112 already contains 3 1's and 1 2.
Therefore I wrote code to iterate through all the permutations, and every iteration is stored in an array. There is a "Master Array" which I planned on being a 2D Array where the first dimension are all unique arrays or permutations. Therefore all I have to do is create a temp array of the new iteration and use Arrays.sort and compare the temp array to all the indexes in the master array (this works because 1211, 1112, 2111, and 1121 all sort to 1112 in ascending order).
Now, the problem I'm having is storing these arrays into the 2D array Masterkey.
I've tried:
Masterkey[count] = array;, but when I print(Masterkey[count][0]) only a single integer is being output rather than the array. (array is the newest permutation)
Masterkey[count] = Arrays.copyOf(array, array.length);, once again prints a single integer rather than the array.
Masterkey[count] = array.clone();, also prints out just an integer.
I may be overlooking something simple, but I'm just struggling to get array to be stored in Masterkey.
Masterkey[count][0] will always print a single integer because Masterkey[count] = array. so Masterkey[count][0] is the same as array[0]. However, if you assign array to Masterkey[count][0] it will print the array.

In a 2d array. Iterate for the first 2 rows and 2 columns, then first 2 rows again, next 2 columns etc

I am trying to iterate over an array in a weird way. I can't think of a good way to do it. I need iterate over the first 2 rows for just 2 columns at a time. So 4 index positions at a time. I would continue on the 1st 2 rows until out of columns then continue to the next 2 rows. I would do this until I was out of rows. I can assume the array will always be an even number of rows and columns (2, 4 , 6) , but not that they are square. It can end up being 4x6 etc. Also the smallest array possible will be a 4x4.
Any suggestions? I am drawing a blank besides just hard coding it of sorts. Find the length of a row, divide it by 2, then just iterate that many times?
Example: I have a 2d array. It is 4X4. That is 4, four element square 'blocks". Blocks are 2x2. So the first block I need to manipulate first is at index positions [0][0],[0][1],[1][0],[1][1].
Iterate rows r = 0;(r +1) < r_max; r+=2
Iterate colums c = 0; (c+1) < c_max; c +=2
operate on r, r+1 and c,c+1
If you feel the "2" is hardcoding, you can easily paramerize it, but the "operate" stage might need 2 more loops for that depending on what you want to do. Otherwise this is quite fine.
I would just add checks or asserts on the top which verify what you say are your assumptions

Create 2 arrays - 1st has random integers, 2nd has unique random integers

I am working on a school homework problem. I need to create 2 int[] arrays. The first array int[10] is filled with random integers. The second array has the same numbers as in the first array, but without any duplicates.
For example, assume my first array is 1,2,2,3,1,5,5,7,9,9. My second array would then be 1,2,3,5,7,9.
Could someone please point me in the right direction to solving this problem.
Put the numbers into a Set. Then retrieve numbers from the Set. Simple! Duplicates will automatically be removed!
I would do the following (assuming that it is homework and you shouldn't be doing anything too complicated)...
Sort the array using java.util.Arrays.sort(myArray); - this will order the numbers, and make sure that all repeating numbers are next to each other.
Loop through the array and keep a count of the number of unique numbers (ie compare the current number to the next number - if they're different, increment the counter by 1)
Create your second int[] array to the correct size (from point 2)
Repeat the same process as point 2, but fill your new array with the unique numbers, rather than incrementing a counter.
This should be enough to get you moving in the right direction. When you have some code, if you still have questions, come back to us and ask.
I recommend using a Set , but here's a way to do it without using a Set. (Note: This will work, but don't ask me about the efficiency of this!)
Have a function like this -
public static boolean isNumberInArray(int[] array, int number)
{
for(int i=0; i<array.length; i++)
{
if(number == array[i])
return true;
}
return false;
}
Now use this function before you make an insert into the new array. I leave you to figure out that part. It's homework after all!
Hints(WATTO explains it better):
a = sorted first array
lastItem = a[0]
append lastItem into new array
for i in 1 to length(a):
if a[i] != lastItem:
append a[i] into new array
lastItem = a[i]
#WATTO Studios has a good approach. Sorting is always useful when duplicates are involved.
I will suggest an alternative method using hash tables:
Create a hashing structure with an integer as key (the number in the original array) and a counter as a value.
Go through the original array and for each number encountered increment it's corresponding counter value in the hash table.
Go through the original array again. For each number check back the hash table. If the counter associated is greater than 1, remove the value and decrement the counter.
Let's see a practical case:
4 5 6 4 1 1 3
First pass will create the following table:
1 -> 2
3 -> 1
4 -> 2
5 -> 1
6 -> 1
Second pass step by step:
4 5 6 4 1 1 3
^
4 has a counter of 2 -> remove and decrement:
1 -> 2
3 -> 1
4 -> 1
5 -> 1
6 -> 1
5 6 4 1 1 3
^
5 has a counter of 1 -> ignore
6 has a counter of 1 -> ignore
4 has a counter of 1 -> ignore
1 has a counter of 2 -> remove and decrement
1 -> 1
3 -> 1
4 -> 1
5 -> 1
6 -> 1
5 6 4 1 3
^
1 has a counter of 1 -> ignore
3 has a counter of 1 -> ignore
Final array:
5 6 4 1 3
There are, of course, more efficient ways to handle the removal (since using an array implies shifting), like inserting the items into a linked list for example. I'll let you decide that. :)
Edit: An even faster approach, requiring a single pass:
Use the same hashing structure as above.
Go through the original array. For each item check the table. If the associated counter is 0, increment it to 1. If it's already 1, remove the item.

Categories