Printing string in rows and column pattern Java - java

i'm just created a java project to print string that is given in rows and column just like matrix. Here's the output that i just made:
h e l l o
_ w o r l
d _ i t s
_ b e a u
t i f u l
Is it possible to show the output like a spiral pattern like this?
h e l l o
_ b e a _
s u l u w
t f i t o
i _ d l r
For the clarification how this spiral matrix created:
Here's my current code:
String str = "hello world its beautiful";
double length = Math.sqrt(str.length());
int x = (int) length;
for (int i = 0, len = str.length(); i < len; i++) {
System.out.print(str.charAt(i) + " ");
if (i % x == x - 1) {
System.out.println();
}
}
I'm trying to make the same pattern like that, but it's never be. Let me know that you can help me with this. I appreciate for every answer that you gave, thank you.

Basically, you move through the string from start to end, but treat the stringbuffer as an array.
You#ll also need to to keep track of your direction (dx,dy) and where your bounds are.
The following code will produce:
hello
beau
l.tw
sufio
i dlr
given the input "hello world is beautiful"
public class Main {
public static void main(String[] args) {
String text ="hello world is beautiful";
int len = text.length();
double sideLength = Math.sqrt( len );
int width = 0;
int height = 0;
// check if it's a square
if ( sideLength > (int) sideLength) {
// nope... it#s a rectangle
width = (int) sideLength +1;
height = (int) Math.ceil((double)len / (double)width);
} else {
// square
width = (int) sideLength;
height = (int) sideLength;
}
// create a buffer for the spiral
StringBuffer buf = new StringBuffer( width * height );
buf.setLength( width * height );
// clear it.
for (int a=0; a < buf.length(); a++ ) {
buf.setCharAt(a, '.');
}
int dstX = 0;
int dstY = 0;
int curWidth = width;
int curHeight = height;
int startX = 0;
int startY = 0;
int dx = 1;
int dy = 0;
// go through the string, char by char
for (int srcPos =0; srcPos < len; srcPos++) {
buf.setCharAt( dstX + dstY * width, text.charAt( srcPos ));
// move cursor
dstX += dx;
dstY += dy;
// check for bounds
if ( dstX == curWidth-1 && dx > 0) {
// end of line while going right, need to go down
dx = 0;
dy = 1;
// also, reduce width
curWidth--;
startY++;
} else if (dstY == curHeight-1 && dy > 0) {
// end of column while going down, need to go left
dx = -1;
dy = 0;
// also, reduce height
curHeight--;
} else if (dstX == startX && dx < 0) {
// hit left border while going left, need to go up
dx = 0;
dy = -1;
// also, increase startX
startX++;
} else if (dstY == startY && dy < 0) {
// hit top border, while going up, need to go right
dx = 1;
dy = 0;
// also, increase startY
startY++;
}
}
// display string
for (int line = 0; line < height; line++) {
System.out.println( buf.substring( line* width, line*width +width) );
}
}
}

spiralMatrix(int s) returns s x s spiral matrix.
static int[][] spiralMatrix(int s) {
int[][] a = new int[s][s];
int n = 0;
for (int b = s - 1, c = 0, x = 0, y = 0, dx = 0, dy = 1; b > 0; b -= 2, x = y = ++c)
for (int j = 0, t = 0; j < 4; ++j, t = dx, dx = dy, dy = -t)
for (int i = 0; i < b; ++i, x += dx, y += dy, ++n)
a[x][y] = n;
if (s % 2 == 1)
a[s / 2][s / 2] = n;
return a;
}
test
for (int s = 0; s < 6; ++s) {
int[][] a = spiralMatrix(s);
System.out.println("s=" + s);
for (int[] row : a)
System.out.println(Arrays.toString(row));
System.out.println();
}
result
s=0
s=1
[0]
s=2
[0, 1]
[3, 2]
s=3
[0, 1, 2]
[7, 8, 3]
[6, 5, 4]
s=4
[0, 1, 2, 3]
[11, 12, 13, 4]
[10, 15, 14, 5]
[9, 8, 7, 6]
s=5
[0, 1, 2, 3, 4]
[15, 16, 17, 18, 5]
[14, 23, 24, 19, 6]
[13, 22, 21, 20, 7]
[12, 11, 10, 9, 8]
And you can do it with this method.
String str = "hello world its beautiful";
int[][] spiral = spiralMatrix(5);
int length = str.length();
for (int x = 0, h = spiral.length, w = spiral[0].length; x < h; ++x) {
for (int y = 0; y < w; ++y) {
int p = spiral[x][y];
System.out.print((p < length ? str.charAt(p) : " ") + " " );
}
System.out.println();
}
result
h e l l o
b e a
s u l u w
t f i t o
i d l r

