Array of ArrayList with Integers filled with combinations - java

Suppose this, I obtain an array of Integer Wraps Objects...
Integer[] p = new Integer[]{7, 5, 3, 2}; //Variable Length
Now, I want create an Array of ArrayList with next respective values.
2
3
3, 2
5
5, 2
5, 3
5, 3, 2
7
7, 2
7, 3
7, 3, 2
7, 5
7, 5, 2
7, 5, 3, 2
7, 5, 3, 2
What code helps me to create an array with value shown before?
In this code I tried generate:
public static void generateTable(int index, int[] current, int[] values) {
if(index == values.length) {
for(int i = 0; i < values.length; i++) {
System.out.print((current[i]) + " ");
}
System.out.println();
} else {
current[index] = 0;
generateTable(index + 1, current, values);
current[index] = values[index];
generateTable(index + 1, current, values);
}
}
This code only show the combination I want to extract only the before combinations (Except Zero values).
0 0 0 0
0 0 0 2
0 0 3 0
0 0 3 2
0 5 0 0
0 5 0 2
0 5 3 0
0 5 3 2
7 0 0 0
7 0 0 2
7 0 3 0
7 0 3 2
7 5 0 0
7 5 0 2
7 5 3 0
7 5 3 2
I test with this code:
java.util.List<Integer>[] arr = new ArrayList[p.length];
for( int i = 0; i < p.length; i++) {
arr[i] = new ArrayList();
for (int j = 0; j <= i; j++) {
arr[i].add(p[j]);
}
System.out.println(arr[i]);
}
The output for before code is not working properly, is not recursive and doesn't show the omitted value like [5, 3, 2] or [7, 5, 2] , etc!
[7]
[7, 5]
[7, 5, 3]
[7, 5, 3, 2]

Instead of directly converting arrays into List. When you do that 0s will also be picked up and placed in your list. Iterate through each index of your array, find only non-zero elements and put them into your list. Can this help?

Related

I'm trying to get combinations but I don't know how to do it

In a test case, I have 1 2 3 4 as the inputs, I want to get
{1+2, 3+4}
{1+3, 2+4}
{1+4, 2+3}
but I only can do {1+2, 3+4} I can't think of any ways to get {1+3, 2+4}.
I need some algorithm advice, can't think of any conditions to do this.
for (int j=0; j<woodLength.length; j++) {
if (woodLength[j][2] != 1) {
// a function that can create the boards using the wood pieces
for (int i=0; i<woodLength.length; i++) {
// set used boards as 1 and unused as 0
if (woodLength[i][1] != 1) {
woodenBoardHeight.add(woodLength[i][0]+woodLength[i+1][0]);
System.out.println(woodenBoardHeight.get(wBHCount));
wBHCount ++;
woodLength[i][1] = 1;
woodLength[i+1][1] = 1;
}
}
for (int i=0; i<woodLength.length; i++) {
woodLength[i][1] = 0;
}
woodLength[j][2] = 1;
woodLength[j+1][2] = 1;
}
}
this is my code, right now this prints {3,7} but I also want {4,6} and {5,5}
If it's helpful, I'm trying to solve CCC 2017 Senior S3 question
https://www.cemc.uwaterloo.ca/contests/computing/2017/stage%201/seniorEF.pdf
One algorithm to create all the combinations of an array makes use of an unsigned binary counter.
Array: 1 2 3 4
0 0 0 0 [] empty combination
0 0 0 1 [4]
0 0 1 0 [3]
0 0 1 1 [3, 4]
and so on.
In your case, you want the combinations that are 2 digits plus 2 digits. We can achieve this by testing the binary counter and creating the combination when the binary counter has exactly 2 bits on.
Array: 1 2 3 4
0 0 1 1 [3, 4] & [1, 2]
0 1 0 1 [2, 4] & [1, 3]
0 1 1 0 [2, 3] & [1, 4]
1 0 0 1 [1, 4] & [2, 3]
1 0 1 0 [1, 3] & [2, 4]
1 1 0 0 [1, 2] & [3, 4]
In your example, the order of the pairs is not important. You can eliminate the duplicate pairs, and you have the three conditions you're looking for.
Use this code to get the solution as expected
public static void main(String[] args) {
List<Integer> num;
Integer[] numArray = {1,2,3,4};
num = Arrays.asList (numArray);
List<Integer> newList = new ArrayList<> ();
for(int i=1;i<num.size ();i++) {
int[] intArray = new int[2];
newList.addAll (num);
newList.remove (0);
newList.remove (i-1);
intArray[0]=num.get (0)+num.get (i);
intArray[1] = newList.get (0)+newList.get (1);
System.out.println ("{"+intArray[0]+","+intArray[1]+"}");
}
}
The Result will be like this :
{3,7}
{4,6}
{5,5}

