Dataset Viewer
Auto-converted to Parquet
year
stringdate
2014-01-01 00:00:00
2024-01-01 00:00:00
session
stringlengths
3
4
utility_classes
listlengths
1
5
solution
listlengths
1
6
test
dict
2014
a02
[ { "content": "package ex2014.a02.sol1;\n\nimport java.util.Set;\n\n\n\npublic interface Scheduler<T> {\n\t\n\t\n\tvoid add(T t);\n\t\n\t\n\tboolean isExecuting();\n\t\n\t\n\tT getExecutingTask();\n\t\n\t\n\tvoid executeNext();\n\t\n\t\n\tvoid complete();\n\t\n\t\n\tvoid stop();\n\t\n\t\n\tvoid preempt();\n\t\n\t\n\tvoid unStop(T t);\n\t\n\t\n\tSet<T> allStopped();\n\t\n\t\n\tSet<T> allWaiting();\n\n}", "filename": "Scheduler.java" } ]
[ { "content": "package ex2014.a02.sol1;\n\nimport java.util.*;\nimport java.util.function.Supplier;\n\npublic class SchedulerImpl<T> implements Scheduler<T>{\n\t\n\tprivate final LinkedList<T> waitingList = new LinkedList<>();\n\tprivate final LinkedList<T> stoppedList = new LinkedList<>();\n\tprivate Optional<T> executingTask = Optional.empty();\n\t\n\t@Override\n\tpublic void add(T t) {\n\t\tif (this.waitingList.contains(t) || this.stoppedList.contains(t) || this.executingTask.equals(Optional.of(t))){\n\t\t\tthrow new IllegalArgumentException();\n\t\t}\n\t\tthis.waitingList.addLast(t);\n\t}\n\n\t@Override\n\tpublic boolean isExecuting() {\n\t\treturn this.executingTask.isPresent();\n\t}\n\n\t@Override\n\tpublic T getExecutingTask() {\n\t\treturn this.executingTask.get();\n\t}\n\n\t@Override\n\tpublic void executeNext() {\n\t\tif (this.isExecuting()){\n\t\t\tthrow new IllegalStateException();\n\t\t}\n\t\tif (this.waitingList.size()==0){\n\t\t\tthrow new NoSuchElementException();\n\t\t}\n\t\tthis.executingTask = Optional.of(this.waitingList.poll());\n\t}\n\n\t@Override\n\tpublic void complete() {\n\t\tif (!this.isExecuting()){\n\t\t\tthrow new IllegalStateException();\n\t\t}\n\t\tthis.executingTask = Optional.empty();\n\t}\n\n\t@Override\n\tpublic void stop() {\n\t\tif (!this.isExecuting()){\n\t\t\tthrow new IllegalStateException();\n\t\t}\n\t\tthis.stoppedList.addLast(this.executingTask.get());\n\t\tthis.executingTask = Optional.empty();\t\t\n\t}\n\t\n\t@Override\n\tpublic void preempt() {\n\t\tif (!this.isExecuting()){\n\t\t\tthrow new IllegalStateException();\n\t\t}\n\t\tthis.waitingList.addLast(this.executingTask.get());\n\t\tthis.executingTask = Optional.empty();\t\t\n\t}\n\t\n\t@Override\n\tpublic void unStop(T t) {\n\t\tif (!this.stoppedList.contains(t)){\n\t\t\tthrow new NoSuchElementException();\n\t\t}\n\t\tif (this.stoppedList.removeFirstOccurrence(t)){\n\t\t\tthis.waitingList.addLast(t);\n\t\t}\n\t}\n\n\t@Override\n\tpublic Set<T> allStopped() {\n\t\treturn new HashSet<>(this.stoppedList);\n\t}\n\n\t@Override\n\tpublic Set<T> allWaiting() {\n\t\treturn new HashSet<>(this.waitingList);\n\t}\n\n\n}", "filename": "SchedulerImpl.java" } ]
{ "components": { "imports": "package ex2014.a02.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;", "private_init": "\t/*\n\t * Implement the Scheduler interface given through a SchedulerImpl class\n\t * with a constructor without arguments.\n\t * This scheduler executes processes one at a time, has a queue of processes waiting,\n\t * and a queue of processes\n\t * stopped (i.e. that cannot restart until they are awakened).\n\t * The comment to the Scheduler code, and the test methods below\n\t * constitute the necessary explanation of the\n\t * problem.\n\t * Remove the comment from the tests..\n\t */\n\n\t// This test verifies that the execution of processes is circular", "test_functions": [ "\[email protected]\n\tpublic void testExec() {\n\t\tScheduler<String> sch = new SchedulerImpl<>();\n\t\tsch.add(\"a\");\n\t\tsch.add(\"b\");\n\t\tsch.add(\"c\");\n\t\tsch.add(\"d\");\n\t\tassertFalse(sch.isExecuting()); // no task running at the moment\n\t\tassertEquals(sch.allWaiting(), new HashSet<>(Arrays.asList(\"a\", \"b\", \"c\", \"d\"))); // tasks waiting: a,b,c,d\n\t\tassertEquals(sch.allStopped(), new HashSet<>(Arrays.asList())); // stopped tasks, none\n\n\t\t// execute the first one, i.e. \"a\"\n\t\tsch.executeNext();\n\t\tassertTrue(sch.isExecuting());\n\t\tassertEquals(sch.getExecutingTask(), \"a\");\n\t\tassertEquals(sch.allWaiting(), new HashSet<>(Arrays.asList(\"b\", \"c\", \"d\"))); // tasks waiting\n\t\tassertEquals(sch.allStopped(), new HashSet<>(Arrays.asList())); // stopped tasks\n\n\t\t// release the execution of \"a\", which returns to waiting\n\t\tsch.preempt();\n\t\tassertFalse(sch.isExecuting()); // no task running\n\t\tassertEquals(sch.allWaiting(), new HashSet<>(Arrays.asList(\"a\", \"b\", \"c\", \"d\"))); // tasks waiting\n\t\tassertEquals(sch.allStopped(), new HashSet<>(Arrays.asList())); // stopped tasks\n\n\t\t// execute and release b,c,d in sequence, then we return to execute a, and so on\n\t\tsch.executeNext();\n\t\tassertEquals(sch.getExecutingTask(), \"b\");\n\t\tsch.preempt();\n\t\tsch.executeNext();\n\t\tassertEquals(sch.getExecutingTask(), \"c\");\n\t\tsch.preempt();\n\t\tsch.executeNext();\n\t\tassertEquals(sch.getExecutingTask(), \"d\");\n\t\tsch.preempt();\n\t\tsch.executeNext();\n\t\tassertEquals(sch.getExecutingTask(), \"a\");\n\t\tassertTrue(sch.isExecuting()); // task running\n\t\tassertEquals(sch.allWaiting(), new HashSet<>(Arrays.asList(\"b\", \"c\", \"d\"))); // tasks waiting\n\t}", "\[email protected]\n\tpublic void testStopping() {\n\t\tScheduler<String> sch = new SchedulerImpl<>();\n\t\tsch.add(\"a\");\n\t\tsch.add(\"b\");\n\t\tsch.add(\"c\");\n\t\tsch.add(\"d\");\n\n\t\t// execute the first one, i.e. a\n\t\tsch.executeNext();\n\t\tassertEquals(sch.getExecutingTask(), \"a\");\n\t\tassertTrue(sch.isExecuting()); // no task running\n\t\tassertEquals(sch.allWaiting(), new HashSet<>(Arrays.asList(\"b\", \"c\", \"d\"))); // tasks waiting\n\t\tassertEquals(sch.allStopped(), new HashSet<>(Arrays.asList())); // stopped tasks\n\n\t\t// stop the task being executed, which ends up in the stopped queue\n\t\tsch.stop();\n\t\tassertFalse(sch.isExecuting()); // no task running\n\t\tassertEquals(sch.allWaiting(), new HashSet<>(Arrays.asList(\"b\", \"c\", \"d\"))); // tasks waiting\n\t\tassertEquals(sch.allStopped(), new HashSet<>(Arrays.asList(\"a\"))); // stopped tasks\n\n\t\t// execute the next one, which is b\n\t\tsch.executeNext();\n\t\tassertEquals(sch.getExecutingTask(), \"b\");\n\n\t\t// stop the task being executed, it ends up in the stopped queue\n\t\tsch.stop();\n\t\tassertFalse(sch.isExecuting()); // no task running\n\t\tassertEquals(sch.allWaiting(), new HashSet<>(Arrays.asList(\"c\", \"d\"))); // tasks waiting\n\t\tassertEquals(sch.allStopped(), new HashSet<>(Arrays.asList(\"a\", \"b\"))); // stopped tasks\n\n\t\t// now \"a\" can continue, it passes into the waiting queue, but at the end!\n\t\tsch.unStop(\"a\");\n\t\tassertFalse(sch.isExecuting()); // no task running\n\t\tassertEquals(sch.allWaiting(), new HashSet<>(Arrays.asList(\"a\", \"c\", \"d\"))); // tasks waiting\n\t\tassertEquals(sch.allStopped(), new HashSet<>(Arrays.asList(\"b\"))); // stopped tasks\n\n\t\t// the next tasks to execute are c,d,a\n\t\tsch.executeNext();\n\t\tassertEquals(sch.getExecutingTask(), \"c\");\n\t\tsch.preempt();\n\t\tsch.executeNext();\n\t\tassertEquals(sch.getExecutingTask(), \"d\");\n\t\tsch.preempt();\n\t\tsch.executeNext();\n\t\tassertEquals(sch.getExecutingTask(), \"a\");\n\n\t}", "\[email protected]\n\tpublic void testFinishing() {\n\t\tScheduler<String> sch = new SchedulerImpl<>();\n\t\tsch.add(\"a\");\n\t\tsch.add(\"b\");\n\t\tsch.add(\"c\");\n\t\tsch.add(\"d\");\n\n\t\t// execute the first one, i.e. a\n\t\tsch.executeNext();\n\t\tassertEquals(sch.getExecutingTask(), \"a\");\n\t\tassertTrue(sch.isExecuting()); // no task running\n\t\tassertEquals(sch.allWaiting(), new HashSet<>(Arrays.asList(\"b\", \"c\", \"d\"))); // tasks waiting\n\t\tassertEquals(sch.allStopped(), new HashSet<>(Arrays.asList())); // stopped tasks\n\n\t\t// a has completed execution, exits from the system\n\t\tsch.complete();\n\t\tassertFalse(sch.isExecuting()); // no task running\n\t\tassertEquals(sch.allWaiting(), new HashSet<>(Arrays.asList(\"b\", \"c\", \"d\"))); // tasks waiting\n\t\tassertEquals(sch.allStopped(), new HashSet<>(Arrays.asList())); // stopped tasks\n\t}", "\[email protected]\n\tpublic void testExceptions() {\n\t\tScheduler<String> sch = new SchedulerImpl<>();\n\t\ttry {\n\t\t\tsch.executeNext();\n\t\t\tfail(\"No task available!\");\n\t\t}" ] }, "content": "package ex2014.a02.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;\n\npublic class Test {\n\n\t/*\n\t * Implement the Scheduler interface given through a SchedulerImpl class\n\t * with a constructor without arguments.\n\t * This scheduler executes processes one at a time, has a queue of processes waiting,\n\t * and a queue of processes\n\t * stopped (i.e. that cannot restart until they are awakened).\n\t * The comment to the Scheduler code, and the test methods below\n\t * constitute the necessary explanation of the\n\t * problem.\n\t * Remove the comment from the tests..\n\t */\n\n\t// This test verifies that the execution of processes is circular\n\[email protected]\n\tpublic void testExec() {\n\t\tScheduler<String> sch = new SchedulerImpl<>();\n\t\tsch.add(\"a\");\n\t\tsch.add(\"b\");\n\t\tsch.add(\"c\");\n\t\tsch.add(\"d\");\n\t\tassertFalse(sch.isExecuting()); // no task running at the moment\n\t\tassertEquals(sch.allWaiting(), new HashSet<>(Arrays.asList(\"a\", \"b\", \"c\", \"d\"))); // tasks waiting: a,b,c,d\n\t\tassertEquals(sch.allStopped(), new HashSet<>(Arrays.asList())); // stopped tasks, none\n\n\t\t// execute the first one, i.e. \"a\"\n\t\tsch.executeNext();\n\t\tassertTrue(sch.isExecuting());\n\t\tassertEquals(sch.getExecutingTask(), \"a\");\n\t\tassertEquals(sch.allWaiting(), new HashSet<>(Arrays.asList(\"b\", \"c\", \"d\"))); // tasks waiting\n\t\tassertEquals(sch.allStopped(), new HashSet<>(Arrays.asList())); // stopped tasks\n\n\t\t// release the execution of \"a\", which returns to waiting\n\t\tsch.preempt();\n\t\tassertFalse(sch.isExecuting()); // no task running\n\t\tassertEquals(sch.allWaiting(), new HashSet<>(Arrays.asList(\"a\", \"b\", \"c\", \"d\"))); // tasks waiting\n\t\tassertEquals(sch.allStopped(), new HashSet<>(Arrays.asList())); // stopped tasks\n\n\t\t// execute and release b,c,d in sequence, then we return to execute a, and so on\n\t\tsch.executeNext();\n\t\tassertEquals(sch.getExecutingTask(), \"b\");\n\t\tsch.preempt();\n\t\tsch.executeNext();\n\t\tassertEquals(sch.getExecutingTask(), \"c\");\n\t\tsch.preempt();\n\t\tsch.executeNext();\n\t\tassertEquals(sch.getExecutingTask(), \"d\");\n\t\tsch.preempt();\n\t\tsch.executeNext();\n\t\tassertEquals(sch.getExecutingTask(), \"a\");\n\t\tassertTrue(sch.isExecuting()); // task running\n\t\tassertEquals(sch.allWaiting(), new HashSet<>(Arrays.asList(\"b\", \"c\", \"d\"))); // tasks waiting\n\t}\n\n\t// This test verifies that stopping processes moves them to the correct queue\n\[email protected]\n\tpublic void testStopping() {\n\t\tScheduler<String> sch = new SchedulerImpl<>();\n\t\tsch.add(\"a\");\n\t\tsch.add(\"b\");\n\t\tsch.add(\"c\");\n\t\tsch.add(\"d\");\n\n\t\t// execute the first one, i.e. a\n\t\tsch.executeNext();\n\t\tassertEquals(sch.getExecutingTask(), \"a\");\n\t\tassertTrue(sch.isExecuting()); // no task running\n\t\tassertEquals(sch.allWaiting(), new HashSet<>(Arrays.asList(\"b\", \"c\", \"d\"))); // tasks waiting\n\t\tassertEquals(sch.allStopped(), new HashSet<>(Arrays.asList())); // stopped tasks\n\n\t\t// stop the task being executed, which ends up in the stopped queue\n\t\tsch.stop();\n\t\tassertFalse(sch.isExecuting()); // no task running\n\t\tassertEquals(sch.allWaiting(), new HashSet<>(Arrays.asList(\"b\", \"c\", \"d\"))); // tasks waiting\n\t\tassertEquals(sch.allStopped(), new HashSet<>(Arrays.asList(\"a\"))); // stopped tasks\n\n\t\t// execute the next one, which is b\n\t\tsch.executeNext();\n\t\tassertEquals(sch.getExecutingTask(), \"b\");\n\n\t\t// stop the task being executed, it ends up in the stopped queue\n\t\tsch.stop();\n\t\tassertFalse(sch.isExecuting()); // no task running\n\t\tassertEquals(sch.allWaiting(), new HashSet<>(Arrays.asList(\"c\", \"d\"))); // tasks waiting\n\t\tassertEquals(sch.allStopped(), new HashSet<>(Arrays.asList(\"a\", \"b\"))); // stopped tasks\n\n\t\t// now \"a\" can continue, it passes into the waiting queue, but at the end!\n\t\tsch.unStop(\"a\");\n\t\tassertFalse(sch.isExecuting()); // no task running\n\t\tassertEquals(sch.allWaiting(), new HashSet<>(Arrays.asList(\"a\", \"c\", \"d\"))); // tasks waiting\n\t\tassertEquals(sch.allStopped(), new HashSet<>(Arrays.asList(\"b\"))); // stopped tasks\n\n\t\t// the next tasks to execute are c,d,a\n\t\tsch.executeNext();\n\t\tassertEquals(sch.getExecutingTask(), \"c\");\n\t\tsch.preempt();\n\t\tsch.executeNext();\n\t\tassertEquals(sch.getExecutingTask(), \"d\");\n\t\tsch.preempt();\n\t\tsch.executeNext();\n\t\tassertEquals(sch.getExecutingTask(), \"a\");\n\n\t}\n\n\t// This test verifies the exit of processes from the system\n\[email protected]\n\tpublic void testFinishing() {\n\t\tScheduler<String> sch = new SchedulerImpl<>();\n\t\tsch.add(\"a\");\n\t\tsch.add(\"b\");\n\t\tsch.add(\"c\");\n\t\tsch.add(\"d\");\n\n\t\t// execute the first one, i.e. a\n\t\tsch.executeNext();\n\t\tassertEquals(sch.getExecutingTask(), \"a\");\n\t\tassertTrue(sch.isExecuting()); // no task running\n\t\tassertEquals(sch.allWaiting(), new HashSet<>(Arrays.asList(\"b\", \"c\", \"d\"))); // tasks waiting\n\t\tassertEquals(sch.allStopped(), new HashSet<>(Arrays.asList())); // stopped tasks\n\n\t\t// a has completed execution, exits from the system\n\t\tsch.complete();\n\t\tassertFalse(sch.isExecuting()); // no task running\n\t\tassertEquals(sch.allWaiting(), new HashSet<>(Arrays.asList(\"b\", \"c\", \"d\"))); // tasks waiting\n\t\tassertEquals(sch.allStopped(), new HashSet<>(Arrays.asList())); // stopped tasks\n\t}\n\n\[email protected]\n\tpublic void testExceptions() {\n\t\tScheduler<String> sch = new SchedulerImpl<>();\n\t\ttry {\n\t\t\tsch.executeNext();\n\t\t\tfail(\"No task available!\");\n\t\t} catch (NoSuchElementException e) {\n\t\t} catch (Exception e) {\n\t\t\tfail(\"Wrong exception thrown\");\n\t\t}\n\t\tsch.add(\"a\");\n\t\ttry {\n\t\t\tsch.add(\"a\");\n\t\t\tfail(\"Not two equivalent tasks!\");\n\t\t} catch (IllegalArgumentException e) {\n\t\t} catch (Exception e) {\n\t\t\tfail(\"Wrong exception thrown\");\n\t\t}\n\t\ttry {\n\t\t\tsch.getExecutingTask();\n\t\t\tfail(\"No task in execution\");\n\t\t} catch (NoSuchElementException e) {\n\t\t} catch (Exception e) {\n\t\t\tfail(\"Wrong exception thrown\");\n\t\t}\n\t\ttry {\n\t\t\tsch.stop();\n\t\t\tfail(\"No task in execution\");\n\t\t} catch (IllegalStateException e) {\n\t\t} catch (Exception e) {\n\t\t\tfail(\"Wrong exception thrown\");\n\t\t}\n\t\ttry {\n\t\t\tsch.complete();\n\t\t\tfail(\"No task in execution\");\n\t\t} catch (IllegalStateException e) {\n\t\t} catch (Exception e) {\n\t\t\tfail(\"Wrong exception thrown\");\n\t\t}\n\t}\n\n}", "filename": "Test.java" }
2014
a03
[ { "content": "package ex2014.a03.sol1;\n\nimport java.io.*;\nimport java.util.*;\n\n\n\npublic interface RandomStatistics{\n\n\t\t\n\tvoid setFileName(String fileName);\n\t\n\t\t\n\tvoid storeSeries(long size) throws IOException;\n\t\n\t\t\n\tdouble loadToMax() throws IOException;\n\t\n\t\t\n\tlong loadToCountSmaller(double threshold) throws IOException;\n\t\n\t\t\n\tList<Long> loadToList(int r) throws IOException;\n\t\n\t\n}", "filename": "RandomStatistics.java" } ]
[ { "content": "package ex2014.a03.sol1;\n\nimport java.io.*;\nimport java.util.*;\nimport java.util.function.*;\n\n/**\n * Questa soluzione usa le lambda per fattorizzare il comportamento\n * comune delle tre load, ma una soluzione equivalente era ottenibile\n * con uno strategy e le classi anonime.\n */\n\npublic class RandomStatisticsImpl implements RandomStatistics{\n\t\n\tprivate Optional<String> fileName = Optional.empty();\n\n\t@Override\n\tpublic void setFileName(String fileName) {\n\t\tthis.fileName = Optional.of(fileName);\n\t}\n\n\t@Override\n\tpublic void storeSeries(long size) throws IOException {\n\t\tDataOutputStream dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(fileName.get())));\n\t\tdos.writeLong(size);\n\t\tfor (long l=0;l<size;l++){\n\t\t\tdos.writeDouble(Math.random());\n\t\t}\n\t\tdos.close();\n\t}\n\t\t\n\t@Override\n\tpublic double loadToMax() throws IOException {\n\t\treturn genericLoad((double)0,(x,y)->x>y?x:y);\n\t}\n\t\n\t@Override\n\tpublic long loadToCountSmaller(double threshold) throws IOException{\n\t\treturn genericLoad((long)0,(x,d)-> d<=threshold ? x+1 : x);\n\t}\n\t\n\t@Override\n\tpublic List<Long> loadToList(int ranges) throws IOException{\n\t\treturn genericLoad(\n\t\t\t\tnew ArrayList<>(Collections.nCopies(ranges, 0L)), \n\t\t\t\t(l,d) ->{\n\t\t\t\t\tint slot = (int)Math.floor(d*ranges);\n\t\t\t\t\tl.set(slot,l.get(slot)+1);\n\t\t\t\t\treturn l;\n\t\t\t\t}\n\t\t);\n\t}\n\t\t\n\tprivate <D> D genericLoad(D data, BiFunction<D,Double,D> acc) throws IOException {\n\t\tDataInputStream dis = new DataInputStream(new BufferedInputStream(new FileInputStream(fileName.get())));\n\t\tlong size = dis.readLong();\n\t\tfor (long l=0;l<size;l++){\n\t\t\tdata = acc.apply(data,dis.readDouble());\n\t\t}\n\t\tdis.close();\n\t\treturn data;\n\t}\n\t\n}", "filename": "RandomStatisticsImpl.java" } ]
{ "components": { "imports": "package ex2014.a03.sol1;\n\nimport static org.junit.Assert.*;\nimport java.io.*;", "private_init": "\t/*\n\t * Implement the RandomStatistics interface given through a RandomStatisticsImpl class with a constructor without arguments.\n\t * This class implements a generator of random real numbers (reals between 0 and 1, generated with Math.random) to be written to a file, \n\t * and then to be read each time to extract various information (the maximum value, how many numbers are below a threshold, \n\t * or a list that describes how the elements are arranged in certain thresholds, for example in 0-0.2, 0.2-0.4, 0.4-0.6, 0.6-0-8, 0.8-1)\n\t * The comment to the RandomStatistics code, and the test method below constitute an additional explanation of the \n\t * problem.\n\t * \n\t * IMPORTANT: 5 points in this exercise will be awarded to those who can build a solution with a high level of quality,\n\t * in particular regarding the absence of any code repetition, using \"well-designed\" code, i.e. carefully choosing the \n\t * pattern to use.\n\t */", "test_functions": [ "\[email protected]\n\tpublic void testOK() throws IOException{\n\t\tString filename = System.getProperty(\"user.home\")+System.getProperty(\"file.separator\")+\"stat.dat\";\n\t\tSystem.out.println(\"Using file: \"+filename);\n\t\tSystem.out.println();\n\t\t\n\t\tRandomStatistics rs = new RandomStatisticsImpl();\n\t\trs.setFileName(filename);\n\t\t// Generate a series of 1000 random numbers\n\t\tlong dim;\n\t\tdim = 1000;\n\t\trs.storeSeries(dim);\n\t\tSystem.out.println(\"Working with dim: \"+dim);\n\t\t// Get various information and print it to the screen..\n\t\tSystem.out.println(\"Max: \"+rs.loadToMax()); // almost 1\n\t\tSystem.out.println(\"Count(<0.8): \"+rs.loadToCountSmaller(0.8)); // almost 800\n\t\tSystem.out.println(\"List(3): \"+rs.loadToList(3)); // quasi [333,333,334]\n\t\tSystem.out.println();\n\t\t\n\t\t// Same thing with a new series of 100000 random numbers\n\t\tdim = 100000;\n\t\trs.storeSeries(dim);\n\t\tSystem.out.println(\"Working with dim: \"+dim);\n\t\tSystem.out.println(\"Max: \"+rs.loadToMax()); // almost 1\n\t\tSystem.out.println(\"Count(<0.5): \"+rs.loadToCountSmaller(0.5)); // almost 50000\n\t\tSystem.out.println(\"List(5): \"+rs.loadToList(5)); // quasi [20000,20000,20000,20000,20000]\n\t\tSystem.out.println();\n\t\t\n\t\t// Test considering acceptable error margins\n\t\tassertTrue(rs.loadToMax()>0.99);\n\t\tassertTrue(rs.loadToCountSmaller(0.5)>49000 && rs.loadToCountSmaller(0.5)<51000);\n\t\tassertEquals(rs.loadToList(5).size(),5);\n\t\tassertTrue(rs.loadToList(5).get(0)>19000 && rs.loadToList(5).get(0)<21000);\n\t\tassertTrue(rs.loadToList(5).get(1)>19000 && rs.loadToList(5).get(0)<21000);\n\t\tassertTrue(rs.loadToList(5).get(2)>19000 && rs.loadToList(5).get(0)<21000);\n\t\tassertTrue(rs.loadToList(5).get(3)>19000 && rs.loadToList(5).get(0)<21000);\n\t\tassertTrue(rs.loadToList(5).get(4)>19000 && rs.loadToList(5).get(0)<21000);\n\t\t\n\t}" ] }, "content": "package ex2014.a03.sol1;\n\nimport static org.junit.Assert.*;\nimport java.io.*;\n\npublic class Test {\n\t\n\t/*\n\t * Implement the RandomStatistics interface given through a RandomStatisticsImpl class with a constructor without arguments.\n\t * This class implements a generator of random real numbers (reals between 0 and 1, generated with Math.random) to be written to a file, \n\t * and then to be read each time to extract various information (the maximum value, how many numbers are below a threshold, \n\t * or a list that describes how the elements are arranged in certain thresholds, for example in 0-0.2, 0.2-0.4, 0.4-0.6, 0.6-0-8, 0.8-1)\n\t * The comment to the RandomStatistics code, and the test method below constitute an additional explanation of the \n\t * problem.\n\t * \n\t * IMPORTANT: 5 points in this exercise will be awarded to those who can build a solution with a high level of quality,\n\t * in particular regarding the absence of any code repetition, using \"well-designed\" code, i.e. carefully choosing the \n\t * pattern to use.\n\t */\n\n\[email protected]\n\tpublic void testOK() throws IOException{\n\t\tString filename = System.getProperty(\"user.home\")+System.getProperty(\"file.separator\")+\"stat.dat\";\n\t\tSystem.out.println(\"Using file: \"+filename);\n\t\tSystem.out.println();\n\t\t\n\t\tRandomStatistics rs = new RandomStatisticsImpl();\n\t\trs.setFileName(filename);\n\t\t// Generate a series of 1000 random numbers\n\t\tlong dim;\n\t\tdim = 1000;\n\t\trs.storeSeries(dim);\n\t\tSystem.out.println(\"Working with dim: \"+dim);\n\t\t// Get various information and print it to the screen..\n\t\tSystem.out.println(\"Max: \"+rs.loadToMax()); // almost 1\n\t\tSystem.out.println(\"Count(<0.8): \"+rs.loadToCountSmaller(0.8)); // almost 800\n\t\tSystem.out.println(\"List(3): \"+rs.loadToList(3)); // quasi [333,333,334]\n\t\tSystem.out.println();\n\t\t\n\t\t// Same thing with a new series of 100000 random numbers\n\t\tdim = 100000;\n\t\trs.storeSeries(dim);\n\t\tSystem.out.println(\"Working with dim: \"+dim);\n\t\tSystem.out.println(\"Max: \"+rs.loadToMax()); // almost 1\n\t\tSystem.out.println(\"Count(<0.5): \"+rs.loadToCountSmaller(0.5)); // almost 50000\n\t\tSystem.out.println(\"List(5): \"+rs.loadToList(5)); // quasi [20000,20000,20000,20000,20000]\n\t\tSystem.out.println();\n\t\t\n\t\t// Test considering acceptable error margins\n\t\tassertTrue(rs.loadToMax()>0.99);\n\t\tassertTrue(rs.loadToCountSmaller(0.5)>49000 && rs.loadToCountSmaller(0.5)<51000);\n\t\tassertEquals(rs.loadToList(5).size(),5);\n\t\tassertTrue(rs.loadToList(5).get(0)>19000 && rs.loadToList(5).get(0)<21000);\n\t\tassertTrue(rs.loadToList(5).get(1)>19000 && rs.loadToList(5).get(0)<21000);\n\t\tassertTrue(rs.loadToList(5).get(2)>19000 && rs.loadToList(5).get(0)<21000);\n\t\tassertTrue(rs.loadToList(5).get(3)>19000 && rs.loadToList(5).get(0)<21000);\n\t\tassertTrue(rs.loadToList(5).get(4)>19000 && rs.loadToList(5).get(0)<21000);\n\t\t\n\t}\n}", "filename": "Test.java" }
2014
a04
[ { "content": "package ex2014.a04.sol1;\n\nimport java.util.*;\n\n\n\npublic interface TicTacToe {\n\t\n\t\n\t\n\tenum Player { X, O };\n\t\n\t\n\t\n\tenum Cell {\n\t\t\n\t\tNW(0,0), N(0,1), NE(0,2),\n\t\tW(1,0), C(1,1), E(1,2),\n\t\tSW(2,0), S(2,1), SE(2,2);\n\t\t\n\t\tpublic static final List<List<Cell>> WINNING_TRIPLES = Arrays.asList(\n\t\t\t\tArrays.asList(NE,N,NW), Arrays.asList(E,C,W), Arrays.asList(SE,S,SW),\n\t\t\t\tArrays.asList(NE,E,SE), Arrays.asList(N,C,S), Arrays.asList(NW,W,SW),\n\t\t\t\tArrays.asList(NE,C,SW), Arrays.asList(NW,C,SE)\n\t\t);\n\t\t\n\t\tfinal private int row;\n\t\tfinal private int col;\n\t\t\n\t\tprivate Cell(int row,int col){\n\t\t\tthis.row = row;\n\t\t\tthis.col = col;\n\t\t}\n\n\t\tpublic int getRow() {\n\t\t\treturn this.row;\n\t\t}\n\n\t\tpublic int getColumn() {\n\t\t\treturn this.col;\n\t\t}\n\t\t\n\t}\n\t\n\t\n\tvoid start(Player p);\n\t\n\t\n\tPlayer nextPlayer();\n\t\n\t\n\tboolean isEven();\n\n\t\n\tboolean isOver();\n\t\n\t\n\tPlayer won();\n\t\t\n\t\n\tvoid move(Cell c,Player p);\n\t\n\t\n\tSet<Cell> getAvailableCells();\n\t\n\t\n\tCell getAvailableCell(int row,int col);\n\t\n\t\n\tMap<Player,Set<Cell>> getOccupiedCells();\n}", "filename": "TicTacToe.java" } ]
[ { "content": "package ex2014.a04.sol1;\n\nimport java.util.*;\nimport java.util.stream.Collectors;\nimport static ex2014.a04.sol1.TicTacToe.Cell.*;\n\n/**\n * Questa interfaccia è usata per controllare una partita del gioco TicTacToe (tris).\n * In generale, richiamare un metodo quando non appropriato (ad esempio, muovere quando la partita è finita) deve lanciare un IllegalStateException.\n * Anche NullPointerException eIllegalArgumentException vadano usati ove necessario per rendere l'implementazione completa e robusta. \n */\n\npublic class TicTacToeImpl implements TicTacToe {\n\t\n\tprivate Optional<Player> turn = Optional.empty();\n\tprivate Set<Cell> available = new HashSet<>(Arrays.asList(Cell.values()));\n\tprivate Map<Player,Set<Cell>> map = new HashMap<>();\n\tprivate Optional<Player> won = Optional.empty();\n\t\n\tpublic TicTacToeImpl(){\n\t\tthis.map.put(Player.X,new HashSet<>());\n\t\tthis.map.put(Player.O,new HashSet<>());\n\t}\n\t\n\t@Override\n\tpublic void start(Player p) {\n\t\tif (turn.isPresent() || this.isOver()){\n\t\t\tthrow new IllegalStateException();\n\t\t}\n\t\tthis.turn = Optional.of(p);\n\t}\n\t\n\tprivate Player otherTurn(Player p){\n\t\treturn p==Player.X ? Player.O : Player.X;\n\t}\n\t\n\n\t@Override\n\tpublic Player nextPlayer() {\n\t return this.turn.isPresent() || this.isOver() ? null : otherTurn(this.turn.get()); \t\n\t}\n\n\t@Override\n\tpublic boolean isOver() {\n\t\treturn this.available.size()==0 || this.won.isPresent();\n\t}\n\n\t@Override\n\tpublic Player won(){\n\t\treturn this.won.orElse(null);\n\t}\n\n\t@Override\n\tpublic boolean isEven() {\n\t\treturn this.available.size()==0 && !this.won.isPresent();\n\t}\n\n\t@Override\n\tpublic void move(Cell c, Player p) {\n\t\tif (!this.turn.isPresent() || this.turn.get()!=p || !this.available.contains(c)){\n\t\t\tthrow new IllegalStateException();\n\t\t}\n\t\tthis.available.remove(c);\n\t\tthis.map.get(p).add(c);\n\t\tif (WINNING_TRIPLES.stream().anyMatch((l)->this.map.get(p).containsAll(l))){\n\t\t\tthis.won = Optional.of(p);\n\t\t} \n\t\tthis.turn = Optional.of(otherTurn(p));\n\t}\n\n\t@Override\n\tpublic Set<Cell> getAvailableCells() {\n\t\treturn new HashSet<>(this.available);\n\t}\n\t\n\t@Override\n\tpublic Cell getAvailableCell(int row, int col) {\n\t\treturn this.getAvailableCells().stream().filter((c)->c.getRow()==row && c.getColumn()==col).findAny().orElse(null);\n\t}\n\n\t@Override\n\tpublic Map<Player, Set<Cell>> getOccupiedCells() {\n\t\treturn this.map.entrySet().stream().collect(Collectors.toMap(e->e.getKey(),e->defend(e.getValue())));\n\t}\n\t\n\t// Local implementation of \"defensive copy\" for a Set<X>\n\tprivate static <X> Set<X> defend(Set<X> set){\n\t\treturn new HashSet<>(set);\n\t}\n\n}", "filename": "TicTacToeImpl.java" } ]
{ "components": { "imports": "package ex2014.a04.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;", "private_init": "\t/*\n\t * Implement the given TicTacToe interface through a TicTacToeImpl class with a no-argument constructor, which\n\t * implements the management of a Tic Tac Toe game.\n\t * The comment on the TicTacToe code, and the two test methods below constitute the necessary explanation of the\n\t * problem.\n\t */\n\n\t// Test of a complete game, in which X wins at the end", "test_functions": [ "\[email protected]\n\tpublic void testOK1() {\n\t\tTicTacToe ttt = new TicTacToeImpl();\n\t\tttt.start(TicTacToe.Player.X);\t// X starts playing\n\t\tassertEquals(ttt.getAvailableCells().size(), 9); // All cells are free\n\t\tttt.move(TicTacToe.Cell.C, TicTacToe.Player.X); // X marks in the central cell\n\t\tttt.move(TicTacToe.Cell.NE, TicTacToe.Player.O); // O marks in the top right cell\n\t\tttt.move(TicTacToe.Cell.NW, TicTacToe.Player.X); // X marks in the top left cell\n\t\tttt.move(TicTacToe.Cell.E, TicTacToe.Player.O); // O marks in the right cell\n\t\tassertEquals(ttt.getAvailableCells().size(), 5); // All cells are free\n\t\tassertEquals(ttt.getOccupiedCells().get(TicTacToe.Player.X).size(),2); // 2 cells have X..\n\t\tassertTrue(ttt.getOccupiedCells().get(TicTacToe.Player.X).contains(TicTacToe.Cell.C)); // X is in C\n\t\tassertTrue(ttt.getOccupiedCells().get(TicTacToe.Player.X).contains(TicTacToe.Cell.NW)); // X is in NW\n\t\tassertEquals(ttt.getOccupiedCells().get(TicTacToe.Player.O).size(),2); // 2 cells have O..\n\t\tassertFalse(ttt.isOver()); // The game is not over\n\t\tassertFalse(ttt.isEven()); // The game is not tied\n\t\tassertNull(ttt.won()); // No one has won\n\t\tassertEquals(ttt.getAvailableCell(2, 2),TicTacToe.Cell.SE); // Cell 2,2 (SW) is free\n\t\tassertNull(ttt.getAvailableCell(1, 1)); // Cell 1,1 (C) is not free\n\t\t// current game state\n\t\t//\tX.O\n\t\t// .XO \n\t\t// ...\n\t\tttt.move(TicTacToe.Cell.S, TicTacToe.Player.X);\n\t\tttt.move(TicTacToe.Cell.N, TicTacToe.Player.O);\n\t\tttt.move(TicTacToe.Cell.W, TicTacToe.Player.X);\n\t\tttt.move(TicTacToe.Cell.SW, TicTacToe.Player.O);\n\t\t// current game state\n\t\t//\tXOO\n\t\t// XXO\n\t\t// OX.\n\t\tassertFalse(ttt.isEven()); // The game is not tied\n\t\tassertFalse(ttt.isOver()); // The game is not over\n\t\tassertNull(ttt.won()); // No one has won\n\t\tttt.move(TicTacToe.Cell.SE, TicTacToe.Player.X); // Winning move\n\n\t\tassertEquals(ttt.won(),TicTacToe.Player.X); // X has won\n\t\tassertFalse(ttt.isEven()); // The game is not tied\n\t\tassertTrue(ttt.isOver()); // The game is over\n\t\tassertEquals(ttt.getAvailableCells().size(), 0); // No free cells\n\t}", "\[email protected]\n\tpublic void testOK2() {\n\t\tTicTacToe ttt = new TicTacToeImpl();\n\t\tttt.start(TicTacToe.Player.O);\n\t\t\n\t\tttt.move(TicTacToe.Cell.NE, TicTacToe.Player.O);\n\t\tttt.move(TicTacToe.Cell.SE, TicTacToe.Player.X);\n\t\tttt.move(TicTacToe.Cell.N, TicTacToe.Player.O);\n\t\tttt.move(TicTacToe.Cell.S, TicTacToe.Player.X);\n\t\tttt.move(TicTacToe.Cell.NW, TicTacToe.Player.O);\n\t\t//\tOOO\n\t\t// ...\n\t\t// .XX\n\t\t\t\n\t\tassertEquals(ttt.won(),TicTacToe.Player.O); // O has won\n\t\tassertFalse(ttt.isEven()); // The game is not tied\n\t\tassertTrue(ttt.isOver()); // The game is over\n\t}", "\[email protected]\n\tpublic void testOK3() {\n\t\tTicTacToe ttt = new TicTacToeImpl();\n\t\tttt.start(TicTacToe.Player.O);\n\t\t\t\n\t\tttt.move(TicTacToe.Cell.NE, TicTacToe.Player.O);\n\t\tttt.move(TicTacToe.Cell.N, TicTacToe.Player.X);\n\t\tttt.move(TicTacToe.Cell.NW, TicTacToe.Player.O);\n\t\tttt.move(TicTacToe.Cell.C, TicTacToe.Player.X);\n\t\tttt.move(TicTacToe.Cell.W, TicTacToe.Player.O);\n\t\tttt.move(TicTacToe.Cell.E, TicTacToe.Player.X);\n\t\tttt.move(TicTacToe.Cell.S, TicTacToe.Player.O);\n\t\tttt.move(TicTacToe.Cell.SW, TicTacToe.Player.X);\n\t\tttt.move(TicTacToe.Cell.SE, TicTacToe.Player.O);\n\t\t//\tOXO\n\t\t// OXX\n\t\t// XOO\n\t\t\t\t\n\t\tassertNull(ttt.won()); // no winner\n\t\tassertTrue(ttt.isEven()); // The game is tied\n\t\tassertTrue(ttt.isOver()); // The game is over\n\t}", "\[email protected]\n\tpublic void testEXC() {\n\t\tTicTacToe ttt = new TicTacToeImpl();\n\t\tttt.start(TicTacToe.Player.O);\n\t\t\n\t\ttry{\n\t\t\tttt.start(TicTacToe.Player.X);\n\t\t\tfail(\"Can't restart!\");\n\t\t}" ] }, "content": "package ex2014.a04.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;\n\npublic class Test {\n\t\n\t/*\n\t * Implement the given TicTacToe interface through a TicTacToeImpl class with a no-argument constructor, which\n\t * implements the management of a Tic Tac Toe game.\n\t * The comment on the TicTacToe code, and the two test methods below constitute the necessary explanation of the\n\t * problem.\n\t */\n\n\t// Test of a complete game, in which X wins at the end\n\[email protected]\n\tpublic void testOK1() {\n\t\tTicTacToe ttt = new TicTacToeImpl();\n\t\tttt.start(TicTacToe.Player.X);\t// X starts playing\n\t\tassertEquals(ttt.getAvailableCells().size(), 9); // All cells are free\n\t\tttt.move(TicTacToe.Cell.C, TicTacToe.Player.X); // X marks in the central cell\n\t\tttt.move(TicTacToe.Cell.NE, TicTacToe.Player.O); // O marks in the top right cell\n\t\tttt.move(TicTacToe.Cell.NW, TicTacToe.Player.X); // X marks in the top left cell\n\t\tttt.move(TicTacToe.Cell.E, TicTacToe.Player.O); // O marks in the right cell\n\t\tassertEquals(ttt.getAvailableCells().size(), 5); // All cells are free\n\t\tassertEquals(ttt.getOccupiedCells().get(TicTacToe.Player.X).size(),2); // 2 cells have X..\n\t\tassertTrue(ttt.getOccupiedCells().get(TicTacToe.Player.X).contains(TicTacToe.Cell.C)); // X is in C\n\t\tassertTrue(ttt.getOccupiedCells().get(TicTacToe.Player.X).contains(TicTacToe.Cell.NW)); // X is in NW\n\t\tassertEquals(ttt.getOccupiedCells().get(TicTacToe.Player.O).size(),2); // 2 cells have O..\n\t\tassertFalse(ttt.isOver()); // The game is not over\n\t\tassertFalse(ttt.isEven()); // The game is not tied\n\t\tassertNull(ttt.won()); // No one has won\n\t\tassertEquals(ttt.getAvailableCell(2, 2),TicTacToe.Cell.SE); // Cell 2,2 (SW) is free\n\t\tassertNull(ttt.getAvailableCell(1, 1)); // Cell 1,1 (C) is not free\n\t\t// current game state\n\t\t//\tX.O\n\t\t// .XO \n\t\t// ...\n\t\tttt.move(TicTacToe.Cell.S, TicTacToe.Player.X);\n\t\tttt.move(TicTacToe.Cell.N, TicTacToe.Player.O);\n\t\tttt.move(TicTacToe.Cell.W, TicTacToe.Player.X);\n\t\tttt.move(TicTacToe.Cell.SW, TicTacToe.Player.O);\n\t\t// current game state\n\t\t//\tXOO\n\t\t// XXO\n\t\t// OX.\n\t\tassertFalse(ttt.isEven()); // The game is not tied\n\t\tassertFalse(ttt.isOver()); // The game is not over\n\t\tassertNull(ttt.won()); // No one has won\n\t\tttt.move(TicTacToe.Cell.SE, TicTacToe.Player.X); // Winning move\n\n\t\tassertEquals(ttt.won(),TicTacToe.Player.X); // X has won\n\t\tassertFalse(ttt.isEven()); // The game is not tied\n\t\tassertTrue(ttt.isOver()); // The game is over\n\t\tassertEquals(ttt.getAvailableCells().size(), 0); // No free cells\n\t}\n\t\n\t// Test of a game in which O wins quickly\n\[email protected]\n\tpublic void testOK2() {\n\t\tTicTacToe ttt = new TicTacToeImpl();\n\t\tttt.start(TicTacToe.Player.O);\n\t\t\n\t\tttt.move(TicTacToe.Cell.NE, TicTacToe.Player.O);\n\t\tttt.move(TicTacToe.Cell.SE, TicTacToe.Player.X);\n\t\tttt.move(TicTacToe.Cell.N, TicTacToe.Player.O);\n\t\tttt.move(TicTacToe.Cell.S, TicTacToe.Player.X);\n\t\tttt.move(TicTacToe.Cell.NW, TicTacToe.Player.O);\n\t\t//\tOOO\n\t\t// ...\n\t\t// .XX\n\t\t\t\n\t\tassertEquals(ttt.won(),TicTacToe.Player.O); // O has won\n\t\tassertFalse(ttt.isEven()); // The game is not tied\n\t\tassertTrue(ttt.isOver()); // The game is over\n\t}\n\t\n\t// Test of a tied game\n\[email protected]\n\tpublic void testOK3() {\n\t\tTicTacToe ttt = new TicTacToeImpl();\n\t\tttt.start(TicTacToe.Player.O);\n\t\t\t\n\t\tttt.move(TicTacToe.Cell.NE, TicTacToe.Player.O);\n\t\tttt.move(TicTacToe.Cell.N, TicTacToe.Player.X);\n\t\tttt.move(TicTacToe.Cell.NW, TicTacToe.Player.O);\n\t\tttt.move(TicTacToe.Cell.C, TicTacToe.Player.X);\n\t\tttt.move(TicTacToe.Cell.W, TicTacToe.Player.O);\n\t\tttt.move(TicTacToe.Cell.E, TicTacToe.Player.X);\n\t\tttt.move(TicTacToe.Cell.S, TicTacToe.Player.O);\n\t\tttt.move(TicTacToe.Cell.SW, TicTacToe.Player.X);\n\t\tttt.move(TicTacToe.Cell.SE, TicTacToe.Player.O);\n\t\t//\tOXO\n\t\t// OXX\n\t\t// XOO\n\t\t\t\t\n\t\tassertNull(ttt.won()); // no winner\n\t\tassertTrue(ttt.isEven()); // The game is tied\n\t\tassertTrue(ttt.isOver()); // The game is over\n\t}\n\t\n\t// Test of exceptions\n\[email protected]\n\tpublic void testEXC() {\n\t\tTicTacToe ttt = new TicTacToeImpl();\n\t\tttt.start(TicTacToe.Player.O);\n\t\t\n\t\ttry{\n\t\t\tttt.start(TicTacToe.Player.X);\n\t\t\tfail(\"Can't restart!\");\n\t\t} catch (IllegalStateException e){\n\t\t} catch (Exception e){\n\t\t\tfail(\"Wrong exception thrown\");\n\t\t}\n\t\t\n\t\tttt.move(TicTacToe.Cell.NE, TicTacToe.Player.O);\n\t\t\n\t\ttry{\n\t\t\tttt.move(TicTacToe.Cell.NE, TicTacToe.Player.X);\n\t\t\tfail(\"Can't move there, it's already O!\");\n\t\t} catch (IllegalStateException e){\n\t\t} catch (Exception e){\n\t\t\tfail(\"Wrong exception thrown\");\n\t\t}\n\t\t\n\t\tttt.move(TicTacToe.Cell.C, TicTacToe.Player.X);\n\t\t\n\t\ttry{\n\t\t\tttt.move(TicTacToe.Cell.NW, TicTacToe.Player.X);\n\t\t\tfail(\"Wrong turn! It's O turn\");\n\t\t} catch (IllegalStateException e){\n\t\t} catch (Exception e){\n\t\t\tfail(\"Wrong exception thrown\");\n\t\t}\n\t}\t\t\n}", "filename": "Test.java" }
2014
a02b
[ { "content": "package ex2014.a02b.sol1;\n\nimport java.util.*;\n\npublic interface TicketDispenser<A> {\n\t\n\t\n\tint getCashDeskSize();\n\t\n\t\n\tint getNextAvailableTicket();\n\t\n\t\n\tint giveNextTicketToAgent(A agent);\n\t\n\t\n\tvoid useCashDesk(int desk);\n\t\n\t\n\tvoid releaseCashDesk(int desk);\n\t\n\t\n\tboolean isCashDeskServing(int desk);\n\t\n\t\n\tA getAgentUsingCashDesk(int desk);\n\t\n\t\n\tint getNextServingTicket();\n\t\n\t\n\tSet<A> allWaiting();\n\t\n\t\n\tSet<A> allCurrentlyServed();\n\n}", "filename": "TicketDispenser.java" } ]
[ { "content": "package ex2014.a02b.sol1;\n\nimport java.util.*;\nimport java.util.stream.*;\n\npublic class TicketDispenserImpl<A> implements TicketDispenser<A>{\n\t\n\tprivate List<A> waiting = new ArrayList<>();\n\tprivate int currentTicket = 0;\n\tprivate int nextTicketToServe = 0;\n\tprivate List<Optional<A>> served = new ArrayList<>();\n\t\n\tpublic TicketDispenserImpl(int size){\n\t\tfor (int i=0;i<size;i++){\n\t\t\tserved.add(Optional.empty());\n\t\t}\n\t}\n\n\t@Override\n\tpublic int getCashDeskSize() {\n\t\treturn this.served.size();\n\t}\n\n\t@Override\n\tpublic int getNextAvailableTicket() {\n\t\treturn this.currentTicket;\n\t\t\n\t}\n\n\t@Override\n\tpublic int giveNextTicketToAgent(A a) {\n\t\tif (this.waiting.contains(a) || \n\t\t\tthis.served.stream().filter(Optional::isPresent).map(Optional::get).anyMatch(a2->a2.equals(a))){\n\t\t\tthrow new IllegalArgumentException();\n\t\t}\n\t\twaiting.add(a);\n\t\treturn this.currentTicket++;\n\t}\n\n\t@Override\n\tpublic void useCashDesk(int desk){\n\t\tSystem.out.println(this.served.get(desk));\n\t\tif (this.waiting.size()==0 || this.served.get(desk).isPresent()){\n\t\t\tthrow new IllegalStateException();\n\t\t}\n\t\tfinal A a = this.waiting.remove(0);\n\t\tthis.served.set(desk,Optional.of(a));\n\t\tthis.nextTicketToServe++;\n\t}\n\n\t@Override\n\tpublic void releaseCashDesk(int desk) {\n\t\tthis.served.set(desk,Optional.empty());\n\t\t\n\t}\n\n\t@Override\n\tpublic boolean isCashDeskServing(int desk) {\n\t\treturn this.served.get(desk).isPresent();\n\t}\n\n\t@Override\n\tpublic A getAgentUsingCashDesk(int desk) {\n\t\tif (!this.isCashDeskServing(desk)){\n\t\t\tthrow new NoSuchElementException();\n\t\t}\n\t\treturn this.served.get(desk).get();\n\t}\n\n\t@Override\n\tpublic int getNextServingTicket() {\n\t\treturn this.nextTicketToServe;\n\t}\n\n\t@Override\n\tpublic Set<A> allWaiting() {\n\t\treturn new HashSet<>(this.waiting);\n\t}\n\n\t@Override\n\tpublic Set<A> allCurrentlyServed() {\n\t\treturn this.served.stream().filter(Optional::isPresent).map(Optional::get).collect(Collectors.toSet());\n\t}\n\n}", "filename": "TicketDispenserImpl.java" } ]
{ "components": { "imports": "package ex2014.a02b.sol1;\n\nimport static org.junit.Assert.*;\n\nimport java.util.*;", "private_init": "\t/*\n\t * Implement the given TicketDispenser interface through a TicketDispenser class with a constructor that accepts\n\t * an integer argument, which represents the number of \"cash desks\" that offer a coordinated service\n\t * by a ticket dispenser (with incremental numerical values) -- like at the post office, to be clear. A user (Agent)\n\t * upon arrival tears off their ticket (Ticket) and waits. When a cash desk (CashDesk) is free, the user\n\t * with the lowest ticket number uses it: when they release it, they exit the system.\n\t * The comment on the TicketDispenser code, and the test methods below constitute the necessary explanation of the\n\t * problem.\n\t * Remove the comment from the tests..\n\t */\n\n\t// This test verifies the correct behavior of the system", "test_functions": [ "\[email protected]\n\tpublic void testExec() { \n\t\t// System with 3 cash desks: 0,1,2; the agents are strings\n\t\tTicketDispenser<String> disp = new TicketDispenserImpl<>(3);\n\t\t\n\t\tassertEquals(disp.getNextServingTicket(),0); \t // next ticket to serve: 0\n\t\tassertEquals(disp.getNextAvailableTicket(),0);\t // next ticket to take: 0\n\t\tassertEquals(disp.allCurrentlyServed().size(),0); // agents currently served: none\n\t\tassertEquals(disp.allWaiting().size(),0);\t\t // agents waiting: none\n\t\t\n\t\t// 5 agents arrive and take the ticket, note the incrementality\n\t\tassertEquals(disp.giveNextTicketToAgent(\"a\"),0);\n\t\tassertEquals(disp.giveNextTicketToAgent(\"b\"),1);\n\t\tassertEquals(disp.giveNextTicketToAgent(\"c\"),2);\n\t\tassertEquals(disp.giveNextTicketToAgent(\"d\"),3);\n\t\tassertEquals(disp.giveNextTicketToAgent(\"e\"),4);\n\t\t\n\t\t// new situation\n\t\tassertEquals(disp.getNextServingTicket(),0); \t\t// next ticket to serve: 0\n\t\tassertEquals(disp.getNextAvailableTicket(),5);\t\t// next ticket to take: 5\n\t\tassertEquals(disp.allCurrentlyServed().size(),0);\t// agents currently served: none\n\t\tassertEquals(disp.allWaiting(),new HashSet<>(Arrays.asList(\"a\",\"b\",\"c\",\"d\",\"e\"))); // agents waiting: a,b,c,d,e\n\t\t\n\t\t// the first two agents in the queue are accepted at desk 0 and 2\n\t\tdisp.useCashDesk(0); // agent a (his turn!) goes to desk 0\n\t\tdisp.useCashDesk(2); // agent b (his turn!) goes to desk 0\n\t\t\n\t\tassertEquals(disp.allCurrentlyServed(),new HashSet<>(Arrays.asList(\"a\",\"b\"))); // a,b served\n\t\tassertEquals(disp.allWaiting(),new HashSet<>(Arrays.asList(\"c\",\"d\",\"e\"))); // c,d,e waiting\n\t\tassertEquals(disp.getNextServingTicket(),2); // the next to be served is the agent with 2\n\t\tassertEquals(disp.getNextAvailableTicket(),5); // the next ticket to tear off is 5\n\t\tassertEquals(disp.getAgentUsingCashDesk(0),\"a\"); // a uses cash desk 0\n\t\tassertEquals(disp.getAgentUsingCashDesk(2),\"b\"); // b uses cash desk 2\n\t\tassertTrue(disp.isCashDeskServing(0));\n\t\tassertTrue(disp.isCashDeskServing(2));\n\t\tassertFalse(disp.isCashDeskServing(1));\t// cash desk 1 is not used\n\t\t\n\t\t// b leaves cash desk 2\n\t\tdisp.releaseCashDesk(2);\n\t\t// cash desk 1 asks for a new customer: it's c!\n\t\tdisp.useCashDesk(1);\n\t\tassertEquals(disp.allCurrentlyServed(),new HashSet<>(Arrays.asList(\"a\",\"c\")));\n\t\tassertEquals(disp.allWaiting(),new HashSet<>(Arrays.asList(\"d\",\"e\")));\n\t\tassertEquals(disp.getNextServingTicket(),3);\n\t\tassertEquals(disp.getNextAvailableTicket(),5);\t\n\t\tassertEquals(disp.getAgentUsingCashDesk(0),\"a\");\n\t\tassertEquals(disp.getAgentUsingCashDesk(1),\"c\");\n\t\tassertTrue(disp.isCashDeskServing(0));\n\t\tassertTrue(disp.isCashDeskServing(1));\n\t\tassertFalse(disp.isCashDeskServing(2));\n\t\t\n\t\t// a new agent arrives: f\n\t\tassertEquals(disp.giveNextTicketToAgent(\"f\"),5);\n\t\tassertEquals(disp.getNextServingTicket(),3);\n\t\tassertEquals(disp.getNextAvailableTicket(),6);\n\t}", "\[email protected]\n\tpublic void testExceptions() {\n\t\tTicketDispenser<String> disp = new TicketDispenserImpl<>(3);\n\t\t\n\t\tdisp.giveNextTicketToAgent(\"a\");\n\t\ttry{\n\t\t\tdisp.giveNextTicketToAgent(\"a\");\n\t\t\tfail(\"No using an agent twice\");\n\t\t}" ] }, "content": "package ex2014.a02b.sol1;\n\nimport static org.junit.Assert.*;\n\nimport java.util.*;\n\npublic class Test {\n\t\n\t/*\n\t * Implement the given TicketDispenser interface through a TicketDispenser class with a constructor that accepts\n\t * an integer argument, which represents the number of \"cash desks\" that offer a coordinated service\n\t * by a ticket dispenser (with incremental numerical values) -- like at the post office, to be clear. A user (Agent)\n\t * upon arrival tears off their ticket (Ticket) and waits. When a cash desk (CashDesk) is free, the user\n\t * with the lowest ticket number uses it: when they release it, they exit the system.\n\t * The comment on the TicketDispenser code, and the test methods below constitute the necessary explanation of the\n\t * problem.\n\t * Remove the comment from the tests..\n\t */\n\n\t// This test verifies the correct behavior of the system\n\[email protected]\n\tpublic void testExec() { \n\t\t// System with 3 cash desks: 0,1,2; the agents are strings\n\t\tTicketDispenser<String> disp = new TicketDispenserImpl<>(3);\n\t\t\n\t\tassertEquals(disp.getNextServingTicket(),0); \t // next ticket to serve: 0\n\t\tassertEquals(disp.getNextAvailableTicket(),0);\t // next ticket to take: 0\n\t\tassertEquals(disp.allCurrentlyServed().size(),0); // agents currently served: none\n\t\tassertEquals(disp.allWaiting().size(),0);\t\t // agents waiting: none\n\t\t\n\t\t// 5 agents arrive and take the ticket, note the incrementality\n\t\tassertEquals(disp.giveNextTicketToAgent(\"a\"),0);\n\t\tassertEquals(disp.giveNextTicketToAgent(\"b\"),1);\n\t\tassertEquals(disp.giveNextTicketToAgent(\"c\"),2);\n\t\tassertEquals(disp.giveNextTicketToAgent(\"d\"),3);\n\t\tassertEquals(disp.giveNextTicketToAgent(\"e\"),4);\n\t\t\n\t\t// new situation\n\t\tassertEquals(disp.getNextServingTicket(),0); \t\t// next ticket to serve: 0\n\t\tassertEquals(disp.getNextAvailableTicket(),5);\t\t// next ticket to take: 5\n\t\tassertEquals(disp.allCurrentlyServed().size(),0);\t// agents currently served: none\n\t\tassertEquals(disp.allWaiting(),new HashSet<>(Arrays.asList(\"a\",\"b\",\"c\",\"d\",\"e\"))); // agents waiting: a,b,c,d,e\n\t\t\n\t\t// the first two agents in the queue are accepted at desk 0 and 2\n\t\tdisp.useCashDesk(0); // agent a (his turn!) goes to desk 0\n\t\tdisp.useCashDesk(2); // agent b (his turn!) goes to desk 0\n\t\t\n\t\tassertEquals(disp.allCurrentlyServed(),new HashSet<>(Arrays.asList(\"a\",\"b\"))); // a,b served\n\t\tassertEquals(disp.allWaiting(),new HashSet<>(Arrays.asList(\"c\",\"d\",\"e\"))); // c,d,e waiting\n\t\tassertEquals(disp.getNextServingTicket(),2); // the next to be served is the agent with 2\n\t\tassertEquals(disp.getNextAvailableTicket(),5); // the next ticket to tear off is 5\n\t\tassertEquals(disp.getAgentUsingCashDesk(0),\"a\"); // a uses cash desk 0\n\t\tassertEquals(disp.getAgentUsingCashDesk(2),\"b\"); // b uses cash desk 2\n\t\tassertTrue(disp.isCashDeskServing(0));\n\t\tassertTrue(disp.isCashDeskServing(2));\n\t\tassertFalse(disp.isCashDeskServing(1));\t// cash desk 1 is not used\n\t\t\n\t\t// b leaves cash desk 2\n\t\tdisp.releaseCashDesk(2);\n\t\t// cash desk 1 asks for a new customer: it's c!\n\t\tdisp.useCashDesk(1);\n\t\tassertEquals(disp.allCurrentlyServed(),new HashSet<>(Arrays.asList(\"a\",\"c\")));\n\t\tassertEquals(disp.allWaiting(),new HashSet<>(Arrays.asList(\"d\",\"e\")));\n\t\tassertEquals(disp.getNextServingTicket(),3);\n\t\tassertEquals(disp.getNextAvailableTicket(),5);\t\n\t\tassertEquals(disp.getAgentUsingCashDesk(0),\"a\");\n\t\tassertEquals(disp.getAgentUsingCashDesk(1),\"c\");\n\t\tassertTrue(disp.isCashDeskServing(0));\n\t\tassertTrue(disp.isCashDeskServing(1));\n\t\tassertFalse(disp.isCashDeskServing(2));\n\t\t\n\t\t// a new agent arrives: f\n\t\tassertEquals(disp.giveNextTicketToAgent(\"f\"),5);\n\t\tassertEquals(disp.getNextServingTicket(),3);\n\t\tassertEquals(disp.getNextAvailableTicket(),6);\n\t}\n\t\n\t// Test of exceptions\n\[email protected]\n\tpublic void testExceptions() {\n\t\tTicketDispenser<String> disp = new TicketDispenserImpl<>(3);\n\t\t\n\t\tdisp.giveNextTicketToAgent(\"a\");\n\t\ttry{\n\t\t\tdisp.giveNextTicketToAgent(\"a\");\n\t\t\tfail(\"No using an agent twice\");\n\t\t} catch (IllegalArgumentException e){\n\t\t} catch (Exception e){\n\t\t\tfail(\"Wrong exception thrown\");\n\t\t}\n\t\tdisp.giveNextTicketToAgent(\"b\");\n\t\tdisp.useCashDesk(0);\n\t\ttry{\n\t\t\tdisp.useCashDesk(0);\n\t\t\tfail(\"Cannot use cashdesk twice\");\n\t\t} catch (IllegalStateException e){\n\t\t} catch (Exception e){\n\t\t\tfail(\"Wrong exception thrown\");\n\t\t}\n\t\tdisp.useCashDesk(1);\n\t\ttry{\n\t\t\tdisp.useCashDesk(2);\n\t\t\tfail(\"No waiting agent\");\n\t\t} catch (IllegalStateException e){\n\t\t} catch (Exception e){\n\t\t\tfail(\"Wrong exception thrown\");\n\t\t}\n\t\ttry{\n\t\t\tdisp.getAgentUsingCashDesk(2);\n\t\t\tfail(\"No agent at cashdesk 2 now\");\n\t\t} catch (NoSuchElementException e){\n\t\t} catch (Exception e){\n\t\t\tfail(\"Wrong exception thrown\");\n\t\t}\n\t}\n\t\n}", "filename": "Test.java" }
2014
a06
[ { "content": "package ex2014.a06.sol1;\n\n\n\npublic interface Lamp {\n\t\n\t\n\t\n\tvoid on() throws IllegalStateException;\n\t\n\t\n\tvoid off();\n\t\n\t\n\tboolean isOn();\n\t\n\t\n\tvoid fail();\n\n}", "filename": "Lamp.java" }, { "content": "package ex2014.a06.sol1;\n\npublic class SimpleLamp implements Lamp {\n\t\n\tprivate boolean on = false;\n\t\n\t@Override\n\tpublic void on() throws IllegalStateException {\n\t\tthis.on = true;\t\t\n\t}\n\n\t@Override\n\tpublic void off() {\n\t\tthis.on = false;\n\t}\n\n\t@Override\n\tpublic boolean isOn() {\n\t\treturn this.on;\n\t}\n\n\t@Override\n\tpublic void fail(){\n\t}\n\t\n}", "filename": "SimpleLamp.java" }, { "content": "package ex2014.a06.sol1;\n\n\npublic interface LampFactory {\n\t\n\t\n\tLamp createLampWithRemainingDuration(int remainingDuration);\n\t\n\t\n\tLamp createLampWithTemporaneousFailure(int failingDuration);\n\n}", "filename": "LampFactory.java" } ]
[ { "content": "package ex2014.a06.sol1;\n\nimport java.util.Optional;\n\npublic class LampWithRemainingDuration extends AbstractLamp {\n\t\n\tprivate int remainingDuration;\n\t\n\tpublic LampWithRemainingDuration(int remainingDuration){\n\t\tthis.remainingDuration = remainingDuration;\n\t}\n\n\t@Override\n\tprotected void checkCanGoOn() throws IllegalStateException {\n\t\tif (this.on){ \n\t\t\treturn; \n\t\t}\n\t\tif (this.fail && this.remainingDuration == 0){\n\t\t\tthrow new IllegalStateException();\n\t\t}\n\t\tif (this.fail){\n\t\t\tthis.remainingDuration--;\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic void fail() {\n\t\tsuper.fail();\n\t}\n\t\n}", "filename": "LampWithRemainingDuration.java" }, { "content": "package ex2014.a06.sol1;\n\nimport java.util.Optional;\n\npublic class LampWithTemporaneousFail extends AbstractLamp {\n\t\n\tprotected int failingPeriod;\n\tprotected final int failingDuration;\n\t\n\tpublic LampWithTemporaneousFail(int failingDuration){\n\t\tthis.failingDuration = failingDuration;\n\t}\n\t\n\t@Override\n\tprotected void checkCanGoOn() throws IllegalStateException {\n\t\tif (this.fail){\n\t\t\tif (this.failingPeriod == this.failingDuration-1){\n\t\t\t\tthis.fail = false;\n\t\t\t} else {\n\t\t\t\tthis.failingPeriod++;\n\t\t\t}\n\t\t\tthrow new IllegalStateException();\n\t\t}\n\t}\n\n\t@Override\n\tpublic void fail() {\n\t\tif (!this.fail){\n\t\t\tsuper.fail();\n\t\t\tthis.failingPeriod = 0;\n\t\t\tthis.on = false;\n\t\t}\n\t}\n\t\n}", "filename": "LampWithTemporaneousFail.java" }, { "content": "package ex2014.a06.sol1;\n\npublic abstract class AbstractLamp implements Lamp {\n\t\n\tprotected boolean on = false;\n\tprotected boolean fail = false;\n\t\n\t@Override\n\tpublic void on() throws IllegalStateException {\n\t\tthis.checkCanGoOn();\n\t\tthis.on = true;\t\t\n\t}\n\t\n\tprotected abstract void checkCanGoOn() throws IllegalStateException;\n\n\t@Override\n\tpublic void off() {\n\t\tthis.on = false;\n\t}\n\n\t@Override\n\tpublic boolean isOn() {\n\t\treturn this.on;\n\t}\n\n\t@Override\n\tpublic void fail(){\n\t\tthis.fail = true;\n\t}\n\t\n}", "filename": "AbstractLamp.java" }, { "content": "package ex2014.a06.sol1;\n\npublic class LampFactoryImpl implements LampFactory{\n\t\n\tpublic Lamp createLampWithRemainingDuration(int remainingDuration){\n\t\treturn new LampWithRemainingDuration(remainingDuration);\n\t}\n\t\n\tpublic Lamp createLampWithTemporaneousFailure(int failingDuration){\n\t\treturn new LampWithTemporaneousFail(failingDuration);\n\t}\n\n}", "filename": "LampFactoryImpl.java" } ]
{ "components": { "imports": "package ex2014.a06.sol2;\n\nimport static org.junit.Assert.*;\n\nimport java.util.*;", "private_init": "\t/*\n\t * Consider the Lamp interface that models a light bulb with also a \"fail\" command that models its failure,\n\t * its trivial implementation SimpleLamp provided as an example only, and the LampFactory interface used to create objects\n\t * of two specific types of light bulbs.\n\t * A LampWithRemainingDuration when it fails will still work for a limited number of switches (taken as input).\n\t * A LampWithTemporaneousFailure when it fails stops working for a limited number of switches (taken as input), then works again.\n\t * \n\t * By implementing two different implementations of Lamp for these two specializations, implement LampFactory with a constructor\n\t * empty. Solutions that factor *all* the common aspects of these two specializations into an abstract class will be preferred.\n\t * \n\t * Remove the comment from the tests below..\n\t */\n\t\n\t// Basic test on any light bulb initially off\n\tprivate void basicChecks(Lamp l){\n\t\tassertFalse(l.isOn());\n\t\tl.on();\n\t\tassertTrue(l.isOn());\n\t\tl.on();\n\t\tassertTrue(l.isOn());\n\t\tl.off();\n\t\tassertFalse(l.isOn());\n\t\tl.off();\n\t\tassertFalse(l.isOn());\n\t\tl.on();\n\t\tassertTrue(l.isOn());\n\t}\n\t\n\t// Test of the provided SimpleLamp", "test_functions": [ "\[email protected]\n\tpublic void testSimpleLamp() {\n\t\tLamp l = new SimpleLamp();\n\t\tbasicChecks(l);\n\t}", "\[email protected]\n\tpublic void testLampWithRemainingDuration() {\n\t\t// Using the factory, I create a light bulb that upon failure will only last 3 more switches\n\t\tLamp l = new LampFactoryImpl().createLampWithRemainingDuration(3);\n\t\t// basic checks\n\t\tbasicChecks(l);\n\t\tl.on();\n\t\tassertTrue(l.isOn());\n\t\t// I make the light bulb fail\n\t\tl.fail();\n\t\t// it was on and remains on\n\t\tassertTrue(l.isOn());\n\t\t// for 3 times I turn it off and on\n\t\tfor (int i=0; i<3; i++){\n\t\t\tl.off();\n\t\t\tassertFalse(l.isOn());\n\t\t\tl.on();\n\t\t\tl.on(); // The second switch in a row has no effect\n\t\t\tassertTrue(l.isOn());\n\t\t}", "\[email protected]\n\tpublic void testLampWithTemporaneousFailure() {\n\t\t// Using the factory, I create a light bulb that upon failure will remain inactive for 3 switches, then work fine\n\t\tLamp l = new LampFactoryImpl().createLampWithTemporaneousFailure(3);\n\t\t// basic checks\n\t\tbasicChecks(l);\n\t\tl.on();\n\t\tassertTrue(l.isOn());\n\t\t// I make the light bulb fail\n\t\tl.fail();\n\t\tassertFalse(l.isOn());\n\t\t// for 3 times I try to turn it on, but it fails giving the exception\n\t\tfor (int i=0; i<3; i++){\n\t\t\ttry{\n\t\t\t\tl.on();\n\t\t\t\tfail(\"Switch on during failure should raise an exception\");\n\t\t\t}" ] }, "content": "package ex2014.a06.sol1;\n\nimport static org.junit.Assert.*;\n\nimport java.util.*;\n\npublic class Test {\n\n\t/*\n\t * Consider the Lamp interface that models a light bulb with also a \"fail\" command that models its failure,\n\t * its trivial implementation SimpleLamp provided as an example only, and the LampFactory interface used to create objects\n\t * of two specific types of light bulbs.\n\t * A LampWithRemainingDuration when it fails will still work for a limited number of switches (taken as input).\n\t * A LampWithTemporaneousFailure when it fails stops working for a limited number of switches (taken as input), then works again.\n\t * \n\t * By implementing two different implementations of Lamp for these two specializations, implement LampFactory with a constructor\n\t * empty. Solutions that factor *all* the common aspects of these two specializations into an abstract class will be preferred.\n\t * \n\t * Remove the comment from the tests below..\n\t */\n\t\n\t// Basic test on any light bulb initially off\n\tprivate void basicChecks(Lamp l){\n\t\tassertFalse(l.isOn());\n\t\tl.on();\n\t\tassertTrue(l.isOn());\n\t\tl.on();\n\t\tassertTrue(l.isOn());\n\t\tl.off();\n\t\tassertFalse(l.isOn());\n\t\tl.off();\n\t\tassertFalse(l.isOn());\n\t\tl.on();\n\t\tassertTrue(l.isOn());\n\t}\n\t\n\t// Test of the provided SimpleLamp\n\[email protected]\n\tpublic void testSimpleLamp() {\n\t\tLamp l = new SimpleLamp();\n\t\tbasicChecks(l);\n\t}\n\t\n\n\t// Test of a LampWithRemainingDuration\n\[email protected]\n\tpublic void testLampWithRemainingDuration() {\n\t\t// Using the factory, I create a light bulb that upon failure will only last 3 more switches\n\t\tLamp l = new LampFactoryImpl().createLampWithRemainingDuration(3);\n\t\t// basic checks\n\t\tbasicChecks(l);\n\t\tl.on();\n\t\tassertTrue(l.isOn());\n\t\t// I make the light bulb fail\n\t\tl.fail();\n\t\t// it was on and remains on\n\t\tassertTrue(l.isOn());\n\t\t// for 3 times I turn it off and on\n\t\tfor (int i=0; i<3; i++){\n\t\t\tl.off();\n\t\t\tassertFalse(l.isOn());\n\t\t\tl.on();\n\t\t\tl.on(); // The second switch in a row has no effect\n\t\t\tassertTrue(l.isOn());\n\t\t}\n\t\t// I turn it off\n\t\tl.off();\n\t\tassertFalse(l.isOn());\n\t\t// I turn it on, and this must cause the exception\n\t\ttry{\n\t\t\tl.on();\n\t\t\tfail(\"Can't switch on 3 switches after fail\");\n\t\t} catch (IllegalStateException e){\n\t\t} catch (Exception e){\n\t\t\tfail(\"Wrong exception thrown\");\n\t\t}\n\t\t// from here on the light bulb is off\n\t\tassertFalse(l.isOn());\n\t}\n\t\n\t// Test of a LampWithTemporaneousFailure\n\[email protected]\n\tpublic void testLampWithTemporaneousFailure() {\n\t\t// Using the factory, I create a light bulb that upon failure will remain inactive for 3 switches, then work fine\n\t\tLamp l = new LampFactoryImpl().createLampWithTemporaneousFailure(3);\n\t\t// basic checks\n\t\tbasicChecks(l);\n\t\tl.on();\n\t\tassertTrue(l.isOn());\n\t\t// I make the light bulb fail\n\t\tl.fail();\n\t\tassertFalse(l.isOn());\n\t\t// for 3 times I try to turn it on, but it fails giving the exception\n\t\tfor (int i=0; i<3; i++){\n\t\t\ttry{\n\t\t\t\tl.on();\n\t\t\t\tfail(\"Switch on during failure should raise an exception\");\n\t\t\t} catch (IllegalStateException e){\n\t\t\t} catch (Exception e){\n\t\t\t\tfail(\"Wrong exception thrown\");\n\t\t\t}\n\t\t\tassertFalse(l.isOn());\n\t\t}\n\t\t// from now on everything is ok\n\t\tl.on();\n\t\tassertTrue(l.isOn());\n\t\tl.off();\n\t\tbasicChecks(l);\n\t}\n}", "filename": "Test.java" }
2014
a05
[ { "content": "package ex2014.a05.sol1;\n\nimport java.util.*;\n\n\n\npublic interface Roulette {\n\t\n\t\n\tfinal static int SINGLE_BET_WIN_FACTOR = 36; \n\t\n\t\n\t\n\tvoid waitBets();\n\t\n\t\n\tvoid bet(String playerName, int betNumber, int quantity);\n\t\n\t\n\tint drawWinningNumber();\n\t\n\t\n\tvoid debugDrawing(int drawnNumber);\n\t\n\t\n\tMap<String,Integer> getWins();\n\t\n\t\n\tint getTotalBets();\n\t\n}", "filename": "Roulette.java" }, { "content": "package ex2014.a05.sol1;\n\n\n\npublic class Pair<X,Y> {\n\t\n\tprivate final X x;\n\tprivate final Y y;\n\t\n\tpublic Pair(X x, Y y) {\n\t\tsuper();\n\t\tthis.x = x;\n\t\tthis.y = y;\n\t}\n\n\tpublic X getX() {\n\t\treturn x;\n\t}\n\n\tpublic Y getY() {\n\t\treturn y;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = 1;\n\t\tresult = prime * result + ((x == null) ? 0 : x.hashCode());\n\t\tresult = prime * result + ((y == null) ? 0 : y.hashCode());\n\t\treturn result;\n\t}\n\n\t@SuppressWarnings(\"rawtypes\")\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (obj == null)\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tPair other = (Pair) obj;\n\t\tif (x == null) {\n\t\t\tif (other.x != null)\n\t\t\t\treturn false;\n\t\t} else if (!x.equals(other.x))\n\t\t\treturn false;\n\t\tif (y == null) {\n\t\t\tif (other.y != null)\n\t\t\t\treturn false;\n\t\t} else if (!y.equals(other.y))\n\t\t\treturn false;\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Pair [x=\" + x + \", y=\" + y + \"]\";\n\t}\n\t\n\t\n\n}", "filename": "Pair.java" } ]
[ { "content": "package ex2014.a05.sol1;\n\nimport java.util.*;\nimport java.util.stream.Collectors;\n\npublic class RouletteImpl implements Roulette{\n\t\n\tprivate boolean betting = false;\n\tprivate final Map<String,List<Pair<Integer,Integer>>> iBets = new HashMap<>();\n\tprivate int lastWin;\n\tprivate final Random rnd = new Random(); \n\n\t@Override\n\tpublic void waitBets() {\n\t\tthis.betting = true;\n\t\tthis.iBets.clear();\n\t}\n\t\n\t@Override\n\tpublic void bet(String playerName, int betNumber, int quantity) {\n\t\tif (!this.betting){\n\t\t\tthrow new IllegalStateException();\n\t\t}\n\t\tif (!this.iBets.containsKey(playerName)){\n\t\t\tthis.iBets.put(playerName,new ArrayList<>());\n\t\t}\n\t\tthis.iBets.get(playerName).add(new Pair<>(betNumber,quantity));\n\t}\n\n\t@Override\n\tpublic int drawWinningNumber() {\n\t\tint d = this.rnd.nextInt(37);\n\t\tthis.debugDrawing(d);\n\t\treturn d;\n\t}\n\t\n\t@Override\n\tpublic void debugDrawing(int drawnNumber) {\n\t\tif (!this.betting){\n\t\t\tthrow new IllegalStateException();\n\t\t}\n\t\tthis.betting = false;\n\t\tthis.lastWin = drawnNumber;\n\t}\n\n\t@Override\n\tpublic Map<String, Integer> getWins() {\n\t\treturn this.iBets.entrySet().stream()\n\t\t\t\t .collect(Collectors.toMap(\n\t\t\t\t \t\t(x)->x.getKey(),\n\t\t\t\t \t\t(x)->x.getValue().stream()\n\t\t\t\t \t\t .filter((p)->p.getX()==this.lastWin)\n\t\t\t\t \t\t .mapToInt(Pair::getY)\n\t\t\t\t \t\t .sum()*SINGLE_BET_WIN_FACTOR\n\t\t\t\t ));\n\t}\n\n\t\t@Override\n\tpublic int getTotalBets() {\n\t\treturn this.iBets.values().stream()\n\t\t\t\t .mapToInt((l)->l.stream()\n\t\t\t\t \t\t .mapToInt(Pair::getY)\n\t\t\t\t \t\t .sum())\n\t\t\t\t .sum();\n\t}\n\n}", "filename": "RouletteImpl.java" } ]
{ "components": { "imports": "package ex2014.a05.sol2;\n\nimport static org.junit.Assert.*;\n\nimport java.util.*;", "private_init": "\t/*\n\t * Implement the Roulette interface given through a RouletteImpl class with a constructor without arguments.\n\t * The comment of Roulette and the tests below are sufficient for understanding the exercise.\n\t * For the exercise to be positively evaluated, it is necessary that testOK1 passes\n\t * \n\t * Remove the comment from the tests below..\n\t */\n\n\t// Test of a \"spin\"", "test_functions": [ "\[email protected]\n\tpublic void testOK1() {\n\t\tRoulette roulette = new RouletteImpl();\n\t\troulette.waitBets(); // Bets open\n\t\tassertEquals(roulette.getTotalBets(), 0); \t// No bets so far\n\t\troulette.bet(\"Mirko\", 10, 1000);\t\t \t// Mirko bets 1000 euros on 10\n\t\troulette.bet(\"Mirko\", 36, 500);\t\t\t\t// Mirko bets 500 euros on 36\n\t\troulette.bet(\"Mirko\", 0, 100);\t\t\t\t// Mirko bets 100 euros on 0\n\t\troulette.bet(\"Carlo\", 10, 400);\t\t\t\t// Carlo bets 400 euros on 10\n\t\tassertEquals(roulette.getTotalBets(), 2000);\t// Bets for 2000 euros on the table\n\t\troulette.debugDrawing(10);\t\t\t\t\t// 10 comes out\n\t\tMap<String, Integer> map = roulette.getWins();\n\t\tSystem.out.println(map);\n\t\tassertEquals(map.size(), 2);\t\t\t\t// 2 winners\n\t\tassertEquals(map.get(\"Mirko\").intValue(), 1000 * 36);\t// Mirko wins 1000*36\n\t\tassertEquals(map.get(\"Carlo\").intValue(), 400 * 36);\t// Carlo wins 1000*36\n\t}", "\[email protected]\n\tpublic void testOK2() {\n\t\tRoulette roulette = new RouletteImpl();\n\t\tList<Integer> l = new ArrayList<>();\n\t\tfor (int i = 0; i < 1000; i++) {\t// 1000 plays\n\t\t\troulette.waitBets();\t\t// Bets open\n\t\t\tassertEquals(roulette.getTotalBets(), 0);\n\t\t\tint number = roulette.drawWinningNumber();\t// \"number\" comes out\n\t\t\tassertTrue(number >= 0);\t//..is within the limits\n\t\t\tassertTrue(number < 37);\n\t\t\tl.add(number);\t// I add it to l\n\t\t}", "\[email protected]\n\tpublic void testOK3() {\n\t\t// Same play as testOK1\n\t\tRoulette roulette = new RouletteImpl();\n\t\troulette.waitBets();\n\t\tassertEquals(roulette.getTotalBets(), 0);\n\t\troulette.bet(\"Mirko\", 10, 1000);\n\t\troulette.bet(\"Mirko\", 36, 500);\n\t\troulette.bet(\"Mirko\", 0, 100);\n\t\troulette.bet(\"Carlo\", 10, 400);\n\t\tassertEquals(roulette.getTotalBets(), 2000);\n\t\troulette.debugDrawing(10);\n\t\tMap<String, Integer> map = roulette.getWins();\n\t\tSystem.out.println(map);\n\t\tassertEquals(map.size(), 2);\n\t\tassertEquals(map.get(\"Mirko\").intValue(), 1000 * 36);\n\t\tassertEquals(map.get(\"Carlo\").intValue(), 400 * 36);\n\n\t\t// I make a new play'\n\t\troulette.waitBets();\n\t\tassertEquals(roulette.getTotalBets(), 0);\n\t\troulette.bet(\"Mirko\", 36, 500);\n\t\troulette.bet(\"Mirko\", 0, 100);\n\t\tassertEquals(roulette.getTotalBets(), 600);\n\t\troulette.debugDrawing(0);\n\t\tmap = roulette.getWins();\n\t\tSystem.out.println(map);\n\t\tassertEquals(map.size(), 1);\n\t\tassertEquals(map.get(\"Mirko\").intValue(), 100 * 36);\n\t}", "\[email protected]\n\tpublic void testFAIL() {\n\t\tRoulette roulette = new RouletteImpl();\n\t\troulette.waitBets();\n\t\troulette.drawWinningNumber();\n\t\ttry{\n\t\t\troulette.bet(\"Mirko\", 10, 1000);\n\t\t\tfail(\"Can't bet after drawing\");\n\t\t}" ] }, "content": "package ex2014.a05.sol1;\n\nimport static org.junit.Assert.*;\n\nimport java.util.*;\n\npublic class Test {\n\n\t/*\n\t * Implement the Roulette interface given through a RouletteImpl class with a constructor without arguments.\n\t * The comment of Roulette and the tests below are sufficient for understanding the exercise.\n\t * For the exercise to be positively evaluated, it is necessary that testOK1 passes\n\t * \n\t * Remove the comment from the tests below..\n\t */\n\n\t// Test of a \"spin\"\n\[email protected]\n\tpublic void testOK1() {\n\t\tRoulette roulette = new RouletteImpl();\n\t\troulette.waitBets(); // Bets open\n\t\tassertEquals(roulette.getTotalBets(), 0); \t// No bets so far\n\t\troulette.bet(\"Mirko\", 10, 1000);\t\t \t// Mirko bets 1000 euros on 10\n\t\troulette.bet(\"Mirko\", 36, 500);\t\t\t\t// Mirko bets 500 euros on 36\n\t\troulette.bet(\"Mirko\", 0, 100);\t\t\t\t// Mirko bets 100 euros on 0\n\t\troulette.bet(\"Carlo\", 10, 400);\t\t\t\t// Carlo bets 400 euros on 10\n\t\tassertEquals(roulette.getTotalBets(), 2000);\t// Bets for 2000 euros on the table\n\t\troulette.debugDrawing(10);\t\t\t\t\t// 10 comes out\n\t\tMap<String, Integer> map = roulette.getWins();\n\t\tSystem.out.println(map);\n\t\tassertEquals(map.size(), 2);\t\t\t\t// 2 winners\n\t\tassertEquals(map.get(\"Mirko\").intValue(), 1000 * 36);\t// Mirko wins 1000*36\n\t\tassertEquals(map.get(\"Carlo\").intValue(), 400 * 36);\t// Carlo wins 1000*36\n\t}\n\n\t// Test on the output of all possible numbers\n\[email protected]\n\tpublic void testOK2() {\n\t\tRoulette roulette = new RouletteImpl();\n\t\tList<Integer> l = new ArrayList<>();\n\t\tfor (int i = 0; i < 1000; i++) {\t// 1000 plays\n\t\t\troulette.waitBets();\t\t// Bets open\n\t\t\tassertEquals(roulette.getTotalBets(), 0);\n\t\t\tint number = roulette.drawWinningNumber();\t// \"number\" comes out\n\t\t\tassertTrue(number >= 0);\t//..is within the limits\n\t\t\tassertTrue(number < 37);\n\t\t\tl.add(number);\t// I add it to l\n\t\t}\n\t\tassertTrue(l.contains(0));\t// 0 came out sometime\n\t\tassertTrue(l.contains(36));\t// 36 came out sometime\n\t}\n\n\t// Test on the correct management of multiple spins\n\[email protected]\n\tpublic void testOK3() {\n\t\t// Same play as testOK1\n\t\tRoulette roulette = new RouletteImpl();\n\t\troulette.waitBets();\n\t\tassertEquals(roulette.getTotalBets(), 0);\n\t\troulette.bet(\"Mirko\", 10, 1000);\n\t\troulette.bet(\"Mirko\", 36, 500);\n\t\troulette.bet(\"Mirko\", 0, 100);\n\t\troulette.bet(\"Carlo\", 10, 400);\n\t\tassertEquals(roulette.getTotalBets(), 2000);\n\t\troulette.debugDrawing(10);\n\t\tMap<String, Integer> map = roulette.getWins();\n\t\tSystem.out.println(map);\n\t\tassertEquals(map.size(), 2);\n\t\tassertEquals(map.get(\"Mirko\").intValue(), 1000 * 36);\n\t\tassertEquals(map.get(\"Carlo\").intValue(), 400 * 36);\n\n\t\t// I make a new play'\n\t\troulette.waitBets();\n\t\tassertEquals(roulette.getTotalBets(), 0);\n\t\troulette.bet(\"Mirko\", 36, 500);\n\t\troulette.bet(\"Mirko\", 0, 100);\n\t\tassertEquals(roulette.getTotalBets(), 600);\n\t\troulette.debugDrawing(0);\n\t\tmap = roulette.getWins();\n\t\tSystem.out.println(map);\n\t\tassertEquals(map.size(), 1);\n\t\tassertEquals(map.get(\"Mirko\").intValue(), 100 * 36);\n\t}\n\n\t// Test on the correct management of exceptions\n\[email protected]\n\tpublic void testFAIL() {\n\t\tRoulette roulette = new RouletteImpl();\n\t\troulette.waitBets();\n\t\troulette.drawWinningNumber();\n\t\ttry{\n\t\t\troulette.bet(\"Mirko\", 10, 1000);\n\t\t\tfail(\"Can't bet after drawing\");\n\t\t} catch (IllegalStateException e){\n\t\t} catch (Exception e){\n\t\t\tfail(\"Wrong exception thrown\");\n\t\t}\n\t\troulette.waitBets();\n\t\troulette.drawWinningNumber();\n\t\ttry{\n\t\t\troulette.drawWinningNumber();\n\t\t\tfail(\"Can't draw twice without allowing new bets\");\n\t\t} catch (IllegalStateException e){\n\t\t} catch (Exception e){\n\t\t\tfail(\"Wrong exception thrown\");\n\t\t}\n\t}\n}", "filename": "Test.java" }
2014
a03b
[ { "content": "package ex2014.a03b.sol1;\n\nimport java.io.*;\nimport java.util.*;\n\n\n\npublic interface DiceStatistics{\n\n\t\t\n\tvoid setFileName(String fileName);\n\t\n\t\t\n\tvoid storeSeries(long size,int diceNumber) throws IOException;\n\t\n\t\t\n\tlong loadToLuckyCount() throws IOException;\n\t\n\t\t\n\tlong loadToOddCount() throws IOException;\n\t\n\t\t\n\tMap<Integer,Long> loadToMap() throws IOException;\n\t\n}", "filename": "DiceStatistics.java" } ]
[ { "content": "package ex2014.a03b.sol1;\n\nimport java.io.*;\nimport java.util.*;\nimport java.util.stream.*;\nimport java.util.function.*;\n\n/**\n */\n\npublic class DiceStatisticsImpl implements DiceStatistics{\n\t\n\tprivate Optional<String> fileName = Optional.empty();\n\n\t@Override\n\tpublic void setFileName(String fileName) {\n\t\tthis.fileName = Optional.of(fileName);\n\t}\n\n\t@Override\n\tpublic void storeSeries(long size,int diceNumber) throws IOException {\n\t\tRandom r = new Random();\n\t\tDataOutputStream dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(fileName.get())));\n\t\tdos.writeLong(size);\n\t\tfor (long l=0;l<size;l++){\n\t\t\tdos.writeInt(IntStream.range(0,diceNumber).map(i->r.nextInt(6)+1).sum());\n\t\t}\n\t\tdos.close();\n\t}\n\t\n\t@Override\n\tpublic long loadToLuckyCount() throws IOException {\n\t\treturn loadToMap().get((loadToMap().size()-1)*6/5);\n\t}\n\t\n\t@Override\n\tpublic Map<Integer, Long> loadToMap() throws IOException {\n\t\treturn genericLoad(\n\t\t\t\tnew HashMap<Integer,Long>(), \n\t\t\t\t(map,i) ->{\n\t\t\t\t\tmap.merge(i, 0L, (v,v2)->v+1);\n\t\t\t\t\treturn map;\n\t\t\t\t}\n\t\t);\n\t}\n\t\n\t@Override\n\tpublic long loadToOddCount() throws IOException {\n\t\treturn genericLoad(0L,(l,i)->l+i%2);\n\t}\n\t\t\n\tprivate <D> D genericLoad(D data, BiFunction<D,Integer,D> acc) throws IOException {\n\t\tDataInputStream dis = new DataInputStream(new BufferedInputStream(new FileInputStream(fileName.get())));\n\t\tlong size = dis.readLong();\n\t\tfor (long l=0;l<size;l++){\n\t\t\tdata = acc.apply(data,dis.readInt());\n\t\t}\n\t\tdis.close();\n\t\treturn data;\n\t}\n\t\n}", "filename": "DiceStatisticsImpl.java" } ]
{ "components": { "imports": "package ex2014.a03b.sol1;\n\nimport static org.junit.Assert.*;\n\nimport java.io.*;", "private_init": "\t/*\n\t * Implement the DiceStatistics interface given through a DiceStatisticsImpl class with a constructor without arguments.\n\t * This class implements a generator of a sequence of results of N dice rolls, to be written to a file one by one. For example, if\n\t * N = 3, and we decide to write 1000 results, we must generate three random integers between 1 and 6,\n\t * and sum them together (gives a number between 3 and 18) 1000 times. To generate the numbers, consider that the java.util.Random.nextInt method,\n\t * if called with argument 6, generates a number between 0 and 5 inclusive. The class also provides methods to reread the sequence\n\t * and extract various information (the number of lucky rolls -- i.e. with all dice giving 6, the number of rolls that give a final value\n\t * odd, and a map that assigns to each result the number of times it was obtained).\n\t * The comment to the DiceStatistics code, and the test method below constitute an additional explanation of the\n\t * problem.\n\t * \n\t * IMPORTANT: 5 points in this exercise will be awarded to those who can build a high-quality solution,\n\t * in particular regarding the absence of any code repetition, using \"well-designed\" code, i.e. choosing carefully\n\t * the pattern to use.\n */", "test_functions": [ "\[email protected]\n\tpublic void testOK() throws IOException{\n\t\tString filename = System.getProperty(\"user.home\")+System.getProperty(\"file.separator\")+\"stat.dat\";\n\t\tSystem.out.println(\"Using file: \"+filename);\n\t\tSystem.out.println();\n\t\t\n\t\tDiceStatistics ds = new DiceStatisticsImpl();\n\t\tds.setFileName(filename);\n\t\t// Generates a sequence of 1000 results of 2 dice rolls\n\t\tlong dim;\n\t\tdim = 1000;\n\t\tds.storeSeries(dim,2); // 1000 rolls of 2 dice\n\t\tSystem.out.println(\"Working with dim \"+dim+\" and 2 dice\");\n\t\t// Gets various information and prints it to the screen..\n\t\tSystem.out.println(\"Odd: \"+ds.loadToOddCount()); // almost 500\n\t\tSystem.out.println(\"Lucky: \"+ds.loadToLuckyCount()); // about 30.\n\t\tSystem.out.println(\"Map(3): \"+ds.loadToMap()); // more or less {2=29, 3=47, 4=87, 5=122, 6=141, 7=166, 8=140, 9=109, 10=81, 11=43, 12=24}" ] }, "content": "package ex2014.a03b.sol1;\n\nimport static org.junit.Assert.*;\n\nimport java.io.*;\n\npublic class Test {\n\t\n\t/*\n\t * Implement the DiceStatistics interface given through a DiceStatisticsImpl class with a constructor without arguments.\n\t * This class implements a generator of a sequence of results of N dice rolls, to be written to a file one by one. For example, if\n\t * N = 3, and we decide to write 1000 results, we must generate three random integers between 1 and 6,\n\t * and sum them together (gives a number between 3 and 18) 1000 times. To generate the numbers, consider that the java.util.Random.nextInt method,\n\t * if called with argument 6, generates a number between 0 and 5 inclusive. The class also provides methods to reread the sequence\n\t * and extract various information (the number of lucky rolls -- i.e. with all dice giving 6, the number of rolls that give a final value\n\t * odd, and a map that assigns to each result the number of times it was obtained).\n\t * The comment to the DiceStatistics code, and the test method below constitute an additional explanation of the\n\t * problem.\n\t * \n\t * IMPORTANT: 5 points in this exercise will be awarded to those who can build a high-quality solution,\n\t * in particular regarding the absence of any code repetition, using \"well-designed\" code, i.e. choosing carefully\n\t * the pattern to use.\n */\n\n\[email protected]\n\tpublic void testOK() throws IOException{\n\t\tString filename = System.getProperty(\"user.home\")+System.getProperty(\"file.separator\")+\"stat.dat\";\n\t\tSystem.out.println(\"Using file: \"+filename);\n\t\tSystem.out.println();\n\t\t\n\t\tDiceStatistics ds = new DiceStatisticsImpl();\n\t\tds.setFileName(filename);\n\t\t// Generates a sequence of 1000 results of 2 dice rolls\n\t\tlong dim;\n\t\tdim = 1000;\n\t\tds.storeSeries(dim,2); // 1000 rolls of 2 dice\n\t\tSystem.out.println(\"Working with dim \"+dim+\" and 2 dice\");\n\t\t// Gets various information and prints it to the screen..\n\t\tSystem.out.println(\"Odd: \"+ds.loadToOddCount()); // almost 500\n\t\tSystem.out.println(\"Lucky: \"+ds.loadToLuckyCount()); // about 30.\n\t\tSystem.out.println(\"Map(3): \"+ds.loadToMap()); // more or less {2=29, 3=47, 4=87, 5=122, 6=141, 7=166, 8=140, 9=109, 10=81, 11=43, 12=24}\n\t\tSystem.out.println();\n\t\t\n\t\t// Same thing with a new series of 100000 results of 3 dice rolls\n\t\tdim = 100000;\n\t\tds.storeSeries(dim,3); // 100000 rolls of 3 dice\n\t\tSystem.out.println(\"Working with dim \"+dim+\" and 3 dice\");\n\t\tSystem.out.println(\"Odd: \"+ds.loadToOddCount()); // almost 50000\n\t\tSystem.out.println(\"Lucky: \"+ds.loadToLuckyCount()); // about 462.\n\t\tSystem.out.println(\"Map(3): \"+ds.loadToMap()); // more or less {3=450, 4=1317, 5=2798, 6=4623, ..., 17=1418, 18=441}\n\n\t\tSystem.out.println();\n\t\t\n\t\t// Test considering acceptable error margins\n\t\tassertTrue(ds.loadToOddCount()>49000 && ds.loadToOddCount()<51000);\n\t\tassertTrue(ds.loadToLuckyCount()>400 && ds.loadToLuckyCount()<500);\n\t\tassertEquals(ds.loadToMap().size(),16);\n\t\tassertTrue(ds.loadToMap().get(3)>400 && ds.loadToMap().get(3)<500);\n\t\tassertTrue(ds.loadToMap().get(18)>400 && ds.loadToMap().get(18)<500);\n\t\tassertTrue(ds.loadToMap().get(10)>12000 && ds.loadToMap().get(10)<13000);\n\t\t\n\t\t\n\t}\n}", "filename": "Test.java" }
2014
a01b
[ { "content": "package ex2014.a01b.sol1;\n\n\n\npublic interface Aggregator<X> {\n\t\n\tX aggregate(X one, X two);\n}", "filename": "Aggregator.java" }, { "content": "package ex2014.a01b.sol1;\n\n\n\npublic interface ProgressiveAcceptor<X> {\n\t\n\t\n\t\n\tvoid setProgressiveFilter(ProgressiveFilter<X> filter);\n\t\n\t\n\tvoid setAggregator(Aggregator<X> aggregator);\n\n\t\n\tvoid setSize(int size);\n\t\n\t\n\tboolean accept(int pos, X elem);\n\t\n\t\n\tX aggregateAll();\n\n}", "filename": "ProgressiveAcceptor.java" }, { "content": "package ex2014.a01b.sol1;\n\n\npublic interface ProgressiveFilter<X> {\n\n\tboolean isNextOK(X previous, X next);\n}", "filename": "ProgressiveFilter.java" } ]
[ { "content": "package ex2014.a01b.sol1;\n\nimport java.util.*;\n\npublic class ProgressiveAcceptorImpl<X> implements ProgressiveAcceptor<X> {\n\n\tprivate ProgressiveFilter<X> filter;\n\tprivate Aggregator<X> aggregator;\n\tprivate int size = -1;\n\tprivate final List<X> elements = new LinkedList<X>();\n\n\tprivate void checkInitialization() {\n\t\tif (this.filter == null || this.aggregator == null || this.size < 0) {\n\t\t\tthrow new IllegalStateException();\n\t\t}\n\t}\n\n\t@Override\n\tpublic void setProgressiveFilter(ProgressiveFilter<X> filter) {\n\t\tthis.filter = Objects.requireNonNull(filter);\n\t}\n\n\t@Override\n\tpublic void setAggregator(Aggregator<X> aggregator) {\n\t\tthis.aggregator = Objects.requireNonNull(aggregator);\n\t}\n\n\t@Override\n\tpublic void setSize(int size) {\n\t\tif (size < 0) {\n\t\t\tthrow new IllegalArgumentException();\n\t\t}\n\t\tthis.size = size;\n\t}\n\n\t@Override\n\tpublic boolean accept(int pos, X elem) {\n\t\tthis.checkInitialization();\n\t\tif (pos > this.elements.size()) {\n\t\t\treturn false;\n\t\t}\n\t\tif (pos > 0 && !this.filter.isNextOK(this.elements.get(pos - 1), elem)) {\n\t\t\treturn false;\n\t\t}\n\t\tif (pos < this.elements.size()) {\n\t\t\tthis.elements.set(pos, elem);\n\t\t} else {\n\t\t\tthis.elements.add(elem);\n\t\t}\n\t\tListIterator<X> it = this.elements.listIterator(pos + 1);\n\t\twhile (it.hasNext()) {\n\t\t\tit.next();\n\t\t\tit.remove();\n\t\t}\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic X aggregateAll() {\n\t\tthis.checkInitialization();\n\t\tIterator<X> it = this.elements.iterator();\n\t\tX x = it.next();\n\t\twhile (it.hasNext()) {\n\t\t\tx = this.aggregator.aggregate(x, it.next());\n\t\t}\n\t\treturn x;\n\n\t}\n\n}", "filename": "ProgressiveAcceptorImpl.java" } ]
{ "components": { "imports": "package ex2014.a01b.sol1;\n\nimport static org.junit.Assert.*;", "private_init": "\t/*\n\t * Implement the ProgressiveAcceptor interface given through a\n\t * ProgressiveAcceptorImpl class with a constructor without arguments.\n\t * The comment to the ProgressiveAcceptor code, and the three test methods here\n\t * below constitute the necessary explanation of the\n\t * problem.\n\t */", "test_functions": [ "\[email protected]\n\tpublic void testOK() {\n\t\tProgressiveAcceptor<Double> pa = new ProgressiveAcceptorImpl<>();\n\t\t// I will aggregate with \"+\", i.e., I will sum\n\t\tpa.setAggregator(new Aggregator<Double>() {\n\n\t\t\t@Override\n\t\t\tpublic Double aggregate(Double one, Double two) {\n\t\t\t\t// TODO Auto-generated method stub\n\t\t\t\treturn one + two;\n\t\t\t}", "\[email protected]\n\tpublic void testAnotherOK() {\n\t\tProgressiveAcceptor<String> pa = new ProgressiveAcceptorImpl<>();\n\t\t// I aggregate by concatenating the strings with a comma in between\n\t\tpa.setAggregator(new Aggregator<String>() {\n\n\t\t\t@Override\n\t\t\tpublic String aggregate(String one, String two) {\n\t\t\t\treturn one + \",\" + two;\n\t\t\t}", "\[email protected]\n\tpublic void testExceptions() {\n\t\tProgressiveAcceptor<Double> pa = new ProgressiveAcceptorImpl<>();\n\t\t// I cannot specify a null aggregator! (same thing for the filter)\n\t\ttry {\n\t\t\tpa.setAggregator(null);\n\t\t}" ] }, "content": "package ex2014.a01b.sol1;\n\nimport static org.junit.Assert.*;\n\npublic class Test {\n\n\t/*\n\t * Implement the ProgressiveAcceptor interface given through a\n\t * ProgressiveAcceptorImpl class with a constructor without arguments.\n\t * The comment to the ProgressiveAcceptor code, and the three test methods here\n\t * below constitute the necessary explanation of the\n\t * problem.\n\t */\n\n\[email protected]\n\tpublic void testOK() {\n\t\tProgressiveAcceptor<Double> pa = new ProgressiveAcceptorImpl<>();\n\t\t// I will aggregate with \"+\", i.e., I will sum\n\t\tpa.setAggregator(new Aggregator<Double>() {\n\n\t\t\t@Override\n\t\t\tpublic Double aggregate(Double one, Double two) {\n\t\t\t\t// TODO Auto-generated method stub\n\t\t\t\treturn one + two;\n\t\t\t}\n\n\t\t});\n\t\t// I will accept elements that are gradually increasing, and therefore the sequence will be ordered in\n\t\t// increasing order\n\t\tpa.setProgressiveFilter(new ProgressiveFilter<Double>() {\n\n\t\t\t@Override\n\t\t\tpublic boolean isNextOK(Double previous, Double next) {\n\t\t\t\treturn next > previous;\n\t\t\t}\n\n\t\t});\n\t\t// I accept a sequence with a maximum of 5 elements\n\t\tpa.setSize(5);\n\t\tassertTrue(pa.accept(0, 10.0));\n\t\t// so far I have inserted 10\n\t\tassertEquals(pa.aggregateAll(), new Double(10.0));\n\t\tassertTrue(pa.accept(1, 20.0));\n\t\tassertTrue(pa.accept(2, 30.0));\n\t\t// so far I have inserted 10,20,30\n\t\tassertEquals(pa.aggregateAll(), new Double(60.0)); // 10+20+30\n\t\tassertTrue(pa.accept(3, 40.0));\n\t\tassertTrue(pa.accept(4, 50.0));\n\t\t// so far I have inserted 10,20,30,40,50\n\t\tassertEquals(pa.aggregateAll(), new Double(150.0)); // 10+20+30+40+50\n\t\tassertTrue(pa.accept(2, 31.0));\n\t\t// having reinserted in the middle, now I have 10,20,31\n\t\tassertEquals(pa.aggregateAll(), new Double(61.0)); // 10+20+31\n\t\tassertTrue(pa.accept(3, 41.0));\n\t\tassertFalse(pa.accept(4, 30.0)); // not accepted, it is not greater than the previous one\n\t\tassertFalse(pa.accept(5, 50.0)); // not accepted, it is out of order\n\t\tassertTrue(pa.accept(4, 51.0));\n\t\t// so far I have inserted 10,20,31,41,51\n\t\tassertEquals(pa.aggregateAll(), new Double(153.0));\n\t\tassertTrue(pa.accept(0, 0.0));\n\t\t// having reinserted at the beginning, now I only have 0\n\t\tassertEquals(pa.aggregateAll(), new Double(0.0));\n\t}\n\n\[email protected]\n\tpublic void testAnotherOK() {\n\t\tProgressiveAcceptor<String> pa = new ProgressiveAcceptorImpl<>();\n\t\t// I aggregate by concatenating the strings with a comma in between\n\t\tpa.setAggregator(new Aggregator<String>() {\n\n\t\t\t@Override\n\t\t\tpublic String aggregate(String one, String two) {\n\t\t\t\treturn one + \",\" + two;\n\t\t\t}\n\t\t});\n\t\t// I only accept non-empty strings (there is no correlation with the string\n\t\t// previous)\n\t\tpa.setProgressiveFilter(new ProgressiveFilter<String>() {\n\n\t\t\t@Override\n\t\t\tpublic boolean isNextOK(String previous, String next) {\n\t\t\t\treturn next.length() > 0;\n\t\t\t}\n\t\t});\n\t\tpa.setSize(5);\n\t\tassertTrue(pa.accept(0, \"ciao\"));\n\t\tassertTrue(pa.accept(1, \"ciao\"));\n\t\tassertFalse(pa.accept(2, \"\"));\n\t\tassertEquals(pa.aggregateAll(), \"ciao,ciao\");\n\t}\n\n\[email protected]\n\tpublic void testExceptions() {\n\t\tProgressiveAcceptor<Double> pa = new ProgressiveAcceptorImpl<>();\n\t\t// I cannot specify a null aggregator! (same thing for the filter)\n\t\ttry {\n\t\t\tpa.setAggregator(null);\n\t\t} catch (NullPointerException e) {\n\t\t} catch (Exception e) { // this catch intercepts the case of exceptions thrown but of the wrong type\n\t\t\tfail(\"Wrong exception thrown\");\n\t\t}\n\t\tpa.setAggregator(new Aggregator<Double>() {\n\n\t\t\t@Override\n\t\t\tpublic Double aggregate(Double one, Double two) {\n\t\t\t\treturn one + two;\n\t\t\t}\n\n\t\t});\n\t\t// I cannot start accepting if I don't have the filter and the size\n\t\ttry {\n\t\t\tpa.accept(0, 10.0);\n\t\t\tfail(\"Not correctly initialized\");\n\t\t} catch (IllegalStateException e) {\n\t\t} catch (Exception e) {\n\t\t\tfail(\"Wrong exception thrown\");\n\t\t}\n\t\tpa.setProgressiveFilter(new ProgressiveFilter<Double>() {\n\n\t\t\t@Override\n\t\t\tpublic boolean isNextOK(Double previous, Double next) {\n\t\t\t\treturn next > previous;\n\t\t\t}\n\n\t\t});\n\t\ttry {\n\t\t\tpa.setSize(-1);\n\t\t\tfail(\"Not negative!\");\n\t\t} catch (IllegalArgumentException e) {\n\t\t} catch (Exception e) {\n\t\t\tfail(\"Wrong exception thrown\");\n\t\t}\n\t}\n}", "filename": "Test.java" }
2014
a01
[ { "content": "package ex2014.a01.sol1;\n\nimport java.util.*;\n\n\n\npublic interface FibonacciAcceptor {\n\n\t\n\tvoid reset(String sequenceName);\n\t\n\t\n\tboolean consumeNext(long l);\n\t\n\t\n\tList<Long> getCurrentSequence();\n\t\n\t\n\tMap<String,List<Long>> getAllSequences();\n}", "filename": "FibonacciAcceptor.java" } ]
[ { "content": "package ex2014.a01.sol1;\n\nimport java.util.*;\nimport java.util.stream.*;\n\n/**\n * Qualche nota su questa soluzione\n * - è solo una delle possibili\n * - usa alcune delle funzionalità di Java 8, come gli Optional e gli Stream, ma questo non era necessario\n * - può essere considerata come soluzione allo \"stato dell'arte\", e quindi approfondibile dallo studente \n */\n\npublic class FibonacciAcceptorImpl implements FibonacciAcceptor {\n\t\n\tprivate final Map<String,List<Long>> map = new HashMap<>();\n\tprivate Optional<List<Long>> currentSequence = Optional.empty(); \n\t\n\t@Override\n\tpublic void reset(final String sequenceName) {\n\t\tif (map.containsKey(sequenceName)){\n\t\t\tthrow new IllegalArgumentException();\n\t\t}\n\t\tthis.currentSequence = Optional.of(new LinkedList<>()); \n\t\tmap.put(sequenceName, this.currentSequence.get());\n\t}\n\n\t@Override\n\tpublic boolean consumeNext(final long l) {\n\t\tif (this.currentSequence.orElseThrow(()->new IllegalStateException()).size()<2 || \n\t\t\tl == this.currentSequence.get().get(this.currentSequence.get().size()-1) +\n\t\t\t\t this.currentSequence.get().get(this.currentSequence.get().size()-2)){\n\t\t\tthis.currentSequence.get().add(l);\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic List<Long> getCurrentSequence() {\n\t\treturn defend(this.currentSequence.orElseThrow(()->new IllegalStateException()));\n\t}\n\n\t@Override\n\tpublic Map<String, List<Long>> getAllSequences() {\n\t\t// note we defend the map but also each list in it\n\t\treturn this.map.entrySet().stream().collect(Collectors.toMap(e->e.getKey(),e->defend(e.getValue())));\n\t}\n\t\n\t// Local implementation of \"defensive copy\" for a List<X>\n\tprivate static <X> List<X> defend(List<X> list){\n\t\treturn new LinkedList<>(list);\n\t}\n\n}", "filename": "FibonacciAcceptorImpl.java" } ]
{ "components": { "imports": "package ex2014.a01.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;", "private_init": "\t/*\n\t * Implement the FibonacciAcceptor interface given through a\n\t * FibonacciAcceptorImpl class with a constructor without arguments.\n\t * The comment on the FibonacciAcceptor code, and the two test methods below\n\t * constitute the necessary explanation of the\n\t * problem.\n\t */", "test_functions": [ "\[email protected]\n\tpublic void testOK() {\n\t\t// Create the object\n\t\tFibonacciAcceptor fib = new FibonacciAcceptorImpl();\n\t\t// Perform the first reset, creating the sequence named \"Standard\"\n\t\tassertEquals(fib.getAllSequences().size(), 0);\n\t\tfib.reset(\"Standard\");\n\t\tassertEquals(fib.getAllSequences().size(), 1);\n\t\t// Insert the Fibonacci sequence from 1,1, up to 13..\n\t\tassertTrue(fib.consumeNext(1));\n\t\tassertTrue(fib.consumeNext(1));\n\t\tassertTrue(fib.consumeNext(2));\n\t\tassertTrue(fib.consumeNext(3));\n\t\tassertTrue(fib.consumeNext(5));\n\t\tassertTrue(fib.consumeNext(8));\n\t\t// Test the current sequence\n\t\tassertEquals(fib.getCurrentSequence(), Arrays.asList(1l, 1l, 2l, 3l, 5l, 8l));\n\t\tassertTrue(fib.consumeNext(13));\n\t\t// Test the current sequence, in two ways\n\t\tassertEquals(fib.getCurrentSequence(), Arrays.asList(1l, 1l, 2l, 3l, 5l, 8l, 13l));\n\t\tassertEquals(fib.getAllSequences().get(\"Standard\"), Arrays.asList(1l, 1l, 2l, 3l, 5l, 8l, 13l));\n\t\t// Repeat with a new sequence, this time from 10,11\n\t\tfib.reset(\"From 10 and 11\");\n\t\tassertTrue(fib.consumeNext(10));\n\t\tassertTrue(fib.consumeNext(11));\n\t\tassertTrue(fib.consumeNext(21));\n\t\tassertTrue(fib.consumeNext(32));\n\t\tassertEquals(fib.getCurrentSequence(), Arrays.asList(10l, 11l, 21l, 32l));\n\t\tassertEquals(fib.getAllSequences().get(\"From 10 and 11\"), Arrays.asList(10l, 11l, 21l, 32l));\n\t\t// Repeat with a new sequence, this time again from 1,1\n\t\tfib.reset(\"Another Standard\");\n\t\tassertTrue(fib.consumeNext(1));\n\t\tassertTrue(fib.consumeNext(1));\n\t\tassertTrue(fib.consumeNext(2));\n\t\t// An incorrect number is intercepted and ignored\n\t\tassertFalse(fib.consumeNext(100));\n\t\tassertTrue(fib.consumeNext(3));\n\t\tassertTrue(fib.consumeNext(5));\n\t\tassertEquals(fib.getCurrentSequence(), Arrays.asList(1l, 1l, 2l, 3l, 5l));\n\t\tassertEquals(fib.getAllSequences().get(\"Another Standard\"), Arrays.asList(1l, 1l, 2l, 3l, 5l));\n\t\t// Do some reads on the current sequences\n\t\tassertEquals(fib.getAllSequences().size(), 3);\n\t\tassertTrue(fib.getAllSequences().containsKey(\"Standard\"));\n\t\tassertEquals(fib.getAllSequences().get(\"Standard\"), Arrays.asList(1l, 1l, 2l, 3l, 5l, 8l, 13l));\n\t}", "\[email protected]\n\tpublic void testExceptions() {\n\t\t// Self-explanatory exception tests\n\t\tFibonacciAcceptor fib = new FibonacciAcceptorImpl();\n\t\ttry {\n\t\t\tfib.consumeNext(1);\n\t\t\tfail(\"Should reset first!\");\n\t\t}" ] }, "content": "package ex2014.a01.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;\n\npublic class Test {\n\n\t/*\n\t * Implement the FibonacciAcceptor interface given through a\n\t * FibonacciAcceptorImpl class with a constructor without arguments.\n\t * The comment on the FibonacciAcceptor code, and the two test methods below\n\t * constitute the necessary explanation of the\n\t * problem.\n\t */\n\n\[email protected]\n\tpublic void testOK() {\n\t\t// Create the object\n\t\tFibonacciAcceptor fib = new FibonacciAcceptorImpl();\n\t\t// Perform the first reset, creating the sequence named \"Standard\"\n\t\tassertEquals(fib.getAllSequences().size(), 0);\n\t\tfib.reset(\"Standard\");\n\t\tassertEquals(fib.getAllSequences().size(), 1);\n\t\t// Insert the Fibonacci sequence from 1,1, up to 13..\n\t\tassertTrue(fib.consumeNext(1));\n\t\tassertTrue(fib.consumeNext(1));\n\t\tassertTrue(fib.consumeNext(2));\n\t\tassertTrue(fib.consumeNext(3));\n\t\tassertTrue(fib.consumeNext(5));\n\t\tassertTrue(fib.consumeNext(8));\n\t\t// Test the current sequence\n\t\tassertEquals(fib.getCurrentSequence(), Arrays.asList(1l, 1l, 2l, 3l, 5l, 8l));\n\t\tassertTrue(fib.consumeNext(13));\n\t\t// Test the current sequence, in two ways\n\t\tassertEquals(fib.getCurrentSequence(), Arrays.asList(1l, 1l, 2l, 3l, 5l, 8l, 13l));\n\t\tassertEquals(fib.getAllSequences().get(\"Standard\"), Arrays.asList(1l, 1l, 2l, 3l, 5l, 8l, 13l));\n\t\t// Repeat with a new sequence, this time from 10,11\n\t\tfib.reset(\"From 10 and 11\");\n\t\tassertTrue(fib.consumeNext(10));\n\t\tassertTrue(fib.consumeNext(11));\n\t\tassertTrue(fib.consumeNext(21));\n\t\tassertTrue(fib.consumeNext(32));\n\t\tassertEquals(fib.getCurrentSequence(), Arrays.asList(10l, 11l, 21l, 32l));\n\t\tassertEquals(fib.getAllSequences().get(\"From 10 and 11\"), Arrays.asList(10l, 11l, 21l, 32l));\n\t\t// Repeat with a new sequence, this time again from 1,1\n\t\tfib.reset(\"Another Standard\");\n\t\tassertTrue(fib.consumeNext(1));\n\t\tassertTrue(fib.consumeNext(1));\n\t\tassertTrue(fib.consumeNext(2));\n\t\t// An incorrect number is intercepted and ignored\n\t\tassertFalse(fib.consumeNext(100));\n\t\tassertTrue(fib.consumeNext(3));\n\t\tassertTrue(fib.consumeNext(5));\n\t\tassertEquals(fib.getCurrentSequence(), Arrays.asList(1l, 1l, 2l, 3l, 5l));\n\t\tassertEquals(fib.getAllSequences().get(\"Another Standard\"), Arrays.asList(1l, 1l, 2l, 3l, 5l));\n\t\t// Do some reads on the current sequences\n\t\tassertEquals(fib.getAllSequences().size(), 3);\n\t\tassertTrue(fib.getAllSequences().containsKey(\"Standard\"));\n\t\tassertEquals(fib.getAllSequences().get(\"Standard\"), Arrays.asList(1l, 1l, 2l, 3l, 5l, 8l, 13l));\n\t}\n\n\[email protected]\n\tpublic void testExceptions() {\n\t\t// Self-explanatory exception tests\n\t\tFibonacciAcceptor fib = new FibonacciAcceptorImpl();\n\t\ttry {\n\t\t\tfib.consumeNext(1);\n\t\t\tfail(\"Should reset first!\");\n\t\t} catch (IllegalStateException e) {\n\t\t} catch (Exception e) {\n\t\t\tfail(\"Wrong exception thrown\");\n\t\t}\n\t\ttry {\n\t\t\tfib.getCurrentSequence();\n\t\t\tfail(\"Should reset first!\");\n\t\t} catch (IllegalStateException e) {\n\t\t} catch (Exception e) {\n\t\t\tfail(\"Wrong exception thrown\");\n\t\t}\n\t\tfib.reset(\"a\");\n\t\ttry {\n\t\t\tfib.reset(\"a\");\n\t\t\tfail(\"Cannot create a sequence with existing name!\");\n\t\t} catch (IllegalArgumentException e) {\n\t\t} catch (Exception e) {\n\t\t\tfail(\"Wrong exception thrown\");\n\t\t}\n\t}\n}", "filename": "Test.java" }
2015
a04
[ { "content": "package ex2015.a04.sol1;\n\nimport java.util.List;\n\n\npublic interface Tree<X> {\n \n \n int size();\n \n \n X getRoot();\n \n \n List<Tree<X>> getSons();\n \n \n boolean contains(X x);\n \n \n Tree<X> getSubTree(X node);\n \n \n List<X> toList();\n}", "filename": "Tree.java" }, { "content": "package ex2015.a04.sol1;\n\nimport java.util.List;\n\n\npublic interface TreeFactory<X> {\n \n \n \n Tree<X> emptyTree();\n \n \n Tree<X> consTree(X root, List<Tree<X>> sons);\n\n}", "filename": "TreeFactory.java" }, { "content": "package ex2015.a04.sol1;\n\n\npublic final class Pair<X, Y> {\n\n private X x;\n private Y y;\n\n \n public Pair(final X x, final Y y) {\n super();\n this.x = x;\n this.y = y;\n }\n\n \n public X getX() {\n return x;\n }\n\n \n public Y getY() {\n return y;\n }\n \n \n public void setX(X x) {\n this.x = x;\n }\n\n \n public void setY(Y y) {\n this.y = y;\n }\n \n\n @Override\n public int hashCode() {\n return x.hashCode() ^ y.hashCode();\n }\n\n @Override\n public boolean equals(final Object obj) {\n return obj instanceof Pair ? x.equals(((Pair<?, ?>) obj).x) && y.equals(((Pair<?, ?>) obj).y) : false;\n }\n\n @Override\n public String toString() {\n return \"<\" + x + \", \" + y + \">\";\n }\n\n}", "filename": "Pair.java" } ]
[ { "content": "package ex2015.a04.sol1;\n\nimport java.util.*;\nimport java.util.function.Supplier;\n\npublic class TreeFactoryImpl<X> implements TreeFactory<X> {\n\n @Override\n public Tree<X> emptyTree() {\n return new EmptyTree<>();\n }\n\n @Override\n public Tree<X> consTree(X root, List<Tree<X>> sons) {\n return new TreeImpl<>(root, sons == null ? Collections.emptyList() : new ArrayList<>(sons));\n }\n \n private static class EmptyTree<X> implements Tree<X>{\n\n private static Supplier<RuntimeException> EXC_EMPTY = ()->new IllegalStateException();\n \n @Override\n public int size() {\n return 0; \n }\n\n @Override\n public X getRoot() {\n throw EXC_EMPTY.get();\n }\n\n @Override\n public List<Tree<X>> getSons() {\n throw EXC_EMPTY.get();\n }\n\n @Override\n public boolean contains(X x) {\n return false;\n }\n \n @Override\n public Tree<X> getSubTree(X node){\n throw EXC_EMPTY.get();\n }\n\n @Override\n public List<X> toList() {\n return Collections.emptyList();\n }\n \n }\n\n}", "filename": "TreeFactoryImpl.java" }, { "content": "package ex2015.a04.sol1;\n\nimport java.util.*;\nimport java.util.function.Supplier;\n\npublic class TreeImpl<X> implements Tree<X>{\n \n private X root;\n private List<Tree<X>> sons;\n \n public TreeImpl(X root, List<Tree<X>> sons){\n this.root = root;\n this.sons = sons;\n Objects.requireNonNull(sons);\n }\n \n @Override\n public int size() {\n return 1 + sons.stream().mapToInt(Tree::size).sum(); \n }\n\n @Override\n public X getRoot() {\n return this.root;\n }\n\n @Override\n public List<Tree<X>> getSons() {\n return new ArrayList<>(this.sons);\n }\n\n @Override\n public boolean contains(X x) {\n return this.root.equals(x) || this.sons.stream().anyMatch(t -> t.contains(x));\n }\n \n @Override\n public Tree<X> getSubTree(X node){\n if (this.root.equals(node)){\n return this;\n }\n if (this.sons.isEmpty()){\n return null;\n }\n return this.sons.stream().map(t->t.getSubTree(node)).filter(t->t!=null).findAny().orElse(null);\n }\n\n @Override\n public List<X> toList() {\n final List<X> l = new ArrayList<>();\n l.add(this.getRoot());\n this.getSons().forEach(l2 -> l.addAll(l2.toList()));\n return l;\n }\n}", "filename": "TreeImpl.java" } ]
{ "components": { "imports": "package ex2015.a04.sol1;\n\nimport static org.junit.Assert.*;\n\nimport java.util.*;\n\n/**\n * Implement the TreeFactory interface with a TreeFactoryImpl class with an empty constructor,\n * which implements a Factory for immutable trees, which adhere to the generic Tree interface provided\n * (for example, do it by also constructing a TreeImpl class that implements Tree).\n * The factory has a method to generate empty trees, and one to generate a tree given\n * a root and a list of children. Assume, without doing checks, that a tree does not\n * have repeated elements.\n *\n * Carefully observe the following test, which together with the comments of the given interfaces\n * constitutes the definition of the problem to be solved.\n *\n * The second test is considered optional for the purpose of being able to correct\n * the exercise -- even if it contributes to the definition of the score.\n *\n * Remove the comment from the test code.\n */", "private_init": "\t", "test_functions": [ "\[email protected]\n public void testBasic() {\n TreeFactory<String> tf = new TreeFactoryImpl<>();\n // construction of three child trees\n // a with three children aa,ab,ac\n Tree<String> son1 = tf.consTree(\"a\",Arrays.asList(\n tf.consTree(\"aa\",null), tf.consTree(\"ab\",null), tf.consTree(\"ac\",null)\n ));\n // only the root b\n Tree<String> son2 = tf.consTree(\"b\",null);\n // c with three children ca,cb,cc, and cc in turn with children cca and ccb\n Tree<String> son3 = tf.consTree(\"c\",Arrays.asList(\n tf.consTree(\"ca\",null),\n tf.consTree(\"cb\",null),\n tf.consTree(\"cc\",Arrays.asList(\n tf.consTree(\"cca\",null),\n tf.consTree(\"ccb\",null)\n ))));\n // I construct a tree through the three child trees\n Tree<String> tree = tf.consTree(\"root\",Arrays.asList(son1,son2,son3));\n\n // test on size()\n assertEquals(son1.size(),4);\n assertEquals(son2.size(),1);\n assertEquals(son3.size(),6);\n assertEquals(tree.size(),12);\n\n // test on getRoot()\n assertEquals(son1.getRoot(),\"a\");\n assertEquals(son2.getRoot(),\"b\");\n assertEquals(son3.getRoot(),\"c\");\n assertEquals(tree.getRoot(),\"root\");\n\n // test on contains\n assertTrue(tree.contains(\"a\"));\n assertTrue(tree.contains(\"b\"));\n assertTrue(tree.contains(\"c\"));\n assertTrue(tree.contains(\"ccb\"));\n assertFalse(tree.contains(\"ccc\"));\n\n // test on toList.. note that the order is NOT relevant\n assertTrue(son1.toList().containsAll(Arrays.asList(\"a\",\"aa\",\"ab\",\"ac\")));\n assertEquals(son1.toList().size(),son1.size());\n assertTrue(son2.toList().containsAll(Arrays.asList(\"b\")));\n assertEquals(son2.toList().size(),son2.size());\n assertTrue(son3.toList().containsAll(Arrays.asList(\"c\",\"ca\",\"cb\",\"cc\",\"cca\",\"ccb\")));\n assertEquals(son3.toList().size(),son3.size());\n assertTrue(tree.toList().containsAll(Arrays.asList(\"c\",\"ca\",\"cb\",\"cc\",\"cca\",\"ccb\",\"b\",\"a\",\"aa\",\"ab\",\"ac\")));\n assertEquals(tree.toList().size(),tree.size());\n\n // test on getSons\n assertTrue(tree.getSons().get(0).toList().containsAll(Arrays.asList(\"a\",\"aa\",\"ab\",\"ac\")));\n assertTrue(tree.getSons().get(1).toList().containsAll(Arrays.asList(\"b\")));\n assertTrue(tree.getSons().get(2).toList().containsAll(Arrays.asList(\"c\",\"ca\",\"cb\",\"cc\",\"cca\",\"ccb\")));\n\n // test on getSubTree\n assertTrue(tree.getSubTree(\"a\").toList().containsAll(Arrays.asList(\"a\",\"aa\",\"ab\",\"ac\")));\n assertTrue(tree.getSubTree(\"b\").toList().containsAll(Arrays.asList(\"b\")));\n assertTrue(tree.getSubTree(\"c\").toList().containsAll(Arrays.asList(\"c\",\"ca\",\"cb\",\"cc\",\"cca\",\"ccb\")));\n assertTrue(tree.getSubTree(\"root\").toList().containsAll(Arrays.asList(\"c\",\"ca\",\"cb\",\"cc\",\"cca\",\"ccb\",\"b\",\"a\",\"aa\",\"ab\",\"ac\")));\n assertTrue(tree.getSubTree(\"cc\").toList().containsAll(Arrays.asList(\"cc\",\"cca\",\"ccb\")));\n }", "\[email protected]\n public void optionalTestEmpty() {\n // test on the case of an empty tree\n TreeFactory<String> tf = new TreeFactoryImpl<>();\n Tree<String> tree = tf.emptyTree();\n\n // size 0\n assertEquals(tree.size(),0);\n\n // you cannot access root\n try{\n tree.getRoot();\n fail(\"can't get root if emty\");\n }" ] }, "content": "package ex2015.a04.sol1;\n\nimport static org.junit.Assert.*;\n\nimport java.util.*;\n\n/**\n * Implement the TreeFactory interface with a TreeFactoryImpl class with an empty constructor,\n * which implements a Factory for immutable trees, which adhere to the generic Tree interface provided\n * (for example, do it by also constructing a TreeImpl class that implements Tree).\n * The factory has a method to generate empty trees, and one to generate a tree given\n * a root and a list of children. Assume, without doing checks, that a tree does not\n * have repeated elements.\n *\n * Carefully observe the following test, which together with the comments of the given interfaces\n * constitutes the definition of the problem to be solved.\n *\n * The second test is considered optional for the purpose of being able to correct\n * the exercise -- even if it contributes to the definition of the score.\n *\n * Remove the comment from the test code.\n */\n\npublic class Test {\n\n @org.junit.Test\n public void testBasic() {\n TreeFactory<String> tf = new TreeFactoryImpl<>();\n // construction of three child trees\n // a with three children aa,ab,ac\n Tree<String> son1 = tf.consTree(\"a\",Arrays.asList(\n tf.consTree(\"aa\",null), tf.consTree(\"ab\",null), tf.consTree(\"ac\",null)\n ));\n // only the root b\n Tree<String> son2 = tf.consTree(\"b\",null);\n // c with three children ca,cb,cc, and cc in turn with children cca and ccb\n Tree<String> son3 = tf.consTree(\"c\",Arrays.asList(\n tf.consTree(\"ca\",null),\n tf.consTree(\"cb\",null),\n tf.consTree(\"cc\",Arrays.asList(\n tf.consTree(\"cca\",null),\n tf.consTree(\"ccb\",null)\n ))));\n // I construct a tree through the three child trees\n Tree<String> tree = tf.consTree(\"root\",Arrays.asList(son1,son2,son3));\n\n // test on size()\n assertEquals(son1.size(),4);\n assertEquals(son2.size(),1);\n assertEquals(son3.size(),6);\n assertEquals(tree.size(),12);\n\n // test on getRoot()\n assertEquals(son1.getRoot(),\"a\");\n assertEquals(son2.getRoot(),\"b\");\n assertEquals(son3.getRoot(),\"c\");\n assertEquals(tree.getRoot(),\"root\");\n\n // test on contains\n assertTrue(tree.contains(\"a\"));\n assertTrue(tree.contains(\"b\"));\n assertTrue(tree.contains(\"c\"));\n assertTrue(tree.contains(\"ccb\"));\n assertFalse(tree.contains(\"ccc\"));\n\n // test on toList.. note that the order is NOT relevant\n assertTrue(son1.toList().containsAll(Arrays.asList(\"a\",\"aa\",\"ab\",\"ac\")));\n assertEquals(son1.toList().size(),son1.size());\n assertTrue(son2.toList().containsAll(Arrays.asList(\"b\")));\n assertEquals(son2.toList().size(),son2.size());\n assertTrue(son3.toList().containsAll(Arrays.asList(\"c\",\"ca\",\"cb\",\"cc\",\"cca\",\"ccb\")));\n assertEquals(son3.toList().size(),son3.size());\n assertTrue(tree.toList().containsAll(Arrays.asList(\"c\",\"ca\",\"cb\",\"cc\",\"cca\",\"ccb\",\"b\",\"a\",\"aa\",\"ab\",\"ac\")));\n assertEquals(tree.toList().size(),tree.size());\n\n // test on getSons\n assertTrue(tree.getSons().get(0).toList().containsAll(Arrays.asList(\"a\",\"aa\",\"ab\",\"ac\")));\n assertTrue(tree.getSons().get(1).toList().containsAll(Arrays.asList(\"b\")));\n assertTrue(tree.getSons().get(2).toList().containsAll(Arrays.asList(\"c\",\"ca\",\"cb\",\"cc\",\"cca\",\"ccb\")));\n\n // test on getSubTree\n assertTrue(tree.getSubTree(\"a\").toList().containsAll(Arrays.asList(\"a\",\"aa\",\"ab\",\"ac\")));\n assertTrue(tree.getSubTree(\"b\").toList().containsAll(Arrays.asList(\"b\")));\n assertTrue(tree.getSubTree(\"c\").toList().containsAll(Arrays.asList(\"c\",\"ca\",\"cb\",\"cc\",\"cca\",\"ccb\")));\n assertTrue(tree.getSubTree(\"root\").toList().containsAll(Arrays.asList(\"c\",\"ca\",\"cb\",\"cc\",\"cca\",\"ccb\",\"b\",\"a\",\"aa\",\"ab\",\"ac\")));\n assertTrue(tree.getSubTree(\"cc\").toList().containsAll(Arrays.asList(\"cc\",\"cca\",\"ccb\")));\n }\n\n @org.junit.Test\n public void optionalTestEmpty() {\n // test on the case of an empty tree\n TreeFactory<String> tf = new TreeFactoryImpl<>();\n Tree<String> tree = tf.emptyTree();\n\n // size 0\n assertEquals(tree.size(),0);\n\n // you cannot access root\n try{\n tree.getRoot();\n fail(\"can't get root if emty\");\n } catch (IllegalStateException e){\n\n } catch (Exception e){\n fail(\"wrong exception\");\n }\n\n // it does not contain any element\n assertFalse(tree.contains(\"a\"));\n\n // it has an empty list of elements\n assertEquals(tree.toList().size(),0);\n\n // you cannot access sons\n try{\n tree.getSons();\n fail(\"can't get sons if emty\");\n } catch (IllegalStateException e){\n\n } catch (Exception e){\n fail(\"wrong exception\");\n }\n\n // you cannot access subtrees\n try{\n tree.getSubTree(\"a\");\n fail(\"can't get subtrees if emty\");\n } catch (IllegalStateException e){\n\n } catch (Exception e){\n fail(\"wrong exception\");\n }\n }\n\n\n}", "filename": "Test.java" }
2015
a03a
[ { "content": "package ex2015.a03a.sol1;\n\nimport java.util.Map;\nimport java.util.Set;\n\n\npublic interface Faculty {\n \n \n void registerCourse(int id, String name);\n \n \n void registerStudent(int id, String name);\n \n \n void associate(int studentId, int courseId);\n \n \n String course(int courseId);\n \n \n String student(int studentId);\n \n \n Set<Integer> coursesByStudent(int studentId);\n \n \n Set<Integer> studentsByCourse(int courseId);\n \n \n Map<String,Set<String>> mapCoursesStudents();\n \n}", "filename": "Faculty.java" }, { "content": "package ex2015.a03a.sol1;\n\n\npublic final class Pair<X, Y> {\n\n private X x;\n private Y y;\n\n \n public Pair(final X x, final Y y) {\n super();\n this.x = x;\n this.y = y;\n }\n\n \n public X getX() {\n return x;\n }\n\n \n public Y getY() {\n return y;\n }\n \n \n public void setX(X x) {\n this.x = x;\n }\n\n \n public void setY(Y y) {\n this.y = y;\n }\n \n\n @Override\n public int hashCode() {\n return x.hashCode() ^ y.hashCode();\n }\n\n @Override\n public boolean equals(final Object obj) {\n return obj instanceof Pair ? x.equals(((Pair<?, ?>) obj).x) && y.equals(((Pair<?, ?>) obj).y) : false;\n }\n\n @Override\n public String toString() {\n return \"<\" + x + \", \" + y + \">\";\n }\n\n}", "filename": "Pair.java" } ]
[ { "content": "package ex2015.a03a.sol1;\n\nimport java.util.*;\nimport java.util.function.Supplier;\nimport java.util.stream.Collectors;\n\npublic class FacultyImpl implements Faculty {\n \n private final Map<Integer,Pair<String,Set<Integer>>> courses = new HashMap<>();\n private final Map<Integer,Pair<String,Set<Integer>>> students = new HashMap<>();\n \n private void check(boolean b, Supplier<RuntimeException> ex){\n if (b) {\n throw ex.get();\n }\n }\n\n @Override\n public void registerCourse(int id, String name) {\n check(this.courses.containsKey(id),()->new IllegalArgumentException(\"course already registered\"));\n this.courses.put(id, new Pair<>(name,new HashSet<>()));\n }\n\n @Override\n public void registerStudent(int id, String name) {\n check(this.students.containsKey(id),()->new IllegalArgumentException(\"course already registered\"));\n this.students.put(id, new Pair<>(name,new HashSet<>()));\n }\n\n @Override\n public void associate(int studentId, int courseId) {\n check(!this.students.containsKey(studentId),()->new IllegalArgumentException(\"student not registered\"));\n check(!this.courses.containsKey(courseId),()->new IllegalArgumentException(\"course not registered\"));\n check(this.courses.get(courseId).getY().contains(studentId),()->new IllegalStateException(\"course/student already registered\"));\n this.courses.get(courseId).getY().add(studentId);\n this.students.get(studentId).getY().add(courseId);\n }\n\n @Override\n public String course(int id) {\n return this.courses.get(id).getX();\n }\n\n @Override\n public String student(int id) {\n return this.students.get(id).getX();\n }\n\n @Override\n public Set<Integer> coursesByStudent(int studentId){\n return Collections.unmodifiableSet(this.students.get(studentId).getY());\n }\n\n @Override\n public Set<Integer> studentsByCourse(int courseId) {\n return Collections.unmodifiableSet(this.courses.get(courseId).getY());\n }\n \n @Override\n public Map<String,Set<String>> mapCoursesStudents(){\n return this.courses.values()\n .stream()\n .collect(Collectors.toMap(e -> e.getX(),\n e -> e.getY().stream()\n .map(i -> this.students.get(i).getX())\n .collect(Collectors.toSet())));\n }\n\n}", "filename": "FacultyImpl.java" } ]
{ "components": { "imports": "package ex2015.a03a.sol1;\n\nimport static org.hamcrest.CoreMatchers.*;\nimport static org.junit.Assert.*;\n\n/**\n * Implement the Faculty interface given through a FacultyImpl class\n * with a constructor without arguments. Models the management of courses in a university,\n * with methods to register courses and students, setting which student attends which courses.\n *\n * Observe carefully the following test, which together with the comments\n * of the Faculty interface constitutes the definition of the problem to be\n * solved.\n *\n * The tests whose name begins with 'optional', and the performance requests indicated\n * in the Faculty interface, are considered optional for the purpose of being able to correct\n * the exercise -- even if they contribute to the definition of the score.\n *\n * Remove the comment from the test code.\n */", "private_init": "\tprivate static void populateFaculty(final Faculty f) {\n f.registerCourse(100, \"OOP\"); // 3 courses\n f.registerCourse(101, \"SISOP\");\n f.registerCourse(102, \"ENG\");\n\n f.registerStudent(1000, \"Rossi\"); // 5 students\n f.registerStudent(1001, \"Bianchi\");\n f.registerStudent(1002, \"Verdi\");\n f.registerStudent(1003, \"Neri\");\n f.registerStudent(1004, \"Rosa\");\n\n f.associate(1000, 100); // all students do OOP\n f.associate(1001, 100);\n f.associate(1002, 100);\n f.associate(1003, 100);\n f.associate(1004, 100);\n\n f.associate(1000, 101); // three students do SISOP\n f.associate(1001, 101);\n f.associate(1002, 101);\n\n f.associate(1000, 102); // only one student does ENG\n }", "test_functions": [ "\[email protected]\n public void testBasicSelectors() {\n Faculty f = new FacultyImpl();\n populateFaculty(f);\n // access to courses and students by id\n assertEquals(f.course(100),\"OOP\");\n assertEquals(f.course(101),\"SISOP\");\n assertEquals(f.student(1000),\"Rossi\");\n assertEquals(f.student(1001),\"Bianchi\");\n\n // access to the courses of a student\n assertThat(f.coursesByStudent(1000), hasItems(100,101,102));\n assertEquals(f.coursesByStudent(1000).size(),3);\n assertThat(f.coursesByStudent(1001), hasItems(100,101));\n assertEquals(f.coursesByStudent(1001).size(),2);\n assertThat(f.coursesByStudent(1003), hasItems(100));\n assertEquals(f.coursesByStudent(1003).size(),1);\n\n // access to the students of a course\n assertThat(f.studentsByCourse(100), hasItems(1000,1001,1002,1003,1004));\n assertEquals(f.studentsByCourse(100).size(),5);\n assertThat(f.studentsByCourse(101), hasItems(1000,1001,1002));\n assertEquals(f.studentsByCourse(101).size(),3);\n assertThat(f.studentsByCourse(102), hasItems(1000));\n assertEquals(f.studentsByCourse(102).size(),1);\n\n // map courses -> set of students\n assertThat(f.mapCoursesStudents().get(\"OOP\"), hasItems(\"Rossi\",\"Bianchi\",\"Verdi\",\"Neri\",\"Rosa\"));\n assertEquals(f.mapCoursesStudents().get(\"OOP\").size(),5);\n assertThat(f.mapCoursesStudents().get(\"SISOP\"), hasItems(\"Rossi\",\"Bianchi\",\"Verdi\"));\n assertEquals(f.mapCoursesStudents().get(\"SISOP\").size(),3);\n }", "\[email protected]\n public void optionalTestExceptions() {\n Faculty f = new FacultyImpl();\n f.registerCourse(1, \"OOP\");\n try{\n f.registerCourse(1, \"SISOP\");\n fail(\"can't register a course twice\");\n }" ] }, "content": "package ex2015.a03a.sol1;\n\nimport static org.hamcrest.CoreMatchers.*;\nimport static org.junit.Assert.*;\n\n/**\n * Implement the Faculty interface given through a FacultyImpl class\n * with a constructor without arguments. Models the management of courses in a university,\n * with methods to register courses and students, setting which student attends which courses.\n *\n * Observe carefully the following test, which together with the comments\n * of the Faculty interface constitutes the definition of the problem to be\n * solved.\n *\n * The tests whose name begins with 'optional', and the performance requests indicated\n * in the Faculty interface, are considered optional for the purpose of being able to correct\n * the exercise -- even if they contribute to the definition of the score.\n *\n * Remove the comment from the test code.\n */\n\npublic class Test {\n\n private static void populateFaculty(final Faculty f) {\n f.registerCourse(100, \"OOP\"); // 3 courses\n f.registerCourse(101, \"SISOP\");\n f.registerCourse(102, \"ENG\");\n\n f.registerStudent(1000, \"Rossi\"); // 5 students\n f.registerStudent(1001, \"Bianchi\");\n f.registerStudent(1002, \"Verdi\");\n f.registerStudent(1003, \"Neri\");\n f.registerStudent(1004, \"Rosa\");\n\n f.associate(1000, 100); // all students do OOP\n f.associate(1001, 100);\n f.associate(1002, 100);\n f.associate(1003, 100);\n f.associate(1004, 100);\n\n f.associate(1000, 101); // three students do SISOP\n f.associate(1001, 101);\n f.associate(1002, 101);\n\n f.associate(1000, 102); // only one student does ENG\n }\n\n\n @org.junit.Test\n public void testBasicSelectors() {\n Faculty f = new FacultyImpl();\n populateFaculty(f);\n // access to courses and students by id\n assertEquals(f.course(100),\"OOP\");\n assertEquals(f.course(101),\"SISOP\");\n assertEquals(f.student(1000),\"Rossi\");\n assertEquals(f.student(1001),\"Bianchi\");\n\n // access to the courses of a student\n assertThat(f.coursesByStudent(1000), hasItems(100,101,102));\n assertEquals(f.coursesByStudent(1000).size(),3);\n assertThat(f.coursesByStudent(1001), hasItems(100,101));\n assertEquals(f.coursesByStudent(1001).size(),2);\n assertThat(f.coursesByStudent(1003), hasItems(100));\n assertEquals(f.coursesByStudent(1003).size(),1);\n\n // access to the students of a course\n assertThat(f.studentsByCourse(100), hasItems(1000,1001,1002,1003,1004));\n assertEquals(f.studentsByCourse(100).size(),5);\n assertThat(f.studentsByCourse(101), hasItems(1000,1001,1002));\n assertEquals(f.studentsByCourse(101).size(),3);\n assertThat(f.studentsByCourse(102), hasItems(1000));\n assertEquals(f.studentsByCourse(102).size(),1);\n\n // map courses -> set of students\n assertThat(f.mapCoursesStudents().get(\"OOP\"), hasItems(\"Rossi\",\"Bianchi\",\"Verdi\",\"Neri\",\"Rosa\"));\n assertEquals(f.mapCoursesStudents().get(\"OOP\").size(),5);\n assertThat(f.mapCoursesStudents().get(\"SISOP\"), hasItems(\"Rossi\",\"Bianchi\",\"Verdi\"));\n assertEquals(f.mapCoursesStudents().get(\"SISOP\").size(),3);\n }\n\n @org.junit.Test\n public void optionalTestExceptions() {\n Faculty f = new FacultyImpl();\n f.registerCourse(1, \"OOP\");\n try{\n f.registerCourse(1, \"SISOP\");\n fail(\"can't register a course twice\");\n } catch (IllegalArgumentException e){\n } catch (Exception e){\n fail(\"wrong exception thrown\");\n }\n f.registerStudent(10, \"Mirko\");\n try{\n f.registerStudent(10, \"Gino\");\n fail(\"can't register a student twice\");\n } catch (IllegalArgumentException e){\n } catch (Exception e){\n fail(\"wrong exception thrown\");\n }\n f.associate(10, 1);\n try{\n f.associate(10,1);\n fail(\"already associated\");\n } catch (IllegalStateException e){\n } catch (Exception e){\n fail(\"wrong exception thrown\");\n }\n try{\n f.associate(10,2);\n fail(\"can't associate non-existing elements\");\n } catch (IllegalArgumentException e){\n } catch (Exception e){\n fail(\"wrong exception thrown\");\n }\n }\n\n\n\n\n}", "filename": "Test.java" }
2015
a02b
[ { "content": "package ex2015.a02b.sol1;\n\nimport java.util.*;\n\n\npublic interface Menu {\n\n \n interface Dish {\n\n \n String getName();\n\n \n int getCost();\n \n \n Temperature getTemperature();\n \n \n Optional<String> awarded();\n }\n \n enum Temperature {\n FROZEN, COLD, NORMAL, HOT; \n }\n\n \n Dish createDish(String name, int cost, Temperature temperature);\n \n \n Dish createDish(String name, int cost, Temperature temperature, String award);\n \n \n void add(Dish d);\n \n \n int getOverallCost();\n \n \n Set<String> getDishNames();\n \n \n Map<Temperature,List<Dish>> getMapByTemperature();\n}", "filename": "Menu.java" }, { "content": "package ex2015.a02b.sol1;\n\n\n\npublic class Pair<X,Y> {\n\t\n\tprivate final X x;\n\tprivate final Y y;\n\t\n\tpublic Pair(X x, Y y) {\n\t\tsuper();\n\t\tthis.x = x;\n\t\tthis.y = y;\n\t}\n\n\tpublic X getX() {\n\t\treturn x;\n\t}\n\n\tpublic Y getY() {\n\t\treturn y;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = 1;\n\t\tresult = prime * result + ((x == null) ? 0 : x.hashCode());\n\t\tresult = prime * result + ((y == null) ? 0 : y.hashCode());\n\t\treturn result;\n\t}\n\n\t@SuppressWarnings(\"rawtypes\")\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (obj == null)\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tPair other = (Pair) obj;\n\t\tif (x == null) {\n\t\t\tif (other.x != null)\n\t\t\t\treturn false;\n\t\t} else if (!x.equals(other.x))\n\t\t\treturn false;\n\t\tif (y == null) {\n\t\t\tif (other.y != null)\n\t\t\t\treturn false;\n\t\t} else if (!y.equals(other.y))\n\t\t\treturn false;\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Pair [x=\" + x + \", y=\" + y + \"]\";\n\t}\n\t\n\t\n\n}", "filename": "Pair.java" } ]
[ { "content": "package ex2015.a02b.sol1;\n\nimport java.util.*;\nimport java.util.stream.Collectors;\n\npublic class MenuImpl implements Menu {\n \n private final Map<String,Dish> map = new HashMap<>();\n \n public MenuImpl(){}\n\n @Override\n public Dish createDish(String name, int cost, Temperature temperature) {\n return new DishBuilder().name(name).cost(cost).temperature(temperature).build();\n }\n\n @Override\n public Dish createDish(String name, int cost, Temperature temperature, String award) {\n return new DishBuilder().name(name).cost(cost).temperature(temperature).award(award).build();\n }\n\n @Override\n public void add(Dish d) {\n if (this.map.containsKey(Objects.requireNonNull(d).getName())){\n throw new IllegalArgumentException();\n }\n this.map.put(d.getName(),d);\n }\n\n @Override\n public int getOverallCost() {\n return this.map.values().stream().map(Dish::getCost).reduce(0, (x,y)->x+y);\n }\n \n @Override\n public Set<String> getDishNames() {\n return this.map.keySet();\n }\n\n @Override\n public Map<Temperature, List<Dish>> getMapByTemperature() {\n return this.map.values().stream().collect(Collectors.groupingBy(Dish::getTemperature, Collectors.toList()));\n }\n \n @Override\n public String toString(){\n return this.map.toString();\n }\n \n private class DishBuilder{\n private String name;\n private int cost;\n private Temperature temperature;\n private String award;\n \n public DishBuilder(){}\n \n public DishBuilder name(String s){\n this.name = s;\n return this;\n }\n \n public DishBuilder cost(int i){\n this.cost = i;\n return this;\n }\n \n public DishBuilder temperature(Temperature t){\n this.temperature = t;\n return this;\n }\n \n public DishBuilder award(String s){\n this.award = s;\n return this;\n }\n \n public Dish build(){\n if (cost <= 0 || this.name == null || this.temperature == null){\n throw new IllegalArgumentException();\n }\n return new DishImpl(this.name,this.cost,this.temperature,this.award);\n }\n }\n\n private class DishImpl implements Dish{\n \n private String name;\n private int cost;\n private Temperature temperature;\n private String award;\n \n private DishImpl(String name, int cost, Temperature temperature, String award) {\n super();\n this.name = name;\n this.cost = cost;\n this.temperature = temperature;\n this.award = award;\n }\n\n @Override\n public String getName() {\n return this.name;\n }\n\n @Override\n public int getCost() {\n return this.cost;\n }\n\n @Override\n public Temperature getTemperature() {\n return this.temperature;\n }\n\n @Override\n public Optional<String> awarded() {\n return Optional.of(this.award);\n }\n\n @Override\n public String toString() {\n return \"D[name=\" + name + \"]\";\n }\n\n @Override\n public int hashCode() {\n final int prime = 31;\n int result = 1;\n result = prime * result + getOuterType().hashCode();\n result = prime * result + ((award == null) ? 0 : award.hashCode());\n result = prime * result + cost;\n result = prime * result + ((name == null) ? 0 : name.hashCode());\n result = prime * result + ((temperature == null) ? 0 : temperature.hashCode());\n return result;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj)\n return true;\n if (obj == null)\n return false;\n if (getClass() != obj.getClass())\n return false;\n DishImpl other = (DishImpl) obj;\n if (!getOuterType().equals(other.getOuterType()))\n return false;\n if (award == null) {\n if (other.award != null)\n return false;\n } else if (!award.equals(other.award))\n return false;\n if (cost != other.cost)\n return false;\n if (name == null) {\n if (other.name != null)\n return false;\n } else if (!name.equals(other.name))\n return false;\n if (temperature != other.temperature)\n return false;\n return true;\n }\n\n private MenuImpl getOuterType() {\n return MenuImpl.this;\n }\n \n }\n}", "filename": "MenuImpl.java" } ]
{ "components": { "imports": "package ex2015.a02b.sol1;\n\nimport static org.junit.Assert.*;\nimport static org.hamcrest.CoreMatchers.*;", "private_init": "\t/*\n * Implement the given Menu interface through a MenuImpl class\n * with a constructor without arguments. Models a restaurant menu,\n * with methods to create dishes, add them to the menu, and methods to extract information about the menu.\n * The comment to the Menu code and the test methods below constitute the\n * necessary explanation of the problem. The tests whose name begins with\n * 'optional' are considered optional for the purpose of being able to\n * correct the exercise -- even if they contribute to the definition of the\n * score.\n *\n * Solutions that create dishes (Dish) with the Builder pattern will be preferred.\n *\n * Remove the comment from the tests..\n */\n\n // creation of a basic menu\n private Menu buildBasicMenu() {\n Menu menu = new MenuImpl();\n menu.add(menu.createDish(\"Tagliere\", 100, Menu.Temperature.NORMAL));\n menu.add(menu.createDish(\"Bruschette\", 90, Menu.Temperature.NORMAL));\n menu.add(menu.createDish(\"Spaghetti\", 120, Menu.Temperature.HOT));\n menu.add(menu.createDish(\"Grigliata\", 150, Menu.Temperature.HOT));\n menu.add(menu.createDish(\"Mascarpone\", 150, Menu.Temperature.FROZEN));\n menu.add(menu.createDish(\"Vino\", 60, Menu.Temperature.COLD, \"Vino dell'anno\")); // menu with award\n return menu;\n }", "test_functions": [ "\[email protected]\n public void testBasicMenu() {\n final Menu menu = buildBasicMenu();\n // Verification of the methods to extract information from the menu\n assertEquals(menu.getDishNames().size(), 6);\n assertThat(menu.getDishNames(), hasItems(\"Tagliere\", \"Bruschette\", \"Spaghetti\", \"Mascarpone\", \"Vino\"));\n assertEquals(menu.getOverallCost(), 670);\n assertEquals(menu.getMapByTemperature().size(), 4);\n assertEquals(menu.getMapByTemperature().get(Menu.Temperature.NORMAL).size(), 2); // 2 NORMAL dishes\n assertEquals(menu.getMapByTemperature().get(Menu.Temperature.HOT).size(), 2); // 2 HOT dishes\n assertEquals(menu.getMapByTemperature().get(Menu.Temperature.FROZEN).size(), 1); // 1 FROZEN dish\n assertEquals(menu.getMapByTemperature().get(Menu.Temperature.COLD).size(), 1); // 1 COLD dish\n // the FROZEN dish is Mascarpone\n assertTrue(menu.getMapByTemperature().get(Menu.Temperature.FROZEN).get(0).getName().equals(\"Mascarpone\"));\n // the COLD dish has the award\n assertTrue(menu.getMapByTemperature().get(Menu.Temperature.COLD).get(0).awarded().isPresent());\n }", "\[email protected]\n public void optionalTestErrors() {\n final Menu menu = buildBasicMenu();\n Menu.Dish mascarpone = menu.createDish(\"Mascarpone\", 100, Menu.Temperature.FROZEN);\n try{\n menu.add(mascarpone);\n fail(\"can't add a dish twice\");\n }" ] }, "content": "package ex2015.a02b.sol1;\n\nimport static org.junit.Assert.*;\nimport static org.hamcrest.CoreMatchers.*;\n\npublic class Test {\n\n /*\n * Implement the given Menu interface through a MenuImpl class\n * with a constructor without arguments. Models a restaurant menu,\n * with methods to create dishes, add them to the menu, and methods to extract information about the menu.\n * The comment to the Menu code and the test methods below constitute the\n * necessary explanation of the problem. The tests whose name begins with\n * 'optional' are considered optional for the purpose of being able to\n * correct the exercise -- even if they contribute to the definition of the\n * score.\n *\n * Solutions that create dishes (Dish) with the Builder pattern will be preferred.\n *\n * Remove the comment from the tests..\n */\n\n // creation of a basic menu\n private Menu buildBasicMenu() {\n Menu menu = new MenuImpl();\n menu.add(menu.createDish(\"Tagliere\", 100, Menu.Temperature.NORMAL));\n menu.add(menu.createDish(\"Bruschette\", 90, Menu.Temperature.NORMAL));\n menu.add(menu.createDish(\"Spaghetti\", 120, Menu.Temperature.HOT));\n menu.add(menu.createDish(\"Grigliata\", 150, Menu.Temperature.HOT));\n menu.add(menu.createDish(\"Mascarpone\", 150, Menu.Temperature.FROZEN));\n menu.add(menu.createDish(\"Vino\", 60, Menu.Temperature.COLD, \"Vino dell'anno\")); // menu with award\n return menu;\n }\n\n @org.junit.Test\n public void testBasicMenu() {\n final Menu menu = buildBasicMenu();\n // Verification of the methods to extract information from the menu\n assertEquals(menu.getDishNames().size(), 6);\n assertThat(menu.getDishNames(), hasItems(\"Tagliere\", \"Bruschette\", \"Spaghetti\", \"Mascarpone\", \"Vino\"));\n assertEquals(menu.getOverallCost(), 670);\n assertEquals(menu.getMapByTemperature().size(), 4);\n assertEquals(menu.getMapByTemperature().get(Menu.Temperature.NORMAL).size(), 2); // 2 NORMAL dishes\n assertEquals(menu.getMapByTemperature().get(Menu.Temperature.HOT).size(), 2); // 2 HOT dishes\n assertEquals(menu.getMapByTemperature().get(Menu.Temperature.FROZEN).size(), 1); // 1 FROZEN dish\n assertEquals(menu.getMapByTemperature().get(Menu.Temperature.COLD).size(), 1); // 1 COLD dish\n // the FROZEN dish is Mascarpone\n assertTrue(menu.getMapByTemperature().get(Menu.Temperature.FROZEN).get(0).getName().equals(\"Mascarpone\"));\n // the COLD dish has the award\n assertTrue(menu.getMapByTemperature().get(Menu.Temperature.COLD).get(0).awarded().isPresent());\n }\n \n @org.junit.Test\n public void optionalTestErrors() {\n final Menu menu = buildBasicMenu();\n Menu.Dish mascarpone = menu.createDish(\"Mascarpone\", 100, Menu.Temperature.FROZEN);\n try{\n menu.add(mascarpone);\n fail(\"can't add a dish twice\");\n } catch (IllegalArgumentException e){\n } catch (Exception e){\n fail(\"wrong exception thrown\");\n }\n try{\n menu.add(null);\n fail(\"can't add a null dish\");\n } catch (NullPointerException e){\n } catch (Exception e){\n fail(\"wrong exception thrown\");\n }\n try{\n menu.createDish(\"Bistecca\", -50, Menu.Temperature.HOT);\n fail(\"can't cost a negative value\");\n } catch (IllegalArgumentException e){\n } catch (Exception e){\n fail(\"wrong exception thrown\");\n }\n try{\n menu.createDish(null, 100, Menu.Temperature.HOT);\n fail(\"can't have a null name\");\n } catch (IllegalArgumentException e){\n } catch (Exception e){\n fail(\"wrong exception thrown\");\n }\n }\n\n}", "filename": "Test.java" }
2015
a06
[ { "content": "package ex2015.a06.sol1;\n\n\npublic interface Countdown {\n\n \n void decrease(); \n \n \n int getValue();\n \n \n boolean isOver(); \n \n}", "filename": "Countdown.java" }, { "content": "package ex2015.a06.sol1;\n\n\npublic interface PowerCountdown extends Countdown {\n \n \n void reset();\n \n \n void speedup();\n\n}", "filename": "PowerCountdown.java" } ]
[ { "content": "package ex2015.a06.sol1;\n\npublic class StandardCountdown extends AbstractCountdown {\n \n public StandardCountdown(int value) {\n super(value);\n }\n\n @Override\n protected void actualDecrease() {\n this.value--;\n }\n\n @Override\n public boolean isOver() {\n return this.value == 0;\n }\n\n}", "filename": "StandardCountdown.java" }, { "content": "package ex2015.a06.sol1;\n\npublic class PowerCountdownImpl extends AbstractCountdown implements PowerCountdown {\n \n private int finalValue;\n private int delta = 1;\n private int initialValue;\n \n public PowerCountdownImpl(int value, int finalValue){\n super(value);\n this.initialValue = value;\n this.finalValue = finalValue;\n }\n\n @Override\n protected void actualDecrease() {\n this.value -= this.delta;\n }\n\n @Override\n public boolean isOver() {\n return this.value <= this.finalValue;\n }\n\n @Override\n public void reset() {\n this.delta = 1;\n this.value = this.initialValue; \n }\n\n @Override\n public void speedup() {\n this.delta++;\n }\n\n}", "filename": "PowerCountdownImpl.java" }, { "content": "package ex2015.a06.sol1;\n\npublic abstract class AbstractCountdown implements Countdown {\n \n protected int value;\n \n public AbstractCountdown(int value) {\n this.value = value;\n }\n \n protected abstract void actualDecrease();\n\n @Override\n public final void decrease() {\n if (this.isOver()){\n throw new IllegalStateException();\n }\n this.actualDecrease();\n\n }\n\n @Override\n public int getValue() {\n return this.value;\n }\n\n}", "filename": "AbstractCountdown.java" } ]
{ "components": { "imports": "package ex2015.a06.sol1;\n\nimport static org.junit.Assert.*;\n\nimport java.util.*;\n\n/**\n * See the documentation of the provided Countdown and PowerCountdown interfaces, which model countdown counters.\n * Implement the Countdown interface with a StandardCountdown class, with a constructor that accepts the initial value of the\n * count: this counter should always decrement by 1 until it reaches the value 0.\n * Implement the PowerCountdown interface with a PowerCountdownImpl class, with a constructor that accepts the initial\n * and final value of the count (the latter should be smaller): this counter initially decrements by 1 at a time, and with each\n * call to speedup() then decrements by an increasing value (2,3,4,..); on reset, it returns to the initial count value\n * and to decrement 1.\n *\n * Considered optional for the purpose of being able to correct the exercise, use -- even if it contributes to achieving\n * the maximum score -- the Template Method pattern to factor the two classes and eliminate any possible form of repetition\n * in the code.\n *\n * Observe the following test carefully, which together with the comments of the given interfaces\n * constitutes the definition of the problem to be solved.\n *\n * Remove the comment from the test code.\n */", "private_init": "\t// Testing StandardCountdown: going from 3 to 0", "test_functions": [ "\[email protected]\n public void testStandard() {\n Countdown countdown = new StandardCountdown(3);\n assertEquals(countdown.getValue(),3);\n assertFalse(countdown.isOver());\n countdown.decrease();\n assertEquals(countdown.getValue(),2);\n assertFalse(countdown.isOver());\n countdown.decrease();\n assertEquals(countdown.getValue(),1);\n assertFalse(countdown.isOver());\n countdown.decrease();\n assertEquals(countdown.getValue(),0);\n assertTrue(countdown.isOver());\n }", "\[email protected]\n public void testStandardException() {\n Countdown countdown = new StandardCountdown(3);\n countdown.decrease();\n countdown.decrease();\n countdown.decrease();\n try{\n countdown.decrease();\n fail(\"Cannot decrease anymore\");\n }", "\[email protected]\n public void testPower1() {\n PowerCountdown pcountdown = new PowerCountdownImpl(4,2);\n assertEquals(pcountdown.getValue(),4);\n assertFalse(pcountdown.isOver());\n pcountdown.decrease();\n assertEquals(pcountdown.getValue(),3);\n assertFalse(pcountdown.isOver());\n pcountdown.decrease();\n assertEquals(pcountdown.getValue(),2);\n assertTrue(pcountdown.isOver());\n }", "\[email protected]\n public void testPower1Exception() {\n PowerCountdown pcountdown = new PowerCountdownImpl(4,2);\n pcountdown.decrease();\n pcountdown.decrease();\n try{\n pcountdown.decrease();\n fail(\"Cannot decrease anymore\");\n }", "\[email protected]\n public void testPower2() {\n PowerCountdown pcountdown = new PowerCountdownImpl(10,0);\n // speed is now 1;\n assertEquals(pcountdown.getValue(),10);\n assertFalse(pcountdown.isOver());\n pcountdown.decrease();\n assertEquals(pcountdown.getValue(),9);\n assertFalse(pcountdown.isOver());\n pcountdown.decrease();\n assertEquals(pcountdown.getValue(),8);\n assertFalse(pcountdown.isOver());\n pcountdown.speedup();\n pcountdown.speedup(); // speed is now 3;\n pcountdown.decrease();\n assertEquals(pcountdown.getValue(),5);\n assertFalse(pcountdown.isOver());\n pcountdown.decrease();\n assertEquals(pcountdown.getValue(),2);\n assertFalse(pcountdown.isOver());\n pcountdown.reset(); // now at value 10, and speed back to 1\n assertEquals(pcountdown.getValue(),10);\n assertFalse(pcountdown.isOver());\n pcountdown.decrease();\n assertEquals(pcountdown.getValue(),9);\n assertFalse(pcountdown.isOver());\n }" ] }, "content": "package ex2015.a06.sol1;\n\nimport static org.junit.Assert.*;\n\nimport java.util.*;\n\n/**\n * See the documentation of the provided Countdown and PowerCountdown interfaces, which model countdown counters.\n * Implement the Countdown interface with a StandardCountdown class, with a constructor that accepts the initial value of the\n * count: this counter should always decrement by 1 until it reaches the value 0.\n * Implement the PowerCountdown interface with a PowerCountdownImpl class, with a constructor that accepts the initial\n * and final value of the count (the latter should be smaller): this counter initially decrements by 1 at a time, and with each\n * call to speedup() then decrements by an increasing value (2,3,4,..); on reset, it returns to the initial count value\n * and to decrement 1.\n *\n * Considered optional for the purpose of being able to correct the exercise, use -- even if it contributes to achieving\n * the maximum score -- the Template Method pattern to factor the two classes and eliminate any possible form of repetition\n * in the code.\n *\n * Observe the following test carefully, which together with the comments of the given interfaces\n * constitutes the definition of the problem to be solved.\n *\n * Remove the comment from the test code.\n */\n\npublic class Test {\n\n // Testing StandardCountdown: going from 3 to 0\n @org.junit.Test\n public void testStandard() {\n Countdown countdown = new StandardCountdown(3);\n assertEquals(countdown.getValue(),3);\n assertFalse(countdown.isOver());\n countdown.decrease();\n assertEquals(countdown.getValue(),2);\n assertFalse(countdown.isOver());\n countdown.decrease();\n assertEquals(countdown.getValue(),1);\n assertFalse(countdown.isOver());\n countdown.decrease();\n assertEquals(countdown.getValue(),0);\n assertTrue(countdown.isOver());\n }\n \n // Testing StandardCountdown: going from 3 to 0, and trying again\n @org.junit.Test\n public void testStandardException() {\n Countdown countdown = new StandardCountdown(3);\n countdown.decrease();\n countdown.decrease();\n countdown.decrease();\n try{\n countdown.decrease();\n fail(\"Cannot decrease anymore\");\n } catch (IllegalStateException e){\n assertTrue(countdown.isOver());\n } catch (Exception e){\n fail(\"Wrong exception thrown\");\n }\n }\n \n // Testing PowerCountdownImpl: going from 4 to 2\n @org.junit.Test\n public void testPower1() {\n PowerCountdown pcountdown = new PowerCountdownImpl(4,2);\n assertEquals(pcountdown.getValue(),4);\n assertFalse(pcountdown.isOver());\n pcountdown.decrease();\n assertEquals(pcountdown.getValue(),3);\n assertFalse(pcountdown.isOver());\n pcountdown.decrease();\n assertEquals(pcountdown.getValue(),2);\n assertTrue(pcountdown.isOver());\n }\n \n // Testing PowerCountdownImpl: going from 4 to 2, and trying again\n @org.junit.Test\n public void testPower1Exception() {\n PowerCountdown pcountdown = new PowerCountdownImpl(4,2);\n pcountdown.decrease();\n pcountdown.decrease();\n try{\n pcountdown.decrease();\n fail(\"Cannot decrease anymore\");\n } catch (IllegalStateException e){\n assertTrue(pcountdown.isOver());\n } catch (Exception e){\n fail(\"Wrong exception thrown\");\n }\n }\n \n // Testing PowerCountdownImpl: going from 10 to 0, at 8 increasing speed to 3, at 2 resetting\n @org.junit.Test\n public void testPower2() {\n PowerCountdown pcountdown = new PowerCountdownImpl(10,0);\n // speed is now 1;\n assertEquals(pcountdown.getValue(),10);\n assertFalse(pcountdown.isOver());\n pcountdown.decrease();\n assertEquals(pcountdown.getValue(),9);\n assertFalse(pcountdown.isOver());\n pcountdown.decrease();\n assertEquals(pcountdown.getValue(),8);\n assertFalse(pcountdown.isOver());\n pcountdown.speedup();\n pcountdown.speedup(); // speed is now 3;\n pcountdown.decrease();\n assertEquals(pcountdown.getValue(),5);\n assertFalse(pcountdown.isOver());\n pcountdown.decrease();\n assertEquals(pcountdown.getValue(),2);\n assertFalse(pcountdown.isOver());\n pcountdown.reset(); // now at value 10, and speed back to 1\n assertEquals(pcountdown.getValue(),10);\n assertFalse(pcountdown.isOver());\n pcountdown.decrease();\n assertEquals(pcountdown.getValue(),9);\n assertFalse(pcountdown.isOver());\n }\n}", "filename": "Test.java" }
2015
a01a
[ { "content": "package ex2015.a01a.sol1;\n\nimport java.util.*;\n\n\npublic interface CoursesCalendar {\n\t\n\t\n\t\n\tenum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY }\n\t\n\t\n\tenum Room { A, B, C, D, E, MAGNA, VELA, C_ALDO_MORO }\n\t\n\t\n\tList<Integer> possibleSlots();\n\t\n\t\n\tvoid bookRoom(Day d, Room r, int start, int duration, String course);\n\t\n\t\n\tSet<Pair<Integer,String>> dayRoomSlots(Day d, Room r);\n\t\n\t\n\tMap<Pair<Day,Room>,Set<Integer>> courseSlots(String course);\n\n}", "filename": "CoursesCalendar.java" }, { "content": "package ex2015.a01a.sol1;\n\n\n\npublic class Pair<X,Y> {\n\t\n\tprivate final X x;\n\tprivate final Y y;\n\t\n\tpublic Pair(X x, Y y) {\n\t\tsuper();\n\t\tthis.x = x;\n\t\tthis.y = y;\n\t}\n\n\tpublic X getX() {\n\t\treturn x;\n\t}\n\n\tpublic Y getY() {\n\t\treturn y;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = 1;\n\t\tresult = prime * result + ((x == null) ? 0 : x.hashCode());\n\t\tresult = prime * result + ((y == null) ? 0 : y.hashCode());\n\t\treturn result;\n\t}\n\n\t@SuppressWarnings(\"rawtypes\")\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (obj == null)\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tPair other = (Pair) obj;\n\t\tif (x == null) {\n\t\t\tif (other.x != null)\n\t\t\t\treturn false;\n\t\t} else if (!x.equals(other.x))\n\t\t\treturn false;\n\t\tif (y == null) {\n\t\t\tif (other.y != null)\n\t\t\t\treturn false;\n\t\t} else if (!y.equals(other.y))\n\t\t\treturn false;\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Pair [x=\" + x + \", y=\" + y + \"]\";\n\t}\n\t\n\t\n\n}", "filename": "Pair.java" } ]
[ { "content": "package ex2015.a01a.sol1;\n\nimport java.util.*;\nimport java.util.stream.*;\n\npublic class CoursesCalendarImpl implements CoursesCalendar {\n\t\n\tprivate static final List<Integer> AVAILABLE_SLOTS = Arrays.asList(9,10,11,12,14,15,16,17);\n\tprivate final Map<Pair<Day, Room>, Map<Integer,String>> slots = new HashMap<>();\n\t\n\tpublic CoursesCalendarImpl(){}\n\t\n\t@Override\n\tpublic List<Integer> possibleSlots(){\n\t\treturn AVAILABLE_SLOTS;\n\t}\n\t\n\tprivate Map<Integer,String> getOrPrepareDayRoom(Day d, Room r){\n\t\treturn slots.merge(new Pair<>(d,r), new HashMap<>(), (x,y)->x);\n\t}\n\n\t@Override\n\tpublic void bookRoom(Day d, Room r, int start, int duration, String course) {\n\t\tfinal Map<Integer,String> map = this.getOrPrepareDayRoom(d,r);\n\t\tint begin = AVAILABLE_SLOTS.indexOf(start);\n\t\tfor (int i = begin; i < begin + duration; i++){\n\t\t\tif (map.containsKey(AVAILABLE_SLOTS.get(i))){\n\t\t\t\tthrow new IllegalStateException();\n\t\t\t}\n\t\t}\n\t\tfor (int i = begin; i < begin + duration; i++){\n\t\t\tmap.put(AVAILABLE_SLOTS.get(i), course);\n\t\t}\n\t}\n\n\t@Override\n\tpublic Set<Pair<Integer, String>> dayRoomSlots(Day d, Room r) {\n\t\tfinal Map<Integer,String> map = this.getOrPrepareDayRoom(d,r);\n\t\treturn map.entrySet().stream().map(e -> new Pair<>(e.getKey(),e.getValue())).collect(Collectors.toSet());\n\t}\n\t\n\t@Override\n\tpublic Map<Pair<Day, Room>, Set<Integer>> courseSlots(String course) {\n\t\treturn this.slots\n\t\t\t\t .entrySet()\n\t\t\t\t .stream()\n\t\t\t\t .collect(Collectors.toMap(k->k.getKey(),\n\t\t\t\t\t\t v-> v.getValue()\n\t\t\t\t\t\t .entrySet()\n\t\t\t\t\t\t .stream()\n\t\t\t\t\t\t .filter(e->e.getValue().equals(course)).map(e->e.getKey())\n\t\t\t\t\t\t .collect(Collectors.toSet())));\n\t}\n}", "filename": "CoursesCalendarImpl.java" } ]
{ "components": { "imports": "package ex2015.a01a.sol1;\n\nimport static org.junit.Assert.*;\nimport static ex2015.a01a.sol1.CoursesCalendar.Day.*;\nimport static ex2015.a01a.sol1.CoursesCalendar.Room.*;\nimport static org.hamcrest.CoreMatchers.*;\n\nimport java.util.*;", "private_init": "\t/*\n\t * Implement the CoursesCalendar interface given through a CoursesCalendarImpl class with a constructor without arguments.\n\t * Model the manager of a weekly lesson schedule, with a method to make a reservation, and methods\n\t * to extract information.\n\t * The comment to the CoursesCalendar code, and the test methods below constitute the necessary explanation of the \n\t * problem.\n\t * The tests whose name begins with 'optional' are considered optional for the purpose of being able to correct\n\t * the exercise -- even if they contribute to the definition of the score.\n\t * Remove the comment from the tests..\n\t */", "test_functions": [ "\[email protected]\n\tpublic void testPossibleSlots() {\n\t\t// slots available for booking in general: exactly 9,10,11,12,14,15,16,17\n\t\tCoursesCalendar cc = new CoursesCalendarImpl();\n\t\tassertEquals(cc.possibleSlots().size(),8);\n\t\tassertThat(cc.possibleSlots(),hasItems(9,10,11,12,14,15,16,17));\n\t}", "\[email protected]\n\tpublic void testBasicBooking() { \n\t\t// almost standard booking for OOP and SISOP\n\t\tCoursesCalendar cc = new CoursesCalendarImpl();\n\t\tcc.bookRoom(MONDAY, VELA, 10, 3, \"OOP\");\n\t\tcc.bookRoom(TUESDAY, VELA, 14, 3, \"OOP\");\n\t\tcc.bookRoom(WEDNESDAY, MAGNA, 10, 3, \"OOP\");\n\t\tcc.bookRoom(THURSDAY, MAGNA, 14, 3, \"OOP\");\n\t\tcc.bookRoom(MONDAY, VELA, 14, 3, \"SISOP\");\n\t\tcc.bookRoom(TUESDAY, VELA, 9, 3, \"SISOP\");\n\t\tcc.bookRoom(WEDNESDAY, MAGNA, 14, 3, \"SISOP\");\n\t\tcc.bookRoom(FRIDAY, C_ALDO_MORO, 10, 3, \"SISOP\");\n\t\t\n\t\t// bookings in VELA on Monday\n\t\tSet<Pair<Integer,String>> set = cc.dayRoomSlots(MONDAY, VELA);\n\t\tassertEquals(set.size(),6);\n\t\tassertTrue(set.contains(new Pair<>(10,\"OOP\")));\n\t\tassertTrue(set.contains(new Pair<>(11,\"OOP\")));\n\t\tassertTrue(set.contains(new Pair<>(12,\"OOP\")));\n\t\tassertTrue(set.contains(new Pair<>(14,\"SISOP\")));\n\t\tassertTrue(set.contains(new Pair<>(15,\"SISOP\")));\n\t\tassertTrue(set.contains(new Pair<>(16,\"SISOP\")));\n\t\t\n\t\t// none in MAGNA on Monday\n\t\tassertEquals(cc.dayRoomSlots(MONDAY, MAGNA).size(),0);\n\t\t\n\t\t// OOP bookings: which ones on Thursday in MAGNA?\n\t\tSet<Integer> set2 = cc.courseSlots(\"OOP\").get(new Pair<>(THURSDAY,MAGNA));\n\t\tassertEquals(set2.size(),3);\n\t\tassertThat(set2,hasItems(14,15,16));\n\t}", "\[email protected]\n\tpublic void optionalTestJumpBooking() {\n\t\t// a 6-hour booking straddling lunch\n\t\tCoursesCalendar cc = new CoursesCalendarImpl();\n\t\tcc.bookRoom(MONDAY, VELA, 10, 6, \"OOP\");\n\t\t\n\t\tSet<Pair<Integer,String>> set = cc.dayRoomSlots(MONDAY, VELA);\n\t\tassertEquals(set.size(),6);\n\t\tassertTrue(set.contains(new Pair<>(10,\"OOP\")));\n\t\tassertTrue(set.contains(new Pair<>(11,\"OOP\")));\n\t\tassertTrue(set.contains(new Pair<>(12,\"OOP\")));\n\t\tassertTrue(set.contains(new Pair<>(14,\"OOP\")));\n\t\tassertTrue(set.contains(new Pair<>(15,\"OOP\")));\n\t\tassertTrue(set.contains(new Pair<>(16,\"OOP\")));\n\t}", "\[email protected]\n\tpublic void testConflictingBooking() { \n\t\t// example of two conflicting bookings\n\t\tCoursesCalendar cc = new CoursesCalendarImpl();\n\t\tcc.bookRoom(MONDAY, VELA, 10, 6, \"OOP\");\n\t\tassertEquals(cc.dayRoomSlots(MONDAY, VELA).size(),6);\n\t\ttry{\n\t\t\tcc.bookRoom(MONDAY, VELA, 9, 2, \"SISOP\");\n\t\t\tfail(\"cannot book with conflict from 16 to 17\");\n\t\t}" ] }, "content": "package ex2015.a01a.sol1;\n\nimport static org.junit.Assert.*;\nimport static ex2015.a01a.sol1.CoursesCalendar.Day.*;\nimport static ex2015.a01a.sol1.CoursesCalendar.Room.*;\nimport static org.hamcrest.CoreMatchers.*;\n\nimport java.util.*;\n\npublic class Test {\n\t\n\t/*\n\t * Implement the CoursesCalendar interface given through a CoursesCalendarImpl class with a constructor without arguments.\n\t * Model the manager of a weekly lesson schedule, with a method to make a reservation, and methods\n\t * to extract information.\n\t * The comment to the CoursesCalendar code, and the test methods below constitute the necessary explanation of the \n\t * problem.\n\t * The tests whose name begins with 'optional' are considered optional for the purpose of being able to correct\n\t * the exercise -- even if they contribute to the definition of the score.\n\t * Remove the comment from the tests..\n\t */\n\n\[email protected]\n\tpublic void testPossibleSlots() {\n\t\t// slots available for booking in general: exactly 9,10,11,12,14,15,16,17\n\t\tCoursesCalendar cc = new CoursesCalendarImpl();\n\t\tassertEquals(cc.possibleSlots().size(),8);\n\t\tassertThat(cc.possibleSlots(),hasItems(9,10,11,12,14,15,16,17));\n\t}\n\t\n\[email protected]\n\tpublic void testBasicBooking() { \n\t\t// almost standard booking for OOP and SISOP\n\t\tCoursesCalendar cc = new CoursesCalendarImpl();\n\t\tcc.bookRoom(MONDAY, VELA, 10, 3, \"OOP\");\n\t\tcc.bookRoom(TUESDAY, VELA, 14, 3, \"OOP\");\n\t\tcc.bookRoom(WEDNESDAY, MAGNA, 10, 3, \"OOP\");\n\t\tcc.bookRoom(THURSDAY, MAGNA, 14, 3, \"OOP\");\n\t\tcc.bookRoom(MONDAY, VELA, 14, 3, \"SISOP\");\n\t\tcc.bookRoom(TUESDAY, VELA, 9, 3, \"SISOP\");\n\t\tcc.bookRoom(WEDNESDAY, MAGNA, 14, 3, \"SISOP\");\n\t\tcc.bookRoom(FRIDAY, C_ALDO_MORO, 10, 3, \"SISOP\");\n\t\t\n\t\t// bookings in VELA on Monday\n\t\tSet<Pair<Integer,String>> set = cc.dayRoomSlots(MONDAY, VELA);\n\t\tassertEquals(set.size(),6);\n\t\tassertTrue(set.contains(new Pair<>(10,\"OOP\")));\n\t\tassertTrue(set.contains(new Pair<>(11,\"OOP\")));\n\t\tassertTrue(set.contains(new Pair<>(12,\"OOP\")));\n\t\tassertTrue(set.contains(new Pair<>(14,\"SISOP\")));\n\t\tassertTrue(set.contains(new Pair<>(15,\"SISOP\")));\n\t\tassertTrue(set.contains(new Pair<>(16,\"SISOP\")));\n\t\t\n\t\t// none in MAGNA on Monday\n\t\tassertEquals(cc.dayRoomSlots(MONDAY, MAGNA).size(),0);\n\t\t\n\t\t// OOP bookings: which ones on Thursday in MAGNA?\n\t\tSet<Integer> set2 = cc.courseSlots(\"OOP\").get(new Pair<>(THURSDAY,MAGNA));\n\t\tassertEquals(set2.size(),3);\n\t\tassertThat(set2,hasItems(14,15,16));\n\t}\n\t\n\[email protected]\n\tpublic void optionalTestJumpBooking() {\n\t\t// a 6-hour booking straddling lunch\n\t\tCoursesCalendar cc = new CoursesCalendarImpl();\n\t\tcc.bookRoom(MONDAY, VELA, 10, 6, \"OOP\");\n\t\t\n\t\tSet<Pair<Integer,String>> set = cc.dayRoomSlots(MONDAY, VELA);\n\t\tassertEquals(set.size(),6);\n\t\tassertTrue(set.contains(new Pair<>(10,\"OOP\")));\n\t\tassertTrue(set.contains(new Pair<>(11,\"OOP\")));\n\t\tassertTrue(set.contains(new Pair<>(12,\"OOP\")));\n\t\tassertTrue(set.contains(new Pair<>(14,\"OOP\")));\n\t\tassertTrue(set.contains(new Pair<>(15,\"OOP\")));\n\t\tassertTrue(set.contains(new Pair<>(16,\"OOP\")));\n\t}\n\t\n\[email protected]\n\tpublic void testConflictingBooking() { \n\t\t// example of two conflicting bookings\n\t\tCoursesCalendar cc = new CoursesCalendarImpl();\n\t\tcc.bookRoom(MONDAY, VELA, 10, 6, \"OOP\");\n\t\tassertEquals(cc.dayRoomSlots(MONDAY, VELA).size(),6);\n\t\ttry{\n\t\t\tcc.bookRoom(MONDAY, VELA, 9, 2, \"SISOP\");\n\t\t\tfail(\"cannot book with conflict from 16 to 17\");\n\t\t} catch (IllegalStateException e){}\n\t\t catch (Exception e){\n\t\t\t fail(\"wrong exception thrown\");\n\t\t}\n\t\t// being in conflict, SISOP doesn't book anything!!\n\t\tassertEquals(cc.dayRoomSlots(MONDAY, VELA).size(),6);\n\t}\n\t\n\t\n}", "filename": "Test.java" }
2015
a02a
[ { "content": "package ex2015.a02a.sol1;\n\nimport java.util.*;\n\n\npublic interface League {\n\t\n \n\tvoid addTeam(String teamName);\n\t\n\t\n\tvoid start();\n\t\n\t\n\tvoid storeResults(Map<Pair<String,String>,Pair<Integer,Integer>> results);\n\t\n\t\n\t\n Map<String,Integer> getTable();\n\t\n}", "filename": "League.java" }, { "content": "package ex2015.a02a.sol1;\n\n\n\npublic class Pair<X,Y> {\n\t\n\tprivate final X x;\n\tprivate final Y y;\n\t\n\tpublic Pair(X x, Y y) {\n\t\tsuper();\n\t\tthis.x = x;\n\t\tthis.y = y;\n\t}\n\n\tpublic X getX() {\n\t\treturn x;\n\t}\n\n\tpublic Y getY() {\n\t\treturn y;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = 1;\n\t\tresult = prime * result + ((x == null) ? 0 : x.hashCode());\n\t\tresult = prime * result + ((y == null) ? 0 : y.hashCode());\n\t\treturn result;\n\t}\n\n\t@SuppressWarnings(\"rawtypes\")\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (obj == null)\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tPair other = (Pair) obj;\n\t\tif (x == null) {\n\t\t\tif (other.x != null)\n\t\t\t\treturn false;\n\t\t} else if (!x.equals(other.x))\n\t\t\treturn false;\n\t\tif (y == null) {\n\t\t\tif (other.y != null)\n\t\t\t\treturn false;\n\t\t} else if (!y.equals(other.y))\n\t\t\treturn false;\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Pair [x=\" + x + \", y=\" + y + \"]\";\n\t}\n\t\n\t\n\n}", "filename": "Pair.java" } ]
[ { "content": "package ex2015.a02a.sol1;\n\nimport java.util.*;\nimport java.util.stream.*;\nimport java.util.function.*;\n\npublic class LeagueImpl implements League {\n\n private final Map<String, Integer> table = new HashMap<>();\n private boolean started = false;\n\n public LeagueImpl() {\n }\n\n private void checkAndRaise(boolean condition, Supplier<RuntimeException> supplier) {\n if (condition) {\n throw supplier.get();\n }\n }\n\n @Override\n public void addTeam(String teamName) {\n checkAndRaise(this.isStarted(), () -> new IllegalStateException());\n checkAndRaise(this.table.containsKey(Objects.requireNonNull(teamName)), () -> new IllegalArgumentException());\n this.table.put(teamName, 0);\n }\n\n private boolean isStarted() {\n return this.started;\n }\n\n @Override\n public void start() {\n checkAndRaise(this.isStarted(), () -> new IllegalStateException());\n this.started = true;\n }\n\n @Override\n public void storeResults(Map<Pair<String, String>, Pair<Integer, Integer>> results) {\n checkAndRaise(!this.isStarted(), () -> new IllegalStateException(\"not started yet\"));\n checkAndRaise(\n results.keySet().stream()\n .anyMatch((p) -> !this.table.containsKey(p.getX()) || !this.table.containsKey(p.getY())),\n () -> new IllegalArgumentException(\"wrong name\"));\n checkAndRaise(\n Stream.concat(results.keySet().stream().map(Pair::getX), results.keySet().stream().map(Pair::getY))\n .distinct().collect(Collectors.counting()) != this.table.size(),\n () -> new IllegalArgumentException(\"name clash\"));\n results.entrySet().forEach(e -> {\n this.updateScore(e.getKey().getX(), e.getValue().getX() - e.getValue().getY());\n this.updateScore(e.getKey().getY(), e.getValue().getY() - e.getValue().getX());\n });\n }\n\n private void updateScore(String teamName, int delta) {\n this.table.compute(teamName, (k, v) -> v + (delta == 0 ? 1 : delta > 0 ? 3 : 0));\n }\n\n @Override\n public Map<String, Integer> getTable() {\n checkAndRaise(!this.isStarted(), () -> new IllegalStateException(\"not started yet\"));\n return Collections.unmodifiableMap(this.table);\n }\n\n}", "filename": "LeagueImpl.java" } ]
{ "components": { "imports": "package ex2015.a02a.sol1;\n\nimport static org.junit.Assert.*;\nimport static org.hamcrest.CoreMatchers.*;\nimport java.util.*;", "private_init": "\t/*\n\t * Implement the League interface given through a LeagueImpl class with a constructor without arguments.\n\t * Model the manager of a football league, with a method to initially add the teams,\n\t * one to start the league, one to insert the results of a matchday, and finally one to retrieve the standings.\n\t * The comment to the League code, and the test methods below constitute the necessary explanation of the \n\t * problem.\n\t * Tests whose name begins with 'optional' are considered optional for the purpose of being able to correct\n\t * the exercise -- even if they contribute to the definition of the score.\n\t * Remove the comment from the tests..\n\t */\n\n private final static String INTER = \"Inter\";\n private final static String JUVE = \"Juve\";\n private final static String MILAN = \"Milan\";\n private final static String ROMA = \"Roma\";\n private final static String NAPOLI = \"Napoli\";\n private final static String LAZIO = \"Lazio\";\n \n // Method to build an initial league\n private League buildInitialLeague(){\n final League league = new LeagueImpl();\n league.addTeam(INTER);\n league.addTeam(JUVE);\n league.addTeam(MILAN);\n league.addTeam(ROMA);\n league.addTeam(NAPOLI);\n league.addTeam(LAZIO);\n return league;\n }", "test_functions": [ "\[email protected]\n\tpublic void testInitialTable() {\n\t\tfinal League league = buildInitialLeague();\n\t\tleague.start();\n\t\t// Standings: all at 0 initially\n\t\tassertEquals(league.getTable().size(),6);\n\t\tassertThat(league.getTable().keySet(),hasItems(INTER,JUVE,MILAN,ROMA,LAZIO,NAPOLI));\n\t\tassertThat(league.getTable().values(),hasItems(0,0,0,0,0,0));\n\t}", "\[email protected]\n public void testTwoResults() {\n final League league = buildInitialLeague();\n league.start();\n // construction of results of a matchday\n Map<Pair<String,String>,Pair<Integer,Integer>> res = new HashMap<>();\n res.put(new Pair<>(INTER,JUVE), new Pair<>(3,0)); // Inter 3, Juve 0\n res.put(new Pair<>(MILAN,ROMA), new Pair<>(0,0)); // Milan 0, Roma 0\n res.put(new Pair<>(LAZIO,NAPOLI), new Pair<>(0,1)); // Lazio 0, Napoli 1\n league.storeResults(res);\n // Read the new standings\n assertEquals(league.getTable().size(),6);\n assertThat(league.getTable().keySet(),hasItems(INTER,JUVE,MILAN,ROMA,LAZIO,NAPOLI));\n // Scores team by team\n assertEquals(league.getTable().get(INTER).intValue(),3);\n assertEquals(league.getTable().get(NAPOLI).intValue(),3);\n assertEquals(league.getTable().get(MILAN).intValue(),1);\n assertEquals(league.getTable().get(ROMA).intValue(),1);\n assertEquals(league.getTable().get(LAZIO).intValue(),0);\n assertEquals(league.getTable().get(JUVE).intValue(),0);\n \n // Other results\n res = new HashMap<>();\n res.put(new Pair<>(INTER,MILAN), new Pair<>(0,0));\n res.put(new Pair<>(JUVE,LAZIO), new Pair<>(3,3));\n res.put(new Pair<>(ROMA,NAPOLI), new Pair<>(2,2));\n league.storeResults(res);\n System.out.println(league.getTable());\n assertEquals(league.getTable().size(),6);\n assertThat(league.getTable().keySet(),hasItems(INTER,JUVE,MILAN,ROMA,LAZIO,NAPOLI));\n assertEquals(league.getTable().get(INTER).intValue(),4);\n assertEquals(league.getTable().get(NAPOLI).intValue(),4);\n assertEquals(league.getTable().get(MILAN).intValue(),2);\n assertEquals(league.getTable().get(ROMA).intValue(),2);\n assertEquals(league.getTable().get(LAZIO).intValue(),1);\n assertEquals(league.getTable().get(JUVE).intValue(),1);\n }", "\[email protected]\n public void testErrorsOnAdding() {\n final League league = buildInitialLeague();\n try{\n league.addTeam(null);\n fail(\"cannot add a null team\");\n }", "\[email protected]\n public void testErrorsOnStarted() {\n final League league = buildInitialLeague();\n // operations not possible before the league has started\n try{\n league.getTable();\n fail(\"cannot read table before started\");\n }", "\[email protected]\n public void optionalTestNameClash1() {\n final League league = buildInitialLeague();\n league.start();\n Map<Pair<String,String>,Pair<Integer,Integer>> res = new HashMap<>();\n res.put(new Pair<>(INTER,INTER), new Pair<>(3,0)); // NO!!!\n res.put(new Pair<>(MILAN,ROMA), new Pair<>(0,0));\n res.put(new Pair<>(LAZIO,NAPOLI), new Pair<>(0,1));\n try{\n league.storeResults(res);\n fail(\"a team can't play against itself\");\n }", "\[email protected]\n public void optionalTestNameClash2() {\n final League league = buildInitialLeague();\n league.start();\n Map<Pair<String,String>,Pair<Integer,Integer>> res = new HashMap<>();\n res.put(new Pair<>(INTER,JUVE), new Pair<>(3,0));\n res.put(new Pair<>(INTER,ROMA), new Pair<>(0,0)); // NO!!!\n res.put(new Pair<>(LAZIO,NAPOLI), new Pair<>(0,1));\n try{\n league.storeResults(res);\n fail(\"a team can't play twice\");\n }", "\[email protected]\n public void optionalTestNameClash3() {\n final League league = buildInitialLeague();\n league.start();\n Map<Pair<String,String>,Pair<Integer,Integer>> res = new HashMap<>();\n res.put(new Pair<>(INTER,JUVE), new Pair<>(3,0));\n res.put(new Pair<>(\"Cesena\",ROMA), new Pair<>(0,0)); // NO!!!\n res.put(new Pair<>(LAZIO,NAPOLI), new Pair<>(0,1));\n try{\n league.storeResults(res);\n fail(\"a team do not exist\");\n }" ] }, "content": "package ex2015.a02a.sol1;\n\nimport static org.junit.Assert.*;\nimport static org.hamcrest.CoreMatchers.*;\nimport java.util.*;\n\npublic class Test {\n\t\n\t/*\n\t * Implement the League interface given through a LeagueImpl class with a constructor without arguments.\n\t * Model the manager of a football league, with a method to initially add the teams,\n\t * one to start the league, one to insert the results of a matchday, and finally one to retrieve the standings.\n\t * The comment to the League code, and the test methods below constitute the necessary explanation of the \n\t * problem.\n\t * Tests whose name begins with 'optional' are considered optional for the purpose of being able to correct\n\t * the exercise -- even if they contribute to the definition of the score.\n\t * Remove the comment from the tests..\n\t */\n\n private final static String INTER = \"Inter\";\n private final static String JUVE = \"Juve\";\n private final static String MILAN = \"Milan\";\n private final static String ROMA = \"Roma\";\n private final static String NAPOLI = \"Napoli\";\n private final static String LAZIO = \"Lazio\";\n \n // Method to build an initial league\n private League buildInitialLeague(){\n final League league = new LeagueImpl();\n league.addTeam(INTER);\n league.addTeam(JUVE);\n league.addTeam(MILAN);\n league.addTeam(ROMA);\n league.addTeam(NAPOLI);\n league.addTeam(LAZIO);\n return league;\n }\n \n @org.junit.Test\n\tpublic void testInitialTable() {\n\t\tfinal League league = buildInitialLeague();\n\t\tleague.start();\n\t\t// Standings: all at 0 initially\n\t\tassertEquals(league.getTable().size(),6);\n\t\tassertThat(league.getTable().keySet(),hasItems(INTER,JUVE,MILAN,ROMA,LAZIO,NAPOLI));\n\t\tassertThat(league.getTable().values(),hasItems(0,0,0,0,0,0));\n\t}\n\t\n @org.junit.Test\n public void testTwoResults() {\n final League league = buildInitialLeague();\n league.start();\n // construction of results of a matchday\n Map<Pair<String,String>,Pair<Integer,Integer>> res = new HashMap<>();\n res.put(new Pair<>(INTER,JUVE), new Pair<>(3,0)); // Inter 3, Juve 0\n res.put(new Pair<>(MILAN,ROMA), new Pair<>(0,0)); // Milan 0, Roma 0\n res.put(new Pair<>(LAZIO,NAPOLI), new Pair<>(0,1)); // Lazio 0, Napoli 1\n league.storeResults(res);\n // Read the new standings\n assertEquals(league.getTable().size(),6);\n assertThat(league.getTable().keySet(),hasItems(INTER,JUVE,MILAN,ROMA,LAZIO,NAPOLI));\n // Scores team by team\n assertEquals(league.getTable().get(INTER).intValue(),3);\n assertEquals(league.getTable().get(NAPOLI).intValue(),3);\n assertEquals(league.getTable().get(MILAN).intValue(),1);\n assertEquals(league.getTable().get(ROMA).intValue(),1);\n assertEquals(league.getTable().get(LAZIO).intValue(),0);\n assertEquals(league.getTable().get(JUVE).intValue(),0);\n \n // Other results\n res = new HashMap<>();\n res.put(new Pair<>(INTER,MILAN), new Pair<>(0,0));\n res.put(new Pair<>(JUVE,LAZIO), new Pair<>(3,3));\n res.put(new Pair<>(ROMA,NAPOLI), new Pair<>(2,2));\n league.storeResults(res);\n System.out.println(league.getTable());\n assertEquals(league.getTable().size(),6);\n assertThat(league.getTable().keySet(),hasItems(INTER,JUVE,MILAN,ROMA,LAZIO,NAPOLI));\n assertEquals(league.getTable().get(INTER).intValue(),4);\n assertEquals(league.getTable().get(NAPOLI).intValue(),4);\n assertEquals(league.getTable().get(MILAN).intValue(),2);\n assertEquals(league.getTable().get(ROMA).intValue(),2);\n assertEquals(league.getTable().get(LAZIO).intValue(),1);\n assertEquals(league.getTable().get(JUVE).intValue(),1);\n }\n \n @org.junit.Test\n public void testErrorsOnAdding() {\n final League league = buildInitialLeague();\n try{\n league.addTeam(null);\n fail(\"cannot add a null team\");\n } catch (NullPointerException e){\n } catch (Exception e){\n fail(\"wrong exception thrown\");\n }\n try{\n league.addTeam(INTER);\n fail(\"cannot add a team twice\");\n } catch (IllegalArgumentException e){\n } catch (Exception e){\n fail(\"wrong exception thrown\");\n }\n }\n \n @org.junit.Test\n public void testErrorsOnStarted() {\n final League league = buildInitialLeague();\n // operations not possible before the league has started\n try{\n league.getTable();\n fail(\"cannot read table before started\");\n } catch (IllegalStateException e){\n } catch (Exception e){\n fail(\"wrong exception thrown\");\n }\n try{\n league.storeResults(null);\n fail(\"cannot store results before started\");\n } catch (IllegalStateException e){\n }catch (Exception e){\n fail(\"wrong exception thrown\");\n }\n league.start();\n // operations not possible after the league has started\n try{\n league.addTeam(\"Cesena\");\n fail(\"cannot add a team once started\");\n } catch (IllegalStateException e){\n } catch (Exception e){\n fail(\"wrong exception thrown\");\n }\n }\n \n @org.junit.Test\n public void optionalTestNameClash1() {\n final League league = buildInitialLeague();\n league.start();\n Map<Pair<String,String>,Pair<Integer,Integer>> res = new HashMap<>();\n res.put(new Pair<>(INTER,INTER), new Pair<>(3,0)); // NO!!!\n res.put(new Pair<>(MILAN,ROMA), new Pair<>(0,0));\n res.put(new Pair<>(LAZIO,NAPOLI), new Pair<>(0,1));\n try{\n league.storeResults(res);\n fail(\"a team can't play against itself\");\n } catch (IllegalArgumentException e){\n } catch (Exception e){\n fail(\"wrong exception thrown\");\n }\n }\n \n @org.junit.Test\n public void optionalTestNameClash2() {\n final League league = buildInitialLeague();\n league.start();\n Map<Pair<String,String>,Pair<Integer,Integer>> res = new HashMap<>();\n res.put(new Pair<>(INTER,JUVE), new Pair<>(3,0));\n res.put(new Pair<>(INTER,ROMA), new Pair<>(0,0)); // NO!!!\n res.put(new Pair<>(LAZIO,NAPOLI), new Pair<>(0,1));\n try{\n league.storeResults(res);\n fail(\"a team can't play twice\");\n } catch (IllegalArgumentException e){\n } catch (Exception e){\n fail(\"wrong exception thrown\");\n }\n }\n \n @org.junit.Test\n public void optionalTestNameClash3() {\n final League league = buildInitialLeague();\n league.start();\n Map<Pair<String,String>,Pair<Integer,Integer>> res = new HashMap<>();\n res.put(new Pair<>(INTER,JUVE), new Pair<>(3,0));\n res.put(new Pair<>(\"Cesena\",ROMA), new Pair<>(0,0)); // NO!!!\n res.put(new Pair<>(LAZIO,NAPOLI), new Pair<>(0,1));\n try{\n league.storeResults(res);\n fail(\"a team do not exist\");\n } catch (IllegalArgumentException e){\n } catch (Exception e){\n fail(\"wrong exception thrown\");\n }\n }\n}", "filename": "Test.java" }
2015
a05
[ { "content": "package ex2015.a05.sol1;\n\nimport java.util.List;\n\n\npublic interface CList<X> {\n \n \n int size();\n \n \n X getElem(int pos);\n \n \n boolean contains(X x);\n \n \n CList<X> add(X x, int pos);\n \n \n CList<X> shift(int pos);\n\n \n \n List<X> toList();\n}", "filename": "CList.java" }, { "content": "package ex2015.a05.sol1;\n\nimport java.util.List;\n\n\npublic interface CListFactory<X> {\n \n \n \n CList<X> emptyCList();\n \n \n CList<X> consCList(List<X> elements);\n\n}", "filename": "CListFactory.java" } ]
[ { "content": "package ex2015.a05.sol1;\n\nimport java.util.Collections;\nimport java.util.LinkedList;\nimport java.util.List;\n\npublic class CListImpl<X> implements CList<X> {\n \n private List<X> elements;\n private int pos;\n \n CListImpl(List<X> elements, int pos) {\n this.elements = elements;\n this.pos = pos;\n }\n \n private int relativePos(int pos){\n return (pos+this.pos) % this.elements.size();\n }\n\n @Override\n public int size() {\n return this.elements.size();\n }\n\n @Override\n public X getElem(int pos) {\n return this.elements.get(this.relativePos(pos));\n }\n\n @Override\n public boolean contains(X x) {\n return this.elements.contains(x);\n }\n\n @Override\n public CList<X> add(X x, int pos) {\n int p = this.relativePos(pos);\n List<X> l = new LinkedList<X>(this.elements);\n l.add(p, x);\n return new CListImpl<>(l,p);\n }\n\n @Override\n public CList<X> shift(int pos) {\n return new CListImpl<>(this.elements,this.relativePos(pos));\n }\n\n @Override\n public List<X> toList() {\n List<X> l = new LinkedList<>(this.elements);\n Collections.rotate(l,-this.pos);\n return l;\n }\n\n @Override\n public String toString() {\n return \"CListImpl [elements=\" + elements + \", pos=\" + pos + \"]\";\n }\n \n \n\n}", "filename": "CListImpl.java" }, { "content": "package ex2015.a05.sol1;\n\nimport java.util.Collections;\nimport java.util.List;\n\npublic class CListFactoryImpl<X> implements CListFactory<X> {\n\n @Override\n public CList<X> emptyCList() {\n return consCList(Collections.emptyList());\n }\n\n @Override\n public CList<X> consCList(List<X> elements) {\n return new CListImpl<>(elements,0);\n }\n\n}", "filename": "CListFactoryImpl.java" }, { "content": "package ex2015.a05.sol1;\n\n/*\n * A standard generic Pair<X,Y>, with getters, hashCode, equals, and toString well implemented. \n */\n\npublic class Pair<X,Y> {\n\t\n\tprivate final X x;\n\tprivate final Y y;\n\t\n\tpublic Pair(X x, Y y) {\n\t\tsuper();\n\t\tthis.x = x;\n\t\tthis.y = y;\n\t}\n\n\tpublic X getX() {\n\t\treturn x;\n\t}\n\n\tpublic Y getY() {\n\t\treturn y;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = 1;\n\t\tresult = prime * result + ((x == null) ? 0 : x.hashCode());\n\t\tresult = prime * result + ((y == null) ? 0 : y.hashCode());\n\t\treturn result;\n\t}\n\n\t@SuppressWarnings(\"rawtypes\")\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (obj == null)\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tPair other = (Pair) obj;\n\t\tif (x == null) {\n\t\t\tif (other.x != null)\n\t\t\t\treturn false;\n\t\t} else if (!x.equals(other.x))\n\t\t\treturn false;\n\t\tif (y == null) {\n\t\t\tif (other.y != null)\n\t\t\t\treturn false;\n\t\t} else if (!y.equals(other.y))\n\t\t\treturn false;\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Pair [x=\" + x + \", y=\" + y + \"]\";\n\t}\n\t\n\t\n\n}", "filename": "Pair.java" } ]
{ "components": { "imports": "package ex2015.a05.sol1;\n\nimport static org.junit.Assert.*;\n\nimport java.util.*;\n\n/**\n * Implement the CListFactory interface with a CListFactoryImpl class with an empty constructor,\n * which implements a Factory for immutable cyclic lists, which adhere to the generic CList interface provided\n * (for example, do this by also constructing a CListImpl class that implements CList).\n * An immutable cyclic list is a list whose last element has the first element of the list as its next element.\n * The factory has a method to generate empty cyclic lists, and one to generate a cyclic list from\n * a list.\n *\n * Pay close attention to the following test, which together with the comments of the given interfaces\n * constitutes the definition of the problem to be solved.\n *\n * The second test is considered optional for the purpose of being able to correct\n * the exercise -- even if it contributes to the definition of the score. Furthermore, try\n * to adopt as much as possible the sharing of structures between different cyclic lists.\n *\n * Remove the comment from the test code.\n */", "private_init": "\t", "test_functions": [ "\[email protected]\n public void testBasic() {\n CListFactory<String> cf = new CListFactoryImpl<>();\n\n CList<String> cl = cf.consCList(Arrays.asList(\"a\",\"b\",\"c\")); // a,b,c,a,b,c,a,b,c,..\n\n assertEquals(cl.size(),3);\n assertEquals(cl.getElem(0),\"a\");\n assertEquals(cl.getElem(1),\"b\");\n assertEquals(cl.getElem(2),\"c\");\n assertEquals(cl.getElem(3),\"a\");\n assertEquals(cl.getElem(4),\"b\");\n assertEquals(cl.getElem(9),\"a\");\n\n assertTrue(cl.contains(\"a\"));\n assertTrue(cl.contains(\"b\"));\n assertTrue(cl.contains(\"c\"));\n assertFalse(cl.contains(\"d\"));\n\n assertEquals(cl.toList(),Arrays.asList(\"a\",\"b\",\"c\"));\n\n CList<String> cl2 = cl.shift(1); // b,c,a,b,c,a,b,c,a,b,c,...\n assertEquals(cl2.size(),3);\n assertEquals(cl2.getElem(0),\"b\");\n assertEquals(cl2.getElem(1),\"c\");\n assertEquals(cl2.getElem(2),\"a\");\n assertEquals(cl2.getElem(3),\"b\");\n assertEquals(cl2.getElem(4),\"c\");\n assertEquals(cl2.getElem(9),\"b\");\n\n assertTrue(cl2.contains(\"a\"));\n assertTrue(cl2.contains(\"b\"));\n assertTrue(cl2.contains(\"c\"));\n assertFalse(cl2.contains(\"d\"));\n\n assertEquals(cl2.toList(),Arrays.asList(\"b\",\"c\",\"a\"));\n\n CList<String> cl3 = cl.shift(2); // c,a,b,c,a,b,c,a,b,c,...\n assertEquals(cl3.size(),3);\n assertEquals(cl3.getElem(0),\"c\");\n assertEquals(cl3.getElem(1),\"a\");\n assertEquals(cl3.getElem(2),\"b\");\n assertEquals(cl3.getElem(3),\"c\");\n assertEquals(cl3.getElem(4),\"a\");\n assertEquals(cl3.getElem(9),\"c\");\n\n assertTrue(cl3.contains(\"a\"));\n assertTrue(cl3.contains(\"b\"));\n assertTrue(cl3.contains(\"c\"));\n assertFalse(cl3.contains(\"d\"));\n\n assertEquals(cl3.toList(),Arrays.asList(\"c\",\"a\",\"b\"));\n\n\n }", "\[email protected]\n public void optionalTest1() {\n CListFactory<String> cf = new CListFactoryImpl<>();\n\n CList<String> cl = cf.consCList(Arrays.asList(\"a\",\"b\",\"c\")); // a,b,c,a,b,c,a,b,c,..\n CList<String> cl2 = cl.add(\"?\",1); // ?,b,c,a,?,b,c,a,..\n\n assertEquals(cl2.size(),4);\n assertEquals(cl2.getElem(0),\"?\");\n assertEquals(cl2.getElem(1),\"b\");\n assertEquals(cl2.getElem(2),\"c\");\n assertEquals(cl2.getElem(3),\"a\");\n assertEquals(cl2.getElem(4),\"?\");\n assertEquals(cl2.getElem(5),\"b\");\n\n assertTrue(cl2.contains(\"a\"));\n assertTrue(cl2.contains(\"b\"));\n assertTrue(cl2.contains(\"c\"));\n assertTrue(cl2.contains(\"?\"));\n assertFalse(cl2.contains(\"d\"));\n\n assertEquals(cl2.toList(),Arrays.asList(\"?\",\"b\",\"c\",\"a\"));\n\n CList<String> cl3 = cf.emptyCList();\n assertEquals(cl3.size(),0);\n\n assertFalse(cl3.contains(\"a\"));\n\n assertTrue(cl3.toList().isEmpty());\n\n }" ] }, "content": "package ex2015.a05.sol1;\n\nimport static org.junit.Assert.*;\n\nimport java.util.*;\n\n/**\n * Implement the CListFactory interface with a CListFactoryImpl class with an empty constructor,\n * which implements a Factory for immutable cyclic lists, which adhere to the generic CList interface provided\n * (for example, do this by also constructing a CListImpl class that implements CList).\n * An immutable cyclic list is a list whose last element has the first element of the list as its next element.\n * The factory has a method to generate empty cyclic lists, and one to generate a cyclic list from\n * a list.\n *\n * Pay close attention to the following test, which together with the comments of the given interfaces\n * constitutes the definition of the problem to be solved.\n *\n * The second test is considered optional for the purpose of being able to correct\n * the exercise -- even if it contributes to the definition of the score. Furthermore, try\n * to adopt as much as possible the sharing of structures between different cyclic lists.\n *\n * Remove the comment from the test code.\n */\n\npublic class Test {\n\n @org.junit.Test\n public void testBasic() {\n CListFactory<String> cf = new CListFactoryImpl<>();\n\n CList<String> cl = cf.consCList(Arrays.asList(\"a\",\"b\",\"c\")); // a,b,c,a,b,c,a,b,c,..\n\n assertEquals(cl.size(),3);\n assertEquals(cl.getElem(0),\"a\");\n assertEquals(cl.getElem(1),\"b\");\n assertEquals(cl.getElem(2),\"c\");\n assertEquals(cl.getElem(3),\"a\");\n assertEquals(cl.getElem(4),\"b\");\n assertEquals(cl.getElem(9),\"a\");\n\n assertTrue(cl.contains(\"a\"));\n assertTrue(cl.contains(\"b\"));\n assertTrue(cl.contains(\"c\"));\n assertFalse(cl.contains(\"d\"));\n\n assertEquals(cl.toList(),Arrays.asList(\"a\",\"b\",\"c\"));\n\n CList<String> cl2 = cl.shift(1); // b,c,a,b,c,a,b,c,a,b,c,...\n assertEquals(cl2.size(),3);\n assertEquals(cl2.getElem(0),\"b\");\n assertEquals(cl2.getElem(1),\"c\");\n assertEquals(cl2.getElem(2),\"a\");\n assertEquals(cl2.getElem(3),\"b\");\n assertEquals(cl2.getElem(4),\"c\");\n assertEquals(cl2.getElem(9),\"b\");\n\n assertTrue(cl2.contains(\"a\"));\n assertTrue(cl2.contains(\"b\"));\n assertTrue(cl2.contains(\"c\"));\n assertFalse(cl2.contains(\"d\"));\n\n assertEquals(cl2.toList(),Arrays.asList(\"b\",\"c\",\"a\"));\n\n CList<String> cl3 = cl.shift(2); // c,a,b,c,a,b,c,a,b,c,...\n assertEquals(cl3.size(),3);\n assertEquals(cl3.getElem(0),\"c\");\n assertEquals(cl3.getElem(1),\"a\");\n assertEquals(cl3.getElem(2),\"b\");\n assertEquals(cl3.getElem(3),\"c\");\n assertEquals(cl3.getElem(4),\"a\");\n assertEquals(cl3.getElem(9),\"c\");\n\n assertTrue(cl3.contains(\"a\"));\n assertTrue(cl3.contains(\"b\"));\n assertTrue(cl3.contains(\"c\"));\n assertFalse(cl3.contains(\"d\"));\n\n assertEquals(cl3.toList(),Arrays.asList(\"c\",\"a\",\"b\"));\n\n\n }\n\n @org.junit.Test\n public void optionalTest1() {\n CListFactory<String> cf = new CListFactoryImpl<>();\n\n CList<String> cl = cf.consCList(Arrays.asList(\"a\",\"b\",\"c\")); // a,b,c,a,b,c,a,b,c,..\n CList<String> cl2 = cl.add(\"?\",1); // ?,b,c,a,?,b,c,a,..\n\n assertEquals(cl2.size(),4);\n assertEquals(cl2.getElem(0),\"?\");\n assertEquals(cl2.getElem(1),\"b\");\n assertEquals(cl2.getElem(2),\"c\");\n assertEquals(cl2.getElem(3),\"a\");\n assertEquals(cl2.getElem(4),\"?\");\n assertEquals(cl2.getElem(5),\"b\");\n\n assertTrue(cl2.contains(\"a\"));\n assertTrue(cl2.contains(\"b\"));\n assertTrue(cl2.contains(\"c\"));\n assertTrue(cl2.contains(\"?\"));\n assertFalse(cl2.contains(\"d\"));\n\n assertEquals(cl2.toList(),Arrays.asList(\"?\",\"b\",\"c\",\"a\"));\n\n CList<String> cl3 = cf.emptyCList();\n assertEquals(cl3.size(),0);\n\n assertFalse(cl3.contains(\"a\"));\n\n assertTrue(cl3.toList().isEmpty());\n\n }\n\n\n}", "filename": "Test.java" }
End of preview. Expand in Data Studio