you could try to make the spiral algorithm first and try to find the value of its each index in the matrix so that later you could map every index of your string into the specific index in the spiral array matrix.
for example:
Input: n = 5
Output: 1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9
Aligned Output: 1 2 3 4 5 16 17 18 19 6 15 24 25 20 7 14 23 22 21 8 13 12 11 10 9
the algorithm can be found here or here.
now you know all the index of each position to make the letters aligned in a spiral way, what you have to do is map each letter of your string to be print according to the number of the spiral matrix sequentially.
print string 1.
print string 2.
print string 3.
print string 4.
print string 5.
print string 16.
print string 17.
print string 18.
print string 19.
print string 6.
print string 15.
cont...

Probably I'll add my answer too, idea is to flatten a two dimensional array to 1d and use the 1D array and transform it to a 2D spiral array. Hope it helps.
Code:
class Test {
static String[][] spiralPrint(int m, int n, String[] a) {
String[][] output = new String[m][n];
int count = 0;
int i, k = 0, l = 0;
while (k < m && l < n) {
for (i = l; i < n; ++i) {
output[k][i] = a[count++];
}
k++;
for (i = k; i < m; ++i) {
output[i][n - 1] = a[count++];
}
n--;
if (k < m) {
for (i = n - 1; i >= l; --i) {
output[m - 1][i] = a[count++];
}
m--;
}
if (l < n) {
for (i = m - 1; i >= k; --i) {
output[i][l] = a[count++];
}
l++;
}
}
return output;
}
private static String[] flattenArray(String[][] input, int m, int n) {
String[] output = new String[m * n];
int k = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
output[k++] = input[i][j];
}
}
return output;
}
public static void main(String[] args) {
String[][] input = {
{"h", "e", "l", "l", "o"},
{"_", "w", "o", "r", "l"},
{"d", "_", "i", "t", "s"},
{"_", "b", "e", "a", "u"},
{"t", "i", "f", "u", "l"}};
int m = 5;
int n = 5;
String[] flattenArray = flattenArray(input, m, n);
String[][] spiralArray = spiralPrint(m, n, flattenArray);
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
System.out.print(spiralArray[i][j] + " ");
}
System.out.println();
}
}
}
Output:
h e l l o
_ b e a _
s u l u w
t f i t o
i _ d l r
Note: Indeed that I followed this Spiral transform to 1D, but it is not straight forward, I have re-modified to fit to the problem.