Can't understand this programming question about matrix?

Can anyone help me out? I can't understand this programming question in Java? What does the greatest sum mean here in the matrix? In case 1, if I add each number from 5 in first row to 1 in last row, it doesn't add to 15. So why the output resulted in: 15 1 and 12 1 for case 2?
Problem#1
You will be given a square matrix of N rows and N columns (1 == N<= 1000) containing positive and negative integers with absolute value not larger than 1000.
You are required to compute the greatest sum achievable by walking a path, starting at any cell of the matrix and always moving downwards or rightwards.
Additionally, you have to report the number of times that value is achievable. N will be in the first line of the input. N lines follow with N integers each. You should output a single line with two integers separated by a single blank space: first one is the greatest sum, second one is the number of times this value can be reached.
Case 1:
For the input provided as follows:
5
3 1 -2 1 1
-6 -1 4 -1 -4
1 1 1 1 1
2 2 2 2 2
1 1 1 1 1
Output of the program will be:
15 1
Case 2:
For the input provided as follows:
3
1 1 1
2 2 2
3 3 3
Output of the program will be:
12 1
The first 3 and 5 input is the size of the matrix 3 x 3 and 5 x 5 is should not counted for addition
as the rule says that you are not allowed to turn left or move up when traversing, below is a simple traversal right direction and bottom direction
12 means 1 + 2 + 3 + 3 + 3 times should be 1, because only in one path this values can be reached
15 means 3 + 1 -1 + 4 + 1 + 2 + 2 + 2 + 1 times should be 1, because only in path this value can be achieved
you need to program 2 x 2 kernel loop which will find the 2 biggest sum number and identify the direction of flow, then jump follow that direction and choose another 2 x 2 and keep on looping, no need to random direction
but, there is a trick here, if you get 2 big numbers there is a possibility that a second path you need to follow
to achieve the second path either you can go for double iteration or single iteration by processing two direction within a singe loop, a simple example of two directions
1 1 0 0 0
2 1 1 0 0
0 2 1 0 0
0 2 1 1 1
0 2 2 2 1
This is only a random solution I provided, but finding weights of the each 2x2 matrices and use tree based traversal, Convolution kernels.... etc should be the best way
This answer is a modification of the algorithm for the "Unique Paths" problem I wrote here: Trying to solve the “Unique Paths” problem, but getting the wrong answer. That other challenge had the same constraint, you can only move down and right, which is why a similar algorithm works.
In this case, we can start at the top-left. We need to maintain 2 arrays, one for the sum achievable for a given cell, and one for the count of paths to get that sum. We also need two variables for the highest sum/count achievable overall (maxSum and maxCount). All of these are initialized to 0's.
For each cell, there are 3 "paths" leading here, and we calculate what the sum/count would be for each of those paths (if possible), where row is an array of the matrix values for the current row being processed:
From above:
The sum/count values are currently the accumulated values from the previous row. Since sum/count values were initialized to 0's, they can be used even when processing the first row.
sumAbove = sum[col] + row[col]
countAbove = count[col]
From the left:
The sum/count values are currently the accumulated values from the previous cell of the current row, because we just updated that when iterating from left to right.
sumLeft = sum[col - 1] + row[col] or row[col] if col == 0
countLeft = count[col - 1] or 0 if col == 0
Starting here:
sumStart = row[col]
countStart = 1
We then find the highest sum of the three, and set the new sum[col] to that value. The new count[col] value will be the sum of the counts where the sum is the max, e.g. if all 3 sums are the same, then count[col] = countAbove + countLeft + countStart.
If the new sum[col] is higher than maxSum, then we update maxSum/maxCount to these new values. If the new sum[col] equals maxSum, we add the new count[col] to maxCount.
Let us use the following matrix as an example:
3 1 -4 1 3
-6 -1 4 -1 -4
1 1 1 1 1
-1 2 2 1 1
12 -5 1 1 0
We start with all 0's.
sum = { 0, 0, 0, 0, 0 }, count = { 0, 0, 0, 0, 0 }, maxSum = 0, maxCount = 0
Process the first row:
row: { 3, 1, -4, 1, 3 }
bestPath: { start, left, left, left/start, left }
sum = { 3, 4, 0, 1, 4 }, count = { 1, 1, 1, 2, 2 }, maxSum = 4, maxCount = 2
For the first three, there is one path to get those sums, i.e. starting at 0,0. For the last two, there are two paths to get those sums, i.e. starting at 0,0 or 3,0 (col,row). To clarify that, we showed the which path lead to the new values labeled bestPath.
Process the second row:
row: { -6, -1, 4, -1, -4 }
bestPath: { above, above, left, left, left }
sum = { -3, 3, 7, 6, 2 }, count = { 1, 1, 1, 1, 1 }, maxSum = 7, maxCount = 1
Process the third row:
row: { 1, 1, 1, 1, 1 }
bestPath: { start, above, above, above, above }
sum = { 1, 4, 8, 7, 3 }, count = { 1, 1, 1, 1, 1 }, maxSum = 8, maxCount = 1
Process the fourth row:
row: { -1, 2, 2, 1, 1 }
bestPath: { above, above, above, left, left }
sum = { 0, 6, 10, 11, 12 }, count = { 1, 1, 1, 1, 1 }, maxSum = 12, maxCount = 1
Process the fifth row:
row: { 12, -5, 1, 1, 0 }
bestPath: { start/above, left, above, above/left, above/left }
sum = { 12, 7, 11, 12, 12 }, count = { 2, 2, 1, 2, 3 }, maxSum = 12, maxCount = 9
Final result:
12 9
With an N x N matrix, this code has excellent O(m) time complexity, where m = N², i.e. the number of cells in the matrix, and O(N) aka O(sqrt m) storage complexity.
Here's the code of implementation using python.
Two matrices are used for testing.
def findMaximumPath(mat):
rows = cols = len(mat)
count_list = []
for i in range(rows):
summ = 0
mat_index = [rows-1, cols-1]
curr_index = [0, i]
summ = mat[curr_index[0]][curr_index[1]]
while curr_index[0] != rows-1 and curr_index[1] != cols-1:
if mat[curr_index[0]][curr_index[1]+1] > mat[curr_index[0]+1][curr_index[1]]:
curr_index[1] = curr_index[1] + 1
else:
curr_index[0] = curr_index[0] + 1
summ += mat[curr_index[0]][curr_index[1]]
#print(str(curr_index) + " Sum: " + str(summ))
if curr_index[0] != rows-1 and curr_index[1] == cols-1:
for i in range(curr_index[0]+1, rows):
summ += mat[i][cols-1]
#print(str(i) + " Sum1: " +str(summ))
if curr_index[0] == rows-1 and curr_index[1] != cols-1:
for i in range(curr_index[1]+1, cols):
summ += mat[rows-1][i]
#print(str(i) + " Sum2: " +str(summ))
count_list.append(summ)
max_sum = max(count_list)
count = 0
for element in count_list:
if(element == max_sum):
count+= 1
print(count_list)
print("Maximum Sum: " + str(max_sum))
print("Number of Occurrences: " + str(count) + "\n")
mat1 = ([[3, 1, -2, 1, 1],
[-6, -1, 4, -1, -4],
[1, 1, 1, 1, 1],
[2, 2, 2, 2, 2],
[1, 1, 1, 1, 1]])
mat2 = ([[1, 1, 1],
[2, 2, 2],
[3, 3, 3]])
findMaximumPath(mat1)
findMaximumPath(mat2)
Output:
Matrix 1:
[15, 12, 10, 2, 1]
Maximum Sum: 15
Number of Occurrences: 1
Matrix 2:
[12, 9, 6]
Maximum Sum: 12
Number of Occurrences: 1

