Arraylist pair comparison? - java

Currently I have an arrayList which contains several value pairs. I'm trying to print them in matrix format as shown in the example below. Every odd number is the location in the matrix and the following number is the value. The location goes up as in a counter and if the number doesn't exist in the array a 0 is placed in it's location. Bit tricky to explain.
arraylist contains (1, 10, 2, 90, 4, 9, 7, 2, 11, 4, 14, 45)
Output:
0 10 90 0
9 0 0 2
0 0 0 4
0 0 45 0
I've tried:
int position, value;
int size = 16;
for (int i = 0 ; i < size ; i += 2) {
position = matrix.get(i);
if(position == i){
value = matrix.get(i+1);
System.out.print(value);
} else {
System.out.print("0");
}
}

You want to read numbers in your array not one after one, but two after two. Try this (this is not enough to solve your problem, but this will help) :
for (int i = 0 ; i < size ; i += 2) {
int position = matrix.get(i);
int value = matrix.get(i+1);
... // Deal with them
}
To actually fill the matrix with the right values, you should use a Map<Integer, Integer>.

You can increment by more than 1 in a for loop, e.g.
for(int i = 0, size = matrix.size( ); i < size ; i = i+2)
{
...
}

Related

Copying 2x2 array contents into 4x6 array in Java

I'm new to Java programming and my assignment was to copy the content of 2x2 two dimensional array into the middle 4x6 two-dimensional array. I did it anyway but it doesn't print out the way I wanted and I dont know why. Can someone help me identify the problem in my source program. Thanks in advance
public class Main {
public static void main(String[] args) {
int[][] a = {{11,12},{21,22}};
int[][] b = new int[4][6];
System.out.print("a[][] = \n");
output(a);
System.out.print("\nb[][] = \n");
copy(a,b);
}
static void output(int[][] x) {
for(int i=0; i<x.length;i++) {
for(int j=0;j<x[i].length;j++) {
System.out.printf(" %2d ", x[i][j]);
}
System.out.println();
}
}
static void copy(int[][] source, int[][] destination) {
for(int i=0;i<source.length;i++) {
destination[i]= new int[source.length];
System.arraycopy(source[i], 0, destination[i+1], 2, destination[i].length);
}
output(destination);
}
}
The result should be
a[][]
11 12
21 22
b[][]
0 0 0 0 0 0
0 0 11 12 0 0
0 0 21 22 0 0
0 0 0 0 0 0
but I got
a[][] =
11 12
21 22
b[][] =
0 0
0 0
0 0 21 22 0 0
0 0 0 0 0 0
instead.
You are doing several things wrong:
replacing the destination row with an empty array of source size.
using the destination length instead of the source length
Here is how it should look.
static void copy(int[][] source, int[][] destination) {
for (int i = 0; i < source.length; i++) {
System.arraycopy(source[i], 0, destination[i + 1], 2,
source[i].length);
}
output(destination);
}
I have included a more general solution as follows:
Not all arrays will lend themselves to this kind of copy. I return a boolean if the copy was successful or not. Here are some guidelines.
Copying to center implies the same number of unfilled rows above and below, or the same number of unfilled columns to the left or right. This can be determined by subtracting the smallest dimension from the largest and seeing if the remainder when divided by two equals zero. If so, the copy should succeed and true is returned. Else, an informational message is printed and false is returned.
The starting location of each row or column is determined by subtracting the shorter dimension from the longer one and dividing by two.
The loop iterates over the source array while the System.arraycopy does the work of copying to the destination, incrementing the destination row index.
int[][] arr = { { 11, 12}, { 21,22}};
int[][] dest = new int[4][6];
if (copyToCenter(arr, dest)) {
for (int[] rows : dest) {
System.out.println(Arrays.toString(rows));
}
}
prints
[0, 0, 0, 0, 0, 0]
[0, 0, 11, 12, 0, 0]
[0, 0, 21, 22, 0, 0]
[0, 0, 0, 0, 0, 0]
The copy method.
static boolean copyToCenter(int[][] source, int[][] destination) {
if ((destination.length - source.length) % 2 != 0
|| (destination[0].length - source[0].length) % 2 != 0) {
System.out
.println("Arrays do not lend themselves to required copy");
return false;
}
int firstCol = (destination[0].length - source[0].length) / 2;
int destRow = (destination.length - source.length) / 2;
for (int[] sourceRow : source) {
System.arraycopy(sourceRow, 0, destination[destRow++],
firstCol, source[0].length);
}
return true;
}

