(URI) Jogando Cartas Fora - Solução 1

Esta solução não é a mais eficiente.

import java.io.*;
import java.util.*;

class Main  {
    public static void main(String[] args) throws NumberFormatException, IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
       
        int qteCartas = leitor(br);
       
        while (qteCartas != 0) {
            ArrayList<Integer> pilha = new ArrayList<Integer>();

            insere(qteCartas, pilha);

            bw.write("Discarded cards: ");
           
            int topo = 0;
            while (qteCartas > 1) {
                if (topo > 0) {
                    bw.write(", ");
                }
                bw.write(String.valueOf(pilha.get(topo)));
                topo++; // simula uma remoção da pilha
                qteCartas--; // por remover uma carta
                realoca(topo, pilha); // coloca a carta no topo na base
                topo++; // considera a proxima carta
            }
           
            bw.newLine();
            bw.write("Remaining card: " + String.valueOf(pilha.get(topo)));
            bw.newLine();
           
            qteCartas = leitor(br);
        }

        bw.flush();       
        bw.close();
    }

    static void insere(int qte, ArrayList<Integer> pilha) {
        for (int i = 0; i < qte; i++) {
            pilha.add(i+1);
        }
    }
   
    static void realoca(int topo, ArrayList<Integer> pilha) {
        int carta = pilha.get(topo);      
        pilha.add(carta);
    }
       
    static int leitor(BufferedReader br) throws NumberFormatException, IOException {
       int n;
       int resp = 0;
       int sinal = 1;
       while (true) {
           n = br.read();
           if (n >= '0' && n <= '9') break;
           if (n == '-') sinal = -1;
           if (n == '+') sinal = 1;
       }
       while (true) {
           resp = resp*10 + n-'0';
           n = br.read();
           if (n < '0' || n > '9') break;
       }

       return resp*sinal;
    }
}

Comments

Popular posts from this blog

(Coderbyte) Dash Insert II - Solução

(Coderbyte) Run Length - Solução

(Coderbyte) Counting Minutes I - Solução