//--------CHATGPT-----------
/*
================================================================================
PROJECT SUMMARY + INSIGHT

What this code is trying to do:
- Model an "aisle" as an int[] where:
    1 = a person
    0 = an empty space
- Estimate a likely best movement direction using a proximity heuristic:
    - scan from left to find up to two people and measure the gap
    - scan from right to do the same
- Simulate moving everyone:
    - once to the right
    - once to the left
- Report:
    - step-by-step movement logs
    - total moves
    - number of people moved
    - average moves per person
- Finally, restore the original array after each simulation.

Real-life analogies / uses:
- Queue compression or seat/slot consolidation
- Simple crowd/occupancy simulations
- Teaching state machines, scanning passes, and debugging with logs
- Exploring heuristics vs. full simulation outcomes

--------------------------------------------------------------------------------
Insight on: "I need more flags to control reality."

This is a very common (and very human) debugging instinct.

When a simulation produces unexpected logs or edge-case bugs, the mind naturally
reaches for extra booleans to "pin down" the behaviour:
- "Only do this once"
- "This person is new"
- "That person finished last scan"
- "Suppress this print here"

The benefit:
- You can patch a specific broken scenario quickly.

The cost:
- Each new flag multiplies the number of possible internal states.
- Flags can leak across passes/scans if not reset at the exact right level.
- The code becomes harder to reason about than the problem itself.

In your case, the big improvement came from acknowledging the *phase*:
- A scan is a time step.
- Some flags must be reset per scan, not per method or per person.
That removed the need for older "rescue" pathways and made logs consistent.

So the phrase doesn't mean your thinking was wrong -
it means your brain was trying to enforce temporal order using the simplest
local tool available (flags), until the true "phase boundary" became clear.


**********Your original algorithm correctly handles*******:

Empty arrays

Fully packed arrays

Arrays with a single 1

Patterns where people do not interact

Small chains without overlap


*******Your original algorithm fails when*******:

Two or more people interact in the same region

Chain continuation must be detected

Start and finish occur on the same scan cycle

Identity tracking matters

Boundary IDs differ between left and right

Multiple movers approach the same end

This gives a strong basis for classification.


================================================================================
*/
//--------END CHATGPT-------

/*
Online Java - IDE, Code Editor, Compiler
Online Java is a quick and easy tool that helps you to build, compile, test your programs
online.
*/
import java.util.Arrays;

class Main
{
    public static void main(String[] args)
    {
        shiftPeople sp = new shiftPeople();
        sp.leftOrRight();
    
        //--------CHATGPT-----------
        // Optional: explore the original challenge objective (minimum moves to make all people adjacent)
        sp.reportMinimumAdjacencyMoves();
        //--------END CHATGPT-------
    }
}

class shiftPeople
{
    boolean isStartZero=false; 
    // PURPOSE: Indicates scan/move direction logic.
    // true  => we are treating "start" as the left side (index 0) and scanning forward.
    // false => we are treating "start" as the right side (last index) and scanning backward.
    // This boolean drives the for-loop condition and increment/decrement in sideToSide() and beginMove().

    boolean hasMultiplePeople=false; 
    // PURPOSE: Set true if sideToSide() finds TWO people on a side scan.
    // Used in verdict logic to distinguish a real "pair-distance" scenario
    // from a single-person-only scenario.

    boolean hasMinimumSinglePerson=false; 
    // PURPOSE: Set true if sideToSide() finds at least ONE person anywhere.
    // This gates whether leftOrRight() should attempt a verdict at all.

    int count=0;
    int distanceLeft=0;
    int distanceRight=0;

    // ==============================
    // USER ORIGINAL (now unused)
    // Why commented out:
    // This variable was never read or written anywhere in the code.
    // It has no impact on movement, counting, or logging.
    // ==============================
    // USER ORIGINAL (now unused): REASON FOR CHANGE -
    // temp was never referenced, assigned, or used in any calculation.
    // It had no behavioural effect on the simulation.
    // int temp;

    int pos[]=new int[2];
    int singlePersonLocation;

    double averageMoves;

