I am working on a problem in which I have to compare two values within the 2D array but I am unable to get the output. Kindly help me to come out of this problem. Here's a glimpse of my code:
int arr[][]=new int[N][N];
for(j=0;j<arr.length;j++)
{
for(k=0;k<arr[j].length;k++)
{
if(arr[j][k]==arr[j][k+1])
c++;
}
}
The problem is that you will get an ArrayOutOfBoundsException due to the comparison if(arr[j][k]==arr[j][k+1]). This happens when you reach the last element of the array since when k is strictly less than arr[j].length, then k+1 element doesn't exist.
Maybe you want to change the condition to k<arr[j].length-1. But I am not sure what you actually what to achieve with the code.
Related
I am a beginner programmer working on a Two Sum problem. An array of integers are given as well as an integer, target. The intention of the program is to find which two numbers in the array of integers add up to the target integer. The most efficient solution I am seeing is quite ingenious in how it iterates over all of the integers in the array and checks if the difference between each integer in the array and the target number is another integer in the array. Then those two would be the solution. My issue is with the HashMap part. How would an empty HashMap .containsKey() work if it is empty and has no keys in it?
class Solution {
public int[] twoSum(int[] nums, int target) {
int n=nums.length;
Map<Integer,Integer> map=new HashMap<>();
int[] result=new int[2];
for(int i=0;i<n;i++){
if(map.containsKey(target-nums[i])){
result[1]=i;
result[0]=map.get(target-nums[i]);
return result;
}
map.put(nums[i],i);
}
return result;
}
}
I tried to research solution explanations but all of them just said that the solution checks if the values are in the map but how would any values be in the map if it is empty and was never linked to the integers array? Thanks a lot for the help.
I give you a phone book. I ask you if 'Ryan Siegrist' is in it. You open it up intending to scan it (or perhaps you're going to be smarter about it and use a fancy algorithm, such as binary searching by opening it to the middle page to see if you should go 'higher' or 'lower') - and it turns out the phone book is simply empty.
The correct answer is of course 'no, Ryan Siegrist is not in this empty phone book'.
HashMap is no different. .containsKey(whateverYouLike) returns false if you invoke it on an empty list. Why wouldn't it?
The stated algorithm does nothing the first time you loop, but note that at the end of the for look, whether the if ( containsKey ) check worked out or failed, an entry is added to the map. So the second and further runs through that loop, the map is no longer empty.
Short version:
If the map is empty and it does not contain a key. Then the line:
map.put(nums[i],i);
will still execute. This is because it is outside of the if check.
Long version
So when the code first iterates through the array, the HashMap is always empty at first because it was initialized as such:
Map<Integer,Integer> map=new HashMap<>();
Then the first iteration of the if check returns false:
if(map.containsKey(target-nums[i]))
But it still executes the line of code which will associate the map with the value of nums at the index of i with the index of i as the value for the map.
Then the loop will continue iterating until a solution is found or the loop terminates.
[the code is shown here ]
image link here
Traversal of the array is from behind and if you guys can show the dry run i would be grateful. solutions using only recursion would be grateful and i will provide the code if you want.
There is no need for a complex formular. You can get the last index with a simple command:
//Suppose you have any array named arr
int lastIndex = arr.length-1;
//you need -1 because length will start with 1, but index starts with 0.
At least if I understand your question correctly. If you want the first index, that will always be 0, unless if your array is null.
Does this help you?
I have a problem with the TSP algorithm
. I'm going to insert code and explain:
List listOfPermutations = new ArrayList();
while (cont.compareTo(deleteRutes) < 0) {
listOfPermutations.add(indexOfCities);
nextPermutation(indexOfCities);
....
The problem I have is the following,
my idea was to insert all possible permutations (arrays) in a list, but the problem is that the list always takes the same values of the array, it is logical since the indexOfCities array is only one. I've been giving it back for a while and I do not know how to solve it. Can someone help me?
indexOfCities holds a reference to an array. This same reference is added as item to listOfPermutations with
listOfPermutations.add(indexOfCities);
in each loop iteration.
Then the array is modified with
nextPermutation(indexOfCities);
in each loop iteration. So the stored references all point to the same modified array.
To solve this, add a copy of the array in indexOfCities to listOfPermutations instead. E.g. like so:
int[] indexOfCitiesAux = indexOfCities.clone();
listOfPermutations.add(indexOfCitiesAux);
I am trying to make a little game on my own to get used to Java and I just had a problem with LinkedList Index. I found a way to patch my problem but I still don't understand why my first solution is not working. This code:
for (int i=0; i <= PlanetList.size(); i++)
{
g.drawImage(PlanetList.get(i).planetImage, PlanetList.get(i).xPos, PlanetList.get(i).yPos);
}
Gave me a java.lang.IndexOutOfBoundsException but this code:
for (int i=1; i <= PlanetList.size(); i++)
{
g.drawImage(PlanetList.get(i-1).planetImage, PlanetList.get(i-1).xPos, PlanetList.get(i-1).yPos);
}
The thing is ... my index start at 0 in both case. Why does the first gives me an Error?
Your last index in the first example is going above the allowed index range. For e.g., if the size of the list is 10, the allowed index range is [0 9]. In your first loop, it goes up to 10 (i <= PlanetList.size()). Change the terminal condition to i < PlanetList.size() to fix your issue.
The alternate is to use no indices to access elements in your list as #GhostCat has suggested:
for (Planet planet : PlanetList) {
g.drawImage(planet.planetImage, planet.xPos, planet.yPos);
}
This is called for-each loop in Java
The other solution is to simply use the index-free version to iterate "collections" that was introduced years ago:
for (Planet planet : PlanetList) {
g.drawImage(planet.planetImage, planet.xPos, planet.yPos);
As a nice side effect, that also eliminates the code duplication that you had in your example.
And while we are at it: you are somehow violating the "tell dont ask" principle. Meaning: you are asking your planet object to give all the details you need to draw it. In good Object Oriented designs, you avoid that. Instead, you tell objects to do something. In other words: you could change your planet class to
public void drawWith(Graphics g) { ...
With that the above code can be rewritten as:
for (Planet planet : ... ) {
planet.drawWith(g);
YOU are getting the Out of bounds error because the variable i declared in the for loop is running for less than equal to condition of planetlist size as i starts from zero it will go till the linked list size but since you have given less than equal to it goes in the loop one more time therefore out of bounds exception .Just change the for loop condition to i less than linked list size it will work
Am working on some programming homework and am a bit lost. The project is to select the even/odd elements of a listarray and store in another array. It is not the even numbers in each element, but the elements themselves so if an array had values "1,2,5,7,9" and returned the even elements it would give "1, 5, 9". Also have to use recursion. Would anyone be able to give me a starting point or some advice. Though about starting with 2 elements and taking 2nd element and then building up from that, but don't know how it would add on the 2nd pass
public static ArrayList<Integer> even(ArrayList<Integer> list)
ArrayList<Integer> evenlist = ListMethods.deepClone(tList);//make copy of list
if (evenlist.size()<=1) // The list is empty or has one element
{
// return null;// Return the list as is
}
if
(evenlist.size()==2)
{
//return right element
//call method again
//add to list
}
Psuedocode
int[] evens,odds;
function categorize(List<Integer> in,int idx)
if(idx>=in.length)
return
int cur = in[idx]
if(even), add to evens
else add to odds
categorize(in,idx+1)
This sounds similar to the homework I just completed, so if it is (And you're in my class!), I'll not tell you to use any terminology we haven't covered as I know it can be daunting trying to discover something new for practicals (beyond what we have to do).
First, set your exit condition. As you've already said, you have to create a new ArrayList out of the existing one. You are going to remove items from the existing ArrayList, storing the integers that are at even (or odd) indices, until the list is empty.
So your exit condition is:
if (evenList is Empty)
return evenList;
Then, work your way through the steps. I would advise determining if the Array you start with has an even of odd number of steps, something like this:
if (evenList has Even Elements)
int holderForIntsAtEvenElements = last evenList EVEN element
Note we start at the last element, so when you are coming OUT of the recursive method, this will be the last one added to your new ArrayList, and thus it'll be in numerical order. You might find this post interesting to do this: What does this boolean return mean?
We then want to remove the last element from the list and recursively call the method again.
Finally, when we hit our exit condition and start to come out, we want to add the ints we've been storing to them, e.g.:
evenList.add(holderForIntsAtEvenElements);
return evenList;
That doesn't solve one problem, which is what to do with the very first element if the list does NOT have an even number of elements - however, I'll let you try and solve that!
That's a good mix of code and pseudo code and will hopefully help to get you on the right track.
You could use a simple for loop like this:
for (int i = 0; i < list.size(); i += 2) {
System.out.println(list.get(i));
}
If you have to use recursion, here's an outline of the steps you might take. (I won't tell you exactly what to do because you haven't tried anything and it is like homework.)
Take first element and store it
Remove (new) first element from list
Call self