0

so I'm given a 2d array of n by m size and a consecutive number of free seats that I have to find in it and output the first line I find it on. Elements in the 2d array consist of 1s and 0s, 1 is for occupied, 0 for free. I managed to solve it 95% id say... my problem is that my code keeps outputing the last row that it finds the free consecutive seats in and not the first one...

This is my code:

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        int n = scanner.nextInt(); // nr. of rows
        int m = scanner.nextInt(); // nr. of seats / row
        int[][] cinema = new int [n][m];

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                cinema[i][j] = scanner.nextInt();
            }
        }
        int k = scanner.nextInt(); // nr. of consecutive available seats
        Boolean consec = false;
        int fff = 0; // final free consecutive seats found

        for (int i = 0; i < n; i++) {

            int cfs = 0; // current free seat / row

            for (int j = 0; j < m; j++) {
                if (cinema[i][j] == 0) {
                    cfs++;

                } else if (cinema[i][j] == 1) {
                    cfs = 0;
                }
                if (cfs == k) {
                    consec = true;
                    fff = i + 1;
                } else if (fff == 0) {
                    consec = false;
                }
            }
        }
        if (consec) {
            System.out.println(fff);
        } else System.out.println(0);
    }
}

What am I doing wrong?

Turing85
  • 18,217
  • 7
  • 33
  • 58
  • 1
    Please read: [How to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) – Turing85 Aug 14 '20 at 17:00
  • It's good to make an example where the inputs are known. Also, nothing in your loops would stop the execution once a consecutive free seat is found. So it will continue until the last one. Maybe break or some such? – matt Aug 14 '20 at 17:03
  • Basically, in the outer loop check for `if(consec) { break; }` to break out (you can also put your print in here). Code formatting of SO is annoying me so I'm deleting my (anyway wrong) post. – Beko Aug 14 '20 at 17:09

0 Answers0