// Lösningar till tentamen, del B 2018-06-08 // Uppgift 1 import java.util.*; public abstract class Gate { protected String name; public Gate(String name) { this.name = name; } public abstract boolean getOutput(); public String getName() { return name; } } class ConstantGate extends Gate { private boolean value; public ConstantGate(String name) { super(name); } public void set(boolean v) { value = v; } public boolean getOutput() { return value; } } abstract class BasicGate extends Gate { protected List input = new ArrayList(); protected BasicGate(String name) { super(name); } protected void checkInput() { if (input.size() < 2) throw new IllegalStateException("Gate " + name + ": Input signal(s) missing"); } protected abstract boolean calculateValue(); public void setInput(Gate g) { input.add(g); } public boolean getOutput() { checkInput(); return calculateValue(); } } class AndGate extends BasicGate { public AndGate(String name) { super(name); } protected boolean calculateValue() { for (Gate g : input) if (!g.getOutput()) return false; return true; } } class OrGate extends BasicGate { public OrGate(String name) { super(name); } protected boolean calculateValue() { for (Gate g : input) if (g.getOutput()) return true; return false; } } class NotGate extends BasicGate { protected NotGate(String name) { super(name); } @Override protected void checkInput() { if (input.size() != 1) throw new IllegalStateException("Gate " + name + ": Illegal number of input signals"); } protected boolean calculateValue() { return !input.get(0).getOutput(); } } // Uppgift 2 public class Lines extends JPanel { private int n; public Lines(int n) { this.n = n; } public void paintComponent(Graphics g) { super.paintComponent(g); Insets i = getInsets(); int w = getWidth() - i.left-i.right; int h = getHeight() - i.top - i.bottom; int dx = w/(n+1); int dy = h/(n+1); for (int j = 1; j <= n; j++) g.drawLine(i.left+j*dx, i.top+h, i.left+w, i.top+h-j*dy); } } // Uppgift 3 import java.util.*; public class Airport { private String name; private NavigableSet departures = new TreeSet(); private Map> flightsTo = new HashMap>(); public Airport(String n) { name = n; } public String getName() { return name; } public NavigableSet getDepartures() { return departures; } public NavigableSet getDepartures(String to) { return flightsTo.get(to); } public void addFlight(Flight f) { departures.add(f); if (!flightsTo.containsKey(f.getDestination())) flightsTo.put(f.getDestination(), new TreeSet()); flightsTo.get(f.getDestination()).add(f); } public void removeFlight(Flight f) { departures.remove(f); NavigableSet e = flightsTo.get(f.getDestination()); if (e != null) { e.remove(f); if (e.isEmpty()) flightsTo.remove(f.getDestination()); } } }