I think that the best way to implement this is the following:
create an instruction object (Dictionary.java) which controls the fill-in process of the matrix
fill in the matrix with data (Spiral.java)
then show the matrix
With this approach, you can change the pattern easily, without changing the rest of the code because the pattern generator works detached from the rest of the code.
This is how the basic Dictionary class may look like:
public abstract class Dictionary {
protected int matrixSize;
protected String[] dictionary;
public Dictionary(int matrixSize) {
this.matrixSize = matrixSize;
dictionary = new String[matrixSize * matrixSize];
}
public abstract String[] createPattern();
public void showPattern() {
Arrays.stream(dictionary).forEach(System.out::println);
}
}
For each pattern, you need to implement the createPattern() method differently.
For example, a frame pattern implementation can be something like this:
public class FrameDictionary extends Dictionary {
protected int dictionaryIndex = 0;
protected int startX, endX;
protected int startY, endY;
public FrameDictionary(int matrixSize) {
super(matrixSize);
startX = -1;
endX = matrixSize - 1;
startY = 0;
endY = matrixSize - 1;
}
#Override
public String[] createPattern() {
while (dictionaryIndex < matrixSize) {
pattern1();
pattern2();
}
return dictionary;
}
/**
* pattern 1
* direction: left -> right then top -> bottom
*/
protected void pattern1() {
startX++;
for (int i = startX; i <= endX; i++) {
dictionary[dictionaryIndex] = i + ":" + startY;
dictionaryIndex++;
}
startY++;
for (int i = startY; i <= endY; i++) {
dictionary[dictionaryIndex] = endX + ":" + i;
dictionaryIndex++;
}
}
/**
* pattern 2
* direction: right -> left then bottom -> top
*/
protected void pattern2() {
endX--;
for (int i = endX; i >= startX; i--) {
dictionary[dictionaryIndex] = i + ":" + endY;
dictionaryIndex++;
}
endY--;
for (int i = endY; i >= startY; i--) {
dictionary[dictionaryIndex] = startX + ":" + i;
dictionaryIndex++;
}
}
}
Output:
a b c d e f
t g
s h
r i
q j
p o n m l k
You can draw the pattern what you need with the following implementation of the createPattern() method:
public class ClockWiseDictionary extends FrameDictionary {
public ClockWiseDictionary(int matrixSize) {
super(matrixSize);
}
#Override
public String[] createPattern() {
int pixelsInMatrix = matrixSize * matrixSize;
while (dictionaryIndex < pixelsInMatrix) {
pattern1();
pattern2();
}
return dictionary;
}
}
Output:
a b c d e f
t u v w x g
s 6 7 8 y h
r 5 0 9 z i
q 4 3 2 1 j
p o n m l k
Or just for fun, a "snake" pattern implementation:
public class SnakeDictionary extends Dictionary {
private int dictionaryIndex = 0;
private int startY = 0;
public SnakeDictionary(int matrixSize) {
super(matrixSize);
}
#Override
public String[] createPattern() {
int pixelsInMatrix = matrixSize * matrixSize;
while (dictionaryIndex < pixelsInMatrix) {
pattern1();
if (dictionaryIndex < pixelsInMatrix) {
pattern2();
}
}
return dictionary;
}
public void pattern1() {
for (int i = 0; i < matrixSize; i++) {
dictionary[dictionaryIndex] = i + ":" + startY;
dictionaryIndex++;
}
startY++;
}
public void pattern2() {
for (int i = matrixSize - 1; i >= 0; i--) {
dictionary[dictionaryIndex] = i + ":" + startY;
dictionaryIndex++;
}
startY++;
}
}
Output:
a b c d e f
l k j i h g
m n o p q r
x w v u t s
y z 1 2 3 4
0 9 8 7 6 5
This is how the main method looks like:
public static void main(String[] args) {
String sentence = "abcdefghijklmnopqrstuvwxyz1234567890";
String[][] spiral = new String[MATRIX_SIZE][MATRIX_SIZE];
// Dictionary dictionary = new FrameDictionary(MATRIX_SIZE);
Dictionary dictionary = new ClockWiseDictionary(MATRIX_SIZE);
// Dictionary dictionary = new SnakeDictionary(MATRIX_SIZE);
String[] pattern = dictionary.createPattern();
//dictionary.showPattern();
Spiral.fill(sentence, pattern, spiral);
Spiral.show(spiral);
}
You can check/download the complete source code from GitHub.
Hope that it helps you.

Here's a one with a recursive approach,
I am traversing the matrix in right -> down -> left -> up fashion on the boundaries
Then change the size and do the same for inner boundaries,
Matrix M would be a spiral matrix then of character indices
Create spiral matrix C for characters by traversing matrix M.
int m = 5;
int n = 5;
int limit = m * n;
int[][] M = new int[m][n];
public void spiral(int[][] M, int row, int col, int c, int start, int m, int n) {
if (c > limit | row >= m | col >= n)
return;
if (M[row][col] == 0)
M[row][col] = c;
if (row == start) // go right
spiral(M, row, col + 1, c + 1, start, m, n);
if (col == n - 1) // go down
spiral(M, row + 1, col, c + 1, start, m, n);
if (row == m - 1 && col > start) // go left
spiral(M, row, col - 1, c + 1, start, m, n);
if (col == start && row >= start) // go up
spiral(M, row - 1, col, c + 1, start, m, n);
};
spiral(M, 0, 0, 1, 0, m, n);
for (int i = m - 1, x = 1, j = n - 1; i >= m - 2 && j >= n - 2; i--, j--, x++)
spiral(M, x, x, M[x][x - 1] + 1, x, i, j);
This would give you spiral Matrix M
Output:
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9
Then create a spiral matrix for characters using matrix M
String string = "hello_world_its_beautiful";
char[][] C = new char[size][size];
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++)
C[i][j] = string.charAt(M[i][j] - 1);
}
Output:
h e l l o
_ b e a _
s u l u w
t f i t o
i _ d l r

When can't go straight turn left to walk, this is the theory used in this solution
int dr[] = {0, 1, 0, -1};
int dc[] = {1, 0, -1, 0};
this is used for always move pattern. And curr & curc represent current position and curm represent current move pattern.
public int[][] solve(int r, int c, String s) {
int m[][] = new int[5][5];
int curr = 0, curc = 0;
for (int pos = 0, curm = 0; pos < r*c; pos++) {
m[curr][curc] = (int) s.charAt(pos);
if (curr + dr[curm] < 0 || curr + dr[curm] >= r || curc + dc[curm] < 0 || curc + dc[curm] >= c
|| m[curr + dr[curm]][curc + dc[curm]] != 0)
curm = (curm + 1) % 4;
curr = curr + dr[curm];
curc = curc + dc[curm];
}
return m;
}
Then you can print this way
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
System.out.printf("%c ", m[i][j]);
}
System.out.println("");
}

