Menu
CoddyTech

Final: Portar inventario

Lección 47 de 48 del curso Ruby para desarrolladores de Java de Coddy.

challenge icon

Desafío

Fácil

Adapta el programa de referencia. El stock empieza en cero; change(delta) acepta un cambio solo si el stock resultante no es negativo y devuelve true o false. quantity lee el stock. Inventory.change(code,delta) aplica cambios para cada código y crea un código solo si la operación tiene éxito. report devuelve las cantidades positivas en orden alfabético de código, como pares code:quantity, o none. La entrada consta de pares code delta, uno por línea. La salida muestra un valor booleano por cada cambio y, después, el informe. Proporciona Stock e Inventory en sus propios archivos.

Devuelve el texto desde solve(input) sin imprimirlo. El controlador bloqueado imprime el texto devuelto con un salto de línea final y comprueba por separado las API públicas requeridas.

Escribe tu código en exercise.rb, stock.rb, inventory.rb. main.rb contiene el código de entrada/salida proporcionado y no se puede editar.

Límites de entrada: como máximo 1000 líneas de datos. Los códigos del inventario contienen solo letras ASCII minúsculas, y cada delta del inventario está entre -1000000 y 1000000. Para la adaptación del sensor, el límite de la primera línea está entre -1000000 y 1000000; la validez de los tokens sigue el contrato del analizador indicado anteriormente.

Programa de referencia en Java. Reproduce su comportamiento usando las API requeridas de Ruby.

import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class Main {
  static class Stock {
    BigInteger quantity = BigInteger.ZERO;
    boolean change(BigInteger delta) {
      BigInteger next = quantity.add(delta);
      if (next.signum() < 0) return false;
      quantity = next;
      return true;
    }
  }
  static class Inventory {
    final Map<String,Stock> items = new TreeMap<>();
    boolean change(String code, BigInteger delta) {
      Stock stock = items.getOrDefault(code, new Stock());
      if (!stock.change(delta)) return false;
      items.put(code, stock);
      return true;
    }
    String report() {
      List<String> parts = new ArrayList<>();
      for (Map.Entry<String,Stock> entry : items.entrySet()) {
        if (entry.getValue().quantity.signum() > 0) parts.add(entry.getKey() + ":" + entry.getValue().quantity);
      }
      return parts.isEmpty() ? "none" : String.join(" ", parts);
    }
  }
  public static void main(String[] args) throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    Inventory inventory = new Inventory();
    String line;
    while ((line = reader.readLine()) != null) {
      if (line.trim().isEmpty()) continue;
      String[] parts = line.trim().split("\\s+");
      System.out.println(inventory.change(parts[0], new BigInteger(parts[1])));
    }
    System.out.println(inventory.report());
  }
}

Pruébalo tú mismo

require_relative 'exercise'
require_relative 'stock'
require_relative 'inventory'
def check(value)
  raise 'Public API check failed' unless value
end
s = Stock.new
check(!s.change(-1) && s.quantity == 0 && s.change(4) && !s.change(-5) && s.quantity == 4)
i = Inventory.new
check(!i.change("x", -2) && i.report == "none")
check(i.change("b", 2) && i.change("a", 1) && i.report == "a:1 b:2")

puts solve(STDIN.read)

Todas las lecciones de Ruby para desarrolladores de Java

Practica por tu cuenta: Compilador de Ruby online