Click here to Skip to main content
15,896,557 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello Codeproject community,

I'm working on a problem asking me to write a method to insert a element element into an array arr at the index index. My code attached below:

The grading system uses a randomized element, array, and index, but every time it runs the array that I return seems to miss an element. Here's one of the grading results:

Expected result: 
{11, 10, 78, 59, 35, 46, 84, 84, 34, 90}

Your result: 
{11, 10, 78, 59, 35, 46, 84, 84, 34}


Thank you

What I have tried:

Java
public void add(int index, int element)
    {
        int tempArr[] = new int[arr.length + 1];

        for(int i = 0; i < index; i++)
        {
            tempArr[i] = arr[i];
        }
        tempArr[index] = element;
        for(int i = index; i < arr.length; i++)
        {
            tempArr[i + 1] = arr[i];
        }
        arr = tempArr;
    }


Full source code:
Java
<pre>public class ExpandingArray
{
    private static final int STARTING_SIZE = 10;
    private int[] arr;
    private int currentSize;
    private int numElements;
    
    public ExpandingArray()
    {
        arr = new int[STARTING_SIZE];
        currentSize = STARTING_SIZE;
        numElements = 0;
    }
    
    // Remove the element at index `index` and shift
    // all subsequent elements to the left. 
    public int remove(int index)
    {
        // your code here
        int tempArr[] = new int[currentSize - 1];
        for(int i = 0; i < index; i++)
        {
            tempArr[i] = arr[i];
        }
        for(int i = index + 1; i < currentSize; i++)
        {
            tempArr[i - 1] = arr[i];
        }
        currentSize--;
        arr = tempArr;
        return 0;
    }
    
    // Add the int `element` at the `index` in the array.
    // You'll need to shift everything one index to the right
    // after this index.
    public void add(int index, int element)
    {
        // your code here
        int tempArr[] = new int[arr.length + 1];

        for(int i = 0; i < index; i++)
        {
            tempArr[i] = arr[i];
            System.out.println(arr[i]);
        }
        tempArr[index] = element;
        System.out.println(tempArr[index]);
        for(int i = index; i < arr.length; i++)
        {
            tempArr[i + 1] = arr[i];
            System.out.println(arr[i]);
        }
        arr = tempArr;
    }
    
    // Return the number of elements in your array.
    public int size()
    {
        return currentSize;
    }
    
    private boolean isFull()
    {
        return numElements == currentSize;
    }
    
    private void expand()
    {
        System.out.println("Expanding");
        int newSize = currentSize * 2;
        int[] newArray = new int[newSize];
        
        // Copy over old elements
        for(int i = 0; i < currentSize; i++)
        {
            newArray[i] = arr[i];
        }
        
        currentSize = newSize;
        arr = newArray;
    }
    
    public int get(int index)
    {
        return arr[index];
    }
    
    public void add(int x)
    {
        if(isFull())
        {
            expand();
        }
        arr[numElements] = x;
        numElements++;
    }
    
    public String toString()
    {
        String str = "{";
        for (int i=0; i < numElements - 1; i++) {
            str += arr[i] + ", ";
        }
        if (str.length() > 0 && str.charAt(str.length()-2)==',') {
            str = str.substring(0, str.length()-2);
            str += "}";
        }
        return str;
    }
}
Posted
Updated 23-Jan-18 18:49pm
v2
Comments
Richard MacCutchan 23-Jan-18 4:40am    
I just tried that code and it works fine. Please show your results.
Yuxi Long 23-Jan-18 20:51pm    
Hi,

Thanks for helping. My full program is attached below. Thank you!
Richard MacCutchan 24-Jan-18 3:36am    
You forgot to increase currentSize in your add method.
Mohibur Rashid 23-Jan-18 19:54pm    
I deleted my answer. Your function is right, and the problem seems to be with your the other function that is accessing your arr variable
Yuxi Long 23-Jan-18 20:51pm    
Hi,

Thanks for helping. My full program is attached below. Thank you!

your toString function is incorrect. If the arr has only one item, then the function will throw
java.lang.StringIndexOutOfBoundsException: String index out of range: -1


here is how it should go;
if there is nothing in the array then print
{}
if one element only then print
{element1}
if more than one then print
{element1, element2}
so, suggested algorithm will be
string := "{"
if element count is zero then
  string := concat(string, "}");
  return
end if

string := concat(string, arr[0]);
while ( item in array, skipping the first element ): do
  string := concat(string, ", ", item);
end while

string := concat(string, "}")

try your source code
 
Share this answer
 
v2
Why are you printing all elements but the last one?
Java
for (int i=0; i < numElements - 1; i++) {

It also look that all variables are not update"d when you add an element.

There is a tool that allow you to see what your code is doing, its name is debugger. It is also a great learning tool because it show you reality and you can see which expectation match reality.
When you don't understand what your code is doing or why it does what it does, the answer is debugger.
Use the debugger to see what your code is doing. Just set a breakpoint and see your code performing, the debugger allow you to execute lines 1 by 1 and to inspect variables as it execute.

Debugger - Wikipedia, the free encyclopedia[^]
http://docs.oracle.com/javase/7/docs/technotes/tools/windows/jdb.html[^]
https://www.jetbrains.com/idea/help/debugging-your-first-java-application.html[^]
The debugger is here to show you what your code is doing and your task is to compare with what it should do.
There is no magic in the debugger, it don't find bugs, it just help you to. When the code don't do what is expected, you are close to a bug.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900