JAB: Java Academic Benchmark

Overview

The Java Academic Benchmark (JAB) is the first exam-based benchmark specifically designed to rigorously evaluate Large Language Models (LLMs) on Java Object-Oriented Programming (OOP) capabilities.

JAB comprises 103 real Java exams administered between 2014 and 2024 at a top-tier academic institution, designed and curated by Professor Mirko Viroli, an experienced full professor and co-author of this project. This ensures that each task reflects pedagogically grounded and conceptually meaningful challenges.

Unlike benchmarks that focus on isolated code snippets, JAB features full exam-style problems with expert-authored JUnit test suites, targeting class- and interface-level reasoning. Designed to assess human learners, these problems isolate common misconceptions and test deep understanding, offering granular insights into where and how models fall short.

Dataset Structure

Each exam in the JAB dataset is structured as follows:

  • year: Year of the exam session
  • session: Specific session identifier
  • utility_classes: Utility classes provided to students during the exam
  • solution: Gold solution created by Prof. Viroli (one of many possible solutions)
  • test: JUnit test cases that must be passed

Benchmark Significance

JAB offers several unique advantages for evaluating LLMs on Java programming tasks:

  1. Educational Validity: Problems are designed by education experts to test conceptual understanding
  2. Comprehensive Assessment: Tasks require full class implementations rather than just completing isolated functions
  3. Object-Oriented Focus: Specifically targets OOP concepts including inheritance, polymorphism, encapsulation, and interfaces
  4. Longitudinal Coverage: Spans a decade of real academic assessments (2014-2024)
  5. Test-Driven Evaluation: Uses rigorous JUnit test suites for objective assessment

License

This dataset is licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0) license.

You are free to:

  • Share — copy and redistribute the material in any medium or format

Under the following terms:

  • Attribution — You must give appropriate credit (see below), provide a link to the license, and indicate if changes were made.
  • NonCommercial — You may not use the material for commercial purposes.
  • NoDerivatives — If you remix, transform, or build upon the material, you may not distribute the modified material.

For details, see: https://creativecommons.org/licenses/by-nc-nd/4.0/

Dataset Owner: Mirko Viroli
License Notice: © Mirko Viroli — CC BY-NC-ND 4.0

Citation

If you use JAB in your research, please cite:

<bib of our future paper>

Contact

For questions or further information about the JAB benchmark, please contact:

Downloads last month
11