Java Permutation Assignment

Main class:
import java.util.List;
import java.util.Random;
public class PermutationGenerator{
public static void main(String[] args) {
Random bruh = new Random();
List<Integer> filledArray = nextPermutation.fillArray();
int[] randomArray = new int[10];
for (int i = 0; i < randomArray.length; i++) {
int randomPosition = bruh.nextInt(10 - i) + 1;
randomArray[i] = filledArray.get(randomPosition);
filledArray.remove(randomPosition);
}
System.out.print("List 1: ");
printArray(randomArray);
}
public static void printArray(int[] array) {
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
System.out.println();
}
}
Runner Class:
`import java.util.ArrayList;
public class nextPermutation {
public static ArrayList<Integer> fillArray() {
ArrayList<Integer> randomArray = new ArrayList<Integer>();
randomArray.add(0);
randomArray.add(1);
randomArray.add(2);
randomArray.add(3);
randomArray.add(4);
randomArray.add(5);
randomArray.add(6);
randomArray.add(7);
randomArray.add(8);
randomArray.add(9);
randomArray.add(10);
return randomArray;
}
}
`
I'm supposed to print out something like this:
List 1: 4 6 8 1 9 7 10 5 3 2
List 2: 6 8 1 7 3 4 9 10 5 2
List 3: 2 4 9 6 8 1 10 5 7 3
List 4: 8 5 4 3 2 9 6 7 1 10
List 5: 10 3 2 6 8 9 5 7 4 1
List 6: 9 10 3 2 1 5 6 8 4 7
List 7: 3 8 5 9 4 2 10 1 6 7
List 8: 3 2 4 5 7 6 9 8 10 1
List 9: 4 1 5 10 8 3 6 2 7 9
List 10: 3 5 2 4 1 7 9 6 8 10
But for me, it only prints out one line.
I think I can use a for loop in order to do this. Alternatively, I could just brute force it but I prefer the former.
What I need help on is where and how I should start the for loop.
Any help would be appreciated.
Simply I defined your part of your code in a method mixArray()
Then I added a for loop that runs 10 times to print 10 lists.
The for loop in printArray does run 10 times but it prints 1 number and a space during
each loop so that's why you were getting just 1 line at the end.
for (int p = 1; p <= 10; p++) {
mixArray();
System.out.print("List "+p+": ");
printArray(randomArray);
System.out.println();
}
public static void mixArray() {
for (int i = 0; i < randomArray.length; i++) {
int randomPosition = bruh.nextInt(10 - i) + 1;
randomArray[i] = filledArray.get(randomPosition);
filledArray.remove(randomPosition);
}
}
Also you might wanna keep in mind that your randomizing the array method might give you back a duplicate array. The chances are very low but it is possible.
a lot cleaner to simply use Collections::shuffle
List<Integer> filledArray = fillArray();
for (int i = 0; i < 10; i++)
{
Collections.shuffle(filledArray);
System.out.println(filledArray);
}
output
[7, 0, 3, 5, 2, 1, 9, 10, 4, 8, 6]
[3, 7, 6, 0, 1, 8, 4, 5, 9, 2, 10]
[3, 7, 2, 4, 9, 10, 0, 8, 5, 1, 6]
[8, 1, 0, 7, 4, 2, 3, 6, 10, 9, 5]
[2, 3, 8, 4, 5, 10, 9, 1, 6, 7, 0]
[10, 2, 0, 1, 5, 8, 7, 6, 9, 3, 4]
[1, 5, 0, 9, 2, 4, 6, 8, 10, 7, 3]
[2, 8, 1, 9, 7, 3, 5, 6, 10, 4, 0]
[9, 1, 2, 4, 6, 8, 0, 3, 10, 5, 7]
[4, 5, 2, 3, 10, 9, 6, 8, 0, 1, 7]

