Caleb Sylvester
Caleb Sylvester

Reputation: 11

How to divide blocks of arrays in a loop?

I am trying to figure out how to take an array stalls[] and find the middle index of a continuously decreasing size.

In essence, I am taking the middle index of an array, assigning it to the boolean true, then taking the new, smaller size of an index and finding the halfway point of that (ignoring everything to the right).

In print form, it might look like

_ _ _ _ _ X _ _ _ _

_ _ X _ _ X _ _ _ _

I can't figure out how to get this to loop correctly. Any help would be appreciated!

Upvotes: 1

Views: 166

Answers (2)

jco.owens
jco.owens

Reputation: 535

A little bit vague as to what you are wanting. But this might get you closer.

public class homework
{
  public static void main(String args[])
  {
    new homework();
  }

  public homework()
  {
    boolean[] stalls = new boolean[50];

    int middle = stalls.length/2;

    for (int i = 0; i < stalls.length; i++)
    {
      stalls[middle] = true;
      middle /= 2; 
    }

    for (int i = 0; i < stalls.length; i++)
    {
      if (stalls[i] == true)
      {
        System.out.print("X");
      }
      else
      {
        System.out.print("_");
      }

      System.out.print(" ");
    }

    System.out.println("");
  }
}

Upvotes: 0

dreamcrash
dreamcrash

Reputation: 51543

Do:

  int begin = 0;
  int end = array_size
  int middle = (end + begin) / 2;


  while( ... )
  {
  // do something
     middle = middle / 2; // break in half
  }

...

The code above iterate over the first half, to iterate over the second half you just have to modify the begin variable, to:

int being = array_size / 2;

corresponding to the middle of the array.

Upvotes: 1

Related Questions