Good evening folks, total newbie here. I need to rewrite a code segment that my teacher gave me, in order to create an animation for a labyrinth solver and my teacher used an ArrayList<int[]> nodes = new ArrayList<int[]>(); to store the walked path (x/y coordinates).
The coordinates are stored via nodes.add(new int[]{x,y});
Now, when the solver has to "walk" backwards after a dead end, the nodes have to be removed from the ArrayList and I want to check if a coordinate is a node. In this case I want to know if the last added node is the coordinate I'm going to.
When I print System.out.println(nodes.get(nodes.size()-1)) I get something like this: [I#6cbb6079
How can I compare nodes.get(nodes.size()-1) and int x = 5, y = 7; for example ?
Compare the values from the node (it is the array, so use [] brackets) with the x and y values:
if (nodes.get(nodes.size()-1)[0] == x && nodes.get(nodes.size()-1)[1] == y)
System.out.println("equals");
If you had Node class you could implement the equals() method for it and use it in this way:
if (nodes.get(nodes.size()-1).equals(new Node(x,y)))
System.out.println("equals");
you are getting array element at location array size -1.
Just need to get value from array index , add index you will get result
like -
nodes.get(nodes.size()-1)[0]
nodes.get(nodes.size()-1)[1]
That is reference that is print out since you are printing an array! Try to print out with index.
For example: System.out.println(nodes.get(nodes.size()-1)[0]) for the x and System.out.println(nodes.get(nodes.size()-1)[1]) for the y.
Related
I looked up the solution to this problem yesterday and tried to solve on my own today but found myself trying to solve this problem in a different way. I feel I may be overcomplicating the problem but I still want an answer to my possible solution just because it is bugging me to know (I am sure everyone has experienced this at some point or another). Anyway here is the problem:
https://www.hackerrank.com/challenges/ctci-array-left-rotation/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=arrays
My idea is that you would first check to see if your array length was equal to the rotations you want then you would simply return the original. There is no work needed to be done.
My next idea would be to check to see if our rotations is greater than our array length. If this is the case, we can either do rotations - array length or ABS VALUE(array length - rotations), which gives us the same result. We can reassign this value to D.
Next, we can create a case to rotate right instead of left. When your rotation is greater than your array length / 2, then we would not to rotate left since we are doing extra work. We instead would want to rotate right. For example:
Array Length 4
Rotations 3 (LEFT)
We can simply rotate right once instead of rotating left 3 times. We could set the rotateRight boolean to true (otherwise set to false which indicated to rotateLeft as normal)
Anyway this is the part I get caught on. I am unsure of how to rotate my elements here. I was thinking of returning a new array. How can I get the correct values for my new array? I am facing issues with IndexOutOfBounds exceptions. Can I also use try catches in this example or is it overkill?
Here is the code I have currently it should match my thoughts from up above:
static int[] rotLeft(int[] a, int d) {
int aLength = a.length;
int counter = 0;
int[] newArray = new int[aLength];
boolean rotateRight = false;
if (aLength == d) {
return a;
}
if (a.length - d < 0) {
d = Math.abs(a.length - d);
}
if(d > a.length/2) {
rotateRight = true;
}
return newArray;
}
If you need any more info let me know.
There is little benefit to trying to simplify the maths, if it leads to a harder-to-write program -- especially since you do not want to rotate the array at all, and can simply place the correct values in the correct places directly.
If the old position of element i was i, after d left-rotations of an array of size len, its new position will be (i-d)%len. If d == len+1 this is indeed equivalent to (i+1)%len -- easier for humans, but computers calculate either expression just as happily.
So the suggested code is:
static int[] rotLeft(int[] a, int d) {
int[] b = new int[a.length];
for (int s=d, t=0; t<a.length; s++, t++) {
// t is target position; s is source position
b[t] = a[s%a.length];
}
return b;
}
Note: code is untested
I have a pseudo code that I have translated into java code but anytime I run the code, I get an empty arraylist as a result but it is supposed to give me a random list of integers.
Here is the pseudo code:
Algorithm 1. RandPerm(N)
Input: Number of cities N
1) Let P = list of length N, (|P|=N) where pi=i
2) Let T = an empty list
3) While |P| > 0
4) Let i = UI(1,|P|)
5) Add pi to the end of T
6) Delete the ith element (pi) from P
7) End While
Output: Random tour T
Here is the java code:
public static ArrayList<Integer> RandPerm(int n)
{
ArrayList<Integer> P = new ArrayList<>(n);
ArrayList<Integer> T = new ArrayList<>();
int i;
while(P.size() > 0)
{
i = CS2004.UI(1, P.size());// generate random numbers between 1 and the size of P
T.add(P.get(i));
P.remove(P.get(i));
}
return T;
}
I don't know what I am doing wrong.
ArrayList<Integer> p = new ArrayList<>(n);
... creates an empty list with an initial capacity of n.
All this does is tell the ArrayList what size array to initialise as backing store - most of the time you achieve nothing useful by specifying this.
So your while(p.size() > 0) runs zero times, because p.size() is zero at the start.
In the pseudocode "where pi=i" suggests to me that you want to initialise the list like this:
for(int i=0;i<n;i++) {
p.add(i)
}
(I have lowercased your variable name - in Java the convention is for variables to startWithALowerCaseLetter -- only class names StartWithUpperCase. It's also the Java convention to give variables descriptive names, so cityIdentifiers perhaps)
You may want to know that, even if you fix the problem that P is always empty, there are 2 more issues with your implementation.
One is that P.remove(P.get(i)) does not necessarily remove the ith item if the list has equal value items. It scans from the beginning and removes the first occurrence of the item. See ArrayList.remove(Object obj). You should use P.remove(i) instead for the correct results.
Then the performance is O(n^2). The reason is that ArrayList remove an item by shifting all the subsequent items one slot to the left, which is an O(n) operation. To get a much better performance, you can implement your own "remove" operation by swapping the item to the end. When you generate the next random index, generate it within the range [0, beginning index of the removed items at the end). Swapping is O(1) and the overall performance is O(n). This is called Knuth Shuffle by the way.
This is the problem:
"A 2d array of ints will be used to represent the value of each block in a city. The value could be negative indicating the block is a liability to own. Complete a method that finds the value of the most valuable contiguous sub rectangle in the city represented by the 2d array. The sub rectangle must be at least 1 by 1. (If all the values are negative "the most valuable" rectangle would be the negative value closest to 0.)
Consider the following example. The 2d array of ints has 6 rows and 5 columns per row, representing an area of the city. The cells with the square around it represent the most valuable contiguous sub rectangle in the given array. (Value of 15.)"
I am completely stumped as to how to go about solving this. I'm thinking that I could start on every single value and make every possible subplot with it and update a variable for the highest value. Is there another way of going about doing this? I'm not looking for the answer, I just need some guidance. Thanks
int most=-10000;
int current=0;
for(int i=0;i<city.length;i++){
for(int j=0;j<city.length;j++){
current+=city[i][j];
if(current>most){
most=current;
}
}
}
return most;
This is my attempt so far. Hopefully you guys can see where I'm going with it. I start at 0,0 and check the entire line and update most accordingly.
The algorithm is to explore all rectangular shapes, and scan the city for that shape. The maximum value is found in a particular shape in a particular part of the city.
Algorithm (assume the city is NxM):
Set MAX = Lowest value in the city
// ROW / COL represent the shape of the rectangle
for ROW = 1 to N
for COL = 1 to M
// scan the city for a shape the size of ROWxCOL
for POS_X = 0 to N-ROW
for POS_Y = 0 to M-COL
// You now have a top,left co-ordinate for the shape (POS_X,POS_Y)
// This represents the position in the city[][] array
SUM Values from co-ordinate POS_X,POS_Y to POS_X+ROW-1, POS_Y+COL-1
IF SUM>MAX; MAX=SUM
PRINT MAX
Can someone explain to me the answer?
What does x equal at the end?
int[] vs = {4, 15, 6, 26, 7, 8};
int x = vs[0];
for (int v : vs)
{
if (v < x) { x = v; }
}
I'll give this another try since I find sfThomas' answer a little confusing.
So:
The answer to your question upfront: x will equal 4. And the purpose of your little algorithm is simply to find the smallest (numerical) value in a given list of values.
Detailed explanation:
In line 1 you set up an array (think of it as an ordered list of values) of integer values (aka "whole numbers"). This array is called vs.
In line 2 you assign the variable x to the first element within vs. This happens to be 4.
Line 3 a for-each loop (official terminology in Java: "Enhanced for Loop") is declared. It executes the loop body (lines 4-6) for each element of the array vs. In each iteration v will hold the value of the currently processed element. Processing order equals declaration order. Thus: In the first iteration v will equal 4, in the second 15 and so on.
A traditional for loop to accomplish the same is given below.
The body of your loop (line 5) consists of a check whether v is ever smaller than x. This is never the case (i.e. there is no value within your array vs that is smaller than the value of the first element of vs) and therefore the code within the brackets x = v; (which would reassign x to the value of this smaller element every time such a smaller element is found) never gets executed. In other words: x always stays with its initial value vs[0] and that is 4.
I hope this was clear enough for a beginner.
for (int i=0; i<vs.length; i++) {
int v = vs[i];
// rest of the loop body
}
It looks for the smallest element in your array - the last part iterates over each element, and if it finds one that is smaller than the previous value, saves that instead in variable 'x'.
for (int v : vs) - this executes the block that is after with each value in the vs array, in a way that variable v is assigned to the given value.
Have a look at this.
{ if (v < x) { x = v; }} - this checks if the current v value is smaller than x, and then if so, saves that value in x.
I'm doing a project in Java which includes (x,y) coordinates.
I have created a class of Cell which has protected integers X & Y;
Upon initialization, i do a for loop which sets an array of cell by multiplying the X & Y given by the user, say if X= 10 and Y = 10, i create an array of cells[100].
However, how can i search the array fast, without doing a for loop and checking each individual value very time?
Say I'm looking for the object that contains X=5 & y = 3.
I know i can go through with a for loop looking for object with values x and y, but i was wondering if there is a way to do a binary search and find "a bit faster" the object[i] that contains X=5 and Y=5.
Thank you very much.
The way to do this is to arrange the Cell objects in the array in a way so that there is a simple mapping from an X,Y coordinate to the Cell's index in the array.
For example, lets assume that X and Y go from 1 to 10. Suppose that we then arrange the Cells so that:
array[0] = Cell(1, 1);
array[1] = Cell(1, 2);
...
array[9] = Cell(1, 10);
array[10] = Cell(2, 1);
array[11] = Cell(2, 2);
...
array[99] = Cell(10, 10);
It should be easy to see that we can calculate the index of Cell(i,j) in the array and fetch the cell as follows:
public Cell getCell(Cell[] array, int i, int j) {
int index = (10 * (i - 1)) + (j - 1);
return array[index];
}
This is the approach that programming languages that support N-dimensional array types typically use to implement them.
This can be trivially modified to deal with cases where:
the constant 10 is something else
the matrix is not square,
the matrix has more than two dimensions
indexes run from 0 to N - 1 instead of 1 to N
etcetera
There are various other ways that you could represent 2-D matrices in Java. The simplest one is just using a Cell[][] cells which allows you to access cells as (for example) cells[i-1][j-1]. More complicated representations can be designed that use less space if the matrix is sparse (i.e. cells are missing) at the cost of more complex code and slower access times.
It sounds like (if you want to use binary search, anyway) you're setting element 0 to the Cell with x = 0, y = 0; element 1 to x = 0, y = 1, etc. If so you should be able to trivially compute the exact index of a given Cell:
// contains the Cell with x = desiredX, y = desiredY
yourArray[desiredX * X + desiredY];
If this is what you're doing, however, it'd probably be simpler to just make a 2-dimensional array:
yourArray = new Cell[X][Y];
...
yourArray[desiredX][desiredY];
the above two answers show the trivial method for getting the array index fast. id like to propose an alternative- use hashmaps with key, value pairings. the value could be objects. accessing hashmap elements run in constant time..