Extract groups of characters in a string

I have a string 123456789I also have a bunch of numbers (identities, if you will) such as
2 1 1 1 2 2
2 1 1 1 3 1
2 1 1 2 1 2
2 1 1 2 2 1
2 1 1 3 1 1
The idea is, these numbers specify the groups of digits that should be extracted from the string (left to right order, if that matters). Therefore, a number like 2 3 2 1 1 means Output the first 2 characters, then the next 3 characters, then the next 2 characters, then the next 1 character, then finally the last 1 character remaining.So as examples,2 1 1 1 2 2 should output 12 3 4 5 67 892 1 1 1 3 1 should output 12 3 4 5 678 92 1 1 2 1 2 should output 12 3 4 56 7 892 1 1 2 2 1 should output 12 3 4 56 78 92 1 1 3 1 1 should output 12 3 4 567 8 9
I tried working with the method charAt() but it would seem that's just not for me
public static void main(String[] args) {
String mine = "123456789";
System.out.println(mine.charAt(2)+"\t"+mine.charAt(1)+"\t"+
mine.charAt(1)+"\t"+mine.charAt(1)+"\t"+mine.charAt(2)
+"\t"+mine.charAt(2));
}
The above gives an unwanted output
3 2 2 2 3 3
How do I solve this rather tricky (for me) issue ?
This should do the work for you.
public static void main(String[] args){
String identities = "2 1 1 1 3 1";
String stringToBreakApart = "123456789";
StringBuilder sb = new StringBuilder();
int currentPosition = 0;
for(String identityString : identities.split(" ")){
int identity = Integer.parseInt(identityString);
sb.append(stringToBreakApart, currentPosition, currentPosition += identity);
sb.append(" ");
}
System.out.println(sb.toString());
}
I've given a simple trial on it. Does below give you some help?
public static void main(String[] args) {
int[][] identitiesBunch = new int[][] {
{2, 1, 1, 1, 2, 2},
{2, 1, 1, 1, 3, 1},
{2, 1, 1, 2, 1, 2},
{2, 1, 1, 2, 2, 1},
{2, 1, 1, 3, 1, 1}
};
String mine = "123456789";
char[] numbers = mine.toCharArray();
int index = 0;
for (int[] identities: identitiesBunch) {
for (int id: identities ) {
for (int i = 0 ; i < id; i++)
System.out.print(numbers[index++]);
System.out.print(' ');
}
index = 0;
System.out.println();
}
}

