Index out of Bounds? - java

Vertex [] vertices = new Vertex[n];
int [] numbers = new int[n*2];
AdjacencyList[] all = new AdjacencyList [n+1];
for (Vertex v : vertices)
{
System.out.println(v.value);
AdjacencyList a = new AdjacencyList(v);
for (int i = 0; i < n; i += 2)
{
if (numbers[i] == v.value){
a.connected[i] = vertices[i+1];//array index out of bounds exception:19
else { a.connected[i] = v; }
}
all[0] = a; //add the finished adjacency list to the array
}
with n = 19 can I'm getting an index out of bounds error at the point indicated in the code. I'm not sure where I'm going wrong, as everything is still within the bounds of 19
vertices = list of Vertex [1-19],
numbers is a flattened array of edges

In the line:
a.connected[i] = vertices[i+1];
You call the index i+1. This will result in an index out of bounds exception. (In your example of when n equals 19: The valid index's will be [0-18]. Your loop will go from 0-18. But in the line it will then add one to it. 18+1 = 19, which is an invalid index)
In your loop change the condition to:
for (int i = 0; i<n-1; i+=2){
To make sure it will not go out of bounds when you add one.

Your array has length, n=19, meaning index [0-18] and i is incremented by 2.
So when i = 18,
a.connected[i] = vertices[i+1];
tries to access vertices[19] which is not existent. Hence ArrayOutOfBoundException. Hope this helps.

Related

Trying to create a array with the intersection of two arrays but fails at creating array with the proper structure

So, I am trying to create 2 randomly generated arrays,(a, and b, each with 10 unique whole numbers from 0 to 20), and then creating 2 arrays with the info of the last two. One containing the numbers that appear in both a and b, and another with the numbers that are unique to a and to b. The arrays must be listed in a "a -> [1, 2, 3,...]" format. At the moment I only know how to generate the 2 arrays, and am currently at the Intersection part. The problem is, that I can create a array with the correct list of numbers, but it will have the same length of the other two, and the spaces where it shouldn't have anything, it will be filled with 0s when its supposed to create a smaller array with only the right numbers.
package tps.tp1.pack2Arrays;
public class P02ArraysExtractUniqsAndReps {
public static void main(String[] args) {
int nbr = 10;
int min = 0;
int max = 20;
generateArray(nbr, min, max);
System.out.println();
}
public static int[] generateArray(int nbr, int min, int max) {
int[] a = new int[nbr];
int[] b = new int[nbr];
int[] s = new int[nbr];
s[0] = 0;
for (int i = 0; i < a.length; i++) {
a[i] = (int) (Math.random() * (max - min));
b[i] = (int) (Math.random() * (max - min));
for (int j = 0; j < i; j++) {
if (a[i] == a[j]) {
i--;
}
if (b[i] == b[j]) {
i--;
}
}
}
System.out.println("a - > " + Arrays.toString(a));
System.out.println("b - > " + Arrays.toString(b));
for (int k = 0; k < a.length; k++) {
for (int l = 0; l < b.length; l++) {
if (a[k] == b[l]) {
s[l] = b[l];
}else {
}
}
}
System.out.println("(a ∪ (b/(a ∩ b)) - > " + Arrays.toString(s));
return null;
}
public static boolean hasValue(int[] array, int value) {
for (int i = 0; i < array.length; i++) {
if (array[i] == value) {
return true;
}
}
return false;
}
}
Is there any way to create the array without the incorrect 0s? (I say incorrect because it is possible to have 0 in both a and b).
Any help/clarification is appreciated.
First, allocate an array large enough to hold the intersection. It needs to be no bigger that the smaller of the source arrays.
When you add a value to the intersection array, always add it starting at the beginning of the array. Use a counter to update the next position. This also allows the value 0 to be a valid value.
Then when finished. use Array.copyOf() to copy only the first part of the array to itself, thus removing the empty (unfilled 0 value) spaces. This works as follow assuming count is the index you have been using to add to the array: Assume count = 3
int[] inter = {1,2,3,0,0,0,0};
inter = Arrays.copyOf(inter, count);
System.out.println(Arrays.toString(inter);
prints
[1,2,3]
Here is an approach using a List
int[] b = {4,3,1,2,5,0,2};
int [] a = {3,5,2,3,7,8,2,0,9,10};
Add one of the arrays to the list.
List<Integer> list = new ArrayList<>();
for(int i : a) {
list.add(i);
}
Allocate the intersection array with count used as the next location. It doesn't matter which array's length you use.
int count = 0;
int [] intersection = new int[a.length];
Now simply iterate thru the other array.
if the list contains the value, add it to the intersection array.
then remove it from the list and increment count. NOTE - The removed value must be converted to an Integer object, otherwise, if a simple int value, it would be interpreted as an index and the value at that index would be removed and not the actual value itself (or an Exception might be thrown).
once finished the intersection array will have the values and probably unseen zeroes at the end.
for(int i = 0; i < b.length; i++) {
int val = b[i];
if (list.contains(val)) {
intersection[count++] = val;
list.remove(Integer.valueOf(val));
}
}
To shorten the array, use the copy method mentioned above.
intersection = Arrays.copyOf(intersection, count);
System.out.println(Arrays.toString(intersection));
prints
[3, 2, 5, 0, 2]
Note that it does not matter which array is which. If you reverse the arrays for a and b above, the same intersection will result, albeit in a different order.
The first thing I notice is that you are declaring your intersection array at the top of the method.
int[] s = new int[nbr];
You are declaring the same amount of space for the array regardless of the amount you actually use.
Method Arrays.toString(int []) will print any uninitialized slots in the array as "0"
There are several different approaches you can take here:
You can delay initializing the array until you have determined the size of the set you are dealing with.
You can transfer your content into another well sized array after figuring out your result set.
You could forego using Array.toString, and build the string up yourself.

java.lang.IndexOutOfBoundsException: Index: 1, Size: 1 in arrays

hello # all i have this probleme i have two arraylist ta,ta1
ta is an 1D arraylist contain many string objects in every frame i got only one object i want to forme a new ArrayList ta1 witch take two or more object colectted from ta in n=2 case we got
1with2 2with3 3with4 ....
example i have n=2;
ta [aa,bb,cc,dd]
ta1 will be [aabb,bbcc,ccdd]
i have tried with this
String m = "";
String h = "";
int e = 0;
for (int i = 0; i <= ta.size(); i++) {
int n = Integer.parseInt(tt.getText());
while (n > 0) {
String t = (ta.get(e + i));
m = m + t;
e++;
n--;
}
ta1.add(m);
}
t3.setText(ta1.toString());
but its giving me that error in the title
tanks for your help in advance
First of all i<=ta.size() is wrong, since the valid indices of ta go from 0 to ta.size()-1.
Second of all, in your while loop you assume that e+i is a valid index in ta, which is also an assumption you can't make without testing first that e+i<ta.size().
First you should move
int n=Integer.parseInt(tt.getText());
to be before the for loop.
This way, changing
for (int i=0;i<=ta.size();i++)
to
for (int i=0;i<=ta.size()-n;i++)
will ensure that e+i<ta.size().
You should also reset the relevant variables in the correct place. I think this should work :
int n = Integer.parseInt(tt.getText());
for (int i=0;i<=ta.size()-n;i++){
int c = n;
String m = "";
int e = 0 ;
while(c>0){
String t=(ta.get(e+i));
m=m+t;
e++;
c--;
}
ta1.add(m);
}
t3.setText(ta1.toString());
for (int i=0;i<=ta.size();i++){
ArrayList is a 0 based index collection. That means that you go from 0 to size - 1. At the moment, you're going from 0 to size, which is causing the IndexOutOfBoundsException.

Iterating an array from both ends using two indices

This is more of an self defined programming exercise than a real problem. I have an array of java.lang.Comparable items. I need to maintain two pointers (an index into the array i.e., int values) i,j . i starts at the beginning of array and moves right until it encounters an element which is less than or equal to the previous element. When it does it stops moving right and ends up pointing to the element which is out of order(element which is not greater than the previous). Similarly j starts at the end of the array and moves left until it finds an element which is not less than the previous.
Also, I need to make sure that the indices don't run out of the array i.e., i cannot go below 0 and j cannot go above arraylength-1
lets say we have an array of 5 elements.
i = 0;
j = 4;(which is the arraylength-1 )
if C,D,E,F,G is the array ,the final values of i and j will be
i = 4 and j = 0
if array is J,D,E,F,G ,the final values of i, j will be
i = 0 , j = 0
if array is B,C,A,D,G , final values of i,j will be
i = 2 , j = 1
I tried to code the logic for moving i to the right, using a while loop as below. I was able to get it working for the i pointer in two cases.
public class PointerMovement{
public static void ptrsPointToOutOfOrderElements(Comparable[] a){
int lo = 0;
int hi = a.length-1;
int i = lo;
int t=i+1;
int j = hi;
//only for moving i to the right .
while(less(a[i],a[t])){
if(t == hi){
i=t;
break;
}
i++;
t++;
}
i=t;
for(Comparable x:a){
System.out.print(x+",");
}
System.out.println();
System.out.println("bad element or end of array at i="+i+"==>"+a[i]);
}
private static boolean less(Comparable x,Comparable y){
return x.compareTo(y) < 0;
}
public static void main(String[] args) {
String[] a = new String[]{"C","D","E","F","G"};//works
//String[] a = new String[]{"B","C","A","D","G"};//works
//String[] a = new String[]{"J","D","E","F","G"};//fails!
ptrsPointToOutOfOrderElements(a);
}
}
My line of reasoning given below
I maintain i=0; and another variable t=i+1
when the while loop fails, less(a[i],a[t]) is false .We need to return a pointer to a[t] which is out of order. so i=t and return i.
if we reach right end of array, the test if(t == hi) passes and we assign i=t and now i points to end of array.
However, the code fails when the out of order element is in the 0th position in the array.
J,D,E,F,G
Instead of i (=0) we get i=1 because i=t is assgined.i ends up pointing to D instead of J.
Can someone point me in the right direction?
update:
this seems to work
public static void ptrsPointToOutOfOrderElements(Comparable[] a){
int lo = 0;
int hi = a.length-1;
int i = lo;
while(less(a[i],a[i+1])){
if(i+1 == hi){
break;
}
i++;
}
i++;
int j = hi;
while(less(a[j-1],a[j])){
if(j-1 == lo){
break;
}
j--;
}
j--;
for(Comparable x:a){
System.out.print(x+",");
}
System.out.println();
if(i>=j){
System.out.println("pointers crossed");
}
System.out.println("bad element or end of array at i="+i+"==>"+a[i]);
System.out.println("bad element or end of array at j="+j+"==>"+a[j]);
}
I do not think you have a problem:
String[] a = new String[]{"C","D","E","F","G"};//works, index should be 4 (but should it be so? It would indicate that G is out of order while it is not. I think you should return 5, indicating that none is out of order.
String[] a = new String[]{"B","C","A","D","G"};//works, index should be 2 as A is out of order
String[] a = new String[]{"J","D","E","F","G"};//works since the first out of order element is indeed D, with index 1
I have tried using simple for loop.
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
for (var i = 0, j = arr.length - 1; i <= j; i++, j--) {
console.log(arr[i] + ' , ' + arr[j]);
}
Output :
1 , 10
2 , 9
3 , 8
4 , 7
5 , 6

2D array and an out of bounds exception

The last for loop will compile but it won't run. It says that array index out of bounds exception:17. I just want to add a ColorRectangles (subclass of ColorShape) to the 1-8 columns in the 17'th row
private ColorShape[][] _tiles;
public GamePanel()
{
_tiles = new ColorShape[8][17];
for (int i = 0; i<16; i++){
for(int j=0; j<8;j++){
_tiles[j][i] = null;
}
}
for (int j=0; j<8;j++){
_tiles[j][17] = new ColorRectangle(Color.BLACK);
}
}
Your array size is 17. Arrays are zero-indexed. This means your maximum array index for your second dimension is actually 16, not 17.
Either change your reference to tiles to:
_tiles[j][16] = new ColorRectangle(Color.BLACK);
OR make your _tiles array bigger like so:
_tiles = new ColorShape[8][18];
Either will fix this problem.
May I also suggest that your game panel object accept 2 dimensions, width and height. This makes your class more useable should you decide to use it again, or change its dimensions. Avoid hardcoding values whenever appropriate. Here it would be most appropriate.
Here's a rewrite for you:
private ColorShape[][] _tiles;
public GamePanel(int width, int height)
{
_tiles = new ColorShape[width][height];
for (int i = 0; i<height; i++){
for(int j=0; j<width;j++){
_tiles[j][i] = null;
}
}
for (int j=0; j<width;j++){
_tiles[j][tiles[j].length-1] = new ColorRectangle(Color.BLACK);
}
}
And here's how you would use it in your case:
GamePanel panel = new GamePanel(8, 17);
But you can always easily change your panels dimensions now!
GamePanel panel = new GamePanel(100,100);
Nifty huh?
This:
_tiles[j][17] = new ColorRectangle(Color.BLACK);
17 is not a valid index for your array since you sized it as [8][17]. Indices are from 0...length - 1, so in your case, up to 16. This is because arrays in Java (and any reasonable programming language) are zero-indexed. Thus, replace with
_tiles[j][16] = new ColorRectangle(Color.BLACK);
and at least you won't get an ArrayIndexOutOfBoundsException.
I just want to add a ColorRectangles (subclass of ColorShape) to the 1-8 columns in the 17'th row
See, in a zero-based indexing scheme, the 17th row is the row with index 16.
The first row corresponds to that with index 0. The second row corresponds to that with index 1. Etc. In general, the nth row corresponds to that with index n - 1 and a row with index n is actually the (n + 1)th row (assuming 0 <= n < length - 1).
Your problem is here:
_tiles[j][17] = new ColorRectangle(Color.BLACK);
You should have this instead (note that arrays are zero-indexed, so 17th column is at index 16):
_tiles[j][16] = new ColorRectangle(Color.BLACK);
In java, indexing starts from zero (0);
private ColorShape[][] _tiles;
public GamePanel()
{
_tiles = new ColorShape[8][18]; // new dim is 18 so last index is 17
for (int i = 0; i<18; i++){
for(int j=0; j<8;j++){
_tiles[j][i] = null;
}
}
for (int j=0; j<8;j++){
_tiles[j][17] = new ColorRectangle(Color.BLACK); //17 was out of bounds
}
}
The length of your array is [8][17] but the indexes go from [0] to [16].
Therefor replace
_tiles[j][17] = new ColorRectangle(Color.BLACK);
with
_tiles[j][16] = new ColorRectangle(Color.BLACK);
You're declaring your array with 8 fields in x range and 17 fields in y range in your code:
_tiles = new ColorShape[8][17];
Because you start counting from zero in the IT, the range is from zero to sixteen (0-16).
So if you want the last field of the array, you have to use the field 16 (_tiles[j][16]).
The code should be:
_tiles[j][16] = new ColorRectangle(Color.BLACK);
The whole thing is called zero-based-numbering/index.
You might also have a bug for the first loop.
Instead of
for (int i = 0; i<16; i++)
it should be
for (int i = 0; i<17; i++)
Arrays are zero-indexed meaning the starting index is 0 up to length-1.
So, in your case, it is up to 16.
For your second loop, it should be
_tiles[j][16] = new ColorRectangle(Color.BLACK);
According to the JLS (Array Access) - All arrays are 0-origin. An array with length n can be indexed by the integers 0 to n-1.
So if you initialize an array like you did _tiles = new ColorShape[8][17];. In order to access you need to do it by 0 to 7 and 0 to 16.
Now, with _tiles[j][17] = new ColorRectangle(Color.BLACK); you are trying to access something with is outside the array you have initialized and therefore you get java.lang.ArrayIndexOutOfBoundsException.

Remove every 3rd element in arraylist

I am trying to loop through an arraylist and gradually remove an element every 3 indices. Once it gets to the end of the arraylist I want to reset the index back to the beginning, and then loop through the arraylist again, again removing an element every 3 indices until there is only one element left in the arraylist.
The listOfWords is an array with a length of 3 that was previously filled.
int listIndex = 0;
do
{
// just to display contents of arraylist
System.out.println(listOfPlayers);
for(int wordIndex = 0; wordIndex < listOfWords.length; wordIndex++
{
System.out.print("Player");
System.out.print(listOfPlayers.get(wordIndex));
System.out.println("");
listIndex = wordIndex;
}
listOfPlayers.remove(listOfPlayers.get(listIndex));
}
while(listOfPlayers.size() > 1);
I have tried to implement for several hours yet I am still having trouble. Here's what happens to the elements of the arraylist:
1, 2, 3, 4
1, 2, 4
1, 2
Then it throws an 'index out of bounds error' exception when it checks for the third element (which no longer exists). Once it reaches the last element I want it to wrap around to the first element and continue through the array. I also want it to start where it left off and not from the beginning once it removes an element from the arraylist.
Maybe I have just missed the boat, but is this what you were after?
import java.util.ArrayList;
import java.util.Random;
public class Test {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<Integer>();
Random r = new Random();
//Populate array with ten random elements
for(int i = 0 ; i < 4; i++){
numbers.add(r.nextInt());
}
while(numbers.size() > 1){
for(int i = 0; i < numbers.size();i++){
if(i%3 == 0){//Every 3rd element should be true
numbers.remove(i);
}
}
}
}
}
You could move every third element to a temporary list then use List#removeAll(Collection) to remove the items when you finish each loop...until the master list was empty...
Lets back up and look at the problem algorithmically.
Start at the first item and start counting.
Go to the next item and increment your count. If there is no next item, go to the beginning.
If the count is '3', delete that item and reset count. (Or modulo.)
If there is one item left in the list, stop.
Lets write pseudocode:
function (takes a list)
remember what index in that list we're at
remember whether this is the item we want to delete.
loop until the list is size 1
increment the item we're looking at.
increment the delete count we're on
should we delete?
if so, delete!
reset delete count
are we at the end of the list?
if so, reset our index
Looking at it this way, it's fairly easy to translate this immediately into code:
public void doIt(List<String> arrayList) {
int index = 0;
int count = 0;
while(arrayList.size() != 1) {
index = index + 1;
count = count + 1; //increment count
String word = arrayList.get(index);//get next item, and do stuff with it
if (count == 3) {
//note that the [Java API][1] allows you to remove by index
arrayList.remove(index - 1);//otherwise you'll get an off-by-one error
count = 0; //reset count
}
if (index = arrayList.size()) {
index = 0; //reset index
}
}
}
So, you can see the trick is to think step by step what you're doing, and then slowly translate that into code. I think you may have been caught up on fixing your initial attempt: never be afraid to throw code out.
Try the following code. It keeps on removing every nth element in List until one element is left.
List<Integer> array = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
int nth = 3;
int step = nth - 1;
int benchmark = 0;
while (array.size() > 1) {
benchmark += step;
benchmark = benchmark > array.size() - 1 ? benchmark % array.size() : benchmark;
System.out.println(benchmark);
array.remove(array.get(benchmark));
System.out.println(array);
}
You could use a counter int k that you keep incrementing by three, like k += 3. However, before you use that counter as an index to kick out any array element, check if you already went beyond and if so, subtract the length of this array from your counter k. Also make sure, to break out of your loop once you find out the array has only one element left.
int k = -1;
int sz = list.length;
while (sz > 1)
{
k += 3;
if (k >= sz)
{
k -= sz;
}
list.remove(k);
sz --;
}
This examples shows that you already know right away how often you will evict an element, i.e. sz - 1 times.
By the way, sz % 3 has only three possible results, 0, 1, 2. With a piece of paper and a cup of coffee you can find out what the surviving element will be depending on that, without running any loop at all!
You could try using an iterator. It's late irl so don't expect too much.
public removeThirdIndex( listOfWords ) {
Iterator iterator = listOfWords.iterator
while( iterator.hasNext() ){
iterator.next();
iterator.next();
iterator.next();
iterator.remove();
}
}
#Test
public void tester(){
// JUnit test > main
List listOfWords = ... // Add a collection data structure with "words"
while( listOfWords.size() < 3 ) {
removeThirdIndex( listOfWords ); // collections are mutable ;(
}
assertTrue( listOfWords.size() < 3 );
}
I would simply set the removed to null and then skip nulls in the inner loop.
boolean continue;
do {
continue = false;
for( int i = 2; i < list.length; i += 3 ){
while( list.item(i++) == null && i < list.length );
Sout("Player " + list.item(--i) );
continue = true;
}
} while (continue);
I'd choose this over unjustified shuffling of the array.
(The i++ and --i might seem ugly and may be rewritten nicely.)

Categories