How to count all possible cases?

For example I have array with length n=3:
for(int i = 0; i < n; i++) {
array[i] = i;
}
So the cases should be:
1. 0
2. 1
3. 2
4. 0 1
5. 0 2
6. 1 2
7. 0 1 2
So the number of cases should be 7 for n = 3.
In my code:
int n = 3;
int[] array = new int[n];
for (int i = 0; i < n; i++) {
array[i] = i;
}
int sum = 0;
for (int i = 0; i < n; i++) {
System.out.println(array[i] + " ");
sum++;
for (int j = i; j < n; j++) {
System.out.print(array[j] + " ");
}
System.out.println();
sum++;
}
System.out.println("sum = " + sum);
Output is:
0
0 1 2
1
1 2
2
2
sum = 6
The number 2 is two times so it is wrong and sum is actually = 5. And I don't get cases
4. 0 1
and
5. 0 2
How to count all possible cases?
Sets, not arrays
The first important observance is that you are not using fixed length arrays here but sets of different lengths.
Take a look at your example. You allow
0
1
2
0, 1
0, 2
1, 2
which are not all of size 3.
Also you don't differentiate between
0, 1
1, 0
so order doesn't matter, like in sets.
Power set
That's why you're actually describing power sets here. For the example set {0, 1, 2} its power set is defined as
P({0, 1, 2}) = {
{}, // empty set
{0},
{1},
{2},
{0, 1},
{0, 2},
{1, 2},
{0, 1, 2}
}
Fortunately there exists an easy closed formula for their size. If n is the size of the input set the size of the power set is
2^n
But they also count the empty set, so you will need to -1 if you don't want that:
2^n - 1
Solution
Thus in Java you could write
int Set<Integer> input = ...
int size = (int) Math.pow(2, input.size()) - 1;
and that's all, you don't need to build the contents manually.
But if you're curious and want to build them, take a look at questions like Obtaining a powerset of a set in Java. It's an implementation of the recursive formula shown at Wikipedia.
So, totally inefficient but also working:
int Set<Integer> input = ...
// Build the power-set using the method from linked question
Set<Set<Integer>> power = powerSet(input);
int size = power.size() - 1;

Triangular matrix get() in one dimensional array

I want to save a triangular matrix in a 1 dim array (to minimize needed space, all zeros are left out) and create a function get() to find a specific entry from the original matrix.
For example:
Lets look at the following triangular matrix :
0 1 2 3
0 0 4 5
0 0 0 6
0 0 0 0
I am saving this matrix like this:
double[] test = {1,2,3,4,5,6};
So all the zeros are left out.
I want to write a function that gives me a value of the original matrix:
get(3,4)
should give me 6
I am checking the input to see if its out of bound and if it is below or on the diagonal.
//Checking if input is valid
if (i <= n && j <= n && i >= 1 && j >= 1){
if( j <= i ){
return 0.0;
}else {
}
}
This works.
How do I proceed though? I have trouble finding the equivalent matrix entry in my array.
Any help would be appreciated.
EDIT:
My whole code:
public class dreiecksmatrix {
int n = 4;
double[] a = {1,2,3,4,5,6};
public double get( int i, int j){
//Checking if input is valid
if (i <= n && j <= n && i >= 0 && j >= 0){
if( j <= i ){
return 0.0;
}else {
}
}
return 1.0;
}
public static void main(String [] args ){
dreiecksmatrix test = new dreiecksmatrix();
System.out.println(test.get(2,3));
}
}
Here is the sample code calculating the value of top-triange. No corner cases check like i,j >= 1 yet, but it's easy to add them.
arr = [[0, 1, 2, 3, 4],
[0, 0, 5, 6, 7],
[0, 0, 0, 8, 9],
[0, 0, 0, 0, 10],
[0, 0, 0, 0, 0]];
flatArr = [1,2,3,4,5,6,7,8,9,10];
n = 5; // matrix size
i = 1;
j = 3;
if (j <= i) {
alert(0);
} else {
pos = 0;
// find an offset caused by first (i - 1) lines
for (k = 1; k < i; k++) {
pos += n - k;
}
// find an offset in line x
pos += j - i;
// array index start from 0 so decrement value
pos = pos - 1;
alert('flatArr[' + pos + '] = ' + flatArr[pos]);
}
If you were instead to store the matrix by columns, there is a simple formula for the index into test of the i,j'th matrix element.
In your example you would have
double[] test = {1,2,4,3,5,6};
If Col(i) is the index pf the start of column i
then
Col(2) = 0
Col(3) = Col(2) + 1
..
Col(n) = Col(n-1) + n-1
Hence
Col(j) = ((j-1)*(j-2))/2
The i,j matrix element is stored i further on from the start of column j,
ie at Col(j)+i, so that you should add
return test[ ((j-1)*(j-2))/2 + i];
to your code
There is an analogous formula if you must store by rows rather than columns. It's a wee bit messier. The idea is to first figure out, starting with the last non-zero row, where the ends of the rows are solved.

