简体   繁体   中英

How do I loop through each array item and divide by two?

An array inhabitants represents cities and their respective populations. For example, the following arrays shows 8 cities and their respective populations:

[3, 6, 0, 4, 3, 2, 7, 1]

Some cities have a population of 0 due to a pandemic zombie disease that is wiping away the human lives. After each day, every city will lose half of its population. write a program to loop though each city population and make it lose half of its population until all cities have no humans left. Make updates to each element in the array And print the array like below for each day:

Day 0 [3, 6, 0, 4, 3, 2, 7, 1]
Day 1 [1, 3, 0, 2, 1, 1, 3, 0]
Day 2 [0, 1, 0, 1, 0, 0, 1, 0]
Day 3 [0, 0, 0, 0, 0, 0, 0, 0]
---- EXTINCT ----

The problem is when I input [3, 6, 0, 4, 3, 2, 7, 1], it gives me two extra array lines with zeros;

Day 0 [3, 6, 0, 4, 3, 2, 7, 1]
Day 1 [1, 3, 0, 2, 1, 1, 3, 0]
Day 2 [0, 1, 0, 1, 0, 0, 1, 0]
Day 3 [0, 0, 0, 0, 0, 0, 0, 0]
Day 4 [0, 0, 0, 0, 0, 0, 0, 0]
Day 5 [0, 0, 0, 0, 0, 0, 0, 0]
---- EXTINCT ----

When i tried inhabitants.length-2 in my for loop, it works but then it creates another issue when the input is different such as;

20
20
0
20
20
10
0
10

Here is my code;

import java.util.*;

class Main {
  public static void main(String[] args) {

    Scanner input = new Scanner(System.in);
    int[] inhabitants = new int[8];

    for(int i=0; i<inhabitants.length; i++) {
        inhabitants[i] = input.nextInt();
    }

    int day = 0;
    System.out.println("Day " + day + " "+ Arrays.toString(inhabitants));
    for (int i = inhabitants.length/2; i <= inhabitants.length-2; i++) {
        for (int j =0; j < inhabitants.length; j++) {
            inhabitants[j] /= 2;
        }
        day++;
        System.out.println("Day " + day + " "+ Arrays.toString(inhabitants));
    }

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

Your outer loop condition should be on inhabitants not being entirely filled with zero. Something like,

int day = 0;
System.out.println("Day " + day + " " + Arrays.toString(inhabitants));
while (!Arrays.stream(inhabitants).allMatch(x -> x == 0)) {
    day++;
    for (int i = 0; i < inhabitants.length; i++) {
        inhabitants[i] /= 2;
    }
    System.out.println("Day " + day + " " + Arrays.toString(inhabitants));
}
System.out.println("---- EXTINCT ----");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM