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();
}
}
Related
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 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
I have a 2D array called board:
2 3 4 5 6 7
3 5 6 7 8 5
3 5 6 7 8 7
I want the value at row 2 and col 3 so I do:
Scanner keyboard = new Scanner(System.in);
int row = keyboard.nextInt()-1;
int col = keyboard.nextInt()-1;
System.out.println(board[row][col]);
I input 2 and 3 which gave me 6, but what I want to do it instead of having row name as numbers such as 0, 1, 2..., I want them to be A, B, C, so it will look like this:
0 1 2 3 4 5 - "name"
A 2 3 4 5 6 7
B 3 5 6 7 8 5
C 3 5 6 7 8 7
So instead of entering 2 and 3 for row and col I will enter B3.
How do I change that?
You can read the "B3" in a string. For the row, 'B' - 'A' now is the index to your board; for the column index, use '3' - '0'.
Remember characters differ from the digits by only an offset.
You can use Map to accomplish that:
Map<String, int[]> matrix = new HashMap<>();
// I assume you have a process to store the input data into the Map
matrix.put("A", new int[]{ 2, 3, 4, 5, 6, 7 });
matrix.put("B", new int[]{ 3, 5, 6, 7, 8, 5 });
matrix.put("C", new int[]{ 3, 5, 6, 7, 8, 7 });
Scanner keyboard = new Scanner(System.in);
String row = keyboard.next();
int col = keyboard.nextInt() - 1;
System.out.println(matrix.get(row)[col]);
Hope it helps!
Well you just have to write a method that changes a 2 char string input into 2 numbers in which you then use to print out the number you want.
ex: "A1"
if the first char = "A", i = 0;
if the second char = "1", j = 1;
hope this helps
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?
Let's say I have a list [x1, x2, x3] where x1, x2, and x3 can take on any value between 1 and 5.
I want to iterate over every possible list that can be created (From [1, 1, 1], [1, 1, 2], . To [5, 5, 5]). This is an easy problem with only 3 elements in the list.
You can do something like this:
for x = 1; x <= 5; x++;
for y = 1; y <= 5; y++;
...
for q = 1; q <= 5; q++;
create list [x, y, ..., q];
do something with the list;
However, how do you iterate over every possible list where the number of elements is over like 10?
Edi: I've added Java as a constraint. I just want to see how this would be done without too many fancy library calls.
Edit2: What I am really looking for is some algorithm to do this, not what sort of libraries can be used to do it. But what I'm looking for is really a language-independent algorithm.
Using Guava you can do it easily:
public static void main(String[] args) {
int lowerBound = 1;
int upperBound = 5;
int setSize=3;
ContiguousSet<Integer> integers = ContiguousSet.create(Range.closed(lowerBound, upperBound), DiscreteDomain.integers());
List<Set<Integer>> sets = Lists.newArrayList();
for (int i = 0; i < setSize; i++) {
sets.add(integers);
}
Set<List<Integer>> cartesianProduct = Sets.cartesianProduct(sets);
for (List<Integer> list : cartesianProduct) {
System.out.println(list);
}
}
Which prints:
[1, 1, 1]
[1, 1, 2]
[1, 1, 3]
[1, 1, 4]
[1, 1, 5]
...
[5, 5, 4]
[5, 5, 5]
Logic :
In arr[x1 x2 x3]; all x1, x2, x3 can have values from 1 to 5. Which means every position in array can have value from 1 to 5. For a value at current position all the values are possible at next position.
suppose at 0 position of array value stored is 1.
[1 _ _] _ represent there is no value.
values for the next position : [1 1 _] , [1 2 _] ,[1 3 _] ,[1 3 _] ,[1 4 _],[1 5 _].
So iterate over current position to store the different possible values from 1 to 5 at current position and for each value call the permutate function again with current position value incremented by 1 for iterating all possible values from 1 to 5 at next position .
Code :
public class permutation {
static int limit;
public static void permutate(int arr[],int curPos)
{
int i;
if(curPos==arr.length)
{
for(i=0;i<arr.length;i++)
{
System.out.print(arr[i] + "\t");
}
System.out.println("");
return;
}
for(i=1;i<=limit;i++)
{
arr[curPos]=i;
permutate(arr,curPos+1);
}
}
public static void main(String[] args) {
int arr[] = new int[3];
limit = 5;
permutate(arr,0);
}
}
Output :
1 1 1
1 1 2
1 1 3
1 1 4
1 1 5
1 2 1
1 2 2
1 2 3
1 2 4
1 2 5
1 3 1
1 3 2
1 3 3
1 3 4
1 3 5
1 4 1
1 4 2
1 4 3
1 4 4
1 4 5
1 5 1
1 5 2
1 5 3
1 5 4
1 5 5
2 1 1
2 1 2
2 1 3
2 1 4
2 1 5
2 2 1
2 2 2
2 2 3
2 2 4
2 2 5
2 3 1
2 3 2
2 3 3
2 3 4
2 3 5
2 4 1
2 4 2
2 4 3
2 4 4
2 4 5
2 5 1
2 5 2
2 5 3
2 5 4
2 5 5
3 1 1
3 1 2
3 1 3
3 1 4
3 1 5
3 2 1
3 2 2
3 2 3
3 2 4
3 2 5
3 3 1
3 3 2
3 3 3
3 3 4
3 3 5
3 4 1
3 4 2
3 4 3
3 4 4
3 4 5
3 5 1
3 5 2
3 5 3
3 5 4
3 5 5
4 1 1
4 1 2
4 1 3
4 1 4
4 1 5
4 2 1
4 2 2
4 2 3
4 2 4
4 2 5
4 3 1
4 3 2
4 3 3
4 3 4
4 3 5
4 4 1
4 4 2
4 4 3
4 4 4
4 4 5
4 5 1
4 5 2
4 5 3
4 5 4
4 5 5
5 1 1
5 1 2
5 1 3
5 1 4
5 1 5
5 2 1
5 2 2
5 2 3
5 2 4
5 2 5
5 3 1
5 3 2
5 3 3
5 3 4
5 3 5
5 4 1
5 4 2
5 4 3
5 4 4
5 4 5
5 5 1
5 5 2
5 5 3
5 5 4
5 5 5
At least in python (You should specify language if it's a constraint):
>>> from itertools import permutations as permu
>>> for i in permu(range(5), 3):
... print i
...
(0, 1, 2)
(0, 1, 3)
(0, 1, 4)
(0, 2, 1)
(0, 2, 3)
(0, 2, 4)
(0, 3, 1)
....
In recursive solution you don't have to sort the list every time. Giving sorted list to recursive function must be sifficient.
To do so, I've written this piece of C# code. Length of output result will be determined by len. Just remember that input length must be equal or bigger than len:
// Input must be sorted, Result must be initialized to empty list
void Iterate(List<int> input, int len, List<int> result)
{
if(result.Count == n)
print result
else
foreach (var i in input)
Iterate(input, len, result.Append(num).ToList())
}
Use this algorithm.
Input: X is the minimum number, Y is the maximum number, and Z is the number of independent choices.
Create an array of size Z, with each element equal to X. Call it Permutation.
Loop:
Add a copy of Permutation to the list of permutations.
Set J to Z minus 1.
Loop:
Add 1 to Permutation[J]. If Permutation[J] is now Y or less, break.
Set Permutation[J] to X.
Subtract 1 from J. If J is now less than 0, return the list of permutations.
Must be classic algorithm. But it always fun to write it from scratch. Here is Java class accepting data set and result list size parameters. Core method is generate(). Also lists might be copied on demand (to be more functional style).
import com.google.common.collect.Maps;
import org.apache.commons.lang.ArrayUtils;
import java.util.Map;
public class PermutationGenerator {
private int listValuesSize;
private int resultListSize;
private String[] currentList;
private Map<String, String> nextValue = Maps.newHashMap();
private int permutations = 0;
public PermutationGenerator(String[] dataSet, int resultListSize) {
this.listValuesSize = dataSet.length;
this.resultListSize = resultListSize;
init(dataSet);
}
private void init(String[] dataSet) {
// rolling values
String previous = dataSet[0];
for (int valuesIndex = 1; valuesIndex < dataSet.length; valuesIndex++) {
nextValue.put(previous, dataSet[valuesIndex]);
previous = dataSet[valuesIndex];
}
nextValue.put(dataSet[dataSet.length - 1], dataSet[0]);
// init
currentList = new String[resultListSize];
for (int i = 0; i < resultListSize; i++) {
currentList[i] = dataSet[0];
}
}
public void generate() {
generate(0, resultListSize - 1);
}
private void generate(int from, int to) {
if (from > to) {
return;
}
for (int i = 0; i < listValuesSize; i++) {
if (from == to) {
processList(currentList);
} else {
generate(from + 1, to);
}
roll(from);
}
}
private void roll(int position) {
currentList[position] = nextValue.get(currentList[position]);
}
private void processList(String[] list) {
permutations++;
System.out.println(ArrayUtils.toString(list));
}
public static void main(String... args) {
PermutationGenerator generator = new PermutationGenerator(new String[]{"1", "2", "3", "4", "5"}, 3);
generator.generate();
System.out.println(generator.permutations);
}
}