ArrayList Removing first element

This is the given question:
Given a non-negative number represented as an array of digits,
add 1 to the number ( increment the number represented by the digits ).
The digits are stored such that the most significant digit is at the head of the list.
Example:
If the vector has [1, 2, 3]
the returned vector should be [1, 2, 4]
as 123 + 1 = 124.
This is my code:
public class Solution {
public ArrayList<Integer> plusOne(ArrayList<Integer> A) {
int carry = 1;
int length = A.size();
ArrayList result = new ArrayList();
for( int i = length - 1; i >=0; i-- ){
int val = A.get(i) + carry;
result.add(0,val % 10);
carry = val / 10;
}
if (carry == 1){
result.add(0,1);
}
for (int j = 0; j < result.size(); j++){
if(result.get(j).equals(0))
result.remove(j);
else
break;
}
return result;
}
}
However, in the test case:
A : [ 0, 6, 0, 6, 4, 8, 8, 1 ]
it says my function returns
6 6 4 8 8 2
while the correct answer is
6 0 6 4 8 8 2
I have no idea what is wrong with my code.
Thanks!
if(result.get(j).equals(0))
result.remove(j);
else
break;
This will fail if every other index contains a 0. Here's what happens:
0 6 0 6 4 8 8 2
^ (j = 0)
The 0 will be removed, and j is incremented by one.
6 0 6 4 8 8 2
^ (j = 1)
Then this 0 is removed as well, skipping the first 6 in your array. To fix this, change the snippet to:
if(result.get(j).equals(0))
result.remove(j--);
else
break;
This compensates for when an index is removed so that j will not skip the number immediately after any removed 0s.
Check out a similar question at Looping through and arraylist and removing elements at specified index
simpler to do just
while (!result.isEmpty() && result.get(0).equals(0)) {
result.remove(0);
}
This will keep removing the left most 0 until there is no more left most zero to be deleted.
Your last for loop is removing 0 from your result ArrayList<Integer>. After removing that loop, you will get perfect output
public static ArrayList<Integer> plusOne(ArrayList<Integer> A) {
int carry = 1;
int length = A.size();
ArrayList result = new ArrayList();
for (int i = length - 1; i >= 0; i--) {
int val = A.get(i) + carry; //2 8
result.add(0, val % 10); // 2 8
carry = val / 10;
}
if (carry == 1) {
result.add(0, 1);
}
// for (int j = 0; j < result.size(); j++) {
// if (result.get(j).equals(0))
// result.remove(j);
// else
// break;
// }
for (boolean isZero = true; isZero; ) {
isZero = result.get(0).equals(0);
if(isZero)
result.remove(0);
}
return result;
}

array in java methods, what is executed?