Related

how to convert Java class to groovy?

I'm working on a project where i want to convert a Java code to Groovy and/or can import java code a function in groovy. It worked fine with java but its not working as expected in groovy.
Basically need to write a function where generated walsh code multiplied with the data and give spreading data. so minimally took (2^2 =4 nodes) to show basic functionality.
// Java code illustrating a simple implementation of CDMA
import java.util.*;
public class simple_cdma {
private int[][] wtable;
private int[][] copy;
private int[] channel_sequence;
public void setUp(int[] data, int num_stations)
{
wtable = new int[num_stations][num_stations];
copy = new int[num_stations][num_stations];
buildWalshTable(num_stations, 0, num_stations - 1, 0,
num_stations - 1, false);
showWalshTable(num_stations);
for (int i = 0; i < num_stations; i++) {
for (int j = 0; j < num_stations; j++) {
// Making a copy of walsh table
// to be used later
copy[i][j] = wtable[i][j];
// each row in table is code for one station.
// So we multiply each row with station data
wtable[i][j] *= data[i];
}
}
channel_sequence = new int[num_stations];
for (int i = 0; i < num_stations; i++) {
for (int j = 0; j < num_stations; j++) {
// Adding all sequences to get channel sequence
channel_sequence[i] += wtable[j][i];
}
}
}
public void listenTo(int sourceStation, int num_stations)
{
int innerProduct = 0;
for (int i = 0; i < num_stations; i++) {
// multiply channel sequence and source station code
innerProduct += copy[sourceStation][i] * channel_sequence[i];
}
System.out.println("The data received is: " +
(innerProduct / num_stations));
}
public int buildWalshTable(int len, int i1, int i2, int j1,
int j2, boolean isBar)
{
// len = size of matrix. (i1, j1), (i2, j2) are
// starting and ending indices of wtable.
// isBar represents whether we want to add simple entry
// or complement(southeast submatrix) to wtable.
if (len == 2) {
if (!isBar) {
wtable[i1][j1] = 1;
wtable[i1][j2] = 1;
wtable[i2][j1] = 1;
wtable[i2][j2] = -1;
}
else {
wtable[i1][j1] = -1;
wtable[i1][j2] = -1;
wtable[i2][j1] = -1;
wtable[i2][j2] = +1;
}
return 0;
}
int midi = (i1 + i2) / 2;
int midj = (j1 + j2) / 2;
buildWalshTable(len / 2, i1, midi, j1, midj, isBar);
buildWalshTable(len / 2, i1, midi, midj + 1, j2, isBar);
buildWalshTable(len / 2, midi + 1, i2, j1, midj, isBar);
buildWalshTable(len / 2, midi + 1, i2, midj + 1, j2, !isBar);
return 0;
}
public void showWalshTable(int num_stations)
{
System.out.print("\n");
for (int i = 0; i < num_stations; i++) {
for (int j = 0; j < num_stations; j++) {
System.out.print(wtable[i][j] + " ");
}
System.out.print("\n");
}
System.out.println("-------------------------");
System.out.print("\n");
}
// Driver Code
public static void main(String[] args)
{
/*
* C1 = [+1 +1 +1 +1]
* C2 = [+1 -1 +1 -1]
* C3 = [+1 +1 -1 -1]
* C4 = [+1 -1 -1 +1]
* Let their data bits currently be:
* D1 = -1
* D2 = -1
* D3 = 0 (Silent)
* D4 = +1
* Resultant channel sequence = C1.D1 + C2.D2 + C3.D3 + C4.D4
* = [-1 -1 -1 -1] + [-1 +1 -1 +1] + [0 0 0 0] + [+1 -1 -1 +1]
* = [-1 -1 -3 +1]
*
* Now suppose station 1 wants to listen to station 2.
* Inner Product = [-1 -1 -3 +1] x C2
* = -1 + 1 - 3 - 1 = -4
*
* Data bit that was sent = -4/4 = -1.
* */
int num_stations = 4;
int[] data = new int[num_stations];
//data bits corresponding to each station
data[0] = -1;
data[1] = -1;
data[2] = 0;
data[3] = 1;
simple_cdma channel = new simple_cdma();
channel.setUp(data, num_stations);
// station you want to listen to
int sourceStation = 1;
channel.listenTo(sourceStation, num_stations);
}
}
Can anyone suggest me what is wrong with my code ?
first of all, I suggest you follow Java bean conventions YourClassName, yourVariable, then remember the default dataTypes
At line 60
public int buildWalshTable(int len, int i1, int i2, int j1, int j2, boolean isBar)
{
...
// In Groovy the first parameter will be a BigDecimal not an int and will fail
buildWalshTable(len / 2, i1, midi, j1, midj, isBar);
...
return 0;
}
So in Groovy this could be change to:
public int buildWalshTable(BigDecimal len, int i1, int i2, int j1, int j2, boolean isBar)
{
...
// In Groovy the first parameter will be a BigDecimal
buildWalshTable(len / 2, i1, midi, j1, midj, isBar);
...
return 0;
}
Now, rename your class from simple_cdma to SimpleCdma I recommend to use your IDE or text editor to do this.
Finally just need to rename your file from .java to .groovy and done.