Is there any way to use for loop to print values in certain range but with a specific order- java [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 6 years ago.
Improve this question
I'm sorry if my question is not very clear because i can't find any other way on how to explain it better.
I want to do something like this by using for loop:
First iteration : 0 , 1, 2, 3, 4,
Second iteration: 1, 2, 3, 4, 0
Third Iteration : 2, 3, 4, 0, 1
Fourth Itertaion : 3, 4, 0, 1, 2
Fifth iteration : 4, 0, 1, 2, 3
Final Iteration : 0, 1, 2, 3, 4
It will print value from 0 to 4 on the first iteration.
And then for the second iteration and the followings the pattern will continue as shown above.
Is it possible to do this using for loop in java?
What's wrong with
int iterations = 6;
for (int n = 0; n < iterations; n++) {
for (int i = 0; i < iterations - 1; i++) {
int value = (i + n) % (iterations - 1);
System.out.print(value + " ");
}
System.out.println();
}
Outputs
0 1 2 3 4
1 2 3 4 0
2 3 4 0 1
3 4 0 1 2
4 0 1 2 3
0 1 2 3 4
Without more information there's not much else to try. The modulo operator is your friend here, I suggest learning about it.
To rotate the array, start by saving the first element and then set every element from the first to the penultimate (that's the next to last) to the next value. Finally, set the last value to the first (that you saved). Something like,
private static void rotate(int[] arr) {
int first = arr[0];
for (int i = 0; i < arr.length - 1; i++) {
arr[i] = arr[i + 1];
}
arr[arr.length - 1] = first;
}
Then, clone the original array and iterate with a do while loop until your array equals its' original state. Something like,
int[] arr = { 0, 1, 2, 3, 4 };
int[] original = arr.clone();
do {
System.out.println(Arrays.toString(arr));
rotate(arr);
} while (!Arrays.equals(arr, original));
System.out.println(Arrays.toString(arr));
Which outputs (as requested)
[0, 1, 2, 3, 4]
[1, 2, 3, 4, 0]
[2, 3, 4, 0, 1]
[3, 4, 0, 1, 2]
[4, 0, 1, 2, 3]
[0, 1, 2, 3, 4]
Also, in Java 8+, you might generate your array with
int[] arr = IntStream.rangeClosed(0, 4).toArray();

Categories

Resources