furuf
furuf

Reputation: 39

Stuck using arrays in java

I am still new to very new to coding. I am trying to take an array filled with "x" amount of elements, and need to find a range of numbers. The parameters take an array, a minimum number, and a maximum number. The end result needs to include the minimum, maximum, and the numbers in between them. Here is kind of an example of what I am talking about:

The starting array:[2, 8, 7, 3, 4]   
Min value: 1
Max value: 5
End result: [2, 3, 4] 

I hope this isn't confusing, and that I kind of explained it well enough to understand.

The code I have is this:

public static int[] range(int[] a, int low, int high) 
{
  int[] rangeArray = new int[0];

  for (int i = low; i <= high; i++)
  {  
     if (low >= a.length && high <= a.length)
     {
        rangeArray[i] = a[i];
     }
  }

  return rangeArray;
}

Upvotes: 0

Views: 308

Answers (6)

Nathaniel Ford
Nathaniel Ford

Reputation: 21220

Your first problem is here:

int[] rangeArray = new int[0];

What this does is instantiate and array of ints named rangeArray. It then initializes it to be of length 0. Therefore, anything added to this array would be out-of-bounds. You should initialize it to the length of the return result; difficult in this case.

Then we have this block of code:

for (int i = low; i <= high; i++) //start at the lowest possible number and go to the highest
{  
   //check for validity
}

There is a bit of conception issue here; you're iterating from low to high. What if low is very low (-1 million?) and high is similarly very high? That's a lot of thinking for no result.

Instead, lets loop through the array you're actually given:

for (int idx = 0; idx < a.length; idx++) {
  //Check the value of int, if it is in the desired range, save it.
}

Finally, lets consider this:

if (low >= a.length && high <= a.length)

This roughly translates to "if the low end of my desired range is greater than the length of the list of numbers I am checking, and the high end of my range is smaller than that same length, take the 'true' branch." This is not what you're looking for.

Instead you want "if the current index value is between my low and high, keep it."

if (a[idx] >= low && a[idx] <= high)

Rolling it up we get:

public static int[] range(int[] a, int low, int high) 
{
  int[] rangeArray = new int[a.length];//this is the most we will need
  int numbersFound = 0;//to keep track of result array index    

  for (int idx = 0; idx < a.length; idx++) {
  {  
     if (a[idx] >= low && a[idx] <= high)
     {
        rangeArray[numbersFound++] = a[i];
     }
  }

  return rangeArray;
}

Note that in this case your array will likely have some empty cells at the end. Be careful of this before using it!

Upvotes: 5

Elayeek
Elayeek

Reputation: 72

For ease and readability I would not rush to generate an array and cut it later because this seems quite wasteful (what if I have an array of many ints but only few of them match?)

I would go with something like:

List<Integer> temp = new List<>();
    for(int i = 0 ; i < a.length ; i++){
        if (low <= a[i]  && high >= a[i] ){
           temp.add(a[i]);
        }
}
return ArrayUtils.toPrimitive(temp.toArray(new Integer[temp.size()]));

This is, in large part, because I am bad with indices and so I try to use the STL instead of arrays when possible

Upvotes: 2

Michael Yaworski
Michael Yaworski

Reputation: 13483

public static int[] range(int[] a, int low, int high) {

    Arrays.sort(a); // sort the aray first

    int length = 0; // number of numbers within the range

    for (int i = 0; i < a.length; i++) { // check all ints in the array

        // if the int is in the range, add 1 to the length
        if (low <= a[i] && high >= a[i]) {
            length++;
        }
    }

    // determine array size with number of numbers found within the range
    int[] rangeArray = new int[length];

    for (int i = 0; i < a.length; i++) // for every int in the array
    {  
        if (low <= a[i] && high >= a[i]) // if number is between the range
        {
            rangeArray[i] = a[i]; // add it to the range array
        }
    }
    return rangeArray;
}

public static void main(String args[]) {
    int[] array = {2, 8, 7, 3, 4};
    int[] rangeArray = range(array, 1, 5);

    System.out.print( Arrays.toString(rangeArray) );
}

Output:

[2, 3, 4]

Upvotes: 1

ccozad
ccozad

Reputation: 1129

Your logic is incorrect.

  1. The size of the array is assigned to zero. How will you store something in that container if there is no space?
  2. You loop counter is off.
    • The easiest way to iterate over an array is to start at the beginning and move to the end
    • Array indexes start at zero
    • Array indexes go up to (length - 1)
  3. You need to use high and low in your test.

psuedo code

initialize result to the same size as the input
foreach(item in array) 
{
   if(item is in range) {
      add item to result
    }
}

Closer to code

results = new Int[a.length()];
int resultsPosition = 0;
for(int i = 0; i < a.length(); i++) {
     if(a[i] => low  && a[i] <= high) {
           results[reultsPosition] = a[i];
           resultsPosition++;
     }
} 

Upvotes: 2

JNYRanger
JNYRanger

Reputation: 7097

You have two main issues here. The first is that you are initializing your array to have 0 elements in it, meaning you can never do anything with it. The line that says int[] rangeArray = new int[0] should be:

int[] rangeArray = new int[a.length];

This says that you want your new array to be as big as the array you are using as your input values. Since we're essentially filtering the parameter array it shouldn't be bigger than it so we won't have out of range errors.

Now the next part if your for loop. You are using your indexes to filter the element's values. This is not what you want to do. Instead you want to iterate over the entire contents of the array. You can use a foreach loop like this and then check if the value at the current index is within your min & max values.

int counter = 0;  //keep track of our spot in our new array
for(int i : a) //iterate over all the elements of a using int i as our iterator
{
   if(i >= min && i<= max) //check if it is within our allowed range
   {
       rangeArray[counter] = i; //add it to the new array
       counter++;               //increment counter to add to next spot in our new array
   }
}

Upvotes: 1

MrMike
MrMike

Reputation: 1540

The line of code int[] rangeArray = new int[0] is instantiating an array with length of 0. You can't do anything with this array!

Since we know the starting array ([2,8,7,3,4]), we know the size. So let's change the array length to 5, since we are adding all of the numbers to this array, all of the items will meet the boundary conditions), making the line of code now int[] rangeArray = new int[5].

Next, let's look at your loops. I'm assuming the path you want to take is to look at each value and see if it is >= the minimum, and also <= the maximum. So, we should set up a second array. Let's call it boundaryArray. Let's also make that length 5, as all of the elements could, in fact, meet the conditions. So we have this line: int[] boundaryArray = new int[5]. So, let's loop through the elements and see if any of the values match. Let's look at this code:

int minimum = 1;
int maximum = 5;
int counter = 0; 
for (int i = 0; i < rangeArray.length; i++)
{
  if (rangeArray[i] >= minimum && rangeArray[i] <= maximum
  {
    boundaryArray[counter] = rangeArray[i];
    counter++;
  }
}

We first initialize two ints, our minimum and maximum (1 and 5 respectively). Next, we have a counter, to keep track of how many items have been added. Then, we use the for loop to go through our original array, and we increment by 1 each time we go through the loop. Then, if the number we're looking at is >= the min and <= the max, we add the number to the boundaryArray and increment the counter.

If you want to print out the list, simply run another for loop from 0 to boundaryArray.length and print out the array, using System.out.println(boundayArray[i].toString()), where i is the for-loop iteration variable.

Upvotes: 1

Related Questions