Find the top k Knapsacks

I got a special case of the Knapsacks problem where the weights are equal to the values. My goal is to print the top j most closed solutions to W(the target weight) using the DP approach.
So far I can print a single result, but I didn't figure how to efficiently track the top j solutions.
package com.gazman.quadratic_sieve.core.poly;
import java.util.ArrayList;
import java.util.List;
class Knapsack {
static List<Integer> knapSack(int W, int[] weights) {
int i, w;
int n = weights.length + 1;
int[][] k = new int[n][W + 1];
for (i = 0; i < n; i++) {
for (w = 0; w <= W; w++) {
if (i == 0 || w == 0) {
k[i][w] = 0;
}
else {
int r = k[i - 1][w];
if (weights[i - 1] <= w) {
int l = weights[i - 1] + k[i - 1][w - weights[i - 1]];
k[i][w] = Math.max(l, r);
} else {
k[i][w] = r;
}
}
}
}
int res = k[n - 1][W];
w = W;
List<Integer> result = new ArrayList<>();
for (i = n - 1; i > 0 && res > 0; i--) {
if (res != k[i - 1][w]) {
result.add(weights[i - 1]);
res = res - weights[i - 1];
w = w - weights[i - 1];
}
}
return result;
}
public static void main(String[] args) {
int[] val = new int[]{12, 102, 120, 280, 1000, 1200};
int W = 1279;
System.out.println(knapSack(W, val)); // [1000, 120, 102, 12]
}
}

Split an array into four sub-array

Given an array, it contains N element, which are all positive integers; if we can find three elements, and they divide the array into four parts (Notice: the three elements are not contained in any part of the four), and the sum of each part are equal, then we call the array a "balanced" array. Design an algorithm to judge whether an array is balance, with limit: Time O(N), Space O(N).
Here is an example:
a = [1,7,4,2,6,5,4,2,2,9,8];
b = [1,8,10,5,3,1,2,3]
a is balanced, 'cause the element 4, 5, 9 divide the array into [1,7], [2,6], [4,2,2], [8], the sum of each is 8.
b is not balanced, because we can not find a solution.
Any idea is appreciated!
Hints
Consider the first element to be removed.
Once you know this position, you can compute the size of the first part.
Once you know the size of the first part, you can compute the location of the second element to be removed, and so on (because all elements are positive integers).
Now you need to find a way to perform this in O(N). Try thinking about what you can do to reuse computations that have already been done, e.g. by keeping a rolling sum of the size of each of your parts.
You can try with this solution:
class BalancedArray
{
public static void main( String[] args ) throws java.lang.Exception
{
int[] a = { 1, 7, 4, 2, 6, 5, 4, 2, 2, 9, 8 }; //BALANCED
//int[] a = {7,0,6,1,0,1,1,5,0,1,2,2,2}; //BALANCED
//int[] a = {1}; //NOT BALANCED
int l = a.length;
if ( l < 7 )
{
System.out.println( "Array NOT balanced" );
} else
{
int maxX = l - 5;
int maxY = l - 3;
int maxZ = l - 1;
int x = 1;
int y = 3;
int z = 5;
int sumX = 0; //From 0 to x
int sumY = 0; //From x to y
int sumJ = 0; //From y to z
int sumZ = 0; //From z to l
for(x = 1; x < maxX; x++)
{
sumX = calcSum(a,0,x);
for(y = x + 2; y < maxY; y++)
{
sumY = calcSum(a,x+1,y);
if(sumY != sumX){
continue;
}
for(z = y + 2; z < maxZ; z++)
{
sumJ = calcSum(a,y+1,z);
if(sumJ != sumY)
{
continue;
}
sumZ = calcSum(a,z+1,l);
if(sumZ != sumJ){
continue;
}
if(sumZ == sumX && sumX == sumY && sumY == sumJ)
{
System.out.println( "Array balanced!!! Elements -> X:" + x + " Y: " + y + " Z:" + z );
return;
}
}
}
}
System.out.println("Array NOT balanced!!");
}
}
private static int calcSum(int[] src, int start, int end)
{
int toReturn = 0;
for ( int i = start; i < end; i++ )
{
toReturn += src[i];
}
return toReturn;
}
}
I made these assumptions:
between each of the three elements, which should split the array in 4 parts, there must be at least a distance of 2;
to be divided in 4 sub-arrays the source array must be at least 7 elements long;