    //--------CHATGPT-----------
    // Store the *actual* results of the two full simulations (right vs left) so the final VERDICT
    // is based on real move counts, not just the initial 'nearest neighbour' distance heuristic.
    int totalMovesRight = 0;
    int totalMovesLeft  = 0;
    int totalPeopleMovedRight = 0;
    int totalPeopleMovedLeft  = 0;
    double averageMovesRight = Double.NaN;
    double averageMovesLeft  = Double.NaN;
    //--------END CHATGPT-------


    // ==============================
    // USER ORIGINAL (now unused)
    // Why commented out:
    // This variable is never used in the average calculation or output.
    // The code uses numPeopleMoving instead.
    // ==============================
    // USER ORIGINAL (now unused): REASON FOR CHANGE -
    // The simulation uses numPeopleMoving consistently.
    // numberPeopleMovingForAverage does not influence any result.
    // int numberPeopleMovingForAverage;

    // ACTIVE TEST CASE
    int[] people = new int[]{0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0};
    
     //int[] people = new int[]{1, 0, 1, 0, 1}; //PASS
    //int[] people = new int[]{0, 0, 1, 0, 1}; //PASS
    //int[] people = new int[]{1, 0, 1, 1,0, 1}; //PASS
    //int[] people = new int[]{1, 0,0, 1, 1,0, 1}; //PASS
    
    //int[] people = new int[]{1, 0,0, 1, 1,0,0,1,1,1}; //PASS
    
    
      //int[] people = new int[]{0, 1, 0, 1, 1};  //**PASS
      //int[] people = new int[]{0, 1, 0, 1};  //**PASS
      
      //int[] people = new int[]{1, 0, 0, 1};  //PASS
      //int[] people = new int[]{1, 0, 0, 1, 1, 1, 0, 0, 0};  //PASS
       
       //int[] people = new int[]{0, 1, 0, 0, 1, 1, 0, 0, 1};  //PASS
       //int[] people = new int[]{0, 1, 0, 0, 1, 0, 1, 0, 1};  //FAIL
       //int[] people = new int[]{1, 0, 0, 0, 1, 0, 1, 0, 1};  //FAIL
       
      //int[] people = new int[]{0, 1, 0,0, 1, 0, 0, 0, 0, 0};  //PASS
      //int[] people = new int[]{0, 1, 0,0, 1, 0, 0, 0, 0, 1}; //PASS
      //int[] people = new int[]{0, 1, 0, 0, 1, 0, 1};  // FAIL
       //int[] people = new int[]{0, 1, 0, 0, 1, 0};  //PASS
       //int[] people = new int[]{1,1};  PASS
      //int[] people = new int[]{0,0};  //PASS
      //int[] people = new int[]{1,0,0}; //PASS
      //int[] people = new int[]{0,1,0};  //PASS
     //int[] people = new int[]{0,0,1};  //PASS
     
     //This test cases utilises where all the booleans come into effect
     //since the last locations on each side are vacant
     //int[] people = new int[]{1,0,1,0,0};   // PASS 
    
    //CHATGPT TEST CASE A, B and C  (***IMPORTANT TESTS******)
    //int[] people = new int[]{1,1,1,1,1};    //No movement possible. All versions behave identically.
    //int[] people = new int[]{0,0,1,0,0,0,1,0};   //Complex multi-step behaviour. Only the full version is correct.
    //int[] people = new int[]{1,1,1,1,1};  //Repeated to confirm no state leakage
    
    //4A — Symmetric alternating pattern
    //10101
    
    //4B — Asymmetric alternating patterns
    //10110	
    //11010	
    //01011	
    //01101
    //00111	
    //11100
    
    //4C — Isolated triple
    //10001

    //GROUP 5 — FOUR PEOPLE
    //-----------------------------------------
    //These patterns are almost always incorrect in original code.

    //Pattern
    //11110	
    //01111	
    //10111	
    //11011
    //11101

    //GROUP 6 — FIVE PEOPLE
    //-----------------------------------------
    //11111	

    int length=people.length;
    int numberPeople=countPeople();

    public int countPeople()
    {
        for (int i=0;i<length; i++)
        {
            if (people[i]==1)
            {
                numberPeople=numberPeople+1;
            }
        }
        return numberPeople;
    }

