I'm new to computer science. I've been told there is only 1 bug in the following Java type pseudo-code but i'm unable to figure it out. Isn't there more then 1? First the if statement means it won't loop as size doesn't equal max size, but i think the loop is also incorrect as rather then i<=size shouldn't it be i<=maxsize?
private int size = 0;
private int maxsize = 16;
private int[] arr = new int[maxsize];
public void append(val, list)
{
if (size == maxsize)
{
int[] newArr = new int[maxsize * 2];
for (i = 0; i <= size ; i )
newArr[i] = arr[i];
arr = newArr;
maxsize = maxsize*2;
}
arr[size ] = val;
}
Out of these options, which one is correct?
- Line 1 should read:
private int size = 16; - Line 7 should read:
if (size > maxsize) - Line 10 should read:
for (i = 0 ; i <= maxsize ; i ) - Line 13 should come before line 10
- Line 15 should read:
arr[ size] = val;
CodePudding user response:
There is certainly more than one bug/issue in this code. Here are some I found
- The for loop uses the variable
iwithout declaring it size = 0so the code inside the for loop never actually runsnewArrhas all of its elements set equal to the elements inarr, and then you go and assignarrtonewArr! This means that thenewArrvariable will point to the same array as thearrvariable, meaning they are no longer duplicates but rather the exact same piece of data- Your function takes in
listbut doesn't use it. This is clearly an issue if the function's intention was to append thevaltolist - Your function and maxsize constant should be static unless these are fields inside of an object and intend to be used as such
I've gone ahead and fixed your code: (Try it here)
public static void main(String args[]) {
int[] myInts = new int[]{1, 2, 4};
for(int i = 0; i < myInts.length; i ){
System.out.print(myInts[i] " ");
}
System.out.println();
myInts = append(5, myInts);
for(int i = 0; i < myInts.length; i ){
System.out.print(myInts[i] " ");
}
}
private static int maxsize = 16;
public static int[] append(int val, int[] list){
int size = list.length;
if(size < maxsize){
int[] newArr = new int[size 1];
for (int i = 0; i < size ; i ){
newArr[i] = list[i];
}
newArr[size] = val;
return newArr;
}
return list;
}
CodePudding user response:
There’s just an off-by-one error. The code is trying to copy size 1 elements from the old array into the new, but the old array only has size elements.