Optimal algorithm for finding max value

I need to design an algorithm to find the maximum value I can get from (stepping) along an int[] at predefined (step lengths).
Input is the number of times we can "use" each step length; and is given by n2, n5 and n10. n2 means that we move 2 spots in the array, n5 means 5 spots and n10 means 10 spots. We can only move forward (from left to right).
The int[] contains the values 1..5, the size of the array is (n2*2 + n5*5 + n10*10). The starting point is int[0].
Example: we start at int[0]. From here we can move to int[0+2] == 3, int[0+5] == 4 or int[0+10] == 1. Let's move to int[5] since it has the highest value. From int[5] we can move to int[5+2], int[5+5] or int[5+10] etc.
We should move along the array in step lengths of 2, 5 or 10 (and we can only use each step length n2-, n5- and n10-times) in such a manner that we step in the array to collect as high sum as possible.
The output is the maximum value possible.
public class Main {
private static int n2 = 5;
private static int n5 = 3;
private static int n10 = 2;
private static final int[] pokestops = new int[n2 * 2 + n5 * 5 + n10 * 10];
public static void main(String[] args) {
Random rand = new Random();
for (int i = 0; i < pokestops.length; i++) {
pokestops[i] = Math.abs(rand.nextInt() % 5) + 1;
}
System.out.println(Arrays.toString(pokestops));
//TODO: return the maximum value possible
}
}
This is an answer in pseudocode (I didn't run it, but it should work).
fill dp with -1.
dp(int id, int 2stepcount, int 5stepcount, int 10stepcount) {
if(id > array_length - 1) return 0;
if(dp[id][2stepcount][5stepcount][10stepcount] != -1) return dp[id][2stepcount][5stepcount][10stepcount];
else dp[id][2stepcount][5stepcount][10stepcount] = 0;
int 2step = 2stepcount < max2stepcount? dp(id + 2, 2stepcount + 1, 5stepcount, 10stepcount) : 0;
int 5step = 5stepcount < max5stepcount? dp(id + 5, 2stepcount, 5stepcount + 1, 10stepcount) : 0;
int 10step = 10stepcount < max10stepcount? dp(id + 10, 2stepcount, 5stepcount, 10stepcount + 1) : 0;
dp[id][2stepcount][5stepcount][10stepcount] += array[id] + max(2step, 5step, 10step);
return dp[id][2stepcount][5stepcount][10stepcount];
}
Call dp(0,0,0,0) and the answer is in dp[0][0][0][0].
If you wanna go backwards, then you do this:
fill dp with -1.
dp(int id, int 2stepcount, int 5stepcount, int 10stepcount) {
if(id > array_length - 1 || id < 0) return 0;
if(dp[id][2stepcount][5stepcount][10stepcount] != -1) return dp[id][2stepcount][5stepcount][10stepcount];
else dp[id][2stepcount][5stepcount][10stepcount] = 0;
int 2stepForward = 2stepcount < max2stepcount? dp(id + 2, 2stepcount + 1, 5stepcount, 10stepcount) : 0;
int 5stepForward = 5stepcount < max5stepcount? dp(id + 5, 2stepcount, 5stepcount + 1, 10stepcount) : 0;
int 10stepForward = 10stepcount < max10stepcount? dp(id + 10, 2stepcount, 5stepcount, 10stepcount + 1) : 0;
int 2stepBackward = 2stepcount < max2stepcount? dp(id - 2, 2stepcount + 1, 5stepcount, 10stepcount) : 0;
int 5stepBackward = 5stepcount < max5stepcount? dp(id - 5, 2stepcount, 5stepcount + 1, 10stepcount) : 0;
int 10stepBackward = 10stepcount < max10stepcount? dp(id - 10, 2stepcount, 5stepcount, 10stepcount + 1) : 0;
dp[id][2stepcount][5stepcount][10stepcount] += array[id] + max(2stepForward, 5stepForward, 10stepForward, 2stepBackward, 5backForward, 10backForward);
return dp[id][2stepcount][5stepcount][10stepcount];
}
But your paths don't get fulled explored, because we stop if the index is negative or greater than the array size - 1, you can add the wrap around functionality, I guess.
this is a solution but i am not sure how optimal it is !
i did some optimization on it but i think much more can be done
I posted it with the example written in question
import java.util.Arrays;
import java.util.Random;
public class FindMax {
private static int n2 = 5;
private static int n5 = 3;
private static int n10 = 2;
private static final int[] pokestops = new int[n2 * 2 + n5 * 5 + n10 * 10];
public static int findMaxValue(int n2, int n5, int n10, int pos, int[] pokestops) {
System.out.print("|");
if (n2 <= 0 || n5 <= 0 || n10 <= 0) {
return 0;
}
int first;
int second;
int third;
if (pokestops[pos] == 5 || ((first = findMaxValue(n2 - 1, n5, n10, pos + 2, pokestops)) == 5) || ((second = findMaxValue(n2, n5 - 1, n10, pos + 5, pokestops)) == 5) || ((third = findMaxValue(n2, n5, n10 - 1, pos + 10, pokestops)) == 5)) {
return 5;
}
return Math.max(Math.max(Math.max(first, second), third), pokestops[pos]);
}
public static void main(String[] args) {
Random rand = new Random();
for (int i = 0; i < pokestops.length; i++) {
pokestops[i] = Math.abs(rand.nextInt() % 5) + 1;
}
System.out.println(Arrays.toString(pokestops));
//TODO: return the maximum value possible
int max = findMaxValue(n2, n5, n10, 0, pokestops);
System.out.println("");
System.out.println("Max is :" + max);
}
}
You need to calculate following dynamic programming dp[c2][c5][c10][id] - where c2 is number of times you've stepped by 2, c5 - by 5, c10 - by 10 and id - where is your current position. I will write example for c2 and c5 only, it can be easily extended.
int[][][][] dp = new int[n2 + 1][n5 + 1][pokestops.length + 1];
for (int[][][] dp2 : dp) for (int[][] dp3 : dp2) Arrays.fill(dp3, Integer.MAX_VALUE);
dp[0][0][0] = pokestops[0];
for (int c2 = 0; c2 <= n2; c2++) {
for (int c5 = 0; c5 <= n5; c5++) {
for (int i = 0; i < pokestops.length; i++) {
if (c2 < n2 && dp[c2 + 1][c5][i + 2] < dp[c2][c5][i] + pokestops[i + 2]) {
dp[c2 + 1][c5][i + 2] = dp[c2][c5][i] + pokestops[i + 2];
}
if (c5 < n5 && dp[c2][c5 + 1][i + 5] < dp[c2][c5][i] + pokestops[i + 5]) {
dp[c2][c5 + 1][i + 5] = dp[c2][c5][i] + pokestops[i + 5];
}
}
}
}
I know the target language is java, but I like pyhton and conversion will not be complicated.
You can define a 4-dimensional array dp where dp[i][a][b][c] is the maximum value that you can
get starting in position i when you already has a steps of length 2, b of length 5 and c of length
10. I use memoization to get a cleaner code.
import random
values = []
memo = {}
def dp(pos, n2, n5, n10):
state = (pos, n2, n5, n10)
if state in memo:
return memo[state]
res = values[pos]
if pos + 2 < len(values) and n2 > 0:
res = max(res, values[pos] + dp(pos + 2, n2 - 1, n5, n10))
if pos + 5 < len(values) and n5 > 0:
res = max(res, values[pos] + dp(pos + 5, n2, n5 - 1, n10))
if pos + 10 < len(values) and n10 > 0:
res = max(res, values[pos] + dp(pos + 10, n2, n5, n10 - 1))
memo[state] = res
return res
n2, n5, n10 = 5, 3, 2
values = [random.randint(1, 5) for _ in range(n2*2 + n5*5 + n10*10)]
print dp(0, n2, n5, n10)
Suspiciously like homework. Not tested:
import java.util.Arrays;
import java.util.Random;
public class Main {
private static Step[] steps = new Step[]{
new Step(2, 5),
new Step(5, 3),
new Step(10, 2)
};
private static final int[] pokestops = new int[calcLength(steps)];
private static int calcLength(Step[] steps) {
int total = 0;
for (Step step : steps) {
total += step.maxCount * step.size;
}
return total;
}
public static void main(String[] args) {
Random rand = new Random();
for (int i = 0; i < pokestops.length; i++) {
pokestops[i] = Math.abs(rand.nextInt() % 5) + 1;
}
System.out.println(Arrays.toString(pokestops));
int[] initialCounts = new int[steps.length];
for (int i = 0; i < steps.length; i++) {
initialCounts[i] = steps[i].maxCount;
}
Counts counts = new Counts(initialCounts);
Tree base = new Tree(0, null, counts);
System.out.println(Tree.max.currentTotal);
}
static class Tree {
final int pos;
final Tree parent;
private final int currentTotal;
static Tree max = null;
Tree[] children = new Tree[steps.length*2];
public Tree(int pos, Tree parent, Counts counts) {
this.pos = pos;
this.parent = parent;
if (pos < 0 || pos >= pokestops.length || counts.exceeded()) {
currentTotal = -1;
} else {
int tmp = parent == null ? 0 : parent.currentTotal;
this.currentTotal = tmp + pokestops[pos];
if (max == null || max.currentTotal < currentTotal) max = this;
for (int i = 0; i < steps.length; i++) {
children[i] = new Tree(pos + steps[i].size, this, counts.decrement(i));
// uncomment to allow forward-back traversal:
//children[2*i] = new Tree(pos - steps[i].size, this, counts.decrement(i));
}
}
}
}
static class Counts {
int[] counts;
public Counts(int[] counts) {
int[] tmp = new int[counts.length];
System.arraycopy(counts, 0, tmp, 0, counts.length);
this.counts = tmp;
}
public Counts decrement(int i) {
int[] tmp = new int[counts.length];
System.arraycopy(counts, 0, tmp, 0, counts.length);
tmp[i] -= 1;
return new Counts(tmp);
}
public boolean exceeded() {
for (int count : counts) {
if (count < 0) return true;
}
return false;
}
}
static class Step {
int size;
int maxCount;
public Step(int size, int maxCount) {
this.size = size;
this.maxCount = maxCount;
}
}
}
There's a line you can uncomment to allow forward and back movement (I'm sure someone said in the comments that was allowed, but now I see in your post it says forward only...)