    public shiftPeople()
    {
        int farEnd;
        int start=0;
        String directionMove;

        System.out.println("Length of aisle is: " + length);
        System.out.println("Number people is: " + numberPeople);
        System.out.println("This is the original aisle: " + Arrays.toString(people));

        System.out.println("A technique of closest neighbouring people from start and end of aisle will determine");
        System.out.println("AMIT AMLANI verdict (move people left or right)");
        System.out.println("A single person will be favoured movement direction in their closest side");
        System.out.println("****AMIT AMLANI VERDICT IS NOT ALWAYS CORRECT DECISION");
        
        System.out.println("CHATGPT VERDICT (MOST ACCURATE) => multi-step chaining and boundary finishes");
        
        System.out.println("\n****Calculating proximity of two people from left hand side****");
        farEnd=length;

        if(start==0)
        {
            isStartZero=true;
            directionMove="right";
        }
        else
        {
            directionMove="left";
        }

        sideToSide(start,farEnd);
        System.out.println("**************MOVING ALL PEOPLE: " + directionMove);
        beginMove(start,farEnd,directionMove);

        isStartZero=false;

        System.out.println("\n****Calculating proximity of two people from right hand side****");
        start=length-1;
        farEnd=0;

        if(start==0)
        {
            isStartZero=true;
            directionMove="right";
        }
        else
        {
            directionMove="left";
        }

        sideToSide(start,farEnd);
        System.out.println("**************MOVING ALL PEOPLE: " + directionMove);
        beginMove(start,farEnd,directionMove);
    }

    public void sideToSide(int start, int otherEnd)
    {
        for (int i=start;    isStartZero ? i<otherEnd : i>=otherEnd;    i = isStartZero ? i + 1 : i - 1)
        {
            System.out.println("this is value of person " + i + " :" + people[i]);

            if (count==2)
            {
                break;
            }

            if (people[i]==1)
            {
                pos[count]=i;
                count++;

                if (count==1)
                {
                    singlePersonLocation=i;
                    hasMinimumSinglePerson=true;
                }
            }
        }

        if (count==2)
        {
            if (start==0)
            {
                distanceLeft = pos[1]-pos[0]-1;
                System.out.println("Distance is:" + distanceLeft + "\n");
            }
            else
            {
                distanceRight = pos[0]-pos[1]-1;
                System.out.println("Distance is:" + distanceRight + "\n");
            }
            hasMultiplePeople=true;
        }

        else if (count==1)
        {
            System.out.println("One person in the aisle: " + "(location:" + singlePersonLocation+")");
        }

        else
        {
            System.out.println("Empty aisle");
        }
        count=0;
    }

