I have a 2D array of varying size, where height can take on any value.
int array[][] = new int[height][height]
Let's say I have a 3 x 3 array with the values of:
7 8 9
6 5 4
1 2 3
Would it be possible to check to see if 1 is adjacent to 2, 2 adjacent to 3, 3 adjacent to 4, 4 adjacent to 5 and so on? Adjacent here being if they are next to each other vertically, horizontally and diagonally.
So basically, there is a link from number 1 to 9 (or maximum number - e.g. if board is a 4x4, then from 1 to 16).
This is what I have been been able to make. It's a good solution, although takes a little more space. Definitely not the best solution for this though. Use of math might be needed for a more optimum solution. I am not that good at math.
//assuming the height as variable - 'r'
//take an input of some element, let's assume a[0][0], taken inside a[e][e]
int f, f1, f2, arflg=0;
int arr = new int[r*r];
for(int i=0;i<r;i++){
for(int j=0;j<r;j++){
arr[arflg]=a[i][j];
arflg++;
if(a[i][j]==a[e][e]) f1 = arflg; //location of element entered on the array
if(a[i][j]==a[e][e]-1) f2 = arflg; //location of element's predecessor on the array
}
}
f = f2 - f1;
if(f==1){
//forward hortizontal
}elseif(f==-1){
//backward horizontal
}elseif(f==r){
//below
}elseif(f==r-1){
//below left
}elseif(f==r+1){
//below right
}elseif(f==-r){
//above
}elseif(f==(-r-1)){
//above left
}elseif(f==(-r+1){
//above right
}
Related
Consider a set of number grids like:
1 1 2 1 2 3
2 2 2 2 3
3 3 3
In other words, a square grid where the number in each position follows a right-angle pattern. How do I write a function that creates, fills in, and returns such a 2d array?
( Also, I'm wondering if Math.max(a, b) would be useful for filling in the grid. I'm wondering if it could return which value is greater between two inputs a and b.)
I already have a function set up, but I don't know where to start:
int[][] cornerPattern(int squareSize) {
}
Hints would be fine
Most of the java programs can easily be solved or atleast initiated by finding a pattern.
So whats the pattern here?
The pattern is that the relation between array index and the element at that place. Every index which has 0 in it has 1 so arr[0][0] is 1.See the pattern there? Every index which has [1] in it has 2. So arr[0][1], arr[1][0] and arr[1][1] are 2 and same is the condition with 3. The size of the array is also defined in the same way. 3, will be [3][3] matrix.
Hope that helps. :)
You are looking for something like this
int m =//input;
int[][] arr = new int[m][m];
for(int i=0;i<m;i++){
for(int j=0;j<m;j++){
if(i>=j)
arr[i][j]=i;
else
arr[i][j]=j;
System.out.print(arr[i][j]);
}
System.out.println();
}
Print all the combinations of elements in matrix of size m * n.
Sample Example:
1 3 5
2 6 7
Expected Output:
2 , 1
2 , 3
2 , 5
6 , 1
6 , 3
6 , 5
7 , 1
7 , 3
7 , 5
Rules:
- Every combination starts from bottom of matrix and proceeds towards top. It may switch columns though.
- Every combination should have number of elements equal to number of rows.
- A combination can't have an element from the same row present twice.
I never could figure the solution out for general case. I can use 3 loops. But I want to understand the recursive solution. I use Java.
Here's a non-recursive way to solve this problem (it's not all that pretty, but it works for your input). I know you were interested in recursion, but I don't have anything like that for you at the moment. Generally, I avoid recursion due to the size of problems I work with (constant heap space errors due to the size of the recursive stack even when -Xmx60G). Hope this helps.
private static List<int[]> combos;
public static void main(String[] args){
combos = new ArrayList<int[]>();
generate(new int[][]{{1,3,5},{2,6,7}});
for(int[] s : combos){
System.out.println(java.util.Arrays.toString(s));
}
}
private static void generate(int[][] elements) {
int rows = elements.length;
int[] elementsIndex = new int[rows];
int[] elementsTotals = new int[rows];
java.util.Arrays.fill(elementsTotals, elements[0].length);
int curIdx = 0;
int[] c = new int[rows];
while(true){
while(curIdx >= 0){
if(curIdx == rows) {
addCombo(c);
curIdx--;
}
if(elementsIndex[curIdx] == elementsTotals[curIdx]){
elementsIndex[curIdx] = 0;
curIdx--;
} else break;
}
if(curIdx < 0) break;
// toggle order:
// bottom up: elements[rows-curIdx-1][elementsIndex[curIdx]++]
// top down: elements[curIdx][elementsIndex[curIdx]++]
c[curIdx] = elements[rows-curIdx-1][elementsIndex[curIdx]++];
curIdx++;
}
}
private static void addCombo(int[] c){
int[] a = new int[c.length];
System.arraycopy(c, 0, a, 0, c.length);
combos.add(a);
}
A recursive solution would look something like this:
printPermutations(String head, Matrix m)
if m is empty print head and return
else for each item in last row of m
printPermutations(head + item, m - bottom row)
here "head" is all the work we've done so far. In the body of a recursive method, there have to be at least two alternatives, one that outputs a result and ends the recursion, and one that goes deeper. For the deeper alternative, we transfer the selected element to head, remove the bottom row since we can't pick more than one item from any row, and do it again.
Done well, a recursive solution is often simpler and cleaner than using loops. On the other hand, recursion tends to use more memory
For a school project i had to code the cracker barrel triangle peg game, http://www.joenord.com/puzzles/peggame/3_mid_game.jpg heres a link to what it is. I made a triangle symmetric matrix to represent the board
|\
|0\
|12\
|345\
|6789\....
public int get( int row, int col )
{
if (row >= col) // prevents array out of bounds
return matrix[row][col];
else
return matrix[col][row];
} //
and here is my get() function that's the form of the matrix. if i try to access get(Row, Column) and row>column i access get(column, row) its set that way in all my methods. This way its easier to prevent out of bounds stuff from happening. empty spots in the triangle are set to 0, all pegs are set to 1. There's unrelated reason why i didn't use a Boolean array. The project is a AI project and to develop a heuristic search algorithm i need access to the number of pegs adjacent to each other. I can easily prevent most duplicates by simply dividing by total/2 since it will count every adjacent in both directions. I don't know how to prevent duplicate checks when i cross that middle line. It only matters on the 0 2 5 and 9 positions. If i really wanted to i could write a separate set of rules for those positions, but that doesn't feel like good coding and is not functional for different sized triangles. any input is welcome and if you need more information feel free to ask.
0, 2, 5, 9 is not an arithmetic progression. The finite differences 2-0 = 2, 5-2 = 3, 9 - 5 = 4 are in arithmetic progression. So the sequence is 0, 0 + 2 = 2, 2 + 3 = 5, 5 + 4 = 9, 9 + 5 = 14, 14 + 6 = 20, etc. They are one less than the triangle numbers 1, 3, 6, 10, 15, 21, etc. The nth triangle number has a short-cut expression, n(n+1)/2 (where n starts at 1, not 0). So your numbers are n(n+1)/2 - 1 for n = 1, 2, 3, ...
Anyway, the situation you are experiencing should tell you that setting it up so get(row,col) == get(col,row) is a bad idea. What I would do instead is to set it up so that your puzzle starts at index 1,1 and increases from there; then put special values -1 in the matrix entries 0,y and x,0 and anything with col > row. You can check for out of bounds conditions just by checking for the value -1 in a cell. Then to count the number of pegs surrounding a position you always do the same thing: check all four adjacent cells for 1's.
I have to partition a 2d array (the size is given by the user) into sub-arrays given an input number by the user. The code i Wrote works well for most of the instances by there are some that I need some help with.
I do this by taking the square root of the input number. So for example:
If the user inserts [10, 10, 9] it means that this is a 10 * 10 array with 9 sub-arrays. Taking the square root of 9 works fine because it gives 3.
If the user inserts [8, 6, 6] it takes the square root of 6 and rounds it up for the longest side (which gives 3) and rounds it down for the shortest (which is 2). So 3 * 2 = 6. It also works fine.
Then there is a situation like 8. The square root of 8 gives 3 and 2. So the array is partitioned into 6 sub-arrays. Is there another way to find a better partitioning for numbers like 8, 14? Or is there a way to find the optimal distribution for such numbers (e.g. 2 * 4 = 8, 2 * 7 = 14)?
You can calculate them a bit different way:
int x = Math.round(Math.sqrt(n));
int y = Math.round(1. * n / x);
Thus you'll receive:
n = 8 => x = 3, y = 3
n = 14 => x = 4, y = 4
What you need to do is find the two nearest factors to the square root. Try this code:
long n = 14;
long y = 0;
long x = Math.round(Math.sqrt(n));
while(true){
if (n % x == 0) {
y = n/x;
break;
}
else {
x--;
}
}
You might also like to put in some error checking to cope with input errors. e.g. n<1.
For example if I have 5 x 5 grid and I have position 13. I want to find the absolute distance of each edge in every direction excluding diagonally. So from 13 to the left would be 3, to the right it would be 1, to the bottom it would be two and to the top it would be 2. How would I approach this?
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
15 16 17 18 19
20 21 22 23 24
Distance from the top would be row,
int row = (int)(13/5); // 2
Distance from the left would be column, take the remainder of 13 by 5.
int col = (int)(13%5); // 3
Distance from the right would be the column minus total columns (5)
int colFromRight = 5-col-1; // 1
Distance from the bottom would be the row minus total rows (5)
int rowFromBottom = 5-row-1; // 2
Edit:
Heres a little diagram th at may help
heres an 1 dimensional array that we want to treat as a 2d array. It has 2 rows and 3 columns for a total of 6 elements. In our program it is a 1d array like this, I am using brackets[] for looks not syntax.
[1][2][3][4][5][6]
visually it would be like this
[1][2][3]
[4][5][6]
So to get the row of say location 5 we say
int location = 5;
int row = floor(location/3);
As you can see every time the row becomes 1+ a multiple of 3 the row number will increase.
for columns its the same thing but with a remainder.
int location = 5;
int column = location%3;
Here every time the location reaches 3 the remainder returns to 0 and the columns start over (essential signaling a new row).
Treat it as a 1-dimensional array and use modulus, division, and subtraction.
row_length = 5
col_length = 5
index = 13
x = (index % row_length);
y = (index - x) / col_length;
distance from left edge = row_length - x
distance from bottom = col_length - y
EDIT: I was actually asked this during an interview a few months ago and botched it. I wrote about it in a blog post here: http://tmblr.co/ZSJA4p18C4Ow0
EDIT 2: Fixed the subtraction to find left/bottom edges.