Finding 5 values in a row diagonally in Java

I have this 10x10 array:
private static int[][] intersections = new int[10][10];
I'm using this code to find if there are 5 values in a row horizontally:
public static int horizontalCheck() {
String horizontal = "";
for (int i = 0; i < intersections.length; i++) {
for (int j = 0; j < intersections[i].length; j++) {
horizontal += Integer.toString(intersections[i][j]);
}
if (horizontal.indexOf("11111") != -1) {
// White wins.
return 1;
} else if (horizontal.indexOf("22222") != -1) {
// Black wins.
return 2;
}
horizontal = "";
}
return 0;
}
And a similar code to do it vertically. But my question is, how could I find if there are 5 values in a row diagonally? The board is sized 10x10 and the diagonals can be both ways anywhere on the board. If you have any questions or need some more information on the code, make sure to ask.
I suggest you write a helper function for this. The function should take these parameters:
r0 - The starting row from which the check needs to start
c0 - The starting column from which the check needs to start
dr - The vertical step from {-1, 0, 1}
dc - The horizontal step from {-1, 0, 1}
len - The number of items to be found
num - The number to find.
Here is how this function may look:
private static boolean checkRow(int r0, int c0, int dr, int dc, int len, int num) {
for (int k = 0 ; k != len ; k++) {
int r = r0 + k*dr;
int c = c0 + k*dc;
if (r < 0 || c < 0 || r >= intersections.length || c > intersections[r].length || intersections[r][c] != num) {
return false;
}
}
return true;
}
With this function in hand, you can check for len items in a row in any direction that you wish:
// See if we've got five eights in any direction:
for (int r = 0 ; r != intersections.length ; r++) {
for (int c = 0 ; c != intersections[r].length ; c++) {
if (checkRow(r, c, 0, 1, 5, 8)) {
System.out.println("Horizontal, starting at "+r+" " +c);
}
if (checkRow(r, c, 1, 0, 5, 8)) {
System.out.println("Vertical, starting at "+r+" " +c);
}
if (checkRow(r, c, 1, 1, 5, 8)) {
System.out.println("Diagonal descending right, starting at "+r+" " +c);
}
if (checkRow(r, c, 1, -1, 5, 8)) {
System.out.println("Diagonal descending left, starting at "+r+" " +c);
}
}
}

Categories