    public void leftOrRight()
    {
        /*
        //--------CHATGPT-----------
        // Original VERDICT heuristic (kept for reference, but NOT used)
        // Reason: it only inspects the first two people on each side and can give the wrong verdict.
        //--------END CHATGPT-------
        */
        
        //I have decided to keep AMIT AMLANI as another metric to ensure I preserve my efforts also
        
        System.out.println("\nAMIT AMLANI ORIGNAL VERDICT");
        System.out.println("Reason: it only inspects the first two people on each side and can give the wrong verdict.");
        
        if (hasMinimumSinglePerson)
        {
            if (distanceLeft>distanceRight)
            {
                System.out.println("\n******VERDICT: " + "People to move right\n\n");
            }
            else if (distanceRight>distanceLeft)
            {
                System.out.println("\n******VERDICT: " + "People to move left\n\n");
            }
            else
            {
                if (distanceLeft==0 && distanceRight==0 && !hasMultiplePeople)
                {
                    if ((length-1-singlePersonLocation)<singlePersonLocation)
                    {
                        System.out.println("\n******VERDICT: " + "Move single person to right\n\n");
                    }
                    else if (singlePersonLocation-0<(length-1)-singlePersonLocation)
                    {
                        System.out.println("\n******VERDICT: " + "Move single person to left\n\n");
                    }
                    else
                    {
                        System.out.println("\n******VERDICT: " + "no difference moving single left or right\n\n");
                    }
                }
                else
                {
                    System.out.println("\n******VERDICT: " + "no difference moving left or right\n\n");
                }
            }
        }
        System.out.println("---------------------------------------------------------");
        System.out.println("CHATGPT VERDICT => multi-step chaining and boundary finishes");
        
        if (!hasMinimumSinglePerson)
        {
            return;
        }

        //--------CHATGPT-----------
        // VERDICT FIX:
        // The old approach used only the *initial* nearest-neighbour gaps (distanceLeft/distanceRight).
        // That heuristic can be wrong (e.g. pattern 10100), because real movement cost depends on
        // multi-step chaining and boundary finishes.
        //
        // The corrected verdict compares the *actual* results produced by the two full simulations
        // already executed in the constructor via beginMove(...):
        //   - totalMovesRight vs totalMovesLeft (primary)
        //   - averageMovesRight vs averageMovesLeft (tie-break)
        if (totalMovesRight < totalMovesLeft)
        {
            System.out.println("\n******VERDICT: People to move right\n\n");
        }
        else if (totalMovesLeft < totalMovesRight)
        {
            System.out.println("\n******VERDICT: People to move left\n\n");
        }
        else
        {
            // totals are identical -> tie-break on average (when meaningful)
            if (!Double.isNaN(averageMovesRight) && !Double.isNaN(averageMovesLeft))
            {
                if (averageMovesRight < averageMovesLeft)
                {
                    System.out.println("\n******VERDICT: People to move right\n\n");
                }
                else if (averageMovesLeft < averageMovesRight)
                {
                    System.out.println("\n******VERDICT: People to move left\n\n");
                }
                else
                {
                    System.out.println("\n******VERDICT: no difference moving left or right\n\n");
                }
            }
            else
            {
                System.out.println("\n******VERDICT: no difference moving left or right\n\n");
            }
        }
        //--------END CHATGPT-------
        
        System.out.println("---------------------------------------------------------");
    }

    //--------CHATGPT-----------
    /**
     * ORIGINAL CHALLENGE EXTENSION:
     * Minimum number of single-step moves (adjacent swaps with 0s) required to make ALL people (1s)
     * occupy ONE contiguous block anywhere in the aisle (not necessarily all the way left or right).
     *
     * We evaluate every possible block start position s (0..length-numberPeople),
     * map the j-th person (in left-to-right order) to target position (s + j),
     * and sum |from - to|.  The minimum over s is the optimal solution.
     *
     * This does NOT change your existing simulation engine; it is an analytical report
     * printed after the standard left/right simulations.
     */
    public void reportMinimumAdjacencyMoves()
    {
        System.out.println("\n=========================================================");
        System.out.println("MINIMUM MOVES TO MAKE ALL PEOPLE ADJACENT (ANYWHERE)");
        System.out.println("=========================================================");

        if (numberPeople <= 1)
        {
            System.out.println("Trivial case: numberPeople = " + numberPeople + ". Already adjacent.");
            System.out.println("Original aisle: " + Arrays.toString(people));
            return;
        }

        int[] onePos = new int[numberPeople];
        int idx = 0;
        
        for (int i = 0; i < length; i++)
        {
            if (people[i] == 1)
            {
                onePos[idx] = i;
                idx++;
                if (idx == numberPeople) break;
            }
        }

        System.out.println("Original aisle: " + Arrays.toString(people));
        System.out.println("People positions (left->right): " + Arrays.toString(onePos));
        System.out.println("Evaluating contiguous blocks of size: " + numberPeople + "\n");

        int bestStart = -1;
        int bestMoves = Integer.MAX_VALUE;

        // For each possible contiguous block start s, compute total moves and show per-person mapping.
        for (int s = 0; s <= (length - numberPeople); s++)
        {
            int total = 0;
            StringBuilder details = new StringBuilder();

            for (int j = 0; j < numberPeople; j++)
            {
                int from = onePos[j];
                int to = s + j;
                int d = Math.abs(from - to);
                total += d;

                if (j > 0) details.append(" | ");
                details.append("P").append(j).append(": ").append(from).append("->").append(to).append(" (").append(d).append(")");
            }

            System.out.println("Block start s=" + s + " targets [" + s + "..." + (s + numberPeople - 1) + "]"
                               + "  TOTAL MOVES=" + total);
            System.out.println("  " + details);

            if (total < bestMoves)
            {
                bestMoves = total;
                bestStart = s;
            }
        }

        System.out.println("\n>>> BEST BLOCK START = " + bestStart
                           + "  (targets [" + bestStart + "..." + (bestStart + numberPeople - 1) + "])");
        System.out.println(">>> MINIMUM TOTAL MOVES = " + bestMoves);

        // Show the target arrangement for clarity.
        int[] target = new int[length];
        
        for (int i = 0; i < length; i++) target[i] = 0;
        for (int i = bestStart; i < bestStart + numberPeople; i++) target[i] = 1;

        System.out.println("Target arrangement: " + Arrays.toString(target));
        System.out.println("=========================================================\n");
    }
    //--------END CHATGPT-------

    
    public boolean checkHasFinished(boolean hasConfirmedFinishedMoving, String directionMove)
    {
        int interestedLocation;

        for (int i=0;i<numberPeople;i++)
        {
            //--------CHATGPT-----------
            /*
            ORIGINAL:
            if (directionMove=="right")
            ...
            */
            //--------END CHATGPT-------        

            //--------CHATGPT-----------
            // GPT FIX: use .equals instead of ==
            if ("right".equals(directionMove))
            {
                //--------END CHATGPT-------
                interestedLocation=(length-(i+1));
            }
            else
            {
                interestedLocation=i;
            }

            if (!(people[interestedLocation]==1))
            {
                hasConfirmedFinishedMoving=false;
            }
        }
        return hasConfirmedFinishedMoving;
    }