I have been struggling with this java problem for several days now, and now I have to give up. I have been told the answer which should be 5 5 3 3, but I cannot in any way see how it is possible to get that result.
Given the following java method:
public int[] methodName(int[] nums)
{
int largestOdd=0;
for(int i=nums.length-2;i>=0;i--)
{
if (nums[i+1] % 2 != 0 && nums[i+1] > largestOdd)
largestOdd = nums[i+1];
if (nums[i] == 0)
nums[i] = largestOdd;
}
return(nums);
}
What is printed when the following Java statements are executed?
int[] nums = {0,5,0,3};
nums = methodName(nums)
for (int i = 0; i<nums.length;i++)
System.out.print(nums[i] + "");
System.out.println();
It just doesnt make any sense for me that first of all it will start printing "5". In my opinion it should be "3" because nums[2+1] = 3 (last index element)
Second of all why will it print four numbers when the loop in the method only will loop through 3 times until hitting -1 ?
If someone can explain how to get the result in a understandable way, I would be very happy.
Thanks in advance
methodName runs backwards through the array, examining every pair of numbers. In this case, the first pair examined will be (0,3).
As it runs over the pairs, methodName keeps track of the largest odd number seen (it looks at the second number of each pair for this).
Whenever the first number is zero, it sets it to the largest odd number seen so far.
So in this case, it will:
Look at (0,3).
Is 3 odd? Yes. Is it the largest odd number seen so far? Yes. So keep track of 3.
Is 0 zero? Yes. So set it to 3. Now the array is {0, 5, 3, 3}.
Move our indices back by 1 and look at (5, 3).
Is 3 odd? Yes. Is it the largest odd number seen so far? No.
Is 5 zero? No.
Move our indices back by 1 and look at (0, 5).
Is 5 odd? Yes. Is it the largest odd number seen so far? Yes. So keep track of 5.
Is 0 zero? Yes. So set it to 5. Now the array is {5, 5, 3, 3}.
We are already at the beginning of the array, so we can't go back any further.
Return to the main method, and print the contents of the array.
{0,5,0,3}
for(int i=nums.length-2;i>=0;i--) // starts at 0 (index 2) <-> num.length 4 - 2
// runs 3 times num.length(4) - 2 = 0
if (nums[i+1] % 2 != 0 && nums[i+1] > largestOdd)
largestOdd = nums[i+1]; <--> // 3
// if odd and grater than 0
// first iteration largestOdd = 3
if (nums[i] == 0) // still i is index 2 {0, 5, 0, 3} = 0, so true
nums[i] = largestOdd; // nums[i] (index 2) = 3
// after first iteration
{0, 5, 3, 3}
Second iteration do nothing (0 is not odd)
Third iteration, do same as first iteration, making final array
{5, 5, 3, 3}
Next Part
// This method returns the same array you passed into to
public int[] methodName(int[] nums)
{
return(nums);
}
// So
nums = methodName(nums) = {5, 5, 3, 3} The new array produced by the method
you can analyse step by step.
In the for-loop: i starts from 2 to 0;
num = [0,5,0,3]
1.
i = 2; largestOdd = 0; nums[i+1] = nums[3] = 3; nums[i] = nums[2] = 0;
first condition "(nums[i+1] % 2 != 0 && nums[i+1] > largestOdd)" is true
largestOdd = nums[i+1] = 3
second condition (nums[i] == 0) is true
nums[i] = nums[2] = largestOdd = 3
nums = [0,5,3,3];
2.
i=1; largestOdd = 3; nums[i+1] = nums[2] = 3; nums[i] = nums[1] = 5;
first condition is false;
second condition is false;
nums = [0,5,3,3];
3.
i=0; largestOdd = 3; nums[i+1] = nums[1] = 5; nums[i] = nums[0] = 0;
first condition is true
largestOdd = 5;
second condition nums[0] = 0 is true
nums[0] = largestOdd = 5;
nums = [5,5,3,3];
Loop 1 start i=2,nums=[0,5,0,3],largestOdd=0
because:(nums[2+1]=3)/2 !=0 && (nums[2+1]=3)>(largestOdd=0)
so:largestOdd=(nums[2+1]=3)=3
beacuse:(nums[2]=0) ==0
so:nums[2]=(largestOdd=3)=3
Loop 1 end i=2,nums=[0,5,3,3],largestOdd=3
Loop 2 start i=1,nums=[0,5,3,3],largestOdd=3
because:(nums[1+1]=3)/2 !=0 && (nums[1+1]=3)>(largestOdd=3)
so:next
beacuse:(nums[1]=5) !=0
so:next
Loop 2 end i=1,nums=[0,5,3,3],largestOdd=3
Loop 3 start i=0,nums=[0,5,3,3],largestOdd=3
because:(nums[0+1]=5)/2 !=0 && (nums[0+1]=5)>(largestOdd=3)
so:largestOdd=(nums[0+1]=5)=5
beacuse:(nums[0]=0) ==0
so:nums[0]=(largestOdd=5)=5
Loop 3 end i=0,nums=[5,5,3,3],largestOdd=5
END LOOP

Categories