For leetcode problem https://leetcode.com/problems/walls-and-gates/solution/
The BFS solution has
.......
private static final List<int[]> DIRECTIONS = Arrays.asList(
new int[] { 1, 0},
new int[] {-1, 0},
new int[] { 0, 1},
new int[] { 0, -1}
);
.....
This is to take turn right while traversing the matrix. Does anyone know how to derive these vectors without memorizing them?
My understanding is you do a cross product with (x,y,0) X (0,0,1) which gives R = yX -xY + 0Z.
I think you take a partial derivative here but I'm unsure of the math proof which gives the directions.
Please explain mathematically how to get vectors {1,0} , {-1, 0}, {0,1} , {0,-1}
My understanding is you do a cross product with (x,y,0) X (0,0,1) which gives R = yX -xY + 0Z.
I think you take a partial derivative here but I'm unsure of the math proof which gives the directions.
Related
The North Carolina Lottery offers several draw games, two of which are Pick 3 and Pick 4. You pick 3 or 4 digits, respectively, between 0 and 9 (inclusive), and the numbers can repeat (e.g., 9-9-9 is a valid combination). I'll use Pick 3 for this example, because it's easier to work with, but I am trying to make this a generic solution to work with any number of numbers.
One of the features of Pick 3 and Pick 4 is "1-OFF," which means you win a prize if at least one of the numbers drawn are 1 up or 1 down from the numbers you have on your ticket.
For example, let's say you played Pick 3 and you picked 5-5-5 for your numbers. At least one number must be 1-off in order to win (so 5-5-5 does not win any prize, if you played the game this way). Winning combinations would be:
1 Number 2 Numbers 3 Numbers
-------- --------- ---------
4-5-5 4-4-5 4-4-4
5-4-5 5-4-4 6-6-6
5-5-4 4-5-4 4-4-6
6-5-5 6-6-5 4-6-6
5-6-5 5-6-6 4-6-4
5-5-6 6-5-6 6-4-4
4-5-6 6-6-4
6-5-4 6-4-6
6-4-5
5-6-4
5-4-6
4-6-5
(I think that's all the combinations, but you get the idea).
The most "efficient" solution I could come up with is to have arrays that define which numbers are altered, and how:
int[][] alterations = {
// 1 digit
{-1, 0, 0}, {0, -1, 0}, {0, 0, -1}, {1, 0, 0}, {0, 1, 0}, {0, 0, 1},
// 2 digits
{-1, -1, 0}, ...
};
And then modify the numbers according to each of the alteration arrays:
int[] numbers = {5, 5, 5};
for(int i = 0; i < alterations.length; i++) {
int[] copy = Arrays.copyOf(numbers, numbers.length);
for(int j = 0; j < alterations[i].length; j++) {
// note: this logic does not account for the numbers 0 and 9:
// 1 down from 0 translates to 9, and 1 up from 9 translates
// to 0, but you get the gist of how this is supposed to work
copy[j] += alterations[i][j];
}
printArray(copy);
}
...
private static void printArray(int[] a) {
String x = "";
for(int i : a)
x += i + " ";
System.out.println(x.trim());
}
But I'm wondering if there's a better way to do this. Has anyone come across something like this and has any better ideas?
Sounds like you're looking for backtracking since constructing the alterations array is quite tedious. In your backtracking algorithm you'd construct your candidates, apply the alteration, and check if the resulting combination is valid, if so then you'd print. I suggest you read Steven Skiena's Algorithms Design Manual Chapter 7 for some background information on backtracking and how it can be done with a combinatorial problem.
//Objective function
double[] c = new double[] { -1., -1. };
//Inequalities constraints
double[][] G = new double[][] {{4./3., -1}, {-1./2., 1.}, {-2., -1.}, {1./3., 1.}};
double[] h = new double[] {2., 1./2., 2., 1./2.};
//Bounds on variables
double[] lb = new double[] {0 , 0};
double[] ub = new double[] {10, 10};
//optimization problem
LPOptimizationRequest or = new LPOptimizationRequest();
or.setC(c);
or.setG(G);
or.setH(h);
or.setLb(lb);
or.setUb(ub);
or.setDumpProblem(true);
//optimization
LPPrimalDualMethod opt = new LPPrimalDualMethod();
opt.setLPOptimizationRequest(or);
opt.optimize();
These code are copied from JOptimizer official document. However, it only shows how to use inequality constraints in linear programming in JOptimizer. I am wondering how to represent an equality constraints in JOptimizer? I know I can achieve this goal by defining multiple inequality constraints, say Ax < b and -Ax < -b are the same thing as Ax=b. But is there any direct way for me to do this?
Okay, I've found the answer. It's quite easy. We just need to replace setG and setH with setA and setB.
I'm testing my neural network for XOR comparisons, and i've encountered an error i'd like to fix without altering the number of neurons in the first hidden layer. The code causing the error is:
public double dotProduct(int[][] a, double[][] ds)
{
int i;
double sum = 0;
for(i = 0; i < a.length; i++)
{
int j;
for(j = 0; j < a[i].length; j++)
{
sum += a[i][j] * ds[i][j];
}
}
return sum;
}
is giving me a null pointer exception. The dot product calculation itself is used to generate the dot product from an inputset my neural net has been provided with.
The input set is this:
int inputSets[][] =
{
{0, 0, 1},
{0, 1, 1},
{1, 0, 1},
{0, 1, 0},
{1, 0, 0},
{1, 1, 1},
{0, 0, 0}
};
It's a multidimensional array containing 7 arrays. It is then used in this:
public double think(int[][] input)
{
output_from_layer1 = sigmoid(dotProd.dotProduct(input, layer1.getWeights()));
return output_from_layer1;
}
The sigmoid part of the function isn't an issue, as it takes a double and
dotProduct is supposed to output a double. The issue as far as I'm aware is that the dotProduct function is taking a larger multidimensional array, and then attempting to cross it with a smaller one (The layer1.getWeights getter that calls the weights array for that layer).
The weights of a layer are defined as such:
layerWeights = new double[numNeurons][inpNum];
and the layer that's being used in the dot product is:
XORlayer layer1 = new XORlayer(4, 3);
So 4 neurons with 3 inputs each. The issue stems from the fact that there aren't enough neurons in this layer for the amount of inputs, as far as i'm aware, which is generating the null pointer exception when there isn't anything further to multiply against the input values.
We have 12 inputs in the neurons, and 21 input values.
My main question is, is there a way to solve this issue so the dot product operation is completed successfully without simply expanding the amount of neurons the layer contains to 7?
This discussion might help. As suggested there, since you're using a 2D array, matrix multiplication (instead of dot product) would likely be more appropriate.
Of course, similar to the dot product, the dimensions must be aligned for matrix multiplication.
inputSets is a 7x3 matrix and layerWeights is a 4x3 matrix. The transpose of layerWeights is a 3x4 matrix. Now the dimensions are aligned, and the matrix multiplication results in a 7x4 matrix.
Based on the posted code, I would suggest something like this:
output_from_layer1 = sigmoid(matrixMult.multiply(input, transpose(layer1.getWeights())));
I have a set of key codes, with values (mod 4 of course), 0 to 3 corresponding to the keys down, left, up, right, in that order. I need to convert these key codes into x and y directions, with a positive x indicating a location left of the origin, and an positive y indicating a location below the origin. The way I see it, I have two ways of doing this:
using arrays:
int [] dx = {0, -1, 0, 1};
int [] dy = {1, 0, -1, 0};
int x = dx[kc];
int y = dy[kc];
or using arithmetic:
int x = (kc%2)*(((kc/2)%2)*2 - 1);
int y = ((kc+1)%2)*(((kc/2)%2)*-2 + 1);
which would be more efficient?
It probably depends on the language. I would think the integer representation would be more efficient. Or better yet, if you need space you could represent directions with bit strings. You would need 4 bits for the four directions. Most ints are 4 bytes, which is 8x the storage! Then again, this probably doesn't affect anything unless you are storing a LOT of these.
I would abstract away the representation with direction methods (getDirection(), setDirection(), etc) and then try running your program with several different kinds.
Edit: woops, I meant to make this a comment, not an answer. Sorry about that.
Profiling would be your friend, but, I would separate your constants out in a different way. Consider:
private static final int[][] directions = {
{0, 1},
{-1, 0},
{0, -1},
{1, 0}
};
Then you can do it as simply:
x = directions[kc][0];
y = directions[kc][1];
First of all, I wouldn't really worry about the efficiency of either approach since it's very unlikely that this code will be the bottleneck in any real world application. I do however, think that the first approach one is much more readable. So if you value your maintenance and debugging time, that's the way to go.
If performance is that important, and this piece of code is critical, you should actually benchmark the two approaches. Use something like google caliper for that.
Second, you can optimize the second approach by replacing the (somewhat slow) modulus operation with a logical AND (x &= 0xfffffffe is the same as x%=2 only faster, assuming x is an int). And replacing the multiplication by 2 with a logical left shift (so x<<1 instead of x*2).
Here's yet another way to do the conversion.
package com.ggl.testing;
import java.awt.Point;
public class Convert {
public Point convertDirection(int index) {
// 0 to 3 corresponds to the keys down, left, up, right
Point[] directions = { new Point(0, 1), new Point(-1, 0),
new Point(0, -1), new Point(1, 0) };
return directions[index];
}
}
This is my first question in a community like this, so my format in question may not be very good sorry for that in the first place.
Now that my problem is I want to deep copy a 2 dimension array in Java. It is pretty easy when doin it in 1 dimension or even 2 dimension array with fixed size of rows and columns. My main problem is I cannot make an initialization for the second array I try to copy such as:
int[][] copyArray = new int[row][column]
Because the row size is not fixed and changes in each row index such as I try to copy this array:
int[][] envoriment = {{1, 1, 1, 1}, {0, 1, 6}, {1}};
So you see, if I say new int[3][4] there will be extra spaces which I don't want. Is there a method to deep copy such kind of 2 dimensional array?
I think what you mean is that the column size isn't fixed. Anyway a simple straightforward way would be:
public int[][] copy(int[][] input) {
int[][] target = new int[input.length][];
for (int i=0; i <input.length; i++) {
target[i] = Arrays.copyOf(input[i], input[i].length);
}
return target;
}
You don't have to initialize both dimensions at the same time:
int[][] test = new int[100][];
test[0] = new int[50];
Does it help ?
Java 8 lambdas make this easy:
int[][] copy = Arrays.stream(envoriment).map(x -> x.clone()).toArray(int[][]::new);
You can also write .map(int[]::clone) after JDK-8056051 is fixed, if you think that's clearer.
You might need something like this:
public class Example {
public static void main(String[] args) {
int[][] envoriment = {{1, 1, 1, 1}, {0, 1, 6}, {1}};
int[][] copyArray = new int[envoriment.length][];
System.arraycopy(envoriment, 0, copyArray, 0, envoriment.length);
}
}