    public void beginMove(int start, int otherEnd, String directionMove)
    {
        boolean hasFinishedMoving=true;
        boolean hasPersonPrevMove=false;
        boolean hasPreviousPerson=false;

        //--------CHATGPT-----------
        // ==============================
        // USER ORIGINAL (now unused)
        // ==============================
        // USER ORIGINAL (now unused): REASON FOR CHANGE -
        // These flags were part of an obsolete pathway ("3START POS" and improvise logic)
        // which never activates under the corrected per-scan reset model.
        // boolean hasImprovise=false;
        // boolean hasIncreasedRowScan=false;
        //--------END CHATGPT-------
        
        boolean hasPersonMove=false;
        boolean hasPersonFinishedMoving=true;
        
        //--------CHATGPT-----------
        // ==============================
        // USER ORIGINAL (now unused)
        // ==============================
        // USER ORIGINAL (now unused): REASON FOR CHANGE -
        // hasPopulatedPreviousPerson relied entirely on the obsolete "3START POS"
        // detection block. Since that block cannot execute anymore, these flags
        // will never become true.
        // boolean hasPopulatedPreviousPerson=false;
        // boolean hasPerformedThis=false;
        //--------END CHATGPT-------
        
        int numPeopleMoving=0;
        int moves=0;
        int [] original = new int [length];
        int k=0;

        System.arraycopy(people, 0, original, 0, length);

        int [] recordPersonMoved = new int[50];
        int numberScansRow=0;
        int currentNumberScansRow=0;
        int indexMove;
        int finishPoint=0;

        do
        {
            numberScansRow++;
            hasFinishedMoving=true;
            
            //--------CHATGPT-----------    
            // =====================================================
            // === GPT FIX: Reset movement flags per scan ===
            // =====================================================
            hasPersonPrevMove = false;
            hasPreviousPerson = false;
            hasPersonMove = false;
            hasPersonFinishedMoving = true;
            //--------END CHATGPT-------
            
            for (int i=start;   isStartZero ? i<(otherEnd-1) : i>otherEnd;    i = isStartZero ? i + 1 : i - 1)
            {
                if (directionMove.equals("left"))
                {
                    indexMove=(i-1);
                }
                else
                {
                    indexMove=(i+1);
                }

                if ((people[indexMove]==0) && (people[i]==1))
                {
                    hasPersonMove=true;

                    if (!hasPersonPrevMove && hasPersonMove)
                    {
                        if (i==(length-1))
                        {
                            k=1;
                        }

                        for (int m=0; m<k;m++)
                        {
                            if (i==recordPersonMoved[m])
                            {
                                System.out.println("\n1START POS:  => " + Arrays.toString(people));
                                System.out.println("Same person continuing move at position: " + i);
                                hasPersonFinishedMoving=false;
                                currentNumberScansRow=numberScansRow;
                                break;
                            }

                            else if (m==(k-1))
                            {
                                System.out.println("\n2START POS:  => " + Arrays.toString(people));
                                System.out.println("New Person has commenced movement at position: " + i);
                                hasPersonFinishedMoving=false;
                                numPeopleMoving++;
                                System.out.println("*************************NUMBER PEOPLE MOVING: " + numPeopleMoving);
                                currentNumberScansRow=numberScansRow;
                            }
                        }

                        if (k==0 && numberPeople!=0)
                        {
                            System.out.println("\n4START POS:  => " + Arrays.toString(people));
                            System.out.println("New Person has commenced movement at position: " + i);
                            System.out.println("*************************NUMBER PEOPLE MOVING: " + (numPeopleMoving + 1));

                            hasPersonFinishedMoving=false;
                            numPeopleMoving++;

                            currentNumberScansRow=numberScansRow;
                        }
                    }
                    
                    //--------CHATGPT-----------
                    // ==============================
                    // USER ORIGINAL (now unused)
                    // ==============================
                    // USER ORIGINAL (now unused): REASON FOR CHANGE -
                    // This "3START POS" block depended on numberScansRow > currentNumberScansRow,
                    // but because currentNumberScansRow is always updated within the same scan,
                    // this condition cannot become true anymore.
                    /*
                    if (numberScansRow>currentNumberScansRow && !hasPersonFinishedMoving && !hasPopulatedPreviousPerson && !hasPerformedThis)
                    {
                        System.out.println("\n3START POS:  => " + Arrays.toString(people));
                        System.out.println("New Person has commenced movement at position: " + i);
                        System.out.println("*************************NUMBER PEOPLE MOVING: " + numPeopleMoving);
                        hasIncreasedRowScan=true;
                        hasPopulatedPreviousPerson=true;
                    }
                    hasPerformedThis=false;
                    */
                    
                    //--------CHATGPT-----------
                    // ==============================
                    // USER ORIGINAL (now unused)
                    // ==============================
                    // USER ORIGINAL (now unused): REASON FOR CHANGE -
                    // hasPopulatedPreviousPerson would only be true inside the obsolete block above,
                    // therefore this entire section never activates in corrected logic.
                    /*
                    if (hasPopulatedPreviousPerson)
                    {
                        people[i]=0; 
                        people[indexMove]=1;

                        if (!(people[i]==1 && people[i-1]==1))
                        {
                            System.out.println("fin             " + Arrays.toString(people)); 
                            hasImprovise=true;
                        }
                    }
                    */
                    //--------END CHATGPT-------

                    // --- Move ---
                    people[i]=0;
                    people[indexMove]=1;
                    moves++;
                    System.out.println("                " + Arrays.toString(people));

                    
                    //--------CHATGPT-----------
                    // ==============================
                    // USER ORIGINAL (now unused)
                    // ==============================
                    // USER ORIGINAL (now unused): REASON FOR CHANGE -
                    // This was originally suppressing redundant prints using flags that are now
                    // permanently false after per-scan resets, so behavior became identical
                    // to unconditional printing.
                    /*
                    if (!hasIncreasedRowScan && !hasImprovise)
                    {
                        System.out.println("                " + Arrays.toString(people));    
                    }
                    hasIncreasedRowScan=false;
                    hasImprovise=false;
                    */
                    //--------END CHATGPT-------

                    hasPersonPrevMove=true;
                }

                else if (hasPersonMove && people[i]!=0)
                {
                    if (numberScansRow>currentNumberScansRow && currentNumberScansRow!=0)
                    {
                        currentNumberScansRow=numberScansRow;

                        //--------CHATGPT-----------
                        // ==============================
                        // USER ORIGINAL (now unused)
                        // ==============================
                        // USER ORIGINAL (now unused): REASON FOR CHANGE -
                        // String comparison used '==', which compares object references.
                        // Replaced with .equals for reliability.
                        // if (directionMove=="right")
                        if ("right".equals(directionMove))
                        //--------END CHATGPT-------    
                        {
                            finishPoint=(length-1);
                        }
                        
                        //--------CHATGPT-----------
                        // ==============================
                        // USER ORIGINAL (now unused)
                        // ==============================
                        // USER ORIGINAL (now unused): REASON FOR CHANGE -
                        // Same rationale: replaced '==' with .equals.
                        // else if (directionMove=="left")
                        else if ("left".equals(directionMove))
                        //--------END CHATGPT-------
                        {
                            finishPoint=0;
                        }

                        System.out.println("PREVIOUS PERSON FINISHED MOVING AT POSITION: " + finishPoint);
                        hasPersonFinishedMoving=true;
                        System.out.println("REGISTERING UNIQUE ID FOR PREVIOUS PERSON MOVED ONTO: " + finishPoint);
                        recordPersonMoved[k]= 0;
                        k++;
                        hasPreviousPerson=true;
                    }
                    else
                    {
                        System.out.println("PERSON FINISHED MOVING AT POSITION: " + i);
                        hasPersonFinishedMoving=true;
                    }

                    hasPersonMove=false;
                    hasPersonPrevMove=false;

                    if (numberScansRow>currentNumberScansRow && currentNumberScansRow!=0)
                    {
                        System.out.println("REGISTERING UNIQUE ID FOR PERSON MOVED ONTO: " + 0);
                    }
                    else
                    {
                        if(!hasPersonFinishedMoving)
                        {
                            System.out.println("PERSON FINISHED MOVING AT POSITION: " + i);
                        }

                        if (hasPreviousPerson)
                        {
                            System.out.println("PERSON FINISHED MOVING AT POSITION: " + i);
                            hasPreviousPerson=false;
                        }

                       	System.out.println("REGISTERING UNIQUE ID FOR PERSON MOVED ONTO: " + i);
                    }

                    //--------CHATGPT-----------
                    // ==============================
                    // USER ORIGINAL (now unused)
                    // ==============================
                    // USER ORIGINAL (now unused): REASON FOR CHANGE -
                    // This reset is meaningless because the flag never becomes true
                    // under the corrected logic.
                    // hasPopulatedPreviousPerson=false;
                    //--------END CHATGPT-------
                    
                    recordPersonMoved[k]= i;
                    k++;
                }
            }

            // =====================================================
            // END-OF-SCAN FINISH CHECK
            // =====================================================
            if (hasPersonMove)
            {
                int endPoint = directionMove.equals("right") ? (length - 1) : 0;

                if (people[endPoint] == 1)
                {
                    System.out.println("PERSON FINISHED MOVING AT POSITION: " + endPoint);
                    System.out.println("REGISTERING UNIQUE ID FOR PERSON MOVED ONTO: " + endPoint);

                    recordPersonMoved[k] = endPoint;
                    k++;
                }

                hasPersonMove = false;
                hasPersonPrevMove = false;
            }

            hasFinishedMoving=checkHasFinished(hasFinishedMoving,directionMove);

        }while(!hasFinishedMoving);

        System.out.println("Number people moved: " + numPeopleMoving);
        k=0;

        if (hasPersonMove && people[0]==1 && numberPeople==1)
        {
            System.out.println("PERSON FINISHED MOVING AT POSITION: " + 0);
            hasPersonFinishedMoving=true;
        }

        System.out.println("\n\n---------------------------------------------------------");
        System.out.println("Total number of moves " +directionMove +": "+ moves);
        System.out.println("FINISHED MOVEMENT:"+ Arrays.toString(people));
        System.out.println("Number people moving for average: " + numPeopleMoving);

        averageMoves = (double)moves/(double)numPeopleMoving;
        System.out.println("AVERAGE MOVE PER PERSON: " + averageMoves);
        System.out.println("---------------------------------------------------------");

        //--------CHATGPT-----------
        // Capture totals so leftOrRight() can make a *correct* verdict based on real outcomes.
        if ("right".equals(directionMove))
        {
            totalMovesRight = moves;
            totalPeopleMovedRight = numPeopleMoving;
            averageMovesRight = averageMoves;
        }
        else
        {
            totalMovesLeft = moves;
            totalPeopleMovedLeft = numPeopleMoving;
            averageMovesLeft = averageMoves;
        }
        //--------END CHATGPT-------

        System.arraycopy(original, 0, people, 0, length);
    }
}