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" }
2015
a01c
[ { "content": "package ex2015.a01c.sol1;\n\npublic interface MapFactory {\n\t\n\t\n\t<K,V> MultiMap<K,V> empty();\n\t\n\t\n\t<K,V> MultiMap<K,V> unmodifiable(MultiMap<K,V> mmap);\n\n}", "filename": "MapFactory.java" }, { "content": "package ex2015.a01c.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.a01c.sol1;\n\nimport java.util.*;\n\n\npublic interface MultiMap<K,V> {\n\t\n\t\n\tvoid add(K key, V value);\n\t\t\n\t\n\tvoid add(K key, Iterable<V> values);\n\t\t\n\t\n\tSet<V> get(K key);\n\t\n\t\n\tSet<Pair<K,V>> entrySet();\n\t\n\t\n\tSet<K> keys();\n\n}", "filename": "MultiMap.java" } ]
[ { "content": "package ex2015.a01c.sol1;\n\nimport java.util.*;\nimport java.util.stream.*;\n\n\npublic class MultiMapImpl<K,V> implements MultiMap<K, V> {\n\n\tprivate Map<K,Set<V>> mmap = new HashMap<>();\n\t\t\n\tprivate void prepareAddition(K key){\n\t\tthis.mmap.merge(key, new HashSet<>(), (x,y)->x);\n\t}\n\t\t\n\t@Override\n\tpublic void add(K key, V value) {\n\t\tthis.prepareAddition(key);\n\t\tthis.mmap.get(key).add(value);\n\t}\n\n\t@Override\n\tpublic void add(K key, Iterable<V> values) {\n\t\tthis.prepareAddition(key);\n\t\tfinal Set<V> set = this.mmap.get(key);\n\t\tvalues.forEach(v -> set.add(v));\n\t}\n\n\t@Override\n\tpublic Set<V> get(K key) {\n\t\tif (mmap.containsKey(key)){\n\t\t\treturn new HashSet<>(mmap.get(key));\n\t\t}\n\t\treturn new HashSet<>();\n\t}\n\n\t@Override\n\tpublic Set<Pair<K, V>> entrySet() {\n\t\treturn this.mmap.keySet().stream().flatMap(k->this.mmap.get(k).stream().map(v->new Pair<>(k,v))).collect(Collectors.toSet());\n\t}\n\n\t@Override\n\tpublic Set<K> keys() {\n\t\treturn this.mmap.keySet();\n\t}\n}", "filename": "MultiMapImpl.java" }, { "content": "package ex2015.a01c.sol1;\n\nimport java.util.*;\n\npublic class MapFactoryImpl implements MapFactory {\n\n\t@Override\n\tpublic <K, V> MultiMap<K, V> empty() {\n\t\treturn new MultiMapImpl<>();\n\t}\n\n\t@Override\n\tpublic <K, V> MultiMap<K, V> unmodifiable(MultiMap<K, V> mmap) {\n\t\tMultiMap<K,V> mmap2 = new MultiMapImpl<>();\n\t\tmmap.entrySet().forEach(p->mmap2.add(p.getX(), p.getY()));\n\t\treturn new MultiMap<K,V>(){\n\n\t\t\t@Override\n\t\t\tpublic void add(K key, V value) {\n\t\t\t\tthrow new UnsupportedOperationException();\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void add(K key, Iterable<V> values) {\n\t\t\t\tthrow new UnsupportedOperationException();\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Set<V> get(K key) {\n\t\t\t\treturn mmap2.get(key);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Set<Pair<K, V>> entrySet() {\n\t\t\t\treturn mmap2.entrySet();\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Set<K> keys() {\n\t\t\t\treturn mmap2.keys();\n\t\t\t}\n\t\t\t\n\t\t};\n\t}\n\n\n}", "filename": "MapFactoryImpl.java" } ]
{ "components": { "imports": "package ex2015.a01c.sol1;\n\nimport static org.junit.Assert.*;\nimport static org.hamcrest.CoreMatchers.*;\n\nimport java.util.*;", "private_init": "\t/*\n\t * Implement the MultiMap interface through a MultiMapImpl class with a constructor without arguments.\n\t * Model a multi-map data type, i.e., a key->value map, where a key can appear\n\t * multiple times, i.e., it can have multiple associated values (without order).\n\t * Additionally, implement MapFactory through a MapFactoryImpl class with a constructor without arguments.\n\t * This models a factory to generate two multi-maps, one empty, and one unmodifiable starting\n\t * from a modifiable one -- i.e., it must throw an UnsupportedOperationException if one tries to add\n\t * elements.\n\t * The comment to the provided code, and the test methods below constitute the necessary explanation of the\n\t * problem.\n\t * Tests whose name starts 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 testKeys() {\n\t\t// adding few associations and testing if keys() works\n\t\tMultiMap<String,Integer> mmap = new MultiMapImpl<>();\n\t\tassertTrue(mmap.keys().isEmpty());\n\t\tmmap.add(\"a\", 10);\n\t\tmmap.add(\"a\", 20);\n\t\tmmap.add(\"a\", 30);\n\t\tmmap.add(\"b\", 10);\n\t\tmmap.add(\"b\", 11);\n\t\tassertEquals(mmap.keys().size(),2);\n\t\tassertThat(mmap.keys(),hasItems(\"a\",\"b\"));\n\t}", "\[email protected]\n\tpublic void testGet() {\n\t\t// adding few associations and testing if gets() works\n\t\tMultiMap<String,Integer> mmap = new MultiMapImpl<>();\n\t\tmmap.add(\"a\", 10);\n\t\tmmap.add(\"a\", 20);\n\t\tmmap.add(\"a\", 30);\n\t\tmmap.add(\"b\", 10);\n\t\tmmap.add(\"b\", 11);\n\t\tassertEquals(mmap.get(\"a\").size(),3);\n\t\tassertThat(mmap.get(\"a\"),hasItems(10,20,30));\n\t\tassertEquals(mmap.get(\"b\").size(),2);\n\t\tassertThat(mmap.get(\"b\"),hasItems(10,11));\n\t\t// adding twice an association has no effect\n\t\tmmap.add(\"b\", 11);\n\t\tassertEquals(mmap.get(\"b\").size(),2);\n\t\tassertThat(mmap.get(\"b\"),hasItems(10,11));\n\t}", "\[email protected]\n\tpublic void testEntries() {\n\t\t// adding few associations and testing if entrySet() works\n\t\tMultiMap<String,Integer> mmap = new MultiMapImpl<>();\n\t\tmmap.add(\"a\", 10);\n\t\tmmap.add(\"a\", 20);\n\t\tmmap.add(\"a\", 30);\n\t\tmmap.add(\"b\", 10);\n\t\tmmap.add(\"b\", 11);\n\t\tassertEquals(mmap.entrySet().size(),5);\n\t\tassertThat(mmap.entrySet(),hasItems(\n\t\t\t\tnew Pair<>(\"a\",10),\n\t\t\t\tnew Pair<>(\"a\",20),\n\t\t\t\tnew Pair<>(\"a\",30),\n\t\t\t\tnew Pair<>(\"b\",10),\n\t\t\t\tnew Pair<>(\"b\",11)));\t\t\n\t}", "\[email protected]\n\tpublic void testGetIsDefended() {\n\t\t// The set provided by get should be a defensive copy!!\n\t\tMultiMap<String,Integer> mmap = new MultiMapImpl<>();\n\t\tmmap.add(\"a\", 10);\n\t\tmmap.add(\"a\", 20);\n\t\tmmap.add(\"a\", 30);\n\t\tmmap.add(\"b\", 10);\n\t\tmmap.add(\"b\", 11);\n\t\tSet<Integer> set = mmap.get(\"a\");\n\t\tassertEquals(set.size(),3);\n\t\tassertThat(set,hasItems(10,20,30));\n\t\t// adding 40 to set has no effect on mmap\n\t\tset.add(40);\n\t\tassertEquals(mmap.entrySet().size(),5);\n\t}", "\[email protected]\n\tpublic void optionalTestEmpty() {\n\t\t// Simple test of empty on the factory\n\t\tMapFactory fact = new MapFactoryImpl();\n\t\tMultiMap<String,Integer> mmap = fact.empty();\n\t\tassertEquals(mmap.entrySet().size(),0);\n\t}", "\[email protected]\n\tpublic void optionalTestUnmodifiable() {\n\t\t// Testing cloning and unmodifiability of the factory method\n\t\tMultiMap<String,Integer> mmap = new MultiMapImpl<>();\n\t\tmmap.add(\"a\", 10);\n\t\tmmap.add(\"a\", 20);\n\t\tmmap.add(\"a\", 30);\n\t\tmmap.add(\"b\", 10);\n\t\tmmap.add(\"b\", 11);\n\t\tMapFactory fact = new MapFactoryImpl();\n\t\t// mmap2 as an unmodificable clone of mmap\n\t\tMultiMap<String,Integer> mmap2 = fact.unmodifiable(mmap);\n\t\t// changing mmap has no effect on mmap2\n\t\tmmap.add(\"b\", 12);\n\t\tassertEquals(mmap.entrySet().size(),6);\n\t\tassertEquals(mmap2.entrySet().size(),5);\n\t\t// trying to add something to mmap2 throws an exception\n\t\ttry{\n\t\t\tmmap2.add(\"b\", 13);\n\t\t\tfail(\"adding to an unmodifiable-multi-map should raise an exception!\");\n\t\t}" ] }, "content": "package ex2015.a01c.sol1;\n\nimport static org.junit.Assert.*;\nimport static org.hamcrest.CoreMatchers.*;\n\nimport java.util.*;\n\npublic class Test {\n\t\n\t/*\n\t * Implement the MultiMap interface through a MultiMapImpl class with a constructor without arguments.\n\t * Model a multi-map data type, i.e., a key->value map, where a key can appear\n\t * multiple times, i.e., it can have multiple associated values (without order).\n\t * Additionally, implement MapFactory through a MapFactoryImpl class with a constructor without arguments.\n\t * This models a factory to generate two multi-maps, one empty, and one unmodifiable starting\n\t * from a modifiable one -- i.e., it must throw an UnsupportedOperationException if one tries to add\n\t * elements.\n\t * The comment to the provided code, and the test methods below constitute the necessary explanation of the\n\t * problem.\n\t * Tests whose name starts 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 testKeys() {\n\t\t// adding few associations and testing if keys() works\n\t\tMultiMap<String,Integer> mmap = new MultiMapImpl<>();\n\t\tassertTrue(mmap.keys().isEmpty());\n\t\tmmap.add(\"a\", 10);\n\t\tmmap.add(\"a\", 20);\n\t\tmmap.add(\"a\", 30);\n\t\tmmap.add(\"b\", 10);\n\t\tmmap.add(\"b\", 11);\n\t\tassertEquals(mmap.keys().size(),2);\n\t\tassertThat(mmap.keys(),hasItems(\"a\",\"b\"));\n\t}\n\t\n\[email protected]\n\tpublic void testGet() {\n\t\t// adding few associations and testing if gets() works\n\t\tMultiMap<String,Integer> mmap = new MultiMapImpl<>();\n\t\tmmap.add(\"a\", 10);\n\t\tmmap.add(\"a\", 20);\n\t\tmmap.add(\"a\", 30);\n\t\tmmap.add(\"b\", 10);\n\t\tmmap.add(\"b\", 11);\n\t\tassertEquals(mmap.get(\"a\").size(),3);\n\t\tassertThat(mmap.get(\"a\"),hasItems(10,20,30));\n\t\tassertEquals(mmap.get(\"b\").size(),2);\n\t\tassertThat(mmap.get(\"b\"),hasItems(10,11));\n\t\t// adding twice an association has no effect\n\t\tmmap.add(\"b\", 11);\n\t\tassertEquals(mmap.get(\"b\").size(),2);\n\t\tassertThat(mmap.get(\"b\"),hasItems(10,11));\n\t}\n\t\n\t@SuppressWarnings(\"unchecked\")\n\[email protected]\n\tpublic void testEntries() {\n\t\t// adding few associations and testing if entrySet() works\n\t\tMultiMap<String,Integer> mmap = new MultiMapImpl<>();\n\t\tmmap.add(\"a\", 10);\n\t\tmmap.add(\"a\", 20);\n\t\tmmap.add(\"a\", 30);\n\t\tmmap.add(\"b\", 10);\n\t\tmmap.add(\"b\", 11);\n\t\tassertEquals(mmap.entrySet().size(),5);\n\t\tassertThat(mmap.entrySet(),hasItems(\n\t\t\t\tnew Pair<>(\"a\",10),\n\t\t\t\tnew Pair<>(\"a\",20),\n\t\t\t\tnew Pair<>(\"a\",30),\n\t\t\t\tnew Pair<>(\"b\",10),\n\t\t\t\tnew Pair<>(\"b\",11)));\t\t\n\t}\n\t\n\[email protected]\n\tpublic void testGetIsDefended() {\n\t\t// The set provided by get should be a defensive copy!!\n\t\tMultiMap<String,Integer> mmap = new MultiMapImpl<>();\n\t\tmmap.add(\"a\", 10);\n\t\tmmap.add(\"a\", 20);\n\t\tmmap.add(\"a\", 30);\n\t\tmmap.add(\"b\", 10);\n\t\tmmap.add(\"b\", 11);\n\t\tSet<Integer> set = mmap.get(\"a\");\n\t\tassertEquals(set.size(),3);\n\t\tassertThat(set,hasItems(10,20,30));\n\t\t// adding 40 to set has no effect on mmap\n\t\tset.add(40);\n\t\tassertEquals(mmap.entrySet().size(),5);\n\t}\n\t\n\[email protected]\n\tpublic void optionalTestEmpty() {\n\t\t// Simple test of empty on the factory\n\t\tMapFactory fact = new MapFactoryImpl();\n\t\tMultiMap<String,Integer> mmap = fact.empty();\n\t\tassertEquals(mmap.entrySet().size(),0);\n\t}\n\t\n\n\t\n\[email protected]\n\tpublic void optionalTestUnmodifiable() {\n\t\t// Testing cloning and unmodifiability of the factory method\n\t\tMultiMap<String,Integer> mmap = new MultiMapImpl<>();\n\t\tmmap.add(\"a\", 10);\n\t\tmmap.add(\"a\", 20);\n\t\tmmap.add(\"a\", 30);\n\t\tmmap.add(\"b\", 10);\n\t\tmmap.add(\"b\", 11);\n\t\tMapFactory fact = new MapFactoryImpl();\n\t\t// mmap2 as an unmodificable clone of mmap\n\t\tMultiMap<String,Integer> mmap2 = fact.unmodifiable(mmap);\n\t\t// changing mmap has no effect on mmap2\n\t\tmmap.add(\"b\", 12);\n\t\tassertEquals(mmap.entrySet().size(),6);\n\t\tassertEquals(mmap2.entrySet().size(),5);\n\t\t// trying to add something to mmap2 throws an exception\n\t\ttry{\n\t\t\tmmap2.add(\"b\", 13);\n\t\t\tfail(\"adding to an unmodifiable-multi-map should raise an exception!\");\n\t\t} catch (UnsupportedOperationException e){}\n\t\t catch (Exception e){\n\t\t\t fail(\"wrong exception thrown\");\n\t\t }\n\t\t// Obviously, the set you obtain by get() is again a defensive copy \n\t\tSet<Integer> s = mmap2.get(\"a\");\n\t\tassertEquals(s.size(),3);\n\t\ts.add(100);\n\t\tSet<Integer> s2 = mmap2.get(\"a\");\n\t\tassertEquals(s2.size(),3);\n\t}\n\t\n}", "filename": "Test.java" }
2015
a03b
[ { "content": "package ex2015.a03b.sol1;\n\nimport java.util.Map;\n\n\npublic interface ThesesManagement {\n \n enum Status {\n TO_BE_APPROVED, APPROVED, SUBMITTED, CONCLUDED \n }\n \n \n void registerStudent(int studentId, String name);\n \n \n void registerThesis(int thesisId, String title, int studentId);\n \n \n void thesisApproved(int thesisId);\n \n \n void thesisSubmitted(int thesisId, String finalTitle);\n \n \n void thesisConcluded(int thesisId, int score);\n \n \n Pair<String,Status> thesis(int thesisId);\n \n \n Map<String, Status> statusByStudent();\n \n \n double averageThesisScore();\n \n}", "filename": "ThesesManagement.java" }, { "content": "package ex2015.a03b.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.a03b.sol1;\n\nimport java.util.*;\nimport java.util.function.Supplier;\nimport java.util.stream.Collectors;\n\npublic class ThesesManagementImpl implements ThesesManagement {\n \n private final Map<Integer,Pair<String,Optional<Thesis>>> students = new HashMap<>();\n private final Map<Integer,Integer> theses = new HashMap<>();\n \n private static class Thesis {\n private String title;\n private Status status = Status.TO_BE_APPROVED;\n private Optional<Integer> score = Optional.empty();\n public Thesis(String title) {\n super();\n this.title = title;\n }\n public Status getStatus(){\n return this.status;\n }\n public String getTitle(){\n return this.title;\n }\n public Optional<Integer> getScore(){\n return this.score;\n }\n public void approved(){\n this.status = Status.APPROVED;\n }\n public void submitted(String finalTitle){\n this.status = Status.SUBMITTED;\n this.title = finalTitle;\n }\n public void concluded(int score){\n this.status = Status.CONCLUDED;\n this.score = Optional.of(score);\n }\n }\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 registerStudent(int studentId, String name) {\n check(this.students.containsKey(studentId),()->new IllegalArgumentException(\"student already registered\"));\n this.students.put(studentId, new Pair<>(name,Optional.empty()));\n }\n\n @Override\n public void registerThesis(int thesisId, String title, int studentId) {\n check(this.theses.containsKey(thesisId),()->new IllegalArgumentException(\"thesis already existing\"));\n check(!this.students.containsKey(studentId),()->new IllegalArgumentException(\"student should exist\"));\n final Pair<String,Optional<Thesis>> info = this.students.get(studentId);\n check(info.getY().isPresent(),()->new IllegalArgumentException(\"student already has a thesis\"));\n this.theses.put(thesisId, studentId);\n info.setY(Optional.of(new Thesis(title)));\n }\n \n private Thesis thesisById(int id){\n return this.students.get(this.theses.get(id)).getY().get();\n }\n\n @Override\n public void thesisApproved(int thesisId) {\n check(this.thesisById(thesisId).getStatus()!=Status.TO_BE_APPROVED,()->new IllegalArgumentException(\"not to be approved\"));\n this.thesisById(thesisId).approved();\n }\n\n @Override\n public void thesisSubmitted(int thesisId, String finalTitle) {\n check(this.thesisById(thesisId).getStatus()!=Status.APPROVED,()->new IllegalArgumentException(\"not to be submitted\"));\n this.thesisById(thesisId).submitted(finalTitle);\n }\n\n @Override\n public void thesisConcluded(int thesisId, int score) {\n check(this.thesisById(thesisId).getStatus()!=Status.SUBMITTED,()->new IllegalArgumentException(\"not to be concluded\"));\n this.thesisById(thesisId).concluded(score);\n }\n\n @Override\n public Map<String, Status> statusByStudent() {\n return this.students\n .values()\n .stream()\n .filter(e -> e.getY().isPresent())\n .map(e -> new Pair<>(e.getX(),e.getY().get()))\n .collect(Collectors.toMap(e -> e.getX(), e -> e.getY().getStatus()));\n }\n\n \n @Override\n public Pair<String, Status> thesis(int thesisId) {\n return new Pair<String,Status>(this.thesisById(thesisId).getTitle(),this.thesisById(thesisId).getStatus());\n }\n\n @Override\n public double averageThesisScore() {\n return this.students\n .values()\n .stream()\n .map(e->e.getY())\n .filter(Optional::isPresent)\n .filter(e->e.get().getScore().isPresent())\n .mapToInt(e->e.get().getScore().get())\n .average().getAsDouble();\n }\n\n \n}", "filename": "ThesesManagementImpl.java" } ]
{ "components": { "imports": "package ex2015.a03b.sol1;\n\nimport static org.junit.Assert.*;\n\n/**\n * Implement the ThesesManagement interface using a TheseManagementImpl class\n * with a constructor without arguments. Models the management of theses\n * of a university course, with methods to register students and their theses,\n * managing the life cycle (to be approved/approved/submitted/concluded) of the thesis.\n *\n * Carefully observe the following test, which together with the comments\n * of the ThesesManagement interface constitutes the definition of the problem to be\n * solved.\n *\n * Tests whose name begins with 'optional', and the performance requests indicated\n * in the ThesesManagement interface, are considered optional for the possibility of correcting\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 populate(final ThesesManagement t) {\n t.registerStudent(1000, \"Rossi\"); // 5 students\n t.registerStudent(1001, \"Bianchi\");\n t.registerStudent(1002, \"Verdi\");\n t.registerStudent(1003, \"Neri\");\n t.registerStudent(1004, \"Rosa\");\n\n // only 4 students have a thesis\n t.registerThesis(1, \"work on OOP\", 1000);\n t.registerThesis(2, \"work on SISOP\", 1001);\n t.registerThesis(3, \"work on ASD\", 1002);\n t.registerThesis(4, \"work on INGSOFT\", 1003);\n\n // only 3 students have an approved thesis\n t.thesisApproved(1);\n t.thesisApproved(2);\n t.thesisApproved(3);\n\n // only 2 students have submitted a final version of the thesis\n t.thesisSubmitted(1, \"work on OOP\");\n t.thesisSubmitted(2, \"survey on SISOP\");\n\n // final vote\n t.thesisConcluded(1, 110);\n t.thesisConcluded(2, 109);\n }", "test_functions": [ "\[email protected]\n public void testBasicManagement() {\n ThesesManagement t = new ThesesManagementImpl();\n populate(t);\n // access to theses by id\n assertEquals(t.thesis(1), new Pair<>(\"work on OOP\", ThesesManagement.Status.CONCLUDED));\n assertEquals(t.thesis(2), new Pair<>(\"survey on SISOP\", ThesesManagement.Status.CONCLUDED));\n assertEquals(t.thesis(3), new Pair<>(\"work on ASD\", ThesesManagement.Status.APPROVED));\n assertEquals(t.thesis(4), new Pair<>(\"work on INGSOFT\", ThesesManagement.Status.TO_BE_APPROVED));\n\n // access to the map from student to thesis status\n assertEquals(t.statusByStudent().get(\"Rossi\"), ThesesManagement.Status.CONCLUDED);\n assertEquals(t.statusByStudent().get(\"Bianchi\"), ThesesManagement.Status.CONCLUDED);\n assertEquals(t.statusByStudent().get(\"Verdi\"), ThesesManagement.Status.APPROVED);\n assertEquals(t.statusByStudent().get(\"Neri\"), ThesesManagement.Status.TO_BE_APPROVED);\n assertEquals(t.statusByStudent().size(), 4);\n\n // average of the scores of the concluded theses, maximum error 0.001\n assertEquals(t.averageThesisScore(), 109.5, 0.001);\n }", "\[email protected]\n public void optionalTestExceptions() {\n ThesesManagement t = new ThesesManagementImpl();\n t.registerStudent(1000, \"Mirko\");\n t.registerStudent(1001, \"Mario\");\n try {\n t.registerStudent(1000, \"Gino\");\n fail(\"can't reuse student id\");\n }" ] }, "content": "package ex2015.a03b.sol1;\n\nimport static org.junit.Assert.*;\n\n/**\n * Implement the ThesesManagement interface using a TheseManagementImpl class\n * with a constructor without arguments. Models the management of theses\n * of a university course, with methods to register students and their theses,\n * managing the life cycle (to be approved/approved/submitted/concluded) of the thesis.\n *\n * Carefully observe the following test, which together with the comments\n * of the ThesesManagement interface constitutes the definition of the problem to be\n * solved.\n *\n * Tests whose name begins with 'optional', and the performance requests indicated\n * in the ThesesManagement interface, are considered optional for the possibility of correcting\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 populate(final ThesesManagement t) {\n t.registerStudent(1000, \"Rossi\"); // 5 students\n t.registerStudent(1001, \"Bianchi\");\n t.registerStudent(1002, \"Verdi\");\n t.registerStudent(1003, \"Neri\");\n t.registerStudent(1004, \"Rosa\");\n\n // only 4 students have a thesis\n t.registerThesis(1, \"work on OOP\", 1000);\n t.registerThesis(2, \"work on SISOP\", 1001);\n t.registerThesis(3, \"work on ASD\", 1002);\n t.registerThesis(4, \"work on INGSOFT\", 1003);\n\n // only 3 students have an approved thesis\n t.thesisApproved(1);\n t.thesisApproved(2);\n t.thesisApproved(3);\n\n // only 2 students have submitted a final version of the thesis\n t.thesisSubmitted(1, \"work on OOP\");\n t.thesisSubmitted(2, \"survey on SISOP\");\n\n // final vote\n t.thesisConcluded(1, 110);\n t.thesisConcluded(2, 109);\n }\n\n @org.junit.Test\n public void testBasicManagement() {\n ThesesManagement t = new ThesesManagementImpl();\n populate(t);\n // access to theses by id\n assertEquals(t.thesis(1), new Pair<>(\"work on OOP\", ThesesManagement.Status.CONCLUDED));\n assertEquals(t.thesis(2), new Pair<>(\"survey on SISOP\", ThesesManagement.Status.CONCLUDED));\n assertEquals(t.thesis(3), new Pair<>(\"work on ASD\", ThesesManagement.Status.APPROVED));\n assertEquals(t.thesis(4), new Pair<>(\"work on INGSOFT\", ThesesManagement.Status.TO_BE_APPROVED));\n\n // access to the map from student to thesis status\n assertEquals(t.statusByStudent().get(\"Rossi\"), ThesesManagement.Status.CONCLUDED);\n assertEquals(t.statusByStudent().get(\"Bianchi\"), ThesesManagement.Status.CONCLUDED);\n assertEquals(t.statusByStudent().get(\"Verdi\"), ThesesManagement.Status.APPROVED);\n assertEquals(t.statusByStudent().get(\"Neri\"), ThesesManagement.Status.TO_BE_APPROVED);\n assertEquals(t.statusByStudent().size(), 4);\n\n // average of the scores of the concluded theses, maximum error 0.001\n assertEquals(t.averageThesisScore(), 109.5, 0.001);\n }\n\n @org.junit.Test\n public void optionalTestExceptions() {\n ThesesManagement t = new ThesesManagementImpl();\n t.registerStudent(1000, \"Mirko\");\n t.registerStudent(1001, \"Mario\");\n try {\n t.registerStudent(1000, \"Gino\");\n fail(\"can't reuse student id\");\n } catch (IllegalArgumentException e) {\n } catch (Exception e) {\n fail(\"wrong exception thrown\");\n }\n t.registerThesis(1, \"work on OOP\", 1000);\n try {\n t.registerThesis(2, \"work on SISOP\", 1000);\n fail(\"can't assign two thesis to the same student\");\n } catch (IllegalArgumentException e) {\n } catch (Exception e) {\n fail(\"wrong exception thrown\");\n }\n try {\n t.registerThesis(1, \"work on SISOP\", 1001);\n fail(\"can't reuse a thesis id\");\n } catch (IllegalArgumentException e) {\n } catch (Exception e) {\n fail(\"wrong exception thrown\");\n }\n t.thesisApproved(1);\n try {\n t.thesisApproved(1);\n fail(\"not to be approved\");\n } catch (IllegalArgumentException e) {\n } catch (Exception e) {\n fail(\"wrong exception thrown\");\n }\n t.thesisSubmitted(1, \"final work on OOP\");\n try {\n t.thesisSubmitted(1, \"final work on OOP\");\n fail(\"not to be submitted\");\n } catch (IllegalArgumentException e) {\n } catch (Exception e) {\n fail(\"wrong exception thrown\");\n }\n t.thesisConcluded(1, 110);\n try {\n t.thesisConcluded(1, 110);\n fail(\"not to be concluded\");\n } catch (IllegalArgumentException e) {\n } catch (Exception e) {\n fail(\"wrong exception thrown\");\n }\n }\n}", "filename": "Test.java" }
2015
a01b
[ { "content": "package ex2015.a01b.sol1;\n\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.SortedSet;\n\n\npublic interface CoursesManagement {\n\n \n static final int TUTORING_SLOTS = 3;\n\n \n enum Course {\n OBJECT_ORIENTED_PROGRAMMING, OPERATING_SYSTEMS, FOUNDATIONS_OF_INFORMATICS, ANALYSIS, GEOMETRY, PHYSICS\n }\n\n \n void assignProfessor(Course c, int year, String professor);\n\n \n void assignTutor(Course c, int year, String professor);\n\n \n Set<Course> getUnassignedCourses(int year);\n\n \n Set<Pair<Integer, Course>> getCoursesByProf(String prof);\n\n \n Map<Integer, Set<Pair<Course, Integer>>> getRemainingTutoringSlots();\n\n}", "filename": "CoursesManagement.java" }, { "content": "package ex2015.a01b.sol1;\n\n\npublic final class Pair<X, Y> {\n\n private final X x;\n private final 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 @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.a01b.sol1;\n\nimport java.util.*;\nimport java.util.stream.*;\n\npublic class CoursesManagementImpl implements CoursesManagement {\n \n private final Map<Integer, Map<Course, Pair<Optional<String>, Set<String>>>> summary = new HashMap<>();\n \n public CoursesManagementImpl(){}\n \n private Map<Course, Pair<Optional<String>, Set<String>>> getOrInit(final int year) {\n final Map<Course, Pair<Optional<String>, Set<String>>> yMap = \n \t\tOptional.ofNullable(summary.get(year)).orElse(new EnumMap<>(Course.class));\n summary.put(year, yMap);\n return yMap;\n }\n\n @Override\n public void assignProfessor(final Course c, final int year, final String professor) {\n final Map<Course, Pair<Optional<String>, Set<String>>> yMap = getOrInit(year);\n final Pair<Optional<String>, Set<String>> profAndTutors = yMap.get(c);\n if (profAndTutors != null && profAndTutors.getX().isPresent()) {\n throw new IllegalStateException(\"This course already has a professor\");\n }\n yMap.put(c, new Pair<>(Optional.of(professor), profAndTutors == null ? new HashSet<>() : profAndTutors.getY()));\n }\n\n @Override\n public void assignTutor(final Course c, final int year, final String tutor) {\n final Map<Course, Pair<Optional<String>, Set<String>>> yMap = getOrInit(year);\n final Pair<Optional<String>, Set<String>> profAndTutors = yMap.getOrDefault(c, new Pair<>(Optional.empty(), new HashSet<>()));\n final Set<String> tutors = profAndTutors.getY();\n if (tutors.size() >= TUTORING_SLOTS) {\n throw new IllegalStateException(\"This course already has three tutors\");\n }\n tutors.add(tutor);\n yMap.putIfAbsent(c, profAndTutors);\n }\n\n @Override\n public Set<Course> getUnassignedCourses(final int year) {\n final Map<Course, Pair<Optional<String>, Set<String>>> target = summary.getOrDefault(year, Collections.emptyMap());\n return Arrays.stream(Course.values())\n .filter(c -> !(target.containsKey(c) && target.get(c).getX().isPresent()))\n .collect(Collectors.toSet());\n }\n\n @Override\n public Set<Pair<Integer, Course>> getCoursesByProf(final String prof) {\n return summary.entrySet().stream()\n .flatMap(e -> e.getValue().entrySet().stream()\n .map(entry -> new Pair<>(entry.getKey(), entry.getValue().getX()))\n .filter(p -> p.getY().isPresent())\n .filter(p -> prof.equals(p.getY().get()))\n .map(p -> new Pair<>(e.getKey(), p.getX()))\n )\n .collect(Collectors.toSet());\n }\n\n @Override\n public Map<Integer, Set<Pair<Course, Integer>>> getRemainingTutoringSlots() {\n return summary.entrySet().stream()\n .map(entry -> new Pair<>(entry.getKey(), Arrays.stream(Course.values())\n .map(c -> new Pair<>(c, TUTORING_SLOTS - Optional.ofNullable(entry.getValue().get(c))\n .map(Pair::getY)\n .map(Collection::size)\n .orElse(0)))\n .collect(Collectors.toSet()))\n )\n .collect(Collectors.toMap(Pair::getX, Pair::getY));\n }\n\n @Override\n public String toString() {\n return summary.toString();\n }\n\n\n}", "filename": "CoursesManagementImpl.java" } ]
{ "components": { "imports": "package ex2015.a01b.sol1;\n\nimport static org.hamcrest.CoreMatchers.*;\nimport static org.junit.Assert.*;\n\nimport java.util.*;\nimport java.util.stream.*;\n\nimport ex2015.a01b.sol1.CoursesManagement.Course;\n\n/**\n * Implement the CoursesManagement interface given through a CoursesManagementImpl class\n * with a constructor without arguments. It models the management\n * of the assignment of courses of a university, with a method to assign a\n * course of a certain year to a professor and a method to add one or more tutors (maximum 3) to a course of a certain year.\n * \n * Carefully observe the following test, which together with the Javadoc comments\n * of the CoursesManagement interface constitute the definition of the problem to be solved.\n * Tests whose name begins with 'optional' 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 final String CASADEI = \"Matteo Casadei\";\n private static final String CICOGNANI = \"Massimo Cicognani\";\n private static final String CROATTI = \"Angelo Croatti\";\n private static final String MONTAGNA = \"Sara Montagna\";\n private static final String MULAZZANI = \"Michele Mulazzani\";\n private static final String PICCININI = \"Maurizio Piccinini\";\n private static final String PIANINI = \"Danilo Pianini\";\n private static final String RICCI = \"Alessandro Ricci\";\n private static final String SANTI = \"Andrea Santi\";\n private static final String VIROLI = \"Mirko Viroli\";\n\n private static void populateAssignment(final CoursesManagement c) {\n \t// creates an assignment of courses to prof and tutors\n IntStream.rangeClosed(2012, 2015).forEach(year -> { // year between 2012 and 2015 inclusive..\n c.assignProfessor(Course.ANALYSIS, year, CICOGNANI);\n c.assignProfessor(Course.GEOMETRY, year, MULAZZANI);\n c.assignProfessor(Course.PHYSICS, year, PICCININI);\n c.assignTutor(Course.FOUNDATIONS_OF_INFORMATICS, year, MONTAGNA);\n });\n IntStream.rangeClosed(2012, 2013).forEach(year -> {\n c.assignProfessor(Course.OPERATING_SYSTEMS, year, RICCI);\n c.assignTutor(Course.OPERATING_SYSTEMS, year, SANTI);\n });\n IntStream.rangeClosed(2013, 2015).forEach(year -> {\n c.assignProfessor(Course.OBJECT_ORIENTED_PROGRAMMING, year, VIROLI);\n c.assignTutor(Course.OBJECT_ORIENTED_PROGRAMMING, year, PIANINI);\n });\n IntStream.rangeClosed(2012, 2014).forEach(year -> {\n c.assignProfessor(Course.FOUNDATIONS_OF_INFORMATICS, year, VIROLI);\n });\n c.assignTutor(Course.FOUNDATIONS_OF_INFORMATICS, 2012, PIANINI);\n c.assignTutor(Course.FOUNDATIONS_OF_INFORMATICS, 2013, PIANINI);\n c.assignTutor(Course.FOUNDATIONS_OF_INFORMATICS, 2014, PIANINI);\n c.assignTutor(Course.OBJECT_ORIENTED_PROGRAMMING, 2013, SANTI);\n c.assignTutor(Course.OBJECT_ORIENTED_PROGRAMMING, 2014, CASADEI);\n c.assignTutor(Course.OBJECT_ORIENTED_PROGRAMMING, 2015, CASADEI);\n c.assignTutor(Course.OBJECT_ORIENTED_PROGRAMMING, 2015, CROATTI);\n }\n \n private static CoursesManagement makeCalendar() {\n return new CoursesManagementImpl();\n }", "test_functions": [ "\[email protected]\n public void testUnassignedCourses() {\n final CoursesManagement cc = makeCalendar();\n // verifies that initially all courses of 2015 are NOT assigned\n assertThat(cc.getUnassignedCourses(2015), hasItems(Course.values()));\n // populates the assignment\n populateAssignment(cc);\n // two courses not assigned in 2015\n assertEquals(2, cc.getUnassignedCourses(2015).size());\n assertThat(cc.getUnassignedCourses(2015),\n hasItems(Course.FOUNDATIONS_OF_INFORMATICS, Course.OPERATING_SYSTEMS));\n // one course not assigned in 2014, etc..\n assertEquals(1, cc.getUnassignedCourses(2014).size());\n assertThat(cc.getUnassignedCourses(2014), hasItems(Course.OPERATING_SYSTEMS));\n assertTrue(cc.getUnassignedCourses(2013).isEmpty());\n assertEquals(1, cc.getUnassignedCourses(2012).size());\n assertThat(cc.getUnassignedCourses(2012), hasItems(Course.OBJECT_ORIENTED_PROGRAMMING));\n }", "\[email protected]\n public void testExceptions() {\n final CoursesManagement cc = makeCalendar();\n populateAssignment(cc);\n try {\n cc.assignProfessor(Course.OBJECT_ORIENTED_PROGRAMMING, 2014, RICCI);\n fail(\"prof already assigned!\");\n }", "\[email protected]\n public void testCoursesByProf() {\n final CoursesManagement cc = makeCalendar();\n assertTrue(cc.getCoursesByProf(VIROLI).isEmpty());\n populateAssignment(cc);\n assertEquals(6, cc.getCoursesByProf(VIROLI).size());\n assertEquals(2, cc.getCoursesByProf(RICCI).size());\n assertTrue(cc.getCoursesByProf(RICCI).contains(new Pair<>(2012,Course.OPERATING_SYSTEMS)));\n assertTrue(cc.getCoursesByProf(RICCI).contains(new Pair<>(2013,Course.OPERATING_SYSTEMS)));\n assertTrue(cc.getCoursesByProf(CASADEI).isEmpty());\n assertTrue(cc.getCoursesByProf(CROATTI).isEmpty());\n assertTrue(cc.getCoursesByProf(PIANINI).isEmpty());\n assertTrue(cc.getCoursesByProf(SANTI).isEmpty());\n }", "\[email protected]\n public void optionalTestRemainingTutoringSlots() {\n final CoursesManagement cc = makeCalendar();\n populateAssignment(cc);\n // there are slots for tutors every year, both 2012, 2013, 2014, 2015\n assertEquals(cc.getRemainingTutoringSlots().size(),4);\n // remaining slots for 2012\n Set<Pair<Course, Integer>> set = cc.getRemainingTutoringSlots().get(2012);\n assertTrue(set.contains(new Pair<>(Course.OPERATING_SYSTEMS,2)));\n assertTrue(set.contains(new Pair<>(Course.PHYSICS,3)));\n assertTrue(set.contains(new Pair<>(Course.FOUNDATIONS_OF_INFORMATICS,1)));\n assertTrue(set.contains(new Pair<>(Course.OBJECT_ORIENTED_PROGRAMMING,3)));\n assertTrue(set.contains(new Pair<>(Course.ANALYSIS,3)));\n // remaining slots for 2015\n final Set<Pair<Course, Integer>> set2 = cc.getRemainingTutoringSlots().get(2015);\n assertThat(set2, hasItems(\n new Pair<>(Course.OBJECT_ORIENTED_PROGRAMMING, 0),\n new Pair<>(Course.FOUNDATIONS_OF_INFORMATICS, 2),\n new Pair<>(Course.OPERATING_SYSTEMS, 3)));\n }" ] }, "content": "package ex2015.a01b.sol1;\n\nimport static org.hamcrest.CoreMatchers.*;\nimport static org.junit.Assert.*;\n\nimport java.util.*;\nimport java.util.stream.*;\n\nimport ex2015.a01b.sol1.CoursesManagement.Course;\n\n/**\n * Implement the CoursesManagement interface given through a CoursesManagementImpl class\n * with a constructor without arguments. It models the management\n * of the assignment of courses of a university, with a method to assign a\n * course of a certain year to a professor and a method to add one or more tutors (maximum 3) to a course of a certain year.\n * \n * Carefully observe the following test, which together with the Javadoc comments\n * of the CoursesManagement interface constitute the definition of the problem to be solved.\n * Tests whose name begins with 'optional' 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 final String CASADEI = \"Matteo Casadei\";\n private static final String CICOGNANI = \"Massimo Cicognani\";\n private static final String CROATTI = \"Angelo Croatti\";\n private static final String MONTAGNA = \"Sara Montagna\";\n private static final String MULAZZANI = \"Michele Mulazzani\";\n private static final String PICCININI = \"Maurizio Piccinini\";\n private static final String PIANINI = \"Danilo Pianini\";\n private static final String RICCI = \"Alessandro Ricci\";\n private static final String SANTI = \"Andrea Santi\";\n private static final String VIROLI = \"Mirko Viroli\";\n\n private static void populateAssignment(final CoursesManagement c) {\n \t// creates an assignment of courses to prof and tutors\n IntStream.rangeClosed(2012, 2015).forEach(year -> { // year between 2012 and 2015 inclusive..\n c.assignProfessor(Course.ANALYSIS, year, CICOGNANI);\n c.assignProfessor(Course.GEOMETRY, year, MULAZZANI);\n c.assignProfessor(Course.PHYSICS, year, PICCININI);\n c.assignTutor(Course.FOUNDATIONS_OF_INFORMATICS, year, MONTAGNA);\n });\n IntStream.rangeClosed(2012, 2013).forEach(year -> {\n c.assignProfessor(Course.OPERATING_SYSTEMS, year, RICCI);\n c.assignTutor(Course.OPERATING_SYSTEMS, year, SANTI);\n });\n IntStream.rangeClosed(2013, 2015).forEach(year -> {\n c.assignProfessor(Course.OBJECT_ORIENTED_PROGRAMMING, year, VIROLI);\n c.assignTutor(Course.OBJECT_ORIENTED_PROGRAMMING, year, PIANINI);\n });\n IntStream.rangeClosed(2012, 2014).forEach(year -> {\n c.assignProfessor(Course.FOUNDATIONS_OF_INFORMATICS, year, VIROLI);\n });\n c.assignTutor(Course.FOUNDATIONS_OF_INFORMATICS, 2012, PIANINI);\n c.assignTutor(Course.FOUNDATIONS_OF_INFORMATICS, 2013, PIANINI);\n c.assignTutor(Course.FOUNDATIONS_OF_INFORMATICS, 2014, PIANINI);\n c.assignTutor(Course.OBJECT_ORIENTED_PROGRAMMING, 2013, SANTI);\n c.assignTutor(Course.OBJECT_ORIENTED_PROGRAMMING, 2014, CASADEI);\n c.assignTutor(Course.OBJECT_ORIENTED_PROGRAMMING, 2015, CASADEI);\n c.assignTutor(Course.OBJECT_ORIENTED_PROGRAMMING, 2015, CROATTI);\n }\n \n private static CoursesManagement makeCalendar() {\n return new CoursesManagementImpl();\n }\n\n @org.junit.Test\n public void testUnassignedCourses() {\n final CoursesManagement cc = makeCalendar();\n // verifies that initially all courses of 2015 are NOT assigned\n assertThat(cc.getUnassignedCourses(2015), hasItems(Course.values()));\n // populates the assignment\n populateAssignment(cc);\n // two courses not assigned in 2015\n assertEquals(2, cc.getUnassignedCourses(2015).size());\n assertThat(cc.getUnassignedCourses(2015),\n hasItems(Course.FOUNDATIONS_OF_INFORMATICS, Course.OPERATING_SYSTEMS));\n // one course not assigned in 2014, etc..\n assertEquals(1, cc.getUnassignedCourses(2014).size());\n assertThat(cc.getUnassignedCourses(2014), hasItems(Course.OPERATING_SYSTEMS));\n assertTrue(cc.getUnassignedCourses(2013).isEmpty());\n assertEquals(1, cc.getUnassignedCourses(2012).size());\n assertThat(cc.getUnassignedCourses(2012), hasItems(Course.OBJECT_ORIENTED_PROGRAMMING));\n }\n\n @org.junit.Test\n public void testExceptions() {\n final CoursesManagement cc = makeCalendar();\n populateAssignment(cc);\n try {\n cc.assignProfessor(Course.OBJECT_ORIENTED_PROGRAMMING, 2014, RICCI);\n fail(\"prof already assigned!\");\n } catch (final IllegalStateException e) {\n } catch (Exception e){\n \tfail(\"wrong exception thrown\");\n }\n try {\n cc.assignTutor(Course.OBJECT_ORIENTED_PROGRAMMING, 2015, SANTI);\n fail(\"3 tutors already assigned\");\n } catch (final IllegalStateException e) {\n } catch (Exception e){\n \tfail(\"wrong exception thrown\");\n }\n }\n\n @org.junit.Test\n public void testCoursesByProf() {\n final CoursesManagement cc = makeCalendar();\n assertTrue(cc.getCoursesByProf(VIROLI).isEmpty());\n populateAssignment(cc);\n assertEquals(6, cc.getCoursesByProf(VIROLI).size());\n assertEquals(2, cc.getCoursesByProf(RICCI).size());\n assertTrue(cc.getCoursesByProf(RICCI).contains(new Pair<>(2012,Course.OPERATING_SYSTEMS)));\n assertTrue(cc.getCoursesByProf(RICCI).contains(new Pair<>(2013,Course.OPERATING_SYSTEMS)));\n assertTrue(cc.getCoursesByProf(CASADEI).isEmpty());\n assertTrue(cc.getCoursesByProf(CROATTI).isEmpty());\n assertTrue(cc.getCoursesByProf(PIANINI).isEmpty());\n assertTrue(cc.getCoursesByProf(SANTI).isEmpty());\n }\n\n @SuppressWarnings(\"unchecked\")\n @org.junit.Test\n public void optionalTestRemainingTutoringSlots() {\n final CoursesManagement cc = makeCalendar();\n populateAssignment(cc);\n // there are slots for tutors every year, both 2012, 2013, 2014, 2015\n assertEquals(cc.getRemainingTutoringSlots().size(),4);\n // remaining slots for 2012\n Set<Pair<Course, Integer>> set = cc.getRemainingTutoringSlots().get(2012);\n assertTrue(set.contains(new Pair<>(Course.OPERATING_SYSTEMS,2)));\n assertTrue(set.contains(new Pair<>(Course.PHYSICS,3)));\n assertTrue(set.contains(new Pair<>(Course.FOUNDATIONS_OF_INFORMATICS,1)));\n assertTrue(set.contains(new Pair<>(Course.OBJECT_ORIENTED_PROGRAMMING,3)));\n assertTrue(set.contains(new Pair<>(Course.ANALYSIS,3)));\n // remaining slots for 2015\n final Set<Pair<Course, Integer>> set2 = cc.getRemainingTutoringSlots().get(2015);\n assertThat(set2, hasItems(\n new Pair<>(Course.OBJECT_ORIENTED_PROGRAMMING, 0),\n new Pair<>(Course.FOUNDATIONS_OF_INFORMATICS, 2),\n new Pair<>(Course.OPERATING_SYSTEMS, 3)));\n }\n \n\n}", "filename": "Test.java" }
2016
a04
[ { "content": "package ex2016.a04.sol1;\n\nimport java.util.*;\n\n\n\ninterface BitIteratorsFactory {\n \n enum Bit {\n ZERO, ONE\n }\n \n \n Iterator<Bit> empty();\n \n \n Iterator<Bit> zeros();\n \n \n Iterator<Bit> ones();\n \n \n Iterator<Bit> fromByteStartingWithLSB(int b);\n \n \n Iterator<Bit> fromBitList(List<Bit> list);\n \n \n Iterator<Bit> fromBooleanList(List<Boolean> list);\n}", "filename": "BitIteratorsFactory.java" } ]
[ { "content": "package ex2016.a04.sol1;\n\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.NoSuchElementException;\n\npublic class BitIteratorsFactoryImpl implements BitIteratorsFactory {\n\n @Override\n public Iterator<Bit> empty() {\n //return java.util.stream.Stream.<Bit>empty().iterator();\n return new Iterator<Bit>(){\n\n @Override\n public boolean hasNext() {\n return false;\n }\n\n @Override\n public Bit next() {\n throw new NoSuchElementException();\n }};\n }\n \n private Iterator<Bit> of(Bit b){\n //return java.util.stream.Stream.<Bit>generate(()->b).iterator();\n return new Iterator<Bit>(){\n\n @Override\n public boolean hasNext() {\n return true;\n }\n\n @Override\n public Bit next() {\n return b;\n } \n };\n }\n\n @Override\n public Iterator<Bit> zeros() {\n return of(Bit.ZERO);\n }\n\n @Override\n public Iterator<Bit> ones() {\n return of(Bit.ONE);\n }\n \n private Bit bitFromBoolean(boolean b){\n return b ? Bit.ONE : Bit.ZERO;\n }\n\n @Override\n public Iterator<Bit> fromByteStartingWithLSB(int b) {\n return new Iterator<Bit>(){\n\n private int val = b;\n private int count = 0;\n \n @Override\n public boolean hasNext() {\n return count < 8;\n }\n\n @Override\n public Bit next() {\n if (!this.hasNext()){\n throw new NoSuchElementException();\n }\n int old = val;\n count++;\n val = (byte) (val / 2);\n return bitFromBoolean(old%2 == 1);\n }\n \n };\n }\n\n @Override\n public Iterator<Bit> fromBitList(List<Bit> list) {\n return list.iterator();\n }\n\n @Override\n public Iterator<Bit> fromBooleanList(List<Boolean> list) {\n return list.stream().map(this::bitFromBoolean).iterator();\n }\n\n}", "filename": "BitIteratorsFactoryImpl.java" } ]
{ "components": { "imports": "package ex2016.a04.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;\nimport static ex2016.a04.sol1.BitIteratorsFactory.*;\nimport static ex2016.a04.sol1.BitIteratorsFactory.Bit.*;\n\n/**\n * Consult the documentation of the BitIteratorsFactory interface: it models a factory for\n * creating various objects of type java.util.Iterator<Bit>, where Bit is a given enum (nested in the factory).\n * \n * The following are considered optional for the purpose of being able to correct the exercise, but still contribute to achieving \n * the totality of the score:\n * - implementation of optional tests (named 'optionalTestXYZ') \n * - minimization of repetitions\n * - minimization of memory waste, allocating objects of potentially large sizes unnecessarily\n * \n * Observe carefully the following test, 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/*\n * A utility function for the test below, which converts a (finite) iterator into a list\n */\n private <T> List<T> iteratorToList(Iterator<T> it){\n final List<T> l = new LinkedList<T>();\n while (it.hasNext()){\n l.add(it.next());\n }\n return l;\n }", "test_functions": [ "\[email protected]\n public void testEmpty() {\n // Functioning of an empty iterator\n final BitIteratorsFactory factory = new BitIteratorsFactoryImpl();\n Iterator<BitIteratorsFactory.Bit> empty = factory.empty();\n assertFalse(empty.hasNext());\n }", "\[email protected]\n public void testZeros() {\n // Functioning of an iterator of zeros\n final BitIteratorsFactory factory = new BitIteratorsFactoryImpl();\n final Iterator<BitIteratorsFactory.Bit> zeros = factory.zeros();\n assertTrue(zeros.hasNext());\n assertEquals(zeros.next(),ZERO);\n assertTrue(zeros.hasNext());\n assertEquals(zeros.next(),ZERO);\n assertTrue(zeros.hasNext());\n assertEquals(zeros.next(),ZERO);\n assertTrue(zeros.hasNext());\n assertEquals(zeros.next(),ZERO);\n assertTrue(zeros.hasNext());\n // ad infinitum\n }", "\[email protected]\n public void testOnes() {\n // Functioning of an iterator of ones\n final BitIteratorsFactory factory = new BitIteratorsFactoryImpl();\n final Iterator<BitIteratorsFactory.Bit> ones = factory.ones();\n assertTrue(ones.hasNext());\n assertEquals(ones.next(),ONE);\n assertTrue(ones.hasNext());\n assertEquals(ones.next(),ONE);\n assertTrue(ones.hasNext());\n assertEquals(ones.next(),ONE);\n assertTrue(ones.hasNext());\n assertEquals(ones.next(),ONE);\n assertTrue(ones.hasNext());\n // ad infinitum\n }", "\[email protected]\n public void testFromByte() {\n // Functioning of an iterator of the bits of a byte, from LSB to MSB\n final BitIteratorsFactory factory = new BitIteratorsFactoryImpl();\n assertEquals(this.iteratorToList(factory.fromByteStartingWithLSB(0)), // 00000000\n Arrays.asList(ZERO,ZERO,ZERO,ZERO,ZERO,ZERO,ZERO,ZERO));\n assertEquals(this.iteratorToList(factory.fromByteStartingWithLSB(1)), // 00000001\n Arrays.asList(ONE,ZERO,ZERO,ZERO,ZERO,ZERO,ZERO,ZERO));\n assertEquals(this.iteratorToList(factory.fromByteStartingWithLSB(15)),// 00001111\n Arrays.asList(ONE,ONE,ONE,ONE,ZERO,ZERO,ZERO,ZERO));\n assertEquals(this.iteratorToList(factory.fromByteStartingWithLSB(16)),// 00010000\n Arrays.asList(ZERO,ZERO,ZERO,ZERO,ONE,ZERO,ZERO,ZERO));\n assertEquals(this.iteratorToList(factory.fromByteStartingWithLSB(255)),//11111111\n Arrays.asList(ONE,ONE,ONE,ONE,ONE,ONE,ONE,ONE));\n }", "\[email protected]\n public void testFromBitList() {\n // Functioning of an iterator from a list of bits\n final BitIteratorsFactory factory = new BitIteratorsFactoryImpl();\n assertEquals(this.iteratorToList(factory.fromBitList(Arrays.asList(ONE,ZERO,ONE))),\n Arrays.asList(ONE,ZERO,ONE));\n assertEquals(this.iteratorToList(factory.fromBitList(Arrays.asList(ONE,ZERO,ONE,ONE))),\n Arrays.asList(ONE,ZERO,ONE,ONE));\n assertEquals(this.iteratorToList(factory.fromBitList(Arrays.asList(ONE,ZERO))),\n Arrays.asList(ONE,ZERO));\n }", "\[email protected]\n public void optionalTestFromBooleanList() {\n // Functioning of an iterator from a list of booleans\n final BitIteratorsFactory factory = new BitIteratorsFactoryImpl();\n assertEquals(this.iteratorToList(factory.fromBooleanList(Arrays.asList(true,false,true))),\n Arrays.asList(ONE,ZERO,ONE));\n assertEquals(this.iteratorToList(factory.fromBooleanList(Arrays.asList(true,false,true,true))),\n Arrays.asList(ONE,ZERO,ONE,ONE));\n assertEquals(this.iteratorToList(factory.fromBooleanList(Arrays.asList(true,false))),\n Arrays.asList(ONE,ZERO));\n }", "\[email protected]\n public void optionalTestExceptions() {\n // Test of exceptions..\n final BitIteratorsFactory factory = new BitIteratorsFactoryImpl();\n try{\n factory.empty().next();\n fail(\"Empty should fail at first next\");\n }" ] }, "content": "package ex2016.a04.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;\nimport static ex2016.a04.sol1.BitIteratorsFactory.*;\nimport static ex2016.a04.sol1.BitIteratorsFactory.Bit.*;\n\n/**\n * Consult the documentation of the BitIteratorsFactory interface: it models a factory for\n * creating various objects of type java.util.Iterator<Bit>, where Bit is a given enum (nested in the factory).\n * \n * The following are considered optional for the purpose of being able to correct the exercise, but still contribute to achieving \n * the totality of the score:\n * - implementation of optional tests (named 'optionalTestXYZ') \n * - minimization of repetitions\n * - minimization of memory waste, allocating objects of potentially large sizes unnecessarily\n * \n * Observe carefully the following test, 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\n\npublic class Test {\n \n /*\n * A utility function for the test below, which converts a (finite) iterator into a list\n */\n private <T> List<T> iteratorToList(Iterator<T> it){\n final List<T> l = new LinkedList<T>();\n while (it.hasNext()){\n l.add(it.next());\n }\n return l;\n }\n \n @org.junit.Test\n public void testEmpty() {\n // Functioning of an empty iterator\n final BitIteratorsFactory factory = new BitIteratorsFactoryImpl();\n Iterator<BitIteratorsFactory.Bit> empty = factory.empty();\n assertFalse(empty.hasNext());\n }\n \n @org.junit.Test\n public void testZeros() {\n // Functioning of an iterator of zeros\n final BitIteratorsFactory factory = new BitIteratorsFactoryImpl();\n final Iterator<BitIteratorsFactory.Bit> zeros = factory.zeros();\n assertTrue(zeros.hasNext());\n assertEquals(zeros.next(),ZERO);\n assertTrue(zeros.hasNext());\n assertEquals(zeros.next(),ZERO);\n assertTrue(zeros.hasNext());\n assertEquals(zeros.next(),ZERO);\n assertTrue(zeros.hasNext());\n assertEquals(zeros.next(),ZERO);\n assertTrue(zeros.hasNext());\n // ad infinitum\n }\n \n @org.junit.Test\n public void testOnes() {\n // Functioning of an iterator of ones\n final BitIteratorsFactory factory = new BitIteratorsFactoryImpl();\n final Iterator<BitIteratorsFactory.Bit> ones = factory.ones();\n assertTrue(ones.hasNext());\n assertEquals(ones.next(),ONE);\n assertTrue(ones.hasNext());\n assertEquals(ones.next(),ONE);\n assertTrue(ones.hasNext());\n assertEquals(ones.next(),ONE);\n assertTrue(ones.hasNext());\n assertEquals(ones.next(),ONE);\n assertTrue(ones.hasNext());\n // ad infinitum\n }\n \n @org.junit.Test\n public void testFromByte() {\n // Functioning of an iterator of the bits of a byte, from LSB to MSB\n final BitIteratorsFactory factory = new BitIteratorsFactoryImpl();\n assertEquals(this.iteratorToList(factory.fromByteStartingWithLSB(0)), // 00000000\n Arrays.asList(ZERO,ZERO,ZERO,ZERO,ZERO,ZERO,ZERO,ZERO));\n assertEquals(this.iteratorToList(factory.fromByteStartingWithLSB(1)), // 00000001\n Arrays.asList(ONE,ZERO,ZERO,ZERO,ZERO,ZERO,ZERO,ZERO));\n assertEquals(this.iteratorToList(factory.fromByteStartingWithLSB(15)),// 00001111\n Arrays.asList(ONE,ONE,ONE,ONE,ZERO,ZERO,ZERO,ZERO));\n assertEquals(this.iteratorToList(factory.fromByteStartingWithLSB(16)),// 00010000\n Arrays.asList(ZERO,ZERO,ZERO,ZERO,ONE,ZERO,ZERO,ZERO));\n assertEquals(this.iteratorToList(factory.fromByteStartingWithLSB(255)),//11111111\n Arrays.asList(ONE,ONE,ONE,ONE,ONE,ONE,ONE,ONE));\n }\n \n @org.junit.Test\n public void testFromBitList() {\n // Functioning of an iterator from a list of bits\n final BitIteratorsFactory factory = new BitIteratorsFactoryImpl();\n assertEquals(this.iteratorToList(factory.fromBitList(Arrays.asList(ONE,ZERO,ONE))),\n Arrays.asList(ONE,ZERO,ONE));\n assertEquals(this.iteratorToList(factory.fromBitList(Arrays.asList(ONE,ZERO,ONE,ONE))),\n Arrays.asList(ONE,ZERO,ONE,ONE));\n assertEquals(this.iteratorToList(factory.fromBitList(Arrays.asList(ONE,ZERO))),\n Arrays.asList(ONE,ZERO));\n }\n \n @org.junit.Test\n public void optionalTestFromBooleanList() {\n // Functioning of an iterator from a list of booleans\n final BitIteratorsFactory factory = new BitIteratorsFactoryImpl();\n assertEquals(this.iteratorToList(factory.fromBooleanList(Arrays.asList(true,false,true))),\n Arrays.asList(ONE,ZERO,ONE));\n assertEquals(this.iteratorToList(factory.fromBooleanList(Arrays.asList(true,false,true,true))),\n Arrays.asList(ONE,ZERO,ONE,ONE));\n assertEquals(this.iteratorToList(factory.fromBooleanList(Arrays.asList(true,false))),\n Arrays.asList(ONE,ZERO));\n }\n \n @org.junit.Test\n public void optionalTestExceptions() {\n // Test of exceptions..\n final BitIteratorsFactory factory = new BitIteratorsFactoryImpl();\n try{\n factory.empty().next();\n fail(\"Empty should fail at first next\");\n } catch (NoSuchElementException e){}\n catch (Exception e){\n fail(\"Should raise a NoSuchElementException\");\n }\n \n Iterator<Bit> it = factory.fromByteStartingWithLSB(0);\n it.next();\n it.next();\n it.next();\n it.next();\n it.next();\n it.next();\n it.next();\n it.next();\n try{\n it.next();\n fail(\"Should fail at ninth call\");\n } catch (NoSuchElementException e){}\n catch (Exception e){\n fail(\"Should raise a NoSuchElementException\");\n }\n \n it = factory.fromBitList(Arrays.asList(ZERO,ZERO,ONE));\n it.next();\n it.next();\n it.next();\n try{\n it.next();\n fail(\"Should fail at fourth call\");\n } catch (NoSuchElementException e){}\n catch (Exception e){\n fail(\"Should raise a NoSuchElementException\");\n }\n }\n \n \n}", "filename": "Test.java" }
2016
a03a
[ { "content": "package ex2016.a03a.sol1;\n\nimport java.util.*;\nimport java.util.function.*;\n\n\n\ninterface BagFactory {\n \n \n <X> Bag<X> empty();\n \n \n <X> Bag<X> fromSet(Set<X> set);\n \n \n <X> Bag<X> fromList(List<X> list);\n \n \n <X> Bag<X> bySupplier(Supplier<X> supplier, int nElements, ToIntFunction<X> copies);\n \n \n <X> Bag<X> byIteration(X first, UnaryOperator<X> next, int nElements, ToIntFunction<X> copies);\n \n}", "filename": "BagFactory.java" }, { "content": "package ex2016.a03a.sol1;\n\nimport java.util.*;\n\n\npublic interface Bag<X> {\n \n \n int numberOfCopies(X x);\n \n \n int size();\n \n \n List<X> toList();\n \n}", "filename": "Bag.java" } ]
[ { "content": "package ex2016.a03a.sol1;\n\nimport java.util.*;\nimport java.util.stream.*;\nimport java.util.function.*;\n\n\n/**\n * Qui di seguito si fornisce una implementazione che usa gli Stream\n * Implementazioni analoghe senza gli Stream sono comunque simili\n */\npublic class BagFactoryImpl implements BagFactory {\n \n // Nota: uso dei SuppresWarnings non necessario all'esame\n // Tuttavia, quella presentata è la giusta (e avanzata) soluzione per evitare di creare\n // nuove Bag vuote ogni volta\n @SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n private static final Bag EMPTY = new BagImpl(Collections.emptyMap()); \n \n //package protected.. accessible to FactoryImpl\n private static <X> void addMany(Map<X,Integer> map, X x, int copies){\n map.merge(x, copies, (k,v) -> v+copies);\n }\n\n \n @SuppressWarnings(\"unchecked\")\n @Override\n public <X> Bag<X> empty() {\n return (Bag<X>)EMPTY;\n }\n \n private <X> Bag<X> fromIteratorWithCopies(Iterator<X> iterator, ToIntFunction<X> copies) {\n final Map<X,Integer> map = new HashMap<>();\n iterator.forEachRemaining(x -> addMany(map,x,copies.applyAsInt(x)));\n return new BagImpl<>(map);\n }\n\n private <X> Bag<X> fromIterator(Iterator<X> iterator) {\n return fromIteratorWithCopies(iterator, x->1);\n }\n \n @Override\n public <X> Bag<X> fromSet(Set<X> set) {\n return this.fromIterator(set.iterator());\n }\n\n @Override\n public <X> Bag<X> fromList(List<X> list) {\n return this.fromIterator(list.iterator()); \n }\n \n @Override\n public <X> Bag<X> bySupplier(Supplier<X> supplier, int elements, ToIntFunction<X> copies) {\n return fromIteratorWithCopies(Stream.generate(supplier).limit(elements).iterator(),copies);\n }\n\n @Override\n public <X> Bag<X> byIteration(X first, UnaryOperator<X> next, int elements, ToIntFunction<X> copies) {\n return fromIteratorWithCopies(Stream.iterate(first,next).limit(elements).iterator(),copies);\n }\n\n}", "filename": "BagFactoryImpl.java" }, { "content": "package ex2016.a03a.sol1;\n\nimport java.util.*;\nimport java.util.function.Function;\nimport java.util.stream.Collectors;\nimport java.util.stream.Stream;\n\npublic class BagImpl<X> implements Bag<X> {\n \n private final Map<X,Integer> map;\n \n //package protected.. accessible to FactoryImpl\n BagImpl(Map<X, Integer> map) {\n super();\n this.map = Collections.unmodifiableMap(map);\n }\n \n @Override\n public int numberOfCopies(X x) {\n return map.getOrDefault(x, 0);\n }\n\n @Override\n public int size() {\n return map.values().stream().collect(Collectors.summingInt(Integer::intValue));\n }\n\n @Override\n public List<X> toList() {\n return map.entrySet()\n .stream()\n .map(e -> Collections.nCopies(e.getValue(), e.getKey()))\n .map(e -> e.stream())\n .flatMap(x->x)\n .collect(Collectors.toList());\n }\n \n \n\n}", "filename": "BagImpl.java" } ]
{ "components": { "imports": "package ex2016.a03a.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;\n\n/**\n * Consult the documentation of the Bag<X> and BagFactory interfaces.\n * \n * BagFactory (to be implemented in a BagFactory class with a constructor without arguments) models a factory for\n * creating various objects of type Bag<X>, i.e., immutable multisets (sets with repetitions) of elements of type X.\n * \n * Bag<X> has as its fundamental operation that of obtaining how many copies of a certain element are present (0 if it doesn't exist).\n * BagFactory has methods for creating empty Bags, Bags from lists, Bags from sets, Bags from iterations, and Bags from \"suppliers\".\n * \n * The following are considered optional for the possibility of correcting the exercise, but still contribute to achieving\n * the totality of the score:\n * - implementation of optional tests (related to the BagFactory.bySupplier and BagFactory.byIteration methods)\n * - good design of the solution, in particular with minimization of repetitions\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", "test_functions": [ "\[email protected]\n public void testEmpty() {\n // Functioning of an empty bag\n final BagFactory factory = new BagFactoryImpl();\n final Bag<String> bag = factory.empty();\n assertEquals(bag.size(),0);\n assertEquals(bag.numberOfCopies(\"a\"),0);\n assertEquals(bag.numberOfCopies(\"b\"),0);\n assertEquals(bag.toList(), Collections.EMPTY_LIST);\n }", "\[email protected]\n public void testFromSet() {\n // Functioning of the bag {10,20,30}", "\[email protected]\n public void testFromList() {\n // Functioning of the bag {10,10,20}", "\[email protected]\n public void testBySupplier() {\n // Functioning of a bag of 10 random numbers, each present in 5 copies\n final BagFactory factory = new BagFactoryImpl();\n final Bag<Double> bag = factory.bySupplier(()->Math.random(),10,d->5);\n assertEquals(bag.size(), 50);\n final List<Double> elems = bag.toList();\n assertEquals(elems.size(), 50);\n // For each of the 50 elements of the bag (obtained from its toList), I verify that it is present in 5 copies\n for (double d: elems){\n assertEquals(bag.numberOfCopies(d),5);\n }", "\[email protected]\n public void testByIteration() {\n // Functioning of the bag {0,0,1,1,2,2,3,3,..,8,8,9,9}" ] }, "content": "package ex2016.a03a.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;\n\n/**\n * Consult the documentation of the Bag<X> and BagFactory interfaces.\n * \n * BagFactory (to be implemented in a BagFactory class with a constructor without arguments) models a factory for\n * creating various objects of type Bag<X>, i.e., immutable multisets (sets with repetitions) of elements of type X.\n * \n * Bag<X> has as its fundamental operation that of obtaining how many copies of a certain element are present (0 if it doesn't exist).\n * BagFactory has methods for creating empty Bags, Bags from lists, Bags from sets, Bags from iterations, and Bags from \"suppliers\".\n * \n * The following are considered optional for the possibility of correcting the exercise, but still contribute to achieving\n * the totality of the score:\n * - implementation of optional tests (related to the BagFactory.bySupplier and BagFactory.byIteration methods)\n * - good design of the solution, in particular with minimization of repetitions\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 @org.junit.Test\n public void testEmpty() {\n // Functioning of an empty bag\n final BagFactory factory = new BagFactoryImpl();\n final Bag<String> bag = factory.empty();\n assertEquals(bag.size(),0);\n assertEquals(bag.numberOfCopies(\"a\"),0);\n assertEquals(bag.numberOfCopies(\"b\"),0);\n assertEquals(bag.toList(), Collections.EMPTY_LIST);\n }\n \n // Utility function to create a set from a list\n private <X> Set<X> listToSet(List<X> list){\n return new HashSet<>(list);\n }\n \n @org.junit.Test\n public void testFromSet() {\n // Functioning of the bag {10,20,30}\n final BagFactory factory = new BagFactoryImpl();\n final Bag<Integer> bag = factory.fromSet(this.listToSet(Arrays.asList(10,20,30)));\n assertEquals(bag.size(),3);\n assertEquals(bag.numberOfCopies(10),1);\n assertEquals(bag.numberOfCopies(20),1);\n assertEquals(bag.numberOfCopies(40),0);\n // the toList on this bag, converted to set, gives me 10,20,30\n // that is, it contains 10,20,30 in any order\n assertEquals(this.listToSet(bag.toList()), this.listToSet(Arrays.asList(10,20,30)));\n }\n \n // Utility function to return the sorted version of a list\n private <X> List<X> sorted(List<X> list){\n return list.stream().sorted().collect(java.util.stream.Collectors.toList());\n }\n \n @org.junit.Test\n public void testFromList() {\n // Functioning of the bag {10,10,20}\n final BagFactory factory = new BagFactoryImpl();\n final Bag<Integer> bag = factory.fromList(Arrays.asList(10,20,20));\n assertEquals(bag.size(),3);\n assertEquals(bag.numberOfCopies(10),1);\n assertEquals(bag.numberOfCopies(20),2);\n assertEquals(bag.numberOfCopies(40),0);\n // the toList on this bag, sorted, gives me 10,20,20\n assertEquals(sorted(bag.toList()), Arrays.asList(10,20,20));\n }\n \n @org.junit.Test\n public void testBySupplier() {\n // Functioning of a bag of 10 random numbers, each present in 5 copies\n final BagFactory factory = new BagFactoryImpl();\n final Bag<Double> bag = factory.bySupplier(()->Math.random(),10,d->5);\n assertEquals(bag.size(), 50);\n final List<Double> elems = bag.toList();\n assertEquals(elems.size(), 50);\n // For each of the 50 elements of the bag (obtained from its toList), I verify that it is present in 5 copies\n for (double d: elems){\n assertEquals(bag.numberOfCopies(d),5);\n }\n }\n \n @org.junit.Test\n public void testByIteration() {\n // Functioning of the bag {0,0,1,1,2,2,3,3,..,8,8,9,9}\n final BagFactory factory = new BagFactoryImpl();\n final Bag<Integer> bag = factory.byIteration(0,x->x+1,10,d->2);\n assertEquals(bag.size(), 20);\n for (int i=0;i<10;i++){\n assertEquals(bag.numberOfCopies(i),2);\n }\n }\n \n \n}", "filename": "Test.java" }
2016
a02b
[ { "content": "package ex2016.a02b.sol1;\n\n\n\npublic interface LuminousDevice extends Device, Luminous {\n \n}", "filename": "LuminousDevice.java" }, { "content": "package ex2016.a02b.sol1;\n\n\npublic interface Luminous {\n \n \n void dim();\n \n \n void brighten();\n \n \n int getIntesity();\n}", "filename": "Luminous.java" }, { "content": "package ex2016.a02b.sol1;\n\n\npublic interface DeviceFactory {\n \n \n Device createDeviceNeverFailing();\n \n \n Device createDeviceFailingAtSwitchOn(int count);\n \n \n LuminousDevice createLuminousDeviceFailingAtMaxIntensity(int maxIntensity);\n\n}", "filename": "DeviceFactory.java" }, { "content": "package ex2016.a02b.sol1;\n\n\npublic interface Device {\n \n \n void on();\n \n \n void off();\n \n \n boolean isOn();\n \n \n boolean isWorking();\n}", "filename": "Device.java" } ]
[ { "content": "package ex2016.a02b.sol1;\n\npublic class LuminousDeviceImpl extends AbstractDevice implements LuminousDevice {\n \n private final int maxIntensity;\n private int intensity = 0;\n \n public LuminousDeviceImpl(int maxIntensity) {\n this.maxIntensity = maxIntensity;\n }\n\n @Override\n protected boolean tryOn() {\n return this.intensity != this.maxIntensity;\n }\n\n @Override\n public void dim() {\n if (this.intensity > 0){\n this.intensity--;\n }\n }\n\n @Override\n public void brighten() {\n if (this.intensity < this.maxIntensity){\n this.intensity++;\n } \n if (this.intensity == this.maxIntensity && this.isOn()) {\n this.stopWorking();\n }\n }\n\n @Override\n public int getIntesity() {\n return this.intensity;\n }\n\n}", "filename": "LuminousDeviceImpl.java" }, { "content": "package ex2016.a02b.sol1;\n\npublic abstract class AbstractDevice implements Device {\n \n private boolean on = false;\n private boolean working = true;\n\n @Override\n public final void on() {\n if (this.isWorking() && !this.isOn()){\n if (this.tryOn()){\n this.on = true;\n } else {\n this.working = false;\n }\n }\n }\n \n protected abstract boolean tryOn();\n\n @Override\n public void off() {\n this.on = false;\n }\n\n @Override\n public boolean isOn() {\n return this.on;\n }\n\n @Override\n public boolean isWorking() {\n return this.working;\n }\n \n protected void stopWorking(){\n this.working = false;\n this.on = false;\n }\n}", "filename": "AbstractDevice.java" }, { "content": "package ex2016.a02b.sol1;\n\npublic class FailingDeviceImpl extends AbstractDevice {\n\n private int counter;\n \n FailingDeviceImpl(int num){\n this.counter = num;\n }\n \n @Override\n protected boolean tryOn() {\n if (this.counter > 0){\n this.counter--;\n }\n return this.counter > 0;\n }\n\n}", "filename": "FailingDeviceImpl.java" }, { "content": "package ex2016.a02b.sol1;\n\npublic class DeviceFactoryImpl implements DeviceFactory {\n\n @Override\n public Device createDeviceNeverFailing() {\n return new AbstractDevice(){\n\n @Override\n protected boolean tryOn() {\n return true;\n }\n \n };\n }\n\n @Override\n public Device createDeviceFailingAtSwitchOn(int count) {\n return new FailingDeviceImpl(count);\n }\n\n @Override\n public LuminousDevice createLuminousDeviceFailingAtMaxIntensity(int maxIntensity) {\n return new LuminousDeviceImpl(maxIntensity);\n }\n\n}", "filename": "DeviceFactoryImpl.java" } ]
{ "components": { "imports": "package ex2016.a02b.sol1;\n\nimport static org.junit.Assert.*;\n\n/**\n * Please consult the documentation of the provided interfaces (Device, Luminous, LuminousDevice and DeviceFactory).\n * The latter represents a factory for devices of three different types, which must be implemented with a class\n * DeviceFactoryImpl with an empty constructor.\n * The 3 devices, respectively, must be:\n * - device that never fails\n * - device that fails at the Nth switch-on\n * - device with brightness (dim and brighten commands), which fails as soon as it is switched on and at maximum intensity\n * *\n * The following are considered optional for the purpose of being able to correct the exercise, but still contribute to achieving\n * the full score:\n * - the good design of the solution, which passes through the template method pattern to factorize the properties\n * common to the 3 devices to be created.\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 * Remove the comment from the test code.\n */", "private_init": "\t// Complete test for the first device to be created", "test_functions": [ "\[email protected]\n public void testDeviceNeverFailing() {\n DeviceFactory factory = new DeviceFactoryImpl();\n Device device = factory.createDeviceNeverFailing();\n // part off\n assertFalse(device.isOn());\n assertTrue(device.isWorking());\n // turning on and off many times everything works normally\n for (int i=0;i<100;i++){\n device.on();\n assertTrue(device.isOn());\n assertTrue(device.isWorking());\n device.off();\n assertFalse(device.isOn());\n assertTrue(device.isWorking());\n }", "\[email protected]\n public void testFailingDevice() {\n DeviceFactory factory = new DeviceFactoryImpl();\n Device device = factory.createDeviceFailingAtSwitchOn(3);\n assertFalse(device.isOn());\n assertTrue(device.isWorking());\n device.on();\n assertTrue(device.isOn());\n assertTrue(device.isWorking());\n device.off();\n assertFalse(device.isOn());\n assertTrue(device.isWorking());\n device.on();\n device.off();\n assertFalse(device.isOn());\n assertTrue(device.isWorking());\n // so far so good, now I turn it on the third time..\n device.on();\n // the device no longer works, and remains so..\n assertFalse(device.isOn());\n assertFalse(device.isWorking());\n device.on();\n assertFalse(device.isOn());\n assertFalse(device.isWorking());\n }", "\[email protected]\n public void testLuminousDevice() {\n DeviceFactory factory = new DeviceFactoryImpl();\n LuminousDevice device = factory.createLuminousDeviceFailingAtMaxIntensity(10);\n assertFalse(device.isOn());\n assertTrue(device.isWorking());\n // test dim and brigthen\n assertEquals(device.getIntesity(),0);\n device.brighten();\n assertEquals(device.getIntesity(),1);\n device.brighten();\n assertEquals(device.getIntesity(),2);\n device.dim();\n assertEquals(device.getIntesity(),1);\n // as long as I stay below intensity 10.. everything always works\n for (int i=0;i<100;i++){\n device.on();\n assertTrue(device.isOn());\n assertTrue(device.isWorking());\n assertEquals(device.getIntesity(),1);\n device.off();\n assertFalse(device.isOn());\n assertTrue(device.isWorking());\n assertEquals(device.getIntesity(),1);\n }" ] }, "content": "package ex2016.a02b.sol1;\n\nimport static org.junit.Assert.*;\n\n/**\n * Please consult the documentation of the provided interfaces (Device, Luminous, LuminousDevice and DeviceFactory).\n * The latter represents a factory for devices of three different types, which must be implemented with a class\n * DeviceFactoryImpl with an empty constructor.\n * The 3 devices, respectively, must be:\n * - device that never fails\n * - device that fails at the Nth switch-on\n * - device with brightness (dim and brighten commands), which fails as soon as it is switched on and at maximum intensity\n * *\n * The following are considered optional for the purpose of being able to correct the exercise, but still contribute to achieving\n * the full score:\n * - the good design of the solution, which passes through the template method pattern to factorize the properties\n * common to the 3 devices to be created.\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 * Remove the comment from the test code.\n */\n\npublic class Test {\n\n // Complete test for the first device to be created\n @org.junit.Test\n public void testDeviceNeverFailing() {\n DeviceFactory factory = new DeviceFactoryImpl();\n Device device = factory.createDeviceNeverFailing();\n // part off\n assertFalse(device.isOn());\n assertTrue(device.isWorking());\n // turning on and off many times everything works normally\n for (int i=0;i<100;i++){\n device.on();\n assertTrue(device.isOn());\n assertTrue(device.isWorking());\n device.off();\n assertFalse(device.isOn());\n assertTrue(device.isWorking());\n }\n }\n\n // Complete test for the second device to be created\n @org.junit.Test\n public void testFailingDevice() {\n DeviceFactory factory = new DeviceFactoryImpl();\n Device device = factory.createDeviceFailingAtSwitchOn(3);\n assertFalse(device.isOn());\n assertTrue(device.isWorking());\n device.on();\n assertTrue(device.isOn());\n assertTrue(device.isWorking());\n device.off();\n assertFalse(device.isOn());\n assertTrue(device.isWorking());\n device.on();\n device.off();\n assertFalse(device.isOn());\n assertTrue(device.isWorking());\n // so far so good, now I turn it on the third time..\n device.on();\n // the device no longer works, and remains so..\n assertFalse(device.isOn());\n assertFalse(device.isWorking());\n device.on();\n assertFalse(device.isOn());\n assertFalse(device.isWorking());\n }\n\n // Complete test for the third device to be created\n @org.junit.Test\n public void testLuminousDevice() {\n DeviceFactory factory = new DeviceFactoryImpl();\n LuminousDevice device = factory.createLuminousDeviceFailingAtMaxIntensity(10);\n assertFalse(device.isOn());\n assertTrue(device.isWorking());\n // test dim and brigthen\n assertEquals(device.getIntesity(),0);\n device.brighten();\n assertEquals(device.getIntesity(),1);\n device.brighten();\n assertEquals(device.getIntesity(),2);\n device.dim();\n assertEquals(device.getIntesity(),1);\n // as long as I stay below intensity 10.. everything always works\n for (int i=0;i<100;i++){\n device.on();\n assertTrue(device.isOn());\n assertTrue(device.isWorking());\n assertEquals(device.getIntesity(),1);\n device.off();\n assertFalse(device.isOn());\n assertTrue(device.isWorking());\n assertEquals(device.getIntesity(),1);\n }\n // bring the intensity to 10..\n for (int i=1;i<10;i++){\n device.brighten();\n }\n assertFalse(device.isOn());\n assertTrue(device.isWorking());\n assertEquals(device.getIntesity(),10);\n // now I turn it on..\n device.on();\n // the device no longer works and remains so..\n assertFalse(device.isOn());\n assertFalse(device.isWorking());\n assertEquals(device.getIntesity(),10);\n device.dim();\n assertFalse(device.isOn());\n assertFalse(device.isWorking());\n assertEquals(device.getIntesity(),9);\n device.on();\n assertFalse(device.isOn());\n assertFalse(device.isWorking());\n assertEquals(device.getIntesity(),9);\n\n // Another test, it fails when I turn it on to maxIntensity\n LuminousDevice device2 = factory.createLuminousDeviceFailingAtMaxIntensity(10);\n device2.on();\n assertTrue(device2.isOn());\n assertTrue(device2.isWorking());\n assertEquals(device2.getIntesity(),0);\n for (int i=0;i<10;i++){\n device2.brighten();\n }\n assertFalse(device2.isOn());\n assertFalse(device2.isWorking());\n assertEquals(device2.getIntesity(),10);\n }\n\n}", "filename": "Test.java" }
2016
a06
[ { "content": "package pr2016.a06.sol1;\n\nimport java.util.*;\n\n\n\ninterface IntIteratorsFactory {\n \n \n Iterator<Integer> empty();\n \n \n Iterator<Integer> zeros();\n \n \n Iterator<Integer> alternateOneAndZeroIndefinitely();\n \n \n Iterator<Integer> fromTo(int start, int end);\n \n \n Iterator<Integer> fromToIndefinitely(int start, int stop);\n \n \n Iterator<Integer> fromList(List<Integer> list);\n}", "filename": "IntIteratorsFactory.java" } ]
[ { "content": "package pr2016.a06.sol1;\n\nimport java.util.*;\nimport java.util.stream.*;\n\npublic class IntIteratorsFactoryImpl implements IntIteratorsFactory {\n\n private Iterator<Integer> fromStream(Stream<Integer> stream){\n return stream.iterator();\n }\n \n @Override\n public Iterator<Integer> fromList(List<Integer> list){\n return list.iterator();\n }\n \n @Override\n public Iterator<Integer> empty() {\n return this.fromStream(Stream.empty());\n }\n \n private Stream<Integer> fromToStream(int start, int end){\n return IntStream.rangeClosed(start, end).boxed();\n }\n \n @Override\n public Iterator<Integer> fromTo(int start, int end){\n return this.fromStream(fromToStream(start, end));\n }\n\n @Override\n public Iterator<Integer> fromToIndefinitely(int start, int end) {\n return java.util.stream.Stream.<Integer>generate(()->0)\n .<Integer>flatMap(i->fromToStream(start, end))\n .iterator();\n }\n \n @Override\n public Iterator<Integer> zeros(){\n return this.fromToIndefinitely(0, 0);\n }\n \n @Override\n public Iterator<Integer> alternateOneAndZeroIndefinitely() {\n return fromToIndefinitely(0,1);\n }\n\n}", "filename": "IntIteratorsFactoryImpl.java" } ]
{ "components": { "imports": "package pr2016.a06.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;\n\n/**\n * Consult the documentation of the IntIteratorsFactory interface: it models a factory for\n * creating various objects of type java.util.Iterator<Integer>.\n * Implement the factory with an IntIteratorsFactoryImpl class so that it passes the tests below.\n *\n * The following are considered optional for the purpose of being able to correct the exercise, but still contribute to achieving\n * the entirety of the score:\n * - implementation of the optional test (the last one, called 'optionalTestAlternateOneAndZeroIndefinitely')\n * - minimization of repetitions\n * - minimization of memory waste, allocating objects of potentially large sizes unnecessarily\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/*\n * A utility function for the test below, which converts a (finite) iterator into a list\n */\n private <T> List<T> iteratorToList(Iterator<T> it){\n final List<T> l = new LinkedList<T>();\n while (it.hasNext()){\n l.add(it.next());\n }\n return l;\n }", "test_functions": [ "\[email protected]\n public void testEmpty() {\n // Functioning of an empty iterator\n final IntIteratorsFactory factory = new IntIteratorsFactoryImpl();\n Iterator<Integer> empty = factory.empty();\n assertFalse(empty.hasNext());\n }", "\[email protected]\n public void testZeros() {\n // Functioning of an iterator of zeros\n final IntIteratorsFactory factory = new IntIteratorsFactoryImpl();\n final Iterator<Integer> zeros = factory.zeros();\n assertTrue(zeros.hasNext());\n assertSame(zeros.next(),0);\n assertTrue(zeros.hasNext());\n assertSame(zeros.next(),0);\n assertTrue(zeros.hasNext());\n assertSame(zeros.next(),0);\n assertTrue(zeros.hasNext());\n assertSame(zeros.next(),0);\n assertTrue(zeros.hasNext());\n // ad infinitum\n }", "\[email protected]\n public void testFromTo() {\n // Functioning of an iterator from 1 to 5\n final IntIteratorsFactory factory = new IntIteratorsFactoryImpl();\n final Iterator<Integer> oneToFive = factory.fromTo(1, 5);\n assertEquals(Arrays.asList(1,2,3,4,5),iteratorToList(oneToFive));\n }", "\[email protected]\n public void testFromList() {\n // Functioning of an iterator from a list\n final IntIteratorsFactory factory = new IntIteratorsFactoryImpl();\n List<Integer> list = Arrays.asList(10,20,30,40,5,6,7,100);\n assertEquals(list,iteratorToList(factory.fromList(list)));\n }", "\[email protected]\n public void testFromToIndefinitely() {\n // Functioning of an iterator from 0 to 2 with repetition\n final IntIteratorsFactory factory = new IntIteratorsFactoryImpl();\n final Iterator<Integer> zeroToTwoInd = factory.fromToIndefinitely(0, 2);\n assertTrue(zeroToTwoInd.hasNext());\n assertSame(zeroToTwoInd.next(),0);\n assertTrue(zeroToTwoInd.hasNext());\n assertSame(zeroToTwoInd.next(),1);\n assertTrue(zeroToTwoInd.hasNext());\n assertSame(zeroToTwoInd.next(),2);\n assertTrue(zeroToTwoInd.hasNext());\n assertSame(zeroToTwoInd.next(),0);\n assertTrue(zeroToTwoInd.hasNext());\n assertSame(zeroToTwoInd.next(),1);\n assertTrue(zeroToTwoInd.hasNext());\n assertSame(zeroToTwoInd.next(),2);\n assertTrue(zeroToTwoInd.hasNext());\n assertSame(zeroToTwoInd.next(),0);\n assertTrue(zeroToTwoInd.hasNext());\n assertSame(zeroToTwoInd.next(),1);\n assertTrue(zeroToTwoInd.hasNext());\n assertSame(zeroToTwoInd.next(),2);\n // ad infinitum\n }", "\[email protected]\n public void optionalTestAlternateOneAndZeroIndefinitely() {\n // Functioning of an iterator of zero, one, zero, one,..\n final IntIteratorsFactory factory = new IntIteratorsFactoryImpl();\n final Iterator<Integer> zeroOneInd = factory.alternateOneAndZeroIndefinitely();\n assertTrue(zeroOneInd.hasNext());\n assertSame(zeroOneInd.next(),0);\n assertTrue(zeroOneInd.hasNext());\n assertSame(zeroOneInd.next(),1);\n assertTrue(zeroOneInd.hasNext());\n assertSame(zeroOneInd.next(),0);\n assertTrue(zeroOneInd.hasNext());\n assertSame(zeroOneInd.next(),1);\n assertTrue(zeroOneInd.hasNext());\n assertSame(zeroOneInd.next(),0);\n assertTrue(zeroOneInd.hasNext());\n // ad infinitum\n }" ] }, "content": "package pr2016.a06.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;\n\n/**\n * Consult the documentation of the IntIteratorsFactory interface: it models a factory for\n * creating various objects of type java.util.Iterator<Integer>.\n * Implement the factory with an IntIteratorsFactoryImpl class so that it passes the tests below.\n *\n * The following are considered optional for the purpose of being able to correct the exercise, but still contribute to achieving\n * the entirety of the score:\n * - implementation of the optional test (the last one, called 'optionalTestAlternateOneAndZeroIndefinitely')\n * - minimization of repetitions\n * - minimization of memory waste, allocating objects of potentially large sizes unnecessarily\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\n\npublic class Test {\n \n /*\n * A utility function for the test below, which converts a (finite) iterator into a list\n */\n private <T> List<T> iteratorToList(Iterator<T> it){\n final List<T> l = new LinkedList<T>();\n while (it.hasNext()){\n l.add(it.next());\n }\n return l;\n }\n \n @org.junit.Test\n public void testEmpty() {\n // Functioning of an empty iterator\n final IntIteratorsFactory factory = new IntIteratorsFactoryImpl();\n Iterator<Integer> empty = factory.empty();\n assertFalse(empty.hasNext());\n }\n \n @org.junit.Test\n public void testZeros() {\n // Functioning of an iterator of zeros\n final IntIteratorsFactory factory = new IntIteratorsFactoryImpl();\n final Iterator<Integer> zeros = factory.zeros();\n assertTrue(zeros.hasNext());\n assertSame(zeros.next(),0);\n assertTrue(zeros.hasNext());\n assertSame(zeros.next(),0);\n assertTrue(zeros.hasNext());\n assertSame(zeros.next(),0);\n assertTrue(zeros.hasNext());\n assertSame(zeros.next(),0);\n assertTrue(zeros.hasNext());\n // ad infinitum\n }\n \n @org.junit.Test\n public void testFromTo() {\n // Functioning of an iterator from 1 to 5\n final IntIteratorsFactory factory = new IntIteratorsFactoryImpl();\n final Iterator<Integer> oneToFive = factory.fromTo(1, 5);\n assertEquals(Arrays.asList(1,2,3,4,5),iteratorToList(oneToFive));\n }\n \n\n @org.junit.Test\n public void testFromList() {\n // Functioning of an iterator from a list\n final IntIteratorsFactory factory = new IntIteratorsFactoryImpl();\n List<Integer> list = Arrays.asList(10,20,30,40,5,6,7,100);\n assertEquals(list,iteratorToList(factory.fromList(list)));\n }\n \n \n @org.junit.Test\n public void testFromToIndefinitely() {\n // Functioning of an iterator from 0 to 2 with repetition\n final IntIteratorsFactory factory = new IntIteratorsFactoryImpl();\n final Iterator<Integer> zeroToTwoInd = factory.fromToIndefinitely(0, 2);\n assertTrue(zeroToTwoInd.hasNext());\n assertSame(zeroToTwoInd.next(),0);\n assertTrue(zeroToTwoInd.hasNext());\n assertSame(zeroToTwoInd.next(),1);\n assertTrue(zeroToTwoInd.hasNext());\n assertSame(zeroToTwoInd.next(),2);\n assertTrue(zeroToTwoInd.hasNext());\n assertSame(zeroToTwoInd.next(),0);\n assertTrue(zeroToTwoInd.hasNext());\n assertSame(zeroToTwoInd.next(),1);\n assertTrue(zeroToTwoInd.hasNext());\n assertSame(zeroToTwoInd.next(),2);\n assertTrue(zeroToTwoInd.hasNext());\n assertSame(zeroToTwoInd.next(),0);\n assertTrue(zeroToTwoInd.hasNext());\n assertSame(zeroToTwoInd.next(),1);\n assertTrue(zeroToTwoInd.hasNext());\n assertSame(zeroToTwoInd.next(),2);\n // ad infinitum\n }\n \n @org.junit.Test\n public void optionalTestAlternateOneAndZeroIndefinitely() {\n // Functioning of an iterator of zero, one, zero, one,..\n final IntIteratorsFactory factory = new IntIteratorsFactoryImpl();\n final Iterator<Integer> zeroOneInd = factory.alternateOneAndZeroIndefinitely();\n assertTrue(zeroOneInd.hasNext());\n assertSame(zeroOneInd.next(),0);\n assertTrue(zeroOneInd.hasNext());\n assertSame(zeroOneInd.next(),1);\n assertTrue(zeroOneInd.hasNext());\n assertSame(zeroOneInd.next(),0);\n assertTrue(zeroOneInd.hasNext());\n assertSame(zeroOneInd.next(),1);\n assertTrue(zeroOneInd.hasNext());\n assertSame(zeroOneInd.next(),0);\n assertTrue(zeroOneInd.hasNext());\n // ad infinitum\n }\n \n}", "filename": "Test.java" }
2016
a01a
[ { "content": "package ex2016.a01a.sol1;\n\nimport java.util.*;\n\n\npublic interface Sequence<X> {\n \n \n Optional<X> getAtPosition(int position);\n \n \n int size();\n \n \n List<X> asList();\n \n \n void executeOnAllElements(Executor<X> executor);\n \n\n \n interface Executor<X> {\n void execute(X x);\n }\n \n}", "filename": "Sequence.java" }, { "content": "package ex2016.a01a.sol1;\n\nimport java.util.Optional;\n\n\n\ninterface SequenceBuilder<X> {\n \n \n void addElement(X x);\n \n \n void removeElement(int position);\n \n \n void reverse();\n \n \n void clear();\n \n \n Optional<Sequence<X>> build();\n \n \n Optional<Sequence<X>> buildWithFilter(Filter<X> filter);\n \n \n <Y> SequenceBuilder<Y> mapToNewBuilder(Mapper<X,Y> mapper);\n \n \n interface Filter<X> {\n boolean check(X x);\n }\n \n \n interface Mapper<X,Y> {\n Y transform(X x);\n }\n}", "filename": "SequenceBuilder.java" } ]
[ { "content": "package ex2016.a01a.sol1;\n\nimport java.util.*;\n\npublic class SequenceImpl<X> implements Sequence<X> {\n \n private final List<X> list;\n \n SequenceImpl(List<X> list){\n this.list = Collections.unmodifiableList(list);\n }\n\n @Override\n public Optional<X> getAtPosition(int position) {\n return position >=0 && position < this.size() ? Optional.of(this.list.get(position)) : Optional.empty();\n }\n\n @Override\n public int size() {\n return this.list.size();\n }\n\n @Override\n public List<X> asList(){\n return this.list;\n }\n \n @Override\n public void executeOnAllElements(Executor<X> executor){\n this.list.forEach(executor::execute);\n }\n}", "filename": "SequenceImpl.java" }, { "content": "package ex2016.a01a.sol1;\n\nimport java.util.*;\n\n\npublic class SequenceBuilderImpl<X> implements SequenceBuilder<X> {\n\n private final List<X> list = new ArrayList<X>();\n private boolean done = false;\n \n @Override\n public void addElement(X x) {\n this.list.add(x);\n }\n \n @Override\n public void removeElement(int position) {\n this.list.remove(position); \n }\n\n @Override\n public void reverse() {\n Collections.reverse(this.list);\n }\n\n @Override\n public void clear() {\n this.list.clear();\n }\n \n @Override\n public Optional<Sequence<X>> build() {\n return this.buildWithFilter(x -> true);\n }\n \n @Override\n public Optional<Sequence<X>> buildWithFilter(Filter<X> filter) {\n if (this.done || !this.list.stream().allMatch(filter::check)) {\n return Optional.empty();\n }\n this.done = true;\n return Optional.of(new SequenceImpl<X>(this.list));\n }\n \n @Override\n public <Y> SequenceBuilder<Y> mapToNewBuilder(Mapper<X, Y> mapper) {\n final SequenceBuilder<Y> builder = new SequenceBuilderImpl<>();\n this.list.forEach(x -> builder.addElement(mapper.transform(x)));\n return builder;\n }\n\n}", "filename": "SequenceBuilderImpl.java" } ]
{ "components": { "imports": "package ex2016.a01a.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;\n\n/**\n * See the documentation of the interfaces SequenceBuilder and Sequence.\n * \n * SequenceBuilder (to be implemented in a class SequenceBuilderImpl with a constructor without arguments) models a builder\n * for objects of type Sequence.\n * \n * Sequence models an immutable sequence of elements\n * (with methods to read length, elements, convert to a list, and execute actions on all elements).\n * \n * SequenceBuilder has methods to add, remove, and reverse elements, and to generate new builders via 'map'.\n * When building the sequence, you can accept a filter to verify that all elements have certain characteristics.\n * \n * The interfaces mention the class java.util.Optional<X>, used to contain or not an element of type X. Remember\n * that objects are constructed with the static methods Optional.of and Optional.empty, and the content is read with\n * the instance methods Optional.isPresent and Optional.get.\n * \n * The following are considered optional for the purpose of being able to correct the exercise, but still contribute to achieving\n * the entirety of the score:\n * - implementation of optional tests (related to the methods SequenceBuilder.mapToNewBuilder and SequenceBuilder.buildWithFilter)\n * - good design of the solution\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 * Remove the comment from the test code.\n */", "private_init": "\t", "test_functions": [ "\[email protected]\n public void testBasic() {\n // A builder used to create the immutable list of elements \"a\",\"b\",\"c\"\n SequenceBuilder<String> b1 = new SequenceBuilderImpl<>();\n b1.addElement(\"a\");\n b1.addElement(\"b\");\n b1.addElement(\"c\");\n // I construct the sequence (without errors, the optional is present)\n final Sequence<String> is = b1.build().get();\n assertEquals(is.asList(), Arrays.asList(\"a\",\"b\",\"c\"));\n assertEquals(is.size(), 3);\n assertEquals(is.getAtPosition(0).get(), \"a\");\n assertEquals(is.getAtPosition(1).get(), \"b\");\n assertEquals(is.getAtPosition(2).get(), \"c\");\n assertFalse(is.getAtPosition(3).isPresent());\n List<String> ls = new ArrayList<>();\n is.executeOnAllElements(s -> ls.add(s)); // for each element of is, I add it to ls\n assertEquals(ls, Arrays.asList(\"a\",\"b\",\"c\"));\n // After doing a build, you can't redo it..\n assertFalse(b1.build().isPresent());\n }", "\[email protected]\n public void testRemove() {\n SequenceBuilder<String> b1 = new SequenceBuilderImpl<>();\n b1.addElement(\"a\");\n b1.addElement(\"b\");\n b1.addElement(\"c\");\n b1.removeElement(1);\n assertEquals(b1.build().get().asList(), Arrays.asList(\"a\",\"c\"));\n }", "\[email protected]\n public void testReverse() {\n SequenceBuilder<String> b1 = new SequenceBuilderImpl<>();\n b1.addElement(\"a\");\n b1.addElement(\"b\");\n b1.addElement(\"c\");\n b1.reverse();\n assertEquals(b1.build().get().asList(), Arrays.asList(\"c\",\"b\",\"a\"));\n }", "\[email protected]\n public void testClear() {\n SequenceBuilder<String> b1 = new SequenceBuilderImpl<>();\n b1.addElement(\"a\");\n b1.addElement(\"b\");\n b1.addElement(\"c\");\n b1.clear();\n assertEquals(b1.build().get().asList(), Arrays.asList());\n }", "\[email protected]\n public void optionalTestMap() {\n SequenceBuilder<String> b1 = new SequenceBuilderImpl<>();\n b1.addElement(\"a\");\n b1.addElement(\"bb\");\n b1.addElement(\"ccc\");\n SequenceBuilder<Integer> b2 = b1.mapToNewBuilder(s -> s.length()*10);\n assertEquals(b2.build().get().asList(), Arrays.asList(10,20,30));\n }", "\[email protected]\n public void optionalTestBuildWithFilter() {\n SequenceBuilder<String> b1 = new SequenceBuilderImpl<>();\n b1.addElement(\"a\");\n b1.addElement(\"bb\");\n b1.addElement(\"c\");\n assertFalse(b1.buildWithFilter(s -> s.length() == 1).isPresent());\n b1.removeElement(1);\n Optional<Sequence<String>> opt = b1.buildWithFilter(s -> s.length() == 1); \n assertTrue(opt.isPresent());\n assertEquals(opt.get().asList(), Arrays.asList(\"a\",\"c\"));\n }" ] }, "content": "package ex2016.a01a.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;\n\n/**\n * See the documentation of the interfaces SequenceBuilder and Sequence.\n * \n * SequenceBuilder (to be implemented in a class SequenceBuilderImpl with a constructor without arguments) models a builder\n * for objects of type Sequence.\n * \n * Sequence models an immutable sequence of elements\n * (with methods to read length, elements, convert to a list, and execute actions on all elements).\n * \n * SequenceBuilder has methods to add, remove, and reverse elements, and to generate new builders via 'map'.\n * When building the sequence, you can accept a filter to verify that all elements have certain characteristics.\n * \n * The interfaces mention the class java.util.Optional<X>, used to contain or not an element of type X. Remember\n * that objects are constructed with the static methods Optional.of and Optional.empty, and the content is read with\n * the instance methods Optional.isPresent and Optional.get.\n * \n * The following are considered optional for the purpose of being able to correct the exercise, but still contribute to achieving\n * the entirety of the score:\n * - implementation of optional tests (related to the methods SequenceBuilder.mapToNewBuilder and SequenceBuilder.buildWithFilter)\n * - good design of the solution\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 * Remove the comment from the test code.\n */\n\npublic class Test {\n \n @org.junit.Test\n public void testBasic() {\n // A builder used to create the immutable list of elements \"a\",\"b\",\"c\"\n SequenceBuilder<String> b1 = new SequenceBuilderImpl<>();\n b1.addElement(\"a\");\n b1.addElement(\"b\");\n b1.addElement(\"c\");\n // I construct the sequence (without errors, the optional is present)\n final Sequence<String> is = b1.build().get();\n assertEquals(is.asList(), Arrays.asList(\"a\",\"b\",\"c\"));\n assertEquals(is.size(), 3);\n assertEquals(is.getAtPosition(0).get(), \"a\");\n assertEquals(is.getAtPosition(1).get(), \"b\");\n assertEquals(is.getAtPosition(2).get(), \"c\");\n assertFalse(is.getAtPosition(3).isPresent());\n List<String> ls = new ArrayList<>();\n is.executeOnAllElements(s -> ls.add(s)); // for each element of is, I add it to ls\n assertEquals(ls, Arrays.asList(\"a\",\"b\",\"c\"));\n // After doing a build, you can't redo it..\n assertFalse(b1.build().isPresent());\n }\n \n @org.junit.Test\n public void testRemove() {\n SequenceBuilder<String> b1 = new SequenceBuilderImpl<>();\n b1.addElement(\"a\");\n b1.addElement(\"b\");\n b1.addElement(\"c\");\n b1.removeElement(1);\n assertEquals(b1.build().get().asList(), Arrays.asList(\"a\",\"c\"));\n }\n \n \n @org.junit.Test\n public void testReverse() {\n SequenceBuilder<String> b1 = new SequenceBuilderImpl<>();\n b1.addElement(\"a\");\n b1.addElement(\"b\");\n b1.addElement(\"c\");\n b1.reverse();\n assertEquals(b1.build().get().asList(), Arrays.asList(\"c\",\"b\",\"a\"));\n }\n \n @org.junit.Test\n public void testClear() {\n SequenceBuilder<String> b1 = new SequenceBuilderImpl<>();\n b1.addElement(\"a\");\n b1.addElement(\"b\");\n b1.addElement(\"c\");\n b1.clear();\n assertEquals(b1.build().get().asList(), Arrays.asList());\n }\n\n @org.junit.Test\n public void optionalTestMap() {\n SequenceBuilder<String> b1 = new SequenceBuilderImpl<>();\n b1.addElement(\"a\");\n b1.addElement(\"bb\");\n b1.addElement(\"ccc\");\n SequenceBuilder<Integer> b2 = b1.mapToNewBuilder(s -> s.length()*10);\n assertEquals(b2.build().get().asList(), Arrays.asList(10,20,30));\n }\n \n @org.junit.Test\n public void optionalTestBuildWithFilter() {\n SequenceBuilder<String> b1 = new SequenceBuilderImpl<>();\n b1.addElement(\"a\");\n b1.addElement(\"bb\");\n b1.addElement(\"c\");\n assertFalse(b1.buildWithFilter(s -> s.length() == 1).isPresent());\n b1.removeElement(1);\n Optional<Sequence<String>> opt = b1.buildWithFilter(s -> s.length() == 1); \n assertTrue(opt.isPresent());\n assertEquals(opt.get().asList(), Arrays.asList(\"a\",\"c\"));\n }\n}", "filename": "Test.java" }
2016
a02a
[ { "content": "package ex2016.a02a.sol1;\n\nimport java.util.*;\n\n\n\n\npublic interface MultiQueue<T,Q> {\n \n \n Set<Q> availableQueues();\n \n \n void openNewQueue(Q queue);\n \n \n boolean isQueueEmpty(Q queue);\n \n \n void enqueue(T elem, Q queue);\n \n \n Optional<T> dequeue(Q queue);\n \n \n Map<Q,Optional<T>> dequeueOneFromAllQueues();\n \n \n Set<T> allEnqueuedElements();\n \n \n List<T> dequeueAllFromQueue(Q queue);\n \n \n void closeQueueAndReallocate(Q queue); \n}", "filename": "MultiQueue.java" } ]
[ { "content": "package ex2016.a02a.sol1;\n\nimport java.util.*;\nimport java.util.function.Supplier;\nimport java.util.stream.Collectors;\n\npublic class MultiQueueImpl<T, Q> implements MultiQueue<T, Q> {\n \n private final static Supplier<RuntimeException> ILLEGAL_ARGUMENT_EXCEPTION_SUPPLIER = ()->new IllegalArgumentException();\n private final static Supplier<RuntimeException> ILLEGAL_EXCEPTION_SUPPLIER = ()->new IllegalStateException();\n \n private Map<Q,List<T>> map = new HashMap<>();\n \n @Override\n public Set<Q> availableQueues() {\n return this.map.keySet();\n }\n\n @Override\n public void openNewQueue(Q queue) {\n raiseException(this.map.containsKey(queue), ILLEGAL_ARGUMENT_EXCEPTION_SUPPLIER);\n this.map.put(queue, createEmptyList());\n }\n\n @Override\n public boolean isQueueEmpty(Q queue) {\n raiseException(!this.map.containsKey(queue), ILLEGAL_ARGUMENT_EXCEPTION_SUPPLIER);\n return this.map.get(queue).isEmpty();\n }\n\n @Override\n public void enqueue(T elem, Q queue) {\n raiseException(!this.map.containsKey(queue), ILLEGAL_ARGUMENT_EXCEPTION_SUPPLIER);\n this.map.get(queue).add(elem);\n }\n\n @Override\n public Optional<T> dequeue(Q queue) {\n raiseException(!this.map.containsKey(queue), ILLEGAL_ARGUMENT_EXCEPTION_SUPPLIER);\n List<T> list = this.map.get(queue);\n if (list.isEmpty()){\n return Optional.empty();\n }\n return Optional.of(list.remove(0));\n }\n\n @Override\n public Map<Q, Optional<T>> dequeueOneFromAllQueues() {\n Map<Q,Optional<T>> res = new HashMap<>();\n for (Q queue: this.map.keySet()){\n res.put(queue, dequeue(queue));\n }\n return Collections.unmodifiableMap(res);\n }\n\n @Override\n public List<T> dequeueAllFromQueue(Q queue) {\n raiseException(!this.map.containsKey(queue), ILLEGAL_ARGUMENT_EXCEPTION_SUPPLIER);\n List<T> list = this.map.get(queue);\n this.map.put(queue, createEmptyList());\n return Collections.unmodifiableList(list);\n }\n \n @Override\n public void closeQueueAndReallocate(Q queue) {\n raiseException(!this.map.containsKey(queue), ILLEGAL_ARGUMENT_EXCEPTION_SUPPLIER);\n raiseException(this.map.size()==1, ILLEGAL_EXCEPTION_SUPPLIER);\n List<T> elems = this.dequeueAllFromQueue(queue);\n this.map.remove(queue);\n Q q = this.map.keySet().stream().findAny().get();\n elems.forEach(t -> this.enqueue(t, q));\n }\n\n @Override\n public Set<T> allEnqueuedElements() {\n return this.map.values().stream().flatMap(Collection::stream).collect(Collectors.toSet());\n }\n \n private static <T> List<T> createEmptyList(){\n return new LinkedList<>();\n }\n \n private void raiseException(boolean condition, Supplier<RuntimeException> supplier){\n if (condition){\n throw supplier.get();\n }\n }\n \n\n}", "filename": "MultiQueueImpl.java" } ]
{ "components": { "imports": "package ex2016.a02a.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;\n\n/**\n * See the documentation of the MultiQueue interface, which represents a multiple queue (FIFO), such as at the supermarket\n * where there are multiple cash registers with queues of people waiting (cash registers that open and close). It provides operations for:\n * - adding an element to a queue (enqueue, read 'enchiù', models the arrival of a new person in a queue)\n * - removing an element from the queue (to serve the next person in a queue, dequeue)\n * - opening a new queue (cash register that opens)\n * - closing an existing queue (cash register that closes, and all people are redirected to another queue)\n * - ..and others\n * \n * Implement this interface with a MultiQueueImpl class, with an empty constructor.\n *\n * The problem mentions the java.util.Optional<X> class, whose objects are used to contain or not contain an element of type X. Remember\n * that objects are constructed with the static methods Optional.of and Optional.empty, and the content is read with the instance methods\n * Optional.isPresent and Optional.get.\n * \n * The following are considered optional for the purpose of being able to correct the exercise, but still contribute to achieving\n * the totality of the score:\n * - implementation of optional tests (related to exception handling and the realization of the closeQueueAndReallocate method)\n * - good design of the solution\n * \n * Observe carefully the following test, 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// In these tests, we only consider multi-queues with queues represented with strings, containing integer elements\n // Your solution must be generic, though!", "test_functions": [ "\[email protected]\n public void testBasic() {\n // Creates queues Q1 and Q2, and puts an element in Q2\n MultiQueue<Integer,String> mq = new MultiQueueImpl<>();\n assertEquals(mq.availableQueues().size(),0);\n mq.openNewQueue(\"Q1\");\n mq.openNewQueue(\"Q2\");\n assertEquals(mq.availableQueues(),new HashSet<>(Arrays.asList(\"Q1\",\"Q2\")));\n mq.enqueue(1000, \"Q2\");\n // Checks which queues are empty\n assertTrue(mq.isQueueEmpty(\"Q1\"));\n assertFalse(mq.isQueueEmpty(\"Q2\"));\n }", "\[email protected]\n public void testEnqueue() {\n // Creates queues Q1 and Q2, and puts various elements inside\n MultiQueue<Integer,String> mq = new MultiQueueImpl<>();\n assertEquals(mq.allEnqueuedElements().size(),0);\n mq.openNewQueue(\"Q1\");\n mq.openNewQueue(\"Q2\");\n mq.enqueue(1000, \"Q2\");\n mq.enqueue(1001, \"Q2\");\n mq.enqueue(1002, \"Q2\");\n mq.enqueue(1003, \"Q1\");\n mq.enqueue(1004, \"Q1\");\n // Checks which elements are in the queue overall\n assertEquals(mq.allEnqueuedElements(),new HashSet<>(Arrays.asList(1000,1001,1002,1003,1004)));\n }", "\[email protected]\n public void testDequeue() {\n // Creates queues Q1 and Q2, and puts various elements inside\n MultiQueue<Integer,String> mq = new MultiQueueImpl<>();\n assertEquals(mq.allEnqueuedElements().size(),0);\n mq.openNewQueue(\"Q1\");\n mq.openNewQueue(\"Q2\");\n mq.enqueue(1000, \"Q2\");\n mq.enqueue(1001, \"Q2\");\n mq.enqueue(1002, \"Q2\");\n mq.enqueue(1003, \"Q1\");\n mq.enqueue(1004, \"Q1\");\n // Checks the order of removal of the elements\n assertEquals(mq.dequeue(\"Q1\"),Optional.of(1003));\n assertEquals(mq.dequeue(\"Q2\"),Optional.of(1000));\n assertEquals(mq.dequeue(\"Q2\"),Optional.of(1001));\n assertEquals(mq.dequeue(\"Q2\"),Optional.of(1002));\n assertEquals(mq.dequeue(\"Q2\"),Optional.empty());\n assertEquals(mq.dequeue(\"Q2\"),Optional.empty());\n // More additions and removals..\n mq.enqueue(1005, \"Q1\");\n mq.enqueue(1006, \"Q2\");\n assertEquals(mq.dequeue(\"Q2\"),Optional.of(1006));\n assertEquals(mq.allEnqueuedElements(),new HashSet<>(Arrays.asList(1004,1005))); \n }", "\[email protected]\n public void testFullDequeue() {\n // Creates queues Q1 and Q2, and puts various elements inside\n MultiQueue<Integer,String> mq = new MultiQueueImpl<>();\n assertEquals(mq.allEnqueuedElements().size(),0);\n mq.openNewQueue(\"Q1\");\n mq.openNewQueue(\"Q2\");\n mq.enqueue(1000, \"Q2\");\n mq.enqueue(1001, \"Q2\");\n mq.enqueue(1002, \"Q2\");\n mq.enqueue(1003, \"Q1\");\n mq.enqueue(1004, \"Q1\");\n // Removes all elements from a queue\n assertEquals(mq.dequeueAllFromQueue(\"Q2\"), Arrays.asList(1000,1001,1002));\n assertEquals(mq.dequeueAllFromQueue(\"Q2\").size(),0);\n }", "\[email protected]\n public void testDequeueOneFromAll() {\n // Creates queues Q1 and Q2 and Q3, and puts various elements in Q1 and Q2\n MultiQueue<Integer,String> mq = new MultiQueueImpl<>();\n assertEquals(mq.allEnqueuedElements().size(),0);\n mq.openNewQueue(\"Q1\");\n mq.openNewQueue(\"Q2\");\n mq.openNewQueue(\"Q3\"); \n mq.enqueue(1000, \"Q2\");\n mq.enqueue(1001, \"Q2\");\n mq.enqueue(1002, \"Q2\");\n mq.enqueue(1003, \"Q1\");\n mq.enqueue(1004, \"Q1\");\n // Removes one element from each queue\n Map<String,Optional<Integer>> map = mq.dequeueOneFromAllQueues();\n assertEquals(map.size(), 3);\n assertEquals(map.get(\"Q1\"), Optional.of(1003));\n assertEquals(map.get(\"Q2\"), Optional.of(1000));\n assertEquals(map.get(\"Q3\"), Optional.empty());\n }", "\[email protected]\n public void optionalTestCloseAndReallocate() {\n // Creates queues Q1 and Q2 and Q3, and puts various elements inside\n MultiQueue<Integer,String> mq = new MultiQueueImpl<>();\n assertEquals(mq.allEnqueuedElements().size(),0);\n mq.openNewQueue(\"Q1\");\n mq.openNewQueue(\"Q2\");\n mq.openNewQueue(\"Q3\"); \n mq.enqueue(1000, \"Q2\");\n mq.enqueue(1001, \"Q2\");\n mq.enqueue(1002, \"Q2\");\n mq.enqueue(1003, \"Q1\");\n mq.enqueue(1004, \"Q1\");\n mq.enqueue(1005, \"Q3\");\n assertEquals(mq.availableQueues(),new HashSet<>(Arrays.asList(\"Q1\",\"Q2\",\"Q3\")));\n assertEquals(mq.allEnqueuedElements(),new HashSet<>(Arrays.asList(1000,1001,1002,1003,1004,1005))); \n // Closes Q1, its elements must end up in some other queue\n mq.closeQueueAndReallocate(\"Q1\");\n assertEquals(mq.allEnqueuedElements(),new HashSet<>(Arrays.asList(1000,1001,1002,1003,1004,1005)));\n assertEquals(mq.availableQueues(),new HashSet<>(Arrays.asList(\"Q2\",\"Q3\")));\n }", "\[email protected]\n public void optionalTestExceptions() {\n // Tests and the various exceptions\n MultiQueue<Integer,String> mq = new MultiQueueImpl<>();\n assertEquals(mq.allEnqueuedElements().size(),0);\n mq.openNewQueue(\"Q1\");\n mq.openNewQueue(\"Q3\");\n mq.enqueue(1000, \"Q1\");\n try{\n mq.openNewQueue(\"Q1\");\n fail(\"can't open Q1 again\");\n }" ] }, "content": "package ex2016.a02a.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;\n\n/**\n * See the documentation of the MultiQueue interface, which represents a multiple queue (FIFO), such as at the supermarket\n * where there are multiple cash registers with queues of people waiting (cash registers that open and close). It provides operations for:\n * - adding an element to a queue (enqueue, read 'enchiù', models the arrival of a new person in a queue)\n * - removing an element from the queue (to serve the next person in a queue, dequeue)\n * - opening a new queue (cash register that opens)\n * - closing an existing queue (cash register that closes, and all people are redirected to another queue)\n * - ..and others\n * \n * Implement this interface with a MultiQueueImpl class, with an empty constructor.\n *\n * The problem mentions the java.util.Optional<X> class, whose objects are used to contain or not contain an element of type X. Remember\n * that objects are constructed with the static methods Optional.of and Optional.empty, and the content is read with the instance methods\n * Optional.isPresent and Optional.get.\n * \n * The following are considered optional for the purpose of being able to correct the exercise, but still contribute to achieving\n * the totality of the score:\n * - implementation of optional tests (related to exception handling and the realization of the closeQueueAndReallocate method)\n * - good design of the solution\n * \n * Observe carefully the following test, 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 // In these tests, we only consider multi-queues with queues represented with strings, containing integer elements\n // Your solution must be generic, though!\n \n @org.junit.Test\n public void testBasic() {\n // Creates queues Q1 and Q2, and puts an element in Q2\n MultiQueue<Integer,String> mq = new MultiQueueImpl<>();\n assertEquals(mq.availableQueues().size(),0);\n mq.openNewQueue(\"Q1\");\n mq.openNewQueue(\"Q2\");\n assertEquals(mq.availableQueues(),new HashSet<>(Arrays.asList(\"Q1\",\"Q2\")));\n mq.enqueue(1000, \"Q2\");\n // Checks which queues are empty\n assertTrue(mq.isQueueEmpty(\"Q1\"));\n assertFalse(mq.isQueueEmpty(\"Q2\"));\n }\n \n @org.junit.Test\n public void testEnqueue() {\n // Creates queues Q1 and Q2, and puts various elements inside\n MultiQueue<Integer,String> mq = new MultiQueueImpl<>();\n assertEquals(mq.allEnqueuedElements().size(),0);\n mq.openNewQueue(\"Q1\");\n mq.openNewQueue(\"Q2\");\n mq.enqueue(1000, \"Q2\");\n mq.enqueue(1001, \"Q2\");\n mq.enqueue(1002, \"Q2\");\n mq.enqueue(1003, \"Q1\");\n mq.enqueue(1004, \"Q1\");\n // Checks which elements are in the queue overall\n assertEquals(mq.allEnqueuedElements(),new HashSet<>(Arrays.asList(1000,1001,1002,1003,1004)));\n }\n \n @org.junit.Test\n public void testDequeue() {\n // Creates queues Q1 and Q2, and puts various elements inside\n MultiQueue<Integer,String> mq = new MultiQueueImpl<>();\n assertEquals(mq.allEnqueuedElements().size(),0);\n mq.openNewQueue(\"Q1\");\n mq.openNewQueue(\"Q2\");\n mq.enqueue(1000, \"Q2\");\n mq.enqueue(1001, \"Q2\");\n mq.enqueue(1002, \"Q2\");\n mq.enqueue(1003, \"Q1\");\n mq.enqueue(1004, \"Q1\");\n // Checks the order of removal of the elements\n assertEquals(mq.dequeue(\"Q1\"),Optional.of(1003));\n assertEquals(mq.dequeue(\"Q2\"),Optional.of(1000));\n assertEquals(mq.dequeue(\"Q2\"),Optional.of(1001));\n assertEquals(mq.dequeue(\"Q2\"),Optional.of(1002));\n assertEquals(mq.dequeue(\"Q2\"),Optional.empty());\n assertEquals(mq.dequeue(\"Q2\"),Optional.empty());\n // More additions and removals..\n mq.enqueue(1005, \"Q1\");\n mq.enqueue(1006, \"Q2\");\n assertEquals(mq.dequeue(\"Q2\"),Optional.of(1006));\n assertEquals(mq.allEnqueuedElements(),new HashSet<>(Arrays.asList(1004,1005))); \n }\n \n\n @org.junit.Test\n public void testFullDequeue() {\n // Creates queues Q1 and Q2, and puts various elements inside\n MultiQueue<Integer,String> mq = new MultiQueueImpl<>();\n assertEquals(mq.allEnqueuedElements().size(),0);\n mq.openNewQueue(\"Q1\");\n mq.openNewQueue(\"Q2\");\n mq.enqueue(1000, \"Q2\");\n mq.enqueue(1001, \"Q2\");\n mq.enqueue(1002, \"Q2\");\n mq.enqueue(1003, \"Q1\");\n mq.enqueue(1004, \"Q1\");\n // Removes all elements from a queue\n assertEquals(mq.dequeueAllFromQueue(\"Q2\"), Arrays.asList(1000,1001,1002));\n assertEquals(mq.dequeueAllFromQueue(\"Q2\").size(),0);\n }\n \n @org.junit.Test\n public void testDequeueOneFromAll() {\n // Creates queues Q1 and Q2 and Q3, and puts various elements in Q1 and Q2\n MultiQueue<Integer,String> mq = new MultiQueueImpl<>();\n assertEquals(mq.allEnqueuedElements().size(),0);\n mq.openNewQueue(\"Q1\");\n mq.openNewQueue(\"Q2\");\n mq.openNewQueue(\"Q3\"); \n mq.enqueue(1000, \"Q2\");\n mq.enqueue(1001, \"Q2\");\n mq.enqueue(1002, \"Q2\");\n mq.enqueue(1003, \"Q1\");\n mq.enqueue(1004, \"Q1\");\n // Removes one element from each queue\n Map<String,Optional<Integer>> map = mq.dequeueOneFromAllQueues();\n assertEquals(map.size(), 3);\n assertEquals(map.get(\"Q1\"), Optional.of(1003));\n assertEquals(map.get(\"Q2\"), Optional.of(1000));\n assertEquals(map.get(\"Q3\"), Optional.empty());\n }\n \n @org.junit.Test\n public void optionalTestCloseAndReallocate() {\n // Creates queues Q1 and Q2 and Q3, and puts various elements inside\n MultiQueue<Integer,String> mq = new MultiQueueImpl<>();\n assertEquals(mq.allEnqueuedElements().size(),0);\n mq.openNewQueue(\"Q1\");\n mq.openNewQueue(\"Q2\");\n mq.openNewQueue(\"Q3\"); \n mq.enqueue(1000, \"Q2\");\n mq.enqueue(1001, \"Q2\");\n mq.enqueue(1002, \"Q2\");\n mq.enqueue(1003, \"Q1\");\n mq.enqueue(1004, \"Q1\");\n mq.enqueue(1005, \"Q3\");\n assertEquals(mq.availableQueues(),new HashSet<>(Arrays.asList(\"Q1\",\"Q2\",\"Q3\")));\n assertEquals(mq.allEnqueuedElements(),new HashSet<>(Arrays.asList(1000,1001,1002,1003,1004,1005))); \n // Closes Q1, its elements must end up in some other queue\n mq.closeQueueAndReallocate(\"Q1\");\n assertEquals(mq.allEnqueuedElements(),new HashSet<>(Arrays.asList(1000,1001,1002,1003,1004,1005)));\n assertEquals(mq.availableQueues(),new HashSet<>(Arrays.asList(\"Q2\",\"Q3\")));\n }\n \n @org.junit.Test\n public void optionalTestExceptions() {\n // Tests and the various exceptions\n MultiQueue<Integer,String> mq = new MultiQueueImpl<>();\n assertEquals(mq.allEnqueuedElements().size(),0);\n mq.openNewQueue(\"Q1\");\n mq.openNewQueue(\"Q3\");\n mq.enqueue(1000, \"Q1\");\n try{\n mq.openNewQueue(\"Q1\");\n fail(\"can't open Q1 again\");\n } catch (IllegalArgumentException e){}\n catch (Exception e){\n fail(\"wrong exception thrown\");\n }\n try{\n mq.isQueueEmpty(\"Q2\");\n fail(\"can't query a non-existing queue\");\n } catch (IllegalArgumentException e){}\n catch (Exception e){\n fail(\"wrong exception thrown\");\n }\n try{\n mq.enqueue(100,\"Q2\");\n fail(\"can't add into a non-existing queue\");\n } catch (IllegalArgumentException e){}\n catch (Exception e){\n fail(\"wrong exception thrown\");\n }\n try{\n mq.dequeue(\"Q2\");\n fail(\"can't remove from a non-existing queue\");\n } catch (IllegalArgumentException e){}\n catch (Exception e){\n fail(\"wrong exception thrown\");\n }\n try{\n mq.dequeueAllFromQueue(\"Q2\");\n fail(\"can't remove from a non-existing queue\");\n } catch (IllegalArgumentException e){}\n catch (Exception e){\n fail(\"wrong exception thrown\");\n }\n try{\n mq.closeQueueAndReallocate(\"Q2\");\n fail(\"can't remove from a non-existing queue\");\n } catch (IllegalArgumentException e){}\n catch (Exception e){\n fail(\"wrong exception thrown\");\n }\n mq.closeQueueAndReallocate(\"Q3\");\n // Ok, but now we have only Q1 left.\n try{\n mq.closeQueueAndReallocate(\"Q1\");\n fail(\"can't close if there's no other queue\");\n } catch (IllegalStateException e){}\n catch (Exception e){\n fail(\"wrong exception thrown\");\n }\n }\n \n}", "filename": "Test.java" }
2016
a05
[ { "content": "package pr2016.a05.sol1;\n\n\npublic interface Elevator {\n \n \n int getCurrentFloor();\n \n \n boolean isMoving();\n \n \n boolean isMovingUp();\n \n \n boolean isMovingDown();\n \n \n void call(int floor);\n \n \n void moveToNext();\n \n \n java.util.Set<Integer> pendingCalls();\n\n}", "filename": "Elevator.java" } ]
[ { "content": "package pr2016.a05.sol1;\n\nimport java.util.*;\n\npublic abstract class AbstractElevator implements Elevator {\n \n protected final NavigableSet<Integer> pending;\n protected boolean up = true;\n protected int floor = 0;\n \n public AbstractElevator() {\n super();\n this.pending = new TreeSet<>();\n }\n \n @Override\n public int getCurrentFloor() {\n return this.floor;\n }\n\n @Override\n public boolean isMoving() {\n return !this.pending.isEmpty();\n }\n\n @Override\n public boolean isMovingUp() {\n return this.isMoving() && this.up;\n }\n\n @Override\n public boolean isMovingDown() {\n return this.isMoving() && !this.up; \n }\n\n @Override\n public void call(int floor) {\n if (this.floor == floor){\n return;\n }\n this.pending.add(floor);\n this.update();\n }\n\n @Override\n public void moveToNext() {\n if (!this.isMoving()){\n return;\n }\n Integer next = this.next();\n this.pending.remove(this.next());\n this.floor = next;\n this.update();\n }\n \n protected Integer next(){\n return this.isMovingUp() ? this.pending.higher(this.floor) : this.pending.lower(this.floor);\n }\n \n protected abstract void update();\n \n @Override\n public Set<Integer> pendingCalls() {\n return Collections.unmodifiableSet(this.pending);\n }\n}", "filename": "AbstractElevator.java" }, { "content": "package pr2016.a05.sol1;\n\npublic class BasicElevatorImpl extends AbstractElevator {\n \n public BasicElevatorImpl() {\n super();\n } \n\n @Override \n protected void update(){\n if (this.isMoving()){\n Integer h = this.pending.higher(this.floor);\n Integer l = this.pending.lower(this.floor);\n if (h!=null && l!=null){\n this.up = h-this.floor < l-this.floor;\n } else {\n this.up = (h!=null);\n }\n }\n }\n }", "filename": "BasicElevatorImpl.java" }, { "content": "package pr2016.a05.sol1;\n\npublic class AlternateElevatorImpl extends AbstractElevator {\n \n public AlternateElevatorImpl() {\n super();\n }\n \n @Override\n protected void update(){\n if (this.isMoving()){\n if (this.next()==null){\n this.up = !this.up;\n }\n }\n }\n}", "filename": "AlternateElevatorImpl.java" } ]
{ "components": { "imports": "package pr2016.a05.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;\n\n/**\n * See the documentation of the Elevator interface: it models an elevator that accepts calls\n * and consequently moves up and down the various floors (floor) of a building.\n * \n * In the mandatory part of the exercise, implement an AlternateElevatorImpl implementation with\n * a constructor without arguments that implements the following policy:\n * - if the elevator is going up, then it continues to go up as long as there are pending calls related to\n * higher floors, and only when it reaches the last one will it descend downwards, and vice versa\n * \n * In the optional part of the exercise, implement a simple variant, a BasicElevatorImpl implementation that instead implements the policy:\n * - each time it proceeds to the nearest floor to which there has been a call\n * \n * The following are considered optional for the purpose of being able to correct the exercise, but still contribute to achieving\n * the totality of the score:\n * - implementation of BasicElevatorImpl\n * - minimization of repetitions, through the template method pattern\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. Note that the three private methods below\n * define tests that must be valid for both Elevators, and that are called twice in methods\n * public, i.e. passing the two types of Elevator. Then follow two specific tests.\n * \n * Remove the comment from the test code.\n */", "private_init": "\tprivate void testInitialCondition(final Elevator elevator) {\n // initial state of the Elevator\n assertEquals(elevator.getCurrentFloor(),0);\n assertFalse(elevator.isMoving());\n assertFalse(elevator.isMovingUp());\n assertFalse(elevator.isMovingDown());\n assertEquals(elevator.pendingCalls().size(),0);\n }\n \n public void testSimpleCall(final Elevator elevator) {\n // response to the call to go to floor 5\n elevator.call(5);\n assertEquals(elevator.getCurrentFloor(),0);\n assertTrue(elevator.isMoving());\n assertTrue(elevator.isMovingUp());\n assertFalse(elevator.isMovingDown());\n assertEquals(elevator.pendingCalls(),new HashSet<>(Arrays.asList(5)));\n elevator.moveToNext();\n assertEquals(elevator.getCurrentFloor(),5);\n assertFalse(elevator.isMoving());\n assertFalse(elevator.isMovingUp());\n assertFalse(elevator.isMovingDown());\n assertTrue(elevator.pendingCalls().isEmpty());\n }\n \n private void testSequenceCalls(final Elevator elevator) {\n // response to the call to go to floors 5, 9 and 6\n // the elevator will go up, first to 5, then 6, then 9\n elevator.call(5);\n elevator.call(9);\n elevator.call(6);\n assertTrue(elevator.isMovingUp());\n assertEquals(elevator.pendingCalls(),new HashSet<>(Arrays.asList(5,6,9)));\n assertEquals(elevator.getCurrentFloor(),0);\n elevator.moveToNext();\n assertTrue(elevator.isMovingUp());\n assertEquals(elevator.pendingCalls(),new HashSet<>(Arrays.asList(6,9)));\n assertEquals(elevator.getCurrentFloor(),5);\n elevator.moveToNext();\n assertTrue(elevator.isMovingUp());\n assertEquals(elevator.pendingCalls(),new HashSet<>(Arrays.asList(9)));\n assertEquals(elevator.getCurrentFloor(),6);\n elevator.moveToNext();\n assertFalse(elevator.isMoving());\n assertEquals(elevator.getCurrentFloor(),9);\n }", "test_functions": [ "\[email protected]\n public void testInitialConditionAlternate() {\n testInitialCondition(new AlternateElevatorImpl());\n }", "\[email protected]\n public void testSimpleCallAlternate() {\n testSimpleCall(new AlternateElevatorImpl());\n }", "\[email protected]\n public void testSequenceCallsAlternate() {\n testSequenceCalls(new AlternateElevatorImpl());\n }", "\[email protected]\n public void optionalTestInitialConditionBasic() {\n testInitialCondition(new BasicElevatorImpl());\n }", "\[email protected]\n public void optionalTestSimpleCallBasic() {\n testSimpleCall(new BasicElevatorImpl());\n }", "\[email protected]\n public void optionalTestSequenceCallsBasic() {\n testSequenceCalls(new BasicElevatorImpl());\n }", "\[email protected]\n public void testUpDownCallsAlternate() {\n // response to the call to go to floors 5, 9 and 6\n // the elevator will go up, first to 5\n // at that point it is called from 0 and from 1\n // but this elevator continues to 6 and then 9\n // and only then goes back down\n final Elevator elevator = new AlternateElevatorImpl();\n elevator.call(5);\n elevator.call(6);\n elevator.call(9);\n assertTrue(elevator.isMovingUp());\n assertEquals(elevator.pendingCalls(),new HashSet<>(Arrays.asList(5,6,9)));\n assertEquals(elevator.getCurrentFloor(),0);\n elevator.moveToNext();\n assertTrue(elevator.isMovingUp());\n assertEquals(elevator.pendingCalls(),new HashSet<>(Arrays.asList(6,9)));\n assertEquals(elevator.getCurrentFloor(),5);\n elevator.call(0);\n elevator.call(1);\n elevator.moveToNext();\n assertTrue(elevator.isMovingUp());\n assertEquals(elevator.pendingCalls(),new HashSet<>(Arrays.asList(0,1,9)));\n assertEquals(elevator.getCurrentFloor(),6);\n elevator.moveToNext();\n assertTrue(elevator.isMovingDown());\n assertEquals(elevator.pendingCalls(),new HashSet<>(Arrays.asList(0,1)));\n assertEquals(elevator.getCurrentFloor(),9);\n elevator.moveToNext();\n assertTrue(elevator.isMovingDown());\n assertEquals(elevator.pendingCalls(),new HashSet<>(Arrays.asList(0)));\n assertEquals(elevator.getCurrentFloor(),1);\n elevator.moveToNext();\n assertFalse(elevator.isMoving());\n assertEquals(elevator.getCurrentFloor(),0);\n }", "\[email protected]\n public void testUpDownCallsBasic() {\n // response to the call to go to floors 5 and 9\n // the elevator will go up, first to 5\n // at that point it is called from 4\n // and this elevator immediately goes down to 4\n final Elevator elevator = new BasicElevatorImpl();\n elevator.call(5);\n elevator.call(9);\n assertTrue(elevator.isMovingUp());\n assertEquals(elevator.pendingCalls(),new HashSet<>(Arrays.asList(5,9)));\n assertEquals(elevator.getCurrentFloor(),0);\n elevator.moveToNext();\n assertTrue(elevator.isMovingUp());\n assertEquals(elevator.pendingCalls(),new HashSet<>(Arrays.asList(9)));\n assertEquals(elevator.getCurrentFloor(),5);\n elevator.call(4);\n assertEquals(elevator.pendingCalls(),new HashSet<>(Arrays.asList(4,9)));\n assertTrue(elevator.isMovingDown());\n elevator.moveToNext();\n assertEquals(elevator.pendingCalls(),new HashSet<>(Arrays.asList(9)));\n assertEquals(elevator.getCurrentFloor(),4);\n }" ] }, "content": "package pr2016.a05.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;\n\n/**\n * See the documentation of the Elevator interface: it models an elevator that accepts calls\n * and consequently moves up and down the various floors (floor) of a building.\n * \n * In the mandatory part of the exercise, implement an AlternateElevatorImpl implementation with\n * a constructor without arguments that implements the following policy:\n * - if the elevator is going up, then it continues to go up as long as there are pending calls related to\n * higher floors, and only when it reaches the last one will it descend downwards, and vice versa\n * \n * In the optional part of the exercise, implement a simple variant, a BasicElevatorImpl implementation that instead implements the policy:\n * - each time it proceeds to the nearest floor to which there has been a call\n * \n * The following are considered optional for the purpose of being able to correct the exercise, but still contribute to achieving\n * the totality of the score:\n * - implementation of BasicElevatorImpl\n * - minimization of repetitions, through the template method pattern\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. Note that the three private methods below\n * define tests that must be valid for both Elevators, and that are called twice in methods\n * public, i.e. passing the two types of Elevator. Then follow two specific tests.\n * \n * Remove the comment from the test code.\n */\n\n\npublic class Test {\n \n private void testInitialCondition(final Elevator elevator) {\n // initial state of the Elevator\n assertEquals(elevator.getCurrentFloor(),0);\n assertFalse(elevator.isMoving());\n assertFalse(elevator.isMovingUp());\n assertFalse(elevator.isMovingDown());\n assertEquals(elevator.pendingCalls().size(),0);\n }\n \n public void testSimpleCall(final Elevator elevator) {\n // response to the call to go to floor 5\n elevator.call(5);\n assertEquals(elevator.getCurrentFloor(),0);\n assertTrue(elevator.isMoving());\n assertTrue(elevator.isMovingUp());\n assertFalse(elevator.isMovingDown());\n assertEquals(elevator.pendingCalls(),new HashSet<>(Arrays.asList(5)));\n elevator.moveToNext();\n assertEquals(elevator.getCurrentFloor(),5);\n assertFalse(elevator.isMoving());\n assertFalse(elevator.isMovingUp());\n assertFalse(elevator.isMovingDown());\n assertTrue(elevator.pendingCalls().isEmpty());\n }\n \n private void testSequenceCalls(final Elevator elevator) {\n // response to the call to go to floors 5, 9 and 6\n // the elevator will go up, first to 5, then 6, then 9\n elevator.call(5);\n elevator.call(9);\n elevator.call(6);\n assertTrue(elevator.isMovingUp());\n assertEquals(elevator.pendingCalls(),new HashSet<>(Arrays.asList(5,6,9)));\n assertEquals(elevator.getCurrentFloor(),0);\n elevator.moveToNext();\n assertTrue(elevator.isMovingUp());\n assertEquals(elevator.pendingCalls(),new HashSet<>(Arrays.asList(6,9)));\n assertEquals(elevator.getCurrentFloor(),5);\n elevator.moveToNext();\n assertTrue(elevator.isMovingUp());\n assertEquals(elevator.pendingCalls(),new HashSet<>(Arrays.asList(9)));\n assertEquals(elevator.getCurrentFloor(),6);\n elevator.moveToNext();\n assertFalse(elevator.isMoving());\n assertEquals(elevator.getCurrentFloor(),9);\n }\n \n @org.junit.Test\n public void testInitialConditionAlternate() {\n testInitialCondition(new AlternateElevatorImpl());\n }\n \n @org.junit.Test\n public void testSimpleCallAlternate() {\n testSimpleCall(new AlternateElevatorImpl());\n }\n \n @org.junit.Test\n public void testSequenceCallsAlternate() {\n testSequenceCalls(new AlternateElevatorImpl());\n }\n \n @org.junit.Test\n public void optionalTestInitialConditionBasic() {\n testInitialCondition(new BasicElevatorImpl());\n }\n \n @org.junit.Test\n public void optionalTestSimpleCallBasic() {\n testSimpleCall(new BasicElevatorImpl());\n }\n \n @org.junit.Test\n public void optionalTestSequenceCallsBasic() {\n testSequenceCalls(new BasicElevatorImpl());\n }\n \n \n @org.junit.Test\n public void testUpDownCallsAlternate() {\n // response to the call to go to floors 5, 9 and 6\n // the elevator will go up, first to 5\n // at that point it is called from 0 and from 1\n // but this elevator continues to 6 and then 9\n // and only then goes back down\n final Elevator elevator = new AlternateElevatorImpl();\n elevator.call(5);\n elevator.call(6);\n elevator.call(9);\n assertTrue(elevator.isMovingUp());\n assertEquals(elevator.pendingCalls(),new HashSet<>(Arrays.asList(5,6,9)));\n assertEquals(elevator.getCurrentFloor(),0);\n elevator.moveToNext();\n assertTrue(elevator.isMovingUp());\n assertEquals(elevator.pendingCalls(),new HashSet<>(Arrays.asList(6,9)));\n assertEquals(elevator.getCurrentFloor(),5);\n elevator.call(0);\n elevator.call(1);\n elevator.moveToNext();\n assertTrue(elevator.isMovingUp());\n assertEquals(elevator.pendingCalls(),new HashSet<>(Arrays.asList(0,1,9)));\n assertEquals(elevator.getCurrentFloor(),6);\n elevator.moveToNext();\n assertTrue(elevator.isMovingDown());\n assertEquals(elevator.pendingCalls(),new HashSet<>(Arrays.asList(0,1)));\n assertEquals(elevator.getCurrentFloor(),9);\n elevator.moveToNext();\n assertTrue(elevator.isMovingDown());\n assertEquals(elevator.pendingCalls(),new HashSet<>(Arrays.asList(0)));\n assertEquals(elevator.getCurrentFloor(),1);\n elevator.moveToNext();\n assertFalse(elevator.isMoving());\n assertEquals(elevator.getCurrentFloor(),0);\n }\n\n \n @org.junit.Test\n public void testUpDownCallsBasic() {\n // response to the call to go to floors 5 and 9\n // the elevator will go up, first to 5\n // at that point it is called from 4\n // and this elevator immediately goes down to 4\n final Elevator elevator = new BasicElevatorImpl();\n elevator.call(5);\n elevator.call(9);\n assertTrue(elevator.isMovingUp());\n assertEquals(elevator.pendingCalls(),new HashSet<>(Arrays.asList(5,9)));\n assertEquals(elevator.getCurrentFloor(),0);\n elevator.moveToNext();\n assertTrue(elevator.isMovingUp());\n assertEquals(elevator.pendingCalls(),new HashSet<>(Arrays.asList(9)));\n assertEquals(elevator.getCurrentFloor(),5);\n elevator.call(4);\n assertEquals(elevator.pendingCalls(),new HashSet<>(Arrays.asList(4,9)));\n assertTrue(elevator.isMovingDown());\n elevator.moveToNext();\n assertEquals(elevator.pendingCalls(),new HashSet<>(Arrays.asList(9)));\n assertEquals(elevator.getCurrentFloor(),4);\n }\n \n \n}", "filename": "Test.java" }
2016
a03b
[ { "content": "package ex2016.a03b.sol1;\n\n\npublic interface Clock {\n \n \n Time getTime();\n \n \n void tick();\n \n \n void registerAlarmObserver(Time time, Runnable observer);\n \n \n void registerHoursDeadlineObserver(int hours, Runnable observer);\n \n \n void registerMinutesDeadlineObserver(int minutes, Runnable observer);\n \n \n void registerSecondsDeadlineObserver(int seconds, Runnable observer);\n}", "filename": "Clock.java" }, { "content": "package ex2016.a03b.sol1;\n\n\npublic interface Time {\n \n \n int getHours();\n \n \n int getMinutes();\n \n \n int getSeconds();\n \n \n String getLabel24();\n \n \n int getSecondsFromMidnight();\n}", "filename": "Time.java" } ]
[ { "content": "package ex2016.a03b.sol1;\n\n/*\n * An helper class used by TimeImpl and ClockImpl\n */\npublic class TimeUtils {\n \n public static int N_SECONDS = 60;\n public static int N_MINUTES = 60;\n public static int N_HOURS = 24;\n \n public static boolean correctHours(int hours){\n return hours >= 0 && hours < N_HOURS;\n }\n \n public static boolean correctMinutes(int minutes){\n return minutes >= 0 && minutes < N_MINUTES;\n }\n \n public static boolean correctSeconds(int seconds){\n return seconds >= 0 && seconds < N_SECONDS;\n }\n}", "filename": "TimeUtils.java" }, { "content": "package ex2016.a03b.sol1;\n\nimport java.util.*;\nimport static ex2016.a03b.sol1.TimeUtils.*;\n\npublic class ClockImpl implements Clock {\n \n private Time time;\n private Map<Time,List<Runnable>> observers = new HashMap<>();\n \n public ClockImpl(Time time){\n this.time = time;\n }\n\n @Override\n public Time getTime() {\n return this.time;\n }\n \n private Time getAdvancedTime(int seconds){\n return new TimeImpl(time.getSecondsFromMidnight()+seconds);\n }\n\n @Override\n public void tick() {\n this.time = this.getAdvancedTime(1);\n notifyObservers();\n }\n \n private void notifyObservers(){\n this.observers.getOrDefault(time, new LinkedList<>()).forEach(Runnable::run);\n }\n\n @Override\n public void registerAlarmObserver(Time time, Runnable observer) {\n final List<Runnable> oneObserver = new LinkedList<>(Arrays.asList(observer));\n this.observers.merge(time, oneObserver, (v,v1)->{v.addAll(v1); return v;});\n }\n\n @Override\n public void registerHoursDeadlineObserver(int hours, Runnable observer) {\n this.registerAlarmObserver(getAdvancedTime(hours*N_SECONDS*N_MINUTES), observer);\n }\n\n @Override\n public void registerMinutesDeadlineObserver(int minutes, Runnable observer) {\n this.registerAlarmObserver(getAdvancedTime(minutes*N_SECONDS), observer);\n }\n\n @Override\n public void registerSecondsDeadlineObserver(int seconds, Runnable observer) {\n this.registerAlarmObserver(getAdvancedTime(seconds), observer);\n }\n}", "filename": "ClockImpl.java" }, { "content": "package ex2016.a03b.sol1;\n\nimport static ex2016.a03b.sol1.TimeUtils.*;\n\npublic class TimeImpl implements Time {\n \n private final int secondsFromMidnight;\n \n // Package private, since it is used by Clock only\n TimeImpl(int secondsFromMidnight){\n this.secondsFromMidnight = secondsFromMidnight % (N_SECONDS*N_MINUTES*N_HOURS);\n }\n \n public TimeImpl(int hours, int minutes, int seconds) {\n if (!correctHours(hours) || !correctMinutes(minutes) || !correctSeconds(seconds)){\n throw new IllegalArgumentException();\n }\n this.secondsFromMidnight = seconds + N_SECONDS*minutes + N_SECONDS*N_MINUTES*hours;\n }\n\n @Override\n public int getHours() {\n return this.secondsFromMidnight / (N_SECONDS*N_MINUTES);\n }\n\n @Override\n public int getMinutes() {\n return (this.secondsFromMidnight % (N_SECONDS*N_MINUTES)) / N_SECONDS;\n }\n\n @Override\n public int getSeconds() {\n return this.secondsFromMidnight % N_SECONDS;\n }\n\n @Override\n public int getSecondsFromMidnight() {\n return this.secondsFromMidnight;\n }\n \n private static String intLabel(int i){\n return (i<10 ? \"0\" : \"\")+i;\n }\n \n @Override\n public String getLabel24() {\n return intLabel(getHours())+\":\"+intLabel(getMinutes())+\":\"+intLabel(getSeconds());\n }\n\n @Override\n public int hashCode() {\n final int prime = 31;\n int result = 1;\n result = prime * result + secondsFromMidnight;\n return result;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj) {\n return true;\n }\n if (obj == null) {\n return false;\n }\n if (getClass() != obj.getClass()) {\n return false;\n }\n TimeImpl other = (TimeImpl) obj;\n if (secondsFromMidnight != other.secondsFromMidnight) {\n return false;\n }\n return true;\n }\n\n}", "filename": "TimeImpl.java" } ]
{ "components": { "imports": "package ex2016.a03b.sol1;\n\nimport static org.junit.Assert.*;\n\nimport java.util.*;\n\n/**\n * Please consult the documentation of the provided Time and Clock interfaces.\n * Time, which must be implemented with a TimeImpl class with a three-argument constructor of type int (hours, minutes, seconds),\n * models the concept of time (for example: 20:30:00 to indicate 8:30 PM).\n * Clock, which must be implemented with a ClockImpl class with a constructor that takes a Time as input, models\n * a clock with an \"alarm\", with methods to advance the time by one second, and to register an observer\n * who will be notified at a certain time (Observer pattern).\n * \n * The following are considered optional for the possibility of correcting the exercise, but still contribute to achieving\n * the totality of the score:\n * - implementation of optional tests (related to the management of notifications, i.e. the Observer pattern)\n * - good design of the solution, in particular with minimization of repetitions and use of magic numbers\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 * Remove the comment from the test code.\n */", "private_init": "\t", "test_functions": [ "\[email protected]\n public void testTime() {\n // Test of basic functionality, in particular, of getSecondsFromMidnight\n final Time time = new TimeImpl(20,30,0); // 20:30:00, 8:30 PM\n assertEquals(time.getHours(),20);\n assertEquals(time.getMinutes(),30);\n assertEquals(time.getSeconds(),0);\n assertEquals(time.getSecondsFromMidnight(),73800);\n final Time time2 = new TimeImpl(1,1,1); // 1:01:01 AM\n assertEquals(time2.getHours(),1); // one hour.. 3600 seconds\n assertEquals(time2.getMinutes(),1); // one minute.. 60 seconds\n assertEquals(time2.getSeconds(),1);\n assertEquals(time2.getSecondsFromMidnight(),3600+60+1);\n }", "\[email protected]\n public void testLabel() {\n final Time time = new TimeImpl(20,30,0); // 20:30:00, 8:30 PM\n assertEquals(time.getLabel24(),\"20:30:00\");\n final Time time2 = new TimeImpl(1,1,1); // 1:01:01 AM\n assertEquals(time2.getLabel24(),\"01:01:01\");\n }", "\[email protected]\n public void testClock() {\n // Verification of the clock's tick functionality\n final Time time = new TimeImpl(20,30,0); // 20:30:00, 8:30 PM\n final Clock clock = new ClockImpl(time);\n assertEquals(clock.getTime(),time); // TimeImpl.equals must be implemented!!\n clock.tick();\n assertEquals(clock.getTime(),new TimeImpl(20,30,1)); \n for (int i=0;i<59;i++){ // 59 seconds pass\n clock.tick();\n }", "\[email protected]\n public void testTimeException() {\n // verification of hour (0-23), minute (0-59) and second (0-59) limits\n try{\n new TimeImpl(25,30,0);\n fail(\"no 25 hours\");\n }", "\[email protected]\n public void optionalTestNotifications(){\n // Functioning of notifications\n final Set<String> alarms = new HashSet<>();\n final Time time = new TimeImpl(20,30,0); // 20:30:00, 8:30 PM\n final Clock clock = new ClockImpl(time);\n // the observers here are lambdas that insert strings into alarms\n clock.registerAlarmObserver(new TimeImpl(20,30,5), ()-> alarms.add(\"a\") ); // \"a\", at 20:30:05\n clock.registerSecondsDeadlineObserver(5, ()-> alarms.add(\"b\") ); // \"b\", at 20:30:05.. i.e. in 5 seconds\n clock.registerMinutesDeadlineObserver(1, ()-> alarms.add(\"c\") ); // \"c\", at 20:31:00.. i.e. in 1 minute\n clock.registerHoursDeadlineObserver(1, ()-> alarms.add(\"d\")); // \"d\", at 21:31:00.. i.e. in 1 hour\n clock.tick(); // 20:30:01\n clock.tick(); // 20:30:02\n clock.tick();\n clock.tick();\n assertEquals(alarms.size(),0); // no alarms yet\n clock.tick(); // 20:30:05\n assertEquals(alarms,new HashSet<>(Arrays.asList(\"a\",\"b\"))); // alarms a and b triggered\n for (int i=0;i<60;i++){\n clock.tick(); // going to 20:31:05 \n }" ] }, "content": "package ex2016.a03b.sol1;\n\nimport static org.junit.Assert.*;\n\nimport java.util.*;\n\n/**\n * Please consult the documentation of the provided Time and Clock interfaces.\n * Time, which must be implemented with a TimeImpl class with a three-argument constructor of type int (hours, minutes, seconds),\n * models the concept of time (for example: 20:30:00 to indicate 8:30 PM).\n * Clock, which must be implemented with a ClockImpl class with a constructor that takes a Time as input, models\n * a clock with an \"alarm\", with methods to advance the time by one second, and to register an observer\n * who will be notified at a certain time (Observer pattern).\n * \n * The following are considered optional for the possibility of correcting the exercise, but still contribute to achieving\n * the totality of the score:\n * - implementation of optional tests (related to the management of notifications, i.e. the Observer pattern)\n * - good design of the solution, in particular with minimization of repetitions and use of magic numbers\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 * Remove the comment from the test code.\n */\n\npublic class Test {\n \n @org.junit.Test\n public void testTime() {\n // Test of basic functionality, in particular, of getSecondsFromMidnight\n final Time time = new TimeImpl(20,30,0); // 20:30:00, 8:30 PM\n assertEquals(time.getHours(),20);\n assertEquals(time.getMinutes(),30);\n assertEquals(time.getSeconds(),0);\n assertEquals(time.getSecondsFromMidnight(),73800);\n final Time time2 = new TimeImpl(1,1,1); // 1:01:01 AM\n assertEquals(time2.getHours(),1); // one hour.. 3600 seconds\n assertEquals(time2.getMinutes(),1); // one minute.. 60 seconds\n assertEquals(time2.getSeconds(),1);\n assertEquals(time2.getSecondsFromMidnight(),3600+60+1);\n }\n \n @org.junit.Test\n public void testLabel() {\n final Time time = new TimeImpl(20,30,0); // 20:30:00, 8:30 PM\n assertEquals(time.getLabel24(),\"20:30:00\");\n final Time time2 = new TimeImpl(1,1,1); // 1:01:01 AM\n assertEquals(time2.getLabel24(),\"01:01:01\");\n }\n \n @org.junit.Test\n public void testClock() {\n // Verification of the clock's tick functionality\n final Time time = new TimeImpl(20,30,0); // 20:30:00, 8:30 PM\n final Clock clock = new ClockImpl(time);\n assertEquals(clock.getTime(),time); // TimeImpl.equals must be implemented!!\n clock.tick();\n assertEquals(clock.getTime(),new TimeImpl(20,30,1)); \n for (int i=0;i<59;i++){ // 59 seconds pass\n clock.tick();\n }\n assertEquals(clock.getTime(),new TimeImpl(20,31,0)); \n for (int i=0;i<60;i++){ // one minute passes\n clock.tick();\n }\n assertEquals(clock.getTime(),new TimeImpl(20,32,0)); \n for (int i=0;i<8*60;i++){ // 8 minutes pass\n clock.tick();\n }\n assertEquals(clock.getTime(),new TimeImpl(20,40,0)); \n for (int i=0;i<20*60+1;i++){ // 20 minutes and one second pass\n clock.tick();\n }\n assertEquals(clock.getTime(),new TimeImpl(21,0,1)); \n for (int i=0;i<60*60;i++){ // one hour passes\n clock.tick();\n }\n assertEquals(clock.getTime(),new TimeImpl(22,0,1)); \n for (int i=0;i<2*60*60;i++){ // two hours pass\n clock.tick();\n }\n assertEquals(clock.getTime(),new TimeImpl(0,0,1)); \n }\n \n @org.junit.Test\n public void testTimeException() {\n // verification of hour (0-23), minute (0-59) and second (0-59) limits\n try{\n new TimeImpl(25,30,0);\n fail(\"no 25 hours\");\n } catch (IllegalArgumentException e){\n } catch (Exception e){\n fail(\"wrong exception thrown\");\n }\n try{\n new TimeImpl(-1,30,0);\n fail(\"no -1 hours\");\n } catch (IllegalArgumentException e){\n } catch (Exception e){\n fail(\"wrong exception thrown\");\n }\n try{\n new TimeImpl(20,60,0);\n fail(\"no 60 minutes\");\n } catch (IllegalArgumentException e){\n } catch (Exception e){\n fail(\"wrong exception thrown\");\n }\n try{\n new TimeImpl(20,30,60);\n fail(\"no 60 seconds\");\n } catch (IllegalArgumentException e){\n } catch (Exception e){\n fail(\"wrong exception thrown\");\n }\n }\n \n \n @org.junit.Test\n public void optionalTestNotifications(){\n // Functioning of notifications\n final Set<String> alarms = new HashSet<>();\n final Time time = new TimeImpl(20,30,0); // 20:30:00, 8:30 PM\n final Clock clock = new ClockImpl(time);\n // the observers here are lambdas that insert strings into alarms\n clock.registerAlarmObserver(new TimeImpl(20,30,5), ()-> alarms.add(\"a\") ); // \"a\", at 20:30:05\n clock.registerSecondsDeadlineObserver(5, ()-> alarms.add(\"b\") ); // \"b\", at 20:30:05.. i.e. in 5 seconds\n clock.registerMinutesDeadlineObserver(1, ()-> alarms.add(\"c\") ); // \"c\", at 20:31:00.. i.e. in 1 minute\n clock.registerHoursDeadlineObserver(1, ()-> alarms.add(\"d\")); // \"d\", at 21:31:00.. i.e. in 1 hour\n clock.tick(); // 20:30:01\n clock.tick(); // 20:30:02\n clock.tick();\n clock.tick();\n assertEquals(alarms.size(),0); // no alarms yet\n clock.tick(); // 20:30:05\n assertEquals(alarms,new HashSet<>(Arrays.asList(\"a\",\"b\"))); // alarms a and b triggered\n for (int i=0;i<60;i++){\n clock.tick(); // going to 20:31:05 \n }\n assertEquals(alarms,new HashSet<>(Arrays.asList(\"a\",\"b\",\"c\"))); // also c triggers\n for (int i=0;i<60*60;i++){\n clock.tick(); // going to 21:31:05 \n }\n assertEquals(alarms,new HashSet<>(Arrays.asList(\"a\",\"b\",\"c\",\"d\"))); // also d triggers\n }\n \n}", "filename": "Test.java" }
2016
a01b
[ { "content": "package ex2016.a01b.sol1;\n\nimport java.util.Collection;\n\ninterface Builders {\n \n <X> ListBuilder<X> makeBasicBuilder();\n\n \n <X> ListBuilder<X> makeBuilderWithSize(int size);\n\n \n <X> ListBuilder<X> makeBuilderFromElements(Collection<X> from);\n\n \n <X> ListBuilder<X> makeBuilderFromElementsAndWithSize(Collection<X> from, int size);\n}", "filename": "Builders.java" }, { "content": "package ex2016.a01b.sol1;\n\nimport java.util.List;\n\n\n\npublic interface ListBuilder<X> {\n \n \n \n void addElement(X x);\n \n \n \n List<X> build();\n}", "filename": "ListBuilder.java" } ]
[ { "content": "package ex2016.a01b.sol1;\n\nimport java.util.*;\n\n\npublic class BuildersImpl implements Builders {\n\n @Override\n public <X> ListBuilder<X> makeBasicBuilder() {\n return new BasicBuilder<>();\n }\n\n @Override\n public <X> ListBuilder<X> makeBuilderWithSize(int size) {\n return new BuilderWithSize<>(this.makeBasicBuilder(), size);\n }\n\n @Override\n public <X> ListBuilder<X> makeBuilderFromElements(Collection<X> from) {\n return new BuilderOf<>(this.makeBasicBuilder(), from);\n }\n \n public <X> ListBuilder<X> makeBuilderFromElementsAndWithSize(Collection<X> from, int size){\n return new BuilderOf<>(this.makeBuilderWithSize(size), from);\n }\n\n}", "filename": "BuildersImpl.java" }, { "content": "package ex2016.a01b.sol1;\n\nimport java.util.*;\n\npublic class BasicBuilder<X> implements ListBuilder<X> {\n\n private final List<X> list = new ArrayList<X>();\n private boolean done = false;\n \n private void checkDone(){\n if (this.done){\n throw new IllegalStateException();\n }\n }\n \n @Override\n public void addElement(X x) {\n this.checkDone();\n Objects.requireNonNull(x);\n this.list.add(x);\n }\n\n @Override\n public List<X> build() {\n this.checkDone();\n this.done = true;\n return Collections.unmodifiableList(this.list);\n } \n}", "filename": "BasicBuilder.java" }, { "content": "package ex2016.a01b.sol1;\n\nimport java.util.List;\n\npublic class BuilderWithSize<X> implements ListBuilder<X> {\n \n private final ListBuilder<X> builder;\n private int remainingSize;\n \n BuilderWithSize(ListBuilder<X> builder, int size) {\n super();\n this.builder = builder;\n this.remainingSize = size;\n }\n\n public void addElement(X x) {\n builder.addElement(x);\n this.remainingSize--;\n }\n\n public List<X> build() {\n if (this.remainingSize != 0){\n throw new IllegalStateException();\n }\n return builder.build();\n }\n}", "filename": "BuilderWithSize.java" }, { "content": "package ex2016.a01b.sol1;\n\nimport java.util.*;\n\npublic class BuilderOf<X> implements ListBuilder<X> {\n \n private final ListBuilder<X> builder;\n private final Collection<X> from;\n \n BuilderOf(ListBuilder<X> builder, Collection<X> from) {\n super();\n this.builder = builder;\n this.from = from;\n }\n\n public void addElement(X x) {\n if (!from.contains(x)){\n throw new IllegalArgumentException();\n }\n builder.addElement(x);\n }\n\n public List<X> build() {\n return builder.build();\n }\n}", "filename": "BuilderOf.java" } ]
{ "components": { "imports": "package ex2016.a01b.sol1;\n\nimport static org.junit.Assert.*;\n\nimport java.util.*;\n\n/**\n * See the documentation of the Builders and ListBuilder interfaces.\n * \n * Builders (to be implemented in a class BuildersImpl with a constructor without arguments) models a factory for objects\n * of type ListBuilder.\n * \n * ListBuilder models a builder for immutable lists, i.e., an object that is used to indicate step by step\n * a list of elements as desired, and then generate an immutable list to produce as output (remember\n * the use of the Collections.unmodifiableList method).\n * \n * Note that Builders requires producing 4 builders of different types: this should be done trying to avoid as much as possible\n * code duplication.\n * \n * The following are considered optional for the purpose of being able to correct the exercise, but still contribute to achieving\n * the totality of the score:\n * - implementation of the last builder (its test is indicated as optional)\n * - non-duplication of code, and in general, good design of the solution\n * \n * Observe carefully the following test, 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", "test_functions": [ "\[email protected]\n public void testBasicBuilder() {\n // Instantiate the factory for builders\n final Builders builders = new BuildersImpl();\n // A builder used to create the immutable list of elements \"a\",\"b\",\"c\" \n final ListBuilder<String> b1 = builders.makeBasicBuilder();\n b1.addElement(\"a\");\n b1.addElement(\"b\");\n b1.addElement(\"c\");\n assertEquals(b1.build(), Arrays.asList(\"a\",\"b\",\"c\"));\n // Similar example, but with Integers\n final ListBuilder<Integer> b2 = builders.makeBasicBuilder();\n b2.addElement(10);\n b2.addElement(50);\n b2.addElement(20);\n b2.addElement(30);\n assertEquals(b2.build(), Arrays.asList(10,50,20,30));\n // Note, after calling build, the builder is no longer usable\n try {\n b2.addElement(40);\n fail(\"cannot add after build\");\n }", "\[email protected]\n public void testBuilderWithSize() {\n // A builder for strings of 3 elements, no more no less\n final Builders builders = new BuildersImpl();\n final ListBuilder<String> b1 = builders.makeBuilderWithSize(3);\n b1.addElement(\"a\");\n b1.addElement(\"b\");\n b1.addElement(\"c\");\n assertEquals(b1.build(), Arrays.asList(\"a\",\"b\",\"c\"));\n // If you try to build a list with fewer or more elements.. it fails\n final ListBuilder<String> b2 = builders.makeBuilderWithSize(3);\n b2.addElement(\"a\");\n b2.addElement(\"b\");\n try{\n b2.build();\n fail(\"cannot build, we need 3 elements, not 2!\");\n }", "\[email protected]\n public void testBuilderFromElements() {\n final Builders builders = new BuildersImpl();\n final ListBuilder<String> b1 = builders.makeBuilderFromElements(Arrays.asList(\"0\",\"1\"));\n // A builder for only strings \"0\" and \"1\"\n b1.addElement(\"0\");\n b1.addElement(\"1\");\n b1.addElement(\"1\");\n assertEquals(b1.build(), Arrays.asList(\"0\",\"1\",\"1\"));\n final ListBuilder<String> b2 = builders.makeBuilderFromElements(Arrays.asList(\"0\",\"1\"));\n b2.addElement(\"0\");\n // trying to insert a \"2\" generates an error\n try{\n b2.addElement(\"2\");\n fail(\"cannot a 2, just a 0 or 1\");\n }", "\[email protected]\n public void optionalTestBuilderFromElementsAndWithSize() {\n final Builders builders = new BuildersImpl();\n final ListBuilder<String> b1 = builders.makeBuilderFromElementsAndWithSize(Arrays.asList(\"0\",\"1\"),4);\n // A builder for strings of 4 elements, each \"0\" or \"1\"\n b1.addElement(\"0\");\n b1.addElement(\"1\");\n b1.addElement(\"1\");\n b1.addElement(\"0\");\n assertEquals(b1.build(), Arrays.asList(\"0\",\"1\",\"1\",\"0\"));\n ListBuilder<String> b2 = builders.makeBuilderFromElementsAndWithSize(Arrays.asList(\"0\",\"1\"),4);\n b2.addElement(\"0\");\n try{\n b2.addElement(\"2\");\n fail(\"cannot add 2, just a 0 or 1\");\n }" ] }, "content": "package ex2016.a01b.sol1;\n\nimport static org.junit.Assert.*;\n\nimport java.util.*;\n\n/**\n * See the documentation of the Builders and ListBuilder interfaces.\n * \n * Builders (to be implemented in a class BuildersImpl with a constructor without arguments) models a factory for objects\n * of type ListBuilder.\n * \n * ListBuilder models a builder for immutable lists, i.e., an object that is used to indicate step by step\n * a list of elements as desired, and then generate an immutable list to produce as output (remember\n * the use of the Collections.unmodifiableList method).\n * \n * Note that Builders requires producing 4 builders of different types: this should be done trying to avoid as much as possible\n * code duplication.\n * \n * The following are considered optional for the purpose of being able to correct the exercise, but still contribute to achieving\n * the totality of the score:\n * - implementation of the last builder (its test is indicated as optional)\n * - non-duplication of code, and in general, good design of the solution\n * \n * Observe carefully the following test, 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 @org.junit.Test\n public void testBasicBuilder() {\n // Instantiate the factory for builders\n final Builders builders = new BuildersImpl();\n // A builder used to create the immutable list of elements \"a\",\"b\",\"c\" \n final ListBuilder<String> b1 = builders.makeBasicBuilder();\n b1.addElement(\"a\");\n b1.addElement(\"b\");\n b1.addElement(\"c\");\n assertEquals(b1.build(), Arrays.asList(\"a\",\"b\",\"c\"));\n // Similar example, but with Integers\n final ListBuilder<Integer> b2 = builders.makeBasicBuilder();\n b2.addElement(10);\n b2.addElement(50);\n b2.addElement(20);\n b2.addElement(30);\n assertEquals(b2.build(), Arrays.asList(10,50,20,30));\n // Note, after calling build, the builder is no longer usable\n try {\n b2.addElement(40);\n fail(\"cannot add after build\");\n } catch (IllegalStateException e){}\n catch (Exception e){\n fail(\"should throw an IllegalStateException, not a \"+e.getClass());\n }\n // ..nor can you do other builds\n try{\n b2.build();\n fail(\"cannot build after building!\");\n } catch (IllegalStateException e){}\n catch (Exception e){\n fail(\"should throw an IllegalStateException, not a \"+e.getClass());\n }\n }\n \n @org.junit.Test\n public void testBuilderWithSize() {\n // A builder for strings of 3 elements, no more no less\n final Builders builders = new BuildersImpl();\n final ListBuilder<String> b1 = builders.makeBuilderWithSize(3);\n b1.addElement(\"a\");\n b1.addElement(\"b\");\n b1.addElement(\"c\");\n assertEquals(b1.build(), Arrays.asList(\"a\",\"b\",\"c\"));\n // If you try to build a list with fewer or more elements.. it fails\n final ListBuilder<String> b2 = builders.makeBuilderWithSize(3);\n b2.addElement(\"a\");\n b2.addElement(\"b\");\n try{\n b2.build();\n fail(\"cannot build, we need 3 elements, not 2!\");\n } catch (IllegalStateException e){}\n catch (Exception e){\n fail(\"should throw an IllegalStateException, not a \"+e.getClass());\n }\n // in case of an incorrect build attempt, you can continue!\n b2.addElement(\"c\");\n assertEquals(b2.build(), Arrays.asList(\"a\",\"b\",\"c\"));\n }\n \n @org.junit.Test\n public void testBuilderFromElements() {\n final Builders builders = new BuildersImpl();\n final ListBuilder<String> b1 = builders.makeBuilderFromElements(Arrays.asList(\"0\",\"1\"));\n // A builder for only strings \"0\" and \"1\"\n b1.addElement(\"0\");\n b1.addElement(\"1\");\n b1.addElement(\"1\");\n assertEquals(b1.build(), Arrays.asList(\"0\",\"1\",\"1\"));\n final ListBuilder<String> b2 = builders.makeBuilderFromElements(Arrays.asList(\"0\",\"1\"));\n b2.addElement(\"0\");\n // trying to insert a \"2\" generates an error\n try{\n b2.addElement(\"2\");\n fail(\"cannot a 2, just a 0 or 1\");\n } catch (IllegalArgumentException e){}\n catch (Exception e){\n fail(\"should throw an IllegalArgumentException, not a \"+e.getClass());\n }\n //.. but then you can continue\n b2.addElement(\"1\");\n assertEquals(b2.build(), Arrays.asList(\"0\",\"1\"));\n }\n \n @org.junit.Test\n public void optionalTestBuilderFromElementsAndWithSize() {\n final Builders builders = new BuildersImpl();\n final ListBuilder<String> b1 = builders.makeBuilderFromElementsAndWithSize(Arrays.asList(\"0\",\"1\"),4);\n // A builder for strings of 4 elements, each \"0\" or \"1\"\n b1.addElement(\"0\");\n b1.addElement(\"1\");\n b1.addElement(\"1\");\n b1.addElement(\"0\");\n assertEquals(b1.build(), Arrays.asList(\"0\",\"1\",\"1\",\"0\"));\n ListBuilder<String> b2 = builders.makeBuilderFromElementsAndWithSize(Arrays.asList(\"0\",\"1\"),4);\n b2.addElement(\"0\");\n try{\n b2.addElement(\"2\");\n fail(\"cannot add 2, just a 0 or 1\");\n } catch (IllegalArgumentException e){}\n catch (Exception e){\n fail(\"should throw an IllegalArgumentException, not a \"+e.getClass());\n }\n b2.addElement(\"1\");\n try{\n b2.build();\n fail(\"cannot build, we need 4 elements, not 2!\");\n } catch (IllegalStateException e){}\n catch (Exception e){\n fail(\"should throw an IllegalStateException, not a \"+e.getClass());\n }\n b2.addElement(\"0\");\n b2.addElement(\"0\");\n assertEquals(b2.build(), Arrays.asList(\"0\",\"1\",\"0\",\"0\"));\n }\n \n}", "filename": "Test.java" }
2017
a04
[ { "content": "package a04.sol1;\n\n\npublic interface Player {\n\t\n\t\n\tint getId();\n\t\n\t\n\tString getName();\n}", "filename": "Player.java" }, { "content": "package a04.sol1;\n\n\npublic interface Match {\n\n\t\n\tPlayer getFirstPlayer();\n\n\t\n\tPlayer getSecondPlayer();\n}", "filename": "Match.java" }, { "content": "package a04.sol1;\n\n\nclass PlayerImpl implements Player {\n\t\n\tprivate final int id;\n\t\n\tprivate final String name;\n\t\n\tpublic PlayerImpl(int id, String name){\n\t\tthis.id=id;\n\t\tthis.name=name;\n\t}\n\n\tpublic int getId() {\n\t\treturn id;\n\t}\n\n\tpublic String getName() {\n\t\treturn name;\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 + id;\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj) {\n\t\t\treturn true;\n\t\t}\n\t\tif (obj == null) {\n\t\t\treturn false;\n\t\t}\n\t\tif (!(obj instanceof PlayerImpl)) {\n\t\t\treturn false;\n\t\t}\n\t\tPlayerImpl other = (PlayerImpl) obj;\n\t\tif (id != other.id) {\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\t\n\t@Override\n\tpublic String toString() {\n\t\treturn name;\n\t}\n}", "filename": "PlayerImpl.java" }, { "content": "package a04.sol1;\n\nimport java.util.List;\nimport java.util.Set;\n\n\npublic interface Turnament {\n\t\n\t\n\tPlayer makePlayer(int id, String name);\n\t\n\t\n\tMatch makeMatch(Player p1, Player p2);\n\t\n\t\n\tvoid registerPlayer(Player player);\n\t\n\t\n\tvoid startTurnament();\n\t\n\t\n\tList<Player> getPlayers();\n\t\n\t\n\tList<Match> getPendingGames();\n\t\n\t\n\tvoid playMatch(Match match, Player winner);\n\t\n\t\n\tboolean isTurnamentOver();\n\t\n\t\n\tPlayer winner();\n\t\n\t\n\tSet<Player> opponents(Player player);\n\n}", "filename": "Turnament.java" }, { "content": "package a04.sol1;\n\n\nclass MatchImpl implements Match {\n\t\n\tprivate Player firstPlayer;\n\tprivate Player secondPlayer;\n\n\tpublic MatchImpl(Player firstPlayer, Player secondPlayer) {\n\t\tsuper();\n\t\tthis.firstPlayer = firstPlayer;\n\t\tthis.secondPlayer = secondPlayer;\n\t}\n\t\n\tpublic Player getFirstPlayer() {\n\t\treturn firstPlayer;\n\t}\n\t\n\tpublic Player getSecondPlayer() {\n\t\treturn secondPlayer;\n\t}\n\t\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = 1;\n\t\tresult = prime * result + ((firstPlayer == null) ? 0 : firstPlayer.hashCode());\n\t\tresult = prime * result + ((secondPlayer == null) ? 0 : secondPlayer.hashCode());\n\t\treturn result;\n\t}\n\t\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj) {\n\t\t\treturn true;\n\t\t}\n\t\tif (obj == null) {\n\t\t\treturn false;\n\t\t}\n\t\tif (!(obj instanceof MatchImpl)) {\n\t\t\treturn false;\n\t\t}\n\t\tMatchImpl other = (MatchImpl) obj;\n\t\tif (firstPlayer == null) {\n\t\t\tif (other.firstPlayer != null) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t} else if (!firstPlayer.equals(other.firstPlayer)) {\n\t\t\treturn false;\n\t\t}\n\t\tif (secondPlayer == null) {\n\t\t\tif (other.secondPlayer != null) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t} else if (!secondPlayer.equals(other.secondPlayer)) {\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\t\n\t@Override\n\tpublic String toString() {\n\t\treturn \"M[\" + firstPlayer + \",\" + secondPlayer + \"]\";\n\t}\n}", "filename": "MatchImpl.java" } ]
[ { "content": "package a04.sol1;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Optional;\nimport java.util.Set;\nimport java.util.stream.Collectors;\n\npublic class TurnamentImpl implements Turnament {\n\n\tprivate final static List<Integer> SIZES = Arrays.asList(1, 2, 4, 8, 16, 32, 64);\n\n\tprivate final List<Player> players = new ArrayList<>();\n\tprivate final List<Player> surviving = new ArrayList<>();\n\tprivate final Map<Match, Optional<Player>> matches = new HashMap<>();\n\n\tprivate void require(boolean b, String msg) {\n\t\tif (!b) {\n\t\t\tthrow new IllegalArgumentException(msg);\n\t\t}\n\t}\n\n\t@Override\n\tpublic Player makePlayer(int id, String name) {\n\t\treturn new PlayerImpl(id, name);\n\t}\n\n\t@Override\n\tpublic Match makeMatch(Player p1, Player p2) {\n\t\treturn new MatchImpl(p1, p2);\n\t}\n\n\t@Override\n\tpublic void registerPlayer(Player player) {\n\t\trequire(this.matches.isEmpty(), \"can't register if turnament is already started\");\n\t\trequire(!players.contains(player), \"player already registered\");\n\t\tplayers.add(player);\n\t}\n\n\t@Override\n\tpublic void startTurnament() {\n\t\trequire(SIZES.contains(players.size()), \"turnament incomplete\");\n\t\trequire(matches.isEmpty(), \"turnament already started\");\n\t\tthis.surviving.addAll(this.players);\n\t\tthis.addNewMatches();\n\t}\n\n\tprivate void addNewMatches() {\n\t\tif (matches.isEmpty() || (!matches.containsValue(Optional.empty()) && surviving.size() > 1)) {\n\t\t\tfor (int i = 0; i < surviving.size(); i = i+2) {\n\t\t\t\tthis.matches.put(new MatchImpl(surviving.get(i), surviving.get(i + 1)), Optional.empty());\n\t\t\t}\n\t\t}\n\t}\n\n\t@Override\n\tpublic List<Player> getPlayers() {\n\t\treturn Collections.unmodifiableList(players);\n\t}\n\n\tprivate boolean hasPlayer(Match match, Player player) {\n\t\treturn match.getFirstPlayer() == player || match.getSecondPlayer() == player;\n\t}\n\n\tprivate Player otherPlayer(Match match, Player player) {\n\t\treturn match.getFirstPlayer() == player ? match.getSecondPlayer() : match.getFirstPlayer();\n\t}\n\n\t@Override\n\tpublic List<Match> getPendingGames() {\n\t\treturn this.matches\n\t\t\t\t .entrySet()\n\t\t\t\t .stream()\n\t\t\t\t .filter(e -> !e.getValue().isPresent())\n\t\t\t\t .map(e -> e.getKey())\n\t\t\t\t .collect(Collectors.toList());\n\t}\n\n\t@Override\n\tpublic void playMatch(Match match, Player winner) {\n\t\trequire(matches.containsKey(match), \"match non pending\");\n\t\tPlayer loser = otherPlayer(match, winner);\n\t\tsurviving.remove(loser);\n\t\tmatches.put(match, Optional.of(winner));\n\t\tthis.addNewMatches();\n\t}\n\n\t@Override\n\tpublic boolean isTurnamentOver() {\n\t\treturn surviving.size() == 1;\n\t}\n\n\t@Override\n\tpublic Player winner() {\n\t\trequire(isTurnamentOver(), \"turnament has no winner yet\");\n\t\treturn surviving.get(0);\n\t}\n\n\t@Override\n\tpublic Set<Player> opponents(Player player) {\n\t\treturn matches.keySet()\n\t\t\t\t .stream()\n\t\t\t\t .filter(m -> hasPlayer(m, player))\n\t\t\t\t .map(m -> otherPlayer(m, player))\n\t\t\t\t .collect(Collectors.toSet());\n\t}\n\n}", "filename": "TurnamentImpl.java" } ]
{ "components": { "imports": "package a04.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;\n\n/**\n * In this exercise, a single-elimination tournament will be modeled (with quarter-finals, semi-finals, finals..),\n * with a bracket of the type shown in the figure (tabellone.gif.. the numbers shown are not indicative).\n * \n * First, consult the documentation of the provided Player and Match interfaces, which are already implemented\n * in PlayerImpl and MatchImpl (it is recommended to use these implementations).\n * Then, consult the documentation of the Turnament interface, which will be implemented with a class\n * TurnamentImpl with a constructor without arguments.\n * \n * The following are considered optional for the purpose of being able to correct the exercise, but still contribute\n * to achieving the totality of the score:\n * - implementation of optional tests (related to the isTurnamentOver, winner and opponents methods)\n * - good design of the solution\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. Note that in this exercise it is not required to\n * handle special cases that would normally throw exceptions.\n * \n * Remove the comment from the test code.\n */", "private_init": "\tprivate List<Player> players = null;\n\t\n\tprivate Turnament createTurnament() {\n\t\t// Method to create a tournament for 8 players\n\t\t// therefore with 4 quarter-finals, then 2 semi-finals, then a final\n\t\t// ..your solution should also handle cases with 16,32,64 players..\n\t\tTurnament t = new TurnamentImpl();\n\t\tplayers = new LinkedList<>();\n\t\tplayers.add(t.makePlayer(100, \"federer\"));\n\t\tplayers.add(t.makePlayer(101, \"fognini\"));\n\t\tplayers.add(t.makePlayer(102, \"wawrinka\"));\n\t\tplayers.add(t.makePlayer(300, \"cecchinato\"));\n\t\tplayers.add(t.makePlayer(200, \"zverev\"));\n\t\tplayers.add(t.makePlayer(400, \"thiem\"));\n\t\tplayers.add(t.makePlayer(105, \"kyrgios\"));\n\t\tplayers.add(t.makePlayer(106, \"nadal\"));\n\t\t// register the 8 players with the tournament\n\t\tplayers.forEach(t::registerPlayer);\n\t\treturn t;\n\t}", "test_functions": [ "\[email protected]\n public void testStart() {\n\t\tTurnament t = createTurnament();\n\t\tassertTrue(t.getPendingGames().isEmpty());\n\t\t// start the tournament\n\t\tt.startTurnament();\n\t\t// I have 8 players and 4 pending matches\n\t\tassertEquals(4,t.getPendingGames().size());\n\t\tassertEquals(8,t.getPlayers().size());\n\t\t// player at the top of the bracket, at the bottom of the bracket, and in position 6\n\t\tassertEquals(\"federer\",t.getPlayers().get(0).getName());\n\t\tassertEquals(\"nadal\",t.getPlayers().get(7).getName());\n\t\tassertEquals(105,t.getPlayers().get(6).getId());\n }", "\[email protected]\n public void testMatchesFirstRound() {\n\t\tTurnament t = createTurnament();\n\t\tt.startTurnament();\n\t\t// the first 4 pending matches are between the players in positions: 0-1, 2-3, 4-5, 6-7\n\t\tassertTrue(t.getPendingGames().contains(t.makeMatch(players.get(0), players.get(1))));\n\t\tassertTrue(t.getPendingGames().contains(t.makeMatch(players.get(2), players.get(3))));\n\t\tassertTrue(t.getPendingGames().contains(t.makeMatch(players.get(4), players.get(5))));\n\t\tassertTrue(t.getPendingGames().contains(t.makeMatch(players.get(6), players.get(7))));\n }", "\[email protected]\n public void testPlay() {\n\t\tTurnament t = createTurnament();\n\t\tt.startTurnament();\n\t\t// play the match 0-1, and player 0 wins, 3 pending matches remain\n\t\tt.playMatch(t.makeMatch(players.get(0), players.get(1)), players.get(0));\n\t\tassertEquals(3,t.getPendingGames().size());\n\t\tassertTrue(t.getPendingGames().contains(t.makeMatch(players.get(2), players.get(3))));\n\t\tassertTrue(t.getPendingGames().contains(t.makeMatch(players.get(4), players.get(5))));\n\t\tassertTrue(t.getPendingGames().contains(t.makeMatch(players.get(6), players.get(7))));\n\t\tassertEquals(8,t.getPlayers().size());\n }", "\[email protected]\n public void testPlayWholeTurnament() {\n\t\tTurnament t = createTurnament();\n\t\tt.startTurnament();\n\t\t// complete tournament.. first play 3 quarter-finals in any order\n\t\tt.playMatch(t.makeMatch(players.get(0), players.get(1)), players.get(0));\n\t\tt.playMatch(t.makeMatch(players.get(6), players.get(7)), players.get(7));\n\t\tt.playMatch(t.makeMatch(players.get(2), players.get(3)), players.get(3));\n\t\t// only one quarter-final remains\n\t\tassertEquals(1,t.getPendingGames().size());\n\t\tt.playMatch(t.makeMatch(players.get(4), players.get(5)), players.get(5));\n\t\t// quarter-finals finished, now the pending matches are the two semi-finals\n\t\tassertEquals(2,t.getPendingGames().size());\n\t\t// based on the results of the quarter-finals, the semi-finals are 0-3 and 5-7\n\t\tassertTrue(t.getPendingGames().contains(t.makeMatch(players.get(0), players.get(3))));\n\t\tassertTrue(t.getPendingGames().contains(t.makeMatch(players.get(5), players.get(7))));\n\t\t// the semi-finals are played\n\t\tt.playMatch(t.makeMatch(players.get(0), players.get(3)), players.get(0));\n\t\tt.playMatch(t.makeMatch(players.get(5), players.get(7)), players.get(7));\n\t\t// only the final 0-7 is missing\n\t\tassertTrue(t.getPendingGames().contains(t.makeMatch(players.get(0), players.get(7))));\n\t\tt.playMatch(t.makeMatch(players.get(0), players.get(7)), players.get(0));\n }", "\[email protected]\n public void optionalTestWinner() {\n\t\tTurnament t = createTurnament();\n\t\tt.startTurnament();\n\t\t// play the 4 quarters, the 2 semi-finals\n\t\tt.playMatch(t.makeMatch(players.get(0), players.get(1)), players.get(0));\n\t\tt.playMatch(t.makeMatch(players.get(6), players.get(7)), players.get(7));\n\t\tt.playMatch(t.makeMatch(players.get(2), players.get(3)), players.get(3));\n\t\tt.playMatch(t.makeMatch(players.get(4), players.get(5)), players.get(5));\n\t\tt.playMatch(t.makeMatch(players.get(0), players.get(3)), players.get(0));\n\t\tt.playMatch(t.makeMatch(players.get(5), players.get(7)), players.get(7));\n\t\t// tournament not finished\n\t\tassertFalse(t.isTurnamentOver());\n\t\t// play the final, the tournament is finished and I have the winner\n\t\tt.playMatch(t.makeMatch(players.get(0), players.get(7)), players.get(0));\n\t\tassertTrue(t.isTurnamentOver());\n\t\tassertEquals(\"federer\",t.winner().getName());\n }", "\[email protected]\n public void optionalTestOpponents() {\n\t\tTurnament t = createTurnament();\n\t\tt.startTurnament();\n\t\t// play the whole tournament\n\t\tt.playMatch(t.makeMatch(players.get(0), players.get(1)), players.get(0));\n\t\tt.playMatch(t.makeMatch(players.get(6), players.get(7)), players.get(7));\n\t\tt.playMatch(t.makeMatch(players.get(2), players.get(3)), players.get(3));\n\t\tt.playMatch(t.makeMatch(players.get(4), players.get(5)), players.get(5));\n\t\tt.playMatch(t.makeMatch(players.get(0), players.get(3)), players.get(0));\n\t\tt.playMatch(t.makeMatch(players.get(5), players.get(7)), players.get(7));\n\t\tt.playMatch(t.makeMatch(players.get(0), players.get(7)), players.get(0));\n\t\tSet<Player> opponents = new HashSet<>(Arrays.asList(\n\t\t\tplayers.get(1), players.get(3), players.get(7)\n\t\t));\n\t\t// player 0, who won the tournament, beat players 1,3,7\n\t\tassertEquals(opponents,t.opponents(players.get(0)));\n }" ] }, "content": "package a04.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;\n\n/**\n * In this exercise, a single-elimination tournament will be modeled (with quarter-finals, semi-finals, finals..),\n * with a bracket of the type shown in the figure (tabellone.gif.. the numbers shown are not indicative).\n * \n * First, consult the documentation of the provided Player and Match interfaces, which are already implemented\n * in PlayerImpl and MatchImpl (it is recommended to use these implementations).\n * Then, consult the documentation of the Turnament interface, which will be implemented with a class\n * TurnamentImpl with a constructor without arguments.\n * \n * The following are considered optional for the purpose of being able to correct the exercise, but still contribute\n * to achieving the totality of the score:\n * - implementation of optional tests (related to the isTurnamentOver, winner and opponents methods)\n * - good design of the solution\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. Note that in this exercise it is not required to\n * handle special cases that would normally throw exceptions.\n * \n * Remove the comment from the test code.\n */\n\npublic class Test {\n\t\n\tprivate List<Player> players = null;\n\t\n\tprivate Turnament createTurnament() {\n\t\t// Method to create a tournament for 8 players\n\t\t// therefore with 4 quarter-finals, then 2 semi-finals, then a final\n\t\t// ..your solution should also handle cases with 16,32,64 players..\n\t\tTurnament t = new TurnamentImpl();\n\t\tplayers = new LinkedList<>();\n\t\tplayers.add(t.makePlayer(100, \"federer\"));\n\t\tplayers.add(t.makePlayer(101, \"fognini\"));\n\t\tplayers.add(t.makePlayer(102, \"wawrinka\"));\n\t\tplayers.add(t.makePlayer(300, \"cecchinato\"));\n\t\tplayers.add(t.makePlayer(200, \"zverev\"));\n\t\tplayers.add(t.makePlayer(400, \"thiem\"));\n\t\tplayers.add(t.makePlayer(105, \"kyrgios\"));\n\t\tplayers.add(t.makePlayer(106, \"nadal\"));\n\t\t// register the 8 players with the tournament\n\t\tplayers.forEach(t::registerPlayer);\n\t\treturn t;\n\t}\n\t\n\[email protected]\n public void testStart() {\n\t\tTurnament t = createTurnament();\n\t\tassertTrue(t.getPendingGames().isEmpty());\n\t\t// start the tournament\n\t\tt.startTurnament();\n\t\t// I have 8 players and 4 pending matches\n\t\tassertEquals(4,t.getPendingGames().size());\n\t\tassertEquals(8,t.getPlayers().size());\n\t\t// player at the top of the bracket, at the bottom of the bracket, and in position 6\n\t\tassertEquals(\"federer\",t.getPlayers().get(0).getName());\n\t\tassertEquals(\"nadal\",t.getPlayers().get(7).getName());\n\t\tassertEquals(105,t.getPlayers().get(6).getId());\n }\n\t\n\[email protected]\n public void testMatchesFirstRound() {\n\t\tTurnament t = createTurnament();\n\t\tt.startTurnament();\n\t\t// the first 4 pending matches are between the players in positions: 0-1, 2-3, 4-5, 6-7\n\t\tassertTrue(t.getPendingGames().contains(t.makeMatch(players.get(0), players.get(1))));\n\t\tassertTrue(t.getPendingGames().contains(t.makeMatch(players.get(2), players.get(3))));\n\t\tassertTrue(t.getPendingGames().contains(t.makeMatch(players.get(4), players.get(5))));\n\t\tassertTrue(t.getPendingGames().contains(t.makeMatch(players.get(6), players.get(7))));\n }\n\t\n\[email protected]\n public void testPlay() {\n\t\tTurnament t = createTurnament();\n\t\tt.startTurnament();\n\t\t// play the match 0-1, and player 0 wins, 3 pending matches remain\n\t\tt.playMatch(t.makeMatch(players.get(0), players.get(1)), players.get(0));\n\t\tassertEquals(3,t.getPendingGames().size());\n\t\tassertTrue(t.getPendingGames().contains(t.makeMatch(players.get(2), players.get(3))));\n\t\tassertTrue(t.getPendingGames().contains(t.makeMatch(players.get(4), players.get(5))));\n\t\tassertTrue(t.getPendingGames().contains(t.makeMatch(players.get(6), players.get(7))));\n\t\tassertEquals(8,t.getPlayers().size());\n }\n\t\n\[email protected]\n public void testPlayWholeTurnament() {\n\t\tTurnament t = createTurnament();\n\t\tt.startTurnament();\n\t\t// complete tournament.. first play 3 quarter-finals in any order\n\t\tt.playMatch(t.makeMatch(players.get(0), players.get(1)), players.get(0));\n\t\tt.playMatch(t.makeMatch(players.get(6), players.get(7)), players.get(7));\n\t\tt.playMatch(t.makeMatch(players.get(2), players.get(3)), players.get(3));\n\t\t// only one quarter-final remains\n\t\tassertEquals(1,t.getPendingGames().size());\n\t\tt.playMatch(t.makeMatch(players.get(4), players.get(5)), players.get(5));\n\t\t// quarter-finals finished, now the pending matches are the two semi-finals\n\t\tassertEquals(2,t.getPendingGames().size());\n\t\t// based on the results of the quarter-finals, the semi-finals are 0-3 and 5-7\n\t\tassertTrue(t.getPendingGames().contains(t.makeMatch(players.get(0), players.get(3))));\n\t\tassertTrue(t.getPendingGames().contains(t.makeMatch(players.get(5), players.get(7))));\n\t\t// the semi-finals are played\n\t\tt.playMatch(t.makeMatch(players.get(0), players.get(3)), players.get(0));\n\t\tt.playMatch(t.makeMatch(players.get(5), players.get(7)), players.get(7));\n\t\t// only the final 0-7 is missing\n\t\tassertTrue(t.getPendingGames().contains(t.makeMatch(players.get(0), players.get(7))));\n\t\tt.playMatch(t.makeMatch(players.get(0), players.get(7)), players.get(0));\n }\n\n\[email protected]\n public void optionalTestWinner() {\n\t\tTurnament t = createTurnament();\n\t\tt.startTurnament();\n\t\t// play the 4 quarters, the 2 semi-finals\n\t\tt.playMatch(t.makeMatch(players.get(0), players.get(1)), players.get(0));\n\t\tt.playMatch(t.makeMatch(players.get(6), players.get(7)), players.get(7));\n\t\tt.playMatch(t.makeMatch(players.get(2), players.get(3)), players.get(3));\n\t\tt.playMatch(t.makeMatch(players.get(4), players.get(5)), players.get(5));\n\t\tt.playMatch(t.makeMatch(players.get(0), players.get(3)), players.get(0));\n\t\tt.playMatch(t.makeMatch(players.get(5), players.get(7)), players.get(7));\n\t\t// tournament not finished\n\t\tassertFalse(t.isTurnamentOver());\n\t\t// play the final, the tournament is finished and I have the winner\n\t\tt.playMatch(t.makeMatch(players.get(0), players.get(7)), players.get(0));\n\t\tassertTrue(t.isTurnamentOver());\n\t\tassertEquals(\"federer\",t.winner().getName());\n }\n\t\n\[email protected]\n public void optionalTestOpponents() {\n\t\tTurnament t = createTurnament();\n\t\tt.startTurnament();\n\t\t// play the whole tournament\n\t\tt.playMatch(t.makeMatch(players.get(0), players.get(1)), players.get(0));\n\t\tt.playMatch(t.makeMatch(players.get(6), players.get(7)), players.get(7));\n\t\tt.playMatch(t.makeMatch(players.get(2), players.get(3)), players.get(3));\n\t\tt.playMatch(t.makeMatch(players.get(4), players.get(5)), players.get(5));\n\t\tt.playMatch(t.makeMatch(players.get(0), players.get(3)), players.get(0));\n\t\tt.playMatch(t.makeMatch(players.get(5), players.get(7)), players.get(7));\n\t\tt.playMatch(t.makeMatch(players.get(0), players.get(7)), players.get(0));\n\t\tSet<Player> opponents = new HashSet<>(Arrays.asList(\n\t\t\tplayers.get(1), players.get(3), players.get(7)\n\t\t));\n\t\t// player 0, who won the tournament, beat players 1,3,7\n\t\tassertEquals(opponents,t.opponents(players.get(0)));\n }\n \n}", "filename": "Test.java" }
2017
a03a
[ { "content": "package a03a.sol1;\n\nimport java.util.*;\n\n\npublic interface ExamsManagement {\n\t\n\t\n\tvoid createStudent(int studentId, String name);\n\t\n\t\n\tvoid createExam(String examName, int incrementalId);\n\t\n\t\n\tvoid registerStudent(String examName, int studentId);\n\t\n\t\n\tvoid examStarted(String examName);\n\n\t\n\tvoid registerEvaluation(int studentId, int evaluation);\n\t\n\t\n\t\n\tvoid examFinished();\n\t\n\t\n\tSet<Integer> examList(String examName);\n\t\n\t\n\tOptional<Integer> lastEvaluation(int studentId);\n\t\n\t\n\tMap<String,Integer> examStudentToEvaluation(String examName);\n\t\n\t\n\tMap<Integer,Integer> examEvaluationToCount(String examName);\n\n}", "filename": "ExamsManagement.java" }, { "content": "package a03a.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 a03a.sol1;\n\nimport java.util.*;\nimport java.util.function.Predicate;\nimport java.util.function.Supplier;\nimport java.util.stream.Collectors;\n\npublic class ExamsManagementImpl implements ExamsManagement {\n\t\n\tprivate Set<Exam> exams = new HashSet<>();\n\tprivate Set<Student> students = new HashSet<>();\n\tprivate Set<Registration> registrations = new HashSet<>();\n\tprivate Optional<Exam> currentExam = Optional.empty();\n\tprivate Optional<Exam> lastExam = Optional.empty();\n\t\n\tprivate static <T> T searchInSet(Set<T> set, Predicate<T> predicate) {\n\t\treturn set.stream().filter(predicate).findAny().get();\n\t}\n\t\n\tprivate Exam examByName(String examName) {\n\t\treturn searchInSet(exams,e -> e.getName().equals(examName));\n\t}\n\n\tprivate Student studentById(int studentId) {\n\t\treturn searchInSet(students, e -> e.getId()==studentId);\n\t}\n\t\n\tprivate Registration registrationByExamAndStudentId(Exam exam, int studentId) {\n\t\treturn searchInSet(registrations, r -> r.getExam().equals(exam) && r.getStudent().getId()==studentId);\n\t}\n\t\n\tprivate void check(boolean supplier) {\n\t\tif (!supplier) {\n\t\t\tthrow new IllegalStateException();\n\t\t}\n\t}\n\n\n\t@Override\n\tpublic void createStudent(int studentId, String name) {\n\t\tthis.students.add(new Student(studentId,name));\n\t}\n\n\t@Override\n\tpublic void createExam(String examName, int incrementalId) {\n\t\tthis.exams.add(new Exam(incrementalId,examName));\n\t}\n\n\t@Override\n\tpublic void registerStudent(String examName, int studentId) {\n\t\tthis.registrations.add(new Registration(examByName(examName),studentById(studentId)));\n\t}\n\t\n\t@Override\n\tpublic void examStarted(String examName) {\n\t\tfinal Exam exam = this.examByName(examName);\n\t\tthis.check(!this.currentExam.isPresent());\n\t\tthis.check(!this.lastExam.isPresent() || this.lastExam.get().getId() < exam.getId()); \n\t\tthis.currentExam = Optional.of(this.examByName(examName));\t\n\t}\n\n\t@Override\n\tpublic void registerEvaluation(int studentId, int evaluation) {\n\t\tthis.check(this.currentExam.isPresent());\n\t\tthis.registrationByExamAndStudentId(currentExam.get(), studentId).registerEvaluation(evaluation);\n\t}\n\n\t@Override\n\tpublic void examFinished() {\n\t\tthis.check(this.currentExam.isPresent());\n\t\tthis.lastExam = this.currentExam;\n\t\tthis.currentExam = Optional.empty();\n\n\t}\n\n\t@Override\n\tpublic Set<Integer> examList(String examName) {\n\t\treturn registrations.stream()\n\t\t\t\t .filter(r -> r.getExam().equals(examByName(examName)))\n\t\t\t\t .map(r -> r.getStudent().getId())\n\t\t\t\t .collect(Collectors.toSet());\n\t}\n\n\t@Override\n\tpublic Optional<Integer> lastEvaluation(int studentId) {\n\t\treturn registrations.stream()\n\t\t\t\t\t\t\t.filter(r -> r.getStudent().getId()==studentId)\n\t\t\t\t\t\t\t.filter(r -> r.getEvaluation().isPresent())\n\t\t\t\t\t\t\t.max((r1,r2)->r1.getExam().getId()-r2.getExam().getId())\n\t\t\t\t\t\t\t.flatMap(Registration::getEvaluation);\n\t}\n\n\t@Override\n\tpublic Map<String, Integer> examStudentToEvaluation(String examName) {\n\t\treturn registrations.stream()\n\t\t\t\t\t\t\t.filter(r -> r.getExam().getName().equals(examName))\n\t\t\t\t\t\t\t.filter(r -> r.getEvaluation().isPresent())\n\t\t\t\t\t\t\t.collect(Collectors.toMap(r->r.getStudent().getName(),r->r.getEvaluation().get()));\n\t}\n\n\t@Override\n\tpublic Map<Integer, Integer> examEvaluationToCount(String examName) {\n\t\treturn registrations.stream()\n\t\t\t\t.filter(r -> r.getExam().getName().equals(examName))\n\t\t\t\t.filter(r -> r.getEvaluation().isPresent())\n\t\t\t\t.collect(Collectors.groupingBy(r->r.getEvaluation().get(), Collectors.summingInt(r->1)));\n\t}\n\n}", "filename": "ExamsManagementImpl.java" }, { "content": "package a03a.sol1;\n\nimport java.util.Optional;\n\npublic class Registration {\n\tprivate final Exam exam;\n\tprivate final Student student;\n\tprivate Optional<Integer> evaluation = Optional.empty();\n\n\tpublic Registration(Exam exam, Student student) {\n\t\tsuper();\n\t\tthis.exam = exam;\n\t\tthis.student = student;\n\t}\n\n\tpublic Exam getExam() {\n\t\treturn exam;\n\t}\n\n\tpublic Student getStudent() {\n\t\treturn student;\n\t}\n\n\tpublic Optional<Integer> getEvaluation() {\n\t\treturn evaluation;\n\t}\n\t\n\tpublic void registerEvaluation(int evaluation) {\n\t\tthis.evaluation = Optional.of(evaluation);\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 + ((exam == null) ? 0 : exam.hashCode());\n\t\tresult = prime * result + ((student == null) ? 0 : student.hashCode());\n\t\treturn result;\n\t}\n\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\tRegistration other = (Registration) obj;\n\t\tif (exam == null) {\n\t\t\tif (other.exam != null)\n\t\t\t\treturn false;\n\t\t} else if (!exam.equals(other.exam))\n\t\t\treturn false;\n\t\tif (student == null) {\n\t\t\tif (other.student != null)\n\t\t\t\treturn false;\n\t\t} else if (!student.equals(other.student))\n\t\t\treturn false;\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Registration [exam=\" + exam + \", student=\" + student + \", evaluation=\" + evaluation + \"]\";\n\t}\n\n}", "filename": "Registration.java" }, { "content": "package a03a.sol1;\n\npublic class Exam {\n\n\tprivate final int id;\n\tprivate final String name;\n\n\tpublic Exam(int id, String name) {\n\t\tsuper();\n\t\tthis.id = id;\n\t\tthis.name = name;\n\t}\n\n\tpublic int getId() {\n\t\treturn id;\n\t}\n\n\tpublic String getName() {\n\t\treturn name;\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 + id;\n\t\tresult = prime * result + ((name == null) ? 0 : name.hashCode());\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj) {\n\t\t\treturn true;\n\t\t}\n\t\tif (obj == null) {\n\t\t\treturn false;\n\t\t}\n\t\tif (!(obj instanceof Exam)) {\n\t\t\treturn false;\n\t\t}\n\t\tExam other = (Exam) obj;\n\t\tif (id != other.id) {\n\t\t\treturn false;\n\t\t}\n\t\tif (name == null) {\n\t\t\tif (other.name != null) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t} else if (!name.equals(other.name)) {\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Exam [id=\" + id + \", name=\" + name + \"]\";\n\t}\n\n}", "filename": "Exam.java" }, { "content": "package a03a.sol1;\n\npublic class Student {\n\n\tprivate final int id;\n\tprivate final String name;\n\n\tpublic Student(int id, String name) {\n\t\tsuper();\n\t\tthis.id = id;\n\t\tthis.name = name;\n\t}\n\n\tpublic int getId() {\n\t\treturn id;\n\t}\n\n\tpublic String getName() {\n\t\treturn name;\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 + id;\n\t\tresult = prime * result + ((name == null) ? 0 : name.hashCode());\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj) {\n\t\t\treturn true;\n\t\t}\n\t\tif (obj == null) {\n\t\t\treturn false;\n\t\t}\n\t\tif (!(obj instanceof Student)) {\n\t\t\treturn false;\n\t\t}\n\t\tStudent other = (Student) obj;\n\t\tif (id != other.id) {\n\t\t\treturn false;\n\t\t}\n\t\tif (name == null) {\n\t\t\tif (other.name != null) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t} else if (!name.equals(other.name)) {\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"StudentImpl [id=\" + id + \", name=\" + name + \"]\";\n\t}\n\n}", "filename": "Student.java" } ]
{ "components": { "imports": "package a03a.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;", "private_init": "\t/*\n\t * Implement the ExamsManagement interface provided through an ExamsManagementImpl class with a constructor without arguments.\n\t * Realizes a concept of exam management (called Exam) of a university course.\n\t * Provides functionality for:\n\t * - creating students and exams (the exams have a temporal order marked by their numeric id); \n\t * - registering students for exams;\n\t * - to start an exam (respecting the temporal order), register grades for this exam, and then finish the exam;\n\t * - to obtain historical information\n\t * \n\t * Note that tests with the @org.junit.Test(expected = ...) annotation only pass if the exception indicated in the ... is thrown.\n\t * Note that tests with the @org.junit.Test annotation pass if no exception is thrown\n\t * Note that methods with the @org.junit.Before annotation are always executed before each test is executed, and serve\n\t * to prepare a \"new\" (always the same) configuration before executing a test.\n\t * \n\t * The following are considered optional for the purpose of being able to correct the exercise, but still contribute to achieving\n\t * the totality of the score:\n\t * - implementation of tests called optionalTestXYZ (related to the examEvaluationToCount method and exception handling) \n\t * - the good design of the solution, in particular with minimization of repetitions\n\t * \n\t */\n\t\n\tprivate ExamsManagement data;\n\t\n\[email protected]\n\tpublic void createData() {\n\t\t// initialization before executing any test\n\t\tthis.data = new ExamsManagementImpl();\n\t\tdata.createStudent(10, \"Mario\");\n\t\tdata.createStudent(20, \"Lucia\");\n\t\tdata.createStudent(30, \"Carlo\");\n\t\tdata.createStudent(40, \"Anna\");\n\t\tdata.createStudent(50, \"Ugo\");\n\t\tdata.createStudent(60, \"Silvia\"); // create 6 students\n\t\tdata.createExam(\"01-Gennaio-2018\", 201801);\n\t\tdata.createExam(\"02-Febbraio-2018\", 201802);\n\t\tdata.createExam(\"03-Febbraio-2018\", 201803); // create 3 exams with incremental id\n\t\tdata.registerStudent(\"01-Gennaio-2018\", 10);\n\t\tdata.registerStudent(\"01-Gennaio-2018\", 20);\n\t\tdata.registerStudent(\"01-Gennaio-2018\", 30);\n\t\tdata.registerStudent(\"01-Gennaio-2018\", 40); \n\t\tdata.registerStudent(\"02-Febbraio-2018\", 50);\n\t\tdata.registerStudent(\"02-Febbraio-2018\", 10); // register 4 students for the first exam, 2 for the second\n\t\tdata.examStarted(\"01-Gennaio-2018\"); // start the first exam\n\t\tdata.registerEvaluation(10, 18);\n\t\tdata.registerEvaluation(40, 25);\n\t\tdata.registerEvaluation(20, 25); // register 3 grades (18,25,25) to 3 students (with id/matriculation number 10,40,20)\n\t\tdata.examFinished(); // conclude the exam\n\t\tdata.examStarted(\"02-Febbraio-2018\"); // start the second exam.. etc..\n\t\tdata.registerEvaluation(10, 30);\n\t\tdata.registerEvaluation(50, 28);\n\t\tdata.examFinished();\n\t}", "test_functions": [ "\[email protected]\n\tpublic void testExamList() {\n\t\t// checks on the ids of the students enrolled in each exam\n\t\tassertEquals(data.examList(\"01-Gennaio-2018\"),new HashSet<>(Arrays.asList(10,20,30,40)));\n\t\tassertEquals(data.examList(\"02-Febbraio-2018\"),new HashSet<>(Arrays.asList(50,10)));\n\t\tassertEquals(data.examList(\"03-Febbraio-2018\"),new HashSet<>(Arrays.asList()));\n\t}", "\[email protected]\n\tpublic void testLastEvaluation() {\n\t\t// checks on the last grade obtained by various students (indicated by id/matriculation number)\n\t\tassertEquals(data.lastEvaluation(10),Optional.of(30));\n\t\tassertEquals(data.lastEvaluation(20),Optional.of(25));\n\t\tassertEquals(data.lastEvaluation(30),Optional.empty());\n\t\tassertEquals(data.lastEvaluation(40),Optional.of(25));\n\t\tassertEquals(data.lastEvaluation(50),Optional.of(28));\n\t}", "\[email protected]\n\tpublic void testExamStudentToEvaluation() {\n\t\t// checks on the grades obtained in a certain exam, found by exam name and then student name\n\t\tassertEquals(data.examStudentToEvaluation(\"01-Gennaio-2018\").size(),3);\n\t\tassertEquals(data.examStudentToEvaluation(\"01-Gennaio-2018\").get(\"Mario\").intValue(),18);\n\t\tassertEquals(data.examStudentToEvaluation(\"01-Gennaio-2018\").get(\"Anna\").intValue(),25);\n\t\tassertEquals(data.examStudentToEvaluation(\"02-Febbraio-2018\").size(),2);\n\t\tassertEquals(data.examStudentToEvaluation(\"02-Febbraio-2018\").get(\"Mario\").intValue(),30);\n\t\tassertEquals(data.examStudentToEvaluation(\"02-Febbraio-2018\").get(\"Ugo\").intValue(),28);\n\t}", "\[email protected]\n\tpublic void optionalTestEvaluationToCount() {\n\t\t// checks on how many students obtained a certain grade in a certain exam\n\t\tassertEquals(data.examEvaluationToCount(\"01-Gennaio-2018\").get(25).intValue(),2); // 2 students got 25 in the January 2018 exam\n\t\tassertEquals(data.examEvaluationToCount(\"01-Gennaio-2018\").get(18).intValue(),1);\n\t\tassertEquals(data.examEvaluationToCount(\"02-Febbraio-2018\").get(30).intValue(),1);\n\t\tassertEquals(data.examEvaluationToCount(\"02-Febbraio-2018\").get(28).intValue(),1);\n\t}" ] }, "content": "package a03a.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;\n\npublic class Test {\n\t\n\t/*\n\t * Implement the ExamsManagement interface provided through an ExamsManagementImpl class with a constructor without arguments.\n\t * Realizes a concept of exam management (called Exam) of a university course.\n\t * Provides functionality for:\n\t * - creating students and exams (the exams have a temporal order marked by their numeric id); \n\t * - registering students for exams;\n\t * - to start an exam (respecting the temporal order), register grades for this exam, and then finish the exam;\n\t * - to obtain historical information\n\t * \n\t * Note that tests with the @org.junit.Test(expected = ...) annotation only pass if the exception indicated in the ... is thrown.\n\t * Note that tests with the @org.junit.Test annotation pass if no exception is thrown\n\t * Note that methods with the @org.junit.Before annotation are always executed before each test is executed, and serve\n\t * to prepare a \"new\" (always the same) configuration before executing a test.\n\t * \n\t * The following are considered optional for the purpose of being able to correct the exercise, but still contribute to achieving\n\t * the totality of the score:\n\t * - implementation of tests called optionalTestXYZ (related to the examEvaluationToCount method and exception handling) \n\t * - the good design of the solution, in particular with minimization of repetitions\n\t * \n\t */\n\t\n\tprivate ExamsManagement data;\n\t\n\[email protected]\n\tpublic void createData() {\n\t\t// initialization before executing any test\n\t\tthis.data = new ExamsManagementImpl();\n\t\tdata.createStudent(10, \"Mario\");\n\t\tdata.createStudent(20, \"Lucia\");\n\t\tdata.createStudent(30, \"Carlo\");\n\t\tdata.createStudent(40, \"Anna\");\n\t\tdata.createStudent(50, \"Ugo\");\n\t\tdata.createStudent(60, \"Silvia\"); // create 6 students\n\t\tdata.createExam(\"01-Gennaio-2018\", 201801);\n\t\tdata.createExam(\"02-Febbraio-2018\", 201802);\n\t\tdata.createExam(\"03-Febbraio-2018\", 201803); // create 3 exams with incremental id\n\t\tdata.registerStudent(\"01-Gennaio-2018\", 10);\n\t\tdata.registerStudent(\"01-Gennaio-2018\", 20);\n\t\tdata.registerStudent(\"01-Gennaio-2018\", 30);\n\t\tdata.registerStudent(\"01-Gennaio-2018\", 40); \n\t\tdata.registerStudent(\"02-Febbraio-2018\", 50);\n\t\tdata.registerStudent(\"02-Febbraio-2018\", 10); // register 4 students for the first exam, 2 for the second\n\t\tdata.examStarted(\"01-Gennaio-2018\"); // start the first exam\n\t\tdata.registerEvaluation(10, 18);\n\t\tdata.registerEvaluation(40, 25);\n\t\tdata.registerEvaluation(20, 25); // register 3 grades (18,25,25) to 3 students (with id/matriculation number 10,40,20)\n\t\tdata.examFinished(); // conclude the exam\n\t\tdata.examStarted(\"02-Febbraio-2018\"); // start the second exam.. etc..\n\t\tdata.registerEvaluation(10, 30);\n\t\tdata.registerEvaluation(50, 28);\n\t\tdata.examFinished();\n\t}\n\t\n\[email protected]\n\tpublic void testExamList() {\n\t\t// checks on the ids of the students enrolled in each exam\n\t\tassertEquals(data.examList(\"01-Gennaio-2018\"),new HashSet<>(Arrays.asList(10,20,30,40)));\n\t\tassertEquals(data.examList(\"02-Febbraio-2018\"),new HashSet<>(Arrays.asList(50,10)));\n\t\tassertEquals(data.examList(\"03-Febbraio-2018\"),new HashSet<>(Arrays.asList()));\n\t}\n\t\n\[email protected]\n\tpublic void testLastEvaluation() {\n\t\t// checks on the last grade obtained by various students (indicated by id/matriculation number)\n\t\tassertEquals(data.lastEvaluation(10),Optional.of(30));\n\t\tassertEquals(data.lastEvaluation(20),Optional.of(25));\n\t\tassertEquals(data.lastEvaluation(30),Optional.empty());\n\t\tassertEquals(data.lastEvaluation(40),Optional.of(25));\n\t\tassertEquals(data.lastEvaluation(50),Optional.of(28));\n\t}\n\t\n\[email protected]\n\tpublic void testExamStudentToEvaluation() {\n\t\t// checks on the grades obtained in a certain exam, found by exam name and then student name\n\t\tassertEquals(data.examStudentToEvaluation(\"01-Gennaio-2018\").size(),3);\n\t\tassertEquals(data.examStudentToEvaluation(\"01-Gennaio-2018\").get(\"Mario\").intValue(),18);\n\t\tassertEquals(data.examStudentToEvaluation(\"01-Gennaio-2018\").get(\"Anna\").intValue(),25);\n\t\tassertEquals(data.examStudentToEvaluation(\"02-Febbraio-2018\").size(),2);\n\t\tassertEquals(data.examStudentToEvaluation(\"02-Febbraio-2018\").get(\"Mario\").intValue(),30);\n\t\tassertEquals(data.examStudentToEvaluation(\"02-Febbraio-2018\").get(\"Ugo\").intValue(),28);\n\t}\n\t\n\[email protected]\n\tpublic void optionalTestEvaluationToCount() {\n\t\t// checks on how many students obtained a certain grade in a certain exam\n\t\tassertEquals(data.examEvaluationToCount(\"01-Gennaio-2018\").get(25).intValue(),2); // 2 students got 25 in the January 2018 exam\n\t\tassertEquals(data.examEvaluationToCount(\"01-Gennaio-2018\").get(18).intValue(),1);\n\t\tassertEquals(data.examEvaluationToCount(\"02-Febbraio-2018\").get(30).intValue(),1);\n\t\tassertEquals(data.examEvaluationToCount(\"02-Febbraio-2018\").get(28).intValue(),1);\n\t}\n\t\n\[email protected](expected = IllegalStateException.class)\n\tpublic void optionalTestExamOrderedStarting() {\n\t\tdata.createExam(\"03-Febbraio-2017\", 201703); \n\t\tdata.examStarted(\"03-Febbraio-2017\"); // you can't start an exam prior to one already completed\n\t}\n\t\n\[email protected](expected = IllegalStateException.class)\n\tpublic void optionalTestExamNotFinished() {\n\t\tdata.createExam(\"04-Giugno-2018\", 201804);\n\t\tdata.examStarted(\"03-Febbraio-2018\");\n\t\tdata.examStarted(\"04-Giugno-2018\"); // you can't start an exam before finishing a previous one\n\t}\n\t\n\[email protected](expected = IllegalStateException.class)\n\tpublic void optionalTestExamNotStarted() {\n\t\tdata.examFinished(); // you can't finish an exam that hasn't been started\n\t}\n\t\n\[email protected](expected = IllegalStateException.class)\n\tpublic void optionalTestExamNotStarted2() {\n\t\tdata.registerEvaluation(50, 28); // you can't register a grade if there are no open exams\n\t}\n\t\n}", "filename": "Test.java" }
2017
a06
[ { "content": "package a06.sol1;\n\nimport java.util.List;\nimport java.util.stream.*;\n\n\npublic interface Sequence<X> {\n\t\n\t\n\tX nextElement();\n\t\n\t\n\tdefault List<X> nextListOfElements(int size) {\n\t\treturn Stream.generate(this::nextElement).limit(size).collect(Collectors.toList());\n\t}\n\t\n}", "filename": "Sequence.java" }, { "content": "package a06.sol1;\n\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.function.BinaryOperator;\n\n\npublic interface SequenceHelpers {\n\t\n\t\n\t<X> Sequence<X> of(X x);\n\t\n\t\n\t<X> Sequence<X> cyclic(List<X> l);\n\t\n\t\n\tdefault <X> Sequence<X> make(X... xs) {\n\t\treturn cyclic(Arrays.asList(xs));\n\t}\n\t\n\t\n\tSequence<Integer> incrementing(int start, int increment);\n\t\n\t\n\t<X> Sequence<X> accumulating(Sequence<X> input, BinaryOperator<X> op);\n\t\n\t\n\t<X> Sequence<Pair<X,Integer>> zip(Sequence<X> input);\n}", "filename": "SequenceHelpers.java" }, { "content": "package a06.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 a06.sol1;\n\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.function.BinaryOperator;\nimport java.util.stream.Collectors;\nimport java.util.stream.Stream;\n\n/**\n * @author mirko\n * Soluzione con gli stream...\n */\npublic class SequenceHelpersImpl implements SequenceHelpers {\n\n\tprivate <X> Stream<X> toStream(Sequence<X> sx) {\n\t\treturn Stream.generate(sx::nextElement);\n\t}\n\n\tprivate <X> Sequence<X> ofStream(Stream<X> s){\n\t\tfinal Iterator<X> it = s.iterator();\n\t\treturn () -> it.next();\n\t}\n\n\t@Override\n\tpublic <X> Sequence<X> of(X x) {\n\t\treturn () -> x;\n\t}\n\n\t@Override\n\tpublic <X> Sequence<X> cyclic(List<X> x) {\n\t\treturn ofStream(Stream.generate(x::stream).flatMap(e->e));\n\t}\n\t\n\t\n\t@Override\n\tpublic Sequence<Integer> incrementing(int start, int increment) {\n\t\treturn new Sequence<Integer>() {\n\t\t\tprivate int next = start;\n\t\t\t@Override\n\t\t\tpublic Integer nextElement() {\n\t\t\t\tfinal int old = next;\n\t\t\t\tnext = next + increment;\n\t\t\t\treturn old;\n\t\t\t}\n\t\t};\n\t}\n\n\t@Override\n\tpublic <X> Sequence<X> accumulating(Sequence<X> input, BinaryOperator<X> op) {\n\t\treturn new Sequence<X>() {\n\t\t\tprivate X next = input.nextElement();\n\t\t\t@Override\n\t\t\tpublic X nextElement() {\n\t\t\t\tfinal X old = next;\n\t\t\t\tnext = op.apply(old, input.nextElement());\n\t\t\t\treturn old;\n\t\t\t}\t\t\t\n\t\t};\n\t}\n\n\t@Override\n\tpublic <X> Sequence<Pair<X, Integer>> zip(Sequence<X> input) {\n\t\treturn new Sequence<Pair<X,Integer>>() {\n\t\t\tprivate int index = 0;\n\t\t\t@Override\n\t\t\tpublic Pair<X,Integer> nextElement() {\n\t\t\t\treturn new Pair<>(input.nextElement(),index++);\n\t\t\t}\t\t\t\n\t\t};\n\t}\n\n}", "filename": "SequenceHelpersImpl.java" } ]
{ "components": { "imports": "package a06.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;\n\n/**\n * Please consult the documentation of the provided interfaces:\n * - Sequence<X> models an infinite and sequential source of data of type X\n * - SequenceHelpers models a set of functionalities to create and combine Sequences\n * \n * Implement SequenceHelpers through a SequenceHelpersImpl class with a constructor without arguments,\n * so that it passes all the tests below.\n * \n * The following are considered optional for the purpose of being able to correct the exercise, but still contribute to achieving\n * the totality of the score:\n * - implementation of optional tests (related to the accumulating method)\n * - good design of the solution, in particular with minimization of repetitions\n * \n * Observe carefully the following test, 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", "test_functions": [ "\[email protected]\n public void testValue() {\n // Test on sequences consisting of a single element\n final SequenceHelpers iso = new SequenceHelpersImpl();\n assertEquals(iso.of(\"a\").nextListOfElements(5),Arrays.asList(\"a\",\"a\",\"a\",\"a\",\"a\"));\n assertEquals(iso.of(\"a\").nextListOfElements(1),Arrays.asList(\"a\"));\n assertEquals(iso.of(\"a\").nextListOfElements(10),Arrays.asList(\"a\",\"a\",\"a\",\"a\",\"a\",\"a\",\"a\",\"a\",\"a\",\"a\"));\n assertEquals(iso.of(1).nextListOfElements(10),Arrays.asList(1,1,1,1,1,1,1,1,1,1));\n }", "\[email protected]\n public void testCyclic() {\n // Test on cyclic sequences\n final SequenceHelpers iso = new SequenceHelpersImpl();\n // sequence: a,b,a,b,a,b,a,b,a,b,....\n assertEquals(iso.cyclic(Arrays.asList(\"a\",\"b\")).nextListOfElements(5),Arrays.asList(\"a\",\"b\",\"a\",\"b\",\"a\"));\n // sequence: 1,2,3,1,2,3,1,2,3,1,2,3,1,2,....\n assertEquals(iso.cyclic(Arrays.asList(1,2,3)).nextListOfElements(10),Arrays.asList(1,2,3,1,2,3,1,2,3,1));\n }", "\[email protected]\n public void testIncrementing() {\n\t\t// Test on sequence construction of increments\n\t\tfinal SequenceHelpers iso = new SequenceHelpersImpl();\n assertEquals(iso.incrementing(1, 2).nextListOfElements(5), Arrays.asList(1,3,5,7,9)); \t\n assertEquals(iso.incrementing(0, -3).nextListOfElements(4), Arrays.asList(0,-3,-6,-9)); \t\n }", "\[email protected]\n public void testZip() {\n\t\t// Test on construction of sequences with zipping\n\t\tfinal SequenceHelpers iso = new SequenceHelpersImpl();\n assertEquals(iso.zip(iso.cyclic(Arrays.asList(\"a\",\"b\",\"c\"))).nextListOfElements(4), \n \t\tArrays.asList(new Pair<>(\"a\",0),new Pair<>(\"b\",1), new Pair<>(\"c\",2), new Pair<>(\"a\",3)));\n }", "\[email protected]\n public void optionalTestAccumulating() {\n\t\t// Test on construction of sequences by accumulation\n\t\tfinal SequenceHelpers iso = new SequenceHelpersImpl();\n assertEquals(iso.accumulating(iso.of(\"1\"), (x,y)->x+y).nextListOfElements(4), \n \t\tArrays.asList(\"1\",\"11\",\"111\",\"1111\"));\n assertEquals(iso.accumulating(iso.cyclic(Arrays.asList(1,2,3)), (x,y)->x*y).nextListOfElements(6), \n \t\tArrays.asList(1,1*2,1*2*3,1*2*3*1,1*2*3*1*2,1*2*3*1*2*3));\n }" ] }, "content": "package a06.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;\n\n/**\n * Please consult the documentation of the provided interfaces:\n * - Sequence<X> models an infinite and sequential source of data of type X\n * - SequenceHelpers models a set of functionalities to create and combine Sequences\n * \n * Implement SequenceHelpers through a SequenceHelpersImpl class with a constructor without arguments,\n * so that it passes all the tests below.\n * \n * The following are considered optional for the purpose of being able to correct the exercise, but still contribute to achieving\n * the totality of the score:\n * - implementation of optional tests (related to the accumulating method)\n * - good design of the solution, in particular with minimization of repetitions\n * \n * Observe carefully the following test, 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\t\n\[email protected]\n public void testValue() {\n // Test on sequences consisting of a single element\n final SequenceHelpers iso = new SequenceHelpersImpl();\n assertEquals(iso.of(\"a\").nextListOfElements(5),Arrays.asList(\"a\",\"a\",\"a\",\"a\",\"a\"));\n assertEquals(iso.of(\"a\").nextListOfElements(1),Arrays.asList(\"a\"));\n assertEquals(iso.of(\"a\").nextListOfElements(10),Arrays.asList(\"a\",\"a\",\"a\",\"a\",\"a\",\"a\",\"a\",\"a\",\"a\",\"a\"));\n assertEquals(iso.of(1).nextListOfElements(10),Arrays.asList(1,1,1,1,1,1,1,1,1,1));\n }\n \n\[email protected]\n public void testCyclic() {\n // Test on cyclic sequences\n final SequenceHelpers iso = new SequenceHelpersImpl();\n // sequence: a,b,a,b,a,b,a,b,a,b,....\n assertEquals(iso.cyclic(Arrays.asList(\"a\",\"b\")).nextListOfElements(5),Arrays.asList(\"a\",\"b\",\"a\",\"b\",\"a\"));\n // sequence: 1,2,3,1,2,3,1,2,3,1,2,3,1,2,....\n assertEquals(iso.cyclic(Arrays.asList(1,2,3)).nextListOfElements(10),Arrays.asList(1,2,3,1,2,3,1,2,3,1));\n }\n\t\n\[email protected]\n public void testIncrementing() {\n\t\t// Test on sequence construction of increments\n\t\tfinal SequenceHelpers iso = new SequenceHelpersImpl();\n assertEquals(iso.incrementing(1, 2).nextListOfElements(5), Arrays.asList(1,3,5,7,9)); \t\n assertEquals(iso.incrementing(0, -3).nextListOfElements(4), Arrays.asList(0,-3,-6,-9)); \t\n }\n\t\n\t\n\[email protected]\n public void testZip() {\n\t\t// Test on construction of sequences with zipping\n\t\tfinal SequenceHelpers iso = new SequenceHelpersImpl();\n assertEquals(iso.zip(iso.cyclic(Arrays.asList(\"a\",\"b\",\"c\"))).nextListOfElements(4), \n \t\tArrays.asList(new Pair<>(\"a\",0),new Pair<>(\"b\",1), new Pair<>(\"c\",2), new Pair<>(\"a\",3)));\n }\n\n\[email protected]\n public void optionalTestAccumulating() {\n\t\t// Test on construction of sequences by accumulation\n\t\tfinal SequenceHelpers iso = new SequenceHelpersImpl();\n assertEquals(iso.accumulating(iso.of(\"1\"), (x,y)->x+y).nextListOfElements(4), \n \t\tArrays.asList(\"1\",\"11\",\"111\",\"1111\"));\n assertEquals(iso.accumulating(iso.cyclic(Arrays.asList(1,2,3)), (x,y)->x*y).nextListOfElements(6), \n \t\tArrays.asList(1,1*2,1*2*3,1*2*3*1,1*2*3*1*2,1*2*3*1*2*3));\n }\n\t \n}", "filename": "Test.java" }
2017
a02a
[ { "content": "package a02a.sol1;\n\n\n\npublic interface SequenceAcceptor {\n\t\n\tstatic enum Sequence {\n\t\tPOWER2, FLIP, RAMBLE, FIBONACCI; \n\t}\n\n\t\n\tvoid reset(Sequence sequence);\n\t\n\t\n\tvoid reset();\n\n\t\n\t\n\tvoid acceptElement(int i);\n\t\t\n}", "filename": "SequenceAcceptor.java" }, { "content": "package 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 a02a.sol1;\n\nimport java.util.*;\nimport java.util.stream.Stream;\n\npublic class SequenceAcceptorImpl implements SequenceAcceptor {\n\t\n\tprivate static Map<Sequence,Iterable<Integer>> sequences;\n\t\n\tstatic {\n\t\tsequences = new HashMap<>();\n\t\tsequences.put(Sequence.POWER2, ()->Stream.iterate(1,x->x*2).iterator());\n\t\tsequences.put(Sequence.FLIP, ()->Stream.iterate(1,x->1-x).iterator());\n\t\tsequences.put(Sequence.RAMBLE, ()->Stream.iterate(new Pair<>(0,1),p->new Pair<>(0,p.getY()+1))\n\t\t\t\t .flatMap(p->Stream.of(p.getX(),p.getY()))\n\t\t\t\t .iterator());\n\t\t/* \n\t\t//alternative, non-stream-based implementation\n\t\tsequences.put(Sequence.RAMBLE, ()->new Iterator<Integer>() {\n\t\t\tint counter=0;\n\t\t\tpublic boolean hasNext() {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tpublic Integer next() {\n\t\t\t\treturn counter++ % 2 == 0 ? 0 : counter/2;\n\t\t\t}\n\t\t});\n\t\t*/\n\t\tsequences.put(Sequence.FIBONACCI, ()->Stream.iterate(new Pair<>(1,1),p->new Pair<>(p.getY(),p.getX()+p.getY()))\n\t\t\t\t\t\t\t\t\t\t\t\t\t.map(Pair::getX)\n\t\t\t\t\t\t\t\t\t\t\t\t\t.iterator());\n\t}\n\t\n\tprivate Sequence seq;\n\tprivate Iterator<Integer> it;\n\t\n\tprivate void checkValidity() {\n\t\tif (seq == null) {\n\t\t\tthrow new IllegalStateException();\n\t\t}\n\t}\n\n\t@Override\n\tpublic void reset(Sequence sequence) {\n\t\tthis.seq = sequence;\n\t\tthis.it = sequences.get(sequence).iterator();\n\t}\n\n\t@Override\n\tpublic void reset() {\n\t\tthis.checkValidity();\n\t\tthis.it = sequences.get(this.seq).iterator();\n\t}\n\n\t@Override\n\tpublic void acceptElement(int i) {\n\t\tthis.checkValidity();\n\t\tif (!this.it.hasNext() || this.it.next()!=i) {\n\t\t\tthrow new IllegalStateException();\n\t\t}\n\t}\n}", "filename": "SequenceAcceptorImpl.java" } ]
{ "components": { "imports": "package a02a.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;", "private_init": "\t/*\n\t * Implement the SequenceAcceptor interface provided through a SequenceAcceptorImpl class with a constructor without arguments.\n\t * Implements a concept of consumer of infinite sequences of integers.\n\t * A finite set of sequences is possible, indicated in the enum SequenceAcceptor.Sequence.\n\t * The reset method in SequenceAcceptor is used to restart the sequence, so as to consume a sequence from the beginning.\n\t * The comment to the SequenceAcceptor code, and the test methods below constitute the necessary explanation of the \n\t * problem.\n\t * \n\t * Note that the tests with the @org.junit.Test(expected = ...) annotation pass only if the exception indicated in the ... is thrown.\n\t * Note that the tests with the @org.junit.Test annotation pass if no exception is thrown\n\t * \n\t * The following are considered optional for the purpose of being able to correct the exercise, but still contribute to the achievement \n\t * of the totality of the score:\n\t * - implementation of the tests called optionalTestXYZ (related to the reset methods and the Fibonacci sequence) \n\t * - the good design of the solution, in particular with minimization of repetitions\n\t * \n\t */", "test_functions": [ "\[email protected]\n\tpublic void testPower2OK() {\n\t\tfinal SequenceAcceptor sa = new SequenceAcceptorImpl();\n\t\tsa.reset(SequenceAcceptor.Sequence.POWER2);\n\t\tsa.acceptElement(1);\n\t\tsa.acceptElement(2);\n\t\tsa.acceptElement(4);\n\t\tsa.acceptElement(8);\n\t\tsa.acceptElement(16);\n\t}", "\[email protected]\n\tpublic void testFlipOK() {\n\t\tfinal SequenceAcceptor sa = new SequenceAcceptorImpl();\n\t\tsa.reset(SequenceAcceptor.Sequence.FLIP);\n\t\tsa.acceptElement(1);\n\t\tsa.acceptElement(0);\n\t\tsa.acceptElement(1);\n\t\tsa.acceptElement(0);\n\t\tsa.acceptElement(1);\n\t}", "\[email protected]\n\tpublic void testRambleOK() {\n\t\tfinal SequenceAcceptor sa = new SequenceAcceptorImpl();\n\t\tsa.reset(SequenceAcceptor.Sequence.RAMBLE);\n\t\tsa.acceptElement(0);\n\t\tsa.acceptElement(1);\n\t\tsa.acceptElement(0);\n\t\tsa.acceptElement(2);\n\t\tsa.acceptElement(0);\n\t\tsa.acceptElement(3);\n\t}", "\[email protected]\n\tpublic void optionalTestFiboOK() {\n\t\tfinal SequenceAcceptor sa = new SequenceAcceptorImpl();\n\t\tsa.reset(SequenceAcceptor.Sequence.FIBONACCI);\n\t\tsa.acceptElement(1);\n\t\tsa.acceptElement(1);\n\t\tsa.acceptElement(2);\n\t\tsa.acceptElement(3);\n\t\tsa.acceptElement(5);\n\t\tsa.acceptElement(8);\n\t\tsa.acceptElement(13);\n\t}", "\[email protected]\n\tpublic void optionalTestReset() {\n\t\t// test with resets and sequence change\n\t\tfinal SequenceAcceptor sa = new SequenceAcceptorImpl();\n\t\tsa.reset(SequenceAcceptor.Sequence.FIBONACCI);\n\t\tsa.acceptElement(1);\n\t\tsa.acceptElement(1);\n\t\tsa.acceptElement(2);\n\t\tsa.acceptElement(3);\n\t\tsa.acceptElement(5);\n\t\tsa.reset(SequenceAcceptor.Sequence.POWER2);\n\t\tsa.acceptElement(1);\n\t\tsa.acceptElement(2);\n\t\tsa.acceptElement(4);\n\t\tsa.reset(SequenceAcceptor.Sequence.POWER2);\n\t\tsa.acceptElement(1);\n\t\tsa.acceptElement(2);\n\t\tsa.acceptElement(4);\n\t}", "\[email protected]\n\tpublic void optionalTestResetEmpty() {\n\t\t// test with resets without sequence change\n\t\tfinal SequenceAcceptor sa = new SequenceAcceptorImpl();\n\t\tsa.reset(SequenceAcceptor.Sequence.FIBONACCI);\n\t\tsa.acceptElement(1);\n\t\tsa.acceptElement(1);\n\t\tsa.acceptElement(2);\n\t\tsa.acceptElement(3);\n\t\tsa.acceptElement(5);\n\t\tsa.reset();\n\t\tsa.acceptElement(1);\n\t\tsa.acceptElement(1);\n\t\tsa.acceptElement(2);\n\t\tsa.acceptElement(3);\n\t\tsa.acceptElement(5);\n\t\tsa.reset();\n\t\tsa.acceptElement(1);\n\t\tsa.acceptElement(1);\n\t\tsa.acceptElement(2);\n\t}" ] }, "content": "package a02a.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;\n\npublic class Test {\n\t\n\t/*\n\t * Implement the SequenceAcceptor interface provided through a SequenceAcceptorImpl class with a constructor without arguments.\n\t * Implements a concept of consumer of infinite sequences of integers.\n\t * A finite set of sequences is possible, indicated in the enum SequenceAcceptor.Sequence.\n\t * The reset method in SequenceAcceptor is used to restart the sequence, so as to consume a sequence from the beginning.\n\t * The comment to the SequenceAcceptor code, and the test methods below constitute the necessary explanation of the \n\t * problem.\n\t * \n\t * Note that the tests with the @org.junit.Test(expected = ...) annotation pass only if the exception indicated in the ... is thrown.\n\t * Note that the tests with the @org.junit.Test annotation pass if no exception is thrown\n\t * \n\t * The following are considered optional for the purpose of being able to correct the exercise, but still contribute to the achievement \n\t * of the totality of the score:\n\t * - implementation of the tests called optionalTestXYZ (related to the reset methods and the Fibonacci sequence) \n\t * - the good design of the solution, in particular with minimization of repetitions\n\t * \n\t */\n\t\n\[email protected]\n\tpublic void testPower2OK() {\n\t\tfinal SequenceAcceptor sa = new SequenceAcceptorImpl();\n\t\tsa.reset(SequenceAcceptor.Sequence.POWER2);\n\t\tsa.acceptElement(1);\n\t\tsa.acceptElement(2);\n\t\tsa.acceptElement(4);\n\t\tsa.acceptElement(8);\n\t\tsa.acceptElement(16);\n\t}\n\t\n\[email protected](expected = IllegalStateException.class)\n\tpublic void testPower2NO() {\n\t\tfinal SequenceAcceptor sa = new SequenceAcceptorImpl();\n\t\tsa.reset(SequenceAcceptor.Sequence.POWER2);\n\t\tsa.acceptElement(1);\n\t\tsa.acceptElement(2);\n\t\tsa.acceptElement(4);\n\t\tsa.acceptElement(8);\n\t\tsa.acceptElement(17); // must be rejected by throwing an exception\n\t}\n\t\n\[email protected]\n\tpublic void testFlipOK() {\n\t\tfinal SequenceAcceptor sa = new SequenceAcceptorImpl();\n\t\tsa.reset(SequenceAcceptor.Sequence.FLIP);\n\t\tsa.acceptElement(1);\n\t\tsa.acceptElement(0);\n\t\tsa.acceptElement(1);\n\t\tsa.acceptElement(0);\n\t\tsa.acceptElement(1);\n\t}\n\t\n\[email protected](expected = IllegalStateException.class)\n\tpublic void testFlipNO() {\n\t\tfinal SequenceAcceptor sa = new SequenceAcceptorImpl();\n\t\tsa.reset(SequenceAcceptor.Sequence.FLIP);\n\t\tsa.acceptElement(1);\n\t\tsa.acceptElement(0);\n\t\tsa.acceptElement(1);\n\t\tsa.acceptElement(0);\n\t\tsa.acceptElement(0); // must be rejected\n\t}\n\t\n\[email protected]\n\tpublic void testRambleOK() {\n\t\tfinal SequenceAcceptor sa = new SequenceAcceptorImpl();\n\t\tsa.reset(SequenceAcceptor.Sequence.RAMBLE);\n\t\tsa.acceptElement(0);\n\t\tsa.acceptElement(1);\n\t\tsa.acceptElement(0);\n\t\tsa.acceptElement(2);\n\t\tsa.acceptElement(0);\n\t\tsa.acceptElement(3);\n\t}\n\t\n\[email protected](expected = IllegalStateException.class)\n\tpublic void testRambleNO() {\n\t\tfinal SequenceAcceptor sa = new SequenceAcceptorImpl();\n\t\tsa.reset(SequenceAcceptor.Sequence.RAMBLE);\n\t\tsa.acceptElement(0);\n\t\tsa.acceptElement(1);\n\t\tsa.acceptElement(0);\n\t\tsa.acceptElement(2);\n\t\tsa.acceptElement(0);\n\t\tsa.acceptElement(0); // must be rejected\n\t}\n\t\n\t// from here on only \"optional\" tests\n\t\n\[email protected]\n\tpublic void optionalTestFiboOK() {\n\t\tfinal SequenceAcceptor sa = new SequenceAcceptorImpl();\n\t\tsa.reset(SequenceAcceptor.Sequence.FIBONACCI);\n\t\tsa.acceptElement(1);\n\t\tsa.acceptElement(1);\n\t\tsa.acceptElement(2);\n\t\tsa.acceptElement(3);\n\t\tsa.acceptElement(5);\n\t\tsa.acceptElement(8);\n\t\tsa.acceptElement(13);\n\t}\n\n\[email protected](expected = IllegalStateException.class)\n\tpublic void optionalTestFiboNO() {\n\t\tfinal SequenceAcceptor sa = new SequenceAcceptorImpl();\n\t\tsa.reset(SequenceAcceptor.Sequence.FIBONACCI);\n\t\tsa.acceptElement(1);\n\t\tsa.acceptElement(1);\n\t\tsa.acceptElement(2);\n\t\tsa.acceptElement(3);\n\t\tsa.acceptElement(5);\n\t\tsa.acceptElement(8);\n\t\tsa.acceptElement(14); // must be rejected\n\t}\n\n\[email protected]\n\tpublic void optionalTestReset() {\n\t\t// test with resets and sequence change\n\t\tfinal SequenceAcceptor sa = new SequenceAcceptorImpl();\n\t\tsa.reset(SequenceAcceptor.Sequence.FIBONACCI);\n\t\tsa.acceptElement(1);\n\t\tsa.acceptElement(1);\n\t\tsa.acceptElement(2);\n\t\tsa.acceptElement(3);\n\t\tsa.acceptElement(5);\n\t\tsa.reset(SequenceAcceptor.Sequence.POWER2);\n\t\tsa.acceptElement(1);\n\t\tsa.acceptElement(2);\n\t\tsa.acceptElement(4);\n\t\tsa.reset(SequenceAcceptor.Sequence.POWER2);\n\t\tsa.acceptElement(1);\n\t\tsa.acceptElement(2);\n\t\tsa.acceptElement(4);\n\t}\n\t\n\[email protected]\n\tpublic void optionalTestResetEmpty() {\n\t\t// test with resets without sequence change\n\t\tfinal SequenceAcceptor sa = new SequenceAcceptorImpl();\n\t\tsa.reset(SequenceAcceptor.Sequence.FIBONACCI);\n\t\tsa.acceptElement(1);\n\t\tsa.acceptElement(1);\n\t\tsa.acceptElement(2);\n\t\tsa.acceptElement(3);\n\t\tsa.acceptElement(5);\n\t\tsa.reset();\n\t\tsa.acceptElement(1);\n\t\tsa.acceptElement(1);\n\t\tsa.acceptElement(2);\n\t\tsa.acceptElement(3);\n\t\tsa.acceptElement(5);\n\t\tsa.reset();\n\t\tsa.acceptElement(1);\n\t\tsa.acceptElement(1);\n\t\tsa.acceptElement(2);\n\t}\n\t\n\[email protected](expected = IllegalStateException.class)\n\tpublic void optionalTestWrongReset() {\n\t\tfinal SequenceAcceptor sa = new SequenceAcceptorImpl();\n\t\t// you can't reset without knowing which sequence you are starting from\n\t\tsa.reset(); \n\t}\n\t\n\[email protected](expected = IllegalStateException.class)\n\tpublic void optionalTestNoReset() {\n\t\tfinal SequenceAcceptor sa = new SequenceAcceptorImpl();\n\t\t// you can't produce an element without having reset at the beginning\n\t\tsa.acceptElement(0);\n\t}\n\n}", "filename": "Test.java" }
2017
a02b
[ { "content": "package a02b.sol1;\n\n\n\npublic interface Transducer<X,Y> {\n\t \n\t\n\tvoid provideNextInput(X x);\n\t\n\t\n\t\n\tvoid inputIsOver();\n\n\t\n\t\n\tboolean isNextOutputReady();\n\t\n\t\n\tY getOutputElement();\n\t\n\t\n\tboolean isOutputOver();\n}", "filename": "Transducer.java" }, { "content": "package a02b.sol1;\n\npublic interface TransducerFactory {\n\t\n\t\n\t<X> Transducer<X,String> makeConcatenator(int inputSize);\n\t\n\t\n\tTransducer<Integer,Integer> makePairSummer();\n}", "filename": "TransducerFactory.java" }, { "content": "package a02b.sol1;\n\npublic interface Function<I, O> {\n\tO apply(I i);\n}", "filename": "Function.java" } ]
[ { "content": "package a02b.sol1;\n\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.function.Supplier;\n\npublic class TransducerImpl<X, Y> implements Transducer<X, Y> {\n\n\tprivate final int maxSize;\n\tprivate Function<List<X>, Y> mapper;\n\tprivate List<X> queue;\n\tprivate boolean inputOver;\n\n\t// Package-private\n\tTransducerImpl(int maxSize, Function<List<X>, Y> mapper) {\n\t\tsuper();\n\t\tthis.maxSize = maxSize;\n\t\tthis.mapper = mapper;\n\t\tthis.queue = new LinkedList<>();\n\t}\n\n\tprivate void checkIllegalState(Supplier<Boolean> condition) {\n\t\tif (condition.get()) {\n\t\t\tthrow new IllegalStateException();\n\t\t}\n\t}\n\n\t@Override\n\tpublic Y getOutputElement() {\n\t\tthis.checkIllegalState(() -> !isNextOutputReady());\n\t\tfinal int size = Math.min(this.maxSize, this.queue.size());\n\t\tfinal Y y = mapper.apply(this.queue.subList(0, size));\n\t\tthis.queue = this.queue.subList(size, this.queue.size());\n\t\treturn y;\n\t}\n\n\t@Override\n\tpublic boolean isNextOutputReady() {\n\t\treturn this.queue.size() >= this.maxSize || (this.inputOver && this.queue.size() > 0);\n\t}\n\n\t@Override\n\tpublic boolean isOutputOver() {\n\t\treturn this.inputOver && this.queue.isEmpty();\n\t}\n\n\t@Override\n\tpublic void provideNextInput(X y) {\n\t\tthis.checkIllegalState(() -> this.inputOver);\n\t\tthis.queue.add(y);\n\t}\n\n\t@Override\n\tpublic void inputIsOver() {\n\t\tthis.checkIllegalState(() -> this.inputOver);\n\t\tthis.inputOver = true;\n\t}\n\n}", "filename": "TransducerImpl.java" }, { "content": "package a02b.sol1;\n\npublic class TransducerFactoryImpl implements TransducerFactory {\n\n\t@Override\n\tpublic <X> Transducer<X, String> makeConcatenator(int inputSize) {\n\t\treturn new TransducerImpl<>(inputSize,l -> l.stream().map(Object::toString).reduce((x,y)->x+y).get());\n\t}\n\n\t\t@Override\n\tpublic Transducer<Integer, Integer> makePairSummer() {\n\t\treturn new TransducerImpl<>(2,l -> l.stream().reduce((x,y)->x+y).get());\n\t}\n\n}", "filename": "TransducerFactoryImpl.java" } ]
{ "components": { "imports": "package a02b.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;", "private_init": "\t/*\n\t * An interface TransducerFactory is provided (to be implemented with a class TransducerFactoryImpl with a constructor without arguments),\n\t * which models a factory for Transducers, i.e., sequence transformers. A Transducer receives objects in sequence until\n\t * its input is closed. In groups, these objects are transformed into an object to be produced as output in a manner similar to\n\t * an iterator: extraction can occur as soon as the values are available or even later.\n\t * The factory asks to implement two types of transducers:\n\t * - concatenator(N): groups objects into lists of N elements, and for each produces the concatenation of their toString\n\t * - summer: groups integers in pairs, and for each pair produces their sum\n\t *\n\t * In both cases, when the transducer is closed, the remaining elements it contains contribute to the formation of at least one\n\t * output element.\n\t * \n\t * Note that the tests with the @org.junit.Test(expected = ...) annotation pass only if the exception indicated in the ... is thrown.\n\t * \n\t * The following are considered optional for the purpose of being able to correct the exercise, but still contribute to achieving\n\t * the totality of the score:\n\t * - implementation of the tests called optionalTestXYZ (related to the pairsummer transducer) \n\t * - the good design of the solution, in particular with minimization of repetitions\n\t * \n\t */", "test_functions": [ "\[email protected]\n\tpublic void testConcatenator() {\n\t\tTransducer<Integer,String> t = new TransducerFactoryImpl().makeConcatenator(3); // concatenates integers 3 by 3\n\t\tassertFalse(t.isNextOutputReady());\n\t\tassertFalse(t.isOutputOver());\n\t\tt.provideNextInput(1);\t// insert 1\n\t\tassertFalse(t.isNextOutputReady());\n\t\tassertFalse(t.isOutputOver());\n\t\tt.provideNextInput(2);\n\t\tt.provideNextInput(3);\n\t\tt.provideNextInput(4); // insert 2,3,4: now internally I have 1,2,3,4\n\t\tassertTrue(t.isNextOutputReady());\n\t\tassertFalse(t.isOutputOver());\n\t\tassertEquals(t.getOutputElement(),\"123\"); // emit an output, 4 remains\n\t\tassertFalse(t.isNextOutputReady());\n\t\tassertFalse(t.isOutputOver());\n\t\tt.provideNextInput(5);\n\t\tt.provideNextInput(6); // insert 5,6: now internally I have 4,5,6\n\t\tassertTrue(t.isNextOutputReady());\n\t\tassertFalse(t.isOutputOver());\n\t\tassertEquals(t.getOutputElement(),\"456\"); // emit an output, nothing remains\n\t\tt.provideNextInput(7); // insert 7: now internally I have 7\n\t\tassertFalse(t.isNextOutputReady());\n\t\tassertFalse(t.isOutputOver());\n\t\tt.inputIsOver();\t\t// the input is closed\n\t\tassertTrue(t.isNextOutputReady()); // the 7 alone is available for an output\n\t\tassertFalse(t.isOutputOver());\n\t\tassertEquals(t.getOutputElement(),\"7\"); // emit an output, nothing remains\n\t\tassertFalse(t.isNextOutputReady());\n\t\tassertTrue(t.isOutputOver());\n\t}", "\[email protected]\n\tpublic void testEmptyConcatenator() {\n\t\t// test in which the transducer is closed immediately..\n\t\tTransducer<Integer,String> t = new TransducerFactoryImpl().makeConcatenator(3);\n\t\tassertFalse(t.isNextOutputReady());\n\t\tassertFalse(t.isOutputOver());\n\t\tt.inputIsOver();\n\t\tassertFalse(t.isNextOutputReady());\n\t\tassertTrue(t.isOutputOver());\n\t}", "\[email protected]\n\tpublic void optionalTestSummer() {\n\t\t// test for the pair summer\n\t\t// only note: on closing, if a single integer remains, it is produced as output\n\t\tTransducer<Integer,Integer> t = new TransducerFactoryImpl().makePairSummer();\n\t\tassertFalse(t.isNextOutputReady());\n\t\tassertFalse(t.isOutputOver());\n\t\tt.provideNextInput(1);\n\t\tassertFalse(t.isNextOutputReady());\n\t\tassertFalse(t.isOutputOver());\n\t\tt.provideNextInput(20);\n\t\tt.provideNextInput(300);\n\t\tassertTrue(t.isNextOutputReady());\n\t\tassertFalse(t.isOutputOver());\n\t\tassertEquals(t.getOutputElement().intValue(),21);\n\t\tassertFalse(t.isNextOutputReady());\n\t\tassertFalse(t.isOutputOver());\n\t\tt.provideNextInput(4000);\n\t\tt.provideNextInput(50000);\n\t\tassertTrue(t.isNextOutputReady());\n\t\tassertFalse(t.isOutputOver());\n\t\tassertEquals(t.getOutputElement().intValue(),4300);\n\t\tt.inputIsOver(); // 5000 remains alone\n\t\tassertTrue(t.isNextOutputReady());\n\t\tassertFalse(t.isOutputOver());\n\t\tassertEquals(t.getOutputElement().intValue(),50000); // 5000 is emitted\n\t\tassertFalse(t.isNextOutputReady());\n\t\tassertTrue(t.isOutputOver());\n\t}" ] }, "content": "package a02b.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;\n\npublic class Test {\n\t\n\t/*\n\t * An interface TransducerFactory is provided (to be implemented with a class TransducerFactoryImpl with a constructor without arguments),\n\t * which models a factory for Transducers, i.e., sequence transformers. A Transducer receives objects in sequence until\n\t * its input is closed. In groups, these objects are transformed into an object to be produced as output in a manner similar to\n\t * an iterator: extraction can occur as soon as the values are available or even later.\n\t * The factory asks to implement two types of transducers:\n\t * - concatenator(N): groups objects into lists of N elements, and for each produces the concatenation of their toString\n\t * - summer: groups integers in pairs, and for each pair produces their sum\n\t *\n\t * In both cases, when the transducer is closed, the remaining elements it contains contribute to the formation of at least one\n\t * output element.\n\t * \n\t * Note that the tests with the @org.junit.Test(expected = ...) annotation pass only if the exception indicated in the ... is thrown.\n\t * \n\t * The following are considered optional for the purpose of being able to correct the exercise, but still contribute to achieving\n\t * the totality of the score:\n\t * - implementation of the tests called optionalTestXYZ (related to the pairsummer transducer) \n\t * - the good design of the solution, in particular with minimization of repetitions\n\t * \n\t */\n\t\n\[email protected]\n\tpublic void testConcatenator() {\n\t\tTransducer<Integer,String> t = new TransducerFactoryImpl().makeConcatenator(3); // concatenates integers 3 by 3\n\t\tassertFalse(t.isNextOutputReady());\n\t\tassertFalse(t.isOutputOver());\n\t\tt.provideNextInput(1);\t// insert 1\n\t\tassertFalse(t.isNextOutputReady());\n\t\tassertFalse(t.isOutputOver());\n\t\tt.provideNextInput(2);\n\t\tt.provideNextInput(3);\n\t\tt.provideNextInput(4); // insert 2,3,4: now internally I have 1,2,3,4\n\t\tassertTrue(t.isNextOutputReady());\n\t\tassertFalse(t.isOutputOver());\n\t\tassertEquals(t.getOutputElement(),\"123\"); // emit an output, 4 remains\n\t\tassertFalse(t.isNextOutputReady());\n\t\tassertFalse(t.isOutputOver());\n\t\tt.provideNextInput(5);\n\t\tt.provideNextInput(6); // insert 5,6: now internally I have 4,5,6\n\t\tassertTrue(t.isNextOutputReady());\n\t\tassertFalse(t.isOutputOver());\n\t\tassertEquals(t.getOutputElement(),\"456\"); // emit an output, nothing remains\n\t\tt.provideNextInput(7); // insert 7: now internally I have 7\n\t\tassertFalse(t.isNextOutputReady());\n\t\tassertFalse(t.isOutputOver());\n\t\tt.inputIsOver();\t\t// the input is closed\n\t\tassertTrue(t.isNextOutputReady()); // the 7 alone is available for an output\n\t\tassertFalse(t.isOutputOver());\n\t\tassertEquals(t.getOutputElement(),\"7\"); // emit an output, nothing remains\n\t\tassertFalse(t.isNextOutputReady());\n\t\tassertTrue(t.isOutputOver());\n\t}\n\t\n\[email protected]\n\tpublic void testEmptyConcatenator() {\n\t\t// test in which the transducer is closed immediately..\n\t\tTransducer<Integer,String> t = new TransducerFactoryImpl().makeConcatenator(3);\n\t\tassertFalse(t.isNextOutputReady());\n\t\tassertFalse(t.isOutputOver());\n\t\tt.inputIsOver();\n\t\tassertFalse(t.isNextOutputReady());\n\t\tassertTrue(t.isOutputOver());\n\t}\n\t\t\n\[email protected](expected = IllegalStateException.class)\n\tpublic void testGettingWhenNotAvailable() {\n\t\t// test in which an attempt is illegally made to take output even when there is none..\n\t\tTransducer<Integer,String> t = new TransducerFactoryImpl().makeConcatenator(3);\n\t\tassertFalse(t.isNextOutputReady());\n\t\tassertFalse(t.isOutputOver());\n\t\tt.provideNextInput(1);\n\t\tassertFalse(t.isNextOutputReady());\n\t\tt.getOutputElement();\n\t}\n\t\n\[email protected](expected = IllegalStateException.class)\n\tpublic void testGettingWhenOver() {\n\t\t// test in which an attempt is illegally made to take an output even when the input is closed and there is none\n\t\tTransducer<Integer,String> t = new TransducerFactoryImpl().makeConcatenator(3);\n\t\tassertFalse(t.isNextOutputReady());\n\t\tassertFalse(t.isOutputOver());\n\t\tt.provideNextInput(1);\n\t\tt.inputIsOver();\n\t\tassertEquals(t.getOutputElement(),\"1\");\n\t\tt.getOutputElement();\n\t}\n\t\n\[email protected](expected = IllegalStateException.class)\n\tpublic void testClosingTwice() {\n\t\t// test in which an attempt is illegally made to close an already closed input\n\t\tTransducer<Integer,String> t = new TransducerFactoryImpl().makeConcatenator(3);\n\t\tt.inputIsOver();\n\t\tt.inputIsOver();\n\t}\n\t\n\t// from here on only optional tests\n\t\n\[email protected]\n\tpublic void optionalTestSummer() {\n\t\t// test for the pair summer\n\t\t// only note: on closing, if a single integer remains, it is produced as output\n\t\tTransducer<Integer,Integer> t = new TransducerFactoryImpl().makePairSummer();\n\t\tassertFalse(t.isNextOutputReady());\n\t\tassertFalse(t.isOutputOver());\n\t\tt.provideNextInput(1);\n\t\tassertFalse(t.isNextOutputReady());\n\t\tassertFalse(t.isOutputOver());\n\t\tt.provideNextInput(20);\n\t\tt.provideNextInput(300);\n\t\tassertTrue(t.isNextOutputReady());\n\t\tassertFalse(t.isOutputOver());\n\t\tassertEquals(t.getOutputElement().intValue(),21);\n\t\tassertFalse(t.isNextOutputReady());\n\t\tassertFalse(t.isOutputOver());\n\t\tt.provideNextInput(4000);\n\t\tt.provideNextInput(50000);\n\t\tassertTrue(t.isNextOutputReady());\n\t\tassertFalse(t.isOutputOver());\n\t\tassertEquals(t.getOutputElement().intValue(),4300);\n\t\tt.inputIsOver(); // 5000 remains alone\n\t\tassertTrue(t.isNextOutputReady());\n\t\tassertFalse(t.isOutputOver());\n\t\tassertEquals(t.getOutputElement().intValue(),50000); // 5000 is emitted\n\t\tassertFalse(t.isNextOutputReady());\n\t\tassertTrue(t.isOutputOver());\n\t}\n\n\[email protected](expected = IllegalStateException.class)\n\tpublic void optionalTestGettingWhenNotAvailableOnSummer() {\n\t\t// like testGettingWhenNotAvailable but for Summer\n\t\tTransducer<Integer,Integer> t = new TransducerFactoryImpl().makePairSummer();\n\t\tassertFalse(t.isNextOutputReady());\n\t\tassertFalse(t.isOutputOver());\n\t\tt.provideNextInput(1);\n\t\tassertFalse(t.isNextOutputReady());\n\t\tt.getOutputElement();\n\t}\n\t\n\[email protected](expected = IllegalStateException.class)\n\tpublic void optionalTestGettingWhenOverOnSummer() {\n\t\t// like testGettingWhenOver but for Summer\n\t\tTransducer<Integer,Integer> t = new TransducerFactoryImpl().makePairSummer();\n\t\tassertFalse(t.isNextOutputReady());\n\t\tassertFalse(t.isOutputOver());\n\t\tt.provideNextInput(1);\n\t\tt.inputIsOver();\n\t\tassertEquals(t.getOutputElement().intValue(),1);\n\t\tt.getOutputElement();\n\t}\n\t\n}", "filename": "Test.java" }
2017
a05
[ { "content": "package a05.sol1;\n\n\npublic interface Match {\n\n\t\n\tString getHomeTeam();\n\n\t\n\tString getAwayTeam();\n}", "filename": "Match.java" }, { "content": "package a05.sol1;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class Combinations {\n\t\n\tpublic static void main(String[] args) {\n\t\t\n\t\tSystem.out.println(combine(Arrays.asList(1,2,3,4)));\n\t\t\n\t\t\n\t\t\n\t\t\n\t\t\n\t\t\n\t\t\n\t\t\n\t}\n\n\t\n\tpublic static <X> List<List<X>> combine(List<X> list){\n\t\t\n\t\tList<List<X>> outlist = new ArrayList<>();\n\t\t\n\t\tfor (int i=0;i<(list.size()-1)*2;i++) {\n\t\t\t\n\t\t\tList<X> viableteams = new ArrayList<>(list);\n\t\t\t\n\t\t\tfor (X s1: list) {\n\t\t\t\tfor (X s2: list) {\n\t\t\t\t\t\n\t\t\t\t\tList<X> newCombination = Arrays.asList(s1,s2);\n\t\t\t\t\tif (!s1.equals(s2) && \n\t\t\t\t\t\t\tviableteams.contains(s1) && \n\t\t\t\t\t\t\tviableteams.contains(s2) && \n\t\t\t\t\t\t\t!outlist.contains(newCombination)) { \n\t\t\t\t\t\toutlist.add(newCombination); \n\t\t\t\t\t\tviableteams.remove(s1); \n\t\t\t\t\t\tviableteams.remove(s2); \n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn outlist;\n\t}\n\n}", "filename": "Combinations.java" }, { "content": "package a05.sol1;\n\npublic class MatchImpl implements Match {\n\t\n\tprivate final String homeTeam;\n\tprivate final String awayTeam;\n\t\n\tpublic MatchImpl(String homeTeam, String awayTeam) {\n\t\tsuper();\n\t\tthis.homeTeam = homeTeam;\n\t\tthis.awayTeam = awayTeam;\n\t}\n\n\t@Override\n\tpublic String getHomeTeam() {\n\t\treturn this.homeTeam;\n\t}\n\n\t@Override\n\tpublic String getAwayTeam() {\n\t\treturn this.awayTeam;\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 + ((awayTeam == null) ? 0 : awayTeam.hashCode());\n\t\tresult = prime * result + ((homeTeam == null) ? 0 : homeTeam.hashCode());\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj) {\n\t\t\treturn true;\n\t\t}\n\t\tif (obj == null) {\n\t\t\treturn false;\n\t\t}\n\t\tif (!(obj instanceof MatchImpl)) {\n\t\t\treturn false;\n\t\t}\n\t\tMatchImpl other = (MatchImpl) obj;\n\t\tif (awayTeam == null) {\n\t\t\tif (other.awayTeam != null) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t} else if (!awayTeam.equals(other.awayTeam)) {\n\t\t\treturn false;\n\t\t}\n\t\tif (homeTeam == null) {\n\t\t\tif (other.homeTeam != null) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t} else if (!homeTeam.equals(other.homeTeam)) {\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"M[\" + homeTeam + \",\" + awayTeam + \"]\";\n\t}\n\t\n\t\n\n}", "filename": "MatchImpl.java" }, { "content": "package a05.sol1;\n\nimport java.util.Map;\nimport java.util.Set;\n\n\n\npublic interface Championship {\n\n\t\n\tvoid registerTeam(String name);\n\t\n\t\n\tvoid startChampionship();\n\t\n\t\n\tvoid newDay();\n\n\t\n\tSet<Match> pendingMatches();\n\t\n\t\n\tvoid matchPlay(Match match, int homeGoals, int awayGoals);\n\t\t\n\t\n\tMap<String,Integer> getClassification();\n\t\n\t\n\tboolean championshipOver();\n\t\n}", "filename": "Championship.java" } ]
[ { "content": "package a05.sol1;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Map.Entry;\nimport java.util.Optional;\nimport java.util.Set;\nimport java.util.stream.Collectors;\n\npublic class ChampionshipImpl implements Championship {\n\t\n\tprivate enum Result {\n\t\tHOMEWIN, HOMELOSS, EVEN;\n\t\t\n\t\tpublic int points(Match m, String team) {\n\t\t\tif (team.equals(m.getHomeTeam())) {\n\t\t\t\treturn this == HOMEWIN ? 3 : this == EVEN ? 1: 0;\n\t\t\t} else if (team.equals(m.getAwayTeam())) {\n\t\t\t\treturn this == HOMEWIN ? 0 : this == EVEN ? 1: 3;\t\t\t\t\n\t\t\t}\n\t\t\treturn 0;\n\t\t}\n\t\t\n\t\tpublic static Result fromGoals(int homeGoals, int awayGoals) {\n\t\t\treturn homeGoals > awayGoals ? HOMEWIN : homeGoals == awayGoals ? EVEN : HOMELOSS;\n\t\t}\n\t}\n\tprivate final List<String> teams = new ArrayList<>();\n\tprivate Map<Match, Optional<Result>> matches;\n\n\t@Override\n\tpublic void registerTeam(String name) {\n\t\tthis.teams.add(name);\n\t}\n\n\t@Override\n\tpublic void startChampionship() {\n\t\tthis.matches = new HashMap<>();\n\t}\n\n\t@Override\n\tpublic Set<Match> pendingMatches() {\n\t\treturn this.matches.entrySet()\n\t\t\t\t .stream()\n\t\t .filter(e -> !e.getValue().isPresent())\n\t\t .map(e -> e.getKey())\n\t\t .collect(Collectors.toSet());\n\t}\n\n\t@Override\n\tpublic void matchPlay(Match m, int homeGoals, int awayGoals) {\n\t\tthis.matches.put(m, Optional.of(Result.fromGoals(homeGoals, awayGoals)));\n\t}\n\t\n\tprivate boolean teamIncluded(String team, Match match) {\n\t\treturn team.equals(match.getAwayTeam()) || team.equals(match.getHomeTeam());\n\t}\n\t\n\tprivate boolean notScheduled(String team) {\n\t\treturn !this.pendingMatches().stream()\n\t\t\t\t\t\t .filter(m -> teamIncluded(team,m))\n\t\t\t\t .anyMatch(e -> true);\n\t}\n\n\t@Override\n\tpublic void newDay() {\n\t\tfor (String team: this.teams) {\n\t\t\tif (notScheduled(team)) {\n\t\t\t\tfor (String team2: this.teams) {\n\t\t\t\t\tMatch match = new MatchImpl(team,team2);\n\t\t\t\t\tif (!team.equals(team2) && notScheduled(team2) && !matches.containsKey(match)) {\n\t\t\t\t\t\tthis.matches.put(match, Optional.empty());\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t@Override\n\tpublic Map<String, Integer> getClassification() {\n\t\tfinal Map<String, Integer> classification = this.teams.stream().collect(Collectors.toMap(team->team, team->0));\n\t\tfor (Entry<Match,Optional<Result>> e: matches.entrySet()) {\n\t\t\tif (e.getValue().isPresent()) {\n\t\t\t\tint homePoints = e.getValue().get().points(e.getKey(), e.getKey().getHomeTeam());\n\t\t\t\tint awayPoints = e.getValue().get().points(e.getKey(), e.getKey().getAwayTeam());\n\t\t\t\tclassification.merge(e.getKey().getHomeTeam(), 0, (i,j)->i+homePoints);\n\t\t\t\tclassification.merge(e.getKey().getAwayTeam(), 0, (i,j)->i+awayPoints);\n\t\t\t}\n\t\t}\n\t\treturn classification;\n\t}\n\n\t@Override\n\tpublic boolean championshipOver() {\n\t\treturn this.pendingMatches().isEmpty() && this.matches.size()==this.teams.size()*(this.teams.size()-1);\n\t}\n\n}", "filename": "ChampionshipImpl.java" } ]
{ "components": { "imports": "package a05.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;\n\n/**\n * In this exercise, a championship organized in the Italian style (or rather, similar to Italian) will be modeled, i.e., with N teams\n * (even) that play (N-1)*2 days. A team can play at home or away. So in the\n * (N-1)*2 days each team meets all the other teams 2 times, once at home and once away.\n * Once the teams are registered in a certain order, the matches of a given day are organized starting from the\n * first team (gradually descending in the list), at home, and finding (if there is one) the first team with which it has not already\n * played at home.\n * This algorithm is available in the data class Combinations---and can be adapted at will, optionally.\n * Note then, that for simplicity, unlike the normal Italian management, there is no division\n * \"first round\" and \"second round\", and therefore two teams could play the first leg and the second leg\n * both at the beginning of the championship, or both at the end.\n * Consider also the test for this purpose, and in particular: testChampionship\n *\n * Consult the documentation of the provided Match interface, which is already implemented in MatchImpl\n * (it is recommended to use this implementation).\n * Then consult the documentation of the Championship interface, which must be implemented with a class\n * ChampionshipImpl with a constructor without arguments.\n *\n * The following are considered optional for the purpose of being able to correct the exercise, but still contribute\n * to achieving the totality of the score:\n * - implementation of the optional test (related to the getClassification method)\n * - good design of the solution\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. Note that in this exercise it is not required to\n * manage particular cases that would normally throw exceptions.\n *\n * Remove the comment from the test code.\n */", "private_init": "\tprivate static final List<String> teams = Arrays.asList(\"Juve\", \"Inter\", \"Milan\", \"Napoli\");", "test_functions": [ "\[email protected]\n public void testStart() {\n\t\tChampionship c = new ChampionshipImpl();\n\t\tteams.forEach(team -> c.registerTeam(team));\n\t\tc.startChampionship();\n\t\t// having not called newDay(), the pending matches have not yet been prepared\n\t\tassertTrue(c.pendingMatches().isEmpty());\n\t}", "\[email protected]\n public void testFirstDay() {\n\t\tChampionshipImpl c = new ChampionshipImpl();\n\t\tteams.forEach(team -> c.registerTeam(team)); // \"Juve\", \"Inter\", \"Milan\", \"Napoli\"\n\t\tc.startChampionship();\n\t\tc.newDay();\n\t\tassertEquals(c.pendingMatches().size(),2);\n\t\t// it starts from Juve, which therefore plays with the second in order, Inter\n\t\tassertTrue(c.pendingMatches().contains(new MatchImpl(\"Juve\",\"Inter\")));\n\t\t// Inter is already assigned, so we continue with Milan at home, which therefore plays with Napoli\n\t\tassertTrue(c.pendingMatches().contains(new MatchImpl(\"Milan\",\"Napoli\")));\n\t}", "\[email protected]\n public void testGames() {\n\t\tChampionshipImpl c = new ChampionshipImpl();\n\t\tteams.forEach(team -> c.registerTeam(team)); // \"Juve\", \"Inter\", \"Milan\", \"Napoli\"\n\t\tc.startChampionship();\n\t\tc.newDay();\n\t\tassertEquals(c.pendingMatches().size(),2);\n\t\tc.matchPlay(new MatchImpl(\"Juve\",\"Inter\"), 0, 2); // Inter wins 2-0\n\t\tassertEquals(c.pendingMatches().size(),1);\n\t\tc.matchPlay(new MatchImpl(\"Milan\",\"Napoli\"), 1, 1); // draw 1-1\n\t\tassertEquals(c.pendingMatches().size(),0); // note that there are no pending matches now, until the next newDay\n\t}", "\[email protected]\n public void testNewDay() {\n\t\tChampionshipImpl c = new ChampionshipImpl();\n\t\tteams.forEach(team -> c.registerTeam(team)); // \"Juve\", \"Inter\", \"Milan\", \"Napoli\"\n\t\tc.startChampionship();\n\t\tc.newDay();\n\t\tc.matchPlay(new MatchImpl(\"Juve\",\"Inter\"), 0, 2);\n\t\tc.matchPlay(new MatchImpl(\"Milan\",\"Napoli\"), 1, 1);\n\t\tassertEquals(c.pendingMatches().size(),0);\n\t\t// I start the second day\n\t\tc.newDay();\n\t\tassertEquals(c.pendingMatches().size(),2);\n\t\t// it always starts from Juve at home: the next possible is Milan\n\t\tassertTrue(c.pendingMatches().contains(new MatchImpl(\"Juve\",\"Milan\")));\n\t\t// the next to consider is Inter, and only Napoli remains\n\t\tassertTrue(c.pendingMatches().contains(new MatchImpl(\"Inter\",\"Napoli\")));\n\t}", "\[email protected]\n public void testChampionship() {\n\t\tChampionshipImpl c = new ChampionshipImpl();\n\t\tteams.forEach(team -> c.registerTeam(team)); // \"Juve\", \"Inter\", \"Milan\", \"Napoli\"\n\t\tc.startChampionship();\n\t\t// list all 6 days ( (4-1)*2 )\n\t\tc.newDay();\n\t\tassertTrue(c.pendingMatches().contains(new MatchImpl(\"Juve\",\"Inter\")));\n\t\tassertTrue(c.pendingMatches().contains(new MatchImpl(\"Milan\",\"Napoli\")));\n\t\tc.matchPlay(new MatchImpl(\"Juve\",\"Inter\"), 0, 2);\n\t\tc.matchPlay(new MatchImpl(\"Milan\",\"Napoli\"), 1, 1);\n\t\tc.newDay();\n\t\tassertTrue(c.pendingMatches().contains(new MatchImpl(\"Juve\",\"Milan\")));\n\t\tassertTrue(c.pendingMatches().contains(new MatchImpl(\"Inter\",\"Napoli\")));\n\t\tc.matchPlay(new MatchImpl(\"Juve\",\"Milan\"), 0, 0);\n\t\tc.matchPlay(new MatchImpl(\"Inter\",\"Napoli\"), 2, 1);\n\t\tc.newDay();\n\t\tassertTrue(c.pendingMatches().contains(new MatchImpl(\"Juve\",\"Napoli\")));\n\t\tassertTrue(c.pendingMatches().contains(new MatchImpl(\"Inter\",\"Milan\")));\n\t\tc.matchPlay(new MatchImpl(\"Juve\",\"Napoli\"), 0, 1);\n\t\tc.matchPlay(new MatchImpl(\"Inter\",\"Milan\"), 3, 0);\n\t\tc.newDay();\n\t\tassertTrue(c.pendingMatches().contains(new MatchImpl(\"Inter\",\"Juve\")));\n\t\tassertTrue(c.pendingMatches().contains(new MatchImpl(\"Napoli\",\"Milan\")));\n\t\tc.matchPlay(new MatchImpl(\"Inter\",\"Juve\"), 0, 2);\n\t\tc.matchPlay(new MatchImpl(\"Napoli\",\"Milan\"), 1, 1);\n\t\tc.newDay();\n\t\tassertTrue(c.pendingMatches().contains(new MatchImpl(\"Milan\",\"Juve\")));\n\t\tassertTrue(c.pendingMatches().contains(new MatchImpl(\"Napoli\",\"Inter\")));\n\t\tc.matchPlay(new MatchImpl(\"Milan\",\"Juve\"), 0, 0);\n\t\tc.matchPlay(new MatchImpl(\"Napoli\",\"Inter\"), 2, 1);\n\t\tc.newDay();\n\t\tassertTrue(c.pendingMatches().contains(new MatchImpl(\"Milan\",\"Inter\")));\n\t\tassertTrue(c.pendingMatches().contains(new MatchImpl(\"Napoli\",\"Juve\")));\n\t\tc.matchPlay(new MatchImpl(\"Milan\",\"Inter\"), 0, 1);\n\t\tc.matchPlay(new MatchImpl(\"Napoli\",\"Juve\"), 3, 0);\n\t}", "\[email protected]\n public void testChampionshipOver() {\n\t\tChampionshipImpl c = new ChampionshipImpl();\n\t\tteams.forEach(team -> c.registerTeam(team)); // \"Juve\", \"Inter\", \"Milan\", \"Napoli\"\n\t\tc.startChampionship();\n\t\tc.newDay();\n\t\tc.matchPlay(new MatchImpl(\"Juve\",\"Inter\"), 0, 2);\n\t\tc.matchPlay(new MatchImpl(\"Milan\",\"Napoli\"), 1, 1);\n\t\tc.newDay();\n\t\tc.matchPlay(new MatchImpl(\"Juve\",\"Milan\"), 0, 0);\n\t\tc.matchPlay(new MatchImpl(\"Inter\",\"Napoli\"), 2, 1);\n\t\tc.newDay();\n\t\tc.matchPlay(new MatchImpl(\"Juve\",\"Napoli\"), 0, 1);\n\t\tc.matchPlay(new MatchImpl(\"Inter\",\"Milan\"), 3, 0);\n\t\tc.newDay();\n\t\tc.matchPlay(new MatchImpl(\"Inter\",\"Juve\"), 0, 2);\n\t\tc.matchPlay(new MatchImpl(\"Napoli\",\"Milan\"), 1, 1);\n\t\tc.newDay();\n\t\tc.matchPlay(new MatchImpl(\"Milan\",\"Juve\"), 0, 0);\n\t\tc.matchPlay(new MatchImpl(\"Napoli\",\"Inter\"), 2, 1);\n\t\tc.newDay();\n\t\tassertFalse(c.championshipOver());\n\t\tc.matchPlay(new MatchImpl(\"Milan\",\"Inter\"), 0, 1);\n\t\tc.matchPlay(new MatchImpl(\"Napoli\",\"Juve\"), 3, 0);\n\t\tassertTrue(c.championshipOver());\n\t}", "\[email protected]\n public void optionalTestClassification() {\n\t\tChampionshipImpl c = new ChampionshipImpl();\n\t\tteams.forEach(team -> c.registerTeam(team));\n\t\tc.startChampionship();\n\t\tc.newDay();\n\t\t// standings at the beginning\n\t\tassertEquals(c.getClassification().get(\"Juve\"),new Integer(0));\n\t\tassertEquals(c.getClassification().get(\"Inter\"),new Integer(0));\n\t\tassertEquals(c.getClassification().get(\"Milan\"),new Integer(0));\n\t\tassertEquals(c.getClassification().get(\"Napoli\"),new Integer(0));\n\t\tc.matchPlay(new MatchImpl(\"Juve\",\"Inter\"), 0, 2);\n\t\tc.matchPlay(new MatchImpl(\"Milan\",\"Napoli\"), 1, 1);\n\t\tc.newDay();\n\t\t// standings after one day\n\t\tassertEquals(c.getClassification().get(\"Juve\"),new Integer(0));\n\t\tassertEquals(c.getClassification().get(\"Inter\"),new Integer(3));\n\t\tassertEquals(c.getClassification().get(\"Milan\"),new Integer(1));\n\t\tassertEquals(c.getClassification().get(\"Napoli\"),new Integer(1));\n\t\tc.matchPlay(new MatchImpl(\"Juve\",\"Milan\"), 0, 0);\n\t\tc.matchPlay(new MatchImpl(\"Inter\",\"Napoli\"), 2, 1);\n\t\tc.newDay();\n\t\tc.matchPlay(new MatchImpl(\"Juve\",\"Napoli\"), 0, 1);\n\t\tc.matchPlay(new MatchImpl(\"Inter\",\"Milan\"), 3, 0);\n\t\tc.newDay();\n\t\tc.matchPlay(new MatchImpl(\"Inter\",\"Juve\"), 0, 2);\n\t\tc.matchPlay(new MatchImpl(\"Napoli\",\"Milan\"), 1, 1);\n\t\tc.newDay();\n\t\tc.matchPlay(new MatchImpl(\"Milan\",\"Juve\"), 0, 0);\n\t\tc.matchPlay(new MatchImpl(\"Napoli\",\"Inter\"), 2, 1);\n\t\tc.newDay();\n\t\tassertFalse(c.championshipOver());\n\t\tc.matchPlay(new MatchImpl(\"Milan\",\"Inter\"), 0, 1);\n\t\tc.matchPlay(new MatchImpl(\"Napoli\",\"Juve\"), 3, 0);\n\t\tassertTrue(c.championshipOver());\n\t\t// final standings\n\t\tassertEquals(c.getClassification().get(\"Juve\"),new Integer(5));\n\t\tassertEquals(c.getClassification().get(\"Inter\"),new Integer(12));\n\t\tassertEquals(c.getClassification().get(\"Milan\"),new Integer(4));\n\t\tassertEquals(c.getClassification().get(\"Napoli\"),new Integer(11));\n\t}" ] }, "content": "package a05.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;\n\n/**\n * In this exercise, a championship organized in the Italian style (or rather, similar to Italian) will be modeled, i.e., with N teams\n * (even) that play (N-1)*2 days. A team can play at home or away. So in the\n * (N-1)*2 days each team meets all the other teams 2 times, once at home and once away.\n * Once the teams are registered in a certain order, the matches of a given day are organized starting from the\n * first team (gradually descending in the list), at home, and finding (if there is one) the first team with which it has not already\n * played at home.\n * This algorithm is available in the data class Combinations---and can be adapted at will, optionally.\n * Note then, that for simplicity, unlike the normal Italian management, there is no division\n * \"first round\" and \"second round\", and therefore two teams could play the first leg and the second leg\n * both at the beginning of the championship, or both at the end.\n * Consider also the test for this purpose, and in particular: testChampionship\n *\n * Consult the documentation of the provided Match interface, which is already implemented in MatchImpl\n * (it is recommended to use this implementation).\n * Then consult the documentation of the Championship interface, which must be implemented with a class\n * ChampionshipImpl with a constructor without arguments.\n *\n * The following are considered optional for the purpose of being able to correct the exercise, but still contribute\n * to achieving the totality of the score:\n * - implementation of the optional test (related to the getClassification method)\n * - good design of the solution\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. Note that in this exercise it is not required to\n * manage particular cases that would normally throw exceptions.\n *\n * Remove the comment from the test code.\n */\n\npublic class Test {\n\n\tprivate static final List<String> teams = Arrays.asList(\"Juve\", \"Inter\", \"Milan\", \"Napoli\");\n\n\[email protected]\n public void testStart() {\n\t\tChampionship c = new ChampionshipImpl();\n\t\tteams.forEach(team -> c.registerTeam(team));\n\t\tc.startChampionship();\n\t\t// having not called newDay(), the pending matches have not yet been prepared\n\t\tassertTrue(c.pendingMatches().isEmpty());\n\t}\n\n\[email protected]\n public void testFirstDay() {\n\t\tChampionshipImpl c = new ChampionshipImpl();\n\t\tteams.forEach(team -> c.registerTeam(team)); // \"Juve\", \"Inter\", \"Milan\", \"Napoli\"\n\t\tc.startChampionship();\n\t\tc.newDay();\n\t\tassertEquals(c.pendingMatches().size(),2);\n\t\t// it starts from Juve, which therefore plays with the second in order, Inter\n\t\tassertTrue(c.pendingMatches().contains(new MatchImpl(\"Juve\",\"Inter\")));\n\t\t// Inter is already assigned, so we continue with Milan at home, which therefore plays with Napoli\n\t\tassertTrue(c.pendingMatches().contains(new MatchImpl(\"Milan\",\"Napoli\")));\n\t}\n\n\[email protected]\n public void testGames() {\n\t\tChampionshipImpl c = new ChampionshipImpl();\n\t\tteams.forEach(team -> c.registerTeam(team)); // \"Juve\", \"Inter\", \"Milan\", \"Napoli\"\n\t\tc.startChampionship();\n\t\tc.newDay();\n\t\tassertEquals(c.pendingMatches().size(),2);\n\t\tc.matchPlay(new MatchImpl(\"Juve\",\"Inter\"), 0, 2); // Inter wins 2-0\n\t\tassertEquals(c.pendingMatches().size(),1);\n\t\tc.matchPlay(new MatchImpl(\"Milan\",\"Napoli\"), 1, 1); // draw 1-1\n\t\tassertEquals(c.pendingMatches().size(),0); // note that there are no pending matches now, until the next newDay\n\t}\n\n\[email protected]\n public void testNewDay() {\n\t\tChampionshipImpl c = new ChampionshipImpl();\n\t\tteams.forEach(team -> c.registerTeam(team)); // \"Juve\", \"Inter\", \"Milan\", \"Napoli\"\n\t\tc.startChampionship();\n\t\tc.newDay();\n\t\tc.matchPlay(new MatchImpl(\"Juve\",\"Inter\"), 0, 2);\n\t\tc.matchPlay(new MatchImpl(\"Milan\",\"Napoli\"), 1, 1);\n\t\tassertEquals(c.pendingMatches().size(),0);\n\t\t// I start the second day\n\t\tc.newDay();\n\t\tassertEquals(c.pendingMatches().size(),2);\n\t\t// it always starts from Juve at home: the next possible is Milan\n\t\tassertTrue(c.pendingMatches().contains(new MatchImpl(\"Juve\",\"Milan\")));\n\t\t// the next to consider is Inter, and only Napoli remains\n\t\tassertTrue(c.pendingMatches().contains(new MatchImpl(\"Inter\",\"Napoli\")));\n\t}\n\n\[email protected]\n public void testChampionship() {\n\t\tChampionshipImpl c = new ChampionshipImpl();\n\t\tteams.forEach(team -> c.registerTeam(team)); // \"Juve\", \"Inter\", \"Milan\", \"Napoli\"\n\t\tc.startChampionship();\n\t\t// list all 6 days ( (4-1)*2 )\n\t\tc.newDay();\n\t\tassertTrue(c.pendingMatches().contains(new MatchImpl(\"Juve\",\"Inter\")));\n\t\tassertTrue(c.pendingMatches().contains(new MatchImpl(\"Milan\",\"Napoli\")));\n\t\tc.matchPlay(new MatchImpl(\"Juve\",\"Inter\"), 0, 2);\n\t\tc.matchPlay(new MatchImpl(\"Milan\",\"Napoli\"), 1, 1);\n\t\tc.newDay();\n\t\tassertTrue(c.pendingMatches().contains(new MatchImpl(\"Juve\",\"Milan\")));\n\t\tassertTrue(c.pendingMatches().contains(new MatchImpl(\"Inter\",\"Napoli\")));\n\t\tc.matchPlay(new MatchImpl(\"Juve\",\"Milan\"), 0, 0);\n\t\tc.matchPlay(new MatchImpl(\"Inter\",\"Napoli\"), 2, 1);\n\t\tc.newDay();\n\t\tassertTrue(c.pendingMatches().contains(new MatchImpl(\"Juve\",\"Napoli\")));\n\t\tassertTrue(c.pendingMatches().contains(new MatchImpl(\"Inter\",\"Milan\")));\n\t\tc.matchPlay(new MatchImpl(\"Juve\",\"Napoli\"), 0, 1);\n\t\tc.matchPlay(new MatchImpl(\"Inter\",\"Milan\"), 3, 0);\n\t\tc.newDay();\n\t\tassertTrue(c.pendingMatches().contains(new MatchImpl(\"Inter\",\"Juve\")));\n\t\tassertTrue(c.pendingMatches().contains(new MatchImpl(\"Napoli\",\"Milan\")));\n\t\tc.matchPlay(new MatchImpl(\"Inter\",\"Juve\"), 0, 2);\n\t\tc.matchPlay(new MatchImpl(\"Napoli\",\"Milan\"), 1, 1);\n\t\tc.newDay();\n\t\tassertTrue(c.pendingMatches().contains(new MatchImpl(\"Milan\",\"Juve\")));\n\t\tassertTrue(c.pendingMatches().contains(new MatchImpl(\"Napoli\",\"Inter\")));\n\t\tc.matchPlay(new MatchImpl(\"Milan\",\"Juve\"), 0, 0);\n\t\tc.matchPlay(new MatchImpl(\"Napoli\",\"Inter\"), 2, 1);\n\t\tc.newDay();\n\t\tassertTrue(c.pendingMatches().contains(new MatchImpl(\"Milan\",\"Inter\")));\n\t\tassertTrue(c.pendingMatches().contains(new MatchImpl(\"Napoli\",\"Juve\")));\n\t\tc.matchPlay(new MatchImpl(\"Milan\",\"Inter\"), 0, 1);\n\t\tc.matchPlay(new MatchImpl(\"Napoli\",\"Juve\"), 3, 0);\n\t}\n\n\[email protected]\n public void testChampionshipOver() {\n\t\tChampionshipImpl c = new ChampionshipImpl();\n\t\tteams.forEach(team -> c.registerTeam(team)); // \"Juve\", \"Inter\", \"Milan\", \"Napoli\"\n\t\tc.startChampionship();\n\t\tc.newDay();\n\t\tc.matchPlay(new MatchImpl(\"Juve\",\"Inter\"), 0, 2);\n\t\tc.matchPlay(new MatchImpl(\"Milan\",\"Napoli\"), 1, 1);\n\t\tc.newDay();\n\t\tc.matchPlay(new MatchImpl(\"Juve\",\"Milan\"), 0, 0);\n\t\tc.matchPlay(new MatchImpl(\"Inter\",\"Napoli\"), 2, 1);\n\t\tc.newDay();\n\t\tc.matchPlay(new MatchImpl(\"Juve\",\"Napoli\"), 0, 1);\n\t\tc.matchPlay(new MatchImpl(\"Inter\",\"Milan\"), 3, 0);\n\t\tc.newDay();\n\t\tc.matchPlay(new MatchImpl(\"Inter\",\"Juve\"), 0, 2);\n\t\tc.matchPlay(new MatchImpl(\"Napoli\",\"Milan\"), 1, 1);\n\t\tc.newDay();\n\t\tc.matchPlay(new MatchImpl(\"Milan\",\"Juve\"), 0, 0);\n\t\tc.matchPlay(new MatchImpl(\"Napoli\",\"Inter\"), 2, 1);\n\t\tc.newDay();\n\t\tassertFalse(c.championshipOver());\n\t\tc.matchPlay(new MatchImpl(\"Milan\",\"Inter\"), 0, 1);\n\t\tc.matchPlay(new MatchImpl(\"Napoli\",\"Juve\"), 3, 0);\n\t\tassertTrue(c.championshipOver());\n\t}\n\n\[email protected]\n public void optionalTestClassification() {\n\t\tChampionshipImpl c = new ChampionshipImpl();\n\t\tteams.forEach(team -> c.registerTeam(team));\n\t\tc.startChampionship();\n\t\tc.newDay();\n\t\t// standings at the beginning\n\t\tassertEquals(c.getClassification().get(\"Juve\"),new Integer(0));\n\t\tassertEquals(c.getClassification().get(\"Inter\"),new Integer(0));\n\t\tassertEquals(c.getClassification().get(\"Milan\"),new Integer(0));\n\t\tassertEquals(c.getClassification().get(\"Napoli\"),new Integer(0));\n\t\tc.matchPlay(new MatchImpl(\"Juve\",\"Inter\"), 0, 2);\n\t\tc.matchPlay(new MatchImpl(\"Milan\",\"Napoli\"), 1, 1);\n\t\tc.newDay();\n\t\t// standings after one day\n\t\tassertEquals(c.getClassification().get(\"Juve\"),new Integer(0));\n\t\tassertEquals(c.getClassification().get(\"Inter\"),new Integer(3));\n\t\tassertEquals(c.getClassification().get(\"Milan\"),new Integer(1));\n\t\tassertEquals(c.getClassification().get(\"Napoli\"),new Integer(1));\n\t\tc.matchPlay(new MatchImpl(\"Juve\",\"Milan\"), 0, 0);\n\t\tc.matchPlay(new MatchImpl(\"Inter\",\"Napoli\"), 2, 1);\n\t\tc.newDay();\n\t\tc.matchPlay(new MatchImpl(\"Juve\",\"Napoli\"), 0, 1);\n\t\tc.matchPlay(new MatchImpl(\"Inter\",\"Milan\"), 3, 0);\n\t\tc.newDay();\n\t\tc.matchPlay(new MatchImpl(\"Inter\",\"Juve\"), 0, 2);\n\t\tc.matchPlay(new MatchImpl(\"Napoli\",\"Milan\"), 1, 1);\n\t\tc.newDay();\n\t\tc.matchPlay(new MatchImpl(\"Milan\",\"Juve\"), 0, 0);\n\t\tc.matchPlay(new MatchImpl(\"Napoli\",\"Inter\"), 2, 1);\n\t\tc.newDay();\n\t\tassertFalse(c.championshipOver());\n\t\tc.matchPlay(new MatchImpl(\"Milan\",\"Inter\"), 0, 1);\n\t\tc.matchPlay(new MatchImpl(\"Napoli\",\"Juve\"), 3, 0);\n\t\tassertTrue(c.championshipOver());\n\t\t// final standings\n\t\tassertEquals(c.getClassification().get(\"Juve\"),new Integer(5));\n\t\tassertEquals(c.getClassification().get(\"Inter\"),new Integer(12));\n\t\tassertEquals(c.getClassification().get(\"Milan\"),new Integer(4));\n\t\tassertEquals(c.getClassification().get(\"Napoli\"),new Integer(11));\n\t}\n}", "filename": "Test.java" }
2017
a03b
[ { "content": "package a03b.sol1;\n\nimport java.util.*;\n\n\npublic interface ExamsManagement {\n\t\n\t\n\tvoid createStudent(int studentId, String name);\n\t\n\t\n\tvoid registerLabEvaluation(int studentId, int evaluation, int exam);\n\t\n\t\n\tvoid registerProjectEvaluation(int studentId, int evaluation, String project);\n\t\n\t\n\tOptional<Integer> finalEvaluation(int studentId);\n\t\n\t\n\tMap<String,Integer> labExamStudentToEvaluation(int exam);\n\t\n\t\n\tMap<String,Integer> allLabExamStudentToFinalEvaluation();\n\t\n\t\n\tMap<String,Integer> projectEvaluation(String project);\n\n}", "filename": "ExamsManagement.java" }, { "content": "package a03b.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 a03b.sol1;\n\nimport java.util.*;\nimport java.util.function.Predicate;\nimport java.util.stream.Collectors;\n\npublic class ExamsManagementImpl implements ExamsManagement {\n\t\n\tprivate Set<Student> students = new HashSet<>();\n\t\n\tprivate static <T> T searchInSet(Set<T> set, Predicate<T> predicate) {\n\t\treturn set.stream().filter(predicate).findAny().get();\n\t}\n\t\n\tprivate Student studentById(int studentId) {\n\t\treturn searchInSet(students, e -> e.getId()==studentId);\n\t}\n\t\n\tprivate boolean studentExists(int studentId) {\n\t\treturn this.students.stream().anyMatch(e->e.getId()==studentId);\n\t}\n\t\n\t\n\tprivate void check(boolean supplier) {\n\t\tif (!supplier) {\n\t\t\tthrow new IllegalStateException();\n\t\t}\n\t}\n\n\t@Override\n\tpublic void createStudent(int studentId, String name) {\n\t\tcheck(!studentExists(studentId));\n\t\tthis.students.add(new StudentImpl(studentId,name));\t\n\t}\n\n\t@Override\n\tpublic void registerLabEvaluation(int studentId, int evaluation, int exam) {\n\t\tcheck(studentExists(studentId));\n\t\tcheck(!this.studentById(studentId).labEvaluations().containsKey(exam));\n\t\tthis.studentById(studentId).addLabEvaluation(exam, evaluation);\n\t}\n\n\t@Override\n\tpublic void registerProjectEvaluation(int studentId, int evaluation, String projectName) {\n\t\tcheck(studentExists(studentId));\n\t\tfinal Student student = this.studentById(studentId); \n\t\tcheck(!student.getProjectName().isPresent());\n\t\tstudent.setProject(projectName, evaluation);\t\t\n\t}\n\n\t@Override\n\tpublic Optional<Integer> finalEvaluation(int studentId) {\n\t\tcheck(studentExists(studentId));\n\t\tfinal Student student = studentById(studentId);\n\t\tif (student.lastLabEvaluation().isPresent() && student.getProjectEvaluation().isPresent()) {\n\t\t\tint v1 = student.lastLabEvaluation().get();\n\t\t\tint v2 = student.getProjectEvaluation().get();\n\t\t\treturn Optional.of((int)Math.round(Math.max(v1, v2)*0.6 + Math.min(v1, v2)*0.4));\n\t\t} \n\t\treturn Optional.empty();\n\t}\n\n\t@Override\n\tpublic Map<String, Integer> labExamStudentToEvaluation(int exam) {\n\t\treturn this.students\n\t\t\t\t .stream()\n\t\t\t\t .filter(s->s.labEvaluations().containsKey(exam))\n\t\t\t\t .collect(Collectors.toMap(Student::getName, s->s.labEvaluations().get(exam)));\n\t}\n\n\t@Override\n\tpublic Map<String, Integer> allLabExamStudentToFinalEvaluation() {\n\t\treturn this.students\n\t\t\t\t .stream()\n\t\t\t\t .filter(s->finalEvaluation(s.getId()).isPresent())\n\t\t\t\t .collect(Collectors.toMap(Student::getName, s->finalEvaluation(s.getId()).get()));\n\t}\n\n\t@Override\n\tpublic Map<String, Integer> projectEvaluation(String project) {\n\t\treturn this.students\n\t\t\t\t .stream()\n\t\t\t\t .filter(s->s.getProjectName().isPresent())\n\t\t\t\t .filter(s->s.getProjectName().get().equals(project))\n\t\t\t\t .collect(Collectors.toMap(Student::getName, s->s.getProjectEvaluation().get()));\n\t}\n\n\n\t\n}", "filename": "ExamsManagementImpl.java" }, { "content": "package a03b.sol1;\n\nimport java.util.Map;\nimport java.util.Optional;\n\npublic interface Student {\n\n\tint getId();\n\n\tString getName();\n\n\tvoid addLabEvaluation(int exam, int evaluation);\n\n\tMap<Integer, Integer> labEvaluations();\n\n\tvoid setProject(String projectName, int evaluation);\n\n\tOptional<String> getProjectName();\n\n\tOptional<Integer> getProjectEvaluation();\n\n\tOptional<Integer> lastLabEvaluation();\n\n}", "filename": "Student.java" }, { "content": "package a03b.sol1;\n\nimport java.util.*;\n\npublic class StudentImpl implements Student {\n\n\tprivate final int id;\n\tprivate final String name;\n\tprivate final Map<Integer,Integer> labEvaluations = new HashMap<>();\n\tprivate Optional<Integer> projectEvaluation = Optional.empty();\n\tprivate Optional<String> projectName = Optional.empty();\n\n\tpublic StudentImpl(int id, String name) {\n\t\tsuper();\n\t\tthis.id = id;\n\t\tthis.name = name;\n\t}\n\n\t/* (non-Javadoc)\n\t * @see a03b.sol1.Student#getId()\n\t */\n\t@Override\n\tpublic int getId() {\n\t\treturn id;\n\t}\n\n\t/* (non-Javadoc)\n\t * @see a03b.sol1.Student#getName()\n\t */\n\t@Override\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\t\n\t/* (non-Javadoc)\n\t * @see a03b.sol1.Student#addLabEvaluation(int, int)\n\t */\n\t@Override\n\tpublic void addLabEvaluation(int exam, int evaluation) {\n\t\tthis.labEvaluations.put(exam, evaluation);\n\t}\n\t\n\t/* (non-Javadoc)\n\t * @see a03b.sol1.Student#labEvaluations()\n\t */\n\t@Override\n\tpublic Map<Integer,Integer> labEvaluations(){\n\t\treturn Collections.unmodifiableMap(labEvaluations);\n\t}\n\t\n\t/* (non-Javadoc)\n\t * @see a03b.sol1.Student#setProject(java.lang.String, int)\n\t */\n\t@Override\n\tpublic void setProject(String projectName, int evaluation) {\n\t\tthis.projectEvaluation = Optional.of(evaluation);\n\t\tthis.projectName = Optional.of(projectName);\n\t}\n\t\n\t/* (non-Javadoc)\n\t * @see a03b.sol1.Student#getProjectName()\n\t */\n\t@Override\n\tpublic Optional<String> getProjectName(){\n\t\treturn this.projectName;\n\t}\n\t\n\t/* (non-Javadoc)\n\t * @see a03b.sol1.Student#getProjectEvaluation()\n\t */\n\t@Override\n\tpublic Optional<Integer> getProjectEvaluation(){\n\t\treturn this.projectEvaluation;\n\t}\n\t\n\t/* (non-Javadoc)\n\t * @see a03b.sol1.Student#lastLabEvaluation()\n\t */\n\t@Override\n\tpublic Optional<Integer> lastLabEvaluation(){\n\t\treturn this.labEvaluations.entrySet().stream().max((e1,e2)->e1.getKey()-e2.getKey()).map(e->e.getValue());\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 + id;\n\t\tresult = prime * result + ((name == null) ? 0 : name.hashCode());\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj) {\n\t\t\treturn true;\n\t\t}\n\t\tif (obj == null) {\n\t\t\treturn false;\n\t\t}\n\t\tif (!(obj instanceof StudentImpl)) {\n\t\t\treturn false;\n\t\t}\n\t\tStudentImpl other = (StudentImpl) obj;\n\t\tif (id != other.id) {\n\t\t\treturn false;\n\t\t}\n\t\tif (name == null) {\n\t\t\tif (other.name != null) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t} else if (!name.equals(other.name)) {\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"StudentImpl [id=\" + id + \", name=\" + name + \", labEvaluations=\" + labEvaluations + \", projectEvaluation=\"\n\t\t\t\t+ projectEvaluation + \", projectName=\" + projectName + \"]\";\n\t}\n\t\n\t\n}", "filename": "StudentImpl.java" } ]
{ "components": { "imports": "package a03b.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;", "private_init": "\t/*\n\t * Implement the ExamsManagement interface provided through an ExamsManagementImpl class with a constructor without arguments.\n\t * Realizes a concept of grade management for this OOP course.\n\t * Provides functionality for:\n\t * - creating students \n\t * - registering student grades for various lab sessions (sessions numbered with incremental id);\n\t * - registering the project grade (defined by a name)\n\t * - calculating the final grade as a weighted average (60% to the best - 40% to the worst), between the lab grade (the last\n\t * achieved) and the project grade\n\t * - to obtain historical information\n\t * \n\t * Note that tests with the @org.junit.Test(expected = ...) annotation only pass if the exception indicated in the ... is thrown.\n\t * Note that tests with the @org.junit.Test annotation pass if no exception is thrown\n\t * Note that methods with the @org.junit.Before annotation are always executed before each test is executed, and are used\n\t * to prepare a \"new\" (always the same) configuration before running a test.\n\t * \n\t * The following are considered optional for the purposes of being able to correct the exercise, but still contribute to achieving \n\t * the totality of the score:\n\t * - implementation of tests called optionalTestXYZ (relating to the projectEvaluation method and exception handling) \n\t * - the good design of the solution, in particular with minimization of repetitions\n\t * \n\t */\n\t\n\tprivate ExamsManagement data;\n\t\n\[email protected]\n\tpublic void createData() {\n\t\tthis.data = new ExamsManagementImpl();\n\t\tdata.createStudent(10, \"Mario\");\n\t\tdata.createStudent(20, \"Lucia\");\n\t\tdata.createStudent(30, \"Carlo\");\n\t\tdata.createStudent(40, \"Anna\");\n\t\tdata.createStudent(50, \"Ugo\");\n\t\tdata.createStudent(60, \"Silvia\");\n\t\tdata.registerLabEvaluation(10, 30, 1);\n\t\tdata.registerLabEvaluation(20, 18, 1);\n\t\tdata.registerLabEvaluation(30, 25, 1);\n\t\tdata.registerLabEvaluation(40, 16, 1);\n\t\t\n\t\tdata.registerProjectEvaluation(20, 30, \"Pacman\");\n\t\tdata.registerProjectEvaluation(40, 29, \"Pacman\");\n\t\t\n\t\tdata.registerLabEvaluation(20, 24, 2);\n\t\tdata.registerLabEvaluation(40, 15, 2);\n\t\t\t\t\n\t\tdata.registerLabEvaluation(50, 21, 3);\n\t\tdata.registerLabEvaluation(60, 21, 3);\n\t\t\n\t\tdata.registerProjectEvaluation(10, 28, \"MarioBros\");\n\t\tdata.registerProjectEvaluation(30, 28, \"MarioBros\");\n\t\t\n\t}", "test_functions": [ "\[email protected]\n\tpublic void testFinalEvaluation() {\n\t\tassertEquals(data.finalEvaluation(10),Optional.of(29));\n\t\tassertEquals(data.finalEvaluation(20),Optional.of(28));\n\t\tassertEquals(data.finalEvaluation(30),Optional.of(27));\n\t\tassertEquals(data.finalEvaluation(40),Optional.of(23));\n\t\tassertEquals(data.finalEvaluation(50),Optional.empty());\n\t\tassertEquals(data.finalEvaluation(60),Optional.empty());\n\t}", "\[email protected]\n\tpublic void testLabExamStudentToEvaluation() {\n\t\tassertEquals(data.labExamStudentToEvaluation(1).size(),4);\n\t\tassertEquals(data.labExamStudentToEvaluation(1).get(\"Mario\").intValue(),30);\n\t\tassertEquals(data.labExamStudentToEvaluation(1).get(\"Lucia\").intValue(),18);\n\t\tassertEquals(data.labExamStudentToEvaluation(1).get(\"Carlo\").intValue(),25);\n\t\tassertEquals(data.labExamStudentToEvaluation(1).get(\"Anna\").intValue(),16);\n\t\tassertEquals(data.labExamStudentToEvaluation(2).size(),2);\n\t\tassertEquals(data.labExamStudentToEvaluation(2).get(\"Lucia\").intValue(),24);\n\t\tassertEquals(data.labExamStudentToEvaluation(2).get(\"Anna\").intValue(),15);\n\t}", "\[email protected]\n\tpublic void testAllLabExamStudentToFinalEvaluation() {\n\t\tassertEquals(data.allLabExamStudentToFinalEvaluation().size(),4);\n\t\tassertEquals(data.allLabExamStudentToFinalEvaluation().get(\"Mario\").intValue(),29);\n\t\tassertEquals(data.allLabExamStudentToFinalEvaluation().get(\"Lucia\").intValue(),28);\n\t\tassertEquals(data.allLabExamStudentToFinalEvaluation().get(\"Carlo\").intValue(),27);\n\t\tassertEquals(data.allLabExamStudentToFinalEvaluation().get(\"Anna\").intValue(),23);\t\n\t}", "\[email protected]\n\tpublic void optionalTestProjectEvaluation() {\n\t\tassertEquals(data.projectEvaluation(\"MarioBros\").get(\"Mario\").intValue(),28);\n\t\tassertEquals(data.projectEvaluation(\"MarioBros\").get(\"Carlo\").intValue(),28);\n\t\tassertEquals(data.projectEvaluation(\"Pacman\").get(\"Lucia\").intValue(),30);\n\t\tassertEquals(data.projectEvaluation(\"Pacman\").get(\"Anna\").intValue(),29);\n\t\t\n\t}" ] }, "content": "package a03b.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;\n\npublic class Test {\n\t\n\t/*\n\t * Implement the ExamsManagement interface provided through an ExamsManagementImpl class with a constructor without arguments.\n\t * Realizes a concept of grade management for this OOP course.\n\t * Provides functionality for:\n\t * - creating students \n\t * - registering student grades for various lab sessions (sessions numbered with incremental id);\n\t * - registering the project grade (defined by a name)\n\t * - calculating the final grade as a weighted average (60% to the best - 40% to the worst), between the lab grade (the last\n\t * achieved) and the project grade\n\t * - to obtain historical information\n\t * \n\t * Note that tests with the @org.junit.Test(expected = ...) annotation only pass if the exception indicated in the ... is thrown.\n\t * Note that tests with the @org.junit.Test annotation pass if no exception is thrown\n\t * Note that methods with the @org.junit.Before annotation are always executed before each test is executed, and are used\n\t * to prepare a \"new\" (always the same) configuration before running a test.\n\t * \n\t * The following are considered optional for the purposes of being able to correct the exercise, but still contribute to achieving \n\t * the totality of the score:\n\t * - implementation of tests called optionalTestXYZ (relating to the projectEvaluation method and exception handling) \n\t * - the good design of the solution, in particular with minimization of repetitions\n\t * \n\t */\n\t\n\tprivate ExamsManagement data;\n\t\n\[email protected]\n\tpublic void createData() {\n\t\tthis.data = new ExamsManagementImpl();\n\t\tdata.createStudent(10, \"Mario\");\n\t\tdata.createStudent(20, \"Lucia\");\n\t\tdata.createStudent(30, \"Carlo\");\n\t\tdata.createStudent(40, \"Anna\");\n\t\tdata.createStudent(50, \"Ugo\");\n\t\tdata.createStudent(60, \"Silvia\");\n\t\tdata.registerLabEvaluation(10, 30, 1);\n\t\tdata.registerLabEvaluation(20, 18, 1);\n\t\tdata.registerLabEvaluation(30, 25, 1);\n\t\tdata.registerLabEvaluation(40, 16, 1);\n\t\t\n\t\tdata.registerProjectEvaluation(20, 30, \"Pacman\");\n\t\tdata.registerProjectEvaluation(40, 29, \"Pacman\");\n\t\t\n\t\tdata.registerLabEvaluation(20, 24, 2);\n\t\tdata.registerLabEvaluation(40, 15, 2);\n\t\t\t\t\n\t\tdata.registerLabEvaluation(50, 21, 3);\n\t\tdata.registerLabEvaluation(60, 21, 3);\n\t\t\n\t\tdata.registerProjectEvaluation(10, 28, \"MarioBros\");\n\t\tdata.registerProjectEvaluation(30, 28, \"MarioBros\");\n\t\t\n\t}\n\t\n\[email protected]\n\tpublic void testFinalEvaluation() {\n\t\tassertEquals(data.finalEvaluation(10),Optional.of(29));\n\t\tassertEquals(data.finalEvaluation(20),Optional.of(28));\n\t\tassertEquals(data.finalEvaluation(30),Optional.of(27));\n\t\tassertEquals(data.finalEvaluation(40),Optional.of(23));\n\t\tassertEquals(data.finalEvaluation(50),Optional.empty());\n\t\tassertEquals(data.finalEvaluation(60),Optional.empty());\n\t}\n\t\n\t\n\[email protected]\n\tpublic void testLabExamStudentToEvaluation() {\n\t\tassertEquals(data.labExamStudentToEvaluation(1).size(),4);\n\t\tassertEquals(data.labExamStudentToEvaluation(1).get(\"Mario\").intValue(),30);\n\t\tassertEquals(data.labExamStudentToEvaluation(1).get(\"Lucia\").intValue(),18);\n\t\tassertEquals(data.labExamStudentToEvaluation(1).get(\"Carlo\").intValue(),25);\n\t\tassertEquals(data.labExamStudentToEvaluation(1).get(\"Anna\").intValue(),16);\n\t\tassertEquals(data.labExamStudentToEvaluation(2).size(),2);\n\t\tassertEquals(data.labExamStudentToEvaluation(2).get(\"Lucia\").intValue(),24);\n\t\tassertEquals(data.labExamStudentToEvaluation(2).get(\"Anna\").intValue(),15);\n\t}\n\t\n\[email protected]\n\tpublic void testAllLabExamStudentToFinalEvaluation() {\n\t\tassertEquals(data.allLabExamStudentToFinalEvaluation().size(),4);\n\t\tassertEquals(data.allLabExamStudentToFinalEvaluation().get(\"Mario\").intValue(),29);\n\t\tassertEquals(data.allLabExamStudentToFinalEvaluation().get(\"Lucia\").intValue(),28);\n\t\tassertEquals(data.allLabExamStudentToFinalEvaluation().get(\"Carlo\").intValue(),27);\n\t\tassertEquals(data.allLabExamStudentToFinalEvaluation().get(\"Anna\").intValue(),23);\t\n\t}\n\t\n\[email protected]\n\tpublic void optionalTestProjectEvaluation() {\n\t\tassertEquals(data.projectEvaluation(\"MarioBros\").get(\"Mario\").intValue(),28);\n\t\tassertEquals(data.projectEvaluation(\"MarioBros\").get(\"Carlo\").intValue(),28);\n\t\tassertEquals(data.projectEvaluation(\"Pacman\").get(\"Lucia\").intValue(),30);\n\t\tassertEquals(data.projectEvaluation(\"Pacman\").get(\"Anna\").intValue(),29);\n\t\t\n\t}\n\t\n\t\n\[email protected](expected = IllegalStateException.class)\n\tpublic void optionalTestStudentDoesNotExist() {\n\t\tdata.registerLabEvaluation(70, 20, 1);\n\t}\n\t\n\[email protected](expected = IllegalStateException.class)\n\tpublic void optionalTestStudentShouldNotExist() {\n\t\tdata.createStudent(10, \"Pippo\");\n\t}\n\t\n\[email protected](expected = IllegalStateException.class)\n\tpublic void optionalTestCantRegisterProjectsTwice() {\n\t\tdata.registerProjectEvaluation(40, 10, \"Arkanoid\");\n\t}\n\t\n\[email protected](expected = IllegalStateException.class)\n\tpublic void testCantRegisterSameLabTwice() {\n\t\tdata.registerLabEvaluation(60, 18, 3);\n\t}\n}", "filename": "Test.java" }
2017
a01b
[ { "content": "package a01b.sol1;\n\n\npublic interface Event<X> {\n\t\n\tint getTime();\n\t\n\tX getValue();\n}", "filename": "Event.java" }, { "content": "package a01b.sol1;\n\nimport java.util.function.Supplier;\n\n\npublic interface TraceFactory {\n\n\t\n\t<X> Trace<X> fromSuppliers(Supplier<Integer> sdeltaTime, Supplier<X> svalue, int size);\n\t\n\t\n\t<X> Trace<X> constant(Supplier<Integer> sdeltaTime, X value, int size);\n\t\n\t\n\t<X> Trace<X> discrete(Supplier<X> svalue, int size);\t\n}", "filename": "TraceFactory.java" }, { "content": "package a01b.sol1;\n\nimport java.util.Iterator;\nimport java.util.Optional;\n\n\npublic interface Trace<X> {\n\n\t\n\tOptional<Event<X>> nextEvent();\n\t\n\t\n\tIterator<Event<X>> iterator();\n\t\n\t\n\t\n\tvoid skipAfter(int time);\n\t\n\t\n\tTrace<X> combineWith(Trace<X> trace);\n\t\n\t\n\tTrace<X> dropValues(X value);\n}", "filename": "Trace.java" }, { "content": "package a01b.sol1;\n\npublic class EventImpl<X> implements Event<X> {\n\t\n\tfinal private int time;\n\tfinal private X value;\n\t\n\tpublic EventImpl(int time, X value) {\n\t\tsuper();\n\t\tthis.time = time;\n\t\tthis.value = value;\n\t}\n\n\t@Override\n\tpublic int getTime() {\n\t\treturn this.time;\n\t}\n\n\t@Override\n\tpublic X getValue() {\n\t\treturn this.value;\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 + (int) (time ^ (time >>> 32));\n\t\tresult = prime * result + ((value == null) ? 0 : value.hashCode());\n\t\treturn result;\n\t}\n\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\tEventImpl other = (EventImpl) obj;\n\t\tif (time != other.time)\n\t\t\treturn false;\n\t\tif (value == null) {\n\t\t\tif (other.value != null)\n\t\t\t\treturn false;\n\t\t} else if (!value.equals(other.value))\n\t\t\treturn false;\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"[\" + time + \":\" + value + \"]\";\n\t}\n\t\n}", "filename": "EventImpl.java" }, { "content": "package a01b.sol1;\n\npublic class Pair<X,Y> {\n\t\n\tprivate final X fst;\n\tprivate final Y snd;\n\tpublic Pair(X fst, Y snd) {\n\t\tsuper();\n\t\tthis.fst = fst;\n\t\tthis.snd = snd;\n\t}\n\tpublic X getFst() {\n\t\treturn fst;\n\t}\n\tpublic Y getSnd() {\n\t\treturn snd;\n\t}\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = 1;\n\t\tresult = prime * result + ((fst == null) ? 0 : fst.hashCode());\n\t\tresult = prime * result + ((snd == null) ? 0 : snd.hashCode());\n\t\treturn result;\n\t}\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 (!(obj instanceof Pair))\n\t\t\treturn false;\n\t\tPair other = (Pair) obj;\n\t\tif (fst == null) {\n\t\t\tif (other.fst != null)\n\t\t\t\treturn false;\n\t\t} else if (!fst.equals(other.fst))\n\t\t\treturn false;\n\t\tif (snd == null) {\n\t\t\tif (other.snd != null)\n\t\t\t\treturn false;\n\t\t} else if (!snd.equals(other.snd))\n\t\t\treturn false;\n\t\treturn true;\n\t}\n\t@Override\n\tpublic String toString() {\n\t\treturn \"[\" + fst + \";\" + snd + \"]\";\n\t}\n\t\n\t\n\n}", "filename": "Pair.java" } ]
[ { "content": "package a01b.sol1;\n\nimport java.util.function.Supplier;\nimport java.util.stream.IntStream;\n\npublic class TraceFactoryImpl implements TraceFactory {\n\n\t@Override\n\tpublic <X> Trace<X> fromSuppliers(Supplier<Integer> deltaTime, Supplier<X> value, int size) {\n\t\treturn new TraceImpl<>(IntStream.iterate(0,l -> l + deltaTime.get())\n \t\t\t\t\t\t .<Event<X>>mapToObj(l -> new EventImpl<X>(l,value.get()))\n \t\t\t\t\t\t .limit(size)\n \t\t\t\t\t\t .iterator());\n\t}\n\n\t@Override\n\tpublic <X> Trace<X> constant(Supplier<Integer> deltaTime, X value, int size) {\n\t\treturn fromSuppliers(deltaTime, ()->value, size);\n\t}\n\n\t@Override\n\tpublic <X> Trace<X> discrete(Supplier<X> value, int size) {\n\t\treturn fromSuppliers(()->1, value, size);\n\t}\n\n}", "filename": "TraceFactoryImpl.java" }, { "content": "package a01b.sol1;\n\nimport java.util.Iterator;\nimport java.util.Optional;\n\npublic class TraceImpl<X> implements Trace<X> {\n\t\n\tprivate final Iterator<Event<X>> it;\n\t\n\t// package-private\n\tTraceImpl(Iterator<Event<X>> it){\n\t\tthis.it = it;\n\t}\n\t\n\t@Override\n\tpublic Optional<Event<X>> nextEvent() {\n\t\treturn it.hasNext() ? Optional.of(it.next()) : Optional.empty();\n\t}\n\n\t@Override\n\tpublic void skipAfter(int time) {\n\t\twhile (it.hasNext() && it.next().getTime()<time) {}\n\t}\n\n\t@Override\n\tpublic Trace<X> combineWith(Trace<X> trace) {\n\t\treturn new TraceImpl<X>(new Iterator<Event<X>>() {\n\t\t\tOptional<Event<X>> e1 = nextEvent();\n\t\t\tOptional<Event<X>> e2 = trace.nextEvent();\n\t\t\t@Override\n\t\t\tpublic boolean hasNext() {\n\t\t\t\treturn e1.isPresent() || e2.isPresent();\n\t\t\t}\n\t\t\t@Override\n\t\t\tpublic Event<X> next() {\n\t\t\t\tEvent<X> e;\n\t\t\t\tif (!e2.isPresent() || e1.isPresent() && e1.get().getTime()<e2.get().getTime()) {\n\t\t\t\t\te = e1.get();\n\t\t\t\t\te1 = nextEvent();\n\t\t\t\t} else {\n\t\t\t\t\te = e2.get();\n\t\t\t\t\te2 = trace.nextEvent();\n\t\t\t\t}\n\t\t\t\treturn e;\n\t\t\t}\n\t\t});\n\t}\n\n\t@Override\n\tpublic Trace<X> dropValues(X value) {\n\t\treturn new TraceImpl<X>(new Iterator<Event<X>>() {\n\t\t\tOptional<Event<X>> e = nextValid();\n\t\t\tprivate Optional<Event<X>> nextValid(){\n\t\t\t\tOptional<Event<X>> e2 = nextEvent();\n\t\t\t\treturn e2.isPresent() && e2.get().getValue().equals(value) ? nextValid() : e2; \n\t\t\t}\n\t\t\t@Override\n\t\t\tpublic boolean hasNext() {\n\t\t\t\treturn e.isPresent();\n\t\t\t}\n\t\t\t@Override\n\t\t\tpublic Event<X> next() {\n\t\t\t\tEvent<X> e2 = e.get();\n\t\t\t\te = nextValid();\n\t\t\t\treturn e2;\n\t\t\t}\n\t\t});\n\t}\n\n\t@Override\n\tpublic Iterator<Event<X>> iterator() {\n\t\treturn this.it;\n\t}\n\t\t\n}", "filename": "TraceImpl.java" } ]
{ "components": { "imports": "package a01b.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;\n\n/**\n * Please consult the documentation of the provided interfaces/class:\n * - Event<X> models a temporal event with value X\n * - EventImpl<X> is its trivial and usable implementation\n * - Trace<X> models a finite temporal source of events of type X\n * - TraceFactory models a factory for various types of trace\n * \n * Implement TraceFactory through a TraceFactoryImpl class with a constructor without arguments,\n * so that it passes all the tests below.\n * \n * The following are considered optional for the possibility of correcting the exercise, but still contribute to reaching\n * the totality of the score:\n * - implementation of optional tests (related to the Trace.dropValues method)\n * - good design of the solution, in particular with minimization of repetitions\n * - the choice of a \"lazy\" implementation for the Traces (assuming that in the factories,\n * size can be very large, and therefore intermediate data structures should never be built)\n * \n * Observe carefully the following test, 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// functionality for internal purposes, which extracts times and values from a trace\n\tprivate <X> Pair<List<Integer>,List<X>> traceToPairs(Trace<X> t){\n\t\tIterator<Event<X>> it = t.iterator();\n\t\tList<Integer> times = new ArrayList<>();\n\t\tList<X> values = new ArrayList<>();\n\t\twhile (it.hasNext()) {\n\t\t\tEvent<X> e = it.next();\n\t\t\ttimes.add(e.getTime());\n\t\t\tvalues.add(e.getValue());\n\t\t}\n\t\treturn new Pair<>(times,values);\n\t}", "test_functions": [ "\[email protected]\n public void testNextEvent() {\n // Test on discrete creation\n final Trace<String> t = new TraceFactoryImpl().discrete(()->\"a\", 2); // 0:a ; 1:a\n Optional<Event<String>> e;\n e = t.nextEvent();\n assertTrue(e.isPresent() && e.get().getTime()==0 && e.get().getValue().equals(\"a\"));\n e = t.nextEvent();\n assertTrue(e.isPresent() && e.get().getTime()==1 && e.get().getValue().equals(\"a\"));\n e = t.nextEvent();\n assertFalse(e.isPresent());\n }", "\[email protected]\n public void testDiscrete() {\n // Test on discrete creation\n final Trace<String> t = new TraceFactoryImpl().discrete(()->\"a\", 5); // 0:a ; 1:a ; .. 4;a\n final Pair<List<Integer>,List<String>> p = traceToPairs(t);\n assertEquals(p.getFst(),Arrays.asList(0,1,2,3,4));\n assertEquals(p.getSnd(),Arrays.asList(\"a\",\"a\",\"a\",\"a\",\"a\"));\n }", "\[email protected]\n public void testConstant() {\n // Test on constant creation\n final Trace<String> t = new TraceFactoryImpl().constant(()->2, \"a\", 5); // 0:a ; 2:a ; 4:a ; .. ; 8:a\n final Pair<List<Integer>,List<String>> p = traceToPairs(t);\n assertEquals(p.getFst(),Arrays.asList(0,2,4,6,8));\n assertEquals(p.getSnd(),Arrays.asList(\"a\",\"a\",\"a\",\"a\",\"a\"));\n }", "\[email protected]\n public void testFromSuppliers() {\n // Test on creation from suppliers\n final Trace<String> t = new TraceFactoryImpl().fromSuppliers(()->2, ()->Math.random()>0.5?\"a\":\"b\", 5);\n // example: 0:a ; 2:b ; 4:b ; 6:b ; 8:a\n final Pair<List<Integer>,List<String>> p = traceToPairs(t);\n assertEquals(p.getFst(),Arrays.asList(0,2,4,6,8));\n assertEquals(p.getSnd().size(),5);\n assertTrue(p.getSnd().get(0).equals(\"a\") || p.getSnd().get(0).equals(\"b\"));\n assertTrue(p.getSnd().get(1).equals(\"a\") || p.getSnd().get(1).equals(\"b\"));\n assertTrue(p.getSnd().get(4).equals(\"a\") || p.getSnd().get(4).equals(\"b\"));\n }", "\[email protected]\n public void testSkip() {\n // Test skip method\n\t\tfinal Trace<String> t = new TraceFactoryImpl().fromSuppliers(()->2, ()->\"a\", 5);\n\t\t// t represents 0:a ; 2:b ; 4:b ; 6:b ; 8:a\n t.skipAfter(2);\n\t\t// t represents 4:b ; 6:b ; 8:a\n final Pair<List<Integer>,List<String>> p = traceToPairs(t);\n assertEquals(p.getFst(),Arrays.asList(4,6,8));\n assertEquals(p.getSnd(),Arrays.asList(\"a\",\"a\",\"a\"));\n }", "\[email protected]\n public void testSkipOver() {\n // Test skip method\n\t\tfinal Trace<String> t = new TraceFactoryImpl().fromSuppliers(()->2, ()->\"a\", 5);\n\t\t// t represents 0:a ; 2:b ; 4:b ; 6:b ; 8:a\n t.skipAfter(10);\n\t\t// t is empty\n final Pair<List<Integer>,List<String>> p = traceToPairs(t);\n assertEquals(p.getFst().size(),0);\n assertEquals(p.getSnd().size(),0);\n }", "\[email protected]\n public void testCombine() {\n // Test combine method\n\t\tfinal Trace<String> t = new TraceFactoryImpl().fromSuppliers(()->2, ()->\"a\", 3); //t is 0:a,2:a,4:a\n\t\tt.nextEvent(); // now t is 2:a,4:a\n\t\tfinal Trace<String> t2 = new TraceFactoryImpl().fromSuppliers(()->5, ()->\"b\", 2); //t2: 0:b,5:b\n\t\tfinal Trace<String> t3 = t2.combineWith(t); // 0:b, 2:a, 4:a, 5:b \n final Pair<List<Integer>,List<String>> p = traceToPairs(t3);\n assertEquals(p.getFst(),Arrays.asList(0,2,4,5));\n assertEquals(p.getSnd(),Arrays.asList(\"b\",\"a\",\"a\",\"b\"));\n }", "\[email protected]\n public void optionalTestDropValues() {\n // Test combine method\n\t\tfinal Trace<String> t = new TraceFactoryImpl().fromSuppliers(()->2, ()->\"a\", 3); //t is 0:a,2:a,4:a\n\t\tt.nextEvent(); // now t is 2:a,4:a\n\t\tfinal Trace<String> t2 = new TraceFactoryImpl().fromSuppliers(()->5, ()->\"b\", 2); //t2: 0:b,5:b\n\t\tfinal Trace<String> t3 = t2.combineWith(t); // 0:b, 2:a, 4:a, 5:b \n final Trace<String> t4 = t3.dropValues(\"a\"); // 0:b, 5:b\n final Pair<List<Integer>,List<String>> p = traceToPairs(t4);\n assertEquals(p.getFst(),Arrays.asList(0,5));\n assertEquals(p.getSnd(),Arrays.asList(\"b\",\"b\"));\n }" ] }, "content": "package a01b.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;\n\n/**\n * Please consult the documentation of the provided interfaces/class:\n * - Event<X> models a temporal event with value X\n * - EventImpl<X> is its trivial and usable implementation\n * - Trace<X> models a finite temporal source of events of type X\n * - TraceFactory models a factory for various types of trace\n * \n * Implement TraceFactory through a TraceFactoryImpl class with a constructor without arguments,\n * so that it passes all the tests below.\n * \n * The following are considered optional for the possibility of correcting the exercise, but still contribute to reaching\n * the totality of the score:\n * - implementation of optional tests (related to the Trace.dropValues method)\n * - good design of the solution, in particular with minimization of repetitions\n * - the choice of a \"lazy\" implementation for the Traces (assuming that in the factories,\n * size can be very large, and therefore intermediate data structures should never be built)\n * \n * Observe carefully the following test, 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\t\n\t// functionality for internal purposes, which extracts times and values from a trace\n\tprivate <X> Pair<List<Integer>,List<X>> traceToPairs(Trace<X> t){\n\t\tIterator<Event<X>> it = t.iterator();\n\t\tList<Integer> times = new ArrayList<>();\n\t\tList<X> values = new ArrayList<>();\n\t\twhile (it.hasNext()) {\n\t\t\tEvent<X> e = it.next();\n\t\t\ttimes.add(e.getTime());\n\t\t\tvalues.add(e.getValue());\n\t\t}\n\t\treturn new Pair<>(times,values);\n\t} \n\t\n\[email protected]\n public void testNextEvent() {\n // Test on discrete creation\n final Trace<String> t = new TraceFactoryImpl().discrete(()->\"a\", 2); // 0:a ; 1:a\n Optional<Event<String>> e;\n e = t.nextEvent();\n assertTrue(e.isPresent() && e.get().getTime()==0 && e.get().getValue().equals(\"a\"));\n e = t.nextEvent();\n assertTrue(e.isPresent() && e.get().getTime()==1 && e.get().getValue().equals(\"a\"));\n e = t.nextEvent();\n assertFalse(e.isPresent());\n }\t\n\n\[email protected]\n public void testDiscrete() {\n // Test on discrete creation\n final Trace<String> t = new TraceFactoryImpl().discrete(()->\"a\", 5); // 0:a ; 1:a ; .. 4;a\n final Pair<List<Integer>,List<String>> p = traceToPairs(t);\n assertEquals(p.getFst(),Arrays.asList(0,1,2,3,4));\n assertEquals(p.getSnd(),Arrays.asList(\"a\",\"a\",\"a\",\"a\",\"a\"));\n }\n\t\n\[email protected]\n public void testConstant() {\n // Test on constant creation\n final Trace<String> t = new TraceFactoryImpl().constant(()->2, \"a\", 5); // 0:a ; 2:a ; 4:a ; .. ; 8:a\n final Pair<List<Integer>,List<String>> p = traceToPairs(t);\n assertEquals(p.getFst(),Arrays.asList(0,2,4,6,8));\n assertEquals(p.getSnd(),Arrays.asList(\"a\",\"a\",\"a\",\"a\",\"a\"));\n } \n\t\n\[email protected]\n public void testFromSuppliers() {\n // Test on creation from suppliers\n final Trace<String> t = new TraceFactoryImpl().fromSuppliers(()->2, ()->Math.random()>0.5?\"a\":\"b\", 5);\n // example: 0:a ; 2:b ; 4:b ; 6:b ; 8:a\n final Pair<List<Integer>,List<String>> p = traceToPairs(t);\n assertEquals(p.getFst(),Arrays.asList(0,2,4,6,8));\n assertEquals(p.getSnd().size(),5);\n assertTrue(p.getSnd().get(0).equals(\"a\") || p.getSnd().get(0).equals(\"b\"));\n assertTrue(p.getSnd().get(1).equals(\"a\") || p.getSnd().get(1).equals(\"b\"));\n assertTrue(p.getSnd().get(4).equals(\"a\") || p.getSnd().get(4).equals(\"b\"));\n }\n\t\n\[email protected]\n public void testSkip() {\n // Test skip method\n\t\tfinal Trace<String> t = new TraceFactoryImpl().fromSuppliers(()->2, ()->\"a\", 5);\n\t\t// t represents 0:a ; 2:b ; 4:b ; 6:b ; 8:a\n t.skipAfter(2);\n\t\t// t represents 4:b ; 6:b ; 8:a\n final Pair<List<Integer>,List<String>> p = traceToPairs(t);\n assertEquals(p.getFst(),Arrays.asList(4,6,8));\n assertEquals(p.getSnd(),Arrays.asList(\"a\",\"a\",\"a\"));\n }\n\t\n\[email protected]\n public void testSkipOver() {\n // Test skip method\n\t\tfinal Trace<String> t = new TraceFactoryImpl().fromSuppliers(()->2, ()->\"a\", 5);\n\t\t// t represents 0:a ; 2:b ; 4:b ; 6:b ; 8:a\n t.skipAfter(10);\n\t\t// t is empty\n final Pair<List<Integer>,List<String>> p = traceToPairs(t);\n assertEquals(p.getFst().size(),0);\n assertEquals(p.getSnd().size(),0);\n }\n\t\n\[email protected]\n public void testCombine() {\n // Test combine method\n\t\tfinal Trace<String> t = new TraceFactoryImpl().fromSuppliers(()->2, ()->\"a\", 3); //t is 0:a,2:a,4:a\n\t\tt.nextEvent(); // now t is 2:a,4:a\n\t\tfinal Trace<String> t2 = new TraceFactoryImpl().fromSuppliers(()->5, ()->\"b\", 2); //t2: 0:b,5:b\n\t\tfinal Trace<String> t3 = t2.combineWith(t); // 0:b, 2:a, 4:a, 5:b \n final Pair<List<Integer>,List<String>> p = traceToPairs(t3);\n assertEquals(p.getFst(),Arrays.asList(0,2,4,5));\n assertEquals(p.getSnd(),Arrays.asList(\"b\",\"a\",\"a\",\"b\"));\n }\n\t\n\[email protected]\n public void optionalTestDropValues() {\n // Test combine method\n\t\tfinal Trace<String> t = new TraceFactoryImpl().fromSuppliers(()->2, ()->\"a\", 3); //t is 0:a,2:a,4:a\n\t\tt.nextEvent(); // now t is 2:a,4:a\n\t\tfinal Trace<String> t2 = new TraceFactoryImpl().fromSuppliers(()->5, ()->\"b\", 2); //t2: 0:b,5:b\n\t\tfinal Trace<String> t3 = t2.combineWith(t); // 0:b, 2:a, 4:a, 5:b \n final Trace<String> t4 = t3.dropValues(\"a\"); // 0:b, 5:b\n final Pair<List<Integer>,List<String>> p = traceToPairs(t4);\n assertEquals(p.getFst(),Arrays.asList(0,5));\n assertEquals(p.getSnd(),Arrays.asList(\"b\",\"b\"));\n }\n}", "filename": "Test.java" }
2018
a04
[ { "content": "package a04.sol1;\n\nimport java.util.Optional;\n\n\npublic interface SimpleIterator<T> {\n\n\t\n\tOptional<T> next();\n}", "filename": "SimpleIterator.java" }, { "content": "package a04.sol1;\n\nimport java.util.*;\n\n\n\ninterface IntegerIteratorsFactory {\n \n \n SimpleIterator<Integer> empty();\n \n \n SimpleIterator<Integer> fromList(List<Integer> list);\n \n \n SimpleIterator<Integer> random(int size);\n \n \n SimpleIterator<Integer> quadratic();\n \n \n SimpleIterator<Integer> recurring();\n \n}", "filename": "IntegerIteratorsFactory.java" } ]
[ { "content": "package a04.sol1;\n\nimport java.util.Collections;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Optional;\nimport java.util.Random;\nimport java.util.stream.Stream;\n\npublic class IntegerIteratorsFactoryImpl implements IntegerIteratorsFactory {\n\t\n\t// idea: costruiamo un adattatore da Stream a SimpleIterator\n\tprivate SimpleIterator<Integer> simpleIteratorFromStream(Stream<Integer> stream){\n\t\tIterator<Integer> it = stream.iterator();\n\t\treturn new SimpleIterator<Integer>() {\n\t\t\t@Override\n\t\t\tpublic Optional<Integer> next() {\n\t\t\t\treturn Optional.of(true).filter(v -> it.hasNext()).map(v -> it.next());\n\t\t\t}\n\t\t};\n\t}\n\t\n\t//.. ora tutti i SimpleIterator si costruiscono piuttosto semplicemente,\n\t// costruendo lo stream dei valori da produrre\n\t@Override\n\tpublic SimpleIterator<Integer> empty() {\n\t\treturn this.simpleIteratorFromStream(Stream.empty());\n\t}\n\n\t@Override\n\tpublic SimpleIterator<Integer> fromList(List<Integer> list) {\n\t\treturn this.simpleIteratorFromStream(list.stream());\n\t}\n\n\t@Override\n\tpublic SimpleIterator<Integer> random(int size) {\n\t\tfinal Random random = new Random();\n\t\treturn this.simpleIteratorFromStream(Stream.generate(()->random.nextInt(size))\n\t\t\t\t .limit(size));\n\t}\n\n\t@Override\n\tpublic SimpleIterator<Integer> quadratic() {\n\t\treturn this.simpleIteratorFromStream(Stream.iterate(0, x->x+1)\n\t\t\t\t .flatMap(i -> Collections.nCopies(i, i)\n\t\t\t\t .stream()));\n\t}\n\n\t@Override\n\tpublic SimpleIterator<Integer> recurring() {\n\t\treturn this.simpleIteratorFromStream(Stream.iterate(0, x->x+1)\n\t\t\t\t .flatMap(i -> Stream.iterate(0, x->x+1)\n\t\t\t\t .limit(i)));\n\t}\n\t\n}", "filename": "IntegerIteratorsFactoryImpl.java" } ]
{ "components": { "imports": "package a04.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;\n\n/**\n * See the documentation of the SimpleIterator interface, which models an iterator, and that of\n * IntegerIteratorsFactory, a factory for various iterators on integers. Implement the latter through\n * an IntegerIteratorsFactoryImpl class so that the tests below pass.\n * \n * The following are considered optional for the purpose of being able to correct the exercise, but still contribute to achieving\n * the entirety of the score:\n * - implementation of optional tests (named 'optionalTestXYZ', i.e. only the last one) \n * - minimization of repetitions\n * - minimization of memory waste, allocating objects of potentially large sizes unnecessarily\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": "\tprivate IntegerIteratorsFactory factory;\n\t\n\[email protected]\n\tpublic void init() {\n\t\tthis.factory = new IntegerIteratorsFactoryImpl();\n\t}", "test_functions": [ "\[email protected]\n public void testEmpty() {\n assertFalse(this.factory.empty().next().isPresent()); // immediately empty..\n assertFalse(this.factory.empty().next().isPresent()); // ..even if retrying\n }", "\[email protected]\n public void testList() {\n \tSimpleIterator<Integer> si = factory.fromList(Arrays.asList(10,20,30));\n assertEquals(si.next(),Optional.of(10)); // produces the elements of the list\n assertEquals(si.next(),Optional.of(20));\n assertEquals(si.next(),Optional.of(30));\n assertFalse(si.next().isPresent());\n assertFalse(si.next().isPresent()); // ..anyway it doesn't proceed\n }", "\[email protected]\n public void testRandom() { // semi-automatic, the video prints will also be checked \n \tSimpleIterator<Integer> si = factory.random(4); // 4 elements included in 0..3\n \tList<Integer> values = Arrays.asList(0,1,2,3);\n \tint b1 = si.next().get();\n \tint b2 = si.next().get();\n \tint b3 = si.next().get();\n \tint b4 = si.next().get();\n \tSystem.out.println(b1+ \" \"+b2+ \" \"+b3+ \" \"+b4); // video verification of randomness\n assertTrue(values.contains(b1)); // b1 included in {0,1,2,3}", "\[email protected]\n public void testQuadratic() { \n \tSimpleIterator<Integer> si = factory.quadratic();\n assertEquals(si.next(),Optional.of(1));\n assertEquals(si.next(),Optional.of(2));\n assertEquals(si.next(),Optional.of(2));\n assertEquals(si.next(),Optional.of(3));\n assertEquals(si.next(),Optional.of(3));\n assertEquals(si.next(),Optional.of(3));\n assertEquals(si.next(),Optional.of(4));\n assertEquals(si.next(),Optional.of(4));\n assertEquals(si.next(),Optional.of(4));\n assertEquals(si.next(),Optional.of(4));\n assertEquals(si.next(),Optional.of(5));\n assertEquals(si.next(),Optional.of(5));\n for (int i=0;i<100;i++) {\n \tassertTrue(si.next().isPresent()); // it continues to produce..\n }", "\[email protected]\n public void optionalTestRecurring() { \n \tSimpleIterator<Integer> si = factory.recurring();\n assertEquals(si.next(),Optional.of(0));\n assertEquals(si.next(),Optional.of(0));\n assertEquals(si.next(),Optional.of(1));\n assertEquals(si.next(),Optional.of(0));\n assertEquals(si.next(),Optional.of(1));\n assertEquals(si.next(),Optional.of(2));\n assertEquals(si.next(),Optional.of(0));\n assertEquals(si.next(),Optional.of(1));\n assertEquals(si.next(),Optional.of(2));\n assertEquals(si.next(),Optional.of(3));\n assertEquals(si.next(),Optional.of(0));\n assertEquals(si.next(),Optional.of(1));\n assertEquals(si.next(),Optional.of(2));\n assertEquals(si.next(),Optional.of(3));\n assertEquals(si.next(),Optional.of(4));\n for (int i=0;i<100;i++) {\n \tassertTrue(si.next().isPresent()); // it continues to produce..\n }" ] }, "content": "package a04.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;\n\n/**\n * See the documentation of the SimpleIterator interface, which models an iterator, and that of\n * IntegerIteratorsFactory, a factory for various iterators on integers. Implement the latter through\n * an IntegerIteratorsFactoryImpl class so that the tests below pass.\n * \n * The following are considered optional for the purpose of being able to correct the exercise, but still contribute to achieving\n * the entirety of the score:\n * - implementation of optional tests (named 'optionalTestXYZ', i.e. only the last one) \n * - minimization of repetitions\n * - minimization of memory waste, allocating objects of potentially large sizes unnecessarily\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\n\npublic class Test {\n\t\n\tprivate IntegerIteratorsFactory factory;\n\t\n\[email protected]\n\tpublic void init() {\n\t\tthis.factory = new IntegerIteratorsFactoryImpl();\n\t}\n \n \n @org.junit.Test\n public void testEmpty() {\n assertFalse(this.factory.empty().next().isPresent()); // immediately empty..\n assertFalse(this.factory.empty().next().isPresent()); // ..even if retrying\n }\n \n @org.junit.Test\n public void testList() {\n \tSimpleIterator<Integer> si = factory.fromList(Arrays.asList(10,20,30));\n assertEquals(si.next(),Optional.of(10)); // produces the elements of the list\n assertEquals(si.next(),Optional.of(20));\n assertEquals(si.next(),Optional.of(30));\n assertFalse(si.next().isPresent());\n assertFalse(si.next().isPresent()); // ..anyway it doesn't proceed\n }\n \n \n @org.junit.Test\n public void testRandom() { // semi-automatic, the video prints will also be checked \n \tSimpleIterator<Integer> si = factory.random(4); // 4 elements included in 0..3\n \tList<Integer> values = Arrays.asList(0,1,2,3);\n \tint b1 = si.next().get();\n \tint b2 = si.next().get();\n \tint b3 = si.next().get();\n \tint b4 = si.next().get();\n \tSystem.out.println(b1+ \" \"+b2+ \" \"+b3+ \" \"+b4); // video verification of randomness\n assertTrue(values.contains(b1)); // b1 included in {0,1,2,3}...\n assertTrue(values.contains(b2)); // etc..\n assertTrue(values.contains(b3));\n assertTrue(values.contains(b4));\n assertFalse(si.next().isPresent());\n assertFalse(si.next().isPresent()); // ..anyway it doesn't proceed\n }\n \n @org.junit.Test\n public void testQuadratic() { \n \tSimpleIterator<Integer> si = factory.quadratic();\n assertEquals(si.next(),Optional.of(1));\n assertEquals(si.next(),Optional.of(2));\n assertEquals(si.next(),Optional.of(2));\n assertEquals(si.next(),Optional.of(3));\n assertEquals(si.next(),Optional.of(3));\n assertEquals(si.next(),Optional.of(3));\n assertEquals(si.next(),Optional.of(4));\n assertEquals(si.next(),Optional.of(4));\n assertEquals(si.next(),Optional.of(4));\n assertEquals(si.next(),Optional.of(4));\n assertEquals(si.next(),Optional.of(5));\n assertEquals(si.next(),Optional.of(5));\n for (int i=0;i<100;i++) {\n \tassertTrue(si.next().isPresent()); // it continues to produce..\n }\n }\n \n @org.junit.Test\n public void optionalTestRecurring() { \n \tSimpleIterator<Integer> si = factory.recurring();\n assertEquals(si.next(),Optional.of(0));\n assertEquals(si.next(),Optional.of(0));\n assertEquals(si.next(),Optional.of(1));\n assertEquals(si.next(),Optional.of(0));\n assertEquals(si.next(),Optional.of(1));\n assertEquals(si.next(),Optional.of(2));\n assertEquals(si.next(),Optional.of(0));\n assertEquals(si.next(),Optional.of(1));\n assertEquals(si.next(),Optional.of(2));\n assertEquals(si.next(),Optional.of(3));\n assertEquals(si.next(),Optional.of(0));\n assertEquals(si.next(),Optional.of(1));\n assertEquals(si.next(),Optional.of(2));\n assertEquals(si.next(),Optional.of(3));\n assertEquals(si.next(),Optional.of(4));\n for (int i=0;i<100;i++) {\n \tassertTrue(si.next().isPresent()); // it continues to produce..\n }\n }\n \n}", "filename": "Test.java" }
2018
a03a
[ { "content": "package a03a.sol1;\n\nimport java.util.Map;\n\nimport a03a.sol1.Evaluation.*;\n\n\ninterface EvaluationBuilder {\n\t\n\t\n\tEvaluationBuilder addEvaluationByMap(String course, int student, Map<Question,Result> results);\n\t\n\t\n\tEvaluationBuilder addEvaluationByResults(String course, int student, Result resOverall, Result resInterest, Result resClarity);\n\t\n\t\n\tEvaluation build();\n}", "filename": "EvaluationBuilder.java" }, { "content": "package a03a.sol1;\n\nimport java.util.Map;\n\n\npublic interface Evaluation {\n\t\n\t\n\tenum Question {\n\t\tOVERALL, \n\t\tINTEREST, \n\t\tCLARITY; \n\t}\n\t\n\t\n\tenum Result {\n\t\tFULLY_NEGATIVE, \n\t\tWEAKLY_NEGATIVE, \n\t\tWEAKLY_POSITIVE, \n\t\tFULLY_POSITIVE; \n\t}\n\t\t\n\t\n\tMap<Question,Result> results(String course, int student);\n\t\n\t\n\tMap<Result,Long> resultsCountForCourseAndQuestion(String course, Question questions);\n\t\n\t\n\tMap<Result,Long> resultsCountForStudent(int student);\n\t\n\t\n\tdouble coursePositiveResultsRatio(String course, Question question);\n\t\n}", "filename": "Evaluation.java" }, { "content": "package a03a.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 a03a.sol1;\n\nimport java.util.*;\nimport java.util.Map.Entry;\nimport java.util.stream.Collectors;\nimport a03a.sol1.Evaluation.*;\n\npublic class EvaluationBuilderImpl implements EvaluationBuilder {\n\n\tprivate final Map<Pair<String, Integer>, Map<Question, Result>> map = new HashMap<>();\n\tprivate boolean built = false;\n\n\t@Override\n\tpublic EvaluationBuilder addEvaluationByMap(String course, int student, Map<Question, Result> results) {\n\t\tif (this.map.containsKey(new Pair<>(course, student))) {\n\t\t\tthrow new IllegalStateException(\"Already added\");\n\t\t}\n\t\tif (results.size() != Question.values().length) {\n\t\t\tthrow new IllegalArgumentException(\"not complete\");\n\t\t}\n\t\tthis.map.put(new Pair<>(course, student), new EnumMap<>(results));\n\t\treturn this;\n\t}\n\n\t@Override\n\tpublic EvaluationBuilder addEvaluationByResults(String course, int student, Result resOverall, Result resInterest, Result resClarity) {\n\t\tMap<Question, Result> results = new EnumMap<>(Question.class);\n\t\tresults.put(Question.OVERALL, resOverall);\n\t\tresults.put(Question.INTEREST, resInterest);\n\t\tresults.put(Question.CLARITY, resClarity);\n\t\treturn this.addEvaluationByMap(course, student, results);\n\t}\n\n\t@Override\n\tpublic Evaluation build() {\n\t\tif (built) {\n\t\t\tthrow new IllegalStateException(\"Already built\");\n\t\t}\n\t\tbuilt = true;\n\t\treturn new Evaluation() {\n\n\t\t\t@Override\n\t\t\tpublic Map<Question, Result> results(String course, int student) {\n\t\t\t\treturn Collections.unmodifiableMap(map.getOrDefault(new Pair<>(course, student), new HashMap<>()));\n\t\t\t}\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic Map<Result, Long> resultsCountForCourseAndQuestion(String course, Question question) {\n\t\t\t\treturn map.entrySet().stream()\n\t\t\t\t\t\t .filter(e -> e.getKey().getX().equals(course))\n\t\t\t\t\t\t .map(Entry::getValue)\n\t\t\t\t\t\t .map(Map::entrySet)\n\t\t\t\t\t\t .flatMap(Set::stream)\n\t\t\t\t\t\t .filter(e -> e.getKey() == question)\n\t\t\t\t\t\t .collect(Collectors.groupingBy(e -> e.getValue(), Collectors.counting()));\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Map<Result, Long> resultsCountForStudent(int student) {\n\t\t\t\treturn map.entrySet().stream()\n\t\t\t\t\t\t .filter(e -> e.getKey().getY().equals(student))\n\t\t\t\t\t\t .map(Entry::getValue)\n\t\t\t\t\t\t .map(Map::entrySet)\n\t\t\t\t\t\t .flatMap(Set::stream)\n\t\t\t\t\t\t .collect(Collectors.groupingBy(e -> e.getValue(), Collectors.counting()));\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic double coursePositiveResultsRatio(String course, Question question) {\n\t\t\t\tList<Result> results = map.entrySet().stream()\n\t\t\t\t\t\t .filter(e -> e.getKey().getX().equals(course))\n\t\t\t\t\t\t .map(Entry::getValue)\n\t\t\t\t\t\t\t\t\t\t .map(Map::entrySet)\n\t\t\t\t\t\t\t\t\t\t .flatMap(Set::stream)\n\t\t\t\t\t\t .filter(e -> e.getKey() == question)\n\t\t\t\t\t\t .map(Entry::getValue)\n\t\t\t\t\t\t .collect(Collectors.toList());\n\t\t\t\treturn results.stream().filter(e -> e == Result.FULLY_POSITIVE || e == Result.WEAKLY_POSITIVE).count() / (double) results.size();\n\t\t\t}\n\n\t\t};\n\t}\n\n}", "filename": "EvaluationBuilderImpl.java" } ]
{ "components": { "imports": "package a03a.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;\n\n/**\n * Please refer to the documentation of the provided interfaces:\n * - Evaluation models the results of the UNIBO student questionnaire for a certain set of courses\n * - EvaluationBuilder models a builder for Evaluation, which allows loading all the data before calling the search methods\n *\n * Implement EvaluationBuilder through an EvaluationBuilderImpl class with a constructor without arguments,\n * so that it passes all the tests below, designed to be self-explanatory.\n *\n * The following are considered optional for the purpose of being able to correct the exercise, but still contribute to achieving\n * the totality of the score:\n * - implementation of optional tests (related to some checks for exceptions and the coursePositiveResultsRatio method)\n * - the quality of the solution, in particular with minimization of repetitions and code that is not unnecessarily complex\n *\n * Scoring indications:\n * - correctness of the mandatory part: 9 points\n * - correctness of the optional part: 4 points\n * - quality of the solution: 4 points\n *\n * Remove the comment from the test code.\n */\n\nimport a03a.sol1.Evaluation.*;\nimport static a03a.sol1.Evaluation.Result.*;", "private_init": "\tprivate EvaluationBuilder builder;\n\tprivate Evaluation ev;\n\n\t// this method instantiates the builder and uses it to load various student questionnaires\n\[email protected]\n\tpublic void init() {\n\t\tthis.builder = new EvaluationBuilderImpl();\n\t\t// the student with registration number 1 fills out the questionnaire for the \"PPS\" course\n\t\t// .. giving \"decidedly yes\" to \"overall satisfied\" and \"quality of the teacher\"\n\t\t// .. and \"more yes than no\" to \"are you interested in the course\"\n\t\t// and similar for the others\n\t\tbuilder.addEvaluationByResults(\"PPS\", 1, FULLY_POSITIVE, WEAKLY_POSITIVE, FULLY_POSITIVE)\n\t\t\t .addEvaluationByResults(\"PPS\", 2, WEAKLY_POSITIVE, WEAKLY_POSITIVE, WEAKLY_NEGATIVE)\n\t\t .addEvaluationByResults(\"PPS\", 3, FULLY_POSITIVE, FULLY_POSITIVE, FULLY_POSITIVE)\n\t\t .addEvaluationByResults(\"LPMC\", 1, FULLY_POSITIVE, FULLY_POSITIVE, FULLY_POSITIVE)\n\t\t .addEvaluationByResults(\"LPMC\", 2, FULLY_NEGATIVE, FULLY_NEGATIVE, FULLY_NEGATIVE)\n\t\t .addEvaluationByResults(\"LPMC\", 3, FULLY_POSITIVE, FULLY_POSITIVE, FULLY_NEGATIVE);\n\t\t// load another questionnaire, with a different but equivalent modality\n\t\tMap<Question,Result> results = new EnumMap<>(Question.class);\n\t\tresults.put(Question.OVERALL, FULLY_POSITIVE);\n\t\tresults.put(Question.INTEREST, FULLY_NEGATIVE);\n\t\tresults.put(Question.CLARITY, WEAKLY_POSITIVE);\n\t\tbuilder.addEvaluationByMap(\"LPMC\", 4, results); // student 4 on the course \"LPMC\"\n\t\tthis. ev = builder.build();\n\t}", "test_functions": [ "\[email protected]\n public void testResults() {\n\t\t// student 1, on the \"PPS\" course, answered \"decidedly yes\" to the question \"are you overall satisfied\"\n\t\tassertEquals(ev.results(\"PPS\", 1).get(Question.OVERALL),FULLY_POSITIVE);\n\t\t// etc..\n\t\tassertEquals(ev.results(\"LPMC\", 3).get(Question.CLARITY),FULLY_NEGATIVE);\n\t\tassertEquals(ev.results(\"LPMC\", 4).get(Question.INTEREST),FULLY_NEGATIVE);\n\t\tassertTrue(ev.results(\"LPMC\", 5).isEmpty());\n\t}", "\[email protected]\n public void testResultsCountForCourseAndCriterion() {\n\t\t// the \"PPS\" course received two \"decidedly yes\" answers to the question \"are you overall satisfied\"\n\t\tassertEquals(ev.resultsCountForCourseAndQuestion(\"PPS\", Question.OVERALL).get(FULLY_POSITIVE).longValue(),2);\n\t\t// etc..\n\t\tassertEquals(ev.resultsCountForCourseAndQuestion(\"PPS\", Question.OVERALL).get(WEAKLY_POSITIVE).longValue(),1);\n\t\tassertEquals(ev.resultsCountForCourseAndQuestion(\"LPMC\", Question.INTEREST).get(FULLY_POSITIVE).longValue(),2);\n\t\tassertEquals(ev.resultsCountForCourseAndQuestion(\"LPMC\", Question.INTEREST).get(FULLY_NEGATIVE).longValue(),2);\n\t}", "\[email protected]\n public void testResultsCountForStudent() {\n\t\t// the student with registration number 1 answered 5 times \"decidedly yes\" in all the questionnaires he filled out\n\t\tassertEquals(ev.resultsCountForStudent(1).get(FULLY_POSITIVE).longValue(),5);\n\t\t// etc..\n\t\tassertEquals(ev.resultsCountForStudent(1).get(WEAKLY_POSITIVE).longValue(),1);\n\t\tassertEquals(ev.resultsCountForStudent(4).get(FULLY_POSITIVE).longValue(),1);\n\t\tassertEquals(ev.resultsCountForStudent(4).get(WEAKLY_POSITIVE).longValue(),1);\n\t\tassertEquals(ev.resultsCountForStudent(4).get(FULLY_NEGATIVE).longValue(),1);\n\t}", "\[email protected]\n public void optionalTestCoursePositiveResultsRatio() {\n\t\t// the \"PPS\" course has 100% (i.e. 1.0, with a maximum deviation of 0.01) of positive judgments to the question \"are you decidedly satisfied\"\n\t\tassertEquals(ev.coursePositiveResultsRatio(\"PPS\", Question.OVERALL),1.0,0.01); // 0.01 of accuracy\n\t\t// the \"PPS\" course has 67% (i.e. 1.0, with a maximum deviation of 0.01) of positive judgments to the question \"the teacher explains clearly\"\n\t\tassertEquals(ev.coursePositiveResultsRatio(\"PPS\", Question.CLARITY),0.67,0.01); // 0.01 of accuracy\n\t\t// etc..\n\t\tassertEquals(ev.coursePositiveResultsRatio(\"LPMC\", Question.OVERALL),0.75,0.01); // 0.01 of accuracy\n\t}" ] }, "content": "package a03a.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;\n\n/**\n * Please refer to the documentation of the provided interfaces:\n * - Evaluation models the results of the UNIBO student questionnaire for a certain set of courses\n * - EvaluationBuilder models a builder for Evaluation, which allows loading all the data before calling the search methods\n *\n * Implement EvaluationBuilder through an EvaluationBuilderImpl class with a constructor without arguments,\n * so that it passes all the tests below, designed to be self-explanatory.\n *\n * The following are considered optional for the purpose of being able to correct the exercise, but still contribute to achieving\n * the totality of the score:\n * - implementation of optional tests (related to some checks for exceptions and the coursePositiveResultsRatio method)\n * - the quality of the solution, in particular with minimization of repetitions and code that is not unnecessarily complex\n *\n * Scoring indications:\n * - correctness of the mandatory part: 9 points\n * - correctness of the optional part: 4 points\n * - quality of the solution: 4 points\n *\n * Remove the comment from the test code.\n */\n\nimport a03a.sol1.Evaluation.*;\nimport static a03a.sol1.Evaluation.Result.*;\n\npublic class Test {\n\n\tprivate EvaluationBuilder builder;\n\tprivate Evaluation ev;\n\n\t// this method instantiates the builder and uses it to load various student questionnaires\n\[email protected]\n\tpublic void init() {\n\t\tthis.builder = new EvaluationBuilderImpl();\n\t\t// the student with registration number 1 fills out the questionnaire for the \"PPS\" course\n\t\t// .. giving \"decidedly yes\" to \"overall satisfied\" and \"quality of the teacher\"\n\t\t// .. and \"more yes than no\" to \"are you interested in the course\"\n\t\t// and similar for the others\n\t\tbuilder.addEvaluationByResults(\"PPS\", 1, FULLY_POSITIVE, WEAKLY_POSITIVE, FULLY_POSITIVE)\n\t\t\t .addEvaluationByResults(\"PPS\", 2, WEAKLY_POSITIVE, WEAKLY_POSITIVE, WEAKLY_NEGATIVE)\n\t\t .addEvaluationByResults(\"PPS\", 3, FULLY_POSITIVE, FULLY_POSITIVE, FULLY_POSITIVE)\n\t\t .addEvaluationByResults(\"LPMC\", 1, FULLY_POSITIVE, FULLY_POSITIVE, FULLY_POSITIVE)\n\t\t .addEvaluationByResults(\"LPMC\", 2, FULLY_NEGATIVE, FULLY_NEGATIVE, FULLY_NEGATIVE)\n\t\t .addEvaluationByResults(\"LPMC\", 3, FULLY_POSITIVE, FULLY_POSITIVE, FULLY_NEGATIVE);\n\t\t// load another questionnaire, with a different but equivalent modality\n\t\tMap<Question,Result> results = new EnumMap<>(Question.class);\n\t\tresults.put(Question.OVERALL, FULLY_POSITIVE);\n\t\tresults.put(Question.INTEREST, FULLY_NEGATIVE);\n\t\tresults.put(Question.CLARITY, WEAKLY_POSITIVE);\n\t\tbuilder.addEvaluationByMap(\"LPMC\", 4, results); // student 4 on the course \"LPMC\"\n\t\tthis. ev = builder.build();\n\t}\n\n\[email protected]\n public void testResults() {\n\t\t// student 1, on the \"PPS\" course, answered \"decidedly yes\" to the question \"are you overall satisfied\"\n\t\tassertEquals(ev.results(\"PPS\", 1).get(Question.OVERALL),FULLY_POSITIVE);\n\t\t// etc..\n\t\tassertEquals(ev.results(\"LPMC\", 3).get(Question.CLARITY),FULLY_NEGATIVE);\n\t\tassertEquals(ev.results(\"LPMC\", 4).get(Question.INTEREST),FULLY_NEGATIVE);\n\t\tassertTrue(ev.results(\"LPMC\", 5).isEmpty());\n\t}\n\n\[email protected]\n public void testResultsCountForCourseAndCriterion() {\n\t\t// the \"PPS\" course received two \"decidedly yes\" answers to the question \"are you overall satisfied\"\n\t\tassertEquals(ev.resultsCountForCourseAndQuestion(\"PPS\", Question.OVERALL).get(FULLY_POSITIVE).longValue(),2);\n\t\t// etc..\n\t\tassertEquals(ev.resultsCountForCourseAndQuestion(\"PPS\", Question.OVERALL).get(WEAKLY_POSITIVE).longValue(),1);\n\t\tassertEquals(ev.resultsCountForCourseAndQuestion(\"LPMC\", Question.INTEREST).get(FULLY_POSITIVE).longValue(),2);\n\t\tassertEquals(ev.resultsCountForCourseAndQuestion(\"LPMC\", Question.INTEREST).get(FULLY_NEGATIVE).longValue(),2);\n\t}\n\n\[email protected]\n public void testResultsCountForStudent() {\n\t\t// the student with registration number 1 answered 5 times \"decidedly yes\" in all the questionnaires he filled out\n\t\tassertEquals(ev.resultsCountForStudent(1).get(FULLY_POSITIVE).longValue(),5);\n\t\t// etc..\n\t\tassertEquals(ev.resultsCountForStudent(1).get(WEAKLY_POSITIVE).longValue(),1);\n\t\tassertEquals(ev.resultsCountForStudent(4).get(FULLY_POSITIVE).longValue(),1);\n\t\tassertEquals(ev.resultsCountForStudent(4).get(WEAKLY_POSITIVE).longValue(),1);\n\t\tassertEquals(ev.resultsCountForStudent(4).get(FULLY_NEGATIVE).longValue(),1);\n\t}\n\n\[email protected](expected = IllegalStateException.class)\n\tpublic void testCantBuildTwice() {\n\t\tbuilder.build(); // already called build..\n }\n\n\t// a judgment is positive if \"decidedly yes\" or \"more yes than no\"\n\[email protected]\n public void optionalTestCoursePositiveResultsRatio() {\n\t\t// the \"PPS\" course has 100% (i.e. 1.0, with a maximum deviation of 0.01) of positive judgments to the question \"are you decidedly satisfied\"\n\t\tassertEquals(ev.coursePositiveResultsRatio(\"PPS\", Question.OVERALL),1.0,0.01); // 0.01 of accuracy\n\t\t// the \"PPS\" course has 67% (i.e. 1.0, with a maximum deviation of 0.01) of positive judgments to the question \"the teacher explains clearly\"\n\t\tassertEquals(ev.coursePositiveResultsRatio(\"PPS\", Question.CLARITY),0.67,0.01); // 0.01 of accuracy\n\t\t// etc..\n\t\tassertEquals(ev.coursePositiveResultsRatio(\"LPMC\", Question.OVERALL),0.75,0.01); // 0.01 of accuracy\n\t}\n\n\[email protected](expected = IllegalArgumentException.class)\n\tpublic void optionalTestIncompleteResults() {\n\t\tbuilder.addEvaluationByMap(\"LPMC\", 10, new HashMap<>()); // empty results, or incomplete anyway\n }\n\n\[email protected](expected = IllegalStateException.class)\n\tpublic void optionalTestResultAlreadyLoaded() {\n\t\tMap<Question,Result> results = new EnumMap<>(Question.class);\n\t\tresults.put(Question.OVERALL, FULLY_POSITIVE);\n\t\tresults.put(Question.INTEREST, FULLY_NEGATIVE);\n\t\tresults.put(Question.CLARITY, WEAKLY_POSITIVE);\n\t\tbuilder.addEvaluationByMap(\"LPMC\", 4, results); // already loaded the data of student 4 for LPMC\n }\n}", "filename": "Test.java" }
2018
a02b
[ { "content": "package a02b.sol1;\n\nimport java.util.*;\n\n\npublic interface Tournament {\n\t\n\t\n\tString getName();\n\t\n\t\n\tint getYear();\n\t\t\n\t\n\tint getWeek();\n\n\t\n\tSet<String> getPlayers();\n\t\n\t\n\tOptional<Integer> getResult(String player);\n\t\n\t\n\tString winner();\n\t\n}", "filename": "Tournament.java" }, { "content": "package a02b.sol1;\n\nimport java.util.Map;\nimport java.util.Set;\n\n\npublic interface TournamentFactory {\n\t\n\t\n\tTournament make(String name, int year, int week, Set<String> players, Map<String,Integer> points);\n}", "filename": "TournamentFactory.java" }, { "content": "package a02b.sol1;\n\nimport java.util.*;\n\n\npublic interface Ranking {\n\n\t\n\tvoid loadTournament(Tournament tournament);\n\t\n\t\n\tint getCurrentWeek();\n\t\n\t\n\tint getCurrentYear();\n\t\n\t\n\tInteger pointsFromPlayer(String player);\n\t\n\t\n\tList<String> ranking();\n\t\n\t\n\tMap<String,String> winnersFromTournamentInLastYear();\n\t\n\t\n\tMap<String,Integer> pointsAtEachTournamentFromPlayer(String player);\n\t\n\t\n\tList<Pair<String,Integer>> pointsAtEachTournamentFromPlayerSorted(String player);\n\t\n}", "filename": "Ranking.java" }, { "content": "package 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 a02b.sol1;\n\nimport java.util.*;\nimport java.util.stream.Collectors;\n\npublic class RankingImpl implements Ranking {\n\t\n\tprivate final List<Tournament> tournaments = new LinkedList<>();\n\t\n\t// Comparatore per tornei come costante\n\tprivate static final Comparator<Tournament> TC = \n\t\t\t(t1,t2)-> t1.getYear()==t2.getYear() ? t1.getWeek()-t2.getWeek() \n\t\t\t\t\t : t1.getYear()-t2.getYear();\n\t\n\t// controllo che un torneo sia nell'anno in corso\t\t\n\tprivate boolean inCurrentYear(Tournament t) {\n\t\tthis.checkNonEmptyTournaments();\n\t\treturn t.getYear()==this.tournaments.get(0).getYear() || (\n\t\t\t\tt.getYear()==this.tournaments.get(0).getYear()-1 &&\n\t\t\t\tt.getWeek()>this.tournaments.get(0).getWeek());\n\t}\t\t\n\t\t\t\n\tprivate void checkNonEmptyTournaments() {\n\t\tif (this.tournaments.isEmpty()) {\n\t\t\tthrow new IllegalStateException();\n\t\t}\n\t}\n\t@Override\n\tpublic void loadTournament(Tournament t) {\n\t\tif (!this.tournaments.isEmpty() && TC.compare(this.tournaments.get(0),t)>=0) {\n\t\t\tthrow new IllegalStateException();\n\t\t}\n\t\tthis.tournaments.add(0,t);\n\t}\n\n\t@Override\n\tpublic int getCurrentWeek() {\n\t\tthis.checkNonEmptyTournaments();\n\t\treturn this.tournaments.get(0).getWeek();\n\t}\n\n\t@Override\n\tpublic int getCurrentYear() {\n\t\tthis.checkNonEmptyTournaments();\n\t\treturn this.tournaments.get(0).getYear();\n\t}\n\n\t@Override\n\tpublic Integer pointsFromPlayer(String player) {\n\t\treturn this.tournaments.stream()\n\t\t\t\t .filter(t -> inCurrentYear(t))\n\t\t\t\t .map(t -> t.getResult(player))\n\t\t\t\t .filter(Optional::isPresent)\n\t\t\t\t .map(Optional::get)\n\t\t\t\t .reduce(0, (x,y)->x+y);\n\t}\n\n\t@Override\n\tpublic List<String> ranking() {\n\t\treturn this.tournaments.stream()\n\t\t\t\t .flatMap(t->t.getPlayers().stream())\n\t\t\t\t .distinct()\n\t\t\t\t .map(p -> new Pair<>(p,pointsFromPlayer(p)))\n\t\t\t\t .sorted((p1,p2)->p2.getY()-p1.getY())\n\t\t\t\t .map(Pair::getX)\n\t\t\t\t .collect(Collectors.toList());\n\t}\n\n\t@Override\n\tpublic Map<String, String> winnersFromTournamentInLastYear() {\n\t\treturn this.tournaments.stream()\n\t\t\t\t .filter(t -> inCurrentYear(t))\n\t\t\t\t .collect(Collectors.toMap(t->t.getName(), t->t.winner()));\n\t}\n\n\t@Override\n\tpublic Map<String, Integer> pointsAtEachTournamentFromPlayer(String player) {\n\t\treturn this.tournaments.stream()\n\t .filter(t -> t.getPlayers().contains(player))\n\t .collect(Collectors.toMap(t->t.getName(), t->t.getResult(player).get()));\n\t}\n\n\t@Override\n\tpublic List<Pair<String, Integer>> pointsAtEachTournamentFromPlayerSorted(String player) {\n\t\treturn this.tournaments.stream()\n\t .filter(t -> t.getPlayers().contains(player))\n\t .sorted(TC)\n\t .map(t -> new Pair<>(t.getName(),t.getResult(player).get()))\n\t .collect(Collectors.toList());\n\t}\n\n}", "filename": "RankingImpl.java" }, { "content": "package a02b.sol1;\n\nimport java.util.Collections;\nimport java.util.Map;\nimport java.util.Objects;\nimport java.util.Optional;\nimport java.util.Set;\n\npublic class TournamentFactoryImpl implements TournamentFactory {\n\n\t@Override\n\tpublic Tournament make(String name, int year, int week, Set<String> players, Map<String, Integer> points) {\n\t\tObjects.requireNonNull(name);\n\t\tObjects.requireNonNull(players);\n\t\tObjects.requireNonNull(points);\n\t\t\n\t\treturn new Tournament() {\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic String getName() {\n\t\t\t\treturn name;\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic int getYear() {\n\t\t\t\treturn year;\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic int getWeek() {\n\t\t\t\treturn week;\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Set<String> getPlayers() {\n\t\t\t\treturn Collections.unmodifiableSet(players);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Optional<Integer> getResult(String player) {\n\t\t\t\treturn Optional.of(player)\n\t\t\t\t\t\t\t .filter(p -> players.contains(p))\n\t\t\t\t\t\t .map(p -> points.containsKey(p) ? points.get(p) : 0);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic String winner() {\n\t\t\t\treturn players.stream().max((p1,p2)->getResult(p1).get()-getResult(p2).get()).get();\n\t\t\t}\n\t\t\t\n\t\t};\n\t}\n}", "filename": "TournamentFactoryImpl.java" } ]
{ "components": { "imports": "package a02b.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;\n\n\n/**\n * Please consult the documentation of the provided interfaces:\n * - Tournament models the results of a Tennis Tournament\n * - TournamentFactory models a simple factory for tournaments\n * - Ranking models a history of the results of the last tournaments\n * \n * Note from the documentation how a tournament has a precise location in time (year and week).\n * Note that a player who participates in a tournament acquires a number of points >=0\n * Note that tournaments can be loaded one after the other in chronological order\n * Note that for the purposes of calculating a player's overall score, only the tournaments\n * of the last year compete (going backwards from the last loaded tournament) \n * \n * Implement TournamentFactory through a class TournamentFactoryImpl with a constructor without arguments,\n * and implement Ranking through a class RankingImpl with a constructor without arguments,\n * so that it passes all the tests below.\n * \n * The following are considered optional for the purpose of being able to correct the exercise, but still contribute to achieving \n * the totality of the score:\n * - implementation of optional tests (related to some checks for exceptions and the last two methods of Ranking)\n * - the quality of the solution, in particular with minimization of repetitions and code not unnecessarily complex\n * \n * Scoring indications:\n * - correctness of the mandatory part: 9 points\n * - correctness of the optional part: 3 points\n * - quality of the solution: 5 points\n * \n * Remove the comment from the test code.\n */", "private_init": "\tprivate static final Map<String,Integer> P1 = new HashMap<String,Integer>(){{\n\t\tthis.put(\"Nadal\", 6000);\n\t\tthis.put(\"Federer\", 7000);\n\t\tthis.put(\"Djokovic\", 6500);\n\t\tthis.put(\"Fognini\", 4000);\n\t}};\n\t\n\tprivate TournamentFactory tf;\n\tprivate Ranking ranking;\n\t\n\tprivate Tournament roma2018() {\n\t\tSet<String> players = new HashSet<>(Arrays.asList(\"Federer\",\"Nadal\",\"Djokovic\",\"Fognini\"));\n\t\tMap<String,Integer> points = new HashMap<String,Integer>(){{\n\t\t\tthis.put(\"Federer\", 1000);\n\t\t\tthis.put(\"Djokovic\", 500);\n\t\t}};\n\t\treturn tf.make(\"roma2018\", 2018, 20, players, points);\n\t}\n\t\n\tprivate Tournament wimbledon2018() {\n\t\tSet<String> players = new HashSet<>(Arrays.asList(\"Federer\",\"Nadal\",\"Djokovic\",\"Tsitsipas\"));\n\t\tMap<String,Integer> points = new HashMap<String,Integer>(){{\n\t\t\tthis.put(\"Djokovic\", 2500);\n\t\t\tthis.put(\"Federer\", 1000);\n\t\t\tthis.put(\"Nadal\", 500);\n\t\t}};\n\t\treturn tf.make(\"wimbledon2018\", 2018, 30, players, points);\n\t}\n\t\n\tprivate Tournament roma2019() {\n\t\tSet<String> players = new HashSet<>(Arrays.asList(\"Federer\",\"Nadal\",\"Djokovic\",\"Tsitsipas\"));\n\t\tMap<String,Integer> points = new HashMap<String,Integer>(){{\n\t\t\tthis.put(\"Nadal\", 1500);\n\t\t\tthis.put(\"Federer\", 500);\n\t\t\tthis.put(\"Tsitsipas\", 200);\n\t\t}};\n\t\treturn tf.make(\"roma2019\", 2019, 20, players, points);\n\t}\n\t\n\[email protected]\n\tpublic void init() {\n\t\ttf = new TournamentFactoryImpl();\n\t\tranking = new RankingImpl();\n\t}\n\t\n\t// base check on the creation of the roma2018 tournament", "test_functions": [ "\[email protected]\n public void testRoma2018() {\n\t\tTournament t = roma2018();\n\t\tassertEquals(t.getName(),\"roma2018\");\n\t\tassertEquals(t.getYear(),2018);\n\t\tassertEquals(t.getWeek(),20);\n\t\tassertEquals(t.getResult(\"Federer\"),Optional.of(1000));\n\t\tassertEquals(t.getResult(\"Djokovic\"),Optional.of(500));\n\t\tassertEquals(t.getResult(\"Nadal\"),Optional.of(0)); // participated\n\t\tassertEquals(t.getResult(\"Fognini\"),Optional.of(0)); // participated\n\t\tassertEquals(t.getResult(\"Tsitsipas\"),Optional.empty()); // did not participate\n\t\tassertEquals(t.winner(), \"Federer\");\n\t}", "\[email protected]\n public void testWimbledon2018() {\n\t\tTournament t = wimbledon2018();\n\t\tassertEquals(t.getName(),\"wimbledon2018\");\n\t\tassertEquals(t.getYear(),2018);\n\t\tassertEquals(t.getWeek(),30);\n\t\tassertEquals(t.getResult(\"Djokovic\"),Optional.of(2500));\n\t\tassertEquals(t.getResult(\"Federer\"),Optional.of(1000));\n\t\tassertEquals(t.getResult(\"Nadal\"),Optional.of(500)); \n\t\tassertEquals(t.getResult(\"Tsitsipas\"),Optional.of(0)); // participated\n\t\tassertEquals(t.getResult(\"Fognini\"),Optional.empty()); // did not participate\n\t\tassertEquals(t.winner(), \"Djokovic\");\n\t}", "\[email protected]\n public void testWholeRanking() {\n\t\tranking.loadTournament(roma2018());\n\t\tranking.loadTournament(wimbledon2018());\n\t\tranking.loadTournament(roma2019()); // points will only be counted on the last two\n\t\tassertEquals(ranking.getCurrentWeek(),20);\n\t\tassertEquals(ranking.getCurrentYear(),2019);\n\t\tassertEquals(ranking.pointsFromPlayer(\"Federer\").intValue(),1500);\n\t\tassertEquals(ranking.pointsFromPlayer(\"Djokovic\").intValue(),2500);\n\t\tassertEquals(ranking.pointsFromPlayer(\"Nadal\").intValue(),2000);\n\t\tassertEquals(ranking.pointsFromPlayer(\"Tsitsipas\").intValue(),200);\n\t\tassertEquals(ranking.pointsFromPlayer(\"Fognini\").intValue(),0);\n\t\tassertEquals(ranking.pointsFromPlayer(\"Fognini\").intValue(),0);\n\t\tassertEquals(ranking.ranking(),Arrays.asList(\"Djokovic\",\"Nadal\",\"Federer\",\"Tsitsipas\",\"Fognini\"));\n\t\tassertEquals(ranking.winnersFromTournamentInLastYear().get(\"roma2019\"),\"Nadal\");\n\t\tassertEquals(ranking.winnersFromTournamentInLastYear().get(\"wimbledon2018\"),\"Djokovic\");\n\t}", "\[email protected]\n public void optionalTestPointsAtEachTournamentFromPlayer() {\n\t\tranking.loadTournament(roma2018());\n\t\tranking.loadTournament(wimbledon2018());\n\t\tranking.loadTournament(roma2019()); // points will only be counted on the last two\n\t\tassertEquals(ranking.pointsAtEachTournamentFromPlayer(\"Federer\").get(\"roma2018\").intValue(),1000);\n\t\tassertEquals(ranking.pointsAtEachTournamentFromPlayer(\"Federer\").get(\"wimbledon2018\").intValue(),1000);\n\t\tassertEquals(ranking.pointsAtEachTournamentFromPlayer(\"Federer\").get(\"roma2019\").intValue(),500);\n\t\tassertEquals(ranking.pointsAtEachTournamentFromPlayer(\"Federer\").size(),3);\n\t\tassertEquals(ranking.pointsAtEachTournamentFromPlayer(\"Tsitsipas\").get(\"roma2019\").intValue(),200);\n\t\tassertEquals(ranking.pointsAtEachTournamentFromPlayer(\"Tsitsipas\").get(\"wimbledon2018\").intValue(),0);\n\t\tassertEquals(ranking.pointsAtEachTournamentFromPlayer(\"Tsitsipas\").size(),2);\n\t\tList<Pair<String,Integer>> list = ranking.pointsAtEachTournamentFromPlayerSorted(\"Federer\");\n\t\tassertEquals(list.size(),3);\n\t\tassertEquals(list.get(0),new Pair<>(\"roma2018\",1000));\n\t\tassertEquals(list.get(1),new Pair<>(\"wimbledon2018\",1000));\n\t\tassertEquals(list.get(2),new Pair<>(\"roma2019\",500));\n\t\tlist = ranking.pointsAtEachTournamentFromPlayerSorted(\"Tsitsipas\");\n\t\tassertEquals(list.size(),2);\n\t\tassertEquals(list.get(0),new Pair<>(\"wimbledon2018\",0));\n\t\tassertEquals(list.get(1),new Pair<>(\"roma2019\",200));\n\t}" ] }, "content": "package a02b.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;\n\n\n/**\n * Please consult the documentation of the provided interfaces:\n * - Tournament models the results of a Tennis Tournament\n * - TournamentFactory models a simple factory for tournaments\n * - Ranking models a history of the results of the last tournaments\n * \n * Note from the documentation how a tournament has a precise location in time (year and week).\n * Note that a player who participates in a tournament acquires a number of points >=0\n * Note that tournaments can be loaded one after the other in chronological order\n * Note that for the purposes of calculating a player's overall score, only the tournaments\n * of the last year compete (going backwards from the last loaded tournament) \n * \n * Implement TournamentFactory through a class TournamentFactoryImpl with a constructor without arguments,\n * and implement Ranking through a class RankingImpl with a constructor without arguments,\n * so that it passes all the tests below.\n * \n * The following are considered optional for the purpose of being able to correct the exercise, but still contribute to achieving \n * the totality of the score:\n * - implementation of optional tests (related to some checks for exceptions and the last two methods of Ranking)\n * - the quality of the solution, in particular with minimization of repetitions and code not unnecessarily complex\n * \n * Scoring indications:\n * - correctness of the mandatory part: 9 points\n * - correctness of the optional part: 3 points\n * - quality of the solution: 5 points\n * \n * Remove the comment from the test code.\n */\n\npublic class Test {\n\t\n\tprivate static final Map<String,Integer> P1 = new HashMap<String,Integer>(){{\n\t\tthis.put(\"Nadal\", 6000);\n\t\tthis.put(\"Federer\", 7000);\n\t\tthis.put(\"Djokovic\", 6500);\n\t\tthis.put(\"Fognini\", 4000);\n\t}};\n\t\n\tprivate TournamentFactory tf;\n\tprivate Ranking ranking;\n\t\n\tprivate Tournament roma2018() {\n\t\tSet<String> players = new HashSet<>(Arrays.asList(\"Federer\",\"Nadal\",\"Djokovic\",\"Fognini\"));\n\t\tMap<String,Integer> points = new HashMap<String,Integer>(){{\n\t\t\tthis.put(\"Federer\", 1000);\n\t\t\tthis.put(\"Djokovic\", 500);\n\t\t}};\n\t\treturn tf.make(\"roma2018\", 2018, 20, players, points);\n\t}\n\t\n\tprivate Tournament wimbledon2018() {\n\t\tSet<String> players = new HashSet<>(Arrays.asList(\"Federer\",\"Nadal\",\"Djokovic\",\"Tsitsipas\"));\n\t\tMap<String,Integer> points = new HashMap<String,Integer>(){{\n\t\t\tthis.put(\"Djokovic\", 2500);\n\t\t\tthis.put(\"Federer\", 1000);\n\t\t\tthis.put(\"Nadal\", 500);\n\t\t}};\n\t\treturn tf.make(\"wimbledon2018\", 2018, 30, players, points);\n\t}\n\t\n\tprivate Tournament roma2019() {\n\t\tSet<String> players = new HashSet<>(Arrays.asList(\"Federer\",\"Nadal\",\"Djokovic\",\"Tsitsipas\"));\n\t\tMap<String,Integer> points = new HashMap<String,Integer>(){{\n\t\t\tthis.put(\"Nadal\", 1500);\n\t\t\tthis.put(\"Federer\", 500);\n\t\t\tthis.put(\"Tsitsipas\", 200);\n\t\t}};\n\t\treturn tf.make(\"roma2019\", 2019, 20, players, points);\n\t}\n\t\n\[email protected]\n\tpublic void init() {\n\t\ttf = new TournamentFactoryImpl();\n\t\tranking = new RankingImpl();\n\t}\n\t\n\t// base check on the creation of the roma2018 tournament\n\[email protected]\n public void testRoma2018() {\n\t\tTournament t = roma2018();\n\t\tassertEquals(t.getName(),\"roma2018\");\n\t\tassertEquals(t.getYear(),2018);\n\t\tassertEquals(t.getWeek(),20);\n\t\tassertEquals(t.getResult(\"Federer\"),Optional.of(1000));\n\t\tassertEquals(t.getResult(\"Djokovic\"),Optional.of(500));\n\t\tassertEquals(t.getResult(\"Nadal\"),Optional.of(0)); // participated\n\t\tassertEquals(t.getResult(\"Fognini\"),Optional.of(0)); // participated\n\t\tassertEquals(t.getResult(\"Tsitsipas\"),Optional.empty()); // did not participate\n\t\tassertEquals(t.winner(), \"Federer\");\n\t}\n\t\n\t// base check on the creation of the roma2018 tournament\n\[email protected]\n public void testWimbledon2018() {\n\t\tTournament t = wimbledon2018();\n\t\tassertEquals(t.getName(),\"wimbledon2018\");\n\t\tassertEquals(t.getYear(),2018);\n\t\tassertEquals(t.getWeek(),30);\n\t\tassertEquals(t.getResult(\"Djokovic\"),Optional.of(2500));\n\t\tassertEquals(t.getResult(\"Federer\"),Optional.of(1000));\n\t\tassertEquals(t.getResult(\"Nadal\"),Optional.of(500)); \n\t\tassertEquals(t.getResult(\"Tsitsipas\"),Optional.of(0)); // participated\n\t\tassertEquals(t.getResult(\"Fognini\"),Optional.empty()); // did not participate\n\t\tassertEquals(t.winner(), \"Djokovic\");\n\t}\n\t\n\[email protected]\n public void testWholeRanking() {\n\t\tranking.loadTournament(roma2018());\n\t\tranking.loadTournament(wimbledon2018());\n\t\tranking.loadTournament(roma2019()); // points will only be counted on the last two\n\t\tassertEquals(ranking.getCurrentWeek(),20);\n\t\tassertEquals(ranking.getCurrentYear(),2019);\n\t\tassertEquals(ranking.pointsFromPlayer(\"Federer\").intValue(),1500);\n\t\tassertEquals(ranking.pointsFromPlayer(\"Djokovic\").intValue(),2500);\n\t\tassertEquals(ranking.pointsFromPlayer(\"Nadal\").intValue(),2000);\n\t\tassertEquals(ranking.pointsFromPlayer(\"Tsitsipas\").intValue(),200);\n\t\tassertEquals(ranking.pointsFromPlayer(\"Fognini\").intValue(),0);\n\t\tassertEquals(ranking.pointsFromPlayer(\"Fognini\").intValue(),0);\n\t\tassertEquals(ranking.ranking(),Arrays.asList(\"Djokovic\",\"Nadal\",\"Federer\",\"Tsitsipas\",\"Fognini\"));\n\t\tassertEquals(ranking.winnersFromTournamentInLastYear().get(\"roma2019\"),\"Nadal\");\n\t\tassertEquals(ranking.winnersFromTournamentInLastYear().get(\"wimbledon2018\"),\"Djokovic\");\n\t}\n\t\n\[email protected]\n public void optionalTestPointsAtEachTournamentFromPlayer() {\n\t\tranking.loadTournament(roma2018());\n\t\tranking.loadTournament(wimbledon2018());\n\t\tranking.loadTournament(roma2019()); // points will only be counted on the last two\n\t\tassertEquals(ranking.pointsAtEachTournamentFromPlayer(\"Federer\").get(\"roma2018\").intValue(),1000);\n\t\tassertEquals(ranking.pointsAtEachTournamentFromPlayer(\"Federer\").get(\"wimbledon2018\").intValue(),1000);\n\t\tassertEquals(ranking.pointsAtEachTournamentFromPlayer(\"Federer\").get(\"roma2019\").intValue(),500);\n\t\tassertEquals(ranking.pointsAtEachTournamentFromPlayer(\"Federer\").size(),3);\n\t\tassertEquals(ranking.pointsAtEachTournamentFromPlayer(\"Tsitsipas\").get(\"roma2019\").intValue(),200);\n\t\tassertEquals(ranking.pointsAtEachTournamentFromPlayer(\"Tsitsipas\").get(\"wimbledon2018\").intValue(),0);\n\t\tassertEquals(ranking.pointsAtEachTournamentFromPlayer(\"Tsitsipas\").size(),2);\n\t\tList<Pair<String,Integer>> list = ranking.pointsAtEachTournamentFromPlayerSorted(\"Federer\");\n\t\tassertEquals(list.size(),3);\n\t\tassertEquals(list.get(0),new Pair<>(\"roma2018\",1000));\n\t\tassertEquals(list.get(1),new Pair<>(\"wimbledon2018\",1000));\n\t\tassertEquals(list.get(2),new Pair<>(\"roma2019\",500));\n\t\tlist = ranking.pointsAtEachTournamentFromPlayerSorted(\"Tsitsipas\");\n\t\tassertEquals(list.size(),2);\n\t\tassertEquals(list.get(0),new Pair<>(\"wimbledon2018\",0));\n\t\tassertEquals(list.get(1),new Pair<>(\"roma2019\",200));\n\t}\n\t\n\[email protected](expected = IllegalStateException.class)\n\tpublic void optionalTestCantLoadATournamentTwice() {\n\t\tranking.loadTournament(roma2018());\n\t\tranking.loadTournament(roma2018());\n\t}\n\t\n\[email protected](expected = IllegalStateException.class)\n\tpublic void optionalTestCantLoadTournamentsInWrongOrder() {\n\t\tranking.loadTournament(wimbledon2018());\n\t\tranking.loadTournament(roma2018());\n\t}\n\t\n\[email protected](expected = IllegalStateException.class)\n\tpublic void optionalTestCantAccessPropertiesBeforeLoadingTournaments() {\n\t\tranking.getCurrentWeek();\n\t}\n\n}", "filename": "Test.java" }
2018
a06
[ { "content": "package a06.sol1;\n\nimport java.util.List;\n\n\npublic interface Parser {\n\t\n\t\n\tboolean acceptToken(String token);\n\t\n\t\n\tboolean inputCompleted();\n\t\n\t\n\tvoid reset();\n\n\t\n\t\n\tdefault boolean acceptAllToEnd(List<String> list) {\n\t\treturn list.stream().allMatch(s -> this.acceptToken(s)) && this.inputCompleted();\n\t}\n\n}", "filename": "Parser.java" }, { "content": "package a06.sol1;\n\nimport java.util.Set;\n\n\npublic interface ParserFactory {\n\t\n\t\n\tParser one(String token);\n\t\n\t\n\tParser many(String token, int elemCount);\n\t\n\t\n\tParser oneOf(Set<String> set);\n\t\n\t\n\tParser sequence(String token1, String token2);\n\t\n\t\n\tParser fullSequence(String begin, Set<String> elem, String separator, String end, int elemCount);\n}", "filename": "ParserFactory.java" } ]
[ { "content": "package a06.sol1;\n\nimport java.util.Collections;\nimport java.util.List;\nimport java.util.Set;\n\n/**\n * This is a rather advanced solution, which some students may study and enjoy.\n * A simpler solution would be to develop each parser as a variation of the implementation of method oneOf.\n */\npublic class ParserFactoryImpl implements ParserFactory {\n\n\t@Override\n\tpublic Parser one(String string) {\n\t\t// 'one' is clearly a particular case of 'oneOf'\n\t\treturn this.oneOf(Collections.singleton(string));\n\t}\n\t\n\t@Override\n\tpublic Parser oneOf(Set<String> list) {\n\t\treturn new Parser() {\n\t\t\t\n\t\t\tprivate boolean consumed = false; // just need a flag as state!\n\n\t\t\t@Override\n\t\t\tpublic boolean acceptToken(String token) {\n\t\t\t\tif (this.inputCompleted()) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tconsumed = true;\n\t\t\t\treturn list.contains(token);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic boolean inputCompleted() {\n\t\t\t\treturn consumed;\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void reset() {\n\t\t\t\tconsumed = false;\n\t\t\t}\n\t\t\t\n\t\t};\n\t}\n\t\n\t@Override\n\tpublic Parser many(String token, int count) {\n\t\treturn many(this.one(token),count); // use a more general parser, see below\n\t}\n\t\n\t/**\n\t * @return a parser that performs parsing of 'p' for 'count' times\n\t */\n\tprivate Parser many(Parser p, int count) {\n\t\treturn new Parser() {\n\t\t\tint c = count;\n\t\t\t@Override\n\t\t\tpublic boolean acceptToken(String token) {\n\t\t\t\tif (p.inputCompleted() && c>0) {\n\t\t\t\t\tp.reset();\n\t\t\t\t\tc--;\n\t\t\t\t}\n\t\t\t\treturn c>0 && p.acceptToken(token);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic boolean inputCompleted() {\n\t\t\t\treturn c==0 || (c==1 && p.inputCompleted());\n\t\t\t}\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic void reset() {\n\t\t\t\tc = count;\n\t\t\t\tp.reset();\n\t\t\t}\n\t\t};\n\t}\n\t\n\t@Override\n\tpublic Parser sequence(String token1, String token2) {\n\t\treturn this.sequence(one(token1),one(token2)); // use a more general parser, see below\n\t}\n\t\n\t/**\n\t * @return a parser that performs parsing of 'p1' and then of 'p2'\n\t */\n\tprivate Parser sequence(Parser p1, Parser p2) {\n\t\treturn new Parser() {\t\t\n\t\t\t@Override\n\t\t\tpublic boolean acceptToken(String string) {\n\t\t\t\treturn (p1.inputCompleted() ? p2 : p1).acceptToken(string);\n\t\t\t}\n\t\t\t@Override\n\t\t\tpublic boolean inputCompleted() {\n\t\t\t\treturn (p1.inputCompleted() && p2.inputCompleted());\n\t\t\t}\n\t\t\t@Override\n\t\t\tpublic void reset() {\n\t\t\t\tp1.reset();\n\t\t\t\tp2.reset();\n\t\t\t}\t\t\t\t\t\t\n\t\t};\n\t\t\n\t}\n\t\n\t/**\n\t * generalise the above parser with a sequence of n parsers\n\t */\n\tprivate Parser sequence(Parser p, Parser... parsers) {\n\t\tParser out = p;\n\t\tfor (Parser p2: parsers) {\n\t\t\tout = sequence(out,p2);\n\t\t}\n\t\treturn out;\n\t}\n\t\n\n\t/* \n\t * And here's the magic! Obtain this parser by combining the above ones!\n\t * This technique is called \"combinators\" (a functional pattern), enjoy it!\n\t * Of course, the student could also implement fullSequence with an ad-hoc parser, as we did for 'oneOf'\n\t */\n\t@Override\n\tpublic Parser fullSequence(String begin, Set<String> elem, String separator, String end, int count) {\n\t\treturn sequence(one(begin),\n\t\t\t\t oneOf(elem),\n\t\t\t\t many(sequence(one(separator),oneOf(elem)),count-1),\n\t\t\t\t one(end));\n\t}\n}", "filename": "ParserFactoryImpl.java" } ]
{ "components": { "imports": "package a06.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;\n\n/**\n * Consult the documentation of the provided interfaces:\n * - Parser models a parser, i.e. a \"consumer\" of strings (tokens)\n * - ParserFactory models a set of functionalities for creating Parsers\n * \n * Implement ParserFactory through a ParserFactoryImple class with a constructor without arguments,\n * so that it passes all the tests below.\n * \n * The following are considered optional for the purpose of being able to correct the exercise, but still contribute to achieving \n * the totality of the score:\n * - implementation by choice of either the first 4 methods of the factory (one,oneOf,many,sequence), or the last one (fullSequence)\n * - the good design of the solution, in particular with minimization of repetitions\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": "\tprivate ParserFactory pf;\n\t\n\[email protected]\n\tpublic void init() {\n\t\tthis.pf = new ParserFactoryImpl();\n\t}", "test_functions": [ "\[email protected]\n public void testOne() {\n // Test on a parser that accepts only one \"a\"\n final Parser parser = this.pf.one(\"a\");\n assertTrue(parser.acceptToken(\"a\")); // takes \"a\"\n assertTrue(parser.inputCompleted()); // has finished\n assertFalse(parser.acceptToken(\"a\")); // does not take another \"a\"\n parser.reset(); // restarts, and works as before\n assertTrue(parser.acceptToken(\"a\"));\n assertTrue(parser.inputCompleted());\n assertFalse(parser.acceptToken(\"a\"));\n parser.reset(); // restarts\n assertFalse(parser.inputCompleted()); // has not finished\n assertTrue(parser.acceptToken(\"a\")); // takes \"a\"\n assertTrue(parser.inputCompleted()); // has finished\n parser.reset();\n assertTrue(parser.acceptAllToEnd(Arrays.asList(\"a\"))); // consumes the sequence made of one \"a\"\n parser.reset();\n assertFalse(parser.acceptAllToEnd(Arrays.asList(\"a\",\"a\"))); // this one does not consume it\n parser.reset();\n assertFalse(parser.acceptAllToEnd(Arrays.asList(\"b\"))); // this one does not consume it\n }", "\[email protected]\n public void testOneOf() {\n // Test on a parser that accepts only one \"a\", or only one \"b\", or only one \"c\"\n final Parser parser = this.pf.oneOf(new HashSet<>(Arrays.asList(\"a\",\"b\",\"c\")));\n assertTrue(parser.acceptToken(\"a\"));\n assertTrue(parser.inputCompleted());\n assertFalse(parser.acceptToken(\"a\"));\n parser.reset();\n assertTrue(parser.acceptToken(\"b\"));\n assertTrue(parser.inputCompleted());\n assertFalse(parser.acceptToken(\"a\"));\n parser.reset();\n assertFalse(parser.inputCompleted());\n assertTrue(parser.acceptToken(\"c\"));\n assertTrue(parser.inputCompleted());\n parser.reset();\n assertTrue(parser.acceptAllToEnd(Arrays.asList(\"a\")));\n parser.reset();\n assertFalse(parser.acceptAllToEnd(Arrays.asList(\"a\",\"a\")));\n parser.reset();\n assertTrue(parser.acceptAllToEnd(Arrays.asList(\"b\")));\n parser.reset();\n assertFalse(parser.acceptAllToEnd(Arrays.asList()));\n }", "\[email protected]\n public void testZeroOrMany() {\n // Test on parsers that accept 0 or more copies of \"a\"\n Parser parser = this.pf.many(\"a\",0); // 0 copies of \"a\"\n assertTrue(parser.inputCompleted()); // already finished\n parser = this.pf.many(\"a\",1); // 1 copy of \"a\"\n assertTrue(parser.acceptToken(\"a\"));\n assertTrue(parser.inputCompleted());\n parser = this.pf.many(\"a\",3); // 3 copies of \"a\"\n assertTrue(parser.acceptToken(\"a\"));\n assertTrue(parser.acceptToken(\"a\"));\n assertTrue(parser.acceptToken(\"a\")); \n assertTrue(parser.inputCompleted());\n parser = this.pf.many(\"a\",0); // other tests using acceptAllToEnd\n assertTrue(parser.acceptAllToEnd(Arrays.asList()));\n parser = this.pf.many(\"a\",1);\n assertTrue(parser.acceptAllToEnd(Arrays.asList(\"a\")));\n parser = this.pf.many(\"a\",3);\n assertTrue(parser.acceptAllToEnd(Arrays.asList(\"a\",\"a\",\"a\")));\n parser.reset();\n assertFalse(parser.acceptAllToEnd(Arrays.asList(\"a\",\"a\",\"b\")));\n }", "\[email protected]\n public void testSequence() {\n // Test on a parser that accepts an \"a\" and then a \"b\", and then nothing else\n final Parser parser = this.pf.sequence(\"a\",\"b\");\n parser.reset();\n assertFalse(parser.acceptAllToEnd(Arrays.asList()));\n parser.reset();\n assertTrue(parser.acceptAllToEnd(Arrays.asList(\"a\",\"b\")));\n parser.reset();\n assertFalse(parser.acceptAllToEnd(Arrays.asList(\"a\")));\n parser.reset();\n assertFalse(parser.acceptAllToEnd(Arrays.asList(\"a\",\"b\",\"a\",\"b\")));\n }", "\[email protected]\n public void testFullSequence() {\n Parser parser = this.pf.fullSequence(\"[\",new HashSet<>(Arrays.asList(\"a\",\"b\")),\";\",\"]\",1);\n assertTrue(parser.acceptToken(\"[\")); // I recognize [ a ] \n assertTrue(parser.acceptToken(\"a\")); \n assertTrue(parser.acceptToken(\"]\")); \n assertTrue(parser.inputCompleted()); \n parser = this.pf.fullSequence(\"[\",new HashSet<>(Arrays.asList(\"a\",\"b\")),\";\",\"]\",1);\n assertTrue(parser.acceptAllToEnd(Arrays.asList(\"[\",\"a\",\"]\"))); // I recognize [ a ]\n parser = this.pf.fullSequence(\"[\",new HashSet<>(Arrays.asList(\"a\",\"b\")),\";\",\"]\",2);\n assertTrue(parser.acceptAllToEnd(Arrays.asList(\"[\",\"a\",\";\",\"b\",\"]\"))); // I recognize [ a ; b ]\n parser = this.pf.fullSequence(\"[\",new HashSet<>(Arrays.asList(\"a\",\"b\")),\";\",\"]\",3);\n assertTrue(parser.acceptAllToEnd(Arrays.asList(\"[\",\"a\",\";\",\"b\",\";\",\"a\",\"]\"))); // I recognize [ a ; b ; a ]\n parser.reset();\n assertFalse(parser.acceptAllToEnd(Arrays.asList(\"[\",\"]\"))); // I don't recognize [ ]\n parser = this.pf.fullSequence(\"[\",new HashSet<>(Arrays.asList(\"a\",\"b\")),\";\",\"]\",3);\n assertFalse(parser.acceptAllToEnd(Arrays.asList(\"[\",\"a\",\"b\",\";\",\"a\",\"]\"))); // I don't recognize [ a b ; a ]\n }" ] }, "content": "package a06.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;\n\n/**\n * Consult the documentation of the provided interfaces:\n * - Parser models a parser, i.e. a \"consumer\" of strings (tokens)\n * - ParserFactory models a set of functionalities for creating Parsers\n * \n * Implement ParserFactory through a ParserFactoryImple class with a constructor without arguments,\n * so that it passes all the tests below.\n * \n * The following are considered optional for the purpose of being able to correct the exercise, but still contribute to achieving \n * the totality of the score:\n * - implementation by choice of either the first 4 methods of the factory (one,oneOf,many,sequence), or the last one (fullSequence)\n * - the good design of the solution, in particular with minimization of repetitions\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\t\n\tprivate ParserFactory pf;\n\t\n\[email protected]\n\tpublic void init() {\n\t\tthis.pf = new ParserFactoryImpl();\n\t}\n\t\n\[email protected]\n public void testOne() {\n // Test on a parser that accepts only one \"a\"\n final Parser parser = this.pf.one(\"a\");\n assertTrue(parser.acceptToken(\"a\")); // takes \"a\"\n assertTrue(parser.inputCompleted()); // has finished\n assertFalse(parser.acceptToken(\"a\")); // does not take another \"a\"\n parser.reset(); // restarts, and works as before\n assertTrue(parser.acceptToken(\"a\"));\n assertTrue(parser.inputCompleted());\n assertFalse(parser.acceptToken(\"a\"));\n parser.reset(); // restarts\n assertFalse(parser.inputCompleted()); // has not finished\n assertTrue(parser.acceptToken(\"a\")); // takes \"a\"\n assertTrue(parser.inputCompleted()); // has finished\n parser.reset();\n assertTrue(parser.acceptAllToEnd(Arrays.asList(\"a\"))); // consumes the sequence made of one \"a\"\n parser.reset();\n assertFalse(parser.acceptAllToEnd(Arrays.asList(\"a\",\"a\"))); // this one does not consume it\n parser.reset();\n assertFalse(parser.acceptAllToEnd(Arrays.asList(\"b\"))); // this one does not consume it\n }\n\n\[email protected]\n public void testOneOf() {\n // Test on a parser that accepts only one \"a\", or only one \"b\", or only one \"c\"\n final Parser parser = this.pf.oneOf(new HashSet<>(Arrays.asList(\"a\",\"b\",\"c\")));\n assertTrue(parser.acceptToken(\"a\"));\n assertTrue(parser.inputCompleted());\n assertFalse(parser.acceptToken(\"a\"));\n parser.reset();\n assertTrue(parser.acceptToken(\"b\"));\n assertTrue(parser.inputCompleted());\n assertFalse(parser.acceptToken(\"a\"));\n parser.reset();\n assertFalse(parser.inputCompleted());\n assertTrue(parser.acceptToken(\"c\"));\n assertTrue(parser.inputCompleted());\n parser.reset();\n assertTrue(parser.acceptAllToEnd(Arrays.asList(\"a\")));\n parser.reset();\n assertFalse(parser.acceptAllToEnd(Arrays.asList(\"a\",\"a\")));\n parser.reset();\n assertTrue(parser.acceptAllToEnd(Arrays.asList(\"b\")));\n parser.reset();\n assertFalse(parser.acceptAllToEnd(Arrays.asList()));\n }\n\t\n\[email protected]\n public void testZeroOrMany() {\n // Test on parsers that accept 0 or more copies of \"a\"\n Parser parser = this.pf.many(\"a\",0); // 0 copies of \"a\"\n assertTrue(parser.inputCompleted()); // already finished\n parser = this.pf.many(\"a\",1); // 1 copy of \"a\"\n assertTrue(parser.acceptToken(\"a\"));\n assertTrue(parser.inputCompleted());\n parser = this.pf.many(\"a\",3); // 3 copies of \"a\"\n assertTrue(parser.acceptToken(\"a\"));\n assertTrue(parser.acceptToken(\"a\"));\n assertTrue(parser.acceptToken(\"a\")); \n assertTrue(parser.inputCompleted());\n parser = this.pf.many(\"a\",0); // other tests using acceptAllToEnd\n assertTrue(parser.acceptAllToEnd(Arrays.asList()));\n parser = this.pf.many(\"a\",1);\n assertTrue(parser.acceptAllToEnd(Arrays.asList(\"a\")));\n parser = this.pf.many(\"a\",3);\n assertTrue(parser.acceptAllToEnd(Arrays.asList(\"a\",\"a\",\"a\")));\n parser.reset();\n assertFalse(parser.acceptAllToEnd(Arrays.asList(\"a\",\"a\",\"b\")));\n }\n\t\n\[email protected]\n public void testSequence() {\n // Test on a parser that accepts an \"a\" and then a \"b\", and then nothing else\n final Parser parser = this.pf.sequence(\"a\",\"b\");\n parser.reset();\n assertFalse(parser.acceptAllToEnd(Arrays.asList()));\n parser.reset();\n assertTrue(parser.acceptAllToEnd(Arrays.asList(\"a\",\"b\")));\n parser.reset();\n assertFalse(parser.acceptAllToEnd(Arrays.asList(\"a\")));\n parser.reset();\n assertFalse(parser.acceptAllToEnd(Arrays.asList(\"a\",\"b\",\"a\",\"b\")));\n }\n\t\n\[email protected]\n public void testFullSequence() {\n Parser parser = this.pf.fullSequence(\"[\",new HashSet<>(Arrays.asList(\"a\",\"b\")),\";\",\"]\",1);\n assertTrue(parser.acceptToken(\"[\")); // I recognize [ a ] \n assertTrue(parser.acceptToken(\"a\")); \n assertTrue(parser.acceptToken(\"]\")); \n assertTrue(parser.inputCompleted()); \n parser = this.pf.fullSequence(\"[\",new HashSet<>(Arrays.asList(\"a\",\"b\")),\";\",\"]\",1);\n assertTrue(parser.acceptAllToEnd(Arrays.asList(\"[\",\"a\",\"]\"))); // I recognize [ a ]\n parser = this.pf.fullSequence(\"[\",new HashSet<>(Arrays.asList(\"a\",\"b\")),\";\",\"]\",2);\n assertTrue(parser.acceptAllToEnd(Arrays.asList(\"[\",\"a\",\";\",\"b\",\"]\"))); // I recognize [ a ; b ]\n parser = this.pf.fullSequence(\"[\",new HashSet<>(Arrays.asList(\"a\",\"b\")),\";\",\"]\",3);\n assertTrue(parser.acceptAllToEnd(Arrays.asList(\"[\",\"a\",\";\",\"b\",\";\",\"a\",\"]\"))); // I recognize [ a ; b ; a ]\n parser.reset();\n assertFalse(parser.acceptAllToEnd(Arrays.asList(\"[\",\"]\"))); // I don't recognize [ ]\n parser = this.pf.fullSequence(\"[\",new HashSet<>(Arrays.asList(\"a\",\"b\")),\";\",\"]\",3);\n assertFalse(parser.acceptAllToEnd(Arrays.asList(\"[\",\"a\",\"b\",\";\",\"a\",\"]\"))); // I don't recognize [ a b ; a ]\n }\n\n}", "filename": "Test.java" }
2018
a01a
[ { "content": "package a01a.sol1;\n\nimport java.util.List;\nimport java.util.function.Function;\n\n\npublic interface SplitIteratorFactory {\n\t\n\t\n\tSplitIterator<Integer> fromRange(int start, int stop);\n\t\n\t\n\tSplitIterator<Integer> fromRangeNoSplit(int start, int stop);\n\t\n\t\n\t<X> SplitIterator<X> fromList(List<X> list);\n\t\n\t\n\t<X> SplitIterator<X> fromListNoSplit(List<X> list);\n\t\n\t\n\t<X> SplitIterator<X> excludeFirst(SplitIterator<X> si);\n\t\n\t\n\t<X,Y> SplitIterator<Y> map(SplitIterator<X> si, Function<X,Y> mapper);\n\n}", "filename": "SplitIteratorFactory.java" }, { "content": "package a01a.sol1;\n\nimport java.util.Optional;\n\n\npublic interface SplitIterator<X> {\n\t\n\t\n\tOptional<X> next();\n\t\n\t\n\tSplitIterator<X> split();\n}", "filename": "SplitIterator.java" } ]
[ { "content": "package a01a.sol1;\n\nimport java.util.List;\nimport java.util.Optional;\nimport java.util.function.Function;\n\npublic class SplitIteratorFactoryImpl implements SplitIteratorFactory {\n\n\t/* \n\t * The iterator should not cache future values!\n\t */\n\t@Override\n\tpublic SplitIterator<Integer> fromRange(int start, int stop) {\n\t\treturn new SplitIterator<Integer>(){\n\t\t\t\n\t\t\tprivate int current = start;\n\n\t\t\t@Override\n\t\t\tpublic Optional<Integer> next() {\n\t\t\t\t// The use of Optional.filter prevents a more verbose use of if \n\t\t\t\treturn Optional.of(this.current++).filter(c -> c <= stop);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic SplitIterator<Integer> split() {\n\t\t\t\tint oldCurrent = this.current;\n\t\t\t\tthis.current = (this.current+stop)/2;\n\t\t\t\treturn fromRange(oldCurrent,this.current-1);\n\t\t\t}\n\t\t};\n\t}\n\t\n\t/* \n\t * You could have the NoSplit version of any Iterator. Hence, there's more quality if you solve the problem once\n\t * and for all. This can be done by a decoration.\n\t */\n\t@Override\n\tpublic SplitIterator<Integer> fromRangeNoSplit(int start, int stop) {\n\t\treturn new NoSplitIteratorDecorator<>(fromRange(start,stop));\n\t}\n\n\n\t@Override\n\tpublic <X, Y> SplitIterator<Y> map(SplitIterator<X> si, Function<X, Y> mapper) {\n\t\treturn new SplitIterator<Y>() {\n\n\t\t\t@Override\n\t\t\tpublic Optional<Y> next() {\n\t\t\t\treturn si.next().map(mapper);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic SplitIterator<Y> split() {\n\t\t\t\treturn map(si.split(),mapper);\n\t\t\t}\n\t\t\t\n\t\t};\n\t}\n\t\n\t/* \n\t * A crucial idea to avoid repetitions here, is to implement fromList by fromRange thanks to map()\n\t */\n\t@Override\n\tpublic <X> SplitIterator<X> fromList(List<X> list) {\n\t\treturn map(fromRange(0,list.size()-1), list::get);\n\t}\n\n\t@Override\n\tpublic <X> SplitIterator<X> fromListNoSplit(List<X> list) {\n\t\treturn new NoSplitIteratorDecorator<>(fromList(list));\n\t}\n\n\t@Override\n\tpublic <X> SplitIterator<X> excludeFirst(SplitIterator<X> si) {\n\t\tsi.next();\n\t\treturn new SplitIterator<X>() {\n\n\t\t\t@Override\n\t\t\tpublic Optional<X> next() {\n\t\t\t\treturn si.next();\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic SplitIterator<X> split() {\n\t\t\t\treturn si.split();\n\t\t\t}\n\t\t\t\n\t\t};\n\t}\n\n}", "filename": "SplitIteratorFactoryImpl.java" }, { "content": "package a01a.sol1;\n\nimport java.util.Optional;\n\npublic class NoSplitIteratorDecorator<X> implements SplitIterator<X> {\n\t\n\tprivate final SplitIterator<X> si;\n\t\n\tpublic NoSplitIteratorDecorator(SplitIterator<X> si) {\n\t\tthis.si = si;\n\t}\n\n\t@Override\n\tpublic Optional<X> next() {\n\t\treturn this.si.next();\n\t}\n\n\t@Override\n\tpublic SplitIterator<X> split() {\n\t\tthrow new UnsupportedOperationException();\n\t}\n\n\t\n\t\n}", "filename": "NoSplitIteratorDecorator.java" } ]
{ "components": { "imports": "package a01a.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;\n\n/**\n * Please consult the documentation of the provided interfaces:\n * - SplitIterator<X> models an iterator of elements of type X, with the possibility of \"splitting\" creating a new iterator\n * - SplitIteratorFactory<X> models a factory for various types of iterator \n * \n * Implement SplitIteratorFactory<X> through a class SplitIteratorFactoryImpl<X> with a constructor without arguments,\n * so that it passes all the tests below.\n * \n * The following are considered optional for the purpose of being able to correct the exercise, but still contribute to achieving\n * the totality of the score:\n * - implementation of optional tests (related to the SplitIteratorFactory.map() method)\n * - the quality of the solution, in particular with minimization of repetitions and code not unnecessarily complex\n * \n * Scoring indications:\n * - correctness of the mandatory part: 9 points\n * - correctness of the optional part: 3 points\n * - quality of the solution: 5 points\n * \n * Remove the comment from the test code.\n */", "private_init": "\tprivate SplitIteratorFactory sif = new SplitIteratorFactoryImpl();\n\t\n\t// basic verification of fromRange()", "test_functions": [ "\[email protected]\n public void testRange() {\n\t\t// in a range from 0 to 3, 0,1,2,3 are produced, and then nothing more\n\t\tfinal SplitIterator<Integer> si = sif.fromRange(0, 3); \n\t\tassertEquals(si.next(),Optional.of(0));\n\t\tassertEquals(si.next(),Optional.of(1));\n\t\tassertEquals(si.next(),Optional.of(2));\n\t\tassertEquals(si.next(),Optional.of(3));\n\t\tassertEquals(si.next(),Optional.empty());\n\t\tassertEquals(si.next(),Optional.empty()); // empty even insisting on producing\n }", "\[email protected]\n public void testRangeAndSplit() {\n\t\tfinal SplitIterator<Integer> si = sif.fromRange(0, 5); \n\t\tassertEquals(si.next(),Optional.of(0));\n\t\t// 1,2,3,4,5.. remain to be produced but it splits\n\t\tfinal SplitIterator<Integer> siNew = si.split(); \n\t\t// siNew iterates the first half (excluding the intermediate if there is one), i.e. 1,2\n\t\tassertEquals(siNew.next(),Optional.of(1));\n\t\tassertEquals(siNew.next(),Optional.of(2));\n\t\tassertEquals(siNew.next(),Optional.empty());\n\t\t// si iterates the second half, i.e. 3,4,5\n\t\tassertEquals(si.next(),Optional.of(3));\n\t\tassertEquals(si.next(),Optional.of(4));\n\t\tassertEquals(si.next(),Optional.of(5));\n\t\tassertEquals(si.next(),Optional.empty());\n }", "\[email protected]\n public void testRangeAndSplitInterleaved() {\n\t\t// like the test above, but siNew and si also work in \"interleaving\" without changes\n\t\tfinal SplitIterator<Integer> si = sif.fromRange(0, 5); \n\t\tassertEquals(si.next(),Optional.of(0));\n\t\tfinal SplitIterator<Integer> siNew = si.split(); \n\t\tassertEquals(siNew.next(),Optional.of(1));\n\t\tassertEquals(si.next(),Optional.of(3));\n\t\tassertEquals(si.next(),Optional.of(4));\n\t\tassertEquals(siNew.next(),Optional.of(2));\n\t\tassertEquals(siNew.next(),Optional.empty());\n\t\tassertEquals(si.next(),Optional.of(5));\n\t\tassertEquals(si.next(),Optional.empty());\n }", "\[email protected]\n public void optionalTestMap() {\n\t\tfinal SplitIterator<String> si = sif.map(sif.fromRange(0, 3),i -> \"s\"+i);\n\t\t// sif produces s0,s1,s2,s3, for mapping from 0,1,2,3\n\t\tassertEquals(si.next(),Optional.of(\"s0\"));\n\t\tassertEquals(si.next(),Optional.of(\"s1\"));\n\t\tassertEquals(si.next(),Optional.of(\"s2\"));\n\t\tassertEquals(si.next(),Optional.of(\"s3\"));\n\t\tassertEquals(si.next(),Optional.empty());\n }", "\[email protected]\n public void optionalTestMapAndSplit() {\n\t\t// checks that the SpliIterator created by map() supports splitting\n\t\tfinal SplitIterator<String> si = sif.map(sif.fromRange(0, 5),i -> \"s\"+i);\n\t\tassertEquals(si.next(),Optional.of(\"s0\"));\n\t\tfinal SplitIterator<String> siNew = si.split(); \n\t\tassertEquals(siNew.next(),Optional.of(\"s1\"));\n\t\tassertEquals(siNew.next(),Optional.of(\"s2\"));\n\t\tassertEquals(siNew.next(),Optional.empty());\n\t\tassertEquals(si.next(),Optional.of(\"s3\"));\n\t\tassertEquals(si.next(),Optional.of(\"s4\"));\n\t\tassertEquals(si.next(),Optional.of(\"s5\"));\n\t\tassertEquals(si.next(),Optional.empty());\n }", "\[email protected]\n public void testList() {\n\t\tfinal SplitIterator<Integer> si = sif.fromList(Arrays.asList(0,10,20,30,40)); \n\t\t// on this list, the iteration produces 0,10,20,30,40, and then nothing more\n\t\tassertEquals(si.next(),Optional.of(0));\n\t\tassertEquals(si.next(),Optional.of(10));\n\t\tassertEquals(si.next(),Optional.of(20));\n\t\tassertEquals(si.next(),Optional.of(30));\n\t\tassertEquals(si.next(),Optional.of(40));\n\t\tassertEquals(si.next(),Optional.empty());\n }", "\[email protected]\n public void testListAndSplit() {\n\t\t// note that everything goes as in the case of the range..\n\t\tfinal SplitIterator<Integer> si = sif.fromList(Arrays.asList(0,10,20,30,40,50)); \n\t\tassertEquals(si.next(),Optional.of(0));\n\t\tfinal SplitIterator<Integer> siNew = si.split(); \n\t\tassertEquals(siNew.next(),Optional.of(10));\n\t\tassertEquals(si.next(),Optional.of(30));\n\t\tassertEquals(si.next(),Optional.of(40));\n\t\tassertEquals(siNew.next(),Optional.of(20));\n\t\tassertEquals(siNew.next(),Optional.empty());\n\t\tassertEquals(si.next(),Optional.of(50));\n\t\tassertEquals(si.next(),Optional.empty());\n }", "\[email protected]\n\tpublic void testExcludeFirst() {\n\t\tfinal SplitIterator<Integer> si = sif.fromList(Arrays.asList(10,20,30));\n\t\t// si would iterate on 10,20,30\n\t\tfinal SplitIterator<Integer> si2 = sif.excludeFirst(si);\n\t\t// si2 iterates on 20,30, because it excludes the first of si\n\t\tassertFalse(si == si2); // si2 is a new iterator!\n\t\tassertEquals(si2.next(),Optional.of(20));\n\t\tassertEquals(si2.next(),Optional.of(30));\n\t\tassertEquals(si2.next(),Optional.empty());\n }" ] }, "content": "package a01a.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;\n\n/**\n * Please consult the documentation of the provided interfaces:\n * - SplitIterator<X> models an iterator of elements of type X, with the possibility of \"splitting\" creating a new iterator\n * - SplitIteratorFactory<X> models a factory for various types of iterator \n * \n * Implement SplitIteratorFactory<X> through a class SplitIteratorFactoryImpl<X> with a constructor without arguments,\n * so that it passes all the tests below.\n * \n * The following are considered optional for the purpose of being able to correct the exercise, but still contribute to achieving\n * the totality of the score:\n * - implementation of optional tests (related to the SplitIteratorFactory.map() method)\n * - the quality of the solution, in particular with minimization of repetitions and code not unnecessarily complex\n * \n * Scoring indications:\n * - correctness of the mandatory part: 9 points\n * - correctness of the optional part: 3 points\n * - quality of the solution: 5 points\n * \n * Remove the comment from the test code.\n */\n\npublic class Test {\n\t\n\tprivate SplitIteratorFactory sif = new SplitIteratorFactoryImpl();\n\t\n\t// basic verification of fromRange()\n\[email protected]\n public void testRange() {\n\t\t// in a range from 0 to 3, 0,1,2,3 are produced, and then nothing more\n\t\tfinal SplitIterator<Integer> si = sif.fromRange(0, 3); \n\t\tassertEquals(si.next(),Optional.of(0));\n\t\tassertEquals(si.next(),Optional.of(1));\n\t\tassertEquals(si.next(),Optional.of(2));\n\t\tassertEquals(si.next(),Optional.of(3));\n\t\tassertEquals(si.next(),Optional.empty());\n\t\tassertEquals(si.next(),Optional.empty()); // empty even insisting on producing\n }\n\t\n\t// verification of the split in fromRange()\n\[email protected]\n public void testRangeAndSplit() {\n\t\tfinal SplitIterator<Integer> si = sif.fromRange(0, 5); \n\t\tassertEquals(si.next(),Optional.of(0));\n\t\t// 1,2,3,4,5.. remain to be produced but it splits\n\t\tfinal SplitIterator<Integer> siNew = si.split(); \n\t\t// siNew iterates the first half (excluding the intermediate if there is one), i.e. 1,2\n\t\tassertEquals(siNew.next(),Optional.of(1));\n\t\tassertEquals(siNew.next(),Optional.of(2));\n\t\tassertEquals(siNew.next(),Optional.empty());\n\t\t// si iterates the second half, i.e. 3,4,5\n\t\tassertEquals(si.next(),Optional.of(3));\n\t\tassertEquals(si.next(),Optional.of(4));\n\t\tassertEquals(si.next(),Optional.of(5));\n\t\tassertEquals(si.next(),Optional.empty());\n }\n\t\n\t// advanced verification of the split in fromRange()\n\[email protected]\n public void testRangeAndSplitInterleaved() {\n\t\t// like the test above, but siNew and si also work in \"interleaving\" without changes\n\t\tfinal SplitIterator<Integer> si = sif.fromRange(0, 5); \n\t\tassertEquals(si.next(),Optional.of(0));\n\t\tfinal SplitIterator<Integer> siNew = si.split(); \n\t\tassertEquals(siNew.next(),Optional.of(1));\n\t\tassertEquals(si.next(),Optional.of(3));\n\t\tassertEquals(si.next(),Optional.of(4));\n\t\tassertEquals(siNew.next(),Optional.of(2));\n\t\tassertEquals(siNew.next(),Optional.empty());\n\t\tassertEquals(si.next(),Optional.of(5));\n\t\tassertEquals(si.next(),Optional.empty());\n }\n\t\n\t// verification of the exception to the split in fromRangeNoSplit()\n\[email protected](expected = UnsupportedOperationException.class)\n\tpublic void testRangeNoSplit() {\n\t\tfinal SplitIterator<Integer> si = sif.fromRangeNoSplit(0, 3); \n\t\tassertEquals(si.next(),Optional.of(0));\n\t\tassertEquals(si.next(),Optional.of(1));\n\t\tassertEquals(si.next(),Optional.of(2));\n\t\tsi.split(); // must throw the exception\n }\n\t\n\t// basic verification of the map() method, which uses fromRange()\n\[email protected]\n public void optionalTestMap() {\n\t\tfinal SplitIterator<String> si = sif.map(sif.fromRange(0, 3),i -> \"s\"+i);\n\t\t// sif produces s0,s1,s2,s3, for mapping from 0,1,2,3\n\t\tassertEquals(si.next(),Optional.of(\"s0\"));\n\t\tassertEquals(si.next(),Optional.of(\"s1\"));\n\t\tassertEquals(si.next(),Optional.of(\"s2\"));\n\t\tassertEquals(si.next(),Optional.of(\"s3\"));\n\t\tassertEquals(si.next(),Optional.empty());\n }\n\t\n\t// advanced verification of the map() method, which uses fromRange()\n\[email protected]\n public void optionalTestMapAndSplit() {\n\t\t// checks that the SpliIterator created by map() supports splitting\n\t\tfinal SplitIterator<String> si = sif.map(sif.fromRange(0, 5),i -> \"s\"+i);\n\t\tassertEquals(si.next(),Optional.of(\"s0\"));\n\t\tfinal SplitIterator<String> siNew = si.split(); \n\t\tassertEquals(siNew.next(),Optional.of(\"s1\"));\n\t\tassertEquals(siNew.next(),Optional.of(\"s2\"));\n\t\tassertEquals(siNew.next(),Optional.empty());\n\t\tassertEquals(si.next(),Optional.of(\"s3\"));\n\t\tassertEquals(si.next(),Optional.of(\"s4\"));\n\t\tassertEquals(si.next(),Optional.of(\"s5\"));\n\t\tassertEquals(si.next(),Optional.empty());\n }\n\t\n\t// basic verification of fromList()\n\[email protected]\n public void testList() {\n\t\tfinal SplitIterator<Integer> si = sif.fromList(Arrays.asList(0,10,20,30,40)); \n\t\t// on this list, the iteration produces 0,10,20,30,40, and then nothing more\n\t\tassertEquals(si.next(),Optional.of(0));\n\t\tassertEquals(si.next(),Optional.of(10));\n\t\tassertEquals(si.next(),Optional.of(20));\n\t\tassertEquals(si.next(),Optional.of(30));\n\t\tassertEquals(si.next(),Optional.of(40));\n\t\tassertEquals(si.next(),Optional.empty());\n }\n\t\n\t// verification of splitting in fromList()\n\[email protected]\n public void testListAndSplit() {\n\t\t// note that everything goes as in the case of the range..\n\t\tfinal SplitIterator<Integer> si = sif.fromList(Arrays.asList(0,10,20,30,40,50)); \n\t\tassertEquals(si.next(),Optional.of(0));\n\t\tfinal SplitIterator<Integer> siNew = si.split(); \n\t\tassertEquals(siNew.next(),Optional.of(10));\n\t\tassertEquals(si.next(),Optional.of(30));\n\t\tassertEquals(si.next(),Optional.of(40));\n\t\tassertEquals(siNew.next(),Optional.of(20));\n\t\tassertEquals(siNew.next(),Optional.empty());\n\t\tassertEquals(si.next(),Optional.of(50));\n\t\tassertEquals(si.next(),Optional.empty());\n }\n\t\n\t// verification of the exception to the split in fromListNoSplit()\n\[email protected](expected = UnsupportedOperationException.class)\n\tpublic void testListNoSplit() {\n\t\tfinal SplitIterator<Integer> si = sif.fromListNoSplit(Arrays.asList(10,20,30)); \n\t\tassertEquals(si.next(),Optional.of(10));\n\t\tassertEquals(si.next(),Optional.of(20));\n\t\tsi.split();\n }\n\t\n\t// basic verification of excludedFirst()\n\[email protected]\n\tpublic void testExcludeFirst() {\n\t\tfinal SplitIterator<Integer> si = sif.fromList(Arrays.asList(10,20,30));\n\t\t// si would iterate on 10,20,30\n\t\tfinal SplitIterator<Integer> si2 = sif.excludeFirst(si);\n\t\t// si2 iterates on 20,30, because it excludes the first of si\n\t\tassertFalse(si == si2); // si2 is a new iterator!\n\t\tassertEquals(si2.next(),Optional.of(20));\n\t\tassertEquals(si2.next(),Optional.of(30));\n\t\tassertEquals(si2.next(),Optional.empty());\n }\n\t\n\t\n}", "filename": "Test.java" }
2018
a02a
[ { "content": "package a02a.sol1;\n\nimport java.util.*;\n\n\npublic interface Tournament {\n\t\n\t\n\tenum Result {\n\t\tWINNER, \n\t\tFINALIST, \n\t\tSEMIFINALIST, \n\t\tQUARTERFINALIST, \n\t\tPARTICIPANT \n\t}\n\t\n\t\n\tenum Type {\n\t\tMAJOR, \n\t\tATP1000, \n\t\tATP500, \n\t\tATP250 \n\t}\n\t\n\t\n\tType getType();\n\t\n\t\n\tString getName();\n\t\t\n\t\n\tOptional<Result> getResult(String player);\n\t\n\t\n\tString winner();\n\t\n\t\n\tMap<String,Integer> initialRanking();\n\t\n\t\n\tMap<String,Integer> resultingRanking();\n\t\n\t\n\tList<String> rank();\n}", "filename": "Tournament.java" }, { "content": "package a02a.sol1;\n\nimport java.util.Map;\n\n\npublic interface TournamentBuilder {\n\t\n\t\n\tTournamentBuilder setType(Tournament.Type type);\n\t\n\t\n\tTournamentBuilder setName(String name);\n\t\t\n\t\n\tTournamentBuilder setPriorRanking(Map<String,Integer> ranking);\n\t\n\t\n\tTournamentBuilder addResult(String player, Tournament.Result result);\n\t\n\t\n\tTournament build();\n}", "filename": "TournamentBuilder.java" }, { "content": "package 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 a02a.sol1;\n\nimport java.util.*;\nimport java.util.Map.Entry;\nimport java.util.stream.Collectors;\n\nimport a02a.sol1.Tournament.Result;\nimport a02a.sol1.Tournament.Type;\n\npublic class TournamentBuilderImpl implements TournamentBuilder {\n\t\n\t// codifico l'associazione torneo-punti in una costante, mediante l'inizializzatore non-statico\n\tprivate static final EnumMap<Type,Integer> TYPE_POINTS = new EnumMap<Type,Integer>(Type.class){{\n\t\tthis.put(Type.MAJOR, 2500);\n\t\tthis.put(Type.ATP1000, 1000);\n\t\tthis.put(Type.ATP500, 500);\n\t\tthis.put(Type.ATP250, 250);\n\t}};\n\t\n\t// codifico l'associazione risultato-percentuale di punti in una costante, mediante l'inizializzatore non-statico\n\tprivate static final EnumMap<Result,Double> RESULT_FACTOR = new EnumMap<Result,Double>(Result.class){{\n\t\tthis.put(Result.WINNER, 1.0);\n\t\tthis.put(Result.FINALIST, 0.5);\n\t\tthis.put(Result.SEMIFINALIST, 0.2);\n\t\tthis.put(Result.QUARTERFINALIST, 0.1);\n\t\tthis.put(Result.PARTICIPANT, 0.0);\n\t}};\n\t\n\t\n\tprivate Optional<Type> optType = Optional.empty();\n\tprivate Optional<String> optName = Optional.empty();\n\tprivate Optional<Map<String,Integer>> optInitialRanking = Optional.empty();\n\tprivate Optional<Map<String,Integer>> optFinalRanking = Optional.empty();\n\tprivate final Map<String,Result> results = new HashMap<>();\n\tprivate boolean built = false;\n\t\n\tprivate static void check(boolean b) {\n\t\tif (!b) {\n\t\t\tthrow new IllegalStateException();\n\t\t}\n\t\t\n\t}\n\t\n\tprivate static <X> Optional<X> reassignOptional(Optional<X> opt, X x) {\n\t\tcheck(!opt.isPresent());\n\t\treturn Optional.of(x);\n\t}\n\n\t@Override\n\tpublic TournamentBuilder setType(Type type) {\n\t\tcheck(!this.built);\n\t\tthis.optType = reassignOptional(this.optType,type);\n\t\treturn this;\n\t}\n\n\t@Override\n\tpublic TournamentBuilder setName(String name) {\n\t\tcheck(!this.built);\n\t\tthis.optName = reassignOptional(this.optName,name);\n\t\treturn this;\n\t}\n\n\t@Override\n\tpublic TournamentBuilder setPriorRanking(Map<String, Integer> ranking) {\n\t\tcheck(!this.built);\n\t\tthis.optInitialRanking = reassignOptional(this.optInitialRanking,new HashMap<>(ranking));\n\t\tthis.optFinalRanking = reassignOptional(this.optFinalRanking,new HashMap<>(ranking));\n\t\treturn this;\n\t}\n\n\t@Override\n\tpublic TournamentBuilder addResult(String player, Result result) {\n\t\tcheck(!this.built);\n\t\tcheck(this.optFinalRanking.isPresent());\n\t\tcheck(this.optType.isPresent());\n\t\tcheck(!this.results.containsKey(player));\t\t\n\t\tcheck(result != Result.WINNER || !this.results.containsValue(Result.WINNER));\t\t\n\t\tthis.results.put(player, result);\n\t\tint points = (int)(TYPE_POINTS.get(this.optType.get())*RESULT_FACTOR.get(result));\n\t\tthis.optFinalRanking.get().merge(player, points, (x,y)->x+y);\n\t\treturn this;\n\t}\n\t\n\t@Override\n\tpublic Tournament build() {\n\t\tcheck(!this.built);\n\t\tcheck(this.optName.isPresent());\n\t\tcheck(this.optType.isPresent());\n\t\tcheck(this.optFinalRanking.isPresent());\n\t\tcheck(this.results.containsValue(Result.WINNER));\n\t\tthis.built = true;\n\t\treturn new Tournament() {\n\t\t\t\n\t\t\tprivate Map<String,Integer> newRanking = Collections.unmodifiableMap(optFinalRanking.get());\n\n\t\t\t@Override\n\t\t\tpublic Type getType() {\n\t\t\t\treturn optType.get();\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic String getName() {\n\t\t\t\treturn optName.get();\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Optional<Result> getResult(String player) {\n\t\t\t\treturn Optional.ofNullable(results.get(player)).filter(c -> c!=null);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic String winner() {\n\t\t\t\tfor (Entry<String,Result> entry: results.entrySet()) {\n\t\t\t\t\tif (entry.getValue()==Result.WINNER) {\n\t\t\t\t\t\treturn entry.getKey();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tthrow new IllegalStateException();\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Map<String, Integer> initialRanking() {\n\t\t\t\treturn Collections.unmodifiableMap(optInitialRanking.get());\n\t\t\t}\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic Map<String, Integer> resultingRanking() {\n\t\t\t\treturn Collections.unmodifiableMap(optFinalRanking.get());\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic List<String> rank() {\n\t\t\t\treturn this.newRanking.entrySet().stream()\n\t\t\t\t\t\t .sorted((e1,e2)->e2.getValue().compareTo(e1.getValue()))\n\t\t\t\t\t\t .map(Entry::getKey)\n\t\t\t\t\t\t .collect(Collectors.toList());\n\t\t\t}\n\n\t\t};\n\t}\n\n}", "filename": "TournamentBuilderImpl.java" } ]
{ "components": { "imports": "package a02a.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;\n\nimport a02a.sol1.Tournament.Result;\nimport a02a.sol1.Tournament.Type;\n\n/**\n * Please consult the documentation of the provided interfaces:\n * - Tournament models the results of a Tennis Tournament\n * - TournamentBuilder models a builder (in the sense of the Builder pattern) for Tournament\n * \n * Note from the documentation how a tournament is of various types: for example, an ATP500 gives 500 points to the winner.\n * Note that the finalist (who loses in the final), the semi-finalist (who loses in the semi-final), etc., take\n * a different amount of points: for example, the finalist always takes 50% of the maximum points, so the\n * finalist of an ATP500 takes 250 points.\n * Note that when a tournament begins, each player already has points acquired in the past (written in initialRanking),\n * and after the tournament, they will consequently have more or the same points (written in resultingRanking). It will therefore be possible\n * after the tournament to see who is the top player (who has the most points), and so on -- the so-called \"ranking\".\n * \n * Implement TournamentBuilder through a TournamentBuilderImpl class with a constructor without arguments,\n * so that it passes all the tests below.\n * \n * The following are considered optional for the purpose of correcting the exercise, but still contribute to achieving\n * the totality of the score:\n * - implementation of optional tests (related to some checks for exceptions)\n * - the quality of the solution, in particular with minimization of repetitions and code not unnecessarily complex\n * \n * Scoring indications:\n * - correctness of the mandatory part: 9 points\n * - correctness of the optional part: 3 points\n * - quality of the solution: 5 points\n * \n * Remove the comment from the test code.\n */", "private_init": "\tprivate static final Map<String,Integer> INITIAL_RANKING = new HashMap<String,Integer>();\n\tstatic{\n\t\tINITIAL_RANKING.put(\"Nadal\", 6000);\n\t\tINITIAL_RANKING.put(\"Federer\", 7000);\n\t\tINITIAL_RANKING.put(\"Djokovic\", 6500);\n\t\tINITIAL_RANKING.put(\"Fognini\", 4000);\n\t}\n\t\n\t\n\tprivate TournamentBuilder tb;\n\t\n\[email protected]\n\tpublic void init() {\n\t\ttb = new TournamentBuilderImpl();\n\t}\n\t\n\t// basic check: ATP1000 of rome, with winner Federer (and so on for the others)", "test_functions": [ "\[email protected]\n public void basicTest() {\n\t\tTournament t = tb.setName(\"roma\")\n\t\t\t\t .setType(Type.ATP1000)\n\t\t\t\t .setPriorRanking(INITIAL_RANKING)\n\t\t\t\t .addResult(\"Federer\", Result.WINNER) // 1000 points\n\t\t\t\t .addResult(\"Nadal\", Result.FINALIST) // 500 points\n\t\t\t\t .addResult(\"Djokovic\", Result.SEMIFINALIST) // 200 points\n\t\t\t\t .addResult(\"Tsitsipas\", Result.QUARTERFINALIST) // 100 point\n\t\t\t\t .addResult(\"Fognini\", Result.PARTICIPANT) // 0 points\n\t\t\t\t .build();\n\t\tassertEquals(t.getName(),\"roma\");\n\t\tassertEquals(t.getType(),Type.ATP1000);\n\t\tassertEquals(t.getResult(\"Federer\"),Optional.of(Result.WINNER));\n\t\tassertEquals(t.getResult(\"Fognini\"),Optional.of(Result.PARTICIPANT));\n\t\tassertEquals(t.getResult(\"Del Potro\"),Optional.empty()); // did not participate\n\t\tassertEquals(t.initialRanking(),INITIAL_RANKING);\n\t\tassertEquals(t.resultingRanking().get(\"Federer\").intValue(),1000+7000);\n\t\tassertEquals(t.resultingRanking().get(\"Nadal\").intValue(),500+6000);\n\t\tassertEquals(t.resultingRanking().get(\"Djokovic\").intValue(),200+6500);\n\t\tassertEquals(t.resultingRanking().get(\"Fognini\").intValue(),4000);\n\t\tassertEquals(t.resultingRanking().get(\"Tsitsipas\").intValue(),100);\n\t\tassertEquals(t.winner(),\"Federer\");\n\t\t// final ranking of the players after the tournament, from who has the most points overall, down\n\t\tassertEquals(t.rank(),Arrays.asList(\"Federer\",\"Djokovic\",\"Nadal\",\"Fognini\",\"Tsitsipas\"));\n }", "\[email protected]\n public void anotherTest() {\n\t\tTournament t = tb.setName(\"melbourne\")\n\t\t\t\t .setType(Type.MAJOR)\n\t\t\t\t .setPriorRanking(INITIAL_RANKING)\n\t\t\t\t .addResult(\"Djokovic\", Result.WINNER) // 2500 points\n\t\t\t\t .addResult(\"Nadal\", Result.FINALIST) // 1250 points\n\t\t\t\t .addResult(\"Tsitsipas\", Result.SEMIFINALIST) // 500 point\n\t\t\t\t .addResult(\"Federer\", Result.QUARTERFINALIST) // 250 points\n\t\t\t\t .build();\n\t\tassertEquals(t.getName(),\"melbourne\");\n\t\tassertEquals(t.getType(),Type.MAJOR);\n\t\tassertEquals(t.getResult(\"Djokovic\"),Optional.of(Result.WINNER));\n\t\tassertEquals(t.getResult(\"Nadal\"),Optional.of(Result.FINALIST));\n\t\tassertEquals(t.initialRanking(),INITIAL_RANKING);\n\t\tassertEquals(t.resultingRanking().get(\"Federer\").intValue(),250+7000);\n\t\tassertEquals(t.resultingRanking().get(\"Nadal\").intValue(),1250+6000);\n\t\tassertEquals(t.resultingRanking().get(\"Djokovic\").intValue(),2500+6500);\n\t\tassertEquals(t.resultingRanking().get(\"Fognini\").intValue(),4000);\n\t\tassertEquals(t.resultingRanking().get(\"Tsitsipas\").intValue(),500);\n\t\tassertEquals(t.winner(),\"Djokovic\");\n\t\tassertEquals(t.rank(),Arrays.asList(\"Djokovic\",\"Federer\",\"Nadal\",\"Fognini\",\"Tsitsipas\"));\n }" ] }, "content": "package a02a.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;\n\nimport a02a.sol1.Tournament.Result;\nimport a02a.sol1.Tournament.Type;\n\n/**\n * Please consult the documentation of the provided interfaces:\n * - Tournament models the results of a Tennis Tournament\n * - TournamentBuilder models a builder (in the sense of the Builder pattern) for Tournament\n * \n * Note from the documentation how a tournament is of various types: for example, an ATP500 gives 500 points to the winner.\n * Note that the finalist (who loses in the final), the semi-finalist (who loses in the semi-final), etc., take\n * a different amount of points: for example, the finalist always takes 50% of the maximum points, so the\n * finalist of an ATP500 takes 250 points.\n * Note that when a tournament begins, each player already has points acquired in the past (written in initialRanking),\n * and after the tournament, they will consequently have more or the same points (written in resultingRanking). It will therefore be possible\n * after the tournament to see who is the top player (who has the most points), and so on -- the so-called \"ranking\".\n * \n * Implement TournamentBuilder through a TournamentBuilderImpl class with a constructor without arguments,\n * so that it passes all the tests below.\n * \n * The following are considered optional for the purpose of correcting the exercise, but still contribute to achieving\n * the totality of the score:\n * - implementation of optional tests (related to some checks for exceptions)\n * - the quality of the solution, in particular with minimization of repetitions and code not unnecessarily complex\n * \n * Scoring indications:\n * - correctness of the mandatory part: 9 points\n * - correctness of the optional part: 3 points\n * - quality of the solution: 5 points\n * \n * Remove the comment from the test code.\n */\n\npublic class Test {\n\t\n\tprivate static final Map<String,Integer> INITIAL_RANKING = new HashMap<String,Integer>();\n\tstatic{\n\t\tINITIAL_RANKING.put(\"Nadal\", 6000);\n\t\tINITIAL_RANKING.put(\"Federer\", 7000);\n\t\tINITIAL_RANKING.put(\"Djokovic\", 6500);\n\t\tINITIAL_RANKING.put(\"Fognini\", 4000);\n\t}\n\t\n\t\n\tprivate TournamentBuilder tb;\n\t\n\[email protected]\n\tpublic void init() {\n\t\ttb = new TournamentBuilderImpl();\n\t}\n\t\n\t// basic check: ATP1000 of rome, with winner Federer (and so on for the others)\n\[email protected]\n public void basicTest() {\n\t\tTournament t = tb.setName(\"roma\")\n\t\t\t\t .setType(Type.ATP1000)\n\t\t\t\t .setPriorRanking(INITIAL_RANKING)\n\t\t\t\t .addResult(\"Federer\", Result.WINNER) // 1000 points\n\t\t\t\t .addResult(\"Nadal\", Result.FINALIST) // 500 points\n\t\t\t\t .addResult(\"Djokovic\", Result.SEMIFINALIST) // 200 points\n\t\t\t\t .addResult(\"Tsitsipas\", Result.QUARTERFINALIST) // 100 point\n\t\t\t\t .addResult(\"Fognini\", Result.PARTICIPANT) // 0 points\n\t\t\t\t .build();\n\t\tassertEquals(t.getName(),\"roma\");\n\t\tassertEquals(t.getType(),Type.ATP1000);\n\t\tassertEquals(t.getResult(\"Federer\"),Optional.of(Result.WINNER));\n\t\tassertEquals(t.getResult(\"Fognini\"),Optional.of(Result.PARTICIPANT));\n\t\tassertEquals(t.getResult(\"Del Potro\"),Optional.empty()); // did not participate\n\t\tassertEquals(t.initialRanking(),INITIAL_RANKING);\n\t\tassertEquals(t.resultingRanking().get(\"Federer\").intValue(),1000+7000);\n\t\tassertEquals(t.resultingRanking().get(\"Nadal\").intValue(),500+6000);\n\t\tassertEquals(t.resultingRanking().get(\"Djokovic\").intValue(),200+6500);\n\t\tassertEquals(t.resultingRanking().get(\"Fognini\").intValue(),4000);\n\t\tassertEquals(t.resultingRanking().get(\"Tsitsipas\").intValue(),100);\n\t\tassertEquals(t.winner(),\"Federer\");\n\t\t// final ranking of the players after the tournament, from who has the most points overall, down\n\t\tassertEquals(t.rank(),Arrays.asList(\"Federer\",\"Djokovic\",\"Nadal\",\"Fognini\",\"Tsitsipas\"));\n }\n\t\n\t// analogous check: MAJOR in melbourne, with winner Djokovic\n\[email protected]\n public void anotherTest() {\n\t\tTournament t = tb.setName(\"melbourne\")\n\t\t\t\t .setType(Type.MAJOR)\n\t\t\t\t .setPriorRanking(INITIAL_RANKING)\n\t\t\t\t .addResult(\"Djokovic\", Result.WINNER) // 2500 points\n\t\t\t\t .addResult(\"Nadal\", Result.FINALIST) // 1250 points\n\t\t\t\t .addResult(\"Tsitsipas\", Result.SEMIFINALIST) // 500 point\n\t\t\t\t .addResult(\"Federer\", Result.QUARTERFINALIST) // 250 points\n\t\t\t\t .build();\n\t\tassertEquals(t.getName(),\"melbourne\");\n\t\tassertEquals(t.getType(),Type.MAJOR);\n\t\tassertEquals(t.getResult(\"Djokovic\"),Optional.of(Result.WINNER));\n\t\tassertEquals(t.getResult(\"Nadal\"),Optional.of(Result.FINALIST));\n\t\tassertEquals(t.initialRanking(),INITIAL_RANKING);\n\t\tassertEquals(t.resultingRanking().get(\"Federer\").intValue(),250+7000);\n\t\tassertEquals(t.resultingRanking().get(\"Nadal\").intValue(),1250+6000);\n\t\tassertEquals(t.resultingRanking().get(\"Djokovic\").intValue(),2500+6500);\n\t\tassertEquals(t.resultingRanking().get(\"Fognini\").intValue(),4000);\n\t\tassertEquals(t.resultingRanking().get(\"Tsitsipas\").intValue(),500);\n\t\tassertEquals(t.winner(),\"Djokovic\");\n\t\tassertEquals(t.rank(),Arrays.asList(\"Djokovic\",\"Federer\",\"Nadal\",\"Fognini\",\"Tsitsipas\"));\n }\n\t\n\t// From here on, tests on exception situations: the name of the test is self-explanatory\n\t// Some are optional\n\t\n\[email protected](expected = IllegalStateException.class)\n\tpublic void testNoTypeSpecified() {\n\t\tTournament t = tb.setName(\"melbourne\")\n\t\t .setPriorRanking(INITIAL_RANKING)\n\t\t .addResult(\"Djokovic\", Result.WINNER) \n\t\t .addResult(\"Nadal\", Result.FINALIST) \n\t\t .addResult(\"Tsitsipas\", Result.SEMIFINALIST) \n\t\t .addResult(\"Federer\", Result.QUARTERFINALIST) \n\t\t .build();\n }\n\t\n\[email protected](expected = IllegalStateException.class)\n\tpublic void testTournamentCantBeBuiltTwice() {\n\t\tTournamentBuilder tb2 = tb.setName(\"melbourne\")\n\t\t .setType(Type.MAJOR)\n\t\t .setPriorRanking(INITIAL_RANKING)\n\t\t .addResult(\"Djokovic\", Result.WINNER) \n\t\t .addResult(\"Nadal\", Result.FINALIST) \n\t\t .addResult(\"Tsitsipas\", Result.SEMIFINALIST) \n\t\t .addResult(\"Federer\", Result.QUARTERFINALIST); \n\t\ttb2.build();\n\t\ttb2.build();\n\t}\n\t\n\[email protected](expected = IllegalStateException.class)\n\tpublic void optionalTestNoNameSpecified() {\n\t\tTournament t = tb.setType(Type.MAJOR)\n\t\t .setPriorRanking(INITIAL_RANKING)\n\t\t .addResult(\"Djokovic\", Result.WINNER) \n\t\t .addResult(\"Nadal\", Result.FINALIST) \n\t\t .addResult(\"Tsitsipas\", Result.SEMIFINALIST) \n\t\t .addResult(\"Federer\", Result.QUARTERFINALIST) \n\t\t .build();\n\t}\n\t\n\[email protected](expected = IllegalStateException.class)\n\tpublic void optionalTestNoRankingSpecified() {\n\t\tTournament t = tb.setName(\"roma\")\n\t\t\t\t .setType(Type.MAJOR)\n\t\t .addResult(\"Djokovic\", Result.WINNER) \n\t\t .addResult(\"Nadal\", Result.FINALIST) \n\t\t .addResult(\"Tsitsipas\", Result.SEMIFINALIST) \n\t\t .addResult(\"Federer\", Result.QUARTERFINALIST) \n\t\t .build();\n\t}\n\n\t\n\[email protected](expected = IllegalStateException.class)\n\tpublic void optionalTestCantAddResultBeforeType() {\n\t\tTournament t = tb.setName(\"melbourne\")\n\t\t .setPriorRanking(INITIAL_RANKING)\n\t\t .addResult(\"Djokovic\", Result.WINNER) \n\t\t .setType(Type.MAJOR)\n\t\t .addResult(\"Nadal\", Result.FINALIST) \n\t\t .addResult(\"Tsitsipas\", Result.SEMIFINALIST) \n\t\t .addResult(\"Federer\", Result.QUARTERFINALIST)\n\t\t .build(); \n\t}\n\t\n\[email protected](expected = IllegalStateException.class)\n\tpublic void optionalTestCantAddResultTwice() {\n\t\tTournament t = tb.setName(\"melbourne\")\n\t\t .setPriorRanking(INITIAL_RANKING)\n\t\t .setType(Type.MAJOR)\n\t\t .addResult(\"Djokovic\", Result.WINNER) \n\t\t .addResult(\"Djokovic\", Result.FINALIST) \n\t\t .build();\n\t}\n\n\[email protected](expected = IllegalStateException.class)\n\tpublic void optionalTestCantAddWinnerTwice() {\n\t\tTournament t = tb.setName(\"melbourne\")\n\t\t .setPriorRanking(INITIAL_RANKING)\n\t\t .setType(Type.MAJOR)\n\t\t .addResult(\"Djokovic\", Result.WINNER) \n\t\t .addResult(\"Nadal\", Result.WINNER) \n\t\t .build(); \n\t}\n\t\n\[email protected](expected = NullPointerException.class)\n\tpublic void optionalTypeCantBeNull() {\n\t\tTournament t = tb.setName(\"melbourne\")\n\t\t .setPriorRanking(INITIAL_RANKING)\n\t\t .setType(null)\n\t\t .build(); \n\t}\n}", "filename": "Test.java" }
2018
a05
[ { "content": "package a05.sol1;\n\nimport java.util.List;\nimport java.util.Optional;\n\n\npublic interface PowerIterator<T> {\n\n\t\n\tOptional<T> next();\n\t\n\t\n\tList<T> allSoFar();\n\t\n\t\n\t\n\tPowerIterator<T> reversed();\n}", "filename": "PowerIterator.java" }, { "content": "package a05.sol1;\n\nimport java.util.*;\nimport java.util.function.UnaryOperator;\n\n\n\ninterface PowerIteratorsFactory {\n \n \n PowerIterator<Integer> incremental(int start, UnaryOperator<Integer> successive);\n \n \n <X> PowerIterator<X> fromList(List<X> list);\n \n \n PowerIterator<Boolean> randomBooleans(int size);\n}", "filename": "PowerIteratorsFactory.java" } ]
[ { "content": "package a05.sol1;\n\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Optional;\nimport java.util.Random;\nimport java.util.function.Function;\nimport java.util.function.UnaryOperator;\nimport java.util.stream.Stream;\n\npublic class PowerIteratorsFactoryImpl implements PowerIteratorsFactory {\n\t\n\tprivate <X> PowerIterator<X> fromStream(final Stream<X> stream){\n\t\tfinal Iterator<X> iterator = stream.iterator();\n\t\treturn new PowerIterator<X>() {\n\t\t\t\n\t\t\tprivate List<X> pastList = new ArrayList<>();\n\t\n\t\t\t@Override\n\t\t\tpublic Optional<X> next() {\n\t\t\t\tX x = null;\n\t\t\t\tif (iterator.hasNext()) {\n\t\t\t\t\tx = iterator.next();\n\t\t\t\t\tpastList.add(x);\n\t\t\t\t}\n\t\t\t\treturn Optional.ofNullable(x);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic List<X> allSoFar() {\n\t\t\t\treturn Collections.unmodifiableList(this.pastList);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic PowerIterator<X> reversed(){\n\t\t\t\tfinal List<X> list = new ArrayList<>(pastList);\n\t\t\t\tCollections.reverse(list);\n\t\t\t\treturn fromStream(list.stream());\n\t\t\t}\n\t\t};\n\t}\n\n\t@Override\n\tpublic PowerIterator<Integer> incremental(int start, UnaryOperator<Integer> successive) {\n\t\treturn this.fromStream(Stream.iterate(start,successive));\n\t}\n\n\t@Override\n\tpublic <X> PowerIterator<X> fromList(List<X> list) {\n\t\treturn this.fromStream(list.stream());\n\t}\n\n\t@Override\n\tpublic PowerIterator<Boolean> randomBooleans(int size) {\n\t\tfinal Random random = new Random();\n\t\treturn this.fromStream(Stream.generate(()->random.nextBoolean()).limit(size));\n\t}\n\n}", "filename": "PowerIteratorsFactoryImpl.java" } ]
{ "components": { "imports": "package a05.sol1;\n\nimport static org.junit.Assert.*;\nimport org.hamcrest.CoreMatchers;\nimport org.hamcrest.CoreMatchers.*;\nimport java.util.*;\n\n/**\n * Consult the documentation of the PowerIteratorsFactory interface: it models a factory to\n * create various objects of type PowerIterator<X>, which in turn represents an iterator of elements of type X,\n * with methods to access the elements already produced (in the past).\n * \n * The following are considered optional for the purpose of being able to correct the exercise, but still contribute to achieving \n * the totality of the score:\n * - implementation of optional tests (named 'optionalTestXYZ') \n * - minimization of repetitions\n * - minimization of memory waste, allocating objects of possibly large sizes unnecessarily\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 * Scoring indications:\n * - correctness of the mandatory part: 9 points\n * - correctness of the optional part: 4 points\n * - quality of the solution: 4 points\n * \n * Remove the comment from the test code.\n */", "private_init": "\tprivate PowerIteratorsFactory factory;\n\t\n\[email protected]\n\tpublic void init() {\n\t\tthis.factory = new PowerIteratorsFactoryImpl(); // class to create\n\t}", "test_functions": [ "\[email protected]\n public void testIncremental() {\n \tPowerIterator<Integer> pi = factory.incremental(5,x->x+2); // pi produces 5,7,9,11,13,...\n assertEquals(pi.next(),Optional.of(5));\n assertEquals(pi.next(),Optional.of(7));\n assertEquals(pi.next(),Optional.of(9));\n assertEquals(pi.next(),Optional.of(11));\n assertEquals(pi.allSoFar(),Arrays.asList(5,7,9,11)); // elements already produced\n for (int i = 0; i < 10; i++) {\n \tpi.next(); // I proceed forward for a while..\n }", "\[email protected]\n public void testRandom() { // semi-automatic, prints to video will also be checked \n \tPowerIterator<Boolean> pi = factory.randomBooleans(4); // pi produces 4 random booleans\n \tboolean b1 = pi.next().get();\n \tboolean b2 = pi.next().get();\n \tboolean b3 = pi.next().get();\n \tboolean b4 = pi.next().get();\n \tSystem.out.println(b1+ \" \"+b2+ \" \"+b3+ \" \"+b4); // I print to video.. just to see if they are really random..\n assertFalse(pi.next().isPresent()); // I have already produced 4, so the next one is an empty optional\n assertEquals(pi.allSoFar(),Arrays.asList(b1,b2,b3,b4)); // I produced exactly b1,b2,b3,b4\n }", "\[email protected]\n public void testFromList() { \n \tPowerIterator<String> pi = factory.fromList(Arrays.asList(\"a\",\"b\",\"c\")); // pi produces a,b,c\n \tassertEquals(pi.next(),Optional.of(\"a\"));\n assertEquals(pi.next(),Optional.of(\"b\"));\n assertEquals(pi.allSoFar(),Arrays.asList(\"a\",\"b\")); // so far a,b\n assertEquals(pi.next(),Optional.of(\"c\"));\n assertEquals(pi.allSoFar(),Arrays.asList(\"a\",\"b\",\"c\")); // so far a,b,c\n assertFalse(pi.next().isPresent()); // there is nothing more to produce\n }", "\[email protected]\n public void optionalTestReversedOnList() { \n \tPowerIterator<String> pi = factory.fromList(Arrays.asList(\"a\",\"b\",\"c\"));\n \tassertEquals(pi.next(),Optional.of(\"a\"));\n assertEquals(pi.next(),Optional.of(\"b\"));\n PowerIterator<String> pi2 = pi.reversed(); //pi2 iterates on b,a\n assertEquals(pi.next(),Optional.of(\"c\")); // c is produced by pi normally\n assertFalse(pi.next().isPresent());\n \n assertEquals(pi2.next(),Optional.of(\"b\"));\n assertEquals(pi2.next(),Optional.of(\"a\"));\n assertEquals(pi2.allSoFar(),Arrays.asList(\"b\",\"a\")); // pi2 produced b,a\n assertFalse(pi2.next().isPresent()); \n }", "\[email protected]\n public void optionalTestReversedOnIncremental() { \n \tPowerIterator<Integer> pi = factory.incremental(0,x->x+1); // 0,1,2,3,...\n \tassertEquals(pi.next(),Optional.of(0));\n assertEquals(pi.next(),Optional.of(1));\n assertEquals(pi.next(),Optional.of(2));\n assertEquals(pi.next(),Optional.of(3));\n PowerIterator<Integer> pi2 = pi.reversed(); // pi2 iterates on 3,2,1,0\n assertEquals(pi2.next(),Optional.of(3));\n assertEquals(pi2.next(),Optional.of(2));\n PowerIterator<Integer> pi3 = pi2.reversed(); // pi2 produced 3,2 in the past, so pi3 iterates on 2,3\n assertEquals(pi3.next(),Optional.of(2));\n assertEquals(pi3.next(),Optional.of(3));\n assertFalse(pi3.next().isPresent()); \n }" ] }, "content": "package a05.sol1;\n\nimport static org.junit.Assert.*;\nimport org.hamcrest.CoreMatchers;\nimport org.hamcrest.CoreMatchers.*;\nimport java.util.*;\n\n/**\n * Consult the documentation of the PowerIteratorsFactory interface: it models a factory to\n * create various objects of type PowerIterator<X>, which in turn represents an iterator of elements of type X,\n * with methods to access the elements already produced (in the past).\n * \n * The following are considered optional for the purpose of being able to correct the exercise, but still contribute to achieving \n * the totality of the score:\n * - implementation of optional tests (named 'optionalTestXYZ') \n * - minimization of repetitions\n * - minimization of memory waste, allocating objects of possibly large sizes unnecessarily\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 * Scoring indications:\n * - correctness of the mandatory part: 9 points\n * - correctness of the optional part: 4 points\n * - quality of the solution: 4 points\n * \n * Remove the comment from the test code.\n */\n\n\npublic class Test {\n\t\n\tprivate PowerIteratorsFactory factory;\n\t\n\[email protected]\n\tpublic void init() {\n\t\tthis.factory = new PowerIteratorsFactoryImpl(); // class to create\n\t}\n \n \n @org.junit.Test\n public void testIncremental() {\n \tPowerIterator<Integer> pi = factory.incremental(5,x->x+2); // pi produces 5,7,9,11,13,...\n assertEquals(pi.next(),Optional.of(5));\n assertEquals(pi.next(),Optional.of(7));\n assertEquals(pi.next(),Optional.of(9));\n assertEquals(pi.next(),Optional.of(11));\n assertEquals(pi.allSoFar(),Arrays.asList(5,7,9,11)); // elements already produced\n for (int i = 0; i < 10; i++) {\n \tpi.next(); // I proceed forward for a while..\n }\n assertEquals(pi.next(),Optional.of(33)); // I arrived at 33\n }\n \n @org.junit.Test\n public void testRandom() { // semi-automatic, prints to video will also be checked \n \tPowerIterator<Boolean> pi = factory.randomBooleans(4); // pi produces 4 random booleans\n \tboolean b1 = pi.next().get();\n \tboolean b2 = pi.next().get();\n \tboolean b3 = pi.next().get();\n \tboolean b4 = pi.next().get();\n \tSystem.out.println(b1+ \" \"+b2+ \" \"+b3+ \" \"+b4); // I print to video.. just to see if they are really random..\n assertFalse(pi.next().isPresent()); // I have already produced 4, so the next one is an empty optional\n assertEquals(pi.allSoFar(),Arrays.asList(b1,b2,b3,b4)); // I produced exactly b1,b2,b3,b4\n }\n \n @org.junit.Test\n public void testFromList() { \n \tPowerIterator<String> pi = factory.fromList(Arrays.asList(\"a\",\"b\",\"c\")); // pi produces a,b,c\n \tassertEquals(pi.next(),Optional.of(\"a\"));\n assertEquals(pi.next(),Optional.of(\"b\"));\n assertEquals(pi.allSoFar(),Arrays.asList(\"a\",\"b\")); // so far a,b\n assertEquals(pi.next(),Optional.of(\"c\"));\n assertEquals(pi.allSoFar(),Arrays.asList(\"a\",\"b\",\"c\")); // so far a,b,c\n assertFalse(pi.next().isPresent()); // there is nothing more to produce\n }\n \n @org.junit.Test\n public void optionalTestReversedOnList() { \n \tPowerIterator<String> pi = factory.fromList(Arrays.asList(\"a\",\"b\",\"c\"));\n \tassertEquals(pi.next(),Optional.of(\"a\"));\n assertEquals(pi.next(),Optional.of(\"b\"));\n PowerIterator<String> pi2 = pi.reversed(); //pi2 iterates on b,a\n assertEquals(pi.next(),Optional.of(\"c\")); // c is produced by pi normally\n assertFalse(pi.next().isPresent());\n \n assertEquals(pi2.next(),Optional.of(\"b\"));\n assertEquals(pi2.next(),Optional.of(\"a\"));\n assertEquals(pi2.allSoFar(),Arrays.asList(\"b\",\"a\")); // pi2 produced b,a\n assertFalse(pi2.next().isPresent()); \n }\n \n @org.junit.Test\n public void optionalTestReversedOnIncremental() { \n \tPowerIterator<Integer> pi = factory.incremental(0,x->x+1); // 0,1,2,3,...\n \tassertEquals(pi.next(),Optional.of(0));\n assertEquals(pi.next(),Optional.of(1));\n assertEquals(pi.next(),Optional.of(2));\n assertEquals(pi.next(),Optional.of(3));\n PowerIterator<Integer> pi2 = pi.reversed(); // pi2 iterates on 3,2,1,0\n assertEquals(pi2.next(),Optional.of(3));\n assertEquals(pi2.next(),Optional.of(2));\n PowerIterator<Integer> pi3 = pi2.reversed(); // pi2 produced 3,2 in the past, so pi3 iterates on 2,3\n assertEquals(pi3.next(),Optional.of(2));\n assertEquals(pi3.next(),Optional.of(3));\n assertFalse(pi3.next().isPresent()); \n }\n \n}", "filename": "Test.java" }
2018
a03b
[ { "content": "package a03b.sol1;\n\nimport java.util.*;\n\n\npublic interface ConferenceReviewing {\n\t\n\t\n\tenum Question {\n\t\tRELEVANCE, \n\t\tSIGNIFICANCE, \t\n\t\tCONFIDENCE, \t\n\t\tFINAL; \t\n\t}\n\t\t\n\t\n\tvoid loadReview(int article, Map<Question,Integer> scores);\n\t\n\t\n\tvoid loadReview(int article, int relevance, int significance, int confidence, int fin);\n\t\n\t\n\tList<Integer> orderedScores(int article, Question question);\n\t\n\t\n\tdouble averageFinalScore(int article);\n\t\n\t\n\tSet<Integer> acceptedArticles();\n\t\n\t\n\t\n\tList<Pair<Integer,Double>> sortedAcceptedArticles();\n\t\n\t\n\tMap<Integer, Double> averageWeightedFinalScoreMap();\n}", "filename": "ConferenceReviewing.java" }, { "content": "package a03b.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 a03b.sol1;\n\nimport java.util.*;\nimport java.util.function.Function;\nimport java.util.stream.Collectors;\n\npublic class ConferenceReviewingImpl implements ConferenceReviewing {\n\t\n\tprivate final List<Pair<Integer,Map<Question, Integer>>> reviews = new ArrayList<>();\n\n\t@Override\n\tpublic void loadReview(int article, Map<Question, Integer> scores) {\n\t\tif (scores.size() < Question.values().length) {\n\t\t\tthrow new IllegalArgumentException();\n\t\t}\n\t\treviews.add(new Pair<>(article,new EnumMap<>(scores)));\n\t}\n\n\t@Override\n\tpublic void loadReview(int article, int relevance, int significance, int confidence, int fin) {\n\t\tMap<Question,Integer> map = new EnumMap<>(Question.class);\n\t\tmap.put(Question.RELEVANCE, relevance);\n\t\tmap.put(Question.SIGNIFICANCE, significance);\n\t\tmap.put(Question.CONFIDENCE, confidence);\n\t\tmap.put(Question.FINAL, fin);\n\t\treviews.add(new Pair<>(article,map));\n\t}\n\t\n\t@Override\n\tpublic List<Integer> orderedScores(int article, Question question) {\n\t\treturn reviews.stream()\n\t\t\t\t .filter(p -> p.getX() == article)\n\t\t\t\t .map(p -> p.getY().get(question))\n\t\t\t\t .sorted()\n\t\t\t\t .collect(Collectors.toList());\n\t}\n\t\n\t@Override\n\tpublic double averageFinalScore(int article) {\n\t\treturn reviews.stream()\n\t\t\t .filter(p -> p.getX() == article)\n\t\t\t .mapToInt(p -> p.getY().get(Question.FINAL))\n\t\t\t .average()\n\t\t\t .getAsDouble();\n\t}\n\t\n\tprivate boolean accepted(int article) {\n\t\treturn averageFinalScore(article) > 5.0 && \n\t\t\t reviews.stream()\n\t\t\t .filter(p -> p.getX()==article)\n\t\t\t .map(Pair::getY)\n\t\t\t .map(Map::entrySet)\n\t\t\t .flatMap(Set::stream)\n\t\t\t .anyMatch(e -> e.getKey()==Question.RELEVANCE && e.getValue() >= 8);\n\t}\n\n\t@Override\n\tpublic Set<Integer> acceptedArticles() {\n\t\treturn reviews.stream()\n\t\t\t\t .map(Pair::getX)\n\t\t\t\t .distinct()\n\t\t\t\t .filter(this::accepted)\n\t\t\t\t .collect(Collectors.toSet());\n\t}\n\n\t@Override\n\tpublic List<Pair<Integer,Double>> sortedAcceptedArticles() {\n\t\treturn this.acceptedArticles()\n\t\t\t\t .stream()\n\t\t\t\t .map(e -> new Pair<>(e,this.averageFinalScore(e)))\n\t\t\t\t .sorted((e1,e2)->e1.getY().compareTo(e2.getY()))\n\t\t\t\t .collect(Collectors.toList());\n\t}\n\t\n\tprivate double averageWeightedFinalScore(int article) {\n\t\treturn reviews.stream()\n\t\t\t\t .filter(p -> p.getX() == article)\n\t\t\t\t .mapToDouble(p -> p.getY().get(Question.FINAL) * p.getY().get(Question.CONFIDENCE) / 10.0)\n\t\t\t\t .average().getAsDouble();\n\t}\n\n\t@Override\n\tpublic Map<Integer, Double> averageWeightedFinalScoreMap() {\n\t\treturn reviews.stream()\n\t\t\t\t .map(Pair::getX)\n\t\t\t\t .distinct()\n\t\t\t\t .collect(Collectors.toMap(Function.identity(), this::averageWeightedFinalScore));\n\t}\n\n\n}", "filename": "ConferenceReviewingImpl.java" } ]
{ "components": { "imports": "package a03b.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;\n\nimport a03b.sol1.ConferenceReviewing.Question;\n\n/**\n * Consult the documentation of the ConferenceReviewing interface, which models the results of the review process\n * of conference articles. Each article is reviewed by one or more anonymous reviewers, each of whom provides\n * a score from 0 to 10 for 4 different \"questions\", modeled by ConferenceReviewing.Question. An article is\n * accepted if the average value of the score for the \"FINAL\" question is >5 and if it has at least one \"RELEVANCE\" score >= 8.\n *\n * Implement ConferenceReviewing through a ConferenceReviewingImpl class with a constructor without arguments,\n * so that it passes all the tests below, designed to be self-explanatory.\n *\n * The following are considered optional for the purpose of being able to correct the exercise, but still contribute to achieving\n * the totality of the score:\n * - implementation of optional tests (related to the implementation of the averageWeightedFinalScoreMap method)\n * - the quality of the solution, in particular with minimization of repetitions and code that is not unnecessarily complex\n *\n * Scoring indications:\n * - correctness of the mandatory part: 9 points\n * - correctness of the optional part: 4 points\n * - quality of the solution: 4 points\n *\n * Remove the comment from the test code.\n */", "private_init": "\tprivate ConferenceReviewing cr;\n\n\t// this method instantiates ConferenceReviewing and loads some reviews into it\n\[email protected]\n\tpublic void init() {\n\t\tthis.cr = new ConferenceReviewingImpl();\n\t\t// load a review for article 1:\n\t\t// - 8 for relevance, significance and final\n\t\t// - 7 for confidence\n\t\t// remember that the order of the questions is: relevance, significance, confidence, final\n\t\tcr.loadReview(1, 8, 8, 6, 8); // 4.8 is the weighted final score (used by averageWeightedFinalScoreMap)\n\t\t// and similar for the others\n\t\tcr.loadReview(1, 9, 9, 6, 9); // 5.4\n\t\tcr.loadReview(2, 9, 9, 10, 9); // 9.0\n\t\tcr.loadReview(2, 4, 6, 10, 6); // 6.0\n\t\tcr.loadReview(3, 3, 3, 3, 3); // 0.9\n\t\tcr.loadReview(3, 4, 4, 4, 4); // 1.6\n\t\tcr.loadReview(4, 6, 6, 6, 6); // 3.6\n\t\tcr.loadReview(4, 7, 7, 8, 7); // 5.6\n\t\tMap<Question,Integer> map = new EnumMap<>(Question.class);\n\t\tmap.put(Question.RELEVANCE, 8);\n\t\tmap.put(Question.SIGNIFICANCE, 8);\n\t\tmap.put(Question.CONFIDENCE, 7); // 5.6\n\t\tmap.put(Question.FINAL, 8);\n\t\tcr.loadReview(4,map);\n\t\tcr.loadReview(5, 6, 6, 6, 10); // 6.0\n\t\tcr.loadReview(5, 7, 7, 7, 10); // 7.0\n\t}", "test_functions": [ "\[email protected]\n\tpublic void testOrderedScores() {\n\t\t// article 2 received the two scores 4,9 on RELEVANCE\n\t\tassertEquals(cr.orderedScores(2, Question.RELEVANCE),Arrays.asList(4,9));\n\t\t// and similar for the others\n\t\tassertEquals(cr.orderedScores(4, Question.CONFIDENCE),Arrays.asList(6,7,8));\n\t\tassertEquals(cr.orderedScores(5, Question.FINAL),Arrays.asList(10,10));\n\t}", "\[email protected]\n\tpublic void testAverageFinalScore() {\n\t\t// article 1 has an average score on FINAL equal to 8.5, with a maximum deviation of 0.01\n\t\tassertEquals(cr.averageFinalScore(1),8.5,0.01);\n\t\t// and similar for the others\n\t\tassertEquals(cr.averageFinalScore(2),7.5,0.01);\n\t\tassertEquals(cr.averageFinalScore(3),3.5,0.01);\n\t\tassertEquals(cr.averageFinalScore(4),7.0,0.01);\n\t\tassertEquals(cr.averageFinalScore(5),10.0,0.01);\n\t}", "\[email protected]\n\tpublic void testAcceptedArticles() {\n\t\t// only articles 1,2,4 should be accepted, having a final average >=5 and at least one score on RELEVANCE >= 8\n\t\tassertEquals(cr.acceptedArticles(),new HashSet<>(Arrays.asList(1,2,4)));\n\t}", "\[email protected]\n\tpublic void testSortedAcceptedArticles() {\n\t\t// accepted articles, and their average final score\n\t\tassertEquals(cr.sortedAcceptedArticles(),Arrays.asList(new Pair<>(4,7.0),new Pair<>(2,7.5),new Pair<>(1,8.5)));\n\t}", "\[email protected]\n\tpublic void optionalTestAverageWeightedFinalScore() {\n\t\t// article 1 has a weighted final average equal to (4.8+5.4)/2 = 5.1, with a maximum deviation of 0.01\n\t\tassertEquals(cr.averageWeightedFinalScoreMap().get(1),(4.8+5.4)/2,0.01);\n\t\t// and similar for the others\n\t\tassertEquals(cr.averageWeightedFinalScoreMap().get(2),(9.0+6.0)/2,0.01);\n\t\tassertEquals(cr.averageWeightedFinalScoreMap().get(3),(0.9+1.6)/2,0.01);\n\t\tassertEquals(cr.averageWeightedFinalScoreMap().get(4),(3.6+5.6+5.6)/3,0.01);\n\t\tassertEquals(cr.averageWeightedFinalScoreMap().get(5),(6.0+7.0)/2,0.01);\n\t\tassertEquals(cr.averageWeightedFinalScoreMap().size(),5);\n\t}" ] }, "content": "package a03b.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;\n\nimport a03b.sol1.ConferenceReviewing.Question;\n\n/**\n * Consult the documentation of the ConferenceReviewing interface, which models the results of the review process\n * of conference articles. Each article is reviewed by one or more anonymous reviewers, each of whom provides\n * a score from 0 to 10 for 4 different \"questions\", modeled by ConferenceReviewing.Question. An article is\n * accepted if the average value of the score for the \"FINAL\" question is >5 and if it has at least one \"RELEVANCE\" score >= 8.\n *\n * Implement ConferenceReviewing through a ConferenceReviewingImpl class with a constructor without arguments,\n * so that it passes all the tests below, designed to be self-explanatory.\n *\n * The following are considered optional for the purpose of being able to correct the exercise, but still contribute to achieving\n * the totality of the score:\n * - implementation of optional tests (related to the implementation of the averageWeightedFinalScoreMap method)\n * - the quality of the solution, in particular with minimization of repetitions and code that is not unnecessarily complex\n *\n * Scoring indications:\n * - correctness of the mandatory part: 9 points\n * - correctness of the optional part: 4 points\n * - quality of the solution: 4 points\n *\n * Remove the comment from the test code.\n */\n\npublic class Test {\n\n\tprivate ConferenceReviewing cr;\n\n\t// this method instantiates ConferenceReviewing and loads some reviews into it\n\[email protected]\n\tpublic void init() {\n\t\tthis.cr = new ConferenceReviewingImpl();\n\t\t// load a review for article 1:\n\t\t// - 8 for relevance, significance and final\n\t\t// - 7 for confidence\n\t\t// remember that the order of the questions is: relevance, significance, confidence, final\n\t\tcr.loadReview(1, 8, 8, 6, 8); // 4.8 is the weighted final score (used by averageWeightedFinalScoreMap)\n\t\t// and similar for the others\n\t\tcr.loadReview(1, 9, 9, 6, 9); // 5.4\n\t\tcr.loadReview(2, 9, 9, 10, 9); // 9.0\n\t\tcr.loadReview(2, 4, 6, 10, 6); // 6.0\n\t\tcr.loadReview(3, 3, 3, 3, 3); // 0.9\n\t\tcr.loadReview(3, 4, 4, 4, 4); // 1.6\n\t\tcr.loadReview(4, 6, 6, 6, 6); // 3.6\n\t\tcr.loadReview(4, 7, 7, 8, 7); // 5.6\n\t\tMap<Question,Integer> map = new EnumMap<>(Question.class);\n\t\tmap.put(Question.RELEVANCE, 8);\n\t\tmap.put(Question.SIGNIFICANCE, 8);\n\t\tmap.put(Question.CONFIDENCE, 7); // 5.6\n\t\tmap.put(Question.FINAL, 8);\n\t\tcr.loadReview(4,map);\n\t\tcr.loadReview(5, 6, 6, 6, 10); // 6.0\n\t\tcr.loadReview(5, 7, 7, 7, 10); // 7.0\n\t}\n\n\[email protected]\n\tpublic void testOrderedScores() {\n\t\t// article 2 received the two scores 4,9 on RELEVANCE\n\t\tassertEquals(cr.orderedScores(2, Question.RELEVANCE),Arrays.asList(4,9));\n\t\t// and similar for the others\n\t\tassertEquals(cr.orderedScores(4, Question.CONFIDENCE),Arrays.asList(6,7,8));\n\t\tassertEquals(cr.orderedScores(5, Question.FINAL),Arrays.asList(10,10));\n\t}\n\n\[email protected]\n\tpublic void testAverageFinalScore() {\n\t\t// article 1 has an average score on FINAL equal to 8.5, with a maximum deviation of 0.01\n\t\tassertEquals(cr.averageFinalScore(1),8.5,0.01);\n\t\t// and similar for the others\n\t\tassertEquals(cr.averageFinalScore(2),7.5,0.01);\n\t\tassertEquals(cr.averageFinalScore(3),3.5,0.01);\n\t\tassertEquals(cr.averageFinalScore(4),7.0,0.01);\n\t\tassertEquals(cr.averageFinalScore(5),10.0,0.01);\n\t}\n\n\[email protected]\n\tpublic void testAcceptedArticles() {\n\t\t// only articles 1,2,4 should be accepted, having a final average >=5 and at least one score on RELEVANCE >= 8\n\t\tassertEquals(cr.acceptedArticles(),new HashSet<>(Arrays.asList(1,2,4)));\n\t}\n\n\[email protected]\n\tpublic void testSortedAcceptedArticles() {\n\t\t// accepted articles, and their average final score\n\t\tassertEquals(cr.sortedAcceptedArticles(),Arrays.asList(new Pair<>(4,7.0),new Pair<>(2,7.5),new Pair<>(1,8.5)));\n\t}\n\n\[email protected]\n\tpublic void optionalTestAverageWeightedFinalScore() {\n\t\t// article 1 has a weighted final average equal to (4.8+5.4)/2 = 5.1, with a maximum deviation of 0.01\n\t\tassertEquals(cr.averageWeightedFinalScoreMap().get(1),(4.8+5.4)/2,0.01);\n\t\t// and similar for the others\n\t\tassertEquals(cr.averageWeightedFinalScoreMap().get(2),(9.0+6.0)/2,0.01);\n\t\tassertEquals(cr.averageWeightedFinalScoreMap().get(3),(0.9+1.6)/2,0.01);\n\t\tassertEquals(cr.averageWeightedFinalScoreMap().get(4),(3.6+5.6+5.6)/3,0.01);\n\t\tassertEquals(cr.averageWeightedFinalScoreMap().get(5),(6.0+7.0)/2,0.01);\n\t\tassertEquals(cr.averageWeightedFinalScoreMap().size(),5);\n\t}\n}", "filename": "Test.java" }
2018
a01b
[ { "content": "package a01b.sol1;\n\nimport java.util.Optional;\n\npublic interface ExamResult {\n\t\n\tenum Kind {\n\t\tRETIRED, FAILED, SUCCEEDED\n\t}\n\t\n\tKind getKind();\n\t\n\tOptional<Integer> getEvaluation();\n\t\n\tboolean cumLaude();\n}", "filename": "ExamResult.java" }, { "content": "package a01b.sol1;\n\nimport java.util.*;\n\npublic interface ExamsManager {\n\t\t\n\tvoid createNewCall(String call);\n\t\n\tvoid addStudentResult(String call, String student, ExamResult result);\n\t\n\tSet<String> getAllStudentsFromCall(String call);\n\t\n\tMap<String, Integer> getEvaluationsMapFromCall(String call);\n\t\n\tMap<String, String> getResultsMapFromStudent(String student);\n\t\n\tOptional<Integer> getBestResultFromStudent(String student);\n}", "filename": "ExamsManager.java" }, { "content": "package a01b.sol1;\n\npublic class Pair<X,Y> {\n\t\n\tprivate final X fst;\n\tprivate final Y snd;\n\tpublic Pair(X fst, Y snd) {\n\t\tsuper();\n\t\tthis.fst = fst;\n\t\tthis.snd = snd;\n\t}\n\tpublic X getFst() {\n\t\treturn fst;\n\t}\n\tpublic Y getSnd() {\n\t\treturn snd;\n\t}\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = 1;\n\t\tresult = prime * result + ((fst == null) ? 0 : fst.hashCode());\n\t\tresult = prime * result + ((snd == null) ? 0 : snd.hashCode());\n\t\treturn result;\n\t}\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 (!(obj instanceof Pair))\n\t\t\treturn false;\n\t\tPair other = (Pair) obj;\n\t\tif (fst == null) {\n\t\t\tif (other.fst != null)\n\t\t\t\treturn false;\n\t\t} else if (!fst.equals(other.fst))\n\t\t\treturn false;\n\t\tif (snd == null) {\n\t\t\tif (other.snd != null)\n\t\t\t\treturn false;\n\t\t} else if (!snd.equals(other.snd))\n\t\t\treturn false;\n\t\treturn true;\n\t}\n\t@Override\n\tpublic String toString() {\n\t\treturn \"[\" + fst + \";\" + snd + \"]\";\n\t}\n\t\n\t\n\n}", "filename": "Pair.java" }, { "content": "package a01b.sol1;\n\npublic interface ExamResultFactory {\n\t\n\tExamResult failed();\n\t\n\tExamResult retired();\n\t\t\n\tExamResult succeededCumLaude();\n\t\n\tExamResult succeeded(int evaluation);\n\n}", "filename": "ExamResultFactory.java" } ]
[ { "content": "package a01b.sol1;\n\nimport java.util.Optional;\n\nimport a01b.sol1.ExamResult.Kind;\n\n/**\n * Note: this solution is more verbose than needed, but it is still a good one since\n * it stresses separation of concepts (SRP principle) and avoidance of repetitions.\n * Alternative good solutions are:\n * - a unique class with a kind, evaluation and boolean field\n * - an enumeration of the 16 possible results \n */\npublic class ExamResultFactoryImpl implements ExamResultFactory {\n\t\n\t/**\n\t * An abstract class common to all implementations of Exams\n\t */\n\tprivate static abstract class AbstractExamResult implements ExamResult {\n\n\t\tprivate final Kind kind;\n\t\t\n\t\tpublic AbstractExamResult(Kind kind) {\n\t\t\tthis.kind = kind;\n\t\t}\n\n\t\t@Override\n\t\tpublic Kind getKind() {\n\t\t\treturn this.kind;\n\t\t}\n\n\t\t@Override\n\t\tpublic Optional<Integer> getEvaluation() {\n\t\t\treturn Optional.empty();\n\t\t}\n\n\t\t@Override\n\t\tpublic boolean cumLaude() {\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\treturn this.kind.toString();\n\t\t}\n\t}\n\t\n\t/**\n\t * An abstract class common to all implementations of successful Exams. \n\t */\n\tprivate static abstract class AbstractSuccessExamResult extends AbstractExamResult{\n\t\t\n\t\tprivate final int evaluation;\n\n\t\tpublic AbstractSuccessExamResult(int evaluation) {\n\t\t\tsuper(Kind.SUCCEEDED);\n\t\t\tif (evaluation < 18 || evaluation > 30) {\n\t\t\t\tthrow new IllegalArgumentException();\n\t\t\t}\n\t\t\tthis.evaluation = evaluation;\n\t\t}\n\n\t\t@Override\n\t\tpublic Optional<Integer> getEvaluation() {\n\t\t\treturn Optional.of(this.evaluation);\n\t\t}\n\t}\n\t\n\t// failed, retired and 30L are better seen as constants\n\tprivate static final ExamResult FAILED = new AbstractExamResult(Kind.FAILED){};\n\tprivate static final ExamResult RETIRED = new AbstractExamResult(Kind.RETIRED){};\n\tprivate static final ExamResult CUMLAUDE = new AbstractSuccessExamResult(30){\n\n\t\t@Override\n\t\tpublic boolean cumLaude() {\n\t\t\treturn true;\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\treturn super.toString()+\"(30L)\";\n\t\t}\t\t\t\n\t};\n\n\t\n\t@Override\n\tpublic ExamResult failed() {\n\t\treturn FAILED;\n\t}\n\n\t@Override\n\tpublic ExamResult retired() {\n\t\treturn RETIRED;\n\t}\n\t\n\t@Override\n\tpublic ExamResult succeededCumLaude() {\n\t\treturn CUMLAUDE;\n\t}\n\t\n\t/* \n\t * Another simple instantiation of AbstractSuccessExamResult\n\t */\n\t@Override\n\tpublic ExamResult succeeded(int evaluation) {\n\t\treturn new AbstractSuccessExamResult(evaluation){\n\n\t\t\t@Override\n\t\t\tpublic String toString() {\n\t\t\t\treturn super.toString()+\"(\"+evaluation+\")\";\n\t\t\t}\t\t\t\n\t\t};\n\t}\n}", "filename": "ExamResultFactoryImpl.java" }, { "content": "package a01b.sol1;\n\nimport java.util.*;\nimport java.util.Map.Entry;\nimport java.util.stream.Collectors;\n\npublic class ExamsManagerImpl implements ExamsManager {\n\n\t// a map from calls to maps from students to results\n\tprivate final Map<String, Map<String, ExamResult>> map = new HashMap<>();\n\t\n\tprivate static void checkArgument(boolean condition) {\n\t\tif (!condition) {\n\t\t\tthrow new IllegalArgumentException();\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic void createNewCall(String call) {\n\t\tcheckArgument(!map.containsKey(call));\n\t\tthis.map.put(call, new HashMap<>());\n\t}\n\n\t@Override\n\tpublic void addStudentResult(String call, String student, ExamResult result) {\n\t\tcheckArgument(map.containsKey(call));\n\t\tcheckArgument(!map.get(call).containsKey(student));\n\t\tthis.map.get(call).put(student, result);\n\t}\n\n\t@Override\n\tpublic Set<String> getAllStudentsFromCall(String call) {\n\t\tcheckArgument(map.containsKey(call));\n\t\treturn this.map.get(call).keySet();\n\t}\n\n\t@Override\n\tpublic Map<String, Integer> getEvaluationsMapFromCall(String call) {\n\t\tcheckArgument(map.containsKey(call));\n\t\treturn this.map.get(call).entrySet().stream()\n\t\t\t\t .filter(e -> e.getValue().getEvaluation().isPresent())\n\t\t\t\t .collect(Collectors.toMap(Entry::getKey, e -> e.getValue().getEvaluation().get()));\n\t}\n\n\t@Override\n\tpublic Map<String, String> getResultsMapFromStudent(String student) {\n\t\treturn this.map.entrySet().stream()\n\t\t\t\t .filter(e -> e.getValue().containsKey(student))\n\t\t\t\t .collect(Collectors.toMap(Entry::getKey, e -> e.getValue().get(student).toString()));\n\t}\n\t\n\t// A solution seeking for many stages, but simple ones\n\t@Override\n\tpublic Optional<Integer> getBestResultFromStudent(String student) {\n\t\treturn this.map.values().stream() // a stream of maps student->result\n\t\t\t\t .map(Map::entrySet) // a stream of sets of entries student->result\n\t\t\t\t .flatMap(Set::stream) // a flattened stream of entries\n\t\t\t .filter(e -> e.getKey().equals(student)) // just consider my student\n\t\t\t .map(Entry::getValue) // stream of results\n\t\t\t .filter(res -> res.getEvaluation().isPresent()) // only those with evaluation\n\t\t\t .map(ExamResult::getEvaluation) // only evaluations (boxed in optional)\n\t\t\t .map(Optional::get) // only evaluations (as int)\n\t\t\t .max((x,y)->x-y); // max\n\t}\n\n}", "filename": "ExamsManagerImpl.java" } ]
{ "components": { "imports": "package a01b.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;\n\n/**\n * Consult the provided interfaces (and the corresponding tests below):\n * - ExamResult that models the possible results of a university exam\n * - ExamResultFactory that models a factory to denote/create the possible exam results\n * - ExamsManager that models the management of exam results for a certain course, in the exam sessions of a year\n *\n * Implement ExamResultFactory and ExamsManager through the classes ExamResultFactoryImpl and ExamsManagerImpl with constructors without arguments,\n * so that all the tests below pass.\n *\n * The following are considered optional for the possibility of correcting the exercise, but still contribute to achieving\n * the totality of the score:\n * - implementation of optional tests (related to the ExamsManager.getBestResultFromStudent method and exception behaviors)\n * - the quality of the solution, in particular with minimization of repetitions and code that is not unnecessarily complex\n *\n * Scoring indications:\n * - correctness of the mandatory part: 9 points\n * - correctness of the optional part: 3 points\n * - quality of the solution: 5 points\n *\n * Remove the comment from the test code.\n */", "private_init": "\tprivate ExamResultFactory erf = new ExamResultFactoryImpl();\n\tprivate ExamsManager em = new ExamsManagerImpl();\n\n\t// basic verification of ExamResultFactory", "test_functions": [ "\[email protected]\n\tpublic void testExamResultsBasicBehaviour() {\n\t\t// exam failed, no grade\n\t\tassertEquals(erf.failed().getKind(), ExamResult.Kind.FAILED);\n\t\tassertFalse(erf.failed().getEvaluation().isPresent());\n\t\tassertFalse(erf.failed().cumLaude());\n\t\tassertEquals(erf.failed().toString(), \"FAILED\");\n\n\t\t// the student withdrew, no grade\n\t\tassertEquals(erf.retired().getKind(), ExamResult.Kind.RETIRED);\n\t\tassertFalse(erf.retired().getEvaluation().isPresent());\n\t\tassertFalse(erf.retired().cumLaude());\n\t\tassertEquals(erf.retired().toString(), \"RETIRED\");\n\n\t\t// 30L\n\t\tassertEquals(erf.succeededCumLaude().getKind(), ExamResult.Kind.SUCCEEDED);\n\t\tassertEquals(erf.succeededCumLaude().getEvaluation(), Optional.of(30));\n\t\tassertTrue(erf.succeededCumLaude().cumLaude());\n\t\tassertEquals(erf.succeededCumLaude().toString(), \"SUCCEEDED(30L)\");\n\n\t\t// exam passed, but not with honors\n\t\tassertEquals(erf.succeeded(28).getKind(), ExamResult.Kind.SUCCEEDED);\n\t\tassertEquals(erf.succeeded(28).getEvaluation(), Optional.of(28));\n\t\tassertFalse(erf.succeeded(28).cumLaude());\n\t\tassertEquals(erf.succeeded(28).toString(), \"SUCCEEDED(28)\");\n\t}", "\[email protected]\n\tpublic void testExamsManagement() {\n\t\tthis.prepareExams();\n\t\t// participants in the January and March exam sessions\n\t\tassertEquals(em.getAllStudentsFromCall(\"gennaio\"),new HashSet<>(Arrays.asList(\"rossi\",\"bianchi\",\"verdi\",\"neri\")));\n\t\tassertEquals(em.getAllStudentsFromCall(\"marzo\"),new HashSet<>(Arrays.asList(\"rossi\",\"bianchi\",\"viola\")));\n\n\t\t// passed students of January with grade\n\t\tassertEquals(em.getEvaluationsMapFromCall(\"gennaio\").size(),2);\n\t\tassertEquals(em.getEvaluationsMapFromCall(\"gennaio\").get(\"verdi\").intValue(),28);\n\t\tassertEquals(em.getEvaluationsMapFromCall(\"gennaio\").get(\"neri\").intValue(),30);\n\t\t// passed students of February with grade\n\t\tassertEquals(em.getEvaluationsMapFromCall(\"febbraio\").size(),2);\n\t\tassertEquals(em.getEvaluationsMapFromCall(\"febbraio\").get(\"bianchi\").intValue(),20);\n\t\tassertEquals(em.getEvaluationsMapFromCall(\"febbraio\").get(\"verdi\").intValue(),30);\n\n\t\t// all results of rossi (pay attention to toString!!)\n\t\tassertEquals(em.getResultsMapFromStudent(\"rossi\").size(),3);\n\t\tassertEquals(em.getResultsMapFromStudent(\"rossi\").get(\"gennaio\"),\"FAILED\");\n\t\tassertEquals(em.getResultsMapFromStudent(\"rossi\").get(\"febbraio\"),\"FAILED\");\n\t\tassertEquals(em.getResultsMapFromStudent(\"rossi\").get(\"marzo\"),\"SUCCEEDED(25)\");\n\t\t// all results of bianchi\n\t\tassertEquals(em.getResultsMapFromStudent(\"bianchi\").size(),3);\n\t\tassertEquals(em.getResultsMapFromStudent(\"bianchi\").get(\"gennaio\"),\"RETIRED\");\n\t\tassertEquals(em.getResultsMapFromStudent(\"bianchi\").get(\"febbraio\"),\"SUCCEEDED(20)\");\n\t\tassertEquals(em.getResultsMapFromStudent(\"bianchi\").get(\"marzo\"),\"SUCCEEDED(25)\");\n\t\t// all results of neri\n\t\tassertEquals(em.getResultsMapFromStudent(\"neri\").size(),1);\n\t\tassertEquals(em.getResultsMapFromStudent(\"neri\").get(\"gennaio\"),\"SUCCEEDED(30L)\");\n\n\t}", "\[email protected]\n\tpublic void optionalTestExamsManagement() {\n\t\tthis.prepareExams();\n\t\t// best grade obtained by each student, or empty..\n\t\tassertEquals(em.getBestResultFromStudent(\"rossi\"),Optional.of(25));\n\t\tassertEquals(em.getBestResultFromStudent(\"bianchi\"),Optional.of(25));\n\t\tassertEquals(em.getBestResultFromStudent(\"neri\"),Optional.of(30));\n\t\tassertEquals(em.getBestResultFromStudent(\"viola\"),Optional.empty());\n\t}" ] }, "content": "package a01b.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;\n\n/**\n * Consult the provided interfaces (and the corresponding tests below):\n * - ExamResult that models the possible results of a university exam\n * - ExamResultFactory that models a factory to denote/create the possible exam results\n * - ExamsManager that models the management of exam results for a certain course, in the exam sessions of a year\n *\n * Implement ExamResultFactory and ExamsManager through the classes ExamResultFactoryImpl and ExamsManagerImpl with constructors without arguments,\n * so that all the tests below pass.\n *\n * The following are considered optional for the possibility of correcting the exercise, but still contribute to achieving\n * the totality of the score:\n * - implementation of optional tests (related to the ExamsManager.getBestResultFromStudent method and exception behaviors)\n * - the quality of the solution, in particular with minimization of repetitions and code that is not unnecessarily complex\n *\n * Scoring indications:\n * - correctness of the mandatory part: 9 points\n * - correctness of the optional part: 3 points\n * - quality of the solution: 5 points\n *\n * Remove the comment from the test code.\n */\n\npublic class Test {\n\n\tprivate ExamResultFactory erf = new ExamResultFactoryImpl();\n\tprivate ExamsManager em = new ExamsManagerImpl();\n\n\t// basic verification of ExamResultFactory\n\[email protected]\n\tpublic void testExamResultsBasicBehaviour() {\n\t\t// exam failed, no grade\n\t\tassertEquals(erf.failed().getKind(), ExamResult.Kind.FAILED);\n\t\tassertFalse(erf.failed().getEvaluation().isPresent());\n\t\tassertFalse(erf.failed().cumLaude());\n\t\tassertEquals(erf.failed().toString(), \"FAILED\");\n\n\t\t// the student withdrew, no grade\n\t\tassertEquals(erf.retired().getKind(), ExamResult.Kind.RETIRED);\n\t\tassertFalse(erf.retired().getEvaluation().isPresent());\n\t\tassertFalse(erf.retired().cumLaude());\n\t\tassertEquals(erf.retired().toString(), \"RETIRED\");\n\n\t\t// 30L\n\t\tassertEquals(erf.succeededCumLaude().getKind(), ExamResult.Kind.SUCCEEDED);\n\t\tassertEquals(erf.succeededCumLaude().getEvaluation(), Optional.of(30));\n\t\tassertTrue(erf.succeededCumLaude().cumLaude());\n\t\tassertEquals(erf.succeededCumLaude().toString(), \"SUCCEEDED(30L)\");\n\n\t\t// exam passed, but not with honors\n\t\tassertEquals(erf.succeeded(28).getKind(), ExamResult.Kind.SUCCEEDED);\n\t\tassertEquals(erf.succeeded(28).getEvaluation(), Optional.of(28));\n\t\tassertFalse(erf.succeeded(28).cumLaude());\n\t\tassertEquals(erf.succeeded(28).toString(), \"SUCCEEDED(28)\");\n\t}\n\n\t// exception verification in ExamResultFactory\n\[email protected](expected = IllegalArgumentException.class)\n\tpublic void optionalTestEvaluationCantBeGreaterThan30() {\n\t\terf.succeeded(32);\n\t}\n\n\t// exception verification in ExamResultFactory\n\[email protected](expected = IllegalArgumentException.class)\n\tpublic void optionalTestEvaluationCantBeSmallerThan18() {\n\t\terf.succeeded(17);\n\t}\n\n\t// method for creating a situation of results in 3 exam sessions\n\tprivate void prepareExams() {\n\t\tem.createNewCall(\"gennaio\"); // January\n\t\tem.createNewCall(\"febbraio\"); // February\n\t\tem.createNewCall(\"marzo\"); // March\n\n\t\tem.addStudentResult(\"gennaio\", \"rossi\", erf.failed()); // rossi -> failed\n\t\tem.addStudentResult(\"gennaio\", \"bianchi\", erf.retired()); // bianchi -> retired\n\t\tem.addStudentResult(\"gennaio\", \"verdi\", erf.succeeded(28)); // verdi -> 28\n\t\tem.addStudentResult(\"gennaio\", \"neri\", erf.succeededCumLaude()); // neri -> 30L\n\n\t\tem.addStudentResult(\"febbraio\", \"rossi\", erf.failed()); // etc..\n\t\tem.addStudentResult(\"febbraio\", \"bianchi\", erf.succeeded(20));\n\t\tem.addStudentResult(\"febbraio\", \"verdi\", erf.succeeded(30));\n\n\t\tem.addStudentResult(\"marzo\", \"rossi\", erf.succeeded(25));\n\t\tem.addStudentResult(\"marzo\", \"bianchi\", erf.succeeded(25));\n\t\tem.addStudentResult(\"marzo\", \"viola\", erf.failed());\n\t}\n\n\t// basic verification of the mandatory part of ExamManager\n\[email protected]\n\tpublic void testExamsManagement() {\n\t\tthis.prepareExams();\n\t\t// participants in the January and March exam sessions\n\t\tassertEquals(em.getAllStudentsFromCall(\"gennaio\"),new HashSet<>(Arrays.asList(\"rossi\",\"bianchi\",\"verdi\",\"neri\")));\n\t\tassertEquals(em.getAllStudentsFromCall(\"marzo\"),new HashSet<>(Arrays.asList(\"rossi\",\"bianchi\",\"viola\")));\n\n\t\t// passed students of January with grade\n\t\tassertEquals(em.getEvaluationsMapFromCall(\"gennaio\").size(),2);\n\t\tassertEquals(em.getEvaluationsMapFromCall(\"gennaio\").get(\"verdi\").intValue(),28);\n\t\tassertEquals(em.getEvaluationsMapFromCall(\"gennaio\").get(\"neri\").intValue(),30);\n\t\t// passed students of February with grade\n\t\tassertEquals(em.getEvaluationsMapFromCall(\"febbraio\").size(),2);\n\t\tassertEquals(em.getEvaluationsMapFromCall(\"febbraio\").get(\"bianchi\").intValue(),20);\n\t\tassertEquals(em.getEvaluationsMapFromCall(\"febbraio\").get(\"verdi\").intValue(),30);\n\n\t\t// all results of rossi (pay attention to toString!!)\n\t\tassertEquals(em.getResultsMapFromStudent(\"rossi\").size(),3);\n\t\tassertEquals(em.getResultsMapFromStudent(\"rossi\").get(\"gennaio\"),\"FAILED\");\n\t\tassertEquals(em.getResultsMapFromStudent(\"rossi\").get(\"febbraio\"),\"FAILED\");\n\t\tassertEquals(em.getResultsMapFromStudent(\"rossi\").get(\"marzo\"),\"SUCCEEDED(25)\");\n\t\t// all results of bianchi\n\t\tassertEquals(em.getResultsMapFromStudent(\"bianchi\").size(),3);\n\t\tassertEquals(em.getResultsMapFromStudent(\"bianchi\").get(\"gennaio\"),\"RETIRED\");\n\t\tassertEquals(em.getResultsMapFromStudent(\"bianchi\").get(\"febbraio\"),\"SUCCEEDED(20)\");\n\t\tassertEquals(em.getResultsMapFromStudent(\"bianchi\").get(\"marzo\"),\"SUCCEEDED(25)\");\n\t\t// all results of neri\n\t\tassertEquals(em.getResultsMapFromStudent(\"neri\").size(),1);\n\t\tassertEquals(em.getResultsMapFromStudent(\"neri\").get(\"gennaio\"),\"SUCCEEDED(30L)\");\n\n\t}\n\n\t// verification of the ExamManager.getBestResultFromStudent method\n\[email protected]\n\tpublic void optionalTestExamsManagement() {\n\t\tthis.prepareExams();\n\t\t// best grade obtained by each student, or empty..\n\t\tassertEquals(em.getBestResultFromStudent(\"rossi\"),Optional.of(25));\n\t\tassertEquals(em.getBestResultFromStudent(\"bianchi\"),Optional.of(25));\n\t\tassertEquals(em.getBestResultFromStudent(\"neri\"),Optional.of(30));\n\t\tassertEquals(em.getBestResultFromStudent(\"viola\"),Optional.empty());\n\t}\n\n\n\[email protected](expected = IllegalArgumentException.class)\n\tpublic void optionalTestCantCreateACallTwice() {\n\t\tthis.prepareExams();\n\t\tem.createNewCall(\"marzo\");\n\t}\n\n\[email protected](expected = IllegalArgumentException.class)\n\tpublic void optionalTestCantRegisterAnEvaluationTwice() {\n\t\tthis.prepareExams();\n\t\tem.addStudentResult(\"gennaio\", \"verdi\", erf.failed());\n\t}\n}", "filename": "Test.java" }
2019
a05a
[ { "content": "package a05a.sol1;\n\nimport java.util.*;\n\n\npublic interface IteratorOfListsFactory {\n\t\n\t\n\t<E> IteratorOfLists<E> iterative(E e);\n\t\n\t\n\t<E> IteratorOfLists<E> iterativeOnList(List<E> list);\n\t\n\t\n\t<E> IteratorOfLists<E> iterativeWithPreamble(E e, List<E> preamble);\n\t\t\n}", "filename": "IteratorOfListsFactory.java" }, { "content": "package a05a.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 a05a.sol1;\n\nimport java.util.List;\n\n\npublic interface IteratorOfLists<E> {\n\t\n\t\n\tList<E> nextList();\n\t\n\t\n\tboolean hasOtherLists();\n\t\n\t\n\tvoid reset();\n\n\t\n}", "filename": "IteratorOfLists.java" } ]
[ { "content": "package a05a.sol1;\n\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.function.Supplier;\nimport java.util.stream.Collectors;\nimport java.util.stream.IntStream;\nimport java.util.stream.Stream;\n\npublic class IteratorOfListsFactoryImpl implements IteratorOfListsFactory {\n\t\n\tprivate static <E> IteratorOfLists<E> fromStream(Supplier<Stream<List<E>>> streamSupplier) {\n\t\treturn new IteratorOfLists<E>() {\n\t\t\t\n\t\t\t{ reset(); } // non-static initializer\n\t\t\t\n\t\t\tprivate Iterator<List<E>> iterator;\n\n\t\t\t@Override\n\t\t\tpublic void reset() {\n\t\t\t\titerator = streamSupplier.get().iterator();\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic List<E> nextList() {\n\t\t\t\treturn iterator.next();\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic boolean hasOtherLists() {\n\t\t\t\treturn iterator.hasNext();\n\t\t\t}\n\t\t\t\n\t\t};\n\t}\n\t\n\t\n\tprivate <E> Stream<List<E>> iterativeStream(E e){\n\t\treturn Stream.iterate(0, i->i+1).map(i -> Collections.nCopies(i, e));\n\t}\n\t\n\t@Override\n\tpublic <E> IteratorOfLists<E> iterative(E e) {\n\t\treturn fromStream(()->iterativeStream(e));\n\t}\n\n\t@Override\n\tpublic <E> IteratorOfLists<E> iterativeOnList(List<E> list) {\n\t\treturn fromStream(()->Stream.iterate(0, i->i+1).map(i-> \n\t\t\tIntStream.range(0, i).mapToObj(j -> list.get(j % list.size())).collect(Collectors.toList())\n\t\t));\n\t}\n\t\n\t@Override\n\tpublic <E> IteratorOfLists<E> iterativeWithPreamble(E e, List<E> preamble) {\n\t\treturn fromStream(()->iterativeStream(e).map(l -> {\n\t\t\tList<E> ll = new ArrayList<>(preamble);\n\t\t\tll.addAll(l);\n\t\t\treturn ll;\n\t\t}));\n\t}\n\n\t\n\n}", "filename": "IteratorOfListsFactoryImpl.java" } ]
{ "components": { "imports": "package a05a.sol1;\n\nimport static org.junit.Assert.*;\n\nimport java.util.List;", "private_init": "\t/*\n\t * Implement the IteratorOfListsFactory interface as indicated in the initFactory method below.\n\t * Implement a factory concept for IteratorOfLists, which in turn models an iterator of lists,\n\t * i.e., an object that gradually produces lists of elements.\n\t * \n\t * The comment to the provided interfaces, and the test methods below constitute the necessary\n\t * explanation of the problem.\n\t * \n\t * The following are considered optional for the purpose of being able to correct the exercise,\n\t * but still contribute to achieving the totality of the score:\n\t * - implementation of the tests called optionalTestXYZ (related to the IteratorOfLists.reset method)\n\t * - good design of the solution, in particular with minimization of repetitions\n\t * \n\t * Remove the comment from the initFactory method.\n\t * \n\t * Scoring indications:\n\t * - correctness of the mandatory part: 9 points\n\t * - correctness of the optional part: 4 points\n\t * - quality of the solution: 4 points\n\t * \n\t */\n\t\n\tprivate IteratorOfListsFactory factory = null;\n\t\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.factory = new IteratorOfListsFactoryImpl();\n\t}", "test_functions": [ "\[email protected]\n\tpublic void testIterative() {\n\t\t// Iterator that produces {}", "\[email protected]\n\tpublic void testIterativeOnList() {\n\t\t// Iterator that produces {}", "\[email protected]\n\tpublic void testIterativeWithPreamble() {\n\t\t// iterator that produces {1,2,3}", "\[email protected]\n\tpublic void optionalTestReset1() {\n\t\tfinal IteratorOfLists<Integer> sp = this.factory.iterative(10);\n\t\tassertEquals(sp.nextList(),List.of());\n\t\tassertEquals(sp.nextList(),List.of(10));\n\t\tsp.reset();\n\t\tassertEquals(sp.nextList(),List.of());\n\t\tassertEquals(sp.nextList(),List.of(10));\n\t\tassertEquals(sp.nextList(),List.of(10,10));\t\t\n\t}", "\[email protected]\n\tpublic void optionalTestReset2() {\n\t\tfinal IteratorOfLists<String> sp = this.factory.iterativeOnList(List.of(\"a\",\"b\",\"c\"));\n\t\tassertEquals(sp.nextList(),List.of());\n\t\tassertEquals(sp.nextList(),List.of(\"a\"));\n\t\tassertEquals(sp.nextList(),List.of(\"a\",\"b\"));\n\t\tsp.reset();\n\t\tassertEquals(sp.nextList(),List.of());\n\t\tassertEquals(sp.nextList(),List.of(\"a\"));\n\t\tassertEquals(sp.nextList(),List.of(\"a\",\"b\"));\n\t\tassertEquals(sp.nextList(),List.of(\"a\",\"b\",\"c\"));\n\t\tassertEquals(sp.nextList(),List.of(\"a\",\"b\",\"c\",\"a\"));\n\t\tassertEquals(sp.nextList(),List.of(\"a\",\"b\",\"c\",\"a\",\"b\"));\n\t\tassertEquals(sp.nextList(),List.of(\"a\",\"b\",\"c\",\"a\",\"b\",\"c\"));\n\t\tassertEquals(sp.nextList(),List.of(\"a\",\"b\",\"c\",\"a\",\"b\",\"c\",\"a\"));\n\t}" ] }, "content": "package a05a.sol1;\n\nimport static org.junit.Assert.*;\n\nimport java.util.List;\n\npublic class Test {\n\t\n\t/*\n\t * Implement the IteratorOfListsFactory interface as indicated in the initFactory method below.\n\t * Implement a factory concept for IteratorOfLists, which in turn models an iterator of lists,\n\t * i.e., an object that gradually produces lists of elements.\n\t * \n\t * The comment to the provided interfaces, and the test methods below constitute the necessary\n\t * explanation of the problem.\n\t * \n\t * The following are considered optional for the purpose of being able to correct the exercise,\n\t * but still contribute to achieving the totality of the score:\n\t * - implementation of the tests called optionalTestXYZ (related to the IteratorOfLists.reset method)\n\t * - good design of the solution, in particular with minimization of repetitions\n\t * \n\t * Remove the comment from the initFactory method.\n\t * \n\t * Scoring indications:\n\t * - correctness of the mandatory part: 9 points\n\t * - correctness of the optional part: 4 points\n\t * - quality of the solution: 4 points\n\t * \n\t */\n\t\n\tprivate IteratorOfListsFactory factory = null;\n\t\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.factory = new IteratorOfListsFactoryImpl();\n\t}\n\n\[email protected]\n\tpublic void testIterative() {\n\t\t// Iterator that produces {}, then {10}, then {10,10}, and so on\n\t\tfinal IteratorOfLists<Integer> sp = this.factory.iterative(10);\n\t\tassertEquals(sp.nextList(),List.of());\n\t\tassertEquals(sp.nextList(),List.of(10));\n\t\tassertEquals(sp.nextList(),List.of(10,10));\n\t\tassertEquals(sp.nextList(),List.of(10,10,10));\n\t\tassertEquals(sp.nextList(),List.of(10,10,10,10));\n\t\tassertTrue(sp.hasOtherLists());\n\t\tfor (int i=0; i<100; i++) {\n\t\t\tsp.nextList();\n\t\t}\n\t\tassertEquals(sp.nextList().size(),105);\n\t}\n\t\n\[email protected]\n\tpublic void testIterativeOnList() {\n\t\t// Iterator that produces {}, then {a}, then {a,b}, then {a,b,c}, then {a,b,c,a}, and so on\n\t\tfinal IteratorOfLists<String> sp = this.factory.iterativeOnList(List.of(\"a\",\"b\",\"c\"));\n\t\tassertEquals(sp.nextList(),List.of());\n\t\tassertEquals(sp.nextList(),List.of(\"a\"));\n\t\tassertEquals(sp.nextList(),List.of(\"a\",\"b\"));\n\t\tassertEquals(sp.nextList(),List.of(\"a\",\"b\",\"c\"));\n\t\tassertEquals(sp.nextList(),List.of(\"a\",\"b\",\"c\",\"a\"));\n\t\tassertEquals(sp.nextList(),List.of(\"a\",\"b\",\"c\",\"a\",\"b\"));\n\t\tassertEquals(sp.nextList(),List.of(\"a\",\"b\",\"c\",\"a\",\"b\",\"c\"));\n\t\tassertEquals(sp.nextList(),List.of(\"a\",\"b\",\"c\",\"a\",\"b\",\"c\",\"a\"));\n\t\tassertTrue(sp.hasOtherLists());\n\t\tfor (int i=0; i<100; i++) {\n\t\t\tsp.nextList();\n\t\t}\n\t\tassertEquals(sp.nextList().size(),108);\n\t}\n\t\n\[email protected]\n\tpublic void testIterativeWithPreamble() {\n\t\t// iterator that produces {1,2,3}, {1,2,3,10}, {1,2,3,10,10}, and so on\n\t\tfinal IteratorOfLists<Integer> sp = this.factory.iterativeWithPreamble(10, List.of(1,2,3));\n\t\tassertEquals(sp.nextList(),List.of(1,2,3));\n\t\tassertEquals(sp.nextList(),List.of(1,2,3,10));\n\t\tassertEquals(sp.nextList(),List.of(1,2,3,10,10));\n\t\tassertEquals(sp.nextList(),List.of(1,2,3,10,10,10));\n\t\tassertEquals(sp.nextList(),List.of(1,2,3,10,10,10,10));\n\t\tassertTrue(sp.hasOtherLists());\n\t\tfor (int i=0; i<100; i++) {\n\t\t\tsp.nextList();\n\t\t}\n\t\tassertEquals(sp.nextList().size(),108);\n\t}\n\t\n\n\[email protected]\n\tpublic void optionalTestReset1() {\n\t\tfinal IteratorOfLists<Integer> sp = this.factory.iterative(10);\n\t\tassertEquals(sp.nextList(),List.of());\n\t\tassertEquals(sp.nextList(),List.of(10));\n\t\tsp.reset();\n\t\tassertEquals(sp.nextList(),List.of());\n\t\tassertEquals(sp.nextList(),List.of(10));\n\t\tassertEquals(sp.nextList(),List.of(10,10));\t\t\n\t}\n\t\n\[email protected]\n\tpublic void optionalTestReset2() {\n\t\tfinal IteratorOfLists<String> sp = this.factory.iterativeOnList(List.of(\"a\",\"b\",\"c\"));\n\t\tassertEquals(sp.nextList(),List.of());\n\t\tassertEquals(sp.nextList(),List.of(\"a\"));\n\t\tassertEquals(sp.nextList(),List.of(\"a\",\"b\"));\n\t\tsp.reset();\n\t\tassertEquals(sp.nextList(),List.of());\n\t\tassertEquals(sp.nextList(),List.of(\"a\"));\n\t\tassertEquals(sp.nextList(),List.of(\"a\",\"b\"));\n\t\tassertEquals(sp.nextList(),List.of(\"a\",\"b\",\"c\"));\n\t\tassertEquals(sp.nextList(),List.of(\"a\",\"b\",\"c\",\"a\"));\n\t\tassertEquals(sp.nextList(),List.of(\"a\",\"b\",\"c\",\"a\",\"b\"));\n\t\tassertEquals(sp.nextList(),List.of(\"a\",\"b\",\"c\",\"a\",\"b\",\"c\"));\n\t\tassertEquals(sp.nextList(),List.of(\"a\",\"b\",\"c\",\"a\",\"b\",\"c\",\"a\"));\n\t}\n\t\n}", "filename": "Test.java" }
2019
a03a
[ { "content": "package a03a.sol1;\n\n\npublic interface RWControllersFactory {\n\t\n\t\n\tRWController createPermissive();\n\t\n\t\n\tRWController createOnlyRead();\n\t\n\t\n\tRWController createMutualExclusion();\n\t\n\t\n\tRWController createManyReadersOrOneWriter();\n\n}", "filename": "RWControllersFactory.java" }, { "content": "package a03a.sol1;\n\n\npublic interface RWController {\n\t\n\t\n\tint enter();\n\t\n\t\n\tvoid goRead(int id);\n\t\n\t\n\tvoid goWrite(int id);\n\t\t\n\t\n\tvoid exit(int id);\n}", "filename": "RWController.java" }, { "content": "package a03a.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 a03a.sol1;\n\nimport java.util.*;\n\npublic class RWControllersFactoryImpl implements RWControllersFactory {\n\t\n\tenum State {\n\t\tENTERED, GO_READ, GO_WRITE\n\t}\n\t\n\t// This policy is used to state weather, given certain readers and writers, we can allow a new read/write\n\tinterface Policy{\n\t\tboolean canGo(boolean reader, Set<Integer> readers, Set<Integer> writers);\n\t}\n\t\n\tprivate RWController byPolicy(Policy p) {\n\t\treturn new RWController() {\n\t\t\tprivate Map<State,Set<Integer>> processes = new EnumMap<>(State.class) {{\n\t\t\t\tput(State.ENTERED, new HashSet<>());\n\t\t\t\tput(State.GO_READ, new HashSet<>());\n\t\t\t\tput(State.GO_WRITE, new HashSet<>());\n\t\t\t}};\n\t\t\tprivate int counterId;\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic int enter() {\n\t\t\t\tthis.processes.get(State.ENTERED).add(this.counterId);\n\t\t\t\treturn this.counterId++;\n\t\t\t}\n\t\t\t\n\t\t\tprivate void go(int id, boolean read, State target) {\n\t\t\t\tif (!processes.get(State.ENTERED).contains(id)) {\n\t\t\t\t\tthrow new IllegalStateException();\n\t\t\t\t}\n\t\t\t\tif (!p.canGo(read, processes.get(State.GO_READ), processes.get(State.GO_WRITE))) {\n\t\t\t\t\tthrow new IllegalStateException();\n\t\t\t\t}\n\t\t\t\tprocesses.get(State.ENTERED).remove(id);\n\t\t\t\tprocesses.get(target).add(id);\n\t\t\t}\n\t\t\t@Override\n\t\t\tpublic void goRead(int id) {\n\t\t\t\tthis.go(id, true, State.GO_READ);\n\t\t\t}\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic void goWrite(int id) {\n\t\t\t\tthis.go(id, false, State.GO_WRITE);\n\t\t\t}\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic void exit(int id) {\n\t\t\t\tif (!processes.get(State.GO_READ).contains(id) && !processes.get(State.GO_WRITE).contains(id)) {\n\t\t\t\t\tthrow new IllegalStateException();\n\t\t\t\t}\n\t\t\t\tprocesses.get(State.GO_WRITE).remove(id);\n\t\t\t\tprocesses.get(State.GO_READ).remove(id);\n\t\t\t}\n\t\t};\n\t}\n\n\t@Override\n\tpublic RWController createPermissive() {\n\t\treturn byPolicy( (b,readers,writers) -> true ); // can always access\n\t}\n\n\t@Override\n\tpublic RWController createOnlyRead() {\n\t\treturn byPolicy( (b,readers,writers) -> b ); // true for readers (b=true)\n\t}\n\n\t@Override\n\tpublic RWController createMutualExclusion() { // true if none is accessing\n\t\treturn byPolicy( (b,readers,writers) -> readers.isEmpty() && writers.isEmpty() );\n\t}\n\n\t@Override\n\tpublic RWController createManyReadersOrOneWriter() { // none is writing and, to read or none is reading\n\t\treturn byPolicy( (b,readers,writers) -> writers.isEmpty() && (b || readers.isEmpty() ));\n\t} \n\t\n\n}", "filename": "RWControllersFactoryImpl.java" } ]
{ "components": { "imports": "package a03a.sol1;\n\nimport static org.junit.Assert.*;", "private_init": "\t/*\n\t * Implement the RWControllerFactory interface as indicated in the initFactory method below.\n\t * Implement a factory concept for RWController, which in turn models the controller of a\n\t * resource, accessible for reading or writing, but with certain constraints on when it can be accessed.\n\t * For example, an RWController could be permissive and always allow access to the resource,\n\t * another could apply \"mutual exclusion\", allowing only one access at a time.\n\t * \n\t * The comment on the provided interfaces, and the test methods below constitute the necessary\n\t * explanation of the problem.\n\t * \n\t * The following are considered optional for the purpose of correcting the exercise,\n\t * but still contribute to achieving the total score:\n\t * - implementation of the tests called optionalTestXYZ (related to the method\n\t * RWControllerFactory.createManyReadersOrOneWriterExam, and some tests on exceptions)\n\t * - good design of the solution, in particular with minimization of repetitions through\n\t * the STRATEGY pattern\n\t * \n\t * Remove the comment from the initFactory method.\n\t * \n\t * Scoring indications:\n\t * - correctness of the mandatory part: 9 points\n\t * - correctness of the optional part: 4 points\n\t * - quality of the solution: 4 points\n\t * \n\t */\n\n\t\n\tprivate RWControllersFactory rwf = null;\n\t\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.rwf = new RWControllersFactoryImpl();\n\t}", "test_functions": [ "\[email protected]\n\tpublic void testPermissiveRW() {\n\t\t// test of an RWController that always allows access\n\t\tfinal RWController rw = this.rwf.createPermissive();\n\t\t// three processes enter, they are given id 0,1,2\n\t\tassertEquals(0, rw.enter());\n\t\tassertEquals(1, rw.enter());\n\t\tassertEquals(2, rw.enter());\n\t\t\n\t\t// 0 wants to read, 1 wants to write: they succeed\n\t\trw.goRead(0);\n\t\trw.goWrite(1);\n\t\t\n\t\t// 0 exits the system, stopping reading\n\t\trw.exit(0);\n\t\t\n\t\t// a new process enters, 3\n\t\tassertEquals(3, rw.enter());\n\t\t\n\t\t// 3 wants to write, 2 wants to read: they succeed\n\t\trw.goWrite(3);\n\t\trw.goRead(2);\n\t\t\n\t\t// 2,1,3 stop accessing, exiting\n\t\trw.exit(2);\n\t\trw.exit(1);\n\t\trw.exit(3);\n\t}", "\[email protected]\n\tpublic void testOnlyRead() {\n\t\t// test of an RWController that works like Permissive, but only allows reads\n\t\tfinal RWController rw = this.rwf.createOnlyRead();\n\t\t\n\t\tassertEquals(0, rw.enter());\n\t\tassertEquals(1, rw.enter());\n\t\tassertEquals(2, rw.enter());\n\t\t\n\t\t// 0 and 1 read successfully, and exit\n\t\trw.goRead(0);\n\t\trw.goRead(1);\n\t\trw.exit(0);\n\t\trw.exit(1);\n\t\t\n\t\tassertEquals(3, rw.enter());\n\t\t\n\t\t// 2 tries to write but fails generating the IllegalStateException\n\t\ttry {\n\t\t\trw.goWrite(2);\n\t\t\tfail(); // if it gets here it means the exception was not generated\n\t\t}", "\[email protected]\n\tpublic void testMutualExclusion() {\n\t\t// test of an RWController that works like Permissive, but allows only one access at a time\n\t\tfinal RWController rw = this.rwf.createMutualExclusion();\n\t\t\n\t\tassertEquals(0, rw.enter());\n\t\tassertEquals(1, rw.enter());\n\t\tassertEquals(2, rw.enter());\n\n\t\t// 0 reads and exits, 1 reads\n\t\trw.goRead(0);\n\t\trw.exit(0);\n\t\trw.goRead(1);\n\t\t\n\t\tassertEquals(3, rw.enter());\n\t\t\n\t\t// 2 tries to read but fails, because 1 is still reading\n\t\ttry {\n\t\t\trw.goRead(2);\n\t\t\tfail();\n\t\t}", "\[email protected]\n\tpublic void optionalTestManyReadersOneWriter() {\n\t\t// test of an RWController that either lets multiple processes read, or lets one process write\n\t\tfinal RWController rw = this.rwf.createManyReadersOrOneWriter();\n\t\t\n\t\tassertEquals(0, rw.enter());\n\t\tassertEquals(1, rw.enter());\n\t\tassertEquals(2, rw.enter());\n\t\t\n\t\t// 0 and 1 can both read\n\t\trw.goRead(0);\n\t\trw.goRead(1);\n\t\trw.exit(0);\n\t\trw.exit(1);\n\t\t\n\t\tassertEquals(3, rw.enter());\n\t\t\n\t\t// 2 reads\n\t\trw.goRead(2);\n\t\t\n\t\t// 3 cannot write, because you either read or write\n\t\ttry {\n\t\t\trw.goWrite(3);\n\t\t\tfail();\n\t\t}" ] }, "content": "package a03a.sol1;\n\nimport static org.junit.Assert.*;\n\npublic class Test {\n\t\n\t/*\n\t * Implement the RWControllerFactory interface as indicated in the initFactory method below.\n\t * Implement a factory concept for RWController, which in turn models the controller of a\n\t * resource, accessible for reading or writing, but with certain constraints on when it can be accessed.\n\t * For example, an RWController could be permissive and always allow access to the resource,\n\t * another could apply \"mutual exclusion\", allowing only one access at a time.\n\t * \n\t * The comment on the provided interfaces, and the test methods below constitute the necessary\n\t * explanation of the problem.\n\t * \n\t * The following are considered optional for the purpose of correcting the exercise,\n\t * but still contribute to achieving the total score:\n\t * - implementation of the tests called optionalTestXYZ (related to the method\n\t * RWControllerFactory.createManyReadersOrOneWriterExam, and some tests on exceptions)\n\t * - good design of the solution, in particular with minimization of repetitions through\n\t * the STRATEGY pattern\n\t * \n\t * Remove the comment from the initFactory method.\n\t * \n\t * Scoring indications:\n\t * - correctness of the mandatory part: 9 points\n\t * - correctness of the optional part: 4 points\n\t * - quality of the solution: 4 points\n\t * \n\t */\n\n\t\n\tprivate RWControllersFactory rwf = null;\n\t\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.rwf = new RWControllersFactoryImpl();\n\t}\n\n\[email protected]\n\tpublic void testPermissiveRW() {\n\t\t// test of an RWController that always allows access\n\t\tfinal RWController rw = this.rwf.createPermissive();\n\t\t// three processes enter, they are given id 0,1,2\n\t\tassertEquals(0, rw.enter());\n\t\tassertEquals(1, rw.enter());\n\t\tassertEquals(2, rw.enter());\n\t\t\n\t\t// 0 wants to read, 1 wants to write: they succeed\n\t\trw.goRead(0);\n\t\trw.goWrite(1);\n\t\t\n\t\t// 0 exits the system, stopping reading\n\t\trw.exit(0);\n\t\t\n\t\t// a new process enters, 3\n\t\tassertEquals(3, rw.enter());\n\t\t\n\t\t// 3 wants to write, 2 wants to read: they succeed\n\t\trw.goWrite(3);\n\t\trw.goRead(2);\n\t\t\n\t\t// 2,1,3 stop accessing, exiting\n\t\trw.exit(2);\n\t\trw.exit(1);\n\t\trw.exit(3);\n\t}\n\t\n\[email protected]\n\tpublic void testOnlyRead() {\n\t\t// test of an RWController that works like Permissive, but only allows reads\n\t\tfinal RWController rw = this.rwf.createOnlyRead();\n\t\t\n\t\tassertEquals(0, rw.enter());\n\t\tassertEquals(1, rw.enter());\n\t\tassertEquals(2, rw.enter());\n\t\t\n\t\t// 0 and 1 read successfully, and exit\n\t\trw.goRead(0);\n\t\trw.goRead(1);\n\t\trw.exit(0);\n\t\trw.exit(1);\n\t\t\n\t\tassertEquals(3, rw.enter());\n\t\t\n\t\t// 2 tries to write but fails generating the IllegalStateException\n\t\ttry {\n\t\t\trw.goWrite(2);\n\t\t\tfail(); // if it gets here it means the exception was not generated\n\t\t} catch (IllegalStateException e) {\n\t\t\t\n\t\t} catch (Exception e) {\n\t\t\tfail(\"wrong exception thrown\");\n\t\t}\n\t}\n\t\n\[email protected]\n\tpublic void testMutualExclusion() {\n\t\t// test of an RWController that works like Permissive, but allows only one access at a time\n\t\tfinal RWController rw = this.rwf.createMutualExclusion();\n\t\t\n\t\tassertEquals(0, rw.enter());\n\t\tassertEquals(1, rw.enter());\n\t\tassertEquals(2, rw.enter());\n\n\t\t// 0 reads and exits, 1 reads\n\t\trw.goRead(0);\n\t\trw.exit(0);\n\t\trw.goRead(1);\n\t\t\n\t\tassertEquals(3, rw.enter());\n\t\t\n\t\t// 2 tries to read but fails, because 1 is still reading\n\t\ttry {\n\t\t\trw.goRead(2);\n\t\t\tfail();\n\t\t} catch (IllegalStateException e) {\n\t\t\t\n\t\t} catch (Exception e) {\n\t\t\tfail(\"wrong exception thrown\");\n\t\t}\n\t\t\n\t\t// 2 tries to write but fails, because 1 is still reading\n\t\ttry {\n\t\t\trw.goWrite(2);\n\t\t\tfail();\n\t\t} catch (IllegalStateException e) {\n\t\t\t\n\t\t} catch (Exception e) {\n\t\t\tfail(\"wrong exception thrown\");\n\t\t}\n\t\t\n\t\t// 1 exits, and at this point 2 can access\n\t\trw.exit(1);\n\t\trw.goWrite(2);\n\t}\n\t\n\t// you can't make someone exit who is not reading/writing\n\t\[email protected](expected = IllegalStateException.class)\n\t\tpublic void testCantExitIfNotAccessing() {\n\t\t\tfinal RWController rw = this.rwf.createPermissive();\n\t\t\t\n\t\t\tassertEquals(0, rw.enter());\n\t\t\trw.exit(0);\n\t\t}\n\t\t\n\t\t// you can't make someone read/write who is already doing it\n\t\[email protected](expected = IllegalStateException.class)\n\t\tpublic void testCantAccessIfAlreadyAccessing() {\n\t\t\tfinal RWController rw = this.rwf.createPermissive();\n\t\t\t\n\t\t\tassertEquals(0, rw.enter());\n\t\t\trw.goRead(0);\n\t\t\trw.goWrite(0);\n\t\t}\n\t\t\n\t\t// you can't make someone read/write who hasn't had an id\n\t\[email protected](expected = IllegalStateException.class)\n\t\tpublic void optionalTestWrongId() {\n\t\t\tfinal RWController rw = this.rwf.createPermissive();\n\t\t\t\n\t\t\tassertEquals(0, rw.enter());\n\t\t\trw.goRead(1);\n\t\t}\n\t\t\n\t\t// you can't make someone read/write who has already exited\n\t\[email protected](expected = IllegalStateException.class)\n\t\tpublic void optionalTestAlreadyExited() {\n\t\t\tfinal RWController rw = this.rwf.createPermissive();\n\t\t\t\n\t\t\tassertEquals(0, rw.enter());\n\t\t\trw.goRead(0);\n\t\t\trw.exit(0);\n\t\t\trw.goRead(0);\n\t\t}\n\n\t\n\[email protected]\n\tpublic void optionalTestManyReadersOneWriter() {\n\t\t// test of an RWController that either lets multiple processes read, or lets one process write\n\t\tfinal RWController rw = this.rwf.createManyReadersOrOneWriter();\n\t\t\n\t\tassertEquals(0, rw.enter());\n\t\tassertEquals(1, rw.enter());\n\t\tassertEquals(2, rw.enter());\n\t\t\n\t\t// 0 and 1 can both read\n\t\trw.goRead(0);\n\t\trw.goRead(1);\n\t\trw.exit(0);\n\t\trw.exit(1);\n\t\t\n\t\tassertEquals(3, rw.enter());\n\t\t\n\t\t// 2 reads\n\t\trw.goRead(2);\n\t\t\n\t\t// 3 cannot write, because you either read or write\n\t\ttry {\n\t\t\trw.goWrite(3);\n\t\t\tfail();\n\t\t} catch (IllegalStateException e) {\n\t\t\t\n\t\t} catch (Exception e) {\n\t\t\tfail(\"wrong exception thrown\");\n\t\t}\n\t\t\n\t\t// 2 exits, 3 enters and writes\n\t\trw.exit(2);\n\t\trw.goWrite(3);\n\t\t\n\t\t\n\t\tassertEquals(4, rw.enter());\n\t\t\n\t\t// 4 cannot write, because only one writes at a time\n\t\ttry {\n\t\t\trw.goWrite(4);\n\t\t\tfail();\n\t\t} catch (IllegalStateException e) {\n\t\t\t\n\t\t} catch (Exception e) {\n\t\t\tfail(\"wrong exception thrown\");\n\t\t}\n\t\t\n\t\t// 4 cannot even read\n\t\ttry {\n\t\t\trw.goRead(4);\n\t\t\tfail();\n\t\t} catch (IllegalStateException e) {\n\t\t\t\n\t\t} catch (Exception e) {\n\t\t\tfail(\"wrong exception thrown\");\n\t\t}\n\t\t\n\t}\n\t\n}", "filename": "Test.java" }
2019
a02b
[ { "content": "package a02b.sol1;\n\npublic interface ExamsFactory {\n\t\n\t\n\tenum SimpleExamActivities {\n\t\tWRITTEN, ORAL, REGISTER\n\t}\n\t\n\t\n\tCourseExam<SimpleExamActivities> simpleExam();\n\n\t\n\tenum OOPExamActivities {\n\t\tLAB_REGISTER, LAB_EXAM, PROJ_PROPOSE, PROJ_SUBMIT, PROJ_EXAM, FINAL_EVALUATION,\n\t\t \n\t\tSTUDY, CSHARP_TASK\n\t}\n\t\n\t\n\tCourseExam<OOPExamActivities> simpleOopExam();\n\t\n\t\n\tCourseExam<OOPExamActivities> fullOopExam();\n}", "filename": "ExamsFactory.java" }, { "content": "package 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 a02b.sol1;\n\nimport java.util.Set;\n\n\npublic interface CourseExam<A> {\n\t\n\t\n\tSet<A> activities();\n\t\n\t\n\tSet<A> getPendingActivities();\n\t\n\t\n\tvoid completed(A a);\n\t\n\t\n\tboolean examOver();\n\n}", "filename": "CourseExam.java" } ]
[ { "content": "package a02b.sol1;\n\nimport java.util.*;\nimport java.util.stream.*;\nimport static a02b.sol1.ExamsFactory.SimpleExamActivities.*;\nimport static a02b.sol1.ExamsFactory.OOPExamActivities.*;\n\npublic class ExamsFactoryImpl implements ExamsFactory {\n\t\n\t// the map associates to an activity those it needs to be done before (see a02a.sol1)\n\tprivate <A> CourseExam<A> fromGraph(Map<A,Set<A>> map) {\n\t\treturn new CourseExam<>() {\n\t\t\t\n\t\t\tprivate Set<A> done = new HashSet<>();\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic Set<A> activities() {\n\t\t\t\treturn map.keySet();\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Set<A> getPendingActivities() {\n\t\t\t\treturn this.examOver() ? Set.of() : this.activities().stream().filter(this::canBeDone).collect(Collectors.toSet());\n\t\t\t}\n\t\t\t\n\t\t\tprivate boolean canBeDone(A activity) {\n\t\t\t\treturn !this.done.contains(activity) && this.done.containsAll(map.get(activity));\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void completed(A activity) {\n\t\t\t\tif (!this.getPendingActivities().contains(activity)) {\n\t\t\t\t\tthrow new IllegalStateException();\n\t\t\t\t}\n\t\t\t\tthis.done.add(activity);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic boolean examOver() {\n\t\t\t\treturn this.done.equals(this.activities());\n\t\t\t}\n\t\t\t\n\t\t};\n\t}\n\t\n\t@Override\n\tpublic CourseExam<SimpleExamActivities> simpleExam() {\n\t\treturn fromGraph(Map.of(\n\t\t\t\tWRITTEN, Set.of(),\n\t\t\t\tORAL, Set.of(WRITTEN),\n\t\t\t\tREGISTER, Set.of(ORAL)\n\t\t\t));\n\t}\n\n\t@Override\n\tpublic CourseExam<OOPExamActivities> simpleOopExam() {\n\t\treturn fromGraph(Map.of(\n\t\t\tLAB_REGISTER, Set.of(),\n\t\t\tLAB_EXAM, Set.of(LAB_REGISTER),\n\t\t\tPROJ_PROPOSE, Set.of(),\n\t\t\tPROJ_SUBMIT, Set.of(PROJ_PROPOSE),\n\t\t\tPROJ_EXAM, Set.of(PROJ_SUBMIT),\n\t\t\tFINAL_EVALUATION, Set.of(PROJ_EXAM,LAB_EXAM)\n\t\t));\n\t}\n\t\n\t@Override\n\tpublic CourseExam<OOPExamActivities> fullOopExam() {\n\t\treturn fromGraph(Map.of(\n\t\t\tSTUDY, Set.of(),\n\t\t\tLAB_REGISTER, Set.of(STUDY),\n\t\t\tLAB_EXAM, Set.of(LAB_REGISTER),\n\t\t\tPROJ_PROPOSE, Set.of(STUDY),\n\t\t\tPROJ_SUBMIT, Set.of(PROJ_PROPOSE),\n\t\t\tPROJ_EXAM, Set.of(PROJ_SUBMIT),\n\t\t\tCSHARP_TASK, Set.of(PROJ_SUBMIT),\n\t\t\tFINAL_EVALUATION, Set.of(CSHARP_TASK,PROJ_EXAM,LAB_EXAM)\n\t\t));\n\t}\n\n}", "filename": "ExamsFactoryImpl.java" } ]
{ "components": { "imports": "package a02b.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;\nimport static a02b.sol1.ExamsFactory.SimpleExamActivities.*;\nimport static a02b.sol1.ExamsFactory.OOPExamActivities.*;", "private_init": "\t/*\n\t * Implement the ExamsFactory interface as indicated in the initFactory method below.\n\t * Implement a factory concept for ExamCourse<A>, which in turn models the activities (of type A) to be performed\n\t * to pass a university exam, and the dependencies between them:\n\t * - each activity can be performed only once\n\t * - when all activities are completed, the exam is finished\n\t * - there are specific constraints on when an activity can be performed, expressed in terms of the completed execution of other activities\n\t * For example, a common exam mode involves first the written exam, then the oral exam, and then the registration of the grade; in others (such as OOP) there\n\t * are instead different tests that can be performed in any order (project and practical are in parallel, and only when I have completed both can I register).\n\t * \n\t * The comment on the provided interfaces, and the test methods below constitute the necessary explanation of the\n\t * problem.\n\t * \n\t * The following are considered optional for the purpose of being able to correct the exercise, but still contribute to achieving\n\t * the totality of the score:\n\t * - implementation of the tests called optionalTestXYZ (related to the ExamsFactory.fullOopExam method)\n\t * - the good design of the solution, in particular with minimization of repetitions\n\t * \n\t * Remove the comment from the initFactory method.\n\t * \n\t * Scoring indications:\n\t * - correctness of the mandatory part: 9 points\n\t * - correctness of the optional part: 4 points\n\t * - quality of the solution: 4 points\n\t * \n\t */\n\n\t\n\tprivate ExamsFactory wf = null;\n\t\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.wf = new ExamsFactoryImpl();\n\t}", "test_functions": [ "\[email protected]\n\tpublic void testSimpleExam() {\n\t\t// An exam in which first \"WRITTEN\" must be done, then \"ORAL\", then \"REGISTER\"\n\t\tfinal CourseExam<ExamsFactory.SimpleExamActivities> w = this.wf.simpleExam();\n\t\t\t\t\n\t\tassertEquals(Set.of(WRITTEN,ORAL,REGISTER),w.activities()); // the activities to be carried out\n\t\tassertFalse(w.examOver());\t\t\t\t\t\t\t\t\t// the exam is not finished\n\t\tassertEquals(Set.of(WRITTEN),w.getPendingActivities());\t\t// the next activities to be carried out\n\t\t\n\t\t// completed WRITTEN, exam not yet finished, the next is ORAL\n\t\tw.completed(WRITTEN);\n\t\tassertFalse(w.examOver());\n\t\tassertEquals(Set.of(ORAL),w.getPendingActivities());\n\t\t\n\t\t// completed ORAL, exam not yet finished, the next is REGISTER\n\t\tw.completed(ORAL);\n\t\tassertFalse(w.examOver());\n\t\tassertEquals(Set.of(REGISTER),w.getPendingActivities());\n\t\t\n\t\t// completed REGISTER, exam finished\n\t\tw.completed(REGISTER);\n\t\tassertTrue(w.examOver());\n\t\tassertEquals(Set.of(),w.getPendingActivities());\n\t}", "\[email protected]\n\tpublic void testSimpleOOPExam() { \n\t\t// An OOP type exam\n\t\tfinal CourseExam<ExamsFactory.OOPExamActivities> w = this.wf.simpleOopExam();\n\t\t\t\t\n\t\tassertEquals(Set.of(LAB_REGISTER,LAB_EXAM,PROJ_PROPOSE,PROJ_SUBMIT,PROJ_EXAM,FINAL_EVALUATION),w.activities());\t\t\n\t\tassertFalse(w.examOver());\n\t\tassertEquals(Set.of(LAB_REGISTER,PROJ_PROPOSE),w.getPendingActivities());\n\t\t\n\t\t// completed LAB_REGISTER, exam not yet finished, now I have to do LAB_EXAM, but also PROJ_PROPOSE\n\t\tw.completed(LAB_REGISTER);\n\t\tassertFalse(w.examOver());\n\t\tassertEquals(Set.of(LAB_EXAM,PROJ_PROPOSE),w.getPendingActivities());\n\t\t\n\t\t// completed PROJ_PROPOSE, exam not yet finished, now I have to do LAB_EXAM, but also PROJ_SUBMIT\n\t\tw.completed(PROJ_PROPOSE);\n\t\tassertFalse(w.examOver());\n\t\tassertEquals(Set.of(LAB_EXAM,PROJ_SUBMIT),w.getPendingActivities());\n\t\t\n\t\t// completed LAB_EXAM, exam not yet finished, now I have to do PROJ_SUBMIT\n\t\tw.completed(LAB_EXAM);\n\t\tassertFalse(w.examOver());\n\t\tassertEquals(Set.of(PROJ_SUBMIT),w.getPendingActivities());\n\t\t\n\t\t// completed PROJ_SUBMIT, exam not yet finished, now I have to do PROJ_EXAM\n\t\tw.completed(PROJ_SUBMIT);\n\t\tassertFalse(w.examOver());\n\t\tassertEquals(Set.of(PROJ_EXAM),w.getPendingActivities());\n\t\t\n\t\t// completed PROJ_EXAM, exam not yet finished, now I have to do FINAL_EVALUATION\n\t\tw.completed(PROJ_EXAM);\n\t\tassertFalse(w.examOver());\n\t\tassertEquals(Set.of(FINAL_EVALUATION),w.getPendingActivities());\n\t\t\n\t\t// completed PROJ_EXAM, exam finished\n\t\tw.completed(FINAL_EVALUATION);\n\t\tassertTrue(w.examOver());\n\t\tassertEquals(Set.of(),w.getPendingActivities());\n\t}", "\[email protected]\n\tpublic void optionalTestFullOOPExam1() {\n\t\t// An extended variant of the OOP exam above\n\t\tfinal CourseExam<ExamsFactory.OOPExamActivities> w = this.wf.fullOopExam();\n\t\t\n\t\t// in addition: STUDY and CSHARP_TASK.. we start with STUDY\n\t\tassertEquals(Set.of(STUDY,LAB_REGISTER,LAB_EXAM,PROJ_PROPOSE,PROJ_SUBMIT,PROJ_EXAM,CSHARP_TASK,FINAL_EVALUATION),w.activities());\t\t\n\t\tassertFalse(w.examOver());\n\t\tassertEquals(Set.of(STUDY),w.getPendingActivities());\n\t\t\n\t\tw.completed(STUDY);\n\t\tassertFalse(w.examOver());\n\t\tassertEquals(Set.of(LAB_REGISTER,PROJ_PROPOSE),w.getPendingActivities());\n\t\t\n\t\tw.completed(LAB_REGISTER);\n\t\tassertFalse(w.examOver());\n\t\tassertEquals(Set.of(LAB_EXAM,PROJ_PROPOSE),w.getPendingActivities());\n\t\t\n\t\tw.completed(PROJ_PROPOSE);\n\t\tassertFalse(w.examOver());\n\t\tassertEquals(Set.of(LAB_EXAM,PROJ_SUBMIT),w.getPendingActivities());\n\t\t\n\t\tw.completed(LAB_EXAM);\n\t\tassertFalse(w.examOver());\n\t\tassertEquals(Set.of(PROJ_SUBMIT),w.getPendingActivities());\n\t\t\n\t\t// Project submitted, now you can also work on the Csharp task\n\t\tw.completed(PROJ_SUBMIT);\n\t\tassertFalse(w.examOver());\n\t\tassertEquals(Set.of(PROJ_EXAM,CSHARP_TASK),w.getPendingActivities());\n\t\t\n\t\t// Csharp task completed, only PROJ_EXAM1 remains\n\t\tw.completed(CSHARP_TASK);\n\t\tassertFalse(w.examOver());\n\t\tassertEquals(Set.of(PROJ_EXAM),w.getPendingActivities());\n\t\t\n\t\tw.completed(PROJ_EXAM);\n\t\tassertFalse(w.examOver());\n\t\tassertEquals(Set.of(FINAL_EVALUATION),w.getPendingActivities());\n\t\t\n\t\tw.completed(FINAL_EVALUATION);\n\t\tassertTrue(w.examOver());\n\t\tassertEquals(Set.of(),w.getPendingActivities());\n\t}", "\[email protected]\n\tpublic void optionalTestFullOOPExam2() {\n\t\t// As before, but now the C# task is performed after completing the project\n\t\tfinal CourseExam<ExamsFactory.OOPExamActivities> w = this.wf.fullOopExam();\n\t\t\n\t\t// in addition: STUDY and CSHARP_TASK.. we start with STUDY\n\t\tassertEquals(Set.of(STUDY,LAB_REGISTER,LAB_EXAM,PROJ_PROPOSE,PROJ_SUBMIT,PROJ_EXAM,CSHARP_TASK,FINAL_EVALUATION),w.activities());\t\t\n\t\tassertFalse(w.examOver());\n\t\tassertEquals(Set.of(STUDY),w.getPendingActivities());\n\t\t\n\t\tw.completed(STUDY);\n\t\tassertFalse(w.examOver());\n\t\tassertEquals(Set.of(LAB_REGISTER,PROJ_PROPOSE),w.getPendingActivities());\n\t\t\n\t\tw.completed(LAB_REGISTER);\n\t\tassertFalse(w.examOver());\n\t\tassertEquals(Set.of(LAB_EXAM,PROJ_PROPOSE),w.getPendingActivities());\n\t\t\n\t\tw.completed(PROJ_PROPOSE);\n\t\tassertFalse(w.examOver());\n\t\tassertEquals(Set.of(LAB_EXAM,PROJ_SUBMIT),w.getPendingActivities());\n\t\t\n\t\tw.completed(LAB_EXAM);\n\t\tassertFalse(w.examOver());\n\t\tassertEquals(Set.of(PROJ_SUBMIT),w.getPendingActivities());\n\t\t\n\t\t// Project submitted, now you can also work on the Csharp task\n\t\tw.completed(PROJ_SUBMIT);\n\t\tassertFalse(w.examOver());\n\t\tassertEquals(Set.of(PROJ_EXAM,CSHARP_TASK),w.getPendingActivities());\n\t\t\n\t\t// Project completed, the csharp task remains\n\t\tw.completed(PROJ_EXAM);\n\t\tassertFalse(w.examOver());\n\t\tassertEquals(Set.of(CSHARP_TASK),w.getPendingActivities());\n\t\t\n\t\tw.completed(CSHARP_TASK);\n\t\tassertFalse(w.examOver());\n\t\tassertEquals(Set.of(FINAL_EVALUATION),w.getPendingActivities());\n\t\t\t\t\n\t\t\n\t\tw.completed(FINAL_EVALUATION);\n\t\tassertTrue(w.examOver());\n\t\tassertEquals(Set.of(),w.getPendingActivities());\n\t}" ] }, "content": "package a02b.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;\nimport static a02b.sol1.ExamsFactory.SimpleExamActivities.*;\nimport static a02b.sol1.ExamsFactory.OOPExamActivities.*;\n\npublic class Test {\n\t\n\t/*\n\t * Implement the ExamsFactory interface as indicated in the initFactory method below.\n\t * Implement a factory concept for ExamCourse<A>, which in turn models the activities (of type A) to be performed\n\t * to pass a university exam, and the dependencies between them:\n\t * - each activity can be performed only once\n\t * - when all activities are completed, the exam is finished\n\t * - there are specific constraints on when an activity can be performed, expressed in terms of the completed execution of other activities\n\t * For example, a common exam mode involves first the written exam, then the oral exam, and then the registration of the grade; in others (such as OOP) there\n\t * are instead different tests that can be performed in any order (project and practical are in parallel, and only when I have completed both can I register).\n\t * \n\t * The comment on the provided interfaces, and the test methods below constitute the necessary explanation of the\n\t * problem.\n\t * \n\t * The following are considered optional for the purpose of being able to correct the exercise, but still contribute to achieving\n\t * the totality of the score:\n\t * - implementation of the tests called optionalTestXYZ (related to the ExamsFactory.fullOopExam method)\n\t * - the good design of the solution, in particular with minimization of repetitions\n\t * \n\t * Remove the comment from the initFactory method.\n\t * \n\t * Scoring indications:\n\t * - correctness of the mandatory part: 9 points\n\t * - correctness of the optional part: 4 points\n\t * - quality of the solution: 4 points\n\t * \n\t */\n\n\t\n\tprivate ExamsFactory wf = null;\n\t\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.wf = new ExamsFactoryImpl();\n\t}\n\n\[email protected]\n\tpublic void testSimpleExam() {\n\t\t// An exam in which first \"WRITTEN\" must be done, then \"ORAL\", then \"REGISTER\"\n\t\tfinal CourseExam<ExamsFactory.SimpleExamActivities> w = this.wf.simpleExam();\n\t\t\t\t\n\t\tassertEquals(Set.of(WRITTEN,ORAL,REGISTER),w.activities()); // the activities to be carried out\n\t\tassertFalse(w.examOver());\t\t\t\t\t\t\t\t\t// the exam is not finished\n\t\tassertEquals(Set.of(WRITTEN),w.getPendingActivities());\t\t// the next activities to be carried out\n\t\t\n\t\t// completed WRITTEN, exam not yet finished, the next is ORAL\n\t\tw.completed(WRITTEN);\n\t\tassertFalse(w.examOver());\n\t\tassertEquals(Set.of(ORAL),w.getPendingActivities());\n\t\t\n\t\t// completed ORAL, exam not yet finished, the next is REGISTER\n\t\tw.completed(ORAL);\n\t\tassertFalse(w.examOver());\n\t\tassertEquals(Set.of(REGISTER),w.getPendingActivities());\n\t\t\n\t\t// completed REGISTER, exam finished\n\t\tw.completed(REGISTER);\n\t\tassertTrue(w.examOver());\n\t\tassertEquals(Set.of(),w.getPendingActivities());\n\t}\n\t\n\[email protected]\n\tpublic void testSimpleOOPExam() { \n\t\t// An OOP type exam\n\t\tfinal CourseExam<ExamsFactory.OOPExamActivities> w = this.wf.simpleOopExam();\n\t\t\t\t\n\t\tassertEquals(Set.of(LAB_REGISTER,LAB_EXAM,PROJ_PROPOSE,PROJ_SUBMIT,PROJ_EXAM,FINAL_EVALUATION),w.activities());\t\t\n\t\tassertFalse(w.examOver());\n\t\tassertEquals(Set.of(LAB_REGISTER,PROJ_PROPOSE),w.getPendingActivities());\n\t\t\n\t\t// completed LAB_REGISTER, exam not yet finished, now I have to do LAB_EXAM, but also PROJ_PROPOSE\n\t\tw.completed(LAB_REGISTER);\n\t\tassertFalse(w.examOver());\n\t\tassertEquals(Set.of(LAB_EXAM,PROJ_PROPOSE),w.getPendingActivities());\n\t\t\n\t\t// completed PROJ_PROPOSE, exam not yet finished, now I have to do LAB_EXAM, but also PROJ_SUBMIT\n\t\tw.completed(PROJ_PROPOSE);\n\t\tassertFalse(w.examOver());\n\t\tassertEquals(Set.of(LAB_EXAM,PROJ_SUBMIT),w.getPendingActivities());\n\t\t\n\t\t// completed LAB_EXAM, exam not yet finished, now I have to do PROJ_SUBMIT\n\t\tw.completed(LAB_EXAM);\n\t\tassertFalse(w.examOver());\n\t\tassertEquals(Set.of(PROJ_SUBMIT),w.getPendingActivities());\n\t\t\n\t\t// completed PROJ_SUBMIT, exam not yet finished, now I have to do PROJ_EXAM\n\t\tw.completed(PROJ_SUBMIT);\n\t\tassertFalse(w.examOver());\n\t\tassertEquals(Set.of(PROJ_EXAM),w.getPendingActivities());\n\t\t\n\t\t// completed PROJ_EXAM, exam not yet finished, now I have to do FINAL_EVALUATION\n\t\tw.completed(PROJ_EXAM);\n\t\tassertFalse(w.examOver());\n\t\tassertEquals(Set.of(FINAL_EVALUATION),w.getPendingActivities());\n\t\t\n\t\t// completed PROJ_EXAM, exam finished\n\t\tw.completed(FINAL_EVALUATION);\n\t\tassertTrue(w.examOver());\n\t\tassertEquals(Set.of(),w.getPendingActivities());\n\t}\n\t\n\[email protected]\n\tpublic void optionalTestFullOOPExam1() {\n\t\t// An extended variant of the OOP exam above\n\t\tfinal CourseExam<ExamsFactory.OOPExamActivities> w = this.wf.fullOopExam();\n\t\t\n\t\t// in addition: STUDY and CSHARP_TASK.. we start with STUDY\n\t\tassertEquals(Set.of(STUDY,LAB_REGISTER,LAB_EXAM,PROJ_PROPOSE,PROJ_SUBMIT,PROJ_EXAM,CSHARP_TASK,FINAL_EVALUATION),w.activities());\t\t\n\t\tassertFalse(w.examOver());\n\t\tassertEquals(Set.of(STUDY),w.getPendingActivities());\n\t\t\n\t\tw.completed(STUDY);\n\t\tassertFalse(w.examOver());\n\t\tassertEquals(Set.of(LAB_REGISTER,PROJ_PROPOSE),w.getPendingActivities());\n\t\t\n\t\tw.completed(LAB_REGISTER);\n\t\tassertFalse(w.examOver());\n\t\tassertEquals(Set.of(LAB_EXAM,PROJ_PROPOSE),w.getPendingActivities());\n\t\t\n\t\tw.completed(PROJ_PROPOSE);\n\t\tassertFalse(w.examOver());\n\t\tassertEquals(Set.of(LAB_EXAM,PROJ_SUBMIT),w.getPendingActivities());\n\t\t\n\t\tw.completed(LAB_EXAM);\n\t\tassertFalse(w.examOver());\n\t\tassertEquals(Set.of(PROJ_SUBMIT),w.getPendingActivities());\n\t\t\n\t\t// Project submitted, now you can also work on the Csharp task\n\t\tw.completed(PROJ_SUBMIT);\n\t\tassertFalse(w.examOver());\n\t\tassertEquals(Set.of(PROJ_EXAM,CSHARP_TASK),w.getPendingActivities());\n\t\t\n\t\t// Csharp task completed, only PROJ_EXAM1 remains\n\t\tw.completed(CSHARP_TASK);\n\t\tassertFalse(w.examOver());\n\t\tassertEquals(Set.of(PROJ_EXAM),w.getPendingActivities());\n\t\t\n\t\tw.completed(PROJ_EXAM);\n\t\tassertFalse(w.examOver());\n\t\tassertEquals(Set.of(FINAL_EVALUATION),w.getPendingActivities());\n\t\t\n\t\tw.completed(FINAL_EVALUATION);\n\t\tassertTrue(w.examOver());\n\t\tassertEquals(Set.of(),w.getPendingActivities());\n\t}\n\t\n\[email protected]\n\tpublic void optionalTestFullOOPExam2() {\n\t\t// As before, but now the C# task is performed after completing the project\n\t\tfinal CourseExam<ExamsFactory.OOPExamActivities> w = this.wf.fullOopExam();\n\t\t\n\t\t// in addition: STUDY and CSHARP_TASK.. we start with STUDY\n\t\tassertEquals(Set.of(STUDY,LAB_REGISTER,LAB_EXAM,PROJ_PROPOSE,PROJ_SUBMIT,PROJ_EXAM,CSHARP_TASK,FINAL_EVALUATION),w.activities());\t\t\n\t\tassertFalse(w.examOver());\n\t\tassertEquals(Set.of(STUDY),w.getPendingActivities());\n\t\t\n\t\tw.completed(STUDY);\n\t\tassertFalse(w.examOver());\n\t\tassertEquals(Set.of(LAB_REGISTER,PROJ_PROPOSE),w.getPendingActivities());\n\t\t\n\t\tw.completed(LAB_REGISTER);\n\t\tassertFalse(w.examOver());\n\t\tassertEquals(Set.of(LAB_EXAM,PROJ_PROPOSE),w.getPendingActivities());\n\t\t\n\t\tw.completed(PROJ_PROPOSE);\n\t\tassertFalse(w.examOver());\n\t\tassertEquals(Set.of(LAB_EXAM,PROJ_SUBMIT),w.getPendingActivities());\n\t\t\n\t\tw.completed(LAB_EXAM);\n\t\tassertFalse(w.examOver());\n\t\tassertEquals(Set.of(PROJ_SUBMIT),w.getPendingActivities());\n\t\t\n\t\t// Project submitted, now you can also work on the Csharp task\n\t\tw.completed(PROJ_SUBMIT);\n\t\tassertFalse(w.examOver());\n\t\tassertEquals(Set.of(PROJ_EXAM,CSHARP_TASK),w.getPendingActivities());\n\t\t\n\t\t// Project completed, the csharp task remains\n\t\tw.completed(PROJ_EXAM);\n\t\tassertFalse(w.examOver());\n\t\tassertEquals(Set.of(CSHARP_TASK),w.getPendingActivities());\n\t\t\n\t\tw.completed(CSHARP_TASK);\n\t\tassertFalse(w.examOver());\n\t\tassertEquals(Set.of(FINAL_EVALUATION),w.getPendingActivities());\n\t\t\t\t\n\t\t\n\t\tw.completed(FINAL_EVALUATION);\n\t\tassertTrue(w.examOver());\n\t\tassertEquals(Set.of(),w.getPendingActivities());\n\t}\n}", "filename": "Test.java" }
2019
a06b
[ { "content": "package a06b.sol1;\n\nimport java.util.List;\n\n\npublic interface MiniAssemblyMachine {\n\t\n\t\n\tvoid inc(int register);\n\t\n\t\n\tvoid dec(int register);\n\t\n\t\n\tvoid jnz(int register, int target);\n\t\n\t\n\tvoid ret();\n\t\n\t\n\tList<Integer> execute(List<Integer> registers);\n\t\n}", "filename": "MiniAssemblyMachine.java" }, { "content": "package a06b.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 a06b.sol1;\n\nimport java.util.ArrayList;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Optional;\n\npublic class MiniAssemblyMachineImpl implements MiniAssemblyMachine {\n\t\n\tinterface Instruction {\n\t\tPair<Optional<Integer>,List<Integer>> exec(int counter, List<Integer> registers);\n\t}\t\n\t\n\tprivate List<Instruction> program = new LinkedList<>();\n\t\n\t\n\t@Override\n\tpublic void inc(int register) {\n\t\tInstruction i = (c,r) -> { r.set(register, r.get(register)+1); return new Pair<>(Optional.of(c+1), r);};\n\t\tprogram.add(i);\n\t}\n\n\t@Override\n\tpublic void dec(int register) {\n\t\tInstruction i = (c,r) -> { r.set(register, r.get(register)-1); return new Pair<>(Optional.of(c+1), r);};\n\t\tprogram.add(i);\n\t}\n\n\t@Override\n\tpublic void jnz(int register, int target) {\n\t\tInstruction i = (c,r) -> new Pair<>(Optional.of(r.get(register)!=0? target: c+1), r);\n\t\tprogram.add(i);\n\t}\n\t\n\t@Override\n\tpublic void ret() {\n\t\tInstruction i = (c,r) -> new Pair<>(Optional.empty(),r);\n\t\tprogram.add(i);\n\t}\n\n\t@Override\n\tpublic \tList<Integer> execute(List<Integer> registers){\n\t\treturn execAt(0, new ArrayList<>(registers)).getY(); // Note defensive copy\n\t}\n\t\t\n\tprivate Pair<Optional<Integer>,List<Integer>> execAt(int line, List<Integer> registers) {\n\t\tif (program.size()<=line) {\n\t\t\tthrow new IllegalStateException();\n\t\t}\n\t\tvar res = program.get(line).exec(line, registers);\n\t\tif (res.getX().isEmpty()) {\n\t\t\treturn res;\n\t\t} else {\n\t\t\treturn execAt(res.getX().get(),res.getY());\n\t\t}\n\t}\n\t \n}", "filename": "MiniAssemblyMachineImpl.java" } ]
{ "components": { "imports": "package a06b.sol1;\n\nimport static org.junit.Assert.*;\n\nimport java.util.Iterator;\nimport java.util.LinkedList;\nimport java.util.List;", "private_init": "\t/*\n\t * Implement the MiniAssemblyMachine interface as indicated in the initFactory method below.\n\t * Implement an interpreter for a mini-assembly with only INC (increment a register),\n\t * DEC (decrement a register), JNZ (Jump if a register is not zero) and RET (terminate execution) instructions.\n\t * \n\t * The comment on the provided interfaces, and the test methods below constitute the necessary\n\t * explanation of the problem.\n\t * \n\t * The following are considered optional for the purpose of being able to correct the exercise,\n\t * but still contribute to achieving the totality of the score:\n\t * - implementation of the tests called optionalTestXYZ (related to exception checks)\n\t * - the good design of the solution, in particular with minimization of repetitions\n\t * \n\t * Remove the comment from the initFactory method.\n\t * \n\t * Scoring indications:\n\t * - correctness of the mandatory part: 9 points\n\t * - correctness of the optional part: 4 points\n\t * - quality of the solution: 4 points\n\t * \n\t */\n\t\n\tprivate MiniAssemblyMachine machine = null;\n\t\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.machine = new MiniAssemblyMachineImpl();\n\t}", "test_functions": [ "\[email protected]\n\tpublic void testInc() {\n\t\tthis.machine.inc(0); // 0: INC R0\n\t\tthis.machine.inc(1); // 1: INC R1\n\t\tthis.machine.inc(1); // 2: INC R1\n\t\tthis.machine.ret(); // 3: RET\n\t\t// Input: R0 = 10, R1 = 20, R2 = 30 \n\t\t// Output: R0 = 11, R1 = 22, R2 = 30\n\t\tassertEquals(List.of(11,22,30),this.machine.execute(List.of(10,20,30)));\n\t}", "\[email protected]\n\tpublic void testDec() {\n\t\tthis.machine.dec(0); // 0: DEC R0\n\t\tthis.machine.dec(1); // 1: DEC R1\n\t\tthis.machine.dec(1); // 2: DEC R1\n\t\tthis.machine.ret(); // 3: RET\n\t\tassertEquals(List.of(9,18,30),this.machine.execute(List.of(10,20,30)));\n\t}", "\[email protected]\n\tpublic void testJnz() {\n\t\tthis.machine.jnz(0, 2); // 0: JNZ R0, #2\n\t\tthis.machine.ret();\t\t// 1: RET\n\t\tthis.machine.inc(0);\t// 2: INC R0\n\t\tthis.machine.ret();\t\t// 3: RET\n\t\tassertEquals(List.of(11,20,30),this.machine.execute(List.of(10,20,30)));\n\t\tassertEquals(List.of(0,20,30),this.machine.execute(List.of(0,20,30)));\n\t}", "\[email protected]\n\tpublic void testSum() {\n\t\tthis.machine.jnz(0, 2);\t// 0: JNZ R0, #2\n\t\tthis.machine.ret();\t\t// 1: RET\n\t\tthis.machine.dec(0);\t// 2: DEC R0\n\t\tthis.machine.inc(1);\t// 3: INC R1\n\t\tthis.machine.jnz(0, 2);\t// 4: JNZ R0, #2\n\t\tthis.machine.ret();\t\t// 5: RET\n\t\tassertEquals(List.of(0,300),this.machine.execute(List.of(100,200)));\n\t}", "\[email protected]\n\tpublic void optionalTestBadJump() {\n\t\t// The next instruction, for JUMP or normal sequential execution, must be there!\n\t\tthis.machine.jnz(0, 2);\n\t\tthis.machine.ret();\n\t\ttry {\n\t\t\tthis.machine.execute(List.of(1));\n\t\t\tfail(\"Exception 'bad jump' required\");\n\t\t}", "\[email protected]\n\tpublic void optionalTestBadRegister() {\n\t\t// Be careful not to access non-existent registers!\n\t\tthis.machine.inc(1);\n\t\tthis.machine.ret();\n\t\ttry {\n\t\t\tthis.machine.execute(List.of(1));\n\t\t\tfail(\"Exception 'wrong register' required\");\n\t\t}" ] }, "content": "package a06b.sol1;\n\nimport static org.junit.Assert.*;\n\nimport java.util.Iterator;\nimport java.util.LinkedList;\nimport java.util.List;\n\npublic class Test {\n\t\n\t/*\n\t * Implement the MiniAssemblyMachine interface as indicated in the initFactory method below.\n\t * Implement an interpreter for a mini-assembly with only INC (increment a register),\n\t * DEC (decrement a register), JNZ (Jump if a register is not zero) and RET (terminate execution) instructions.\n\t * \n\t * The comment on the provided interfaces, and the test methods below constitute the necessary\n\t * explanation of the problem.\n\t * \n\t * The following are considered optional for the purpose of being able to correct the exercise,\n\t * but still contribute to achieving the totality of the score:\n\t * - implementation of the tests called optionalTestXYZ (related to exception checks)\n\t * - the good design of the solution, in particular with minimization of repetitions\n\t * \n\t * Remove the comment from the initFactory method.\n\t * \n\t * Scoring indications:\n\t * - correctness of the mandatory part: 9 points\n\t * - correctness of the optional part: 4 points\n\t * - quality of the solution: 4 points\n\t * \n\t */\n\t\n\tprivate MiniAssemblyMachine machine = null;\n\t\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.machine = new MiniAssemblyMachineImpl();\n\t}\n\t\n\[email protected]\n\tpublic void testInc() {\n\t\tthis.machine.inc(0); // 0: INC R0\n\t\tthis.machine.inc(1); // 1: INC R1\n\t\tthis.machine.inc(1); // 2: INC R1\n\t\tthis.machine.ret(); // 3: RET\n\t\t// Input: R0 = 10, R1 = 20, R2 = 30 \n\t\t// Output: R0 = 11, R1 = 22, R2 = 30\n\t\tassertEquals(List.of(11,22,30),this.machine.execute(List.of(10,20,30)));\n\t}\n\t\n\[email protected]\n\tpublic void testDec() {\n\t\tthis.machine.dec(0); // 0: DEC R0\n\t\tthis.machine.dec(1); // 1: DEC R1\n\t\tthis.machine.dec(1); // 2: DEC R1\n\t\tthis.machine.ret(); // 3: RET\n\t\tassertEquals(List.of(9,18,30),this.machine.execute(List.of(10,20,30)));\n\t}\n\n\t\n\[email protected]\n\tpublic void testJnz() {\n\t\tthis.machine.jnz(0, 2); // 0: JNZ R0, #2\n\t\tthis.machine.ret();\t\t// 1: RET\n\t\tthis.machine.inc(0);\t// 2: INC R0\n\t\tthis.machine.ret();\t\t// 3: RET\n\t\tassertEquals(List.of(11,20,30),this.machine.execute(List.of(10,20,30)));\n\t\tassertEquals(List.of(0,20,30),this.machine.execute(List.of(0,20,30)));\n\t}\n\t\n\[email protected]\n\tpublic void testSum() {\n\t\tthis.machine.jnz(0, 2);\t// 0: JNZ R0, #2\n\t\tthis.machine.ret();\t\t// 1: RET\n\t\tthis.machine.dec(0);\t// 2: DEC R0\n\t\tthis.machine.inc(1);\t// 3: INC R1\n\t\tthis.machine.jnz(0, 2);\t// 4: JNZ R0, #2\n\t\tthis.machine.ret();\t\t// 5: RET\n\t\tassertEquals(List.of(0,300),this.machine.execute(List.of(100,200)));\n\t}\n\t\n\[email protected]\n\tpublic void optionalTestBadJump() {\n\t\t// The next instruction, for JUMP or normal sequential execution, must be there!\n\t\tthis.machine.jnz(0, 2);\n\t\tthis.machine.ret();\n\t\ttry {\n\t\t\tthis.machine.execute(List.of(1));\n\t\t\tfail(\"Exception 'bad jump' required\");\n\t\t} catch (IllegalStateException e){\n\t\t\t\n\t\t} catch (Exception e) {\n\t\t\tfail(\"Wrong exception\");\n\t\t}\n\t}\n\t\n\[email protected]\n\tpublic void optionalTestBadRegister() {\n\t\t// Be careful not to access non-existent registers!\n\t\tthis.machine.inc(1);\n\t\tthis.machine.ret();\n\t\ttry {\n\t\t\tthis.machine.execute(List.of(1));\n\t\t\tfail(\"Exception 'wrong register' required\");\n\t\t} catch (IndexOutOfBoundsException e){\n\t\t\t\n\t\t} catch (Exception e) {\n\t\t\tfail(\"Wrong exception\");\n\t\t}\n\t}\n\t\n\n\t\n}", "filename": "Test.java" }
2019
a01a
[ { "content": "package a01a.sol1;\n\nimport java.util.List;\nimport java.util.Set;\n\npublic interface GraphFactory {\n\n\t\n\t<X> Graph<X> createDirectedChain(List<X> nodes);\n\t\n\t\n\t<X> Graph<X> createBidirectionalChain(List<X> nodes);\n\t\n\t\n\t<X> Graph<X> createDirectedCircle(List<X> nodes);\n\t\n\t\n\t<X> Graph<X> createBidirectionalCircle(List<X> nodes);\n\t\n\t\n\t<X> Graph<X> createDirectedStar(X center, Set<X> nodes);\n\t\n\t\n\t<X> Graph<X> createBidirectionalStar(X center, Set<X> nodes);\n\t\n\t\n\t<X> Graph<X> createFull(Set<X> nodes);\n\t\n\t\n\t<X> Graph<X> combine(Graph<X> g1, Graph<X> g2);\n\t\n\t\n}", "filename": "GraphFactory.java" }, { "content": "package a01a.sol1;\n\nimport java.util.Set;\nimport java.util.stream.Stream;\n\n\npublic interface Graph<X> {\n\t\n\t\n\tSet<X> getNodes();\n\t\n\t\n\tboolean edgePresent(X start, X end);\n\t\n\t\n\tint getEdgesCount();\n\t\n\t\n\tStream<Pair<X,X>> getEdgesStream();\n\n}", "filename": "Graph.java" }, { "content": "package 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 a01a.sol1;\n\nimport java.util.*;\nimport java.util.stream.*;\n\npublic class GraphFactoryImpl implements GraphFactory {\n\t\n\t/**\n\t * A useful internal factory from a stream of edges..\n\t */\n\tprivate static <X> Graph<X> fromStream(Stream<Pair<X,X>> edgesStream){\n\t\treturn new Graph<X>() {\n\t\t\t\n\t\t\tprivate Set<Pair<X,X>> edges = edgesStream.collect(Collectors.toSet());\n\n\t\t\t@Override\n\t\t\tpublic Set<X> getNodes() {\n\t\t\t\treturn this.edges.stream()\n\t\t\t\t\t\t .flatMap(p -> Stream.of(p.getX(),p.getY()))\n\t\t\t\t\t\t .collect(Collectors.toSet());\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic boolean edgePresent(X start, X end) {\n\t\t\t\treturn this.edges.contains(new Pair<>(start,end));\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic int getEdgesCount() {\n\t\t\t\treturn this.edges.size();\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Stream<Pair<X, X>> getEdgesStream() {\n\t\t\t\treturn this.edges.stream();\n\t\t\t}\n\t\t\t\n\t\t};\n\t}\n\t\n\t/**\n\t * A useful internal factory turning a directed graph into a bidirectional one\n\t */\n\tprivate static <X> Graph<X> bidirectionalFromDirected(Graph<X> graph){\n\t\treturn new Graph<X>() {\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic Set<X> getNodes() {\n\t\t\t\treturn graph.getNodes();\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic boolean edgePresent(X start, X end) {\n\t\t\t\treturn graph.edgePresent(start, end) || graph.edgePresent(end, start);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic int getEdgesCount() {\n\t\t\t\treturn graph.getEdgesCount()*2;\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Stream<Pair<X, X>> getEdgesStream() {\n\t\t\t\treturn graph.getEdgesStream().flatMap(p -> Stream.of(p,new Pair<>(p.getY(),p.getX()))).distinct();\n\t\t\t}\n\t\t\t\n\t\t};\n\t}\n\t\n\t// From here everything is rather straightforward\n\n\t@Override\n\tpublic <X> Graph<X> createDirectedChain(List<X> nodes) {\n\t\treturn fromStream(IntStream.range(0, nodes.size()-1).mapToObj(i -> new Pair<>(nodes.get(i),nodes.get(i+1))));\n\t}\n\n\t@Override\n\tpublic <X> Graph<X> createBidirectionalChain(List<X> nodes) {\n\t\treturn bidirectionalFromDirected(createDirectedChain(nodes));\n\t}\n\n\t@Override\n\tpublic <X> Graph<X> createDirectedCircle(List<X> nodes) {\n\t\tList<X> nodesWithEnd = new LinkedList<>(nodes);\n\t\tnodesWithEnd.add(nodes.get(0));\n\t\treturn this.createDirectedChain(nodesWithEnd);\n\t}\n\n\t@Override\n\tpublic <X> Graph<X> createBidirectionalCircle(List<X> nodes) {\n\t\treturn bidirectionalFromDirected(createDirectedCircle(nodes));\n\t}\n\n\t@Override\n\tpublic <X> Graph<X> createDirectedStar(X center, Set<X> nodes) {\n\t\treturn fromStream(nodes.stream().map(n -> new Pair<>(center,n)));\n\t}\n\n\t@Override\n\tpublic <X> Graph<X> createBidirectionalStar(X center, Set<X> nodes) {\n\t\treturn bidirectionalFromDirected(createDirectedStar(center,nodes));\n\t}\n\n\t@Override\n\tpublic <X> Graph<X> createFull(Set<X> nodes) {\n\t\treturn fromStream(nodes.stream().flatMap(n-> nodes.stream().filter(n2->n2!=n).map(n2 -> new Pair<>(n,n2))));\n\t}\n\n\t@Override\n\tpublic <X> Graph<X> combine(Graph<X> g1, Graph<X> g2) {\n\t\treturn new Graph<X>() {\n\t\t\t\n\t\t\tprivate int size = (int)this.getEdgesStream().count(); \n\n\t\t\t@Override\n\t\t\tpublic Set<X> getNodes() {\n\t\t\t\treturn this.getEdgesStream().flatMap(p -> Stream.of(p.getX(), p.getY())).collect(Collectors.toSet());\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic boolean edgePresent(X start, X end) {\n\t\t\t\treturn g1.edgePresent(start, end) || g2.edgePresent(start, end);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic int getEdgesCount() {\n\t\t\t\treturn this.size;\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Stream<Pair<X, X>> getEdgesStream() {\n\t\t\t\treturn Stream.concat(g1.getEdgesStream(),g2.getEdgesStream()).distinct();\n\t\t\t}\n\t\t\t\n\t\t};\n\t}\n\t\n\t\n}", "filename": "GraphFactoryImpl.java" } ]
{ "components": { "imports": "package a01a.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;", "private_init": "\t/*\n\t * Implement the GraphFactory interface as indicated in the initFactory method below.\n\t * Implement a factory concept for directed graphs, where each node is represented by a\n\t * value whose type is the type-variable <X> of the Graph interface.\n\t * The factory provides various functionalities to create very simple graphs (chain, cycle, star,\n\t * fully connected, or a union of these), in the \"directed\" variant (only directed edges) or \"bidirectional\"\n\t * (always two edges, one forward and one backward).\n\t * The comment on the provided interfaces, and the test methods below constitute the necessary explanation of the\n\t * problem.\n\t *\n\t * The following are considered optional for the purpose of being able to correct the exercise, but still contribute to achieving\n\t * the totality of the score:\n\t * - implementation of the tests called optionalTestXYZ (related to the Graph.getEdgesStream() and GraphFactory.combine() methods)\n\t * - the good design of the solution, in particular with minimization of repetitions\n\t *\n\t * Remove the comment from the initFactory method.\n\t *\n\t * Scoring indications:\n\t * - correctness of the mandatory part: 9 points\n\t * - correctness of the optional part: 4 points\n\t * - quality of the solution: 4 points\n\t *\n\t */\n\t\n\tprivate GraphFactory gf = null;\n\t\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.gf = new GraphFactoryImpl();\n\t}", "test_functions": [ "\[email protected]\n\tpublic void testDirectedChain() {\n\t\t// a->b, b->c, c->d\n\t\tfinal Graph<String> g = this.gf.createDirectedChain(List.of(\"a\",\"b\",\"c\",\"d\"));\n\t\tassertEquals(Set.of(\"a\",\"b\",\"c\",\"d\"),g.getNodes());\n\t\tassertEquals(3,g.getEdgesCount());\n\t\tassertTrue(g.edgePresent(\"a\", \"b\"));\n\t\tassertTrue(g.edgePresent(\"b\", \"c\"));\n\t\tassertTrue(g.edgePresent(\"c\", \"d\"));\n\t}", "\[email protected]\n\tpublic void testDirectedCircle() {\n\t\t// 10->20, 20->30, 30->40, 40->10\n\t\tfinal Graph<Integer> g = this.gf.createDirectedCircle(List.of(10,20,30,40));\n\t\tassertEquals(Set.of(10,20,30,40),g.getNodes());\n\t\tassertEquals(4,g.getEdgesCount());\n\t\tassertTrue(g.edgePresent(10,20));\n\t\tassertTrue(g.edgePresent(20,30));\n\t\tassertTrue(g.edgePresent(30,40));\n\t\tassertTrue(g.edgePresent(40,10));\n\t\t\n\t}", "\[email protected]\n\tpublic void testDirectedStar() {\n\t\t// 0->10, 0->20, 0->30\n\t\tfinal Graph<Integer> g = this.gf.createDirectedStar(0,Set.of(10,20,30));\n\t\tassertEquals(Set.of(0,10,20,30),g.getNodes());\n\t\tassertEquals(3,g.getEdgesCount());\n\t\tassertTrue(g.edgePresent(0,10));\n\t\tassertTrue(g.edgePresent(0,20));\n\t\tassertTrue(g.edgePresent(0,30));\n\t}", "\[email protected]\n\tpublic void testBiChain() {\n\t\tfinal Graph<String> g = this.gf.createBidirectionalChain(List.of(\"a\",\"b\",\"c\",\"d\"));\n\t\tassertEquals(Set.of(\"a\",\"b\",\"c\",\"d\"),g.getNodes());\n\t\tassertEquals(6,g.getEdgesCount());\n\t\tassertTrue(g.edgePresent(\"a\", \"b\"));\n\t\tassertTrue(g.edgePresent(\"b\", \"c\"));\n\t\tassertTrue(g.edgePresent(\"c\", \"d\"));\n\t\tassertTrue(g.edgePresent(\"b\", \"a\"));\n\t\tassertTrue(g.edgePresent(\"c\", \"b\"));\n\t\tassertTrue(g.edgePresent(\"d\", \"c\"));\n\t}", "\[email protected]\n\tpublic void testBiCircle() {\n\t\tfinal Graph<Integer> g = this.gf.createBidirectionalCircle(List.of(10,20,30,40));\n\t\tassertEquals(Set.of(10,20,30,40),g.getNodes());\n\t\tassertEquals(8,g.getEdgesCount());\n\t\tassertTrue(g.edgePresent(10,20));\n\t\tassertTrue(g.edgePresent(20,30));\n\t\tassertTrue(g.edgePresent(30,40));\n\t\tassertTrue(g.edgePresent(40,10));\n\t\tassertTrue(g.edgePresent(20,10));\n\t\tassertTrue(g.edgePresent(30,20));\n\t\tassertTrue(g.edgePresent(40,30));\n\t\tassertTrue(g.edgePresent(10,40));\n\t}", "\[email protected]\n\tpublic void testBiStar() {\n\t\tfinal Graph<Integer> g = this.gf.createBidirectionalStar(0,Set.of(10,20,30));\n\t\tassertEquals(Set.of(0,10,20,30),g.getNodes());\n\t\tassertEquals(6,g.getEdgesCount());\n\t\tassertTrue(g.edgePresent(0,10));\n\t\tassertTrue(g.edgePresent(0,20));\n\t\tassertTrue(g.edgePresent(0,30));\n\t\tassertTrue(g.edgePresent(10,0));\n\t\tassertTrue(g.edgePresent(20,0));\n\t\tassertTrue(g.edgePresent(30,0));\n\t}", "\[email protected]\n\tpublic void testFull() {\n\t\t// 10->20, 10->30, .. 6 cases..\n\t\tfinal Graph<Integer> g = this.gf.createFull(Set.of(10,20,30));\n\t\tassertEquals(Set.of(10,20,30),g.getNodes());\n\t\tassertEquals(6,g.getEdgesCount());\n\t\tassertTrue(g.edgePresent(10,20));\n\t\tassertTrue(g.edgePresent(10,30));\n\t\tassertTrue(g.edgePresent(20,30));\n\t\tassertTrue(g.edgePresent(20,10));\n\t\tassertTrue(g.edgePresent(30,20));\n\t\tassertTrue(g.edgePresent(30,10));\n\t}", "\[email protected]\n\tpublic void optionalTestCombine() {\n\t\t// simple union of the two graphs\n\t\tfinal Graph<Integer> g1 = this.gf.createDirectedStar(0,Set.of(10,20,30));\n\t\tfinal Graph<Integer> g2 = this.gf.createDirectedStar(0,Set.of(10,40));\n\t\tfinal Graph<Integer> g = this.gf.combine(g1, g2);\n\t\tassertEquals(Set.of(0,10,20,30,40),g.getNodes());\n\t\tassertEquals(4,g.getEdgesCount());\n\t\tassertTrue(g.edgePresent(0,10));\n\t\tassertTrue(g.edgePresent(0,20));\n\t\tassertTrue(g.edgePresent(0,30));\n\t\tassertTrue(g.edgePresent(0,40));\n\t}" ] }, "content": "package a01a.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;\n\npublic class Test {\n\t\n\t/*\n\t * Implement the GraphFactory interface as indicated in the initFactory method below.\n\t * Implement a factory concept for directed graphs, where each node is represented by a\n\t * value whose type is the type-variable <X> of the Graph interface.\n\t * The factory provides various functionalities to create very simple graphs (chain, cycle, star,\n\t * fully connected, or a union of these), in the \"directed\" variant (only directed edges) or \"bidirectional\"\n\t * (always two edges, one forward and one backward).\n\t * The comment on the provided interfaces, and the test methods below constitute the necessary explanation of the\n\t * problem.\n\t *\n\t * The following are considered optional for the purpose of being able to correct the exercise, but still contribute to achieving\n\t * the totality of the score:\n\t * - implementation of the tests called optionalTestXYZ (related to the Graph.getEdgesStream() and GraphFactory.combine() methods)\n\t * - the good design of the solution, in particular with minimization of repetitions\n\t *\n\t * Remove the comment from the initFactory method.\n\t *\n\t * Scoring indications:\n\t * - correctness of the mandatory part: 9 points\n\t * - correctness of the optional part: 4 points\n\t * - quality of the solution: 4 points\n\t *\n\t */\n\t\n\tprivate GraphFactory gf = null;\n\t\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.gf = new GraphFactoryImpl();\n\t}\n\t\n\t\n\[email protected]\n\tpublic void testDirectedChain() {\n\t\t// a->b, b->c, c->d\n\t\tfinal Graph<String> g = this.gf.createDirectedChain(List.of(\"a\",\"b\",\"c\",\"d\"));\n\t\tassertEquals(Set.of(\"a\",\"b\",\"c\",\"d\"),g.getNodes());\n\t\tassertEquals(3,g.getEdgesCount());\n\t\tassertTrue(g.edgePresent(\"a\", \"b\"));\n\t\tassertTrue(g.edgePresent(\"b\", \"c\"));\n\t\tassertTrue(g.edgePresent(\"c\", \"d\"));\n\t}\n\t\n\[email protected]\n\tpublic void testDirectedCircle() {\n\t\t// 10->20, 20->30, 30->40, 40->10\n\t\tfinal Graph<Integer> g = this.gf.createDirectedCircle(List.of(10,20,30,40));\n\t\tassertEquals(Set.of(10,20,30,40),g.getNodes());\n\t\tassertEquals(4,g.getEdgesCount());\n\t\tassertTrue(g.edgePresent(10,20));\n\t\tassertTrue(g.edgePresent(20,30));\n\t\tassertTrue(g.edgePresent(30,40));\n\t\tassertTrue(g.edgePresent(40,10));\n\t\t\n\t}\n\t\n\[email protected]\n\tpublic void testDirectedStar() {\n\t\t// 0->10, 0->20, 0->30\n\t\tfinal Graph<Integer> g = this.gf.createDirectedStar(0,Set.of(10,20,30));\n\t\tassertEquals(Set.of(0,10,20,30),g.getNodes());\n\t\tassertEquals(3,g.getEdgesCount());\n\t\tassertTrue(g.edgePresent(0,10));\n\t\tassertTrue(g.edgePresent(0,20));\n\t\tassertTrue(g.edgePresent(0,30));\n\t}\n\t\n\t// from here the bidirectional equivalents..\n\t\n\[email protected]\n\tpublic void testBiChain() {\n\t\tfinal Graph<String> g = this.gf.createBidirectionalChain(List.of(\"a\",\"b\",\"c\",\"d\"));\n\t\tassertEquals(Set.of(\"a\",\"b\",\"c\",\"d\"),g.getNodes());\n\t\tassertEquals(6,g.getEdgesCount());\n\t\tassertTrue(g.edgePresent(\"a\", \"b\"));\n\t\tassertTrue(g.edgePresent(\"b\", \"c\"));\n\t\tassertTrue(g.edgePresent(\"c\", \"d\"));\n\t\tassertTrue(g.edgePresent(\"b\", \"a\"));\n\t\tassertTrue(g.edgePresent(\"c\", \"b\"));\n\t\tassertTrue(g.edgePresent(\"d\", \"c\"));\n\t}\n\t\n\[email protected]\n\tpublic void testBiCircle() {\n\t\tfinal Graph<Integer> g = this.gf.createBidirectionalCircle(List.of(10,20,30,40));\n\t\tassertEquals(Set.of(10,20,30,40),g.getNodes());\n\t\tassertEquals(8,g.getEdgesCount());\n\t\tassertTrue(g.edgePresent(10,20));\n\t\tassertTrue(g.edgePresent(20,30));\n\t\tassertTrue(g.edgePresent(30,40));\n\t\tassertTrue(g.edgePresent(40,10));\n\t\tassertTrue(g.edgePresent(20,10));\n\t\tassertTrue(g.edgePresent(30,20));\n\t\tassertTrue(g.edgePresent(40,30));\n\t\tassertTrue(g.edgePresent(10,40));\n\t}\n\t\n\[email protected]\n\tpublic void testBiStar() {\n\t\tfinal Graph<Integer> g = this.gf.createBidirectionalStar(0,Set.of(10,20,30));\n\t\tassertEquals(Set.of(0,10,20,30),g.getNodes());\n\t\tassertEquals(6,g.getEdgesCount());\n\t\tassertTrue(g.edgePresent(0,10));\n\t\tassertTrue(g.edgePresent(0,20));\n\t\tassertTrue(g.edgePresent(0,30));\n\t\tassertTrue(g.edgePresent(10,0));\n\t\tassertTrue(g.edgePresent(20,0));\n\t\tassertTrue(g.edgePresent(30,0));\n\t}\n\t\n\[email protected]\n\tpublic void testFull() {\n\t\t// 10->20, 10->30, .. 6 cases..\n\t\tfinal Graph<Integer> g = this.gf.createFull(Set.of(10,20,30));\n\t\tassertEquals(Set.of(10,20,30),g.getNodes());\n\t\tassertEquals(6,g.getEdgesCount());\n\t\tassertTrue(g.edgePresent(10,20));\n\t\tassertTrue(g.edgePresent(10,30));\n\t\tassertTrue(g.edgePresent(20,30));\n\t\tassertTrue(g.edgePresent(20,10));\n\t\tassertTrue(g.edgePresent(30,20));\n\t\tassertTrue(g.edgePresent(30,10));\n\t}\n\t\n\t// from here the optional\n\t\n\[email protected]\n\tpublic void optionalTestCombine() {\n\t\t// simple union of the two graphs\n\t\tfinal Graph<Integer> g1 = this.gf.createDirectedStar(0,Set.of(10,20,30));\n\t\tfinal Graph<Integer> g2 = this.gf.createDirectedStar(0,Set.of(10,40));\n\t\tfinal Graph<Integer> g = this.gf.combine(g1, g2);\n\t\tassertEquals(Set.of(0,10,20,30,40),g.getNodes());\n\t\tassertEquals(4,g.getEdgesCount());\n\t\tassertTrue(g.edgePresent(0,10));\n\t\tassertTrue(g.edgePresent(0,20));\n\t\tassertTrue(g.edgePresent(0,30));\n\t\tassertTrue(g.edgePresent(0,40));\n\t}\n}", "filename": "Test.java" }
2019
a02a
[ { "content": "package a02a.sol1;\n\nimport java.util.Set;\n\n\npublic interface Workflow<T> {\n\t\n\t\n\tSet<T> getTasks();\n\t\n\t\n\tSet<T> getNextTasksToDo();\n\t\n\t\n\tvoid doTask(T t);\n\t\n\t\n\tboolean isCompleted();\n\n}", "filename": "Workflow.java" }, { "content": "package a02a.sol1;\n\nimport java.util.List;\nimport java.util.Set;\n\npublic interface WorkflowsFactory {\n\t\n\t\n\t<T> Workflow<T> singleTask(T task);\n\t\n\t\n\t<T> Workflow<T> tasksSequence(List<T> tasks);\n\t\n\t\n\t<T> Workflow<T> tasksJoin(Set<T> initialTasks, T finalTask);\n\t\n\t\n\t<T> Workflow<T> tasksFork(T initialTask, Set<T> finalTasks);\n\t\n\t\n\t<T> Workflow<T> concat(Workflow<T> first, Workflow<T> second);\n\t\n}", "filename": "WorkflowsFactory.java" }, { "content": "package 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 a02a.sol1;\n\nimport java.util.*;\nimport java.util.stream.*;\n\npublic class WorkflowsFactoryImpl implements WorkflowsFactory {\n\t\n\t// the map associates to a task to those it needs to be done before starting\n\tprivate <T> Workflow<T> fromGraph(Map<T,Set<T>> map) {\n\t\treturn new Workflow<>() {\n\t\t\t\n\t\t\tprivate Set<T> done = new HashSet<>();\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic Set<T> getTasks() {\n\t\t\t\treturn map.keySet();\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Set<T> getNextTasksToDo() {\n\t\t\t\treturn this.isCompleted() ? Set.of() : this.getTasks().stream().filter(this::canBeDone).collect(Collectors.toSet());\n\t\t\t}\n\t\t\t\n\t\t\tprivate boolean canBeDone(T t) {\n\t\t\t\treturn !this.done.contains(t) && this.done.containsAll(map.get(t));\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void doTask(T t) {\n\t\t\t\tif (!this.getNextTasksToDo().contains(t)) {\n\t\t\t\t\tthrow this.getTasks().contains(t) ? new IllegalStateException() : new IllegalArgumentException();\n\t\t\t\t}\n\t\t\t\tthis.done.add(t);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic boolean isCompleted() {\n\t\t\t\treturn this.done.equals(this.getTasks());\n\t\t\t}\n\t\t\t\n\t\t};\n\t}\n\t\n\t@Override\n\tpublic <T> Workflow<T> singleTask(T task) {\n\t\treturn tasksSequence(List.of(task));\n\t}\n\n\t@Override\n\tpublic <T> Workflow<T> tasksSequence(List<T> tasks) {\n\t\t// t1 -> t0, t2 -> t1, ... plus t0->nothing\n\t\tStream<Pair<T,Set<T>>> s = Stream.concat(\n\t\t\t\tIntStream.range(1,tasks.size()).mapToObj(i->new Pair<>(tasks.get(i), Set.of(tasks.get(i-1)))), \n\t\t\t\tStream.of(new Pair<>(tasks.get(0),Set.of())));\n\t\treturn fromGraph(s.collect(Collectors.toMap(Pair::getX,Pair::getY)));\n\t}\n\n\t@Override\n\tpublic <T> Workflow<T> tasksJoin(Set<T> initialTasks, T finalTask) {\n\t\t// i0-> nothing, i1 -> nothing ... plus final->initialiTasks\n\t\tStream<Pair<T,Set<T>>> s = Stream.concat(\n\t\t\t\tinitialTasks.stream().map(t->new Pair<>(t, Set.of())),\n\t\t\t\tStream.of(new Pair<>(finalTask,initialTasks)));\n\t\treturn fromGraph(s.collect(Collectors.toMap(Pair::getX,Pair::getY)));\n\t}\n\t\n\t@Override\n\tpublic <T> Workflow<T> tasksFork(T initialTask, Set<T> finalTasks) {\n\t\tStream<Pair<T,Set<T>>> s = Stream.concat(\n\t\t\t\tfinalTasks.stream().map(t->new Pair<>(t, Set.of(initialTask))),\n\t\t\t\tStream.of(new Pair<>(initialTask,Set.of())));\n\t\treturn fromGraph(s.collect(Collectors.toMap(Pair::getX,Pair::getY)));\n\t}\n\n\t@Override\n\tpublic <T> Workflow<T> concat(Workflow<T> first, Workflow<T> second) {\n\t\treturn new Workflow<>() {\n\t\t\t\n\t\t\tprivate boolean onFirst = true;\n\n\t\t\t@Override\n\t\t\tpublic Set<T> getTasks() {\n\t\t\t\tSet<T> set = new HashSet<>(first.getTasks());\n\t\t\t\tset.addAll(second.getTasks());\n\t\t\t\treturn set;\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Set<T> getNextTasksToDo() {\n\t\t\t\treturn this.onFirst ? first.getNextTasksToDo() : second.getNextTasksToDo();\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void doTask(T t) {\n\t\t\t\tif (this.onFirst) {\n\t\t\t\t\tfirst.doTask(t);\n\t\t\t\t\tif (first.isCompleted()) {\n\t\t\t\t\t\tthis.onFirst = false;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tsecond.doTask(t);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic boolean isCompleted() {\n\t\t\t\treturn !this.onFirst && second.isCompleted();\n\t\t\t}\n\t\t\t\n\t\t};\n\t}\n}", "filename": "WorkflowsFactoryImpl.java" } ]
{ "components": { "imports": "package a02a.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;", "private_init": "\t/*\n\t * Implement the WorkflowsFactory interface as indicated in the initFactory method below.\n\t * Create a factory concept for workflows, modeled by the Workflow<T> interface. A Workflow is\n\t * a set of tasks (of type T) to be performed:\n\t * - each can be executed only once\n\t * - when all are executed the workflow is terminated\n\t * - there are specific constraints on when a task can be executed, expressed in terms of the successful execution of other tasks\n\t * \n\t * The comment on the provided interfaces, and the test methods below constitute the necessary explanation of the \n\t * problem.\n\t * \n\t * The following are considered optional for the purpose of correcting the exercise, but still contribute to achieving \n\t * the totality of the score:\n\t * - implementation of the tests called optionalTestXYZ (related to the WorkflowsFactory.concat() methods and error handling) \n\t * - the good design of the solution, in particular with minimization of repetitions\n\t * \n\t * Remove the comment from the initFactory method.\n\t * \n\t * Scoring indications:\n\t * - correctness of the mandatory part: 9 points\n\t * - correctness of the optional part: 4 points\n\t * - quality of the solution: 4 points\n\t * \n\t */\n\t\n\t\n\tprivate WorkflowsFactory wf = null;\n\t\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.wf = new WorkflowsFactoryImpl();\n\t}", "test_functions": [ "\[email protected]\n\tpublic void testSingleTask() {\n\t\t// a workflow consisting of only the task 'a'\n\t\tfinal Workflow<String> w = this.wf.singleTask(\"a\");\n\t\t\n\t\tassertEquals(Set.of(\"a\"),w.getTasks()); \t\t// 'a' is the only task\t\t\n\t\tassertFalse(w.isCompleted());\t\t\t\t\t// the workflow is not completed\n\t\tassertEquals(Set.of(\"a\"),w.getNextTasksToDo()); // 'a' is the only next task to execute\n\t\t\n\t\tw.doTask(\"a\");\t\t\t\t\t\t\t\t\t// execute 'a'\n\t\tassertTrue(w.isCompleted()); \t\t\t\t\t// the workflow is completed\n\t\tassertEquals(Set.of(),w.getNextTasksToDo()); \t// there are no more tasks to execute\n\t}", "\[email protected]\n\tpublic void testTaskSequence() { \n\t\t// a workflow that requires executing 'a', then 'b', then 'c', then 'd' (in summary: a->b;b->c;c->d)\n\t\tfinal Workflow<String> w = this.wf.tasksSequence(List.of(\"a\",\"b\",\"c\",\"d\"));\n\t\tassertEquals(Set.of(\"a\",\"b\",\"c\",\"d\"),w.getTasks());\t\t\n\t\tassertFalse(w.isCompleted());\n\t\tassertEquals(Set.of(\"a\"),w.getNextTasksToDo());\n\t\t\n\t\t// executed 'a' then I will not be finished, I will have to execute 'b'\n\t\tw.doTask(\"a\");\n\t\tassertFalse(w.isCompleted());\n\t\tassertEquals(Set.of(\"b\"),w.getNextTasksToDo());\n\t\t\n\t\t// executed 'b' then I will not be finished, I will have to execute 'c'\n\t\tw.doTask(\"b\");\n\t\tassertFalse(w.isCompleted());\n\t\tassertEquals(Set.of(\"c\"),w.getNextTasksToDo());\n\t\t\n\t\t// executed 'c' then I will not be finished, I will have to execute 'd'\n\t\tw.doTask(\"c\");\n\t\tassertFalse(w.isCompleted());\n\t\tassertEquals(Set.of(\"d\"),w.getNextTasksToDo());\n\t\t\n\t\t// executed 'd' the workflow is terminated\n\t\tw.doTask(\"d\");\n\t\tassertTrue(w.isCompleted());\n\t\tassertEquals(Set.of(),w.getNextTasksToDo());\n\t}", "\[email protected]\n\tpublic void testTaskJoin() { \n\t\t// a workflow that requires executing '10', '20' and '30' (in any order), and only after '0' (in summary: 10->0;20->0;30->0)\n\t\tfinal Workflow<Integer> w = this.wf.tasksJoin(Set.of(10,20,30),0);\n\t\tassertEquals(Set.of(10,20,30,0),w.getTasks());\t\t\n\t\tassertFalse(w.isCompleted());\n\t\tassertEquals(Set.of(10,20,30),w.getNextTasksToDo());\n\t\t\n\t\t// executed '30' then I will not be finished, I will have to execute '10' and '20'\n\t\tw.doTask(30);\n\t\tassertFalse(w.isCompleted());\n\t\tassertEquals(Set.of(10,20),w.getNextTasksToDo());\n\t\t\n\t\t// executed '10' then I will not be finished, I will have to execute '20'\n\t\tw.doTask(10);\n\t\tassertFalse(w.isCompleted());\n\t\tassertEquals(Set.of(20),w.getNextTasksToDo());\n\t\t\n\t\t// executed '20' then I will not be finished, I will have to execute '0'\n\t\tw.doTask(20);\n\t\tassertFalse(w.isCompleted());\n\t\tassertEquals(Set.of(0),w.getNextTasksToDo());\n\t\t\n\t\t// executed '0' the workflow is terminated\n\t\tw.doTask(0);\n\t\tassertTrue(w.isCompleted());\n\t\tassertEquals(Set.of(),w.getNextTasksToDo());\n\t}", "\[email protected]\n\tpublic void testTaskFork() { \n\t\t// a workflow that requires executing '0', and then '10', '20' and '30' in any order (in summary: 0->10;0->20;0->30)\n\t\tfinal Workflow<Integer> w = this.wf.tasksFork(0,Set.of(10,20,30));\n\t\tassertEquals(Set.of(10,20,30,0),w.getTasks());\t\t\n\t\tassertFalse(w.isCompleted());\n\t\tassertEquals(Set.of(0),w.getNextTasksToDo());\n\t\t\n\t\t// executed '0' then I will not be finished, I will have to execute '10', '20' and '30'\n\t\tw.doTask(0);\n\t\tassertFalse(w.isCompleted());\n\t\tassertEquals(Set.of(10,20,30),w.getNextTasksToDo());\n\t\t\n\t\t// executed '10' then I will not be finished, I will have to execute '20' and '30'\n\t\tw.doTask(10);\n\t\tassertFalse(w.isCompleted());\n\t\tassertEquals(Set.of(20,30),w.getNextTasksToDo());\n\t\t\n\t\t// executed '30' then I will not be finished, I will have to execute '20'\n\t\tw.doTask(30);\n\t\tassertFalse(w.isCompleted());\n\t\tassertEquals(Set.of(20),w.getNextTasksToDo());\n\t\t\n\t\t// executed '20' the workflow is terminated\n\t\tw.doTask(20);\n\t\tassertTrue(w.isCompleted());\n\t\tassertEquals(Set.of(),w.getNextTasksToDo());\n\t}", "\[email protected]\n\tpublic void optionalTestConcatenation() { \n\t\tfinal Workflow<Integer> w1 = this.wf.tasksJoin(Set.of(10,20),0); \t\t// 10->0, 20->0\n\t\tfinal Workflow<Integer> w2 = this.wf.tasksSequence(List.of(1,2));\t\t// 1->2\n\t\t// the concatenation of w1 and w2, that is, when w1 is finished, w2 starts\t\t\t\t// 10->0, 20->0, 0->1, 1->2\n\t\tfinal Workflow<Integer> w = this.wf.concat(w1, w2);\n\t\t\t\t\n\t\tassertEquals(Set.of(10,20,0,1,2),w.getTasks());\t\t\n\t\tassertFalse(w.isCompleted());\n\t\tassertEquals(Set.of(10,20),w.getNextTasksToDo());\n\t\t\n\t\tw.doTask(10);\n\t\tassertFalse(w.isCompleted());\n\t\tassertEquals(Set.of(20),w.getNextTasksToDo());\n\t\t\n\t\tw.doTask(20);\n\t\tassertFalse(w.isCompleted());\n\t\tassertEquals(Set.of(0),w.getNextTasksToDo());\n\t\t\n\t\tw.doTask(0);\n\t\tassertFalse(w.isCompleted());\n\t\tassertEquals(Set.of(1),w.getNextTasksToDo());\n\t\t\n\t\tw.doTask(1);\n\t\tassertFalse(w.isCompleted());\n\t\tassertEquals(Set.of(2),w.getNextTasksToDo());\n\t\t\n\t\tw.doTask(2);\n\t\tassertTrue(w.isCompleted());\n\t\tassertEquals(Set.of(),w.getNextTasksToDo());\n\t}" ] }, "content": "package a02a.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;\n\npublic class Test {\n\t\n\t/*\n\t * Implement the WorkflowsFactory interface as indicated in the initFactory method below.\n\t * Create a factory concept for workflows, modeled by the Workflow<T> interface. A Workflow is\n\t * a set of tasks (of type T) to be performed:\n\t * - each can be executed only once\n\t * - when all are executed the workflow is terminated\n\t * - there are specific constraints on when a task can be executed, expressed in terms of the successful execution of other tasks\n\t * \n\t * The comment on the provided interfaces, and the test methods below constitute the necessary explanation of the \n\t * problem.\n\t * \n\t * The following are considered optional for the purpose of correcting the exercise, but still contribute to achieving \n\t * the totality of the score:\n\t * - implementation of the tests called optionalTestXYZ (related to the WorkflowsFactory.concat() methods and error handling) \n\t * - the good design of the solution, in particular with minimization of repetitions\n\t * \n\t * Remove the comment from the initFactory method.\n\t * \n\t * Scoring indications:\n\t * - correctness of the mandatory part: 9 points\n\t * - correctness of the optional part: 4 points\n\t * - quality of the solution: 4 points\n\t * \n\t */\n\t\n\t\n\tprivate WorkflowsFactory wf = null;\n\t\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.wf = new WorkflowsFactoryImpl();\n\t}\n\n\[email protected]\n\tpublic void testSingleTask() {\n\t\t// a workflow consisting of only the task 'a'\n\t\tfinal Workflow<String> w = this.wf.singleTask(\"a\");\n\t\t\n\t\tassertEquals(Set.of(\"a\"),w.getTasks()); \t\t// 'a' is the only task\t\t\n\t\tassertFalse(w.isCompleted());\t\t\t\t\t// the workflow is not completed\n\t\tassertEquals(Set.of(\"a\"),w.getNextTasksToDo()); // 'a' is the only next task to execute\n\t\t\n\t\tw.doTask(\"a\");\t\t\t\t\t\t\t\t\t// execute 'a'\n\t\tassertTrue(w.isCompleted()); \t\t\t\t\t// the workflow is completed\n\t\tassertEquals(Set.of(),w.getNextTasksToDo()); \t// there are no more tasks to execute\n\t}\n\n\t\n\[email protected]\n\tpublic void testTaskSequence() { \n\t\t// a workflow that requires executing 'a', then 'b', then 'c', then 'd' (in summary: a->b;b->c;c->d)\n\t\tfinal Workflow<String> w = this.wf.tasksSequence(List.of(\"a\",\"b\",\"c\",\"d\"));\n\t\tassertEquals(Set.of(\"a\",\"b\",\"c\",\"d\"),w.getTasks());\t\t\n\t\tassertFalse(w.isCompleted());\n\t\tassertEquals(Set.of(\"a\"),w.getNextTasksToDo());\n\t\t\n\t\t// executed 'a' then I will not be finished, I will have to execute 'b'\n\t\tw.doTask(\"a\");\n\t\tassertFalse(w.isCompleted());\n\t\tassertEquals(Set.of(\"b\"),w.getNextTasksToDo());\n\t\t\n\t\t// executed 'b' then I will not be finished, I will have to execute 'c'\n\t\tw.doTask(\"b\");\n\t\tassertFalse(w.isCompleted());\n\t\tassertEquals(Set.of(\"c\"),w.getNextTasksToDo());\n\t\t\n\t\t// executed 'c' then I will not be finished, I will have to execute 'd'\n\t\tw.doTask(\"c\");\n\t\tassertFalse(w.isCompleted());\n\t\tassertEquals(Set.of(\"d\"),w.getNextTasksToDo());\n\t\t\n\t\t// executed 'd' the workflow is terminated\n\t\tw.doTask(\"d\");\n\t\tassertTrue(w.isCompleted());\n\t\tassertEquals(Set.of(),w.getNextTasksToDo());\n\t}\n\t\n\[email protected]\n\tpublic void testTaskJoin() { \n\t\t// a workflow that requires executing '10', '20' and '30' (in any order), and only after '0' (in summary: 10->0;20->0;30->0)\n\t\tfinal Workflow<Integer> w = this.wf.tasksJoin(Set.of(10,20,30),0);\n\t\tassertEquals(Set.of(10,20,30,0),w.getTasks());\t\t\n\t\tassertFalse(w.isCompleted());\n\t\tassertEquals(Set.of(10,20,30),w.getNextTasksToDo());\n\t\t\n\t\t// executed '30' then I will not be finished, I will have to execute '10' and '20'\n\t\tw.doTask(30);\n\t\tassertFalse(w.isCompleted());\n\t\tassertEquals(Set.of(10,20),w.getNextTasksToDo());\n\t\t\n\t\t// executed '10' then I will not be finished, I will have to execute '20'\n\t\tw.doTask(10);\n\t\tassertFalse(w.isCompleted());\n\t\tassertEquals(Set.of(20),w.getNextTasksToDo());\n\t\t\n\t\t// executed '20' then I will not be finished, I will have to execute '0'\n\t\tw.doTask(20);\n\t\tassertFalse(w.isCompleted());\n\t\tassertEquals(Set.of(0),w.getNextTasksToDo());\n\t\t\n\t\t// executed '0' the workflow is terminated\n\t\tw.doTask(0);\n\t\tassertTrue(w.isCompleted());\n\t\tassertEquals(Set.of(),w.getNextTasksToDo());\n\t}\n\t\n\[email protected]\n\tpublic void testTaskFork() { \n\t\t// a workflow that requires executing '0', and then '10', '20' and '30' in any order (in summary: 0->10;0->20;0->30)\n\t\tfinal Workflow<Integer> w = this.wf.tasksFork(0,Set.of(10,20,30));\n\t\tassertEquals(Set.of(10,20,30,0),w.getTasks());\t\t\n\t\tassertFalse(w.isCompleted());\n\t\tassertEquals(Set.of(0),w.getNextTasksToDo());\n\t\t\n\t\t// executed '0' then I will not be finished, I will have to execute '10', '20' and '30'\n\t\tw.doTask(0);\n\t\tassertFalse(w.isCompleted());\n\t\tassertEquals(Set.of(10,20,30),w.getNextTasksToDo());\n\t\t\n\t\t// executed '10' then I will not be finished, I will have to execute '20' and '30'\n\t\tw.doTask(10);\n\t\tassertFalse(w.isCompleted());\n\t\tassertEquals(Set.of(20,30),w.getNextTasksToDo());\n\t\t\n\t\t// executed '30' then I will not be finished, I will have to execute '20'\n\t\tw.doTask(30);\n\t\tassertFalse(w.isCompleted());\n\t\tassertEquals(Set.of(20),w.getNextTasksToDo());\n\t\t\n\t\t// executed '20' the workflow is terminated\n\t\tw.doTask(20);\n\t\tassertTrue(w.isCompleted());\n\t\tassertEquals(Set.of(),w.getNextTasksToDo());\n\t}\n\t\n\[email protected]\n\tpublic void optionalTestConcatenation() { \n\t\tfinal Workflow<Integer> w1 = this.wf.tasksJoin(Set.of(10,20),0); \t\t// 10->0, 20->0\n\t\tfinal Workflow<Integer> w2 = this.wf.tasksSequence(List.of(1,2));\t\t// 1->2\n\t\t// the concatenation of w1 and w2, that is, when w1 is finished, w2 starts\t\t\t\t// 10->0, 20->0, 0->1, 1->2\n\t\tfinal Workflow<Integer> w = this.wf.concat(w1, w2);\n\t\t\t\t\n\t\tassertEquals(Set.of(10,20,0,1,2),w.getTasks());\t\t\n\t\tassertFalse(w.isCompleted());\n\t\tassertEquals(Set.of(10,20),w.getNextTasksToDo());\n\t\t\n\t\tw.doTask(10);\n\t\tassertFalse(w.isCompleted());\n\t\tassertEquals(Set.of(20),w.getNextTasksToDo());\n\t\t\n\t\tw.doTask(20);\n\t\tassertFalse(w.isCompleted());\n\t\tassertEquals(Set.of(0),w.getNextTasksToDo());\n\t\t\n\t\tw.doTask(0);\n\t\tassertFalse(w.isCompleted());\n\t\tassertEquals(Set.of(1),w.getNextTasksToDo());\n\t\t\n\t\tw.doTask(1);\n\t\tassertFalse(w.isCompleted());\n\t\tassertEquals(Set.of(2),w.getNextTasksToDo());\n\t\t\n\t\tw.doTask(2);\n\t\tassertTrue(w.isCompleted());\n\t\tassertEquals(Set.of(),w.getNextTasksToDo());\n\t}\n\t\n\[email protected](expected = IllegalStateException.class)\n\tpublic void optionalTestWrongTask() { \n\t\tfinal Workflow<String> w = this.wf.tasksSequence(List.of(\"a\",\"b\",\"c\",\"d\"));\n\t\tassertEquals(Set.of(\"a\",\"b\",\"c\",\"d\"),w.getTasks());\t\t\n\t\tassertFalse(w.isCompleted());\n\t\tassertEquals(Set.of(\"a\"),w.getNextTasksToDo());\n\t\t\t\t\n\t\tw.doTask(\"a\");\n\t\tassertFalse(w.isCompleted());\n\t\tassertEquals(Set.of(\"b\"),w.getNextTasksToDo());\n\t\t\n\t\t// IT IS NOT THE TIME TO EXECUTE 'c': IllegalStateException \n\t\tw.doTask(\"c\");\n\t}\n\t\n\[email protected](expected = IllegalArgumentException.class)\n\tpublic void optionalTestUnknownTask() { \n\t\tfinal Workflow<String> w = this.wf.tasksSequence(List.of(\"a\",\"b\",\"c\",\"d\"));\n\t\tassertEquals(Set.of(\"a\",\"b\",\"c\",\"d\"),w.getTasks());\t\t\n\t\tassertFalse(w.isCompleted());\n\t\tassertEquals(Set.of(\"a\"),w.getNextTasksToDo());\n\t\t\t\t\n\t\tw.doTask(\"a\");\n\t\tassertFalse(w.isCompleted());\n\t\tassertEquals(Set.of(\"b\"),w.getNextTasksToDo());\n\t\t\t\t\n\t\t// 'pippo' is not an executable task: IllegalArgumentException \n\t\tw.doTask(\"pippo\");\n\t}\n\t\n}", "filename": "Test.java" }
2019
a05b
[ { "content": "package a05b.sol1;\n\nimport java.util.Iterator;\nimport java.util.stream.Stream;\n\n\npublic interface IteratorIteratorFactory {\n\t\n\t\n\t<E> Iterator<Iterator<E>> constantWithSingleton(E e);\n\t\n\t\n\t<E> Iterator<Iterator<E>> increasingSizeWithSingleton(E e);\n\t\n\t\n\tIterator<Iterator<Integer>> squares();\n\n\t\n\tIterator<Iterator<Integer>> evens();\n}", "filename": "IteratorIteratorFactory.java" }, { "content": "package a05b.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 a05b.sol1;\n\nimport java.util.Iterator;\nimport java.util.function.Supplier;\nimport java.util.function.UnaryOperator;\nimport java.util.stream.Stream;\n\npublic class IteratorIteratorFactoryImpl implements IteratorIteratorFactory {\n\n\tprivate <E> Iterator<Iterator<E>> withSizes(Supplier<Stream<E>> supplier, Stream<Integer> sizes) {\n\t\treturn sizes.map(i -> supplier.get().limit(i).iterator()).iterator();\n\t}\n\t\n\tprivate <E> Iterator<Iterator<E>> increasing(Supplier<Stream<E>> supplier) {\n\t\treturn withSizes(supplier,Stream.iterate(1,x->x+1));\n\t}\n\t\n\tprivate Iterator<Iterator<Integer>> fromUnary(UnaryOperator<Integer> u) {\n\t\treturn increasing(()->Stream.iterate(0, x->x+1).map(u::apply));\n\t}\n\n\n\t@Override\n\tpublic <E> Iterator<Iterator<E>> constantWithSingleton(E e) {\n\t\treturn withSizes(() -> Stream.of(e),Stream.generate(()->1));\n\t}\n\t\n\t@Override\n\tpublic <E> Iterator<Iterator<E>> increasingSizeWithSingleton(E e) {\n\t\treturn increasing(()->Stream.generate(()->e));\n\t}\n\t\n\t@Override\n\tpublic Iterator<Iterator<Integer>> squares() {\n\t\treturn fromUnary(i -> i*i);\n\t}\n\n\t@Override\n\tpublic Iterator<Iterator<Integer>> evens() {\n\t\treturn fromUnary(i -> i*2);\n\t}\n\n}", "filename": "IteratorIteratorFactoryImpl.java" } ]
{ "components": { "imports": "package a05b.sol1;\n\nimport static org.junit.Assert.*;\n\nimport java.util.Iterator;\nimport java.util.LinkedList;\nimport java.util.List;", "private_init": "\t/*\n\t * Implement the IteratorIteratorFactory interface as indicated in the initFactory method below.\n\t * Create a factory for various iterators, each of which in turn produces an iterator at each step.\n\t * An iterator of iterators is a way to gradually generate various sequences of elements.\n\t * \n\t * The comment on the provided interfaces, and the test methods below constitute the necessary \n\t * explanation of the problem.\n\t * \n\t * The following are considered optional for the purpose of being able to correct the exercise, \n\t * but still contribute to achieving the total score:\n\t * - implementation of the tests called optionalTestXYZ (related to the increasingSizeWithSingleton() method of the factory) \n\t * - the good design of the solution, in particular with minimization of repetitions\n\t * \n\t * Remove the comment from the initFactory method.\n\t * \n\t * Scoring indications:\n\t * - correctness of the mandatory part: 9 points\n\t * - correctness of the optional part: 4 points\n\t * - quality of the solution: 4 points\n\t * \n\t */\n\t\n\tprivate IteratorIteratorFactory factory = null;\n\t\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.factory = new IteratorIteratorFactoryImpl();\n\t}", "test_functions": [ "\[email protected]\n\tpublic void testConstant() {\n\t\tfinal Iterator<Iterator<String>> ii = this.factory.constantWithSingleton(\"a\");\n\t\t\n\t\t// ii first gives an iterator, i1, giving only an \"a\"\n\t\tassertTrue(ii.hasNext());\n\t\tfinal Iterator<String> i1 = ii.next();\n\t\tassertTrue(i1.hasNext());\n\t\tassertEquals(\"a\",i1.next());\n\t\tassertFalse(i1.hasNext());\n\t\t\n\t\t// ii then gives an iterator, i2, giving only an \"a\"\n\t\tassertTrue(ii.hasNext());\n\t\tfinal Iterator<String> i2 = ii.next();\n\t\tassertTrue(i2.hasNext());\n\t\tassertEquals(\"a\",i2.next());\n\t\tassertFalse(i2.hasNext());\n\t\t\n\t\t// after many times..\n\t\tfor (int i=0;i<100;i++) {\n\t\t\tii.next();\n\t\t}", "\[email protected]\n\tpublic void testConstantVariant() {\n\t\t// an equivalent formulation of the test above, more succint thanks to method iteratorToList\n\t\tfinal Iterator<Iterator<String>> ii = this.factory.constantWithSingleton(\"a\");\n\t\t\n\t\t// ii first gives the sequence with only an \"a\" \n\t\tassertEquals(List.of(\"a\"), this.iteratorToList(ii.next()));\n\t\t// ii then gives the sequence with only an \"a\" \n\t\tassertEquals(List.of(\"a\"), this.iteratorToList(ii.next()));\n\t\t// after many times..\n\t\tfor (int i=0;i<100;i++) {\n\t\t\tii.next();\n\t\t}", "\[email protected]\n\tpublic void optionalTestIncreasing() {\n\t\tfinal Iterator<Iterator<String>> ii = this.factory.increasingSizeWithSingleton(\"a\");\n\t\t\n\t\t// the sequences returned each time by the iterator\n\t\tassertEquals(List.of(\"a\"), this.iteratorToList(ii.next()));\n\t\tassertEquals(List.of(\"a\",\"a\"), this.iteratorToList(ii.next()));\n\t\tassertEquals(List.of(\"a\",\"a\",\"a\"), this.iteratorToList(ii.next()));\n\t\tassertEquals(List.of(\"a\",\"a\",\"a\",\"a\"), this.iteratorToList(ii.next()));\n\t\tfor (int i=0;i<100;i++) {\n\t\t\tii.next();\n\t\t}", "\[email protected]\n\tpublic void testSquares() {\n\t\tfinal Iterator<Iterator<Integer>> ii = this.factory.squares();\n\t\t// giving {0}", "\[email protected]\n\tpublic void testEvens() {\n\t\tfinal Iterator<Iterator<Integer>> ii = this.factory.evens();\n\t\t\n\t\t// giving {0}" ] }, "content": "package a05b.sol1;\n\nimport static org.junit.Assert.*;\n\nimport java.util.Iterator;\nimport java.util.LinkedList;\nimport java.util.List;\n\npublic class Test {\n\t\n\t/*\n\t * Implement the IteratorIteratorFactory interface as indicated in the initFactory method below.\n\t * Create a factory for various iterators, each of which in turn produces an iterator at each step.\n\t * An iterator of iterators is a way to gradually generate various sequences of elements.\n\t * \n\t * The comment on the provided interfaces, and the test methods below constitute the necessary \n\t * explanation of the problem.\n\t * \n\t * The following are considered optional for the purpose of being able to correct the exercise, \n\t * but still contribute to achieving the total score:\n\t * - implementation of the tests called optionalTestXYZ (related to the increasingSizeWithSingleton() method of the factory) \n\t * - the good design of the solution, in particular with minimization of repetitions\n\t * \n\t * Remove the comment from the initFactory method.\n\t * \n\t * Scoring indications:\n\t * - correctness of the mandatory part: 9 points\n\t * - correctness of the optional part: 4 points\n\t * - quality of the solution: 4 points\n\t * \n\t */\n\t\n\tprivate IteratorIteratorFactory factory = null;\n\t\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.factory = new IteratorIteratorFactoryImpl();\n\t}\n\n\[email protected]\n\tpublic void testConstant() {\n\t\tfinal Iterator<Iterator<String>> ii = this.factory.constantWithSingleton(\"a\");\n\t\t\n\t\t// ii first gives an iterator, i1, giving only an \"a\"\n\t\tassertTrue(ii.hasNext());\n\t\tfinal Iterator<String> i1 = ii.next();\n\t\tassertTrue(i1.hasNext());\n\t\tassertEquals(\"a\",i1.next());\n\t\tassertFalse(i1.hasNext());\n\t\t\n\t\t// ii then gives an iterator, i2, giving only an \"a\"\n\t\tassertTrue(ii.hasNext());\n\t\tfinal Iterator<String> i2 = ii.next();\n\t\tassertTrue(i2.hasNext());\n\t\tassertEquals(\"a\",i2.next());\n\t\tassertFalse(i2.hasNext());\n\t\t\n\t\t// after many times..\n\t\tfor (int i=0;i<100;i++) {\n\t\t\tii.next();\n\t\t}\n\t\t\n\t\t//.. ii still gives an iterator, i3, giving only an \"a\"\n\t\tassertTrue(ii.hasNext());\n\t\tfinal Iterator<String> i3 = ii.next();\n\t\tassertTrue(i3.hasNext());\n\t\tassertEquals(\"a\",i3.next());\n\t\tassertFalse(i3.hasNext());\n\t}\n\t\n\tprivate <E> List<E> iteratorToList(Iterator<E> it){\n\t\tfinal List<E> l = new LinkedList<>();\n\t\twhile (it.hasNext()) {\n\t\t\tl.add(it.next());\n\t\t}\n\t\treturn l;\n\t}\n\t\n\[email protected]\n\tpublic void testConstantVariant() {\n\t\t// an equivalent formulation of the test above, more succint thanks to method iteratorToList\n\t\tfinal Iterator<Iterator<String>> ii = this.factory.constantWithSingleton(\"a\");\n\t\t\n\t\t// ii first gives the sequence with only an \"a\" \n\t\tassertEquals(List.of(\"a\"), this.iteratorToList(ii.next()));\n\t\t// ii then gives the sequence with only an \"a\" \n\t\tassertEquals(List.of(\"a\"), this.iteratorToList(ii.next()));\n\t\t// after many times..\n\t\tfor (int i=0;i<100;i++) {\n\t\t\tii.next();\n\t\t}\n\t\t// ..ii still gives the sequence with only an \"a\" \n\t\tassertEquals(List.of(\"a\"), this.iteratorToList(ii.next()));\n\t\tassertTrue(ii.hasNext());\n\t}\n\t\n\[email protected]\n\tpublic void optionalTestIncreasing() {\n\t\tfinal Iterator<Iterator<String>> ii = this.factory.increasingSizeWithSingleton(\"a\");\n\t\t\n\t\t// the sequences returned each time by the iterator\n\t\tassertEquals(List.of(\"a\"), this.iteratorToList(ii.next()));\n\t\tassertEquals(List.of(\"a\",\"a\"), this.iteratorToList(ii.next()));\n\t\tassertEquals(List.of(\"a\",\"a\",\"a\"), this.iteratorToList(ii.next()));\n\t\tassertEquals(List.of(\"a\",\"a\",\"a\",\"a\"), this.iteratorToList(ii.next()));\n\t\tfor (int i=0;i<100;i++) {\n\t\t\tii.next();\n\t\t}\n\t\t// after 100 attempts can still give more\n\t\tassertTrue(ii.hasNext());\n\t}\n\t\n\[email protected]\n\tpublic void testSquares() {\n\t\tfinal Iterator<Iterator<Integer>> ii = this.factory.squares();\n\t\t// giving {0}, {0,1}, {0,1,4}, {0,1,4,9,16}... namely the square numbers\n\t\tassertEquals(List.of(0), this.iteratorToList(ii.next()));\n\t\tassertEquals(List.of(0,1), this.iteratorToList(ii.next()));\n\t\tassertEquals(List.of(0,1,4), this.iteratorToList(ii.next()));\n\t\tassertEquals(List.of(0,1,4,9), this.iteratorToList(ii.next()));\n\t\tassertEquals(List.of(0,1,4,9,16), this.iteratorToList(ii.next()));\n\t\tfor (int i=0;i<100;i++) {\n\t\t\tii.next();\n\t\t}\n\t\tassertTrue(ii.hasNext());\n\t}\n\t\n\[email protected]\n\tpublic void testEvens() {\n\t\tfinal Iterator<Iterator<Integer>> ii = this.factory.evens();\n\t\t\n\t\t// giving {0}, {0,2}, {0,2,4}, ... namely the even numbers\n\t\tassertEquals(List.of(0), this.iteratorToList(ii.next()));\n\t\tassertEquals(List.of(0,2), this.iteratorToList(ii.next()));\n\t\tassertEquals(List.of(0,2,4), this.iteratorToList(ii.next()));\n\t\tassertEquals(List.of(0,2,4,6), this.iteratorToList(ii.next()));\n\t\tassertEquals(List.of(0,2,4,6,8), this.iteratorToList(ii.next()));\n\t\tfor (int i=0;i<100;i++) {\n\t\t\tii.next();\n\t\t}\n\t\tassertTrue(ii.hasNext());\n\t}\n\n\n\t\n}", "filename": "Test.java" }
2019
a03b
[ { "content": "package a03b.sol1;\n\nimport java.util.List;\nimport java.util.Optional;\n\n\n\npublic interface PostOffice {\n\t\n\tenum Operation { SEND, RECEIVE }\n\t\n\t\n\tint getTicket(Operation operation);\n\t\n\t\n\tOptional<Operation> deskState(int desk);\n\t\n\t\n\tList<Integer> peopleWaiting();\n\t\n\t\n\tvoid goToDesk(int ticket, int desk);\n\t\n\t\n\tvoid deskReleased(int desk);\n\t\n\t\n\tvoid exitOnWait(int ticket);\n}", "filename": "PostOffice.java" }, { "content": "package a03b.sol1;\n\n\npublic interface PostOfficeFactory {\n\t\n\t\n\tPostOffice createFlexible(int desksSize);\n\t\n\t\n\tPostOffice createAlternating(int desksSize);\n\n}", "filename": "PostOfficeFactory.java" }, { "content": "package a03b.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 a03b.sol1;\n\nimport java.util.*;\nimport java.util.stream.*;\n\nimport a03b.sol1.PostOffice.Operation;\n\npublic class PostOfficeFactoryImpl implements PostOfficeFactory {\n\t\n\t// This policy is used to state, given a previous operation at a desk, what could be the next one\n\tinterface NextPolicy {\n\t\tOptional<Operation> next(Operation previous);\n\t}\n\t\n\tprivate PostOffice fromPolicy(NextPolicy policy, int desksSize) {\n\t\treturn new PostOffice() {\n\t\t\t\n\t\t\tprivate int ticketCount;\n\t\t\tprivate List<Optional<Operation>> next = new ArrayList<>() {{\n\t\t\t\tfor (int i=0; i<desksSize; i++) {\n\t\t\t\t\tadd(Optional.empty());\n\t\t\t\t}\n\t\t\t}};\n\t\t\tprivate Map<Integer,Operation> waiting = new HashMap<>();\n\t\t\tprivate List<Optional<Pair<Integer,Operation>>> served = new ArrayList<>() {{\n\t\t\t\tfor (int i=0; i<desksSize; i++) {\n\t\t\t\t\tadd(Optional.empty());\n\t\t\t\t}\n\t\t\t}};\n\n\t\t\t@Override\n\t\t\tpublic int getTicket(Operation operation) {\n\t\t\t\tthis.waiting.put(this.ticketCount,operation);\n\t\t\t\treturn this.ticketCount++;\n\t\t\t}\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic List<Integer> peopleWaiting() {\n\t\t\t\treturn this.waiting.keySet().stream().sorted().collect(Collectors.toList());\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Optional<Operation> deskState(int desk) {\n\t\t\t\treturn this.served.get(desk).map(Pair::getY);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void goToDesk(int ticket, int desk) {\n\t\t\t\tif (ticket != waiting.keySet().stream().mapToInt(i->i).min().getAsInt()) {\n\t\t\t\t\tthrow new IllegalStateException(\"not the next in line..\");\n\t\t\t\t}\n\t\t\t\tif (this.served.get(desk).isPresent()) {\n\t\t\t\t\tthrow new IllegalStateException(\"desk busy\");\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\tif (this.next.get(desk).isPresent() && \n\t\t\t\t\tthis.next.get(desk).get()!= this.waiting.get(ticket)) {\n\t\t\t\t\tthrow new IllegalStateException(\"counter can't be used for this operation\");\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\tvar p = new Pair<>(ticket, this.waiting.get(ticket));\n\t\t\t\tthis.waiting.remove(ticket);\n\t\t\t\tthis.served.set(desk, Optional.of(p));\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void deskReleased(int desk) {\n\t\t\t\tif (this.served.get(desk).isEmpty()) {\n\t\t\t\t\tthrow new IllegalStateException();\t\t\n\t\t\t\t}\n\t\t\t\tthis.next.set(desk, policy.next(this.served.get(desk).get().getY()));\n\t\t\t\tthis.served.set(desk, Optional.empty());\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void exitOnWait(int ticket) {\n\t\t\t\tif (!this.waiting.containsKey(ticket)) {\n\t\t\t\t\tthrow new IllegalStateException();\n\t\t\t\t}\n\t\t\t\tthis.waiting.remove(ticket);\n\t\t\t}\n\t\t\t\n\t\t};\n\t}\n\n\t@Override\n\tpublic PostOffice createFlexible(int desksSize) {\n\t\treturn this.fromPolicy(o->Optional.empty(),desksSize);\n\t}\n\n\t\t@Override\n\tpublic PostOffice createAlternating(int desks) {\n\t\treturn this.fromPolicy(o->Optional.of(o==Operation.SEND ? Operation.RECEIVE : Operation.SEND),desks);\n\t}\n\n}", "filename": "PostOfficeFactoryImpl.java" } ]
{ "components": { "imports": "package a03b.sol1;\n\nimport static org.junit.Assert.*;\n\nimport java.util.List;\nimport java.util.Optional;\nimport a03b.sol1.PostOffice.Operation;", "private_init": "\t/*\n\t * Implement the PostOfficeFactory interface as indicated in the initFactory method below.\n\t * Realize a factory concept for PostOffice, which in turn models a post office\n\t * where people enter, take a numbered ticket indicating which operation they want to do\n\t * (sending or receiving), go in order to the free counters ('desks'), and then exit\n\t * the post office (they could also exit while waiting, without being served).\n\t * The factory creates two implementations, where the counters impose different constraints on which type of\n\t * operation they can perform from time to time.\n\t *\n\t * The comment on the provided interfaces, and the test methods below constitute the necessary\n\t * explanation of the problem.\n\t *\n\t * The following are considered optional for the purpose of being able to correct the exercise,\n\t * but still contribute to achieving the totality of the score:\n\t * - implementation of the test called optionalTestXYZ (related to the method\n\t * PostOffice.createAlternating)\n\t * - good design of the solution, in particular with minimization of repetitions\n\t *\n\t * Remove the comment from the initFactory method.\n\t *\n\t * Scoring indications:\n\t * - correctness of the mandatory part: 9 points\n\t * - correctness of the optional part: 4 points\n\t * - quality of the solution: 4 points\n\t *\n\t */\n\n\tprivate PostOfficeFactory pof = null;\n\t\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.pof = new PostOfficeFactoryImpl();\n\t}\n\t\n\t// basic checks on any PostOffice\n\tprivate void basicChecks(PostOffice po) {\n\t\t// initially all counters are free and no one is in line\n\t\tassertEquals(Optional.empty(),po.deskState(0));\n\t\tassertEquals(Optional.empty(),po.deskState(1));\n\t\tassertEquals(Optional.empty(),po.deskState(2));\n\t\tassertEquals(List.of(),po.peopleWaiting());\n\n\t\t// 3 customers arrive\n\t\tassertEquals(0, po.getTicket(Operation.SEND));\n\t\tassertEquals(1, po.getTicket(Operation.RECEIVE));\n\t\tassertEquals(2, po.getTicket(Operation.SEND));\n\t\t\n\t\t// all counters are free, the three customers are in line\n\t\tassertEquals(Optional.empty(),po.deskState(0));\n\t\tassertEquals(Optional.empty(),po.deskState(1));\n\t\tassertEquals(Optional.empty(),po.deskState(2));\n\t\tassertEquals(List.of(0,1,2),po.peopleWaiting());\n\t\t\n\t\t// the customer with ticket 0 goes to counter 0\n\t\tpo.goToDesk(0, 0);\n\t\t\n\t\t// the first counter is serving a SEND, customers 1 and 2 are in line\n\t\tassertEquals(Optional.of(Operation.SEND),po.deskState(0));\n\t\tassertEquals(Optional.empty(),po.deskState(1));\n\t\tassertEquals(Optional.empty(),po.deskState(2));\n\t\tassertEquals(List.of(1,2),po.peopleWaiting());\n\t\t\n\t\t// customer 2 exits, 3 enters\n\t\tpo.exitOnWait(2);\n\t\tassertEquals(3, po.getTicket(Operation.RECEIVE));\n\t\t\n\t\t// the first counter is serving a SEND, customers 1 and 3 are in line\n\t\tassertEquals(Optional.of(Operation.SEND),po.deskState(0));\n\t\tassertEquals(Optional.empty(),po.deskState(1));\n\t\tassertEquals(Optional.empty(),po.deskState(2));\n\t\tassertEquals(List.of(1,3),po.peopleWaiting());\n\t\t\n\t\t// the customer with ticket 1 goes to counter 2\n\t\tpo.goToDesk(1, 2);\n\t\t\n\t\tassertEquals(Optional.of(Operation.SEND),po.deskState(0));\n\t\tassertEquals(Optional.empty(),po.deskState(1));\n\t\tassertEquals(Optional.of(Operation.RECEIVE),po.deskState(2));\n\t\tassertEquals(List.of(3),po.peopleWaiting());\n\t\t\n\t\t// the customer at counter 0 exits\n\t\tpo.deskReleased(0);\n\t\t\n\t\t// the third counter is serving a RECEIVE, client 3 is in line\n\t\tassertEquals(Optional.empty(),po.deskState(0));\n\t\tassertEquals(Optional.empty(),po.deskState(1));\n\t\tassertEquals(Optional.of(Operation.RECEIVE),po.deskState(2));\n\t\tassertEquals(List.of(3),po.peopleWaiting());\n\t}", "test_functions": [ "\[email protected]\n\tpublic void testFlexibleBasic() {\n\t\tfinal PostOffice po = this.pof.createFlexible(3);\n\t\tthis.basicChecks(po); // base test, see above\n\t}", "\[email protected]\n\tpublic void testFlexiblePOAllocation() {\n\t\tfinal PostOffice po = this.pof.createFlexible(3);\n\t\t\n\t\tassertEquals(0, po.getTicket(Operation.SEND));\n\t\tassertEquals(1, po.getTicket(Operation.SEND));\n\t\tassertEquals(2, po.getTicket(Operation.RECEIVE));\n\t\t\n\t\t// verify that every possible allocation is correct, without exceptions\n\t\t\n\t\tpo.goToDesk(0, 0);\n\t\tpo.deskReleased(0);\n\t\t\n\t\tpo.goToDesk(1, 0);\n\t\tpo.deskReleased(0);\n\t\t\n\t\tpo.goToDesk(2, 0);\n\t\tpo.deskReleased(0);\n\t}", "\[email protected]\n\tpublic void optionalTestAlternatingBasic() {\n\t\tfinal PostOffice po = this.pof.createAlternating(3);\n\t\tthis.basicChecks(po); // base test, see above\n\t}", "\[email protected]\n\tpublic void optionalTestAlternatingPOAllocation() {\n\t\tfinal PostOffice po = this.pof.createAlternating(3);\n\t\t\n\t\tassertEquals(0, po.getTicket(Operation.SEND));\n\t\tassertEquals(1, po.getTicket(Operation.SEND));\n\t\tassertEquals(2, po.getTicket(Operation.RECEIVE));\n\t\tassertEquals(3, po.getTicket(Operation.RECEIVE));\n\t\t\n\t\t// counter 0 accepts a SEND\n\t\tpo.goToDesk(0, 0);\n\t\tpo.deskReleased(0);\n\t\t\n\t\t// now counter 0 does not accept a SEND\n\t\t// the test passes only if an IllegalStateException is thrown..\n\t\t\n\t\ttry {\n\t\t\tpo.goToDesk(1,0);\n\t\t\tfail(\"can't use desk 0 for sending again\");\n\t\t}" ] }, "content": "package a03b.sol1;\n\nimport static org.junit.Assert.*;\n\nimport java.util.List;\nimport java.util.Optional;\nimport a03b.sol1.PostOffice.Operation;\n\npublic class Test {\n\t\n\t/*\n\t * Implement the PostOfficeFactory interface as indicated in the initFactory method below.\n\t * Realize a factory concept for PostOffice, which in turn models a post office\n\t * where people enter, take a numbered ticket indicating which operation they want to do\n\t * (sending or receiving), go in order to the free counters ('desks'), and then exit\n\t * the post office (they could also exit while waiting, without being served).\n\t * The factory creates two implementations, where the counters impose different constraints on which type of\n\t * operation they can perform from time to time.\n\t *\n\t * The comment on the provided interfaces, and the test methods below constitute the necessary\n\t * explanation of the problem.\n\t *\n\t * The following are considered optional for the purpose of being able to correct the exercise,\n\t * but still contribute to achieving the totality of the score:\n\t * - implementation of the test called optionalTestXYZ (related to the method\n\t * PostOffice.createAlternating)\n\t * - good design of the solution, in particular with minimization of repetitions\n\t *\n\t * Remove the comment from the initFactory method.\n\t *\n\t * Scoring indications:\n\t * - correctness of the mandatory part: 9 points\n\t * - correctness of the optional part: 4 points\n\t * - quality of the solution: 4 points\n\t *\n\t */\n\n\tprivate PostOfficeFactory pof = null;\n\t\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.pof = new PostOfficeFactoryImpl();\n\t}\n\t\n\t// basic checks on any PostOffice\n\tprivate void basicChecks(PostOffice po) {\n\t\t// initially all counters are free and no one is in line\n\t\tassertEquals(Optional.empty(),po.deskState(0));\n\t\tassertEquals(Optional.empty(),po.deskState(1));\n\t\tassertEquals(Optional.empty(),po.deskState(2));\n\t\tassertEquals(List.of(),po.peopleWaiting());\n\n\t\t// 3 customers arrive\n\t\tassertEquals(0, po.getTicket(Operation.SEND));\n\t\tassertEquals(1, po.getTicket(Operation.RECEIVE));\n\t\tassertEquals(2, po.getTicket(Operation.SEND));\n\t\t\n\t\t// all counters are free, the three customers are in line\n\t\tassertEquals(Optional.empty(),po.deskState(0));\n\t\tassertEquals(Optional.empty(),po.deskState(1));\n\t\tassertEquals(Optional.empty(),po.deskState(2));\n\t\tassertEquals(List.of(0,1,2),po.peopleWaiting());\n\t\t\n\t\t// the customer with ticket 0 goes to counter 0\n\t\tpo.goToDesk(0, 0);\n\t\t\n\t\t// the first counter is serving a SEND, customers 1 and 2 are in line\n\t\tassertEquals(Optional.of(Operation.SEND),po.deskState(0));\n\t\tassertEquals(Optional.empty(),po.deskState(1));\n\t\tassertEquals(Optional.empty(),po.deskState(2));\n\t\tassertEquals(List.of(1,2),po.peopleWaiting());\n\t\t\n\t\t// customer 2 exits, 3 enters\n\t\tpo.exitOnWait(2);\n\t\tassertEquals(3, po.getTicket(Operation.RECEIVE));\n\t\t\n\t\t// the first counter is serving a SEND, customers 1 and 3 are in line\n\t\tassertEquals(Optional.of(Operation.SEND),po.deskState(0));\n\t\tassertEquals(Optional.empty(),po.deskState(1));\n\t\tassertEquals(Optional.empty(),po.deskState(2));\n\t\tassertEquals(List.of(1,3),po.peopleWaiting());\n\t\t\n\t\t// the customer with ticket 1 goes to counter 2\n\t\tpo.goToDesk(1, 2);\n\t\t\n\t\tassertEquals(Optional.of(Operation.SEND),po.deskState(0));\n\t\tassertEquals(Optional.empty(),po.deskState(1));\n\t\tassertEquals(Optional.of(Operation.RECEIVE),po.deskState(2));\n\t\tassertEquals(List.of(3),po.peopleWaiting());\n\t\t\n\t\t// the customer at counter 0 exits\n\t\tpo.deskReleased(0);\n\t\t\n\t\t// the third counter is serving a RECEIVE, client 3 is in line\n\t\tassertEquals(Optional.empty(),po.deskState(0));\n\t\tassertEquals(Optional.empty(),po.deskState(1));\n\t\tassertEquals(Optional.of(Operation.RECEIVE),po.deskState(2));\n\t\tassertEquals(List.of(3),po.peopleWaiting());\n\t}\n\t\n\[email protected]\n\tpublic void testFlexibleBasic() {\n\t\tfinal PostOffice po = this.pof.createFlexible(3);\n\t\tthis.basicChecks(po); // base test, see above\n\t}\n\n\[email protected]\n\tpublic void testFlexiblePOAllocation() {\n\t\tfinal PostOffice po = this.pof.createFlexible(3);\n\t\t\n\t\tassertEquals(0, po.getTicket(Operation.SEND));\n\t\tassertEquals(1, po.getTicket(Operation.SEND));\n\t\tassertEquals(2, po.getTicket(Operation.RECEIVE));\n\t\t\n\t\t// verify that every possible allocation is correct, without exceptions\n\t\t\n\t\tpo.goToDesk(0, 0);\n\t\tpo.deskReleased(0);\n\t\t\n\t\tpo.goToDesk(1, 0);\n\t\tpo.deskReleased(0);\n\t\t\n\t\tpo.goToDesk(2, 0);\n\t\tpo.deskReleased(0);\n\t}\n\t\n\[email protected]\n\tpublic void optionalTestAlternatingBasic() {\n\t\tfinal PostOffice po = this.pof.createAlternating(3);\n\t\tthis.basicChecks(po); // base test, see above\n\t}\n\t\n\[email protected]\n\tpublic void optionalTestAlternatingPOAllocation() {\n\t\tfinal PostOffice po = this.pof.createAlternating(3);\n\t\t\n\t\tassertEquals(0, po.getTicket(Operation.SEND));\n\t\tassertEquals(1, po.getTicket(Operation.SEND));\n\t\tassertEquals(2, po.getTicket(Operation.RECEIVE));\n\t\tassertEquals(3, po.getTicket(Operation.RECEIVE));\n\t\t\n\t\t// counter 0 accepts a SEND\n\t\tpo.goToDesk(0, 0);\n\t\tpo.deskReleased(0);\n\t\t\n\t\t// now counter 0 does not accept a SEND\n\t\t// the test passes only if an IllegalStateException is thrown..\n\t\t\n\t\ttry {\n\t\t\tpo.goToDesk(1,0);\n\t\t\tfail(\"can't use desk 0 for sending again\");\n\t\t} catch (IllegalStateException e) {\n\t\t\t\n\t\t} catch (Exception e) {\n\t\t\tfail(\"wrong exception raised\");\n\t\t}\n\t\t\n\t\t// customer 1 can go to counter 1\n\t\tpo.goToDesk(1,1);\n\t\t// customer 2, having a RECEIVE can go to counter 0\n\t\tpo.goToDesk(2,0);\n\t\tpo.deskReleased(0);\n\t\t\n\t\t// now counter 0 does not accept a RECEIVE\n\t\ttry {\n\t\t\tpo.goToDesk(3,0);\n\t\t\tfail(\"can't use desk 0 for receiving again\");\n\t\t} catch (IllegalStateException e) {\n\t\t\t\n\t\t} catch (Exception e) {\n\t\t\tfail(\"wrong exception raised\");\n\t\t}\n\t}\n\t\n\t\n}", "filename": "Test.java" }
2019
a06a
[ { "content": "package a06a.sol1;\n\n\npublic interface SRServiceFactory {\n\t\n\t\n\tSRService createMaximumAccess();\n\t\n\t\n\tSRService createWithNoConcurrentAccess();\n\t\n\t\n\tSRService createManyReceiveAndMaxTwoSend();\n\t\n}", "filename": "SRServiceFactory.java" }, { "content": "package a06a.sol1;\n\n\npublic interface SRService {\n\t\n\t\n\tint enter();\n\t\n\t\n\tvoid goReceive(int id);\n\t\n\t\n\tvoid goSend(int id);\n\t\t\n\t\n\tvoid exit(int id);\n}", "filename": "SRService.java" }, { "content": "package a06a.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 a06a.sol1;\n\nimport java.util.*;\n\npublic class SRServiceFactoryImpl implements SRServiceFactory {\n\t\n\tenum State {\n\t\tENTERED, GO_RECEIVE, GO_SEND\n\t}\n\t\n\t// This policy is used to state weather, given certain receiver and senders, we can allow a new receive/send\n\tinterface Policy{\n\t\tboolean canGo(boolean receiver, Set<Integer> receivers, Set<Integer> senders);\n\t}\n\t\n\tprivate SRService byPolicy(Policy p) {\n\t\treturn new SRService() {\n\t\t\tprivate Map<State,Set<Integer>> clients = new EnumMap<>(State.class) {{\n\t\t\t\tput(State.ENTERED, new HashSet<>());\n\t\t\t\tput(State.GO_RECEIVE, new HashSet<>());\n\t\t\t\tput(State.GO_SEND, new HashSet<>());\n\t\t\t}};\n\t\t\tprivate int counterId;\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic int enter() {\n\t\t\t\tthis.clients.get(State.ENTERED).add(this.counterId);\n\t\t\t\treturn this.counterId++;\n\t\t\t}\n\t\t\t\n\t\t\tprivate void go(int id, boolean receive, State target) {\n\t\t\t\tif (!clients.get(State.ENTERED).contains(id)) {\n\t\t\t\t\tthrow new IllegalStateException();\n\t\t\t\t}\n\t\t\t\tif (!p.canGo(receive, clients.get(State.GO_RECEIVE), clients.get(State.GO_SEND))) {\n\t\t\t\t\tthrow new IllegalStateException();\n\t\t\t\t}\n\t\t\t\tclients.get(State.ENTERED).remove(id);\n\t\t\t\tclients.get(target).add(id);\n\t\t\t}\n\t\t\t@Override\n\t\t\tpublic void goReceive(int id) {\n\t\t\t\tthis.go(id, true, State.GO_RECEIVE);\n\t\t\t}\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic void goSend(int id) {\n\t\t\t\tthis.go(id, false, State.GO_SEND);\n\t\t\t}\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic void exit(int id) {\n\t\t\t\tif (!clients.get(State.GO_RECEIVE).contains(id) && !clients.get(State.GO_SEND).contains(id)) {\n\t\t\t\t\tthrow new IllegalStateException();\n\t\t\t\t}\n\t\t\t\tclients.get(State.GO_SEND).remove(id);\n\t\t\t\tclients.get(State.GO_RECEIVE).remove(id);\n\t\t\t}\n\t\t};\n\t}\n\n\t@Override\n\tpublic SRService createMaximumAccess() {\n\t\treturn byPolicy( (b,receivers,senders) -> true ); // can always access\n\t}\n\n\t@Override\n\tpublic SRService createWithNoConcurrentAccess() { // true if none is accessing\n\t\treturn byPolicy( (b,receivers,senders) -> receivers.isEmpty() && senders.isEmpty() );\n\t}\n\n\t@Override\n\tpublic SRService createManyReceiveAndMaxTwoSend() {\n\t\treturn byPolicy( (b,receivers,senders) -> b || senders.size()<=1);\n\t}\n\n}", "filename": "SRServiceFactoryImpl.java" } ]
{ "components": { "imports": "package a06a.sol1;\n\nimport static org.junit.Assert.*;", "private_init": "\t/*\n\t * Implement the SRServiceFactory interface as indicated in the initFactory method below.\n\t * Create a factory concept for SRService, which in turn models (the counter for) a postal service,\n\t * where each customer can send or receive a package, but with certain constraints on when they can access it.\n\t * For example, an SRService could be permissive and always allow everyone to access the\n\t * counter concurrently, another could allow only one access at a time,\n\t * etcetera.\n\t *\n\t * The comments on the provided interfaces, and the test methods below constitute\n\t * the necessary explanation of the problem.\n\t *\n\t * The following are considered optional for the purpose of being able to correct\n\t * the exercise, but still contribute to achieving the full\n\t * score:\n\t * - implementation of the tests called optionalTestXYZ (related to some tests\n\t * on exceptions)\n\t * - good design of the solution, in particular with\n\t * minimization of repetitions, for example through the STRATEGY pattern\n\t *\n\t * Remove the comment from the initFactory method.\n\t *\n\t * Scoring indications:\n\t * - correctness of the required part: 8 points\n\t * - correctness of the optional part: 4 points\n\t * - quality of the solution: 5 points\n\t *\n\t */\n\n\tprivate SRServiceFactory srf = null;\n\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.srf = new SRServiceFactoryImpl();\n\t}", "test_functions": [ "\[email protected]\n\tpublic void testMaximumAccess() {\n\t\t// test of a service that always allows access\n\t\tfinal SRService sr = this.srf.createMaximumAccess();\n\t\t// three customers enter, they are given id 0,1,2\n\t\tassertEquals(0, sr.enter());\n\t\tassertEquals(1, sr.enter());\n\t\tassertEquals(2, sr.enter());\n\n\t\t// 0 wants to receive, 1 wants to send: they succeed\n\t\tsr.goReceive(0);\n\t\tsr.goSend(1);\n\n\t\t// 0 exits the system, completing the reception\n\t\tsr.exit(0);\n\n\t\t// a new customer enters, 3\n\t\tassertEquals(3, sr.enter());\n\n\t\t// 3 wants to send, 2 wants to receive: they succeed\n\t\tsr.goSend(3);\n\t\tsr.goReceive(2);\n\n\t\t// 2,1,3 complete the operation, exiting\n\t\tsr.exit(2);\n\t\tsr.exit(1);\n\t\tsr.exit(3);\n\t}", "\[email protected]\n\tpublic void testNoConcurrentAccess() {\n\t\t// test of a service that allows only one access at a time\n\t\tfinal SRService sr = this.srf.createWithNoConcurrentAccess();\n\n\t\tassertEquals(0, sr.enter());\n\t\tassertEquals(1, sr.enter());\n\t\tassertEquals(2, sr.enter());\n\n\t\t// 0 receives and exits, then 1 sends\n\t\tsr.goReceive(0);\n\t\tsr.exit(0);\n\t\tsr.goReceive(1);\n\n\t\tassertEquals(3, sr.enter());\n\n\t\t// 2 tries to receive but fails, because customer 1 is still sending\n\t\ttry {\n\t\t\tsr.goReceive(2);\n\t\t\tfail();\n\t\t}", "\[email protected]\n\tpublic void testManyReceiveAndOneSend() {\n\t\t// test of a service that lets multiple customers receive, but only one process\n\t\t// at a time can send\n\t\tfinal SRService sr = this.srf.createManyReceiveAndMaxTwoSend();\n\n\t\tassertEquals(0, sr.enter());\n\t\tassertEquals(1, sr.enter());\n\t\tassertEquals(2, sr.enter());\n\n\t\t// 0 and 1 can both receive, 2 can send\n\t\tsr.goReceive(0);\n\t\tsr.goReceive(1);\n\t\tsr.goSend(2);\n\n\t\tassertEquals(3, sr.enter());\n\t\tassertEquals(4, sr.enter());\n\n\t\t// 2 can send\n\t\tsr.goSend(3);\n\n\t\t// 4 cannot send, because 2 and 3 are already sending\n\t\ttry {\n\t\t\tsr.goSend(4);\n\t\t\tfail();\n\t\t}" ] }, "content": "package a06a.sol1;\n\nimport static org.junit.Assert.*;\n\npublic class Test {\n\n\t/*\n\t * Implement the SRServiceFactory interface as indicated in the initFactory method below.\n\t * Create a factory concept for SRService, which in turn models (the counter for) a postal service,\n\t * where each customer can send or receive a package, but with certain constraints on when they can access it.\n\t * For example, an SRService could be permissive and always allow everyone to access the\n\t * counter concurrently, another could allow only one access at a time,\n\t * etcetera.\n\t *\n\t * The comments on the provided interfaces, and the test methods below constitute\n\t * the necessary explanation of the problem.\n\t *\n\t * The following are considered optional for the purpose of being able to correct\n\t * the exercise, but still contribute to achieving the full\n\t * score:\n\t * - implementation of the tests called optionalTestXYZ (related to some tests\n\t * on exceptions)\n\t * - good design of the solution, in particular with\n\t * minimization of repetitions, for example through the STRATEGY pattern\n\t *\n\t * Remove the comment from the initFactory method.\n\t *\n\t * Scoring indications:\n\t * - correctness of the required part: 8 points\n\t * - correctness of the optional part: 4 points\n\t * - quality of the solution: 5 points\n\t *\n\t */\n\n\tprivate SRServiceFactory srf = null;\n\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.srf = new SRServiceFactoryImpl();\n\t}\n\n\[email protected]\n\tpublic void testMaximumAccess() {\n\t\t// test of a service that always allows access\n\t\tfinal SRService sr = this.srf.createMaximumAccess();\n\t\t// three customers enter, they are given id 0,1,2\n\t\tassertEquals(0, sr.enter());\n\t\tassertEquals(1, sr.enter());\n\t\tassertEquals(2, sr.enter());\n\n\t\t// 0 wants to receive, 1 wants to send: they succeed\n\t\tsr.goReceive(0);\n\t\tsr.goSend(1);\n\n\t\t// 0 exits the system, completing the reception\n\t\tsr.exit(0);\n\n\t\t// a new customer enters, 3\n\t\tassertEquals(3, sr.enter());\n\n\t\t// 3 wants to send, 2 wants to receive: they succeed\n\t\tsr.goSend(3);\n\t\tsr.goReceive(2);\n\n\t\t// 2,1,3 complete the operation, exiting\n\t\tsr.exit(2);\n\t\tsr.exit(1);\n\t\tsr.exit(3);\n\t}\n\n\[email protected]\n\tpublic void testNoConcurrentAccess() {\n\t\t// test of a service that allows only one access at a time\n\t\tfinal SRService sr = this.srf.createWithNoConcurrentAccess();\n\n\t\tassertEquals(0, sr.enter());\n\t\tassertEquals(1, sr.enter());\n\t\tassertEquals(2, sr.enter());\n\n\t\t// 0 receives and exits, then 1 sends\n\t\tsr.goReceive(0);\n\t\tsr.exit(0);\n\t\tsr.goReceive(1);\n\n\t\tassertEquals(3, sr.enter());\n\n\t\t// 2 tries to receive but fails, because customer 1 is still sending\n\t\ttry {\n\t\t\tsr.goReceive(2);\n\t\t\tfail();\n\t\t} catch (IllegalStateException e) {\n\n\t\t} catch (Exception e) {\n\t\t\tfail(\"wrong exception thrown\");\n\t\t}\n\n\t\t// 2 tries to send but fails, because customer 1 is still sending\n\t\ttry {\n\t\t\tsr.goSend(2);\n\t\t\tfail();\n\t\t} catch (IllegalStateException e) {\n\n\t\t} catch (Exception e) {\n\t\t\tfail(\"wrong exception thrown\");\n\t\t}\n\n\t\t// 1 exits, and at this point 2 can access\n\t\tsr.exit(1);\n\t\tsr.goSend(2);\n\t}\n\n\t// you can't make someone exit who is not performing an operation\n\[email protected](expected = IllegalStateException.class)\n\tpublic void testCantExitIfNotAccessing() {\n\t\tfinal SRService sr = this.srf.createMaximumAccess();\n\n\t\tassertEquals(0, sr.enter());\n\t\tsr.exit(0);\n\t}\n\t\n\[email protected]\n\tpublic void testManyReceiveAndOneSend() {\n\t\t// test of a service that lets multiple customers receive, but only one process\n\t\t// at a time can send\n\t\tfinal SRService sr = this.srf.createManyReceiveAndMaxTwoSend();\n\n\t\tassertEquals(0, sr.enter());\n\t\tassertEquals(1, sr.enter());\n\t\tassertEquals(2, sr.enter());\n\n\t\t// 0 and 1 can both receive, 2 can send\n\t\tsr.goReceive(0);\n\t\tsr.goReceive(1);\n\t\tsr.goSend(2);\n\n\t\tassertEquals(3, sr.enter());\n\t\tassertEquals(4, sr.enter());\n\n\t\t// 2 can send\n\t\tsr.goSend(3);\n\n\t\t// 4 cannot send, because 2 and 3 are already sending\n\t\ttry {\n\t\t\tsr.goSend(4);\n\t\t\tfail();\n\t\t} catch (IllegalStateException e) {\n\n\t\t} catch (Exception e) {\n\t\t\tfail(\"wrong exception thrown\");\n\t\t}\n\n\t}\n\n\t// you can't make someone execute an operation if they are already doing it\n\[email protected](expected = IllegalStateException.class)\n\tpublic void testCantAccessIfAlreadyAccessing() {\n\t\tfinal SRService sr = this.srf.createMaximumAccess();\n\n\t\tassertEquals(0, sr.enter());\n\t\tsr.goReceive(0);\n\t\tsr.goSend(0);\n\t}\n\n\t// you can't make someone execute an operation if they haven't had an id\n\[email protected](expected = IllegalStateException.class)\n\tpublic void optionalTestWrongId() {\n\t\tfinal SRService sr = this.srf.createMaximumAccess();\n\n\t\tassertEquals(0, sr.enter());\n\t\tsr.goReceive(1);\n\t}\n\n\t// you can't make someone execute an operation if they have already exited\n\[email protected](expected = IllegalStateException.class)\n\tpublic void optionalTestAlreadyExited() {\n\t\tfinal SRService sr = this.srf.createMaximumAccess();\n\n\t\tassertEquals(0, sr.enter());\n\t\tsr.goReceive(0);\n\t\tsr.exit(0);\n\t\tsr.goReceive(0);\n\t}\n}", "filename": "Test.java" }
2019
a04b
[ { "content": "package a04b.sol1;\n\n\npublic interface ParsersFactory {\n\t\n\t\n\tParser<Integer> createSequenceParserToCount(String t);\n\t\n\t\n\tParser<String> createNonEmptySequenceParserToString(String t);\n\t\n\t\n\tParser<Integer> createExpressionParserToResult();\n}", "filename": "ParsersFactory.java" }, { "content": "package a04b.sol1;\n\nimport java.util.List;\n\n\npublic interface Parser<R> {\n\t\n\t\n\tboolean getNext(String token);\n\t\n\t\n\tboolean getAllInList(List<String> tokens);\n\t\t\n\t\n\tR completeAndCreateResult();\n}", "filename": "Parser.java" }, { "content": "package a04b.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 a04b.sol1;\n\nimport java.util.List;\nimport java.util.Optional;\nimport java.util.Set;\n\npublic class ParsersFactoryImpl implements ParsersFactory {\n\t\n\tprivate abstract class AbstractParser<R> implements Parser<R> {\n\t\t\n\t\tprotected boolean correct = true;\n\t\tprotected R result; \n\t\t\n\t\tprotected AbstractParser(R initialResult) {\n\t\t\tthis.result = initialResult;\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic boolean getNext(String token) { // template method\n\t\t\tthis.correct = this.correct && canBeAccepted(token);\n\t\t\tthis.updateResult(token);\n\t\t\treturn this.correct;\n\t\t}\n\t\t\n\t\tprotected abstract boolean canBeAccepted(String token);\n\t\t\n\t\tprotected abstract void updateResult(String token);\n\t\t\n\t\tprotected abstract boolean sentenceIsComplete();\n\n\t\t@Override\n\t\tpublic R completeAndCreateResult() { // template method\n\t\t\tif (!this.correct || !this.sentenceIsComplete()) {\n\t\t\t\tthrow new IllegalStateException();\n\t\t\t}\n\t\t\treturn this.result;\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic boolean getAllInList(List<String> tokens) { // template method\n\t\t\treturn tokens.stream().allMatch(this::getNext);\n\t\t}\n\t}\n\n\t@Override\n\tpublic Parser<Integer> createSequenceParserToCount(String t) {\n\t\treturn new AbstractParser<Integer>(0) {\n\n\t\t\t@Override\n\t\t\tprotected boolean canBeAccepted(String token) {\n\t\t\t\treturn token.equals(t);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tprotected void updateResult(String token) {\n\t\t\t\tthis.result++;\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tprotected boolean sentenceIsComplete() {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\n\t\t};\n\t}\n\n\t@Override\n\tpublic Parser<String> createNonEmptySequenceParserToString(String t) {\n\t\treturn new AbstractParser<String>(\"\") {\n\n\t\t\t@Override\n\t\t\tprotected boolean canBeAccepted(String token) {\n\t\t\t\treturn token.equals(t);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tprotected void updateResult(String token) {\n\t\t\t\tthis.result = this.result + token;\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tprotected boolean sentenceIsComplete() {\n\t\t\t\treturn this.result.length()>0;\n\t\t\t}\n\t\t\n\t\t};\n\t}\n\n\t@Override\n\tpublic Parser<Integer> createExpressionParserToResult() {\n\t\treturn new AbstractParser<Integer>(0) {\n\t\t\tprivate final Set<String> OPERATORS = Set.of(\"+\",\"-\");\n\t\t\tprivate final Set<String> NUMBERS = Set.of(\"0\",\"1\");\n\t\t\tprivate Optional<String> previousToken = Optional.empty();\n\t\t\t\n\t\t\tprivate int num(String t) {\n\t\t\t\treturn t.equals(\"0\") ? 0 : 1;\n\t\t\t}\n\t\t\t\n\t\t\tprivate java.util.function.BinaryOperator<Integer> op(String t) {\n\t\t\t\treturn t.equals(\"+\") ? (a,b)->a+b : (a,b)->a-b;\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tprotected boolean canBeAccepted(String token) {\n\t\t\t\tif (previousToken.isEmpty() || OPERATORS.contains(previousToken.get())) {\n\t\t\t\t\treturn NUMBERS.contains(token);\n\t\t\t\t} else {\n\t\t\t\t\treturn OPERATORS.contains(token);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tprotected void updateResult(String token) {\n\t\t\t\tif (previousToken.isEmpty()) {\n\t\t\t\t\tthis.result = num(token);\n\t\t\t\t} else if ( OPERATORS.contains(previousToken.get()) ) {\n\t\t\t\t\tthis.result = op(previousToken.get()).apply(this.result, num(token));\n\t\t\t\t} \n\t\t\t\tthis.previousToken = Optional.of(token);\n\t\t\t\tSystem.out.println(\"Aft \"+result + \" \" + token + \" \" + previousToken);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tprotected boolean sentenceIsComplete() {\n\t\t\t\treturn previousToken.isPresent() && !OPERATORS.contains(previousToken.get());\n\t\t\t}\n\t\t\n\t\t};\n\t}\n\n\t\n}", "filename": "ParsersFactoryImpl.java" } ]
{ "components": { "imports": "package a04b.sol1;\n\nimport static org.junit.Assert.*;\n\nimport java.util.List;\n\nimport org.junit.Assert;", "private_init": "\t/*\n\t * A parser is a software component that consumes a sequence of tokens (strings) one by one, and when\n\t * finished, it recognizes whether the overall \"phrase\" corresponds to a specific syntax (or structure/grammar),\n\t * possibly producing a result.\n\t * Implement the ParsersFactory interface as indicated in the initFactory method below.\n\t * It realizes a factory concept for Parser<R>, which in turn models a parser that returns a result\n\t * of type R.\n\t *\n\t * The comments on the provided interfaces, and the test methods below constitute the necessary\n\t * explanation of the problem.\n\t *\n\t * The following are considered optional for the purpose of being able to correct the exercise,\n\t * but still contribute to achieving the totality of the score:\n\t * - implementation of the tests called optionalTestXYZ (related to the ParserFactory.createNonEmptySequenceParserToString method)\n\t * - the good design of the solution, in particular with minimization of repetitions\n\t *\n\t * Remove the comment from the initFactory method.\n\t *\n\t * Scoring indications:\n\t * - correctness of the mandatory part: 9 points\n\t * - correctness of the optional part: 4 points\n\t * - quality of the solution: 4 points\n\t *\n\t */\n\t\n\tprivate ParsersFactory factory = null;\n\t\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.factory = new ParsersFactoryImpl();\n\t}", "test_functions": [ "\[email protected]\n\tpublic void testSequenceParserOK() {\n\t\t// a parser for arbitrarily long sequences of \"a\"\n\t\tfinal Parser<Integer> sp = this.factory.createSequenceParserToCount(\"a\");\n\t\tassertTrue(sp.getNext(\"a\"));\n\t\tassertTrue(sp.getNext(\"a\"));\n\t\tassertTrue(sp.getNext(\"a\"));\n\t\t// the phrase \"a\",\"a\",\"a\" must be recognized, with result 3\n\t\tassertEquals(sp.completeAndCreateResult().intValue(),3);\n\t}", "\[email protected]\n\tpublic void testSequenceParserOKWithList() {\n\t\t// a parser for arbitrarily long sequences of \"a\"\n\t\tfinal Parser<Integer> sp = this.factory.createSequenceParserToCount(\"a\");\n\t\tassertTrue(sp.getAllInList(List.of(\"a\",\"a\",\"a\",\"a\")));\n\t\t// the phrase \"a\",\"a\",\"a\",\"a\" must be recognized, with result 4\n\t\tassertEquals(sp.completeAndCreateResult().intValue(),4);\n\t}", "\[email protected]\n\tpublic void testSequenceParserWithEmptySequence() {\n\t\t// a parser for arbitrarily long sequences of \"a\"\n\t\tfinal Parser<Integer> sp = this.factory.createSequenceParserToCount(\"a\");\n\t\t// the phrase without tokens, a special case of a sequence of \"a\" must be recognized, with result 0\n\t\tassertEquals(sp.completeAndCreateResult().intValue(),0);\n\t}", "\[email protected]\n\tpublic void testSequenceParserThatFails() {\n\t\t// a parser for arbitrarily long sequences of \"a\"\n\t\tfinal Parser<Integer> sp = this.factory.createSequenceParserToCount(\"a\");\n\t\tassertTrue(sp.getNext(\"a\")); // so far so good\n\t\tassertTrue(sp.getNext(\"a\")); // so far so good\n\t\tassertFalse(sp.getNext(\"b\")); // token not recognized, the parser becomes unusable\n\t\tassertFalse(sp.getNext(\"a\")); // no longer recognizes anything..\n\t\tassertFalse(sp.getNext(\"a\"));\n\t\ttry {\n\t\t\t// the attempt to complete causes an IllegalStateException\n\t\t\tsp.completeAndCreateResult();\n\t\t\tAssert.fail();\n\t\t}", "\[email protected]\n\tpublic void optionalTestNonEmptySequenceParserOK() {\n\t\t// a parser for non-empty sequences of \"b\".. that gives the concatenation as a result\n\t\tfinal Parser<String> sp = this.factory.createNonEmptySequenceParserToString(\"b\");\n\t\tassertTrue(sp.getAllInList(List.of(\"b\",\"b\",\"b\",\"b\")));\n\t\t// the phrase \"b\",\"b\",\"b\",\"b\" must be recognized, with result \"bbbb\"\n\t\tassertEquals(sp.completeAndCreateResult(),\"bbbb\");\n\t}", "\[email protected]\n\tpublic void optionalTestNonEmptySequenceParsersThatFails() {\n\t\t// a parser for non-empty sequences of \"b\".. that gives the concatenation as a result\n\t\tfinal Parser<String> sp = this.factory.createNonEmptySequenceParserToString(\"b\");\n\t\t// the phrase \"b\",\"b\",\"a\",\"b\" must NOT be recognized\n\t\tassertFalse(sp.getAllInList(List.of(\"b\",\"b\",\"a\",\"b\")));\n\t\ttry {\n\t\t\t// the attempt to complete causes an IllegalStateException\n\t\t\tsp.completeAndCreateResult();\n\t\t\tAssert.fail();\n\t\t}", "\[email protected]\n\tpublic void testExpressionParserOK1() {\n\t\t// a parser for expressions with +/- on 0/1\n\t\tfinal Parser<Integer> sp = this.factory.createExpressionParserToResult();\n\t\tassertTrue(sp.getAllInList(List.of(\"1\",\"+\",\"1\",\"+\",\"0\")));\n\t\t// correct expression, result 2\n\t\tassertEquals(sp.completeAndCreateResult().intValue(),2);\n\t}", "\[email protected]\n\tpublic void testExpressionParserOK2() {\n\t\t// a parser for expressions with +/- on 0/1\n\t\tfinal Parser<Integer> sp = this.factory.createExpressionParserToResult();\n\t\tassertTrue(sp.getAllInList(List.of(\"1\",\"-\",\"1\",\"+\",\"1\")));\n\t\t// correct expression, result 1\n\t\tassertEquals(sp.completeAndCreateResult().intValue(),1);\n\t}", "\[email protected]\n\tpublic void testExpressionParserOK3() {\n\t\t// a parser for expressions with +/- on 0/1\n\t\tfinal Parser<Integer> sp = this.factory.createExpressionParserToResult();\n\t\tassertTrue(sp.getAllInList(List.of(\"1\",\"-\",\"1\",\"-\",\"1\",\"-\",\"0\")));\n\t\t// correct expression, result -1\n\t\tassertEquals(sp.completeAndCreateResult().intValue(),-1);\n\t}", "\[email protected]\n\tpublic void testExpressionParsersThatFails1() {\n\t\t// a parser for expressions with +/- on 0/1\n\t\tfinal Parser<Integer> sp = this.factory.createExpressionParserToResult();\n\t\t// expression NOT correct\n\t\tassertFalse(sp.getAllInList(List.of(\"1\",\"-\",\"1\",\"1\")));\n\t}", "\[email protected]\n\tpublic void testExpressionParsersThatFails2() {\n\t\t// a parser for expressions with +/- on 0/1\n\t\tfinal Parser<Integer> sp = this.factory.createExpressionParserToResult();\n\t\t// expression NOT correct\n\t\tassertFalse(sp.getAllInList(List.of(\"1\",\"-\",\"-\",\"1\")));\n\t}", "\[email protected]\n\tpublic void testExpressionParsersThatFails3() {\n\t\t// a parser for expressions with +/- on 0/1\n\t\tfinal Parser<Integer> sp = this.factory.createExpressionParserToResult();\n\t\t// expression NOT correct\n\t\tassertFalse(sp.getAllInList(List.of(\"+\",\"1\",\"-\",\"1\")));\n\t}", "\[email protected]\n\tpublic void testExpressionParsersThatFails4() {\n\t\t// a parser for expressions with +/- on 0/1\n\t\tfinal Parser<Integer> sp = this.factory.createExpressionParserToResult();\n\t\t// expression NOT correct\n\t\tassertFalse(sp.getAllInList(List.of(\"1\",\"-\",\"2\")));\n\t}" ] }, "content": "package a04b.sol1;\n\nimport static org.junit.Assert.*;\n\nimport java.util.List;\n\nimport org.junit.Assert;\n\npublic class Test {\n\t\n\t/*\n\t * A parser is a software component that consumes a sequence of tokens (strings) one by one, and when\n\t * finished, it recognizes whether the overall \"phrase\" corresponds to a specific syntax (or structure/grammar),\n\t * possibly producing a result.\n\t * Implement the ParsersFactory interface as indicated in the initFactory method below.\n\t * It realizes a factory concept for Parser<R>, which in turn models a parser that returns a result\n\t * of type R.\n\t *\n\t * The comments on the provided interfaces, and the test methods below constitute the necessary\n\t * explanation of the problem.\n\t *\n\t * The following are considered optional for the purpose of being able to correct the exercise,\n\t * but still contribute to achieving the totality of the score:\n\t * - implementation of the tests called optionalTestXYZ (related to the ParserFactory.createNonEmptySequenceParserToString method)\n\t * - the good design of the solution, in particular with minimization of repetitions\n\t *\n\t * Remove the comment from the initFactory method.\n\t *\n\t * Scoring indications:\n\t * - correctness of the mandatory part: 9 points\n\t * - correctness of the optional part: 4 points\n\t * - quality of the solution: 4 points\n\t *\n\t */\n\t\n\tprivate ParsersFactory factory = null;\n\t\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.factory = new ParsersFactoryImpl();\n\t}\n\n\[email protected]\n\tpublic void testSequenceParserOK() {\n\t\t// a parser for arbitrarily long sequences of \"a\"\n\t\tfinal Parser<Integer> sp = this.factory.createSequenceParserToCount(\"a\");\n\t\tassertTrue(sp.getNext(\"a\"));\n\t\tassertTrue(sp.getNext(\"a\"));\n\t\tassertTrue(sp.getNext(\"a\"));\n\t\t// the phrase \"a\",\"a\",\"a\" must be recognized, with result 3\n\t\tassertEquals(sp.completeAndCreateResult().intValue(),3);\n\t}\n\t\n\[email protected]\n\tpublic void testSequenceParserOKWithList() {\n\t\t// a parser for arbitrarily long sequences of \"a\"\n\t\tfinal Parser<Integer> sp = this.factory.createSequenceParserToCount(\"a\");\n\t\tassertTrue(sp.getAllInList(List.of(\"a\",\"a\",\"a\",\"a\")));\n\t\t// the phrase \"a\",\"a\",\"a\",\"a\" must be recognized, with result 4\n\t\tassertEquals(sp.completeAndCreateResult().intValue(),4);\n\t}\n\t\n\[email protected]\n\tpublic void testSequenceParserWithEmptySequence() {\n\t\t// a parser for arbitrarily long sequences of \"a\"\n\t\tfinal Parser<Integer> sp = this.factory.createSequenceParserToCount(\"a\");\n\t\t// the phrase without tokens, a special case of a sequence of \"a\" must be recognized, with result 0\n\t\tassertEquals(sp.completeAndCreateResult().intValue(),0);\n\t}\n\t\n\[email protected]\n\tpublic void testSequenceParserThatFails() {\n\t\t// a parser for arbitrarily long sequences of \"a\"\n\t\tfinal Parser<Integer> sp = this.factory.createSequenceParserToCount(\"a\");\n\t\tassertTrue(sp.getNext(\"a\")); // so far so good\n\t\tassertTrue(sp.getNext(\"a\")); // so far so good\n\t\tassertFalse(sp.getNext(\"b\")); // token not recognized, the parser becomes unusable\n\t\tassertFalse(sp.getNext(\"a\")); // no longer recognizes anything..\n\t\tassertFalse(sp.getNext(\"a\"));\n\t\ttry {\n\t\t\t// the attempt to complete causes an IllegalStateException\n\t\t\tsp.completeAndCreateResult();\n\t\t\tAssert.fail();\n\t\t} catch (IllegalStateException e) {\n\t\t} catch (Exception e) {\n\t\t\tAssert.fail();\n\t\t}\n\t}\n\t\n\[email protected]\n\tpublic void optionalTestNonEmptySequenceParserOK() {\n\t\t// a parser for non-empty sequences of \"b\".. that gives the concatenation as a result\n\t\tfinal Parser<String> sp = this.factory.createNonEmptySequenceParserToString(\"b\");\n\t\tassertTrue(sp.getAllInList(List.of(\"b\",\"b\",\"b\",\"b\")));\n\t\t// the phrase \"b\",\"b\",\"b\",\"b\" must be recognized, with result \"bbbb\"\n\t\tassertEquals(sp.completeAndCreateResult(),\"bbbb\");\n\t}\n\t\n\[email protected]\n\tpublic void optionalTestNonEmptySequenceParsersThatFails() {\n\t\t// a parser for non-empty sequences of \"b\".. that gives the concatenation as a result\n\t\tfinal Parser<String> sp = this.factory.createNonEmptySequenceParserToString(\"b\");\n\t\t// the phrase \"b\",\"b\",\"a\",\"b\" must NOT be recognized\n\t\tassertFalse(sp.getAllInList(List.of(\"b\",\"b\",\"a\",\"b\")));\n\t\ttry {\n\t\t\t// the attempt to complete causes an IllegalStateException\n\t\t\tsp.completeAndCreateResult();\n\t\t\tAssert.fail();\n\t\t} catch (IllegalStateException e) {\n\t\t} catch (Exception e) {\n\t\t\tAssert.fail();\n\t\t}\n\t\t// a parser for non-empty sequences of \"b\".. that gives the concatenation as a result\n\t\tfinal Parser<String> sp2 = this.factory.createNonEmptySequenceParserToString(\"b\");\n\t\ttry {\n\t\t\t// the attempt to complete causes an IllegalStateException, because the empty sequence is not recognized\n\t\t\tsp2.completeAndCreateResult();\n\t\t\tAssert.fail();\n\t\t} catch (IllegalStateException e) {\n\t\t} catch (Exception e) {\n\t\t\tAssert.fail();\n\t\t}\n\t}\n\t\n\[email protected]\n\tpublic void testExpressionParserOK1() {\n\t\t// a parser for expressions with +/- on 0/1\n\t\tfinal Parser<Integer> sp = this.factory.createExpressionParserToResult();\n\t\tassertTrue(sp.getAllInList(List.of(\"1\",\"+\",\"1\",\"+\",\"0\")));\n\t\t// correct expression, result 2\n\t\tassertEquals(sp.completeAndCreateResult().intValue(),2);\n\t}\n\t\n\[email protected]\n\tpublic void testExpressionParserOK2() {\n\t\t// a parser for expressions with +/- on 0/1\n\t\tfinal Parser<Integer> sp = this.factory.createExpressionParserToResult();\n\t\tassertTrue(sp.getAllInList(List.of(\"1\",\"-\",\"1\",\"+\",\"1\")));\n\t\t// correct expression, result 1\n\t\tassertEquals(sp.completeAndCreateResult().intValue(),1);\n\t}\n\t\n\[email protected]\n\tpublic void testExpressionParserOK3() {\n\t\t// a parser for expressions with +/- on 0/1\n\t\tfinal Parser<Integer> sp = this.factory.createExpressionParserToResult();\n\t\tassertTrue(sp.getAllInList(List.of(\"1\",\"-\",\"1\",\"-\",\"1\",\"-\",\"0\")));\n\t\t// correct expression, result -1\n\t\tassertEquals(sp.completeAndCreateResult().intValue(),-1);\n\t}\n\t\n\[email protected]\n\tpublic void testExpressionParsersThatFails1() {\n\t\t// a parser for expressions with +/- on 0/1\n\t\tfinal Parser<Integer> sp = this.factory.createExpressionParserToResult();\n\t\t// expression NOT correct\n\t\tassertFalse(sp.getAllInList(List.of(\"1\",\"-\",\"1\",\"1\")));\n\t}\n\t\n\[email protected]\n\tpublic void testExpressionParsersThatFails2() {\n\t\t// a parser for expressions with +/- on 0/1\n\t\tfinal Parser<Integer> sp = this.factory.createExpressionParserToResult();\n\t\t// expression NOT correct\n\t\tassertFalse(sp.getAllInList(List.of(\"1\",\"-\",\"-\",\"1\")));\n\t}\n\t\n\[email protected]\n\tpublic void testExpressionParsersThatFails3() {\n\t\t// a parser for expressions with +/- on 0/1\n\t\tfinal Parser<Integer> sp = this.factory.createExpressionParserToResult();\n\t\t// expression NOT correct\n\t\tassertFalse(sp.getAllInList(List.of(\"+\",\"1\",\"-\",\"1\")));\n\t}\n\t\n\[email protected]\n\tpublic void testExpressionParsersThatFails4() {\n\t\t// a parser for expressions with +/- on 0/1\n\t\tfinal Parser<Integer> sp = this.factory.createExpressionParserToResult();\n\t\t// expression NOT correct\n\t\tassertFalse(sp.getAllInList(List.of(\"1\",\"-\",\"2\")));\n\t}\n}", "filename": "Test.java" }
2019
a01b
[ { "content": "package a01b.sol1;\n\n\n\npublic class Cell<X> {\n\t\n\tprivate int row;\n\tprivate int column;\n\tprivate X value;\n\t\n\tpublic Cell(int row, int column, X value) {\n\t\tsuper();\n\t\tthis.row = row;\n\t\tthis.column = column;\n\t\tthis.value = value;\n\t}\n\n\tpublic int getRow() {\n\t\treturn this.row;\n\t}\n\n\tpublic int getColumn() {\n\t\treturn this.column;\n\t}\n\n\tpublic X getValue() {\n\t\treturn this.value;\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 + column;\n\t\tresult = prime * result + row;\n\t\tresult = prime * result + ((value == null) ? 0 : value.hashCode());\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj) {\n\t\t\treturn true;\n\t\t}\n\t\tif (!(obj instanceof Cell)) {\n\t\t\treturn false;\n\t\t}\n\t\tCell other = (Cell) obj;\n\t\tif (column != other.column) {\n\t\t\treturn false;\n\t\t}\n\t\tif (row != other.row) {\n\t\t\treturn false;\n\t\t}\n\t\tif (value == null) {\n\t\t\tif (other.value != null) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t} else if (!value.equals(other.value)) {\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Cell [row=\" + row + \", column=\" + column + \", value=\" + value + \"]\";\n\t}\n\n\t\n}", "filename": "Cell.java" }, { "content": "package a01b.sol1;\n\nimport java.util.Iterator;\n\npublic interface Grid<E> {\n\n\t\n\tint getRows();\n\t\n\t\n\tint getColumns();\n\t\n\t\n\tE getValue(int row, int column);\n\t\n\t\n\tvoid setColumn(int column, E value);\n\t\n\t\n\tvoid setRow(int row, E value);\n\t\n\t\n\tvoid setBorder(E value);\n\t\n\t\n\tvoid setDiagonal(E value);\n\t\n\t\n\tIterator<Cell<E>> iterator(boolean onlyNonNull);\n}", "filename": "Grid.java" }, { "content": "package a01b.sol1;\n\n\npublic interface GridFactory {\n\n\t\n\t<E> Grid<E> create(int rows, int cols);\n}", "filename": "GridFactory.java" }, { "content": "package a01b.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 a01b.sol1;\n\nimport java.util.*;\nimport java.util.stream.IntStream;\n\npublic class GridImpl<X> implements Grid<X> {\n\t\n\tprivate Map<Pair<Integer,Integer>,X> map = new HashMap<>();\n\tprivate int rows;\n\tprivate int columns;\n\t\n\tpublic GridImpl(int rows, int columns) {\n\t\tsuper();\n\t\tthis.rows = rows;\n\t\tthis.columns = columns;\n\t}\n\n\t@Override\n\tpublic int getRows() {\n\t\treturn this.rows;\n\t}\n\n\t@Override\n\tpublic int getColumns() {\n\t\treturn this.columns;\n\t}\n\n\t@Override\n\tpublic void setColumn(int column, X value) {\n\t\tfor (int row=0; row<this.rows; row++) {\n\t\t\tthis.map.put(new Pair<>(row,column),value);\n\t\t}\n\t}\n\n\t@Override\n\tpublic void setRow(int row, X value) {\n\t\tfor (int column=0; column<this.columns; column++) {\n\t\t\tthis.map.put(new Pair<>(row,column),value);\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic X getValue(int row, int column) {\n\t\treturn this.map.get(new Pair<>(row,column));\n\t}\n\n\t@Override\n\tpublic void setBorder(X value) {\n\t\tthis.setRow(0, value);\n\t\tthis.setRow(this.rows-1, value);\n\t\tthis.setColumn(0, value);\n\t\tthis.setColumn(this.columns-1, value);\n\t}\n\n\t@Override\n\tpublic void setDiagonal(X value) {\n\t\tfor (int i=0; i<this.rows && i<this.columns; i++) {\n\t\t\tthis.map.put(new Pair<>(i,i),value);\n\t\t}\n\t}\n\n\t@Override\n\tpublic Iterator<Cell<X>> iterator(boolean onlyNonNull) {\n\t\treturn IntStream.range(0,this.rows)\n\t\t\t\t\t\t.boxed()\n\t\t\t\t .flatMap(r-> IntStream.range(0,this.columns).boxed().map(c->new Pair<>(r,c)))\n\t\t\t\t .map(p -> new Cell<>(p.getX(),p.getY(),map.get(p)))\n\t\t\t\t .filter(p -> !onlyNonNull || p.getValue()!=null)\n\t\t\t\t .iterator();\n\t}\n}", "filename": "GridImpl.java" }, { "content": "package a01b.sol1;\n\npublic class GridFactoryImpl implements GridFactory {\n\n\t@Override\n\tpublic <X> Grid<X> create(int rows, int columns) {\n\t\treturn new GridImpl<>(rows,columns);\n\t}\n\n}", "filename": "GridFactoryImpl.java" } ]
{ "components": { "imports": "package a01b.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;", "private_init": "\t/*\n\t * Implement the GridFactory interface as indicated in the initFactory method below.\n\t * Implement a factory concept for rectangular grids, where each cell contains a\n\t * value whose type is that of the type-variable <X> of the Grid interface.\n\t * The factory provides a grid that logically has all cells initially empty (null value).\n\t * The grid provides methods to set values on a row, a column, the diagonal, and the entire border.\n\t * It also provides a method to iterate over all cells, or only the non-empty ones.\n\t * The comment on the provided interfaces, and the test methods below constitute the necessary explanation of the\n\t * problem.\n\t *\n\t * The following are considered optional for the purpose of being able to correct the exercise, but still contribute to achieving\n\t * the totality of the score:\n\t * - implementation of the tests called optionalTestXYZ (relative to the Grid.iterator() method)\n\t * - the good design of the solution, in particular with minimization of repetitions\n\t *\n\t * Remove the comment from the initFactory method.\n\t *\n\t * Scoring indications:\n\t * - correctness of the mandatory part: 9 points\n\t * - correctness of the optional part: 4 points\n\t * - quality of the solution: 4 points\n\t *\n\t */\n\t\n\tprivate GridFactory gf = null;\n\t\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.gf = new GridFactoryImpl();\n\t}", "test_functions": [ "\[email protected]\n\tpublic void testBasic() {\n\t\tfinal Grid<String> g = this.gf.create(2, 3); // two rows [null,null,null] and [null,null,null]\n\t\tassertNull(g.getValue(0, 0));\n\t\tassertEquals(2,g.getRows());\n\t\tassertEquals(3,g.getColumns());\n\t}", "\[email protected]\n\tpublic void testRow() {\n\t\tfinal Grid<String> g = this.gf.create(2, 3); // two rows: [null,null,null] and [null,null,null]\n\t\tg.setRow(0, \"a\"); // two rows: [a,a,a] and [null,null,null]\n\t\tassertNull(g.getValue(1, 0));\n\t\tassertNull(g.getValue(1, 1));\n\t\tassertNull(g.getValue(1, 2));\n\t\tassertEquals(\"a\",g.getValue(0,0));\n\t\tassertEquals(\"a\",g.getValue(0,1));\n\t\tassertEquals(\"a\",g.getValue(0,2));\n\t}", "\[email protected]\n\tpublic void testColumn() {\n\t\tfinal Grid<Integer> g = this.gf.create(2, 3); // two rows: [null,null,null] and [null,null,null]\n\t\tg.setColumn(1, 10); // two rows [null,10,null] and [null,10,null]\n\t\tassertNull(g.getValue(0, 0));\n\t\tassertNull(g.getValue(0, 2));\n\t\tassertNull(g.getValue(1, 0));\n\t\tassertNull(g.getValue(1, 2));\n\t\tassertEquals(10,g.getValue(0,1).intValue());\n\t\tassertEquals(10,g.getValue(1,1).intValue());\n\t}", "\[email protected]\n\tpublic void testDiagonal() { // two rows: [null,null,null] and [null,null,null]\n\t\tfinal Grid<Integer> g = this.gf.create(2, 3);\n\t\tg.setDiagonal(100); // two rows: [100,null,null] and [null,100,null]\n\t\tassertEquals(100,g.getValue(0, 0).intValue());\n\t\tassertNull(g.getValue(0, 1));\n\t\tassertNull(g.getValue(0, 2));\n\t\tassertNull(g.getValue(1, 0));\n\t\tassertEquals(100,g.getValue(1, 1).intValue());\n\t\tassertNull(g.getValue(1, 2));\n\t}", "\[email protected]\n\tpublic void testBorder() {\n\t\tfinal Grid<String> g = this.gf.create(3, 3); // tree rows: [null,null,null], [null,null,null] and [null,null,null]\n\t\tg.setBorder(\"b\"); // tree rows: [b,b,b], [b,null,b] and [b,b,b]\n\t\tassertEquals(\"b\",g.getValue(0, 0));\n\t\tassertEquals(\"b\",g.getValue(0, 1));\n\t\tassertEquals(\"b\",g.getValue(0, 2));\n\t\tassertEquals(\"b\",g.getValue(1, 0));\n\t\tassertNull(g.getValue(1, 1));\n\t\tassertEquals(\"b\",g.getValue(1, 2));\n\t\tassertEquals(\"b\",g.getValue(2, 0));\n\t\tassertEquals(\"b\",g.getValue(2, 1));\n\t\tassertEquals(\"b\",g.getValue(2, 2));\n\t}", "\[email protected]\n\tpublic void optionalTestIteratorOnlyNonNull() {\n\t\tfinal Grid<String> g = this.gf.create(3, 3);\n\t\tg.setColumn(0,\"a\");\n\t\tg.setColumn(2,\"b\");\n\t\tvar it = g.iterator(true);\n\t\tassertTrue(it.hasNext());\n\t\tassertEquals(new Cell<>(0,0,\"a\"),it.next());\n\t\tassertEquals(new Cell<>(0,2,\"b\"),it.next());\n\t\tassertEquals(new Cell<>(1,0,\"a\"),it.next());\n\t\tassertEquals(new Cell<>(1,2,\"b\"),it.next());\n\t\tassertEquals(new Cell<>(2,0,\"a\"),it.next());\n\t\tassertEquals(new Cell<>(2,2,\"b\"),it.next());\n\t\tassertFalse(it.hasNext());\n\t}", "\[email protected]\n\tpublic void optionalTestIteratorAlsoNull() {\n\t\tfinal Grid<String> g = this.gf.create(3, 3);\n\t\tg.setColumn(0,\"a\");\n\t\tg.setColumn(2,\"b\");\n\t\tvar it = g.iterator(false);\n\t\tassertTrue(it.hasNext());\n\t\tassertEquals(new Cell<>(0,0,\"a\"),it.next());\n\t\tassertEquals(new Cell<>(0,1,null),it.next());\n\t\tassertEquals(new Cell<>(0,2,\"b\"),it.next());\n\t\tassertEquals(new Cell<>(1,0,\"a\"),it.next());\n\t\tassertEquals(new Cell<>(1,1,null),it.next());\n\t\tassertEquals(new Cell<>(1,2,\"b\"),it.next());\n\t\tassertEquals(new Cell<>(2,0,\"a\"),it.next());\n\t\tassertEquals(new Cell<>(2,1,null),it.next());\n\t\tassertEquals(new Cell<>(2,2,\"b\"),it.next());\n\t\tassertFalse(it.hasNext());\n\t}" ] }, "content": "package a01b.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;\n\npublic class Test {\n\t\n\t/*\n\t * Implement the GridFactory interface as indicated in the initFactory method below.\n\t * Implement a factory concept for rectangular grids, where each cell contains a\n\t * value whose type is that of the type-variable <X> of the Grid interface.\n\t * The factory provides a grid that logically has all cells initially empty (null value).\n\t * The grid provides methods to set values on a row, a column, the diagonal, and the entire border.\n\t * It also provides a method to iterate over all cells, or only the non-empty ones.\n\t * The comment on the provided interfaces, and the test methods below constitute the necessary explanation of the\n\t * problem.\n\t *\n\t * The following are considered optional for the purpose of being able to correct the exercise, but still contribute to achieving\n\t * the totality of the score:\n\t * - implementation of the tests called optionalTestXYZ (relative to the Grid.iterator() method)\n\t * - the good design of the solution, in particular with minimization of repetitions\n\t *\n\t * Remove the comment from the initFactory method.\n\t *\n\t * Scoring indications:\n\t * - correctness of the mandatory part: 9 points\n\t * - correctness of the optional part: 4 points\n\t * - quality of the solution: 4 points\n\t *\n\t */\n\t\n\tprivate GridFactory gf = null;\n\t\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.gf = new GridFactoryImpl();\n\t}\n\t\n\t\n\[email protected]\n\tpublic void testBasic() {\n\t\tfinal Grid<String> g = this.gf.create(2, 3); // two rows [null,null,null] and [null,null,null]\n\t\tassertNull(g.getValue(0, 0));\n\t\tassertEquals(2,g.getRows());\n\t\tassertEquals(3,g.getColumns());\n\t}\n\t\n\[email protected]\n\tpublic void testRow() {\n\t\tfinal Grid<String> g = this.gf.create(2, 3); // two rows: [null,null,null] and [null,null,null]\n\t\tg.setRow(0, \"a\"); // two rows: [a,a,a] and [null,null,null]\n\t\tassertNull(g.getValue(1, 0));\n\t\tassertNull(g.getValue(1, 1));\n\t\tassertNull(g.getValue(1, 2));\n\t\tassertEquals(\"a\",g.getValue(0,0));\n\t\tassertEquals(\"a\",g.getValue(0,1));\n\t\tassertEquals(\"a\",g.getValue(0,2));\n\t}\n\t\n\[email protected]\n\tpublic void testColumn() {\n\t\tfinal Grid<Integer> g = this.gf.create(2, 3); // two rows: [null,null,null] and [null,null,null]\n\t\tg.setColumn(1, 10); // two rows [null,10,null] and [null,10,null]\n\t\tassertNull(g.getValue(0, 0));\n\t\tassertNull(g.getValue(0, 2));\n\t\tassertNull(g.getValue(1, 0));\n\t\tassertNull(g.getValue(1, 2));\n\t\tassertEquals(10,g.getValue(0,1).intValue());\n\t\tassertEquals(10,g.getValue(1,1).intValue());\n\t}\n\t\n\[email protected]\n\tpublic void testDiagonal() { // two rows: [null,null,null] and [null,null,null]\n\t\tfinal Grid<Integer> g = this.gf.create(2, 3);\n\t\tg.setDiagonal(100); // two rows: [100,null,null] and [null,100,null]\n\t\tassertEquals(100,g.getValue(0, 0).intValue());\n\t\tassertNull(g.getValue(0, 1));\n\t\tassertNull(g.getValue(0, 2));\n\t\tassertNull(g.getValue(1, 0));\n\t\tassertEquals(100,g.getValue(1, 1).intValue());\n\t\tassertNull(g.getValue(1, 2));\n\t}\n\t\n\[email protected]\n\tpublic void testBorder() {\n\t\tfinal Grid<String> g = this.gf.create(3, 3); // tree rows: [null,null,null], [null,null,null] and [null,null,null]\n\t\tg.setBorder(\"b\"); // tree rows: [b,b,b], [b,null,b] and [b,b,b]\n\t\tassertEquals(\"b\",g.getValue(0, 0));\n\t\tassertEquals(\"b\",g.getValue(0, 1));\n\t\tassertEquals(\"b\",g.getValue(0, 2));\n\t\tassertEquals(\"b\",g.getValue(1, 0));\n\t\tassertNull(g.getValue(1, 1));\n\t\tassertEquals(\"b\",g.getValue(1, 2));\n\t\tassertEquals(\"b\",g.getValue(2, 0));\n\t\tassertEquals(\"b\",g.getValue(2, 1));\n\t\tassertEquals(\"b\",g.getValue(2, 2));\n\t}\n\t\n\t// from here the optionals\n\t\n\[email protected]\n\tpublic void optionalTestIteratorOnlyNonNull() {\n\t\tfinal Grid<String> g = this.gf.create(3, 3);\n\t\tg.setColumn(0,\"a\");\n\t\tg.setColumn(2,\"b\");\n\t\tvar it = g.iterator(true);\n\t\tassertTrue(it.hasNext());\n\t\tassertEquals(new Cell<>(0,0,\"a\"),it.next());\n\t\tassertEquals(new Cell<>(0,2,\"b\"),it.next());\n\t\tassertEquals(new Cell<>(1,0,\"a\"),it.next());\n\t\tassertEquals(new Cell<>(1,2,\"b\"),it.next());\n\t\tassertEquals(new Cell<>(2,0,\"a\"),it.next());\n\t\tassertEquals(new Cell<>(2,2,\"b\"),it.next());\n\t\tassertFalse(it.hasNext());\n\t}\n\t\n\[email protected]\n\tpublic void optionalTestIteratorAlsoNull() {\n\t\tfinal Grid<String> g = this.gf.create(3, 3);\n\t\tg.setColumn(0,\"a\");\n\t\tg.setColumn(2,\"b\");\n\t\tvar it = g.iterator(false);\n\t\tassertTrue(it.hasNext());\n\t\tassertEquals(new Cell<>(0,0,\"a\"),it.next());\n\t\tassertEquals(new Cell<>(0,1,null),it.next());\n\t\tassertEquals(new Cell<>(0,2,\"b\"),it.next());\n\t\tassertEquals(new Cell<>(1,0,\"a\"),it.next());\n\t\tassertEquals(new Cell<>(1,1,null),it.next());\n\t\tassertEquals(new Cell<>(1,2,\"b\"),it.next());\n\t\tassertEquals(new Cell<>(2,0,\"a\"),it.next());\n\t\tassertEquals(new Cell<>(2,1,null),it.next());\n\t\tassertEquals(new Cell<>(2,2,\"b\"),it.next());\n\t\tassertFalse(it.hasNext());\n\t}\n}", "filename": "Test.java" }
2019
a04a
[ { "content": "package a04a.sol1;\n\nimport java.util.List;\n\n\npublic interface SequencesProvider<E> {\n\t\n\t\n\tList<E> nextSequence();\n\t\n\t\n\tboolean hasOtherSequences();\n\t\n\t\n\tvoid reset();\n\n\t\n}", "filename": "SequencesProvider.java" }, { "content": "package a04a.sol1;\n\n\npublic interface SequencesProvidersFactory {\n\t\n\t\n\t<E> SequencesProvider<E> iterative(E e);\n\t\n\t\n\t<E> SequencesProvider<E> alternating(E e1, E e2);\n\t\n\t\n\t<E> SequencesProvider<E> iterativeBounded(E e, int bound);\n\t\n\t\n\t<E> SequencesProvider<E> alternatingBounded(E e1, E e2, int bound);\n}", "filename": "SequencesProvidersFactory.java" }, { "content": "package a04a.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 a04a.sol1;\n\nimport java.util.Collections;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.function.Supplier;\nimport java.util.stream.Stream;\n\npublic class SequencesProvidersFactoryImpl implements SequencesProvidersFactory {\n\t\n\tprivate static <E> SequencesProvider<E> fromStream(Supplier<Stream<List<E>>> streamSupplier) {\n\t\treturn new SequencesProvider<E>() {\n\t\t\t\n\t\t\t{ reset(); } // non-static initializer\n\t\t\t\n\t\t\tprivate Iterator<List<E>> iterator;\n\n\t\t\t@Override\n\t\t\tpublic void reset() {\n\t\t\t\titerator = streamSupplier.get().iterator();\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic List<E> nextSequence() {\n\t\t\t\treturn iterator.next();\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic boolean hasOtherSequences() {\n\t\t\t\treturn iterator.hasNext();\n\t\t\t}\n\t\t\t\n\t\t};\n\t}\n\t\n\tprivate <E> Stream<List<E>> iterativeStream(E e){\n\t\treturn Stream.iterate(0, i->i+1).map(i -> Collections.nCopies(i, e));\n\t}\n\t\n\tprivate <E> Stream<List<E>> alternatingStream(E e1, E e2){\n\t\treturn Stream.iterate(0, i->i+1).flatMap(i -> Stream.of(Collections.nCopies(i, e1),Collections.nCopies(i, e2)));\n\t}\n\n\t@Override\n\tpublic <E> SequencesProvider<E> iterative(E e) {\n\t\treturn fromStream(()->iterativeStream(e));\n\t}\n\n\t@Override\n\tpublic <E> SequencesProvider<E> alternating(E e1, E e2) {\n\t\treturn fromStream(()->alternatingStream(e1,e2));\n\t}\n\n\t@Override\n\tpublic <E> SequencesProvider<E> iterativeBounded(E e, int bound) {\n\t\treturn fromStream(()->iterativeStream(e).limit(bound));\n\t}\n\n\t@Override\n\tpublic <E> SequencesProvider<E> alternatingBounded(E e1, E e2, int bound) {\n\t\treturn fromStream(()->alternatingStream(e1,e2).limit(bound));\n\t}\n\n}", "filename": "SequencesProvidersFactoryImpl.java" } ]
{ "components": { "imports": "package a04a.sol1;\n\nimport static org.junit.Assert.*;\n\nimport java.util.List;", "private_init": "\t/*\n\t * Implement the SequencesProvidersFactory interface as indicated in the initFactory method below.\n\t * Implement a factory concept for SequencesProvider, which in turn models a list iterator,\n\t * i.e. that gradually produces lists of elements.\n\t * \n\t * The comment to the provided interfaces, and the test methods below constitute the necessary \n\t * explanation of the problem.\n\t * \n\t * The following are considered optional for the purpose of being able to correct the exercise, \n\t * but still contribute to achieving the totality of the score:\n\t * - implementation of the tests called optionalTestXYZ (related to the SequencesProvider.reset method) \n\t * - the good design of the solution, in particular with minimization of repetitions\n\t * \n\t * Remove the comment from the initFactory method.\n\t * \n\t * Scoring indications:\n\t * - correctness of the mandatory part: 9 points\n\t * - correctness of the optional part: 4 points\n\t * - quality of the solution: 4 points\n\t * \n\t */\n\t\n\tprivate SequencesProvidersFactory factory = null;\n\t\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.factory = new SequencesProvidersFactoryImpl();\n\t}", "test_functions": [ "\[email protected]\n\tpublic void testIterative() {\n\t\t// iterator that produces (), (10), (10,10), (10,10,10),...\n\t\tfinal SequencesProvider<Integer> sp = this.factory.iterative(10);\n\t\tassertEquals(sp.nextSequence(),List.of());\n\t\tassertEquals(sp.nextSequence(),List.of(10));\n\t\tassertEquals(sp.nextSequence(),List.of(10,10));\n\t\tassertEquals(sp.nextSequence(),List.of(10,10,10));\n\t\tassertEquals(sp.nextSequence(),List.of(10,10,10,10));\n\t\tassertTrue(sp.hasOtherSequences());\n\t\tfor (int i=0; i<100; i++) {\n\t\t\tsp.nextSequence();\n\t\t}", "\[email protected]\n\tpublic void testAlternating() {\n\t\t// iterator that produces (), (), (a), (b), (a,a), (b,b),...\n\t\tfinal SequencesProvider<String> sp = this.factory.alternating(\"a\",\"b\");\n\t\tassertEquals(sp.nextSequence(),List.of());\n\t\tassertEquals(sp.nextSequence(),List.of());\n\t\tassertEquals(sp.nextSequence(),List.of(\"a\"));\n\t\tassertEquals(sp.nextSequence(),List.of(\"b\"));\n\t\tassertEquals(sp.nextSequence(),List.of(\"a\",\"a\"));\n\t\tassertEquals(sp.nextSequence(),List.of(\"b\",\"b\"));\n\t\tassertEquals(sp.nextSequence(),List.of(\"a\",\"a\",\"a\"));\n\t\tassertEquals(sp.nextSequence(),List.of(\"b\",\"b\",\"b\"));\n\t\tassertTrue(sp.hasOtherSequences());\n\t\tfor (int i=0; i<100; i++) {\n\t\t\tsp.nextSequence();\n\t\t}", "\[email protected]\n\tpublic void testIterativeBounded() {\n\t\t// like iterative, but only produces 4 lists\n\t\tfinal SequencesProvider<Integer> sp = this.factory.iterativeBounded(10,4);\n\t\tassertEquals(sp.nextSequence(),List.of());\n\t\tassertEquals(sp.nextSequence(),List.of(10));\n\t\tassertEquals(sp.nextSequence(),List.of(10,10));\n\t\tassertTrue(sp.hasOtherSequences());\n\t\tassertEquals(sp.nextSequence(),List.of(10,10,10));\n\t\tassertFalse(sp.hasOtherSequences());\n\t}", "\[email protected]\n\tpublic void testAlternatingBounded() {\n\t\t// like alternating, but only produces 7 lists\n\t\tfinal SequencesProvider<String> sp = this.factory.alternatingBounded(\"a\",\"b\",7);\n\t\tassertEquals(sp.nextSequence(),List.of());\n\t\tassertEquals(sp.nextSequence(),List.of());\n\t\tassertEquals(sp.nextSequence(),List.of(\"a\"));\n\t\tassertEquals(sp.nextSequence(),List.of(\"b\"));\n\t\tassertEquals(sp.nextSequence(),List.of(\"a\",\"a\"));\n\t\tassertEquals(sp.nextSequence(),List.of(\"b\",\"b\"));\n\t\tassertTrue(sp.hasOtherSequences());\n\t\tassertEquals(sp.nextSequence(),List.of(\"a\",\"a\",\"a\"));\n\t\tassertFalse(sp.hasOtherSequences());\n\t}", "\[email protected]\n\tpublic void optionalTestReset1() {\n\t\tfinal SequencesProvider<Integer> sp = this.factory.iterative(10);\n\t\tassertEquals(sp.nextSequence(),List.of());\n\t\tassertEquals(sp.nextSequence(),List.of(10));\n\t\tsp.reset();\n\t\tassertEquals(sp.nextSequence(),List.of());\n\t\tassertEquals(sp.nextSequence(),List.of(10));\n\t\tassertEquals(sp.nextSequence(),List.of(10,10));\t\t\n\t}", "\[email protected]\n\tpublic void optionalTestReset2() {\n\t\tfinal SequencesProvider<String> sp = this.factory.alternatingBounded(\"a\",\"b\",7);\n\t\tassertEquals(sp.nextSequence(),List.of());\n\t\tassertEquals(sp.nextSequence(),List.of());\n\t\tassertEquals(sp.nextSequence(),List.of(\"a\"));\n\t\tassertEquals(sp.nextSequence(),List.of(\"b\"));\n\t\tsp.reset();\n\t\tassertEquals(sp.nextSequence(),List.of());\n\t\tassertEquals(sp.nextSequence(),List.of());\n\t\tassertEquals(sp.nextSequence(),List.of(\"a\"));\n\t\tassertEquals(sp.nextSequence(),List.of(\"b\"));\n\t\tsp.reset();\n\t\tassertEquals(sp.nextSequence(),List.of());\n\t\tassertEquals(sp.nextSequence(),List.of());\n\t\tassertEquals(sp.nextSequence(),List.of(\"a\"));\n\t\tassertEquals(sp.nextSequence(),List.of(\"b\"));\n\t\tassertEquals(sp.nextSequence(),List.of(\"a\",\"a\"));\n\t\tassertEquals(sp.nextSequence(),List.of(\"b\",\"b\"));\n\t\tassertTrue(sp.hasOtherSequences());\n\t\tassertEquals(sp.nextSequence(),List.of(\"a\",\"a\",\"a\"));\n\t\tassertFalse(sp.hasOtherSequences());\n\t}" ] }, "content": "package a04a.sol1;\n\nimport static org.junit.Assert.*;\n\nimport java.util.List;\n\npublic class Test {\n\t\n\t/*\n\t * Implement the SequencesProvidersFactory interface as indicated in the initFactory method below.\n\t * Implement a factory concept for SequencesProvider, which in turn models a list iterator,\n\t * i.e. that gradually produces lists of elements.\n\t * \n\t * The comment to the provided interfaces, and the test methods below constitute the necessary \n\t * explanation of the problem.\n\t * \n\t * The following are considered optional for the purpose of being able to correct the exercise, \n\t * but still contribute to achieving the totality of the score:\n\t * - implementation of the tests called optionalTestXYZ (related to the SequencesProvider.reset method) \n\t * - the good design of the solution, in particular with minimization of repetitions\n\t * \n\t * Remove the comment from the initFactory method.\n\t * \n\t * Scoring indications:\n\t * - correctness of the mandatory part: 9 points\n\t * - correctness of the optional part: 4 points\n\t * - quality of the solution: 4 points\n\t * \n\t */\n\t\n\tprivate SequencesProvidersFactory factory = null;\n\t\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.factory = new SequencesProvidersFactoryImpl();\n\t}\n\n\[email protected]\n\tpublic void testIterative() {\n\t\t// iterator that produces (), (10), (10,10), (10,10,10),...\n\t\tfinal SequencesProvider<Integer> sp = this.factory.iterative(10);\n\t\tassertEquals(sp.nextSequence(),List.of());\n\t\tassertEquals(sp.nextSequence(),List.of(10));\n\t\tassertEquals(sp.nextSequence(),List.of(10,10));\n\t\tassertEquals(sp.nextSequence(),List.of(10,10,10));\n\t\tassertEquals(sp.nextSequence(),List.of(10,10,10,10));\n\t\tassertTrue(sp.hasOtherSequences());\n\t\tfor (int i=0; i<100; i++) {\n\t\t\tsp.nextSequence();\n\t\t}\n\t\tassertEquals(sp.nextSequence().size(),105);\n\t}\n\t\n\[email protected]\n\tpublic void testAlternating() {\n\t\t// iterator that produces (), (), (a), (b), (a,a), (b,b),...\n\t\tfinal SequencesProvider<String> sp = this.factory.alternating(\"a\",\"b\");\n\t\tassertEquals(sp.nextSequence(),List.of());\n\t\tassertEquals(sp.nextSequence(),List.of());\n\t\tassertEquals(sp.nextSequence(),List.of(\"a\"));\n\t\tassertEquals(sp.nextSequence(),List.of(\"b\"));\n\t\tassertEquals(sp.nextSequence(),List.of(\"a\",\"a\"));\n\t\tassertEquals(sp.nextSequence(),List.of(\"b\",\"b\"));\n\t\tassertEquals(sp.nextSequence(),List.of(\"a\",\"a\",\"a\"));\n\t\tassertEquals(sp.nextSequence(),List.of(\"b\",\"b\",\"b\"));\n\t\tassertTrue(sp.hasOtherSequences());\n\t\tfor (int i=0; i<100; i++) {\n\t\t\tsp.nextSequence();\n\t\t}\n\t\tassertEquals(sp.nextSequence().size(),54);\n\t}\n\t\n\[email protected]\n\tpublic void testIterativeBounded() {\n\t\t// like iterative, but only produces 4 lists\n\t\tfinal SequencesProvider<Integer> sp = this.factory.iterativeBounded(10,4);\n\t\tassertEquals(sp.nextSequence(),List.of());\n\t\tassertEquals(sp.nextSequence(),List.of(10));\n\t\tassertEquals(sp.nextSequence(),List.of(10,10));\n\t\tassertTrue(sp.hasOtherSequences());\n\t\tassertEquals(sp.nextSequence(),List.of(10,10,10));\n\t\tassertFalse(sp.hasOtherSequences());\n\t}\n\t\n\[email protected]\n\tpublic void testAlternatingBounded() {\n\t\t// like alternating, but only produces 7 lists\n\t\tfinal SequencesProvider<String> sp = this.factory.alternatingBounded(\"a\",\"b\",7);\n\t\tassertEquals(sp.nextSequence(),List.of());\n\t\tassertEquals(sp.nextSequence(),List.of());\n\t\tassertEquals(sp.nextSequence(),List.of(\"a\"));\n\t\tassertEquals(sp.nextSequence(),List.of(\"b\"));\n\t\tassertEquals(sp.nextSequence(),List.of(\"a\",\"a\"));\n\t\tassertEquals(sp.nextSequence(),List.of(\"b\",\"b\"));\n\t\tassertTrue(sp.hasOtherSequences());\n\t\tassertEquals(sp.nextSequence(),List.of(\"a\",\"a\",\"a\"));\n\t\tassertFalse(sp.hasOtherSequences());\n\t}\n\t\n\[email protected]\n\tpublic void optionalTestReset1() {\n\t\tfinal SequencesProvider<Integer> sp = this.factory.iterative(10);\n\t\tassertEquals(sp.nextSequence(),List.of());\n\t\tassertEquals(sp.nextSequence(),List.of(10));\n\t\tsp.reset();\n\t\tassertEquals(sp.nextSequence(),List.of());\n\t\tassertEquals(sp.nextSequence(),List.of(10));\n\t\tassertEquals(sp.nextSequence(),List.of(10,10));\t\t\n\t}\n\t\n\[email protected]\n\tpublic void optionalTestReset2() {\n\t\tfinal SequencesProvider<String> sp = this.factory.alternatingBounded(\"a\",\"b\",7);\n\t\tassertEquals(sp.nextSequence(),List.of());\n\t\tassertEquals(sp.nextSequence(),List.of());\n\t\tassertEquals(sp.nextSequence(),List.of(\"a\"));\n\t\tassertEquals(sp.nextSequence(),List.of(\"b\"));\n\t\tsp.reset();\n\t\tassertEquals(sp.nextSequence(),List.of());\n\t\tassertEquals(sp.nextSequence(),List.of());\n\t\tassertEquals(sp.nextSequence(),List.of(\"a\"));\n\t\tassertEquals(sp.nextSequence(),List.of(\"b\"));\n\t\tsp.reset();\n\t\tassertEquals(sp.nextSequence(),List.of());\n\t\tassertEquals(sp.nextSequence(),List.of());\n\t\tassertEquals(sp.nextSequence(),List.of(\"a\"));\n\t\tassertEquals(sp.nextSequence(),List.of(\"b\"));\n\t\tassertEquals(sp.nextSequence(),List.of(\"a\",\"a\"));\n\t\tassertEquals(sp.nextSequence(),List.of(\"b\",\"b\"));\n\t\tassertTrue(sp.hasOtherSequences());\n\t\tassertEquals(sp.nextSequence(),List.of(\"a\",\"a\",\"a\"));\n\t\tassertFalse(sp.hasOtherSequences());\n\t}\n\t\n}", "filename": "Test.java" }
2020
a04
[ { "content": "package a04.sol1;\n\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Optional;\n\n\npublic interface FunctionalStream<E> {\n\t\n\t\n\tinterface NextResult<E> {\n\t\tE getElement();\n\t\tFunctionalStream<E> getStream();\n\t}\n\t\n\t\n\t\n\tNextResult<E> next();\n\t\n\t\n\tList<E> toList(int size);\n\t\n\t\n\tIterator<E> toIterator();\n}", "filename": "FunctionalStream.java" }, { "content": "package a04.sol1;\n\nimport java.util.List;\nimport java.util.function.Function;\nimport java.util.function.UnaryOperator;\n\npublic interface FunctionalStreamFactory {\n\t\n\t\n\t\n\t<E> FunctionalStream<E> fromListRepetitive(List<E> list);\n\t\n\t\n\t<E> FunctionalStream<E> iterate(E initial, UnaryOperator<E> op);\n\t\n\t\n\t<A,B> FunctionalStream<B> map(FunctionalStream<A> fstream, Function<A,B> mapper);\n}", "filename": "FunctionalStreamFactory.java" }, { "content": "package a04.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 a04.sol1;\n\nimport java.util.Iterator;\nimport java.util.LinkedList;\nimport java.util.List;\n\n@FunctionalInterface\npublic interface FunctionalStreamTemplate<E> extends FunctionalStream<E> {\n\n\t@Override\n\tdefault List<E> toList(int size) {\n\t\tvar list = new LinkedList<E>();\n\t\tFunctionalStream<E> stream = this;\n\t\tfor (int i=0; i<size; i++) {\n\t\t\tvar next = stream.next();\n\t\t\tlist.add(next.getElement());\n\t\t\tstream = next.getStream();\n\t\t}\n\t\treturn list;\n\t}\n\t\n\t@Override\n\tdefault Iterator<E> toIterator() {\n\t\treturn new Iterator<>() {\n\n\t\t\tFunctionalStream<E> stream = FunctionalStreamTemplate.this;\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic boolean hasNext() {\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic E next() {\n\t\t\t\tvar v = stream.next().getElement();\n\t\t\t\tstream = stream.next().getStream();\n\t\t\t\treturn v;\n\t\t\t}\n\t\t};\n\t}\n\n\tpublic static class NextResultImpl<E> implements NextResult<E>{\n\t\tprivate final E element;\n\t\tprivate final FunctionalStream<E> nextIterator;\n\t\t\n\t\tpublic NextResultImpl(E element, FunctionalStream<E> nextIterator) {\n\t\t\tthis.element = element;\n\t\t\tthis.nextIterator = nextIterator;\n\t\t}\n\n\t\t@Override\n\t\tpublic E getElement() {\n\t\t\treturn this.element;\n\t\t}\n\n\t\t@Override\n\t\tpublic FunctionalStream<E> getStream() {\n\t\t\treturn this.nextIterator;\n\t\t}\n\t\t\n\t}\n\n}", "filename": "FunctionalStreamTemplate.java" }, { "content": "package a04.sol1;\n\nimport java.util.List;\nimport java.util.Optional;\nimport java.util.function.Function;\nimport java.util.function.UnaryOperator;\nimport static a04.sol1.FunctionalStreamTemplate.NextResultImpl;\n\npublic class FunctionalStreamFactoryImpl implements FunctionalStreamFactory {\n\t\n\t@Override\n\tpublic <E> FunctionalStream<E> iterate(E initial, UnaryOperator<E> op) {\n\t\treturn (FunctionalStreamTemplate<E>)\n\t\t\t\t() -> new NextResultImpl<>(initial, iterate(op.apply(initial),op));\n\t}\n\t\n\t@Override\n\tpublic <A, B> FunctionalStream<B> map(FunctionalStream<A> fstream, Function<A, B> mapper) {\n\t\treturn (FunctionalStreamTemplate<B>)\n\t\t\t\t() -> new NextResultImpl<>(mapper.apply(fstream.next().getElement()),map(fstream.next().getStream(),mapper));\n\n\t}\n\n\t@Override\n\tpublic <E> FunctionalStream<E> fromListRepetitive(List<E> list) {\n\t\treturn map(map(iterate(0,x->x+1), x -> x % list.size()), list::get);\n\t}\n}", "filename": "FunctionalStreamFactoryImpl.java" } ]
{ "components": { "imports": "package a04.sol1;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertTrue;\nimport java.util.List;", "private_init": "\t/*\n\t * Implement the FunctionalStreamFactory interface as indicated in the initFactory method\n\t * below. Creates a factory for FunctionalStream<E>, i.e.,\n\t * infinite streams of elements of type E.\n\t * \n\t * The comments on the provided interfaces, and the test methods below\n\t * constitute the necessary explanation of the problem.\n\t * \n\t * The following are considered optional for the purpose of being able to correct\n\t * the exercise, but still contribute to achieving the totality of the\n\t * score: \n\t * \n\t * - implementation of the tests called optionalTestXYZ (related to the\n\t * FunctionalStream.toIterator method) \n\t * \n\t * - the good design of the solution, in particular using succinct code and\n\t * that avoids repetitions\n\t * \n\t * Remove the comment from the initFactory method.\n\t * \n\t * Scoring indications: \n\t * \n\t * - correctness of the mandatory part: 10 points \n\t * \n\t * - correctness of the optional part: 4 points \n\t * \n\t * - quality of the solution: 3 points\n\t * \n\t */\n\n\tprivate FunctionalStreamFactory factory = null;\n\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.factory = new FunctionalStreamFactoryImpl();\n\t}", "test_functions": [ "\[email protected]\n\tpublic void testIterate() {\n\t\tvar str = this.factory.iterate(\"\",s -> s+\"a\"); // {\"\",\"a\",\"aa\",\"aaa\",...}", "\[email protected]\n\tpublic void testMap() {\n\t\tvar str0 = this.factory.iterate(0, s -> s+2); // {0,2,4,6,8,...}", "\[email protected]\n\tpublic void testListRepetitive() {\n\t\tvar str = this.factory.fromListRepetitive(List.of(\"a\",\"b\")); // {\"a\",\"b\",\"a\",\"b\",\"a\",...}", "\[email protected]\n\tpublic void optionalTestIterator() {\n\t\tvar str = this.factory.iterate(\"\",s -> s+\"a\");\n\t\tvar iterator = str.toIterator();\n\t\tassertEquals(\"\", iterator.next());\n\t\tassertTrue(iterator.hasNext());\n\t\tassertEquals(\"a\", iterator.next());\n\t\tassertTrue(iterator.hasNext());\n\t\tassertEquals(\"aa\", iterator.next());\n\t\tassertTrue(iterator.hasNext());\n\t\tassertEquals(\"aaa\", iterator.next());\n\t\tassertTrue(iterator.hasNext());\n\t}" ] }, "content": "package a04.sol1;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertTrue;\nimport java.util.List;\n\npublic class Test {\n\n\t/*\n\t * Implement the FunctionalStreamFactory interface as indicated in the initFactory method\n\t * below. Creates a factory for FunctionalStream<E>, i.e.,\n\t * infinite streams of elements of type E.\n\t * \n\t * The comments on the provided interfaces, and the test methods below\n\t * constitute the necessary explanation of the problem.\n\t * \n\t * The following are considered optional for the purpose of being able to correct\n\t * the exercise, but still contribute to achieving the totality of the\n\t * score: \n\t * \n\t * - implementation of the tests called optionalTestXYZ (related to the\n\t * FunctionalStream.toIterator method) \n\t * \n\t * - the good design of the solution, in particular using succinct code and\n\t * that avoids repetitions\n\t * \n\t * Remove the comment from the initFactory method.\n\t * \n\t * Scoring indications: \n\t * \n\t * - correctness of the mandatory part: 10 points \n\t * \n\t * - correctness of the optional part: 4 points \n\t * \n\t * - quality of the solution: 3 points\n\t * \n\t */\n\n\tprivate FunctionalStreamFactory factory = null;\n\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.factory = new FunctionalStreamFactoryImpl();\n\t}\n\n\n\[email protected]\n\tpublic void testIterate() {\n\t\tvar str = this.factory.iterate(\"\",s -> s+\"a\"); // {\"\",\"a\",\"aa\",\"aaa\",...}\n\t\tvar res = str.next();\n\t\tassertEquals(\"\", res.getElement());\n\t\tres = res.getStream().next();\n\t\tassertEquals(\"a\", res.getElement());\n\t\tres = res.getStream().next();\n\t\tassertEquals(\"aa\", res.getElement());\n\t\tvar list = res.getStream().toList(3); // list of the next 3 elements starting from here\n\t\tassertEquals(List.of(\"aaa\",\"aaaa\",\"aaaaa\"), list);\n\t}\n\t\n\[email protected]\n\tpublic void testMap() {\n\t\tvar str0 = this.factory.iterate(0, s -> s+2); // {0,2,4,6,8,...}\n\t\tvar str = this.factory.map(str0, i -> \"\"+i+i); // {\"00\",\"22\",\"44\",\"66\",\"88\",...}\n\t\tvar res = str.next();\n\t\tassertEquals(\"00\", res.getElement());\n\t\tres = res.getStream().next();\n\t\tassertEquals(\"22\", res.getElement());\n\t\tres = res.getStream().next();\n\t\tassertEquals(\"44\", res.getElement());\n\t\tvar list = res.getStream().toList(5);\n\t\tassertEquals(List.of(\"66\",\"88\",\"1010\",\"1212\",\"1414\"), list);\n\t}\n\t\n\[email protected]\n\tpublic void testListRepetitive() {\n\t\tvar str = this.factory.fromListRepetitive(List.of(\"a\",\"b\")); // {\"a\",\"b\",\"a\",\"b\",\"a\",...}\n\t\tvar res = str.next();\n\t\tassertEquals(\"a\", res.getElement());\n\t\tres = res.getStream().next();\n\t\tassertEquals(\"b\", res.getElement());\n\t\tres = res.getStream().next();\n\t\tassertEquals(\"a\", res.getElement());\n\t\tvar list = res.getStream().toList(3);\n\t\tassertEquals(List.of(\"b\",\"a\",\"b\"), list);\n\t}\n\t\n\[email protected]\n\tpublic void optionalTestIterator() {\n\t\tvar str = this.factory.iterate(\"\",s -> s+\"a\");\n\t\tvar iterator = str.toIterator();\n\t\tassertEquals(\"\", iterator.next());\n\t\tassertTrue(iterator.hasNext());\n\t\tassertEquals(\"a\", iterator.next());\n\t\tassertTrue(iterator.hasNext());\n\t\tassertEquals(\"aa\", iterator.next());\n\t\tassertTrue(iterator.hasNext());\n\t\tassertEquals(\"aaa\", iterator.next());\n\t\tassertTrue(iterator.hasNext());\n\t}\n\t\n\t\n}", "filename": "Test.java" }
2020
a03a
[ { "content": "package a03a.sol1;\n\nimport java.util.Set;\nimport java.util.function.BiPredicate;\nimport java.util.function.Function;\nimport java.util.function.Predicate;\n\n\npublic interface GroupingFactory {\n\t\n\t\n\t<G,V> Grouping<G,V> fromPairs(Iterable<Pair<G,V>> values);\n\t\n\t\n\t<V> Grouping<V,V> singletons(Set<V> values);\n\t\n\t\n\t<V> Grouping<V,V> withChampion(Set<V> values, BiPredicate<V,V> sameGroup, Predicate<V> champion);\n\t\n\t\n\t<G,V> Grouping<G,V> fromFunction(Set<V> values, Function<V,G> mapper);\n}", "filename": "GroupingFactory.java" }, { "content": "package a03a.sol1;\n\nimport java.util.Map;\nimport java.util.Optional;\nimport java.util.Set;\n\n\npublic interface Grouping<G,V> {\n\t\n\t\n\tSet<V> getValuesOfGroup(G group);\n\t\n\t\n\tSet<G> getGroups();\n\t\n\t\n\tOptional<G> getGroupOf(V data);\n\t\n\t\n\tMap<G,Set<V>> asMap();\n\t\n\t\n\tGrouping<G,V> combineGroups(G initial1, G initial2, G result);\n\n}", "filename": "Grouping.java" }, { "content": "package a03a.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 a03a.sol1;\n\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.function.BiPredicate;\nimport java.util.function.Function;\nimport java.util.function.Predicate;\n\npublic class GroupingFactoryImpl implements GroupingFactory {\n\n\t@Override\n\tpublic <G, V> Grouping<G, V> fromPairs(Iterable<Pair<G,V>> values) {\n\t\tMap<G,Set<V>> map = new HashMap<>();\n\t\tvalues.forEach(p -> map.merge(p.getX(), new HashSet<>(Set.of(p.getY())), (s1,s2) -> {s2.addAll(s1); return s2;}));\n\t\treturn new GroupingImpl<>(map);\n\t}\n\n\t@Override\n\tpublic <G, V> Grouping<G, V> fromFunction(Set<V> values, Function<V, G> mapper) {\n\t\treturn fromPairs(()->values.stream().map(v->new Pair<>(mapper.apply(v),v)).iterator());\n\t}\n\n\t@Override\n\tpublic <V> Grouping<V, V> singletons(Set<V> values) {\n\t\treturn withChampion(values, Object::equals, v->true );\n\t}\n\n\t@Override\n\tpublic <V> Grouping<V, V> withChampion(Set<V> values, BiPredicate<V, V> sameGroup, Predicate<V> champion) {\n\t\treturn fromFunction(values, v-> values.stream().filter(w -> sameGroup.test(v, w)).findAny().get());\n\t}\n\n}", "filename": "GroupingFactoryImpl.java" }, { "content": "package a03a.sol1;\n\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.Map;\nimport java.util.Optional;\nimport java.util.Set;\nimport java.util.stream.Collectors;\nimport java.util.stream.Stream;\n\npublic class GroupingImpl<G,V> implements Grouping<G, V> {\n\t\n\tprivate final Map<G,Set<V>> map;\n\t\n\tpublic GroupingImpl(Map<G, Set<V>> map) {\n\t\tthis.map = map;\n\t}\n\n\t@Override\n\tpublic Set<V> getValuesOfGroup(G group) {\n\t\treturn this.map.get(group);\n\t}\n\n\t@Override\n\tpublic Set<G> getGroups() {\n\t\treturn this.map.keySet();\n\t}\n\n\t@Override\n\tpublic Optional<G> getGroupOf(V data) {\n\t\treturn this.map.entrySet().stream().filter(e -> e.getValue().contains(data)).map(e -> e.getKey()).findAny();\n\t}\n\n\t@Override\n\tpublic Map<G, Set<V>> asMap() {\n\t\treturn Collections.unmodifiableMap(this.map);\n\t}\n\n\t@Override\n\tpublic Grouping<G, V> combineGroups(G initial1, G initial2, G result) {\n\t\tMap<G,Set<V>> map2 = new HashMap<>(this.map);\n\t\tvar s = new HashSet<>(map2.get(initial1));\n\t\ts.addAll(map2.get(initial2));\n\t\tmap2.put(result, s);\n\t\tmap2.remove(initial1);\n\t\tmap2.remove(initial2);\n\t\treturn new GroupingImpl<>(map2);\n\t}\n\t\n\t\n\n}", "filename": "GroupingImpl.java" } ]
{ "components": { "imports": "package a03a.sol1;\n\nimport static org.junit.Assert.*;\n\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Optional;\nimport java.util.Set;\nimport java.util.stream.Collectors;\nimport java.util.stream.IntStream;\nimport java.util.stream.Stream;", "private_init": "\t/*\n\t * Implement the GroupingFactory interface as indicated in the initFactory method below.\n\t * Creates a factory for Grouping<G,V>, i.e., strategies for grouping data (type V) into groups (type G)\n\t * -- a piece of data belongs to only one group.\n\t * \n\t * The comment on the provided interfaces, and the test methods below\n\t * constitute the necessary explanation of the problem.\n\t * \n\t * The following are considered optional for the purpose of being able to correct\n\t * the exercise, but still contribute to achieving the totality of the\n\t * score:\n\t * \n\t * - implementation of the tests called optionalTestXYZ (related to\n\t * Grouping.combineGroups and GroupingFactory.fromFunction)\n\t * \n\t * - the good design of the solution, in particular using succinct code and\n\t * that avoids repetitions\n\t * \n\t * Remove the comment from the initFactory method.\n\t * \n\t * Scoring indications:\n\t * \n\t * - correctness of the mandatory part: 10 points\n\t * \n\t * - correctness of the optional part: 4 points\n\t * \n\t * - quality of the solution: 3 points\n\t * \n\t */\n\n\tprivate GroupingFactory factory = null;\n\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.factory = new GroupingFactoryImpl();\n\t}\n\n\t// Even, odd, negative: an enum used in some tests\n\tenum IntegerType {\n\t\tEVEN, ODD, NEGATIVE\n\t};", "test_functions": [ "\[email protected]\n\tpublic void testFromPairs() {\n\t\t// memberships of numbers in [-3,8] to the three types\n\t\tSet<Pair<IntegerType, Integer>> pairs = Set.of(new Pair<>(IntegerType.EVEN, 0), new Pair<>(IntegerType.EVEN, 2),\n\t\t\t\tnew Pair<>(IntegerType.EVEN, 4), new Pair<>(IntegerType.EVEN, 6), new Pair<>(IntegerType.EVEN, 8),\n\t\t\t\tnew Pair<>(IntegerType.ODD, 1), new Pair<>(IntegerType.ODD, 3), new Pair<>(IntegerType.ODD, 5),\n\t\t\t\tnew Pair<>(IntegerType.ODD, 7), new Pair<>(IntegerType.NEGATIVE, -1),\n\t\t\t\tnew Pair<>(IntegerType.NEGATIVE, -2), new Pair<>(IntegerType.NEGATIVE, -3));\n\t\tGrouping<IntegerType, Integer> grouping = this.factory.fromPairs(pairs);\n\n\t\t// the three groups\n\t\tassertEquals(Set.of(IntegerType.EVEN, IntegerType.ODD, IntegerType.NEGATIVE), grouping.getGroups());\n\n\t\t// the group of 0,1, and -1... and 100 (which is not there)\n\t\tassertEquals(Optional.of(IntegerType.EVEN), grouping.getGroupOf(0));\n\t\tassertEquals(Optional.of(IntegerType.ODD), grouping.getGroupOf(1));\n\t\tassertEquals(Optional.of(IntegerType.NEGATIVE), grouping.getGroupOf(-1));\n\t\tassertEquals(Optional.empty(), grouping.getGroupOf(100));\n\n\t\t// the values of the \"even\" group\n\t\tassertEquals(Set.of(0, 2, 4, 6, 8), grouping.getValuesOfGroup(IntegerType.EVEN));\n\n\t\t// test on the map\n\t\tassertEquals(3, grouping.asMap().size());\n\t\tassertEquals(Set.of(0, 2, 4, 6, 8), grouping.asMap().get(IntegerType.EVEN));\n\t\tassertEquals(4, grouping.asMap().get(IntegerType.ODD).size());\n\t}", "\[email protected]\n\tpublic void testSingleton() {\n\t\t// \"a\",\"b\",\"c\" make three groups, one each\n\t\tGrouping<String, String> grouping = this.factory.singletons(Set.of(\"a\", \"b\", \"c\"));\n\n\t\t// the three groups\n\t\tassertEquals(Set.of(\"a\", \"b\", \"c\"), grouping.getGroups());\n\n\t\tassertEquals(Optional.of(\"a\"), grouping.getGroupOf(\"a\"));\n\t\tassertEquals(Optional.of(\"b\"), grouping.getGroupOf(\"b\"));\n\t\tassertEquals(Optional.of(\"c\"), grouping.getGroupOf(\"c\"));\n\t\tassertEquals(Optional.empty(), grouping.getGroupOf(\"d\"));\n\n\t\tassertEquals(Set.of(\"a\"), grouping.getValuesOfGroup(\"a\"));\n\t\tassertEquals(Set.of(\"b\"), grouping.getValuesOfGroup(\"b\"));\n\n\t\t// test on the map\n\t\tassertEquals(Set.of(\"a\"), grouping.asMap().get(\"a\"));\n\t\tassertEquals(3, grouping.asMap().size());\n\t}", "\[email protected]\n\tpublic void testWithChampion() {\n\t\t// we group the values from 0 to 99\n\t\tSet<Integer> range = IntStream.range(0, 100).mapToObj(i -> i).collect(Collectors.toSet());\n\t\t// we group the values with the same unit value (32 and 42 are together, having unit 2), i.e., with\n\t\t// same remainder of the division by 10\n\t\t// the representative of a group is the value without tens (the representative of the group with unit 2 is\n\t\t// therefore the number 2)\n\t\tGrouping<Integer, Integer> grouping = this.factory.withChampion(range, (i, j) -> i % 10 == j % 10, i -> i < 10);\n\n\t\t// so we form 10 groups, with these representatives\n\t\tassertEquals(Set.of(0, 1, 2, 3, 4, 5, 6, 7, 8, 9), grouping.getGroups());\n\n\t\tassertEquals(Optional.of(2), grouping.getGroupOf(22)); // the group of 22\n\t\tassertEquals(Optional.of(6), grouping.getGroupOf(56)); // ..\n\t\tassertEquals(Optional.of(0), grouping.getGroupOf(90));\n\t\tassertEquals(Optional.empty(), grouping.getGroupOf(100));\n\n\t\tassertEquals(Set.of(2, 12, 22, 32, 42, 52, 62, 72, 82, 92), grouping.getValuesOfGroup(2)); // the elements of group 2\n\t\tassertEquals(Set.of(6, 16, 26, 36, 46, 56, 66, 76, 86, 96), grouping.getValuesOfGroup(6)); // the elements of group 6\n\n\t\tassertEquals(Set.of(2, 12, 22, 32, 42, 52, 62, 72, 82, 92), grouping.asMap().get(2));\n\t\tassertEquals(10, grouping.asMap().size());\n\t}", "\[email protected]\n\tpublic void optionalTestFromFunction() {\n\t\t// The exact same example as testFromPairs, but with fromFunction\n\t\tSet<Integer> range = IntStream.range(-3, 9).mapToObj(i -> i).collect(Collectors.toSet());\n\t\t// The function associates each value with its group...\n\t\tGrouping<IntegerType, Integer> grouping = this.factory.fromFunction(range,\n\t\t\t\ti -> i < 0 ? IntegerType.NEGATIVE : \n\t\t\t\t\ti % 2 == 0 ? IntegerType.EVEN : IntegerType.ODD);\n\n\t\t// From here on as testFromPairs\n\t\t\n\t\t// the three groups\n\t\tassertEquals(Set.of(IntegerType.EVEN, IntegerType.ODD, IntegerType.NEGATIVE), grouping.getGroups());\n\n\t\t// the group of 0,1, and -1... and 100 (which is not there)\n\t\tassertEquals(Optional.of(IntegerType.EVEN), grouping.getGroupOf(0));\n\t\tassertEquals(Optional.of(IntegerType.ODD), grouping.getGroupOf(1));\n\t\tassertEquals(Optional.of(IntegerType.NEGATIVE), grouping.getGroupOf(-1));\n\t\tassertEquals(Optional.empty(), grouping.getGroupOf(100));\n\n\t\t// the values of the \"even\" group\n\t\tassertEquals(Set.of(0, 2, 4, 6, 8), grouping.getValuesOfGroup(IntegerType.EVEN));\n\n\t\t// test on the map\n\t\tassertEquals(3, grouping.asMap().size());\n\t\tassertEquals(Set.of(0, 2, 4, 6, 8), grouping.asMap().get(IntegerType.EVEN));\n\t\tassertEquals(4, grouping.asMap().get(IntegerType.ODD).size());\n\t}", "\[email protected]\n\tpublic void optionalTestCombineGroups() {\n\t\t// We take the grouping of testSingleton, and reunite the group a and b in a group ab\n\t\tGrouping<String, String> grouping = this.factory.singletons(Set.of(\"a\", \"b\", \"c\")).combineGroups(\"a\", \"b\",\"ab\");\n\n\t\tassertEquals(Set.of(\"ab\", \"c\"), grouping.getGroups());\n\n\t\tassertEquals(Optional.of(\"ab\"), grouping.getGroupOf(\"a\"));\n\t\tassertEquals(Optional.of(\"ab\"), grouping.getGroupOf(\"b\"));\n\t\tassertEquals(Optional.of(\"c\"), grouping.getGroupOf(\"c\"));\n\n\t\tassertEquals(Set.of(\"a\", \"b\"), grouping.getValuesOfGroup(\"ab\"));\n\t\tassertEquals(Set.of(\"c\"), grouping.getValuesOfGroup(\"c\"));\n\n\t\tassertEquals(Set.of(\"a\", \"b\"), grouping.asMap().get(\"ab\"));\n\t}" ] }, "content": "package a03a.sol1;\n\nimport static org.junit.Assert.*;\n\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Optional;\nimport java.util.Set;\nimport java.util.stream.Collectors;\nimport java.util.stream.IntStream;\nimport java.util.stream.Stream;\n\npublic class Test {\n\n\t/*\n\t * Implement the GroupingFactory interface as indicated in the initFactory method below.\n\t * Creates a factory for Grouping<G,V>, i.e., strategies for grouping data (type V) into groups (type G)\n\t * -- a piece of data belongs to only one group.\n\t * \n\t * The comment on the provided interfaces, and the test methods below\n\t * constitute the necessary explanation of the problem.\n\t * \n\t * The following are considered optional for the purpose of being able to correct\n\t * the exercise, but still contribute to achieving the totality of the\n\t * score:\n\t * \n\t * - implementation of the tests called optionalTestXYZ (related to\n\t * Grouping.combineGroups and GroupingFactory.fromFunction)\n\t * \n\t * - the good design of the solution, in particular using succinct code and\n\t * that avoids repetitions\n\t * \n\t * Remove the comment from the initFactory method.\n\t * \n\t * Scoring indications:\n\t * \n\t * - correctness of the mandatory part: 10 points\n\t * \n\t * - correctness of the optional part: 4 points\n\t * \n\t * - quality of the solution: 3 points\n\t * \n\t */\n\n\tprivate GroupingFactory factory = null;\n\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.factory = new GroupingFactoryImpl();\n\t}\n\n\t// Even, odd, negative: an enum used in some tests\n\tenum IntegerType {\n\t\tEVEN, ODD, NEGATIVE\n\t};\n\n\[email protected]\n\tpublic void testFromPairs() {\n\t\t// memberships of numbers in [-3,8] to the three types\n\t\tSet<Pair<IntegerType, Integer>> pairs = Set.of(new Pair<>(IntegerType.EVEN, 0), new Pair<>(IntegerType.EVEN, 2),\n\t\t\t\tnew Pair<>(IntegerType.EVEN, 4), new Pair<>(IntegerType.EVEN, 6), new Pair<>(IntegerType.EVEN, 8),\n\t\t\t\tnew Pair<>(IntegerType.ODD, 1), new Pair<>(IntegerType.ODD, 3), new Pair<>(IntegerType.ODD, 5),\n\t\t\t\tnew Pair<>(IntegerType.ODD, 7), new Pair<>(IntegerType.NEGATIVE, -1),\n\t\t\t\tnew Pair<>(IntegerType.NEGATIVE, -2), new Pair<>(IntegerType.NEGATIVE, -3));\n\t\tGrouping<IntegerType, Integer> grouping = this.factory.fromPairs(pairs);\n\n\t\t// the three groups\n\t\tassertEquals(Set.of(IntegerType.EVEN, IntegerType.ODD, IntegerType.NEGATIVE), grouping.getGroups());\n\n\t\t// the group of 0,1, and -1... and 100 (which is not there)\n\t\tassertEquals(Optional.of(IntegerType.EVEN), grouping.getGroupOf(0));\n\t\tassertEquals(Optional.of(IntegerType.ODD), grouping.getGroupOf(1));\n\t\tassertEquals(Optional.of(IntegerType.NEGATIVE), grouping.getGroupOf(-1));\n\t\tassertEquals(Optional.empty(), grouping.getGroupOf(100));\n\n\t\t// the values of the \"even\" group\n\t\tassertEquals(Set.of(0, 2, 4, 6, 8), grouping.getValuesOfGroup(IntegerType.EVEN));\n\n\t\t// test on the map\n\t\tassertEquals(3, grouping.asMap().size());\n\t\tassertEquals(Set.of(0, 2, 4, 6, 8), grouping.asMap().get(IntegerType.EVEN));\n\t\tassertEquals(4, grouping.asMap().get(IntegerType.ODD).size());\n\t}\n\n\[email protected]\n\tpublic void testSingleton() {\n\t\t// \"a\",\"b\",\"c\" make three groups, one each\n\t\tGrouping<String, String> grouping = this.factory.singletons(Set.of(\"a\", \"b\", \"c\"));\n\n\t\t// the three groups\n\t\tassertEquals(Set.of(\"a\", \"b\", \"c\"), grouping.getGroups());\n\n\t\tassertEquals(Optional.of(\"a\"), grouping.getGroupOf(\"a\"));\n\t\tassertEquals(Optional.of(\"b\"), grouping.getGroupOf(\"b\"));\n\t\tassertEquals(Optional.of(\"c\"), grouping.getGroupOf(\"c\"));\n\t\tassertEquals(Optional.empty(), grouping.getGroupOf(\"d\"));\n\n\t\tassertEquals(Set.of(\"a\"), grouping.getValuesOfGroup(\"a\"));\n\t\tassertEquals(Set.of(\"b\"), grouping.getValuesOfGroup(\"b\"));\n\n\t\t// test on the map\n\t\tassertEquals(Set.of(\"a\"), grouping.asMap().get(\"a\"));\n\t\tassertEquals(3, grouping.asMap().size());\n\t}\n\n\[email protected]\n\tpublic void testWithChampion() {\n\t\t// we group the values from 0 to 99\n\t\tSet<Integer> range = IntStream.range(0, 100).mapToObj(i -> i).collect(Collectors.toSet());\n\t\t// we group the values with the same unit value (32 and 42 are together, having unit 2), i.e., with\n\t\t// same remainder of the division by 10\n\t\t// the representative of a group is the value without tens (the representative of the group with unit 2 is\n\t\t// therefore the number 2)\n\t\tGrouping<Integer, Integer> grouping = this.factory.withChampion(range, (i, j) -> i % 10 == j % 10, i -> i < 10);\n\n\t\t// so we form 10 groups, with these representatives\n\t\tassertEquals(Set.of(0, 1, 2, 3, 4, 5, 6, 7, 8, 9), grouping.getGroups());\n\n\t\tassertEquals(Optional.of(2), grouping.getGroupOf(22)); // the group of 22\n\t\tassertEquals(Optional.of(6), grouping.getGroupOf(56)); // ..\n\t\tassertEquals(Optional.of(0), grouping.getGroupOf(90));\n\t\tassertEquals(Optional.empty(), grouping.getGroupOf(100));\n\n\t\tassertEquals(Set.of(2, 12, 22, 32, 42, 52, 62, 72, 82, 92), grouping.getValuesOfGroup(2)); // the elements of group 2\n\t\tassertEquals(Set.of(6, 16, 26, 36, 46, 56, 66, 76, 86, 96), grouping.getValuesOfGroup(6)); // the elements of group 6\n\n\t\tassertEquals(Set.of(2, 12, 22, 32, 42, 52, 62, 72, 82, 92), grouping.asMap().get(2));\n\t\tassertEquals(10, grouping.asMap().size());\n\t}\n\n\[email protected]\n\tpublic void optionalTestFromFunction() {\n\t\t// The exact same example as testFromPairs, but with fromFunction\n\t\tSet<Integer> range = IntStream.range(-3, 9).mapToObj(i -> i).collect(Collectors.toSet());\n\t\t// The function associates each value with its group...\n\t\tGrouping<IntegerType, Integer> grouping = this.factory.fromFunction(range,\n\t\t\t\ti -> i < 0 ? IntegerType.NEGATIVE : \n\t\t\t\t\ti % 2 == 0 ? IntegerType.EVEN : IntegerType.ODD);\n\n\t\t// From here on as testFromPairs\n\t\t\n\t\t// the three groups\n\t\tassertEquals(Set.of(IntegerType.EVEN, IntegerType.ODD, IntegerType.NEGATIVE), grouping.getGroups());\n\n\t\t// the group of 0,1, and -1... and 100 (which is not there)\n\t\tassertEquals(Optional.of(IntegerType.EVEN), grouping.getGroupOf(0));\n\t\tassertEquals(Optional.of(IntegerType.ODD), grouping.getGroupOf(1));\n\t\tassertEquals(Optional.of(IntegerType.NEGATIVE), grouping.getGroupOf(-1));\n\t\tassertEquals(Optional.empty(), grouping.getGroupOf(100));\n\n\t\t// the values of the \"even\" group\n\t\tassertEquals(Set.of(0, 2, 4, 6, 8), grouping.getValuesOfGroup(IntegerType.EVEN));\n\n\t\t// test on the map\n\t\tassertEquals(3, grouping.asMap().size());\n\t\tassertEquals(Set.of(0, 2, 4, 6, 8), grouping.asMap().get(IntegerType.EVEN));\n\t\tassertEquals(4, grouping.asMap().get(IntegerType.ODD).size());\n\t}\n\n\[email protected]\n\tpublic void optionalTestCombineGroups() {\n\t\t// We take the grouping of testSingleton, and reunite the group a and b in a group ab\n\t\tGrouping<String, String> grouping = this.factory.singletons(Set.of(\"a\", \"b\", \"c\")).combineGroups(\"a\", \"b\",\"ab\");\n\n\t\tassertEquals(Set.of(\"ab\", \"c\"), grouping.getGroups());\n\n\t\tassertEquals(Optional.of(\"ab\"), grouping.getGroupOf(\"a\"));\n\t\tassertEquals(Optional.of(\"ab\"), grouping.getGroupOf(\"b\"));\n\t\tassertEquals(Optional.of(\"c\"), grouping.getGroupOf(\"c\"));\n\n\t\tassertEquals(Set.of(\"a\", \"b\"), grouping.getValuesOfGroup(\"ab\"));\n\t\tassertEquals(Set.of(\"c\"), grouping.getValuesOfGroup(\"c\"));\n\n\t\tassertEquals(Set.of(\"a\", \"b\"), grouping.asMap().get(\"ab\"));\n\t}\n}", "filename": "Test.java" }
2020
a02b
[ { "content": "package a02b.sol1;\n\nimport java.util.function.Predicate;\n\n\npublic interface PatternExtractorFactory {\n\t\n\t\n\tPatternExtractor<Integer,Integer> countConsecutiveZeros();\n\t\n\t\n\tPatternExtractor<Double,Double> averageConsecutiveInRange(double min, double max);\n\t\n\t\n\tPatternExtractor<String,String> concatenateBySeparator(String separator);\n\t\n\t\n\tPatternExtractor<String,Double> sumNumericStrings();\n\n}", "filename": "PatternExtractorFactory.java" }, { "content": "package a02b.sol1;\n\nimport java.util.Iterator;\nimport java.util.List;\n\n\npublic interface PatternExtractor<X,Y>{\n\t\n\t\n\tList<Y> extract(List<X> input);\n}", "filename": "PatternExtractor.java" }, { "content": "package 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 a02b.sol1;\n\nimport java.util.ArrayList;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Optional;\nimport java.util.function.BiPredicate;\nimport java.util.function.Function;\nimport java.util.function.Predicate;\nimport java.util.stream.Stream;\n\npublic class PatternExtractorFactoryImpl implements PatternExtractorFactory {\n\n\t/**\n\t * Typical strategy-based technique: all patternextractors can be obtained by this default one,\n\t * by proper functional arguments\n\t */\n\t\n\tprivate static class PatternExtractorImpl<X,Y> implements PatternExtractor<X,Y> {\n\n\t\tprivate final Predicate<X> predicate;\n\t\tprivate final Function<List<X>, Y> mapper;\n\t\t\n\t\tpublic PatternExtractorImpl(Predicate<X> predicate, Function<List<X>, Y> mapper) {\n\t\t\tsuper();\n\t\t\tthis.predicate = predicate;\n\t\t\tthis.mapper = mapper;\n\t\t}\n\n\t\t@Override\n\t\tpublic List<Y> extract(List<X> list) {\n\t\t\tList<X> accumulator = new ArrayList<>();\n\t\t\tfinal List<Y> output = new ArrayList<>();\n\t\t\tfor (final var x: list){\n\t\t\t\tif (predicate.test(x)) {\n\t\t\t\t\taccumulator.add(x);\n\t\t\t\t} else if (!accumulator.isEmpty()) {\n\t\t\t\t\toutput.add(this.mapper.apply(accumulator));\n\t\t\t\t\taccumulator = new ArrayList<>();\n\t\t\t\t} \n\t\t\t}\n\t\t\tif (!accumulator.isEmpty()) {\n\t\t\t\toutput.add(this.mapper.apply(accumulator));\n\t\t\t}\n\t\t\treturn output;\n\t\t}\n\t}\n\n\t@Override\n\tpublic PatternExtractor<Integer, Integer> countConsecutiveZeros() {\n\t\treturn new PatternExtractorImpl<>( x -> x==0, List::size);\n\t}\n\n\t@Override\n\tpublic PatternExtractor<Double, Double> averageConsecutiveInRange(double min, double max) {\n\t\treturn new PatternExtractorImpl<>( x -> x>=min && x<=max, list -> list.stream().mapToDouble(d->d).average().getAsDouble());\n\t}\n\n\t@Override\n\tpublic PatternExtractor<String, String> concatenateBySeparator(String separator) {\n\t\treturn new PatternExtractorImpl<>( x -> !x.equals(separator), list -> list.stream().reduce((x,y)->x+y).get());\n\t}\n\t\n\tprivate boolean isNumeric(String s) {\n\t\ttry {\n\t\t\tDouble.parseDouble(s);\n\t\t\treturn true;\n\t\t} catch (Exception e) {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t@Override\n\tpublic PatternExtractor<String, Double> sumNumericStrings() {\n\t\treturn new PatternExtractorImpl<>(this::isNumeric, list -> list.stream().map(Double::parseDouble).reduce((x,y)->x+y).get());\n\t}\n\n\t\n}", "filename": "PatternExtractorFactoryImpl.java" } ]
{ "components": { "imports": "package a02b.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;\n\n/**\n * Please refer to the documentation of the PatternExtractorFactory interface, which models\n * a factory for PatternExtractor, which in turn models a transformer from lists to\n * lists, which works by isolating parts of the list in the input whose values have certain characteristics\n * and consequently producing summary information in output for each of these parts.\n * \n * The comments on the provided interfaces, and the test methods below constitute the necessary\n * explanation of the problem.\n * \n * The following are considered optional for the purpose of being able to correct\n * the exercise, but still contribute to achieving the totality of the\n * score:\n * - implementation of optional tests (named 'optionalTestXYZ', i.e. those related to\n * PatternExtractorFactory.sumNumericStrings)\n * - conciseness of the code and removal of all repetitions\n *\n * Remove the comment from the init method.\n * \n * Scoring indications:\n * - correctness of the mandatory part: 10 points\n * - correctness of the optional part: 4 points\n * - quality of the solution: 3 points\n * \n */", "private_init": "\tprivate PatternExtractorFactory factory;\n\n\[email protected]\n\tpublic void init() {\n\t\tthis.factory = new PatternExtractorFactoryImpl();\n\t}", "test_functions": [ "\[email protected]\n\tpublic void testConsecutiveZeros() {\n\t\tvar pe = this.factory.countConsecutiveZeros();\n\t\tassertEquals(List.of(2,3), pe.extract(List.of(1,0,0,2,3,0,0,0,4)));\n\t\t\n\t}", "\[email protected]\n\tpublic void testAverage() {\n\t\tvar pe = this.factory.averageConsecutiveInRange(0.0, 10.0);\n\t\tassertEquals(List.of(5.5,2.0), pe.extract(List.of(5.0,6.0,-1.0,1.0,2.0,3.0,-4.0,-5.0)));\n\t}", "\[email protected]\n\tpublic void testConcatenate() {\n\t\tvar pe = this.factory.concatenateBySeparator(\":\");\n\t\tassertEquals(List.of(\"ab\",\"cde\",\"f\"), pe.extract(List.of(\"a\",\"b\",\":\",\"c\",\"d\",\"e\",\":\",\":\",\"f\")));\n\t}", "\[email protected]\n\tpublic void optionalTestNumericStrings() {\n\t\tvar pe = this.factory.sumNumericStrings();\n\t\tassertEquals(List.of(30.0,30.0,150.0), pe.extract(List.of(\"10\",\"20\",\"a\",\"30\",\"d\",\"40\",\"50\",\"60\")));\n\t}" ] }, "content": "package a02b.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;\n\n/**\n * Please refer to the documentation of the PatternExtractorFactory interface, which models\n * a factory for PatternExtractor, which in turn models a transformer from lists to\n * lists, which works by isolating parts of the list in the input whose values have certain characteristics\n * and consequently producing summary information in output for each of these parts.\n * \n * The comments on the provided interfaces, and the test methods below constitute the necessary\n * explanation of the problem.\n * \n * The following are considered optional for the purpose of being able to correct\n * the exercise, but still contribute to achieving the totality of the\n * score:\n * - implementation of optional tests (named 'optionalTestXYZ', i.e. those related to\n * PatternExtractorFactory.sumNumericStrings)\n * - conciseness of the code and removal of all repetitions\n *\n * Remove the comment from the init method.\n * \n * Scoring indications:\n * - correctness of the mandatory part: 10 points\n * - correctness of the optional part: 4 points\n * - quality of the solution: 3 points\n * \n */\n\npublic class Test {\n\n\tprivate PatternExtractorFactory factory;\n\n\[email protected]\n\tpublic void init() {\n\t\tthis.factory = new PatternExtractorFactoryImpl();\n\t}\n\n\[email protected]\n\tpublic void testConsecutiveZeros() {\n\t\tvar pe = this.factory.countConsecutiveZeros();\n\t\tassertEquals(List.of(2,3), pe.extract(List.of(1,0,0,2,3,0,0,0,4)));\n\t\t\n\t}\n\t\n\[email protected]\n\tpublic void testAverage() {\n\t\tvar pe = this.factory.averageConsecutiveInRange(0.0, 10.0);\n\t\tassertEquals(List.of(5.5,2.0), pe.extract(List.of(5.0,6.0,-1.0,1.0,2.0,3.0,-4.0,-5.0)));\n\t}\n\t\n\[email protected]\n\tpublic void testConcatenate() {\n\t\tvar pe = this.factory.concatenateBySeparator(\":\");\n\t\tassertEquals(List.of(\"ab\",\"cde\",\"f\"), pe.extract(List.of(\"a\",\"b\",\":\",\"c\",\"d\",\"e\",\":\",\":\",\"f\")));\n\t}\n\t\n\[email protected]\n\tpublic void optionalTestNumericStrings() {\n\t\tvar pe = this.factory.sumNumericStrings();\n\t\tassertEquals(List.of(30.0,30.0,150.0), pe.extract(List.of(\"10\",\"20\",\"a\",\"30\",\"d\",\"40\",\"50\",\"60\")));\n\t}\n}", "filename": "Test.java" }
2020
a06
[ { "content": "package a06.sol1;\n\nimport java.util.function.BinaryOperator;\nimport java.util.function.Function;\n\n\npublic interface BTree<L> {\n\n\t\n\tboolean isLeaf();\n\t\n\t\n\tL getLeaf();\n\t\n\t\n\tBTree<L> getLeft();\n\t\n\t\n\tBTree<L> getRight();\n\t\n\t\n\tL compute(BinaryOperator<L> function);\n\t\n\t\n\t<O> BTree<O> map(Function<L,O> mapper);\n\t\n\t\n\tBTree<L> symmetric();\n}", "filename": "BTree.java" }, { "content": "package a06.sol1;\n\nimport java.util.List;\nimport java.util.function.BiFunction;\n\npublic interface BTreeFactory {\n\t\n\t\n\t<L> BTree<L> leaf(L value);\n\t\n\t\n\t<L> BTree<L> compose(BTree<L> left, BTree<L> right);\n\t\n\t\n\t<L> BTree<L> nested(List<L> leafs);\n}", "filename": "BTreeFactory.java" }, { "content": "package a06.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 a06.sol1;\n\nimport java.util.NoSuchElementException;\nimport java.util.function.BinaryOperator;\nimport java.util.function.Function;\n\nclass Cons<L> implements BTree<L>{\n\tprivate final BTree<L> left;\n\tprivate final BTree<L> right;\n\t\n\tpublic Cons(BTree<L> left, BTree<L> right) {\n\t\tthis.left = left;\n\t\tthis.right = right;\n\t}\n\t\n\t@Override\n\tpublic boolean isLeaf() {\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic L getLeaf() {\n\t\tthrow new NoSuchElementException();\n\t}\n\n\t@Override\n\tpublic BTree<L> getLeft() {\n\t\treturn left;\n\t}\n\n\t@Override\n\tpublic BTree<L> getRight() {\n\t\treturn right;\n\t}\n\n\t@Override\n\tpublic L compute(BinaryOperator<L> function) {\n\t\treturn function.apply(left.compute(function),right.compute(function));\n\t}\n\n\t@Override\n\tpublic <O> BTree<O> map(Function<L,O> mapper) {\n\t\treturn new Cons<>(left.map(mapper),right.map(mapper));\n\t}\n\n\t@Override\n\tpublic BTree<L> symmetric() {\n\t\treturn new Cons<>(right.symmetric(),left.symmetric());\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"(\" + left + \", \" + right + \")\";\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 + ((left == null) ? 0 : left.hashCode());\n\t\tresult = prime * result + ((right == null) ? 0 : right.hashCode());\n\t\treturn result;\n\t}\n\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\tCons other = (Cons) obj;\n\t\tif (left == null) {\n\t\t\tif (other.left != null)\n\t\t\t\treturn false;\n\t\t} else if (!left.equals(other.left))\n\t\t\treturn false;\n\t\tif (right == null) {\n\t\t\tif (other.right != null)\n\t\t\t\treturn false;\n\t\t} else if (!right.equals(other.right))\n\t\t\treturn false;\n\t\treturn true;\n\t}\n\n\t\n}", "filename": "Cons.java" }, { "content": "package a06.sol1;\n\nimport java.util.List;\n\npublic class BTreeFactoryImpl implements BTreeFactory {\n\t\n\t@Override\n\tpublic <L> BTree<L> leaf(L value) {\n\t\treturn new Leaf<>(value);\t\t\t\n\t}\n\n\t@Override\n\tpublic <L> BTree<L> compose(BTree<L> left, BTree<L> right) {\n\t\treturn new Cons<>(left,right);\n\t}\n\n\t@Override\n\tpublic <L> BTree<L> nested(List<L> leafs) {\n\t\tvar iterator = leafs.iterator();\n\t\tBTree<L> tree = leaf(iterator.next());\n\t\twhile (iterator.hasNext()) {\n\t\t\ttree = compose(leaf(iterator.next()),tree);\n\t\t}\n\t\treturn tree;\n\t}\n\n}", "filename": "BTreeFactoryImpl.java" }, { "content": "package a06.sol1;\n\nimport java.util.NoSuchElementException;\nimport java.util.function.BinaryOperator;\nimport java.util.function.Function;\n\nclass Leaf<L> implements BTree<L>{\n\tprivate L value;\n\t\n\tpublic Leaf(L value) {\n\t\tthis.value = value;\n\t}\n\n\t@Override\n\tpublic boolean isLeaf() {\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic L getLeaf() {\n\t\treturn this.value;\n\t}\n\n\t@Override\n\tpublic BTree<L> getLeft() {\n\t\tthrow new NoSuchElementException();\n\t}\n\n\t@Override\n\tpublic BTree<L> getRight() {\n\t\tthrow new NoSuchElementException();\n\t}\n\n\t@Override\n\tpublic L compute(BinaryOperator<L> function) {\n\t\treturn this.value;\n\t}\n\n\t@Override\n\tpublic <O> BTree<O> map(Function<L,O> mapper) {\n\t\treturn new Leaf<>(mapper.apply(this.value));\n\t}\n\t\n\t@Override\n\tpublic BTree<L> symmetric() {\n\t\treturn this;\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 + ((value == null) ? 0 : value.hashCode());\n\t\treturn result;\n\t}\n\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\tLeaf other = (Leaf) obj;\n\t\tif (value == null) {\n\t\t\tif (other.value != null)\n\t\t\t\treturn false;\n\t\t} else if (!value.equals(other.value))\n\t\t\treturn false;\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"'\" + value;\n\t}\t\n}", "filename": "Leaf.java" } ]
{ "components": { "imports": "package a06.sol1;\n\nimport static org.junit.Assert.*;\n\nimport java.util.List;\nimport java.util.NoSuchElementException;", "private_init": "\t/*\n\t * Implement the BTreeFactory interface as indicated in the\n\t * initFactory method below. Create a factory for BTrees, i.e.,\n\t * binary trees where the values present are in the leaves (LEAF).\n\t * For example, a tree could have a root and two leaves with values 1 and 2,\n\t * also indicated briefly with (1,2), another could have a root,\n\t * a left child consisting of the tree (1,2) and a right child with only\n\t * the leaf 3, and we would indicate it with ((1,2),3)\n\t *\n\t * The comment on the provided interfaces, and the test methods below\n\t * constitute the necessary explanation of the problem.\n\t *\n\t * The following are considered optional for the purpose of being able to correct\n\t * the exercise, but still contribute to achieving the totality of the\n\t * score:\n\t *\n\t * - implementation of the last test, called optionalTestXYZ (related to the\n\t * method BTreeFactory.nested)\n\t *\n\t * - the good design of the solution, in particular using succinct code\n\t *\n\t * Remove the comment from the initFactory method.\n\t *\n\t * Scoring indications:\n\t *\n\t * - correctness of the mandatory part: 10 points\n\t *\n\t * - correctness of the optional part: 4 points\n\t *\n\t * - quality of the solution: 3 points\n\t *\n\t */\n\n\tprivate BTreeFactory factory = null;\n\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.factory = new BTreeFactoryImpl();\n\t}", "test_functions": [ "\[email protected]\n\tpublic void testSimple() {\n\t\tvar left = this.factory.leaf(1);\n\t\tvar right = this.factory.leaf(2);\n\t\tvar tree = this.factory.compose(left, right); // the tree (1,2)\n\t\t\n\t\t// from here, simple getters\n\t\tassertTrue(left.isLeaf());\n\t\tassertTrue(right.isLeaf());\n\t\tassertFalse(tree.isLeaf());\n\t\t\n\t\tassertEquals(Integer.valueOf(1), left.getLeaf());\n\t\tassertEquals(Integer.valueOf(2), right.getLeaf());\n\t\t\n\t\tassertEquals(this.factory.leaf(1), tree.getLeft());\n\t\tassertEquals(this.factory.leaf(2), tree.getRight());\n\t}", "\[email protected]\n\tpublic void testExceptions() {\n\t\tvar left = this.factory.leaf(1);\n\t\tvar right = this.factory.leaf(2);\n\t\tvar tree = this.factory.compose(left, right); // (1,2)\n\n\t\t// attention, a leaf does not have left and right, and vice versa\n\t\tassertThrows(NoSuchElementException.class, ()->tree.getLeaf());\n\t\tassertThrows(NoSuchElementException.class, ()->left.getLeft());\n\t\tassertThrows(NoSuchElementException.class, ()->left.getRight());\n\t\tassertThrows(NoSuchElementException.class, ()->right.getLeft());\n\t\tassertThrows(NoSuchElementException.class, ()->right.getRight());\n\t}", "\[email protected]\n\tpublic void testCompute() {\n\t\tvar left = this.factory.leaf(1);\n\t\tvar right = this.factory.leaf(2);\n\t\tvar tree1 = this.factory.compose(left, right); // (1,2)\n\t\tvar tree = this.factory.compose(tree1, this.factory.leaf(3)); // ((1,2),3)\n\t\t\n\t\t// + is executed for each node in the tree, obtaining as a result ((1+2)+3)\n\t\tassertEquals(Integer.valueOf(3), tree1.compute((l1,l2) -> l1+l2));\n\t\t\n\t\t// same thing also - and *\n\t\tassertEquals(Integer.valueOf(6), tree.compute((l1,l2) -> l1+l2));\n\t\tassertEquals(Integer.valueOf(-4), tree.compute((l1,l2) -> l1-l2));\n\t\tassertEquals(Integer.valueOf(6), tree.compute((l1,l2) -> l1*l2));\n\t}", "\[email protected]\n\tpublic void testMap() {\n\t\tvar left = this.factory.leaf(1);\n\t\tvar right = this.factory.leaf(2);\n\t\tvar tree1 = this.factory.compose(left, right); // +(1,2)\n\t\t\n\t\t// each value in the leaves is incremented\n\t\tassertEquals(this.factory.leaf(2), left.map(i ->i+1));\n\t\t// the square of each value in the leaves is taken\n\t\tassertEquals(this.factory.compose(this.factory.leaf(1), this.factory.leaf(4)), tree1.map(i->i*i)); \n\t}", "\[email protected]\n\tpublic void testSymmetric() {\n\t\tvar left = this.factory.leaf(1);\n\t\tvar right = this.factory.leaf(2);\n\t\tvar tree1 = this.factory.compose(left, right); // (1,2)\n\t\tvar tree = this.factory.compose(tree1, this.factory.leaf(3)); // ((1,2),3)\n\t\t\n\t\t// the symmetric is a tree horizontally mirrored to the one in input\n\t\t// symmetric of (1,2) is (2,1)\n\t\tassertEquals(this.factory.compose(this.factory.leaf(2), this.factory.leaf(1)), tree1.symmetric());\n\t\t// symmetric of ((1,2),3) is (3,(2,1))\n\t\tassertEquals(this.factory.compose(this.factory.leaf(2), this.factory.leaf(1)), tree.symmetric().getRight());\n\t}", "\[email protected]\n\tpublic void optionalTestNested() {\n\t\t// the nested of (1,2,3,4) is a tree that has those values in the leaves, ordered, for example (1,(2,(3,4))\n\t\tassertEquals(Integer.valueOf(10), this.factory.nested(List.of(1,2,3,4)).compute((a,b)->a+b));\n\t\tassertEquals(Integer.valueOf(24), this.factory.nested(List.of(1,2,3,4)).compute((a,b)->a*b));\n\t}" ] }, "content": "package a06.sol1;\n\nimport static org.junit.Assert.*;\n\nimport java.util.List;\nimport java.util.NoSuchElementException;\n\npublic class Test {\n\n\t/*\n\t * Implement the BTreeFactory interface as indicated in the\n\t * initFactory method below. Create a factory for BTrees, i.e.,\n\t * binary trees where the values present are in the leaves (LEAF).\n\t * For example, a tree could have a root and two leaves with values 1 and 2,\n\t * also indicated briefly with (1,2), another could have a root,\n\t * a left child consisting of the tree (1,2) and a right child with only\n\t * the leaf 3, and we would indicate it with ((1,2),3)\n\t *\n\t * The comment on the provided interfaces, and the test methods below\n\t * constitute the necessary explanation of the problem.\n\t *\n\t * The following are considered optional for the purpose of being able to correct\n\t * the exercise, but still contribute to achieving the totality of the\n\t * score:\n\t *\n\t * - implementation of the last test, called optionalTestXYZ (related to the\n\t * method BTreeFactory.nested)\n\t *\n\t * - the good design of the solution, in particular using succinct code\n\t *\n\t * Remove the comment from the initFactory method.\n\t *\n\t * Scoring indications:\n\t *\n\t * - correctness of the mandatory part: 10 points\n\t *\n\t * - correctness of the optional part: 4 points\n\t *\n\t * - quality of the solution: 3 points\n\t *\n\t */\n\n\tprivate BTreeFactory factory = null;\n\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.factory = new BTreeFactoryImpl();\n\t}\n\t\n\[email protected]\n\tpublic void testSimple() {\n\t\tvar left = this.factory.leaf(1);\n\t\tvar right = this.factory.leaf(2);\n\t\tvar tree = this.factory.compose(left, right); // the tree (1,2)\n\t\t\n\t\t// from here, simple getters\n\t\tassertTrue(left.isLeaf());\n\t\tassertTrue(right.isLeaf());\n\t\tassertFalse(tree.isLeaf());\n\t\t\n\t\tassertEquals(Integer.valueOf(1), left.getLeaf());\n\t\tassertEquals(Integer.valueOf(2), right.getLeaf());\n\t\t\n\t\tassertEquals(this.factory.leaf(1), tree.getLeft());\n\t\tassertEquals(this.factory.leaf(2), tree.getRight());\n\t}\n\t\n\[email protected]\n\tpublic void testExceptions() {\n\t\tvar left = this.factory.leaf(1);\n\t\tvar right = this.factory.leaf(2);\n\t\tvar tree = this.factory.compose(left, right); // (1,2)\n\n\t\t// attention, a leaf does not have left and right, and vice versa\n\t\tassertThrows(NoSuchElementException.class, ()->tree.getLeaf());\n\t\tassertThrows(NoSuchElementException.class, ()->left.getLeft());\n\t\tassertThrows(NoSuchElementException.class, ()->left.getRight());\n\t\tassertThrows(NoSuchElementException.class, ()->right.getLeft());\n\t\tassertThrows(NoSuchElementException.class, ()->right.getRight());\n\t}\n\t\n\[email protected]\n\tpublic void testCompute() {\n\t\tvar left = this.factory.leaf(1);\n\t\tvar right = this.factory.leaf(2);\n\t\tvar tree1 = this.factory.compose(left, right); // (1,2)\n\t\tvar tree = this.factory.compose(tree1, this.factory.leaf(3)); // ((1,2),3)\n\t\t\n\t\t// + is executed for each node in the tree, obtaining as a result ((1+2)+3)\n\t\tassertEquals(Integer.valueOf(3), tree1.compute((l1,l2) -> l1+l2));\n\t\t\n\t\t// same thing also - and *\n\t\tassertEquals(Integer.valueOf(6), tree.compute((l1,l2) -> l1+l2));\n\t\tassertEquals(Integer.valueOf(-4), tree.compute((l1,l2) -> l1-l2));\n\t\tassertEquals(Integer.valueOf(6), tree.compute((l1,l2) -> l1*l2));\n\t}\n\t\n\[email protected]\n\tpublic void testMap() {\n\t\tvar left = this.factory.leaf(1);\n\t\tvar right = this.factory.leaf(2);\n\t\tvar tree1 = this.factory.compose(left, right); // +(1,2)\n\t\t\n\t\t// each value in the leaves is incremented\n\t\tassertEquals(this.factory.leaf(2), left.map(i ->i+1));\n\t\t// the square of each value in the leaves is taken\n\t\tassertEquals(this.factory.compose(this.factory.leaf(1), this.factory.leaf(4)), tree1.map(i->i*i)); \n\t}\n\t\n\[email protected]\n\tpublic void testSymmetric() {\n\t\tvar left = this.factory.leaf(1);\n\t\tvar right = this.factory.leaf(2);\n\t\tvar tree1 = this.factory.compose(left, right); // (1,2)\n\t\tvar tree = this.factory.compose(tree1, this.factory.leaf(3)); // ((1,2),3)\n\t\t\n\t\t// the symmetric is a tree horizontally mirrored to the one in input\n\t\t// symmetric of (1,2) is (2,1)\n\t\tassertEquals(this.factory.compose(this.factory.leaf(2), this.factory.leaf(1)), tree1.symmetric());\n\t\t// symmetric of ((1,2),3) is (3,(2,1))\n\t\tassertEquals(this.factory.compose(this.factory.leaf(2), this.factory.leaf(1)), tree.symmetric().getRight());\n\t}\n\t\n\[email protected]\n\tpublic void optionalTestNested() {\n\t\t// the nested of (1,2,3,4) is a tree that has those values in the leaves, ordered, for example (1,(2,(3,4))\n\t\tassertEquals(Integer.valueOf(10), this.factory.nested(List.of(1,2,3,4)).compute((a,b)->a+b));\n\t\tassertEquals(Integer.valueOf(24), this.factory.nested(List.of(1,2,3,4)).compute((a,b)->a*b));\n\t}\n}", "filename": "Test.java" }
2020
a01a
[ { "content": "package a01a.sol1;\n\nimport java.util.List;\nimport java.util.Set;\n\n\npublic interface Tree<E> {\n\t\n\t\n\tE getRoot();\n\t\n\t\n\tList<Tree<E>> getChildren();\n\t\n\t\n\tSet<E> getLeafs();\n\t\n\t\n\tSet<E> getAll();\n\t\n\t\n\t@Override \n\tString toString();\n\t\n}", "filename": "Tree.java" }, { "content": "package a01a.sol1;\n\nimport java.util.List;\nimport java.util.Set;\n\npublic interface TreeFactory {\n\n\t\n\t<E> Tree<E> singleValue(E root);\n\t\n\t\n\t<E> Tree<E> twoChildren(E root, Tree<E> child1, Tree<E> child2);\n\t\n\t\n\t<E> Tree<E> oneLevel(E root, List<E> children);\n\t\n\t\n\t<E> Tree<E> chain(E root, List<E> list);\n\t\n}", "filename": "TreeFactory.java" }, { "content": "package 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 a01a.sol1;\n\nimport java.util.Collections;\nimport java.util.List;\nimport java.util.Set;\nimport java.util.stream.Collectors;\nimport java.util.stream.Stream;\n\npublic class TreeFactoryImpl implements TreeFactory {\n\n\t@Override\n\tpublic <E> Tree<E> singleValue(E root) {\n\t\treturn new TreeImpl<>(root,Collections.emptyList());\n\t}\n\n\t@Override\n\tpublic <E> Tree<E> twoChildren(E root, Tree<E> child1, Tree<E> child2) {\n\t\treturn new TreeImpl<>(root,Stream.of(child1,child2).collect(Collectors.toList()));\n\t}\n\n\t@Override\n\tpublic <E> Tree<E> oneLevel(E root, List<E> children) {\n\t\treturn new TreeImpl<>(root,children.stream().map(this::singleValue).collect(Collectors.toList()));\n\t}\n\n\t@Override\n\tpublic <E> Tree<E> chain(E root, List<E> list) {\n\t\tif (list.isEmpty()) {\n\t\t\treturn singleValue(root);\n\t\t}\n\t\treturn new TreeImpl<>(root,Collections.singletonList(chain(list.get(0),list.subList(1, list.size()))));\n\t}\n}", "filename": "TreeFactoryImpl.java" }, { "content": "package a01a.sol1;\n\nimport java.util.Collections;\nimport java.util.List;\nimport java.util.Set;\nimport java.util.stream.Collectors;\nimport java.util.stream.Stream;\n\npublic class TreeImpl<E> implements Tree<E> {\n\t\n\tprivate final E root;\n\tprivate final List<Tree<E>> children;\n\t\n\tTreeImpl(E root, List<Tree<E>> children) {\n\t\tsuper();\n\t\tthis.root = root;\n\t\tthis.children = children;\n\t}\n\n\t@Override\n\tpublic E getRoot() {\n\t\treturn this.root;\n\t}\n\n\t@Override\n\tpublic List<Tree<E>> getChildren() {\n\t\treturn Collections.unmodifiableList(this.children);\n\t}\n\n\t@Override\n\tpublic Set<E> getLeafs() {\n\t\tif (this.children.isEmpty()) {\n\t\t\treturn Collections.singleton(this.root);\n\t\t}\n\t\treturn this.children.stream().flatMap(t -> t.getLeafs().stream()).collect(Collectors.toSet());\n\t}\n\n\t@Override\n\tpublic Set<E> getAll() {\n\t\treturn Stream.concat(\n\t\t\t\tStream.of(this.root), \n\t\t\t\tthis.children.stream().flatMap(t -> t.getAll().stream())).collect(Collectors.toSet());\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn root.toString() + children;\n\t}\n\t\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = 1;\n\t\tresult = prime * result + ((children == null) ? 0 : children.hashCode());\n\t\tresult = prime * result + ((root == null) ? 0 : root.hashCode());\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj) {\n\t\t\treturn true;\n\t\t}\n\t\tif (!(obj instanceof TreeImpl)) {\n\t\t\treturn false;\n\t\t}\n\t\tTreeImpl other = (TreeImpl) obj;\n\t\tif (children == null) {\n\t\t\tif (other.children != null) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t} else if (!children.equals(other.children)) {\n\t\t\treturn false;\n\t\t}\n\t\tif (root == null) {\n\t\t\tif (other.root != null) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t} else if (!root.equals(other.root)) {\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\t\n}", "filename": "TreeImpl.java" } ]
{ "components": { "imports": "package a01a.sol1;\n\nimport static org.junit.Assert.*;\n\nimport java.util.Iterator;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Set;\nimport java.util.stream.Collectors;", "private_init": "\t/*\n\t * Implement the TreeFactory interface as indicated in the initFactory method below.\n\t * Create a factory for Trees, i.e., immutable tree data structures (a node has \"n\" ordered children).\n\t * Implement the equals and hashcode methods correctly (via Eclipse as usual) for these Trees.\n\t * \n\t * The comment on the provided interfaces, and the test methods below constitute the necessary\n\t * explanation of the problem.\n\t * \n\t * The following are considered optional for the purpose of being able to correct the exercise,\n\t * but still contribute to achieving the totality of the score:\n\t * - implementation of the tests called optionalTestXYZ (related to toString and twoChains)\n\t * - good design of the solution, in particular using succinct code\n\t * \n\t * Remove the comment from the initFactory method.\n\t * \n\t * Scoring indications:\n\t * - correctness of the mandatory part: 10 points\n\t * - correctness of the optional part: 4 points (2 for toString, 2 for twoChains\n\t * - quality of the solution: 3 points\n\t * \n\t */\n\t\n\t\n\tprivate TreeFactory factory = null;\n\t\n\t\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.factory= new TreeFactoryImpl();\n\t}\n\t\n\t/**\n\t * An optional test, showing all the trees we will use in this exam \n\t */", "test_functions": [ "\[email protected]\n\tpublic void optionalTestToStrings() {\n\t\tTree<String> tree = this.factory.singleValue(\"a\");\n\t\tassertEquals(\"a[]\", tree.toString());\n\t\t\n\t\tTree<Integer> tree2 = this.factory.oneLevel(10, List.of(11,12,13));\n\t\tassertEquals(\"10[11[], 12[], 13[]]\", tree2.toString());\n\t\t\n\t\tTree<Integer> treeA = this.factory.oneLevel(10, List.of(11,12));\n\t\tTree<Integer> treeB = this.factory.singleValue(20);\n\t\tTree<Integer> treeC = this.factory.twoChildren(1, treeA, treeB);\n\t\tassertEquals(\"1[10[11[], 12[]], 20[]]\", treeC.toString());\n\t\t\n\t\tTree<Integer> tree3 = this.factory.chain(10, List.of(20,30));\n\t\tassertEquals(\"10[20[30[]]]\", tree3.toString());\n\t\n\t}", "\[email protected]\n\tpublic void testSingleValue() {\n\t\t// a tree with only the root\n\t\tTree<String> tree = this.factory.singleValue(\"a\");\n\n\t\tassertEquals(\"a\", tree.getRoot());\n\t\tassertTrue(tree.getChildren().isEmpty());\n\t\tassertEquals(Set.of(\"a\"), tree.getLeafs());\n\t\tassertEquals(Set.of(\"a\"), tree.getAll());\n\t\t//assertEquals(\"a[]\", tree.toString()); // SAME TEST IN optionalTestToString\n\t}", "\[email protected]\n\tpublic void testOneLevel() {\n\t\t// a tree with the root and 3 children that are also leaves\n\t\tTree<Integer> tree = this.factory.oneLevel(10, List.of(11,12,13));\n\n\t\tassertEquals(Integer.valueOf(10), tree.getRoot());\n\t\tassertEquals(3, tree.getChildren().size());\n\t\tassertEquals(Integer.valueOf(11),tree.getChildren().get(0).getRoot()); // first child\n\t\tassertEquals(Integer.valueOf(12),tree.getChildren().get(1).getRoot()); // second child\n\t\tassertEquals(Integer.valueOf(13),tree.getChildren().get(2).getRoot()); // third child\n\t\tassertEquals(Set.of(11,12,13), tree.getLeafs());\n\t\tassertEquals(Set.of(10,11,12,13), tree.getAll());\n\t\t//assertEquals(\"10[11[], 12[], 13[]]\", tree.toString()); // SAME TEST IN optionalTestToString\n\t}", "\[email protected]\n\tpublic void testTwoChildren() {\n\t\tTree<Integer> tree1 = this.factory.oneLevel(10, List.of(11,12));\n\t\tTree<Integer> tree2 = this.factory.singleValue(20);\n\t\t// a tree with the root and the 2 children tree1 and tree2\n\t\tTree<Integer> tree = this.factory.twoChildren(1, tree1, tree2);\n\t\t\n\t\tassertEquals(Integer.valueOf(1), tree.getRoot());\n\t\tassertEquals(2, tree.getChildren().size());\n\t\tassertEquals(Integer.valueOf(10),tree.getChildren().get(0).getRoot()); // root of the first child\n\t\tassertEquals(2,tree.getChildren().get(0).getChildren().size()); // how many children the first child has\n\t\tassertEquals(Integer.valueOf(20),tree.getChildren().get(1).getRoot()); // root of the second child\n\t\tassertEquals(Set.of(11,12,20), tree.getLeafs());\n\t\tassertEquals(Set.of(1,10,11,12,20), tree.getAll());\n\t\t//assertEquals(\"1[10[11[], 12[]], 20[]]\", tree.toString()); // SAME TEST IN optionalTestToString\n\t}", "\[email protected]\n\tpublic void optionalTestChain() {\n\t\t// a tree with root 10, child 20, child of the child 30\n\t\tTree<Integer> tree = this.factory.chain(10, List.of(20,30));\n\t\t\n\t\tassertEquals(Integer.valueOf(10), tree.getRoot());\n\t\tassertEquals(1, tree.getChildren().size());\n\t\tassertEquals(Integer.valueOf(20),tree.getChildren().get(0).getRoot()); // root of the child\n\t\tassertEquals(1,tree.getChildren().get(0).getChildren().size()); // number of children of the child\n\t\tassertEquals(Integer.valueOf(30),tree.getChildren().get(0).getChildren().get(0).getRoot()); // root of the child of the child\n\t\tassertEquals(0,tree.getChildren().get(0).getChildren().get(0).getChildren().size()); // ...\n\t\tassertEquals(Set.of(30), tree.getLeafs());\n\t\tassertEquals(Set.of(10,20,30), tree.getAll());\n\t\t//assertEquals(\"10[20[30[]]]\", tree.toString()); // SAME TEST IN optionalTestToString\n\t}" ] }, "content": "package a01a.sol1;\n\nimport static org.junit.Assert.*;\n\nimport java.util.Iterator;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Set;\nimport java.util.stream.Collectors;\n\npublic class Test {\n\t\n\t/*\n\t * Implement the TreeFactory interface as indicated in the initFactory method below.\n\t * Create a factory for Trees, i.e., immutable tree data structures (a node has \"n\" ordered children).\n\t * Implement the equals and hashcode methods correctly (via Eclipse as usual) for these Trees.\n\t * \n\t * The comment on the provided interfaces, and the test methods below constitute the necessary\n\t * explanation of the problem.\n\t * \n\t * The following are considered optional for the purpose of being able to correct the exercise,\n\t * but still contribute to achieving the totality of the score:\n\t * - implementation of the tests called optionalTestXYZ (related to toString and twoChains)\n\t * - good design of the solution, in particular using succinct code\n\t * \n\t * Remove the comment from the initFactory method.\n\t * \n\t * Scoring indications:\n\t * - correctness of the mandatory part: 10 points\n\t * - correctness of the optional part: 4 points (2 for toString, 2 for twoChains\n\t * - quality of the solution: 3 points\n\t * \n\t */\n\t\n\t\n\tprivate TreeFactory factory = null;\n\t\n\t\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.factory= new TreeFactoryImpl();\n\t}\n\t\n\t/**\n\t * An optional test, showing all the trees we will use in this exam \n\t */\n\[email protected]\n\tpublic void optionalTestToStrings() {\n\t\tTree<String> tree = this.factory.singleValue(\"a\");\n\t\tassertEquals(\"a[]\", tree.toString());\n\t\t\n\t\tTree<Integer> tree2 = this.factory.oneLevel(10, List.of(11,12,13));\n\t\tassertEquals(\"10[11[], 12[], 13[]]\", tree2.toString());\n\t\t\n\t\tTree<Integer> treeA = this.factory.oneLevel(10, List.of(11,12));\n\t\tTree<Integer> treeB = this.factory.singleValue(20);\n\t\tTree<Integer> treeC = this.factory.twoChildren(1, treeA, treeB);\n\t\tassertEquals(\"1[10[11[], 12[]], 20[]]\", treeC.toString());\n\t\t\n\t\tTree<Integer> tree3 = this.factory.chain(10, List.of(20,30));\n\t\tassertEquals(\"10[20[30[]]]\", tree3.toString());\n\t\n\t}\n\n\t\n\[email protected]\n\tpublic void testSingleValue() {\n\t\t// a tree with only the root\n\t\tTree<String> tree = this.factory.singleValue(\"a\");\n\n\t\tassertEquals(\"a\", tree.getRoot());\n\t\tassertTrue(tree.getChildren().isEmpty());\n\t\tassertEquals(Set.of(\"a\"), tree.getLeafs());\n\t\tassertEquals(Set.of(\"a\"), tree.getAll());\n\t\t//assertEquals(\"a[]\", tree.toString()); // SAME TEST IN optionalTestToString\n\t}\n\t\n\[email protected]\n\tpublic void testOneLevel() {\n\t\t// a tree with the root and 3 children that are also leaves\n\t\tTree<Integer> tree = this.factory.oneLevel(10, List.of(11,12,13));\n\n\t\tassertEquals(Integer.valueOf(10), tree.getRoot());\n\t\tassertEquals(3, tree.getChildren().size());\n\t\tassertEquals(Integer.valueOf(11),tree.getChildren().get(0).getRoot()); // first child\n\t\tassertEquals(Integer.valueOf(12),tree.getChildren().get(1).getRoot()); // second child\n\t\tassertEquals(Integer.valueOf(13),tree.getChildren().get(2).getRoot()); // third child\n\t\tassertEquals(Set.of(11,12,13), tree.getLeafs());\n\t\tassertEquals(Set.of(10,11,12,13), tree.getAll());\n\t\t//assertEquals(\"10[11[], 12[], 13[]]\", tree.toString()); // SAME TEST IN optionalTestToString\n\t}\n\t\n\[email protected]\n\tpublic void testTwoChildren() {\n\t\tTree<Integer> tree1 = this.factory.oneLevel(10, List.of(11,12));\n\t\tTree<Integer> tree2 = this.factory.singleValue(20);\n\t\t// a tree with the root and the 2 children tree1 and tree2\n\t\tTree<Integer> tree = this.factory.twoChildren(1, tree1, tree2);\n\t\t\n\t\tassertEquals(Integer.valueOf(1), tree.getRoot());\n\t\tassertEquals(2, tree.getChildren().size());\n\t\tassertEquals(Integer.valueOf(10),tree.getChildren().get(0).getRoot()); // root of the first child\n\t\tassertEquals(2,tree.getChildren().get(0).getChildren().size()); // how many children the first child has\n\t\tassertEquals(Integer.valueOf(20),tree.getChildren().get(1).getRoot()); // root of the second child\n\t\tassertEquals(Set.of(11,12,20), tree.getLeafs());\n\t\tassertEquals(Set.of(1,10,11,12,20), tree.getAll());\n\t\t//assertEquals(\"1[10[11[], 12[]], 20[]]\", tree.toString()); // SAME TEST IN optionalTestToString\n\t}\n\t\n\[email protected]\n\tpublic void optionalTestChain() {\n\t\t// a tree with root 10, child 20, child of the child 30\n\t\tTree<Integer> tree = this.factory.chain(10, List.of(20,30));\n\t\t\n\t\tassertEquals(Integer.valueOf(10), tree.getRoot());\n\t\tassertEquals(1, tree.getChildren().size());\n\t\tassertEquals(Integer.valueOf(20),tree.getChildren().get(0).getRoot()); // root of the child\n\t\tassertEquals(1,tree.getChildren().get(0).getChildren().size()); // number of children of the child\n\t\tassertEquals(Integer.valueOf(30),tree.getChildren().get(0).getChildren().get(0).getRoot()); // root of the child of the child\n\t\tassertEquals(0,tree.getChildren().get(0).getChildren().get(0).getChildren().size()); // ...\n\t\tassertEquals(Set.of(30), tree.getLeafs());\n\t\tassertEquals(Set.of(10,20,30), tree.getAll());\n\t\t//assertEquals(\"10[20[30[]]]\", tree.toString()); // SAME TEST IN optionalTestToString\n\t}\t\n\t\n}", "filename": "Test.java" }
2020
a02a
[ { "content": "package a02a.sol1;\n\nimport java.util.Iterator;\n\n\npublic interface Scanner<X,Y>{\n\t\n\tY scan(Iterator<X> input);\n}", "filename": "Scanner.java" }, { "content": "package 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 a02a.sol1;\n\nimport java.util.List;\nimport java.util.Optional;\nimport java.util.function.Function;\nimport java.util.function.Predicate;\n\n\npublic interface ScannerFactory {\n\t\n\t\n\t<X,Y> Scanner<X,List<Y>> collect(Predicate<X> filter, Function<X,Y> mapper);\n\t\n\t\n\t<X> Scanner<X,Optional<X>> findFirst(Predicate<X> filter);\n\t\n\t\n\tScanner<Integer,Optional<Integer>> maximalPrefix();\n\t\n\t\n\tScanner<Integer,List<Integer>> cumulativeSum();\n\t\n}", "filename": "ScannerFactory.java" } ]
[ { "content": "package a02a.sol1;\n\nimport java.util.Iterator;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Optional;\nimport java.util.function.BiFunction;\nimport java.util.function.Function;\nimport java.util.function.Predicate;\n\npublic class ScannerFactoryImpl implements ScannerFactory {\n\t\n\t/**\n\t * Typical strategy-based technique: all scanners can be obtained by the default one,\n\t * by proper arguments (datas and lambdas)\n\t */\n\tprivate <I,S,O> Scanner<I,O> defaultScanner(S initialState, BiFunction<I,S,S> updateState, Function<S,O> mapper){\n\t\treturn new Scanner<>() {\n\n\t\t\t@Override\n\t\t\tpublic O scan(Iterator<I> input) {\n\t\t\t\tS state = initialState;\n\t\t\t\twhile(input.hasNext()) {\n\t\t\t\t\tstate = updateState.apply(input.next(), state);\n\t\t\t\t}\n\t\t\t\treturn mapper.apply(state);\n\t\t\t}\n\t\t\t\n\t\t};\n\t}\n\t\n\tprivate <I,O> Scanner<I,O> simpleScanner(O initialState, BiFunction<I,O,O> updateState){\n\t\treturn defaultScanner(initialState,updateState,x->x); \n\t}\n\t\n\t\n\n\t@Override\n\tpublic Scanner<Integer, List<Integer>> cumulativeSum() {\n\t\treturn simpleScanner(\n\t\t\t\tnew LinkedList<Integer>(), \n\t\t\t\t(sum,list) -> {\n\t\t\t\t\tlist.add(sum+(list.isEmpty() ? 0 : list.get(list.size()-1)));\n\t\t\t\t\treturn list;\n\t\t\t\t});\n\t}\n\n\t@Override\n\tpublic <X, Y> Scanner<X, List<Y>> collect(Predicate<X> filter, Function<X, Y> mapper) {\n\t\treturn simpleScanner(\n\t\t\t\tnew LinkedList<Y>(), \n\t\t\t\t(e,list) -> {\n\t\t\t\t\tif (filter.test(e)) {\n\t\t\t\t\t\tlist.add(mapper.apply(e));\n\t\t\t\t\t} \n\t\t\t\t\treturn list;\n\t\t\t\t});\n\t}\n\n\t@Override\n\tpublic <X> Scanner<X, Optional<X>> findFirst(Predicate<X> filter) {\n\t\treturn simpleScanner(\n\t\t\t\tOptional.<X>empty(), \n\t\t\t\t(e,opt) -> opt.isPresent() ? opt : Optional.of(e).filter(filter));\n\t}\n\n\t@Override\n\tpublic Scanner<Integer, Optional<Integer>> maximalPrefix() {\n\t\treturn defaultScanner(\n\t\t\t\tnew Pair<>(false,Optional.<Integer>empty()), \n\t\t\t\t(e,p) -> {\n\t\t\t\t\tif (p.getY().isEmpty()) { \n\t\t\t\t\t\treturn new Pair<>(false,Optional.of(e));\n\t\t\t\t\t} else if (p.getX()) {\n\t\t\t\t\t\treturn p;\n\t\t\t\t\t} else if (e > p.getY().get()) { \n\t\t\t\t\t\treturn new Pair<>(false,Optional.of(e));\n\t\t\t\t\t}\n\t\t\t\t\treturn new Pair<>(true,p.getY());\n\t\t\t\t},\n\t\t\t\tPair::getY);\n\t}\n\n}", "filename": "ScannerFactoryImpl.java" } ]
{ "components": { "imports": "package a02a.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;\n\n/**\n * See the documentation of the ScannerFactory interface, which models\n * a factory for Scanner, which in turn models an object that takes a list\n * and extracts some information from it.\n * \n * The comments on the provided interfaces, and the test methods below constitute the necessary\n * explanation of the problem.\n * \n * The following are considered optional for the purpose of being able to correct\n * the exercise, but still contribute to achieving the entirety of the\n * score:\n * - implementation of optional tests (named 'optionalTestXYZ', i.e. those related to\n * ScannerFactory.cumulativeSums)\n * - conciseness of the code and removal of all repetitions\n *\n * Remove the comment from the init method.\n * \n * Scoring indications:\n * - correctness of the mandatory part: 10 points\n * - correctness of the optional part: 4 points\n * - quality of the solution: 3 points\n * \n */", "private_init": "\tprivate ScannerFactory factory;\n\n\[email protected]\n\tpublic void init() {\n\t\tthis.factory = new ScannerFactoryImpl();\n\t}", "test_functions": [ "\[email protected]\n\tpublic void optionalTestCumulativeSum() {\n\t\t// cumulative sum of the elements \"so far\"\n\t\tvar s = this.factory.cumulativeSum();\n\t\tassertEquals(List.of(1,1,1,3,6,6,6,6,10), s.scan(List.of(1,0,0,2,3,0,0,0,4).iterator()));\n\t}", "\[email protected]\n\tpublic void testCollect() {\n\t\t// collects elements with certain characteristics and transforms them\n\t\tScanner<Integer,List<Integer>> s = this.factory.collect(x-> x>0, x->x*2);\n\t\tassertEquals(List.of(2,4,6,8), s.scan(List.of(1,0,0,2,3,0,0,0,4).iterator()));\n\t}", "\[email protected]\n\tpublic void testFindFirst() {\n\t\t// finds the first with certain characteristics\n\t\tScanner<Integer,Optional<Integer>> s = this.factory.findFirst(x-> x<0);\n\t\tassertEquals(Optional.of(-3), s.scan(List.of(1,0,0,2,-3,0,0,0,4).iterator()));\n\t\tassertEquals(Optional.of(-1), s.scan(List.of(-1,0,0,2,-3,0,0,0,4).iterator()));\n\t\tassertEquals(Optional.of(-4), s.scan(List.of(1,0,0,2,3,0,0,0,-4).iterator()));\n\t\tassertEquals(Optional.empty(), s.scan(List.of(1,0,0,2,3,0,0,0,4).iterator()));\n\t}", "\[email protected]\n\tpublic void testMaximalPrefix() {\n\t\t// finds the largest element of the initial ordered subsequence\n\t\tScanner<Integer,Optional<Integer>> s = this.factory.maximalPrefix();\n\t\tassertEquals(Optional.of(20), s.scan(List.of(1,10,20,5,30,40).iterator()));\n\t\tassertEquals(Optional.of(3), s.scan(List.of(1,2,3).iterator()));\n\t\tassertEquals(Optional.of(1), s.scan(List.of(1).iterator()));\n\t\tassertEquals(Optional.empty(), s.scan(List.<Integer>of().iterator()));\n\t}" ] }, "content": "package a02a.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;\n\n/**\n * See the documentation of the ScannerFactory interface, which models\n * a factory for Scanner, which in turn models an object that takes a list\n * and extracts some information from it.\n * \n * The comments on the provided interfaces, and the test methods below constitute the necessary\n * explanation of the problem.\n * \n * The following are considered optional for the purpose of being able to correct\n * the exercise, but still contribute to achieving the entirety of the\n * score:\n * - implementation of optional tests (named 'optionalTestXYZ', i.e. those related to\n * ScannerFactory.cumulativeSums)\n * - conciseness of the code and removal of all repetitions\n *\n * Remove the comment from the init method.\n * \n * Scoring indications:\n * - correctness of the mandatory part: 10 points\n * - correctness of the optional part: 4 points\n * - quality of the solution: 3 points\n * \n */\n\npublic class Test {\n\n\tprivate ScannerFactory factory;\n\n\[email protected]\n\tpublic void init() {\n\t\tthis.factory = new ScannerFactoryImpl();\n\t}\n\n\[email protected]\n\tpublic void optionalTestCumulativeSum() {\n\t\t// cumulative sum of the elements \"so far\"\n\t\tvar s = this.factory.cumulativeSum();\n\t\tassertEquals(List.of(1,1,1,3,6,6,6,6,10), s.scan(List.of(1,0,0,2,3,0,0,0,4).iterator()));\n\t}\n\t\n\[email protected]\n\tpublic void testCollect() {\n\t\t// collects elements with certain characteristics and transforms them\n\t\tScanner<Integer,List<Integer>> s = this.factory.collect(x-> x>0, x->x*2);\n\t\tassertEquals(List.of(2,4,6,8), s.scan(List.of(1,0,0,2,3,0,0,0,4).iterator()));\n\t}\n\t\n\[email protected]\n\tpublic void testFindFirst() {\n\t\t// finds the first with certain characteristics\n\t\tScanner<Integer,Optional<Integer>> s = this.factory.findFirst(x-> x<0);\n\t\tassertEquals(Optional.of(-3), s.scan(List.of(1,0,0,2,-3,0,0,0,4).iterator()));\n\t\tassertEquals(Optional.of(-1), s.scan(List.of(-1,0,0,2,-3,0,0,0,4).iterator()));\n\t\tassertEquals(Optional.of(-4), s.scan(List.of(1,0,0,2,3,0,0,0,-4).iterator()));\n\t\tassertEquals(Optional.empty(), s.scan(List.of(1,0,0,2,3,0,0,0,4).iterator()));\n\t}\n\t\n\[email protected]\n\tpublic void testMaximalPrefix() {\n\t\t// finds the largest element of the initial ordered subsequence\n\t\tScanner<Integer,Optional<Integer>> s = this.factory.maximalPrefix();\n\t\tassertEquals(Optional.of(20), s.scan(List.of(1,10,20,5,30,40).iterator()));\n\t\tassertEquals(Optional.of(3), s.scan(List.of(1,2,3).iterator()));\n\t\tassertEquals(Optional.of(1), s.scan(List.of(1).iterator()));\n\t\tassertEquals(Optional.empty(), s.scan(List.<Integer>of().iterator()));\n\t}\n\t\n}", "filename": "Test.java" }
2020
a05
[ { "content": "package a05.sol1;\n\n\npublic interface BatteryFactory {\n\t\n\t\n\tBattery createSimpleBattery();\n\t\n\t\n\tBattery createSimpleBatteryByDrop(double energyPerDurationDrop);\n\n\t\n\tBattery createSimpleBatteryWithExponentialDrop();\n\n\t\n\tBattery createSecureBattery();\n\t\n\t\n\tBattery createRechargeableBattery();\n\t\n\t\n\tBattery createSecureAndRechargeableBattery();\n\n}", "filename": "BatteryFactory.java" }, { "content": "package a05.sol1;\n\n\npublic interface Battery {\n\t\n\t\n\tvoid startUse();\n\t\n\t\n\tvoid stopUse(double duration);\n\t\n\t\n\tdouble getEnergy();\n\t\n\t\n\tvoid recharge();\n}", "filename": "Battery.java" }, { "content": "package 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 a05.sol1;\n\npublic class RechargableBattery extends BatteryDecorator {\n\t\n\tprivate static final double EFFICIENCY_LOSS = 0.01;\n\tprivate double rechargeValue = 1.0;\n\t\n\tpublic RechargableBattery(AbstractBattery base) {\n\t\tsuper(base);\n\t}\n\t\n\t@Override\n\tpublic void recharge() {\n\t\tsuper.setEnergy(this.rechargeValue);\n\t\tthis.rechargeValue = this.rechargeValue - EFFICIENCY_LOSS;\n\t}\n}", "filename": "RechargableBattery.java" }, { "content": "package a05.sol1;\n\nimport java.util.function.BiFunction;\n\npublic class SimpleBattery extends AbstractBattery {\n\t\n\tprivate final BiFunction<Double, Double, Double> dropFunction;\n\t\n\tprotected SimpleBattery(BiFunction<Double, Double, Double> dropFunction) {\n\t\tthis.dropFunction = dropFunction;\n\t\tthis.setEnergy(1.0);\n\t}\n\t\n\t@Override\n\tpublic void startUse() {\n\t}\n\n\t@Override\n\tpublic void stopUse(double duration) {\n\t\tthis.setEnergy(this.dropFunction.apply(this.getEnergy(), duration));\n\t\tif (this.getEnergy()<= 0.0) {\n\t\t\tthis.setEnergy(0.0);\n\t\t}\n\t}\n\t\t\n\t@Override\n\tpublic void recharge() {\n\t}\n}", "filename": "SimpleBattery.java" }, { "content": "package a05.sol1;\n\npublic class SecureBattery extends BatteryDecorator {\n\n\tpublic SecureBattery(AbstractBattery base) {\n\t\tsuper(base);\n\t}\n\t\n\tboolean inUse = false;\n\t\n\t@Override\n\tpublic void startUse() {\n\t\tif (inUse || this.getEnergy() <= 0.0) {\n\t\t\tthrow new IllegalStateException();\n\t\t}\n\t\tinUse = true;\n\t\tsuper.startUse();\n\t}\n\n\t@Override\n\tpublic void stopUse(double duration) {\n\t\tif (!inUse) {\n\t\t\tthrow new IllegalStateException();\n\t\t}\n\t\tinUse = false;\n\t\tsuper.stopUse(duration);\n\t}\n}", "filename": "SecureBattery.java" }, { "content": "package a05.sol1;\n\npublic abstract class AbstractBattery implements Battery {\n\t\n\tprivate double energy;\n\t\n\t@Override\n\tpublic double getEnergy() {\n\t\treturn this.energy;\n\t}\n\n\tprotected void setEnergy(double energy) {\n\t\tthis.energy = energy;\n\t}\n}", "filename": "AbstractBattery.java" }, { "content": "package a05.sol1;\n\npublic class BatteryDecorator extends AbstractBattery {\n\tprivate AbstractBattery base;\n\n\tpublic BatteryDecorator(AbstractBattery base) {\n\t\tthis.base = base;\n\t}\n\n\t@Override\n\tpublic void startUse() {\n\t\tthis.base.startUse();\n\t}\n\n\t@Override\n\tpublic void stopUse(double duration) {\n\t\tthis.base.stopUse(duration);\n\t}\n\n\t@Override\n\tpublic double getEnergy() {\n\t\treturn this.base.getEnergy();\n\t}\n\n\t@Override\n\tpublic void recharge() {\n\t\tthis.base.recharge();\n\t}\n\t\n\tprotected void setEnergy(double energy) {\n\t\tthis.base.setEnergy(energy);\n\t}\n}", "filename": "BatteryDecorator.java" }, { "content": "package a05.sol1;\n\nimport java.util.function.BiFunction;\n\npublic class BatteryFactoryImpl implements BatteryFactory {\n\n\tprivate static class AbstractBatteryFactory {\n\t\t\n\t\tpublic static AbstractBattery defaulBattery() {\n\t\t\treturn simple((e, d) -> e - d);\n\t\t}\n\n\t\tpublic static AbstractBattery simple(BiFunction<Double, Double, Double> function) {\n\t\t\treturn new SimpleBattery(function);\n\t\t}\n\n\t\tpublic static AbstractBattery secure(AbstractBattery base) {\n\t\t\treturn new SecureBattery(base);\n\t\t}\n\n\t\tpublic static AbstractBattery rechargable(AbstractBattery base) {\n\t\t\treturn new RechargableBattery(base);\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic Battery createSimpleBattery() {\n\t\treturn AbstractBatteryFactory.defaulBattery();\n\t}\n\n\t@Override\n\tpublic Battery createSimpleBatteryByDrop(double energyPerDurationDrop) {\n\t\treturn AbstractBatteryFactory.simple((e, d) -> e - d * energyPerDurationDrop);\n\t}\n\n\t@Override\n\tpublic Battery createSimpleBatteryWithExponentialDrop() {\n\t\treturn AbstractBatteryFactory.simple((e, d) -> e / 2);\n\t}\n\n\t@Override\n\tpublic Battery createSecureBattery() {\n\t\treturn AbstractBatteryFactory.secure(AbstractBatteryFactory.defaulBattery());\n\t}\n\n\t@Override\n\tpublic Battery createRechargeableBattery() {\n\t\treturn AbstractBatteryFactory.rechargable(AbstractBatteryFactory.defaulBattery());\n\t}\n\n\t@Override\n\tpublic Battery createSecureAndRechargeableBattery() {\n\t\treturn AbstractBatteryFactory.rechargable(AbstractBatteryFactory.secure(AbstractBatteryFactory.defaulBattery()));\n\t}\n\n}", "filename": "BatteryFactoryImpl.java" } ]
{ "components": { "imports": "package a05.sol1;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertTrue;\nimport static org.junit.jupiter.api.Assertions.fail;\n\nimport java.util.List;\n\nimport org.junit.jupiter.api.Assertions;", "private_init": "\t/*\n\t * Implement the batteryFactory interface as indicated in the initFactory method\n\t * below. Create a factory for Batteries, i.e.\n\t * batteries that discharge as they are used.\n\t * \n\t * The comment on the provided interfaces, and the test methods below\n\t * constitute the necessary explanation of the problem.\n\t * \n\t * WARNING: It is considered mandatory to avoid the main repetitions\n\t * \n\t * The following are considered optional for the purpose of being able to correct\n\t * the exercise, but still contribute to achieving the totality of the\n\t * score:\n\t * \n\t * - implementation of the last test, called optionalTestXYZ (related to\n\t * the BatteryFactory.createSecureAndRechargableBattery method)\n\t * \n\t * - good design of the solution, in particular using succinct code\n\t * \n\t * Remove the comment from the initFactory method.\n\t * \n\t * Scoring indications:\n\t * \n\t * - correctness of the mandatory part: 10 points\n\t * \n\t * - correctness of the optional part: 4 points\n\t * \n\t * - quality of the solution: 3 points\n\t * \n\t */\n\n\tprivate BatteryFactory factory = null;\n\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.factory = new BatteryFactoryImpl();\n\t}\n\t\n\tprivate static final double PRECISION = 0.01; // required when asserting equality of booleans\n\n\t\n\t/**\n\t * This methods checks that battery reaches energy level1 after drop1 use, and level2 after further drop2 use\n\t */\n\tprivate void basicChecks(Battery battery, double drop1, double level1, double drop2, double level2) {\n\t\tassertEquals(1.0, battery.getEnergy(), PRECISION);\n\t\tbattery.startUse();\n\t\tbattery.stopUse(drop1);\n\t\tassertEquals(level1, battery.getEnergy(), PRECISION);\n\t\tbattery.startUse();\n\t\tbattery.stopUse(drop2);\n\t\tassertEquals(level2, battery.getEnergy(), PRECISION);\n\t}", "test_functions": [ "\[email protected]\n\tpublic void testSimple() {\n\t\tvar battery = this.factory.createSimpleBattery();\n\t\t// used 0.2, remains at 0.8; used 0.3, remains at 0.5\n\t\tbasicChecks(battery, 0.2, 0.8, 0.3, 0.5); \n\t\tbattery.recharge(); // recharge has no effect\n\t\tassertEquals(0.5, battery.getEnergy(), PRECISION);\n\t\tbattery.startUse(); // no effect, no exception\n\t\tbattery.startUse(); // no effect, no exception\n\t\tbattery.stopUse(0.1); // drops 0.1, no exception\n\t\tbattery.stopUse(0.1); // drops 0.1, no exception\n\t\tassertEquals(0.3, battery.getEnergy(), PRECISION);\n\t\tbattery.stopUse(0.5); // reaches 0 without problems\n\t\tassertEquals(0.0, battery.getEnergy(), PRECISION);\n\t}", "\[email protected]\n\tpublic void testByDrop1() {\n\t\t// given the 2.0 rate, it means that with duration 0.1 it drops 0.2 of energy\n\t\tvar battery = this.factory.createSimpleBatteryByDrop(2.0);\n\t\t// used 0.1, remains at 0.8; used 0.15, remains at 0.5\n\t\tbasicChecks(battery, 0.1, 0.8, 0.15, 0.5);\n\t\tbattery.recharge(); // recharge has no effect\n\t\tassertEquals(0.5, battery.getEnergy(), PRECISION);\n\t\tbattery.startUse(); // no effect, no exception\n\t\tbattery.startUse(); // no effect, no exception\n\t\tbattery.stopUse(0.05); // drops 0.1, no exception\n\t\tbattery.stopUse(0.05); // drops 0.1, no exception\n\t\tassertEquals(0.3, battery.getEnergy(), PRECISION);\n\t\tbattery.stopUse(0.25); // reaches 0 without problems\n\t\tassertEquals(0.0, battery.getEnergy(), PRECISION);\n\t}", "\[email protected]\n\tpublic void testExponential() {\n\t\tvar battery = this.factory.createSimpleBatteryWithExponentialDrop();\n\t\t// used, remains at 0.5; used, remains at 0.25\n\t\tbasicChecks(battery, 1.0, 0.5, 1.0, 0.25);\n\t\tbattery.recharge(); // recharge has no effect\n\t\tassertEquals(0.25, battery.getEnergy(), PRECISION);\n\t\t// no exception are raised as for SimpleBattery above\n\t}", "\[email protected]\n\tpublic void testSecure() {\n\t\tvar battery = this.factory.createSecureBattery();\n\t\t// As with simpleBattery\n\t\tbasicChecks(battery, 0.2, 0.8, 0.3, 0.5);\n\t\tbattery.recharge(); // recharge has no effect\n\t\tassertEquals(0.5, battery.getEnergy(), PRECISION);\n\t\t// stopping with starting gives exception \n\t\tAssertions.assertThrows(IllegalStateException.class, ()->battery.stopUse(0.2));\n\t\tbattery.startUse();\n\t\t// starting if already started gives exception\n\t\tAssertions.assertThrows(IllegalStateException.class, ()->battery.startUse());\n\t\tbattery.stopUse(0.6);\n\t\t// starting with energy 0.0 gives exception\n\t\tAssertions.assertThrows(IllegalStateException.class, ()->battery.startUse());\n\t}", "\[email protected]\n\tpublic void testRecharge() {\n\t\tvar battery = this.factory.createRechargableBattery();\n\t\t// As with simpleBattery\n\t\tbasicChecks(battery, 0.2, 0.8, 0.3, 0.5);\n\t\tbattery.recharge(); // to 1\n\t\tassertEquals(1.0, battery.getEnergy(), PRECISION);\n\t\tbattery.startUse();\n\t\tbattery.stopUse(0.5);\n\t\tbattery.recharge(); // to 0.99\n\t\tassertEquals(0.99, battery.getEnergy(), PRECISION);\n\t\tbattery.startUse();\n\t\tbattery.stopUse(0.5);\n\t\tbattery.recharge(); // to 0.98\n\t\tassertEquals(0.98, battery.getEnergy(), PRECISION);\n\t\t\n\t}", "\[email protected]\n\tpublic void optionalTestSecureAndRechargableBattery() {\n\t\t// Altogther simple, rechargable and secure\n\t\tvar battery = this.factory.createSecureAndRechargableBattery();\n\t\tbasicChecks(battery, 0.2, 0.8, 0.3, 0.5);\n\t\tbattery.recharge();\n\t\tassertEquals(1.0, battery.getEnergy(), PRECISION);\n\t\tbattery.startUse();\n\t\tbattery.stopUse(0.5);\n\t\tbattery.recharge();\n\t\tassertEquals(0.99, battery.getEnergy(), PRECISION);\n\t\tbattery.startUse();\n\t\tbattery.stopUse(0.5);\n\t\tbattery.recharge();\n\t\tassertEquals(0.98, battery.getEnergy(), PRECISION);\n\t\tAssertions.assertThrows(IllegalStateException.class, ()->battery.stopUse(0.2));\n\t\tbattery.startUse();\n\t\tAssertions.assertThrows(IllegalStateException.class, ()->battery.startUse());\n\t\tbattery.stopUse(1.0);\n\t\tAssertions.assertThrows(IllegalStateException.class, ()->battery.startUse());\n\t}" ] }, "content": "package a05.sol1;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertTrue;\nimport static org.junit.jupiter.api.Assertions.fail;\n\nimport java.util.List;\n\nimport org.junit.jupiter.api.Assertions;\n\npublic class Test {\n\n\t/*\n\t * Implement the batteryFactory interface as indicated in the initFactory method\n\t * below. Create a factory for Batteries, i.e.\n\t * batteries that discharge as they are used.\n\t * \n\t * The comment on the provided interfaces, and the test methods below\n\t * constitute the necessary explanation of the problem.\n\t * \n\t * WARNING: It is considered mandatory to avoid the main repetitions\n\t * \n\t * The following are considered optional for the purpose of being able to correct\n\t * the exercise, but still contribute to achieving the totality of the\n\t * score:\n\t * \n\t * - implementation of the last test, called optionalTestXYZ (related to\n\t * the BatteryFactory.createSecureAndRechargeableBattery method)\n\t * \n\t * - good design of the solution, in particular using succinct code\n\t * \n\t * Remove the comment from the initFactory method.\n\t * \n\t * Scoring indications:\n\t * \n\t * - correctness of the mandatory part: 10 points\n\t * \n\t * - correctness of the optional part: 4 points\n\t * \n\t * - quality of the solution: 3 points\n\t * \n\t */\n\n\tprivate BatteryFactory factory = null;\n\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.factory = new BatteryFactoryImpl();\n\t}\n\t\n\tprivate static final double PRECISION = 0.01; // required when asserting equality of booleans\n\n\t\n\t/**\n\t * This methods checks that battery reaches energy level1 after drop1 use, and level2 after further drop2 use\n\t */\n\tprivate void basicChecks(Battery battery, double drop1, double level1, double drop2, double level2) {\n\t\tassertEquals(1.0, battery.getEnergy(), PRECISION);\n\t\tbattery.startUse();\n\t\tbattery.stopUse(drop1);\n\t\tassertEquals(level1, battery.getEnergy(), PRECISION);\n\t\tbattery.startUse();\n\t\tbattery.stopUse(drop2);\n\t\tassertEquals(level2, battery.getEnergy(), PRECISION);\n\t}\n\t\n\[email protected]\n\tpublic void testSimple() {\n\t\tvar battery = this.factory.createSimpleBattery();\n\t\t// used 0.2, remains at 0.8; used 0.3, remains at 0.5\n\t\tbasicChecks(battery, 0.2, 0.8, 0.3, 0.5); \n\t\tbattery.recharge(); // recharge has no effect\n\t\tassertEquals(0.5, battery.getEnergy(), PRECISION);\n\t\tbattery.startUse(); // no effect, no exception\n\t\tbattery.startUse(); // no effect, no exception\n\t\tbattery.stopUse(0.1); // drops 0.1, no exception\n\t\tbattery.stopUse(0.1); // drops 0.1, no exception\n\t\tassertEquals(0.3, battery.getEnergy(), PRECISION);\n\t\tbattery.stopUse(0.5); // reaches 0 without problems\n\t\tassertEquals(0.0, battery.getEnergy(), PRECISION);\n\t}\n\t\n\[email protected]\n\tpublic void testByDrop1() {\n\t\t// given the 2.0 rate, it means that with duration 0.1 it drops 0.2 of energy\n\t\tvar battery = this.factory.createSimpleBatteryByDrop(2.0);\n\t\t// used 0.1, remains at 0.8; used 0.15, remains at 0.5\n\t\tbasicChecks(battery, 0.1, 0.8, 0.15, 0.5);\n\t\tbattery.recharge(); // recharge has no effect\n\t\tassertEquals(0.5, battery.getEnergy(), PRECISION);\n\t\tbattery.startUse(); // no effect, no exception\n\t\tbattery.startUse(); // no effect, no exception\n\t\tbattery.stopUse(0.05); // drops 0.1, no exception\n\t\tbattery.stopUse(0.05); // drops 0.1, no exception\n\t\tassertEquals(0.3, battery.getEnergy(), PRECISION);\n\t\tbattery.stopUse(0.25); // reaches 0 without problems\n\t\tassertEquals(0.0, battery.getEnergy(), PRECISION);\n\t}\n\t\n\[email protected]\n\tpublic void testExponential() {\n\t\tvar battery = this.factory.createSimpleBatteryWithExponentialDrop();\n\t\t// used, remains at 0.5; used, remains at 0.25\n\t\tbasicChecks(battery, 1.0, 0.5, 1.0, 0.25);\n\t\tbattery.recharge(); // recharge has no effect\n\t\tassertEquals(0.25, battery.getEnergy(), PRECISION);\n\t\t// no exception are raised as for SimpleBattery above\n\t}\n\t\n\[email protected]\n\tpublic void testSecure() {\n\t\tvar battery = this.factory.createSecureBattery();\n\t\t// As with simpleBattery\n\t\tbasicChecks(battery, 0.2, 0.8, 0.3, 0.5);\n\t\tbattery.recharge(); // recharge has no effect\n\t\tassertEquals(0.5, battery.getEnergy(), PRECISION);\n\t\t// stopping with starting gives exception \n\t\tAssertions.assertThrows(IllegalStateException.class, ()->battery.stopUse(0.2));\n\t\tbattery.startUse();\n\t\t// starting if already started gives exception\n\t\tAssertions.assertThrows(IllegalStateException.class, ()->battery.startUse());\n\t\tbattery.stopUse(0.6);\n\t\t// starting with energy 0.0 gives exception\n\t\tAssertions.assertThrows(IllegalStateException.class, ()->battery.startUse());\n\t}\n\t\n\[email protected]\n\tpublic void testRecharge() {\n\t\tvar battery = this.factory.createRechargeableBattery();\n\t\t// As with simpleBattery\n\t\tbasicChecks(battery, 0.2, 0.8, 0.3, 0.5);\n\t\tbattery.recharge(); // to 1\n\t\tassertEquals(1.0, battery.getEnergy(), PRECISION);\n\t\tbattery.startUse();\n\t\tbattery.stopUse(0.5);\n\t\tbattery.recharge(); // to 0.99\n\t\tassertEquals(0.99, battery.getEnergy(), PRECISION);\n\t\tbattery.startUse();\n\t\tbattery.stopUse(0.5);\n\t\tbattery.recharge(); // to 0.98\n\t\tassertEquals(0.98, battery.getEnergy(), PRECISION);\n\t\t\n\t}\n\t\n\[email protected]\n\tpublic void optionalTestSecureAndRechargableBattery() {\n\t\t// Altogther simple, rechargable and secure\n\t\tvar battery = this.factory.createSecureAndRechargeableBattery();\n\t\tbasicChecks(battery, 0.2, 0.8, 0.3, 0.5);\n\t\tbattery.recharge();\n\t\tassertEquals(1.0, battery.getEnergy(), PRECISION);\n\t\tbattery.startUse();\n\t\tbattery.stopUse(0.5);\n\t\tbattery.recharge();\n\t\tassertEquals(0.99, battery.getEnergy(), PRECISION);\n\t\tbattery.startUse();\n\t\tbattery.stopUse(0.5);\n\t\tbattery.recharge();\n\t\tassertEquals(0.98, battery.getEnergy(), PRECISION);\n\t\tAssertions.assertThrows(IllegalStateException.class, ()->battery.stopUse(0.2));\n\t\tbattery.startUse();\n\t\tAssertions.assertThrows(IllegalStateException.class, ()->battery.startUse());\n\t\tbattery.stopUse(1.0);\n\t\tAssertions.assertThrows(IllegalStateException.class, ()->battery.startUse());\n\t}\n\t\n\t\n}", "filename": "Test.java" }
2020
a03c
[ { "content": "package a03c.sol1;\n\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.function.BiFunction;\n\n\n\npublic interface TableFactory {\n\t\n\t\n\t<R,C,V> Table<R,C,V> fromMap(Map<Pair<R,C>,V> map);\n\t\n\t\n\t<R,C,V> Table<R,C,V> fromFunction(Set<R> rows, Set<C> columns, BiFunction<R,C,V> valueFunction);\n\t\n\t\n\t<G> Table<G,G,Boolean> graph(Set<Pair<G,G>> edges);\n\t\n\t\n\t<V> Table<Integer,Integer,V> squareMatrix(V[][] values);\n\n}", "filename": "TableFactory.java" }, { "content": "package a03c.sol1;\n\nimport java.util.Map;\nimport java.util.Optional;\nimport java.util.Set;\n\n\npublic interface Table<R,C,V> {\n\t\n\t\n\tSet<R> rows();\n\t\n\t\n\tSet<C> columns();\n\n\t\n\tMap<C,Map<R,V>> asColumnMap();\n\t\n\t\n\tMap<R,Map<C,V>> asRowMap();\n\t\n\t\n\tOptional<V> getValue(R row, C column);\n\t\n\t\n\tvoid putValue(R row, C column, V value);\n}", "filename": "Table.java" }, { "content": "package a03c.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 a03c.sol1;\n\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Optional;\nimport java.util.Set;\nimport java.util.function.BiFunction;\nimport java.util.stream.Collectors;\nimport java.util.stream.IntStream;\nimport java.util.stream.Stream;\n\npublic class TableFactoryImpl implements TableFactory {\n\t\n\tstatic class TableImpl<R,C,V> implements Table<R,C,V>{\n\t\tprivate final Map<Pair<R, C>, V> map;\n\t\tprivate final Set<R> rows;\n\t\tprivate final Set<C> columns;\n\t\t\n\n\t\tpublic TableImpl(Map<Pair<R, C>, V> map) {\n\t\t\tthis.map = new HashMap<>(map);\n\t\t\tthis.rows = this.map.keySet().stream().map(Pair::getX).collect(Collectors.toSet());\n\t\t\tthis.columns = this.map.keySet().stream().map(Pair::getY).collect(Collectors.toSet());\n\t\t}\n\n\t\t@Override\n\t\tpublic Map<C, Map<R, V>> asColumnMap() {\n\t\t\treturn this.columns.stream().collect(\n\t\t\t\t\tCollectors.toMap(c->c, \n\t\t\t\t\t\t\tc-> this.rows.\n\t\t\t\t\t\t\tstream().\n\t\t\t\t\t\t\tmap(r->new Pair<>(r,this.getValue(r,c))).\n\t\t\t\t\t\t\tfilter(p->p.getY().isPresent()).\n\t\t\t\t\t\t\tcollect(Collectors.toMap(p->p.getX(), p->p.getY().get()))));\n\t\t}\n\n\t\t@Override\n\t\tpublic Map<R, Map<C, V>> asRowMap() {\n\t\t\treturn this.rows.stream().collect(\n\t\t\t\t\tCollectors.toMap(r->r, \n\t\t\t\t\t\t\tr-> this.columns.\n\t\t\t\t\t\t\tstream().\n\t\t\t\t\t\t\tmap(c->new Pair<>(c,this.getValue(r,c))).\n\t\t\t\t\t\t\tfilter(p->p.getY().isPresent()).\n\t\t\t\t\t\t\tcollect(Collectors.toMap(p->p.getX(), p->p.getY().get()))));\n\t\t}\n\n\t\t@Override\n\t\tpublic Optional<V> getValue(R row, C column) {\n\t\t\treturn Optional.ofNullable(this.map.get(new Pair<>(row,column)));\n\t\t}\n\n\t\t@Override\n\t\tpublic void putValue(R row, C column, V value) {\n\t\t\tthis.map.put(new Pair<>(row,column), value);\n\t\t}\n\n\t\t@Override\n\t\tpublic Set<R> rows() {\n\t\t\treturn this.rows;\n\t\t}\n\n\t\t@Override\n\t\tpublic Set<C> columns() {\n\t\t\treturn this.columns;\n\t\t}\n\t\t\n\t\t\n\t}\n\n\t@Override\n\tpublic <R, C, V> Table<R, C, V> fromMap(Map<Pair<R, C>, V> map) {\n\t\treturn new TableImpl<>(map);\n\t}\n\n\t@Override\n\tpublic <R, C, V> Table<R, C, V> fromFunction(Set<R> rows, Set<C> columns, BiFunction<R, C, V> valueFunction) {\n\t\treturn new TableImpl<>(\n\t\t\t\trows.stream().flatMap(r -> columns.stream().\n\t\t\t\t\t\tmap(c -> new Pair<>(r,c))).\n\t\t\t\t\t\tcollect(Collectors.toMap(p->p, p->valueFunction.apply(p.getX(),p.getY()))));\n\t}\n\n\t@Override\n\tpublic <G> Table<G, G, Boolean> graph(Set<Pair<G, G>> edges) {\n\t\tfinal Set<G> nodes = edges.stream().flatMap(p -> Stream.of(p.getX(),p.getY())).collect(Collectors.toSet());\n\t\treturn this.fromFunction(nodes,nodes,(n,m)->edges.contains(new Pair<>(n,m)));\n\t}\n\n\t@Override\n\tpublic <V> Table<Integer, Integer, V> squareMatrix(V[][] values) {\n\t\tfinal Set<Integer> rows = Stream.iterate(0,x->x+1).limit(values.length).collect(Collectors.toSet());\n\t\treturn this.fromFunction(rows,rows,(n,m)->values[n][m]);\n\t}\n\n}", "filename": "TableFactoryImpl.java" } ]
{ "components": { "imports": "package a03c.sol1;\n\nimport static org.junit.Assert.*;\n\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Optional;\nimport java.util.Set;\nimport java.util.stream.Collectors;\nimport java.util.stream.Stream;", "private_init": "\t/*\n\t * Implement the TableFactory interface as indicated in the initFactory method\n\t * below. Create a factory for Table<R,C,V>, which are data structures that model\n\t * a table with information for each row (type R) and each column (type C): so each cell\n\t * is identified by a row value, a column value, and has a value (type V) inserted in the cell.\n\t * \n\t * The comment on the provided interfaces, and the test methods below\n\t * constitute the necessary explanation of the problem.\n\t * \n\t * The following are considered optional for the purpose of correcting\n\t * the exercise, but still contribute to achieving the total\n\t * score:\n\t * \n\t * - implementation of the tests called optionalTestXYZ (related to Table.asColumnMap and TableFactory.squareMatrix)\n\t * \n\t * - good design of the solution, in particular using concise code without repetitions\n\t * \n\t * Remove the comment from the initFactory method.\n\t * \n\t * Scoring indications:\n\t * \n\t * - correctness of the mandatory part: 10 points\n\t * \n\t * - correctness of the optional part: 4 points\n\t * \n\t * - quality of the solution: 3 points\n\t * \n\t */\n\n\tprivate TableFactory factory = null;\n\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.factory = new TableFactoryImpl();\n\t}\n\n\t// lab and project: an enum used in some tests\n\tenum Esame {\n\t\tLAB, PROJECT\n\t};", "test_functions": [ "\[email protected]\n\tpublic void testFromMap() {\n\t\tMap<Pair<String, Esame>, Integer> map = new HashMap<>();\n\t\tmap.put(new Pair<>(\"Rossi\", Esame.LAB), 20);\n\t\tmap.put(new Pair<>(\"Rossi\", Esame.PROJECT), 28);\n\t\tmap.put(new Pair<>(\"Verdi\", Esame.LAB), 20);\n\t\tmap.put(new Pair<>(\"Casadei\", Esame.LAB), 19);\n\t\tmap.put(new Pair<>(\"Grandi\", Esame.PROJECT), 19);\n\t\t// a table that associates people (rows) and exam type (columns), to a grade\n\t\tvar table = this.factory.fromMap(map);\n\t\tassertEquals(Set.of(Esame.LAB, Esame.PROJECT), table.columns()); // columns\n\t\tassertEquals(Set.of(\"Rossi\", \"Verdi\", \"Casadei\", \"Grandi\"), table.rows()); // rows\n\t\tassertEquals(Optional.empty(), table.getValue(\"Casadei\", Esame.PROJECT)); // what did Casadei get in the project\n\t\tassertEquals(Optional.of(19), table.getValue(\"Casadei\", Esame.LAB)); // what did Casadei get in the lab exam\n\n\t\ttable.putValue(\"Casadei\", Esame.PROJECT, 25); // now Casadei got 25 in the project\n\t\tassertEquals(Optional.of(25), table.getValue(\"Casadei\", Esame.PROJECT));\n\n\t\tassertEquals(Map.of(Esame.LAB, 20, Esame.PROJECT, 28), table.asRowMap().get(\"Rossi\")); // Rossi's grades\n\t\tassertEquals(Map.of(Esame.LAB, 20), table.asRowMap().get(\"Verdi\")); // Verdi's grades\n\t\tassertEquals(Map.of(Esame.PROJECT, 19), table.asRowMap().get(\"Grandi\")); // Grandi's grades\n\n\t}", "\[email protected]\n\tpublic void testFromFunction() {\n\t\t// the classic \"*\" table, a table with integers (0..9) in rows and columns, and multiplications in cells\n\t\tfinal Set<Integer> range = Stream.iterate(0,x->x+1).limit(10).collect(Collectors.toSet());\n\t\tfinal Table<Integer,Integer,Integer> table = this.factory.fromFunction(range, range, (i,j)->i*j);\n\t\t\n\t\tassertEquals(range, table.columns()); // columns\n\t\tassertEquals(range, table.rows()); // rows\n\t\tassertEquals(Optional.empty(), table.getValue(100,100)); // 100,100 has no cell\n\t\tassertEquals(Optional.of(54), table.getValue(6,9)); // row 6, column 9 --> value 54\n\t\t\n\t\tassertEquals(Set.of(0,5,10,15,20,25,30,35,40,45),new HashSet<>(table.asRowMap().get(5).values())); // 5th row, the 5 times table\n\t}", "\[email protected]\n\tpublic void testGraph() {\n\t\tfinal Set<Pair<String,String>> edges = Set.of(\n\t\t\t\tnew Pair<>(\"a\",\"b\"), // a->b\n\t\t\t\tnew Pair<>(\"b\",\"c\"), // b->c\n\t\t\t\tnew Pair<>(\"c\",\"d\"), // c->d\n\t\t\t\tnew Pair<>(\"d\",\"a\"), // d->a\n\t\t\t\tnew Pair<>(\"a\",\"a\") // a->a\n\t\t);\n\t\t// a table that represents the graph above (with true where there is an edge, false where there is no edge)\n\t\tfinal Table<String,String,Boolean> table = this.factory.graph(edges);\n\t\t\n\t\tassertEquals(Set.of(\"a\",\"b\",\"c\",\"d\"), table.columns()); // columns\n\t\tassertEquals(Set.of(\"a\",\"b\",\"c\",\"d\"), table.rows()); // rows\n\t\t\n\t\tassertEquals(Optional.of(true), table.getValue(\"a\",\"b\")); // is there an edge from a to b?\n\t\tassertEquals(Optional.of(false), table.getValue(\"a\",\"c\")); // is there an edge from a to c?\n\t\t\n\t\tassertEquals(4,table.asRowMap().size()); // 4 rows\n\t\tassertEquals(4,table.asRowMap().get(\"a\").size()); // the first row has 4 columns\n\t\tassertTrue(table.asRowMap().get(\"a\").get(\"b\"));\n\t\tassertFalse(table.asRowMap().get(\"a\").get(\"c\"));\n\t}", "\[email protected]\n\tpublic void optionalTestArray() {\n\t\tfinal String[][] array = new String[][] {\n\t\t\tnew String[] {\"a\",\"b\"}", "\[email protected]\n\tpublic void optionalTestColumnMap() {\n\t\t// like the example in testFromMap... but testing asColumnMap\n\t\tMap<Pair<String, Esame>, Integer> map = new HashMap<>();\n\t\tmap.put(new Pair<>(\"Rossi\", Esame.LAB), 20);\n\t\tmap.put(new Pair<>(\"Rossi\", Esame.PROJECT), 28);\n\t\tmap.put(new Pair<>(\"Verdi\", Esame.LAB), 20);\n\t\tmap.put(new Pair<>(\"Casadei\", Esame.LAB), 19);\n\t\tmap.put(new Pair<>(\"Grandi\", Esame.PROJECT), 19);\n\t\tvar table = this.factory.fromMap(map);\n\n\t\tassertEquals(Map.of(\"Rossi\", 20, \"Verdi\", 20, \"Casadei\", 19), table.asColumnMap().get(Esame.LAB));\n\t\tassertEquals(Map.of(\"Rossi\", 28, \"Grandi\", 19), table.asColumnMap().get(Esame.PROJECT));\n\t\t\n\t\t\n\t\t// like the example in testGraph... but testing asColumnMap\n\t\tfinal Set<Pair<String,String>> edges = Set.of(\n\t\t\t\tnew Pair<>(\"a\",\"b\"),\n\t\t\t\tnew Pair<>(\"b\",\"c\"),\n\t\t\t\tnew Pair<>(\"c\",\"d\"),\n\t\t\t\tnew Pair<>(\"d\",\"a\"),\n\t\t\t\tnew Pair<>(\"a\",\"a\")\n\t\t);\n\t\tfinal Table<String,String,Boolean> table2 = this.factory.graph(edges);\n\t\t\n\t\t\n\t\tassertEquals(4,table2.asColumnMap().size());\n\t\tassertEquals(4,table2.asColumnMap().get(\"a\").size());\n\t\tassertTrue(table2.asColumnMap().get(\"a\").get(\"d\"));\n\t\tassertTrue(table2.asColumnMap().get(\"a\").get(\"a\"));\n\t\tassertFalse(table2.asColumnMap().get(\"a\").get(\"b\"));\n\t}" ] }, "content": "package a03c.sol1;\n\nimport static org.junit.Assert.*;\n\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Optional;\nimport java.util.Set;\nimport java.util.stream.Collectors;\nimport java.util.stream.Stream;\n\npublic class Test {\n\n\t/*\n\t * Implement the TableFactory interface as indicated in the initFactory method\n\t * below. Create a factory for Table<R,C,V>, which are data structures that model\n\t * a table with information for each row (type R) and each column (type C): so each cell\n\t * is identified by a row value, a column value, and has a value (type V) inserted in the cell.\n\t * \n\t * The comment on the provided interfaces, and the test methods below\n\t * constitute the necessary explanation of the problem.\n\t * \n\t * The following are considered optional for the purpose of correcting\n\t * the exercise, but still contribute to achieving the total\n\t * score:\n\t * \n\t * - implementation of the tests called optionalTestXYZ (related to Table.asColumnMap and TableFactory.squareMatrix)\n\t * \n\t * - good design of the solution, in particular using concise code without repetitions\n\t * \n\t * Remove the comment from the initFactory method.\n\t * \n\t * Scoring indications:\n\t * \n\t * - correctness of the mandatory part: 10 points\n\t * \n\t * - correctness of the optional part: 4 points\n\t * \n\t * - quality of the solution: 3 points\n\t * \n\t */\n\n\tprivate TableFactory factory = null;\n\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.factory = new TableFactoryImpl();\n\t}\n\n\t// lab and project: an enum used in some tests\n\tenum Esame {\n\t\tLAB, PROJECT\n\t};\n\n\[email protected]\n\tpublic void testFromMap() {\n\t\tMap<Pair<String, Esame>, Integer> map = new HashMap<>();\n\t\tmap.put(new Pair<>(\"Rossi\", Esame.LAB), 20);\n\t\tmap.put(new Pair<>(\"Rossi\", Esame.PROJECT), 28);\n\t\tmap.put(new Pair<>(\"Verdi\", Esame.LAB), 20);\n\t\tmap.put(new Pair<>(\"Casadei\", Esame.LAB), 19);\n\t\tmap.put(new Pair<>(\"Grandi\", Esame.PROJECT), 19);\n\t\t// a table that associates people (rows) and exam type (columns), to a grade\n\t\tvar table = this.factory.fromMap(map);\n\t\tassertEquals(Set.of(Esame.LAB, Esame.PROJECT), table.columns()); // columns\n\t\tassertEquals(Set.of(\"Rossi\", \"Verdi\", \"Casadei\", \"Grandi\"), table.rows()); // rows\n\t\tassertEquals(Optional.empty(), table.getValue(\"Casadei\", Esame.PROJECT)); // what did Casadei get in the project\n\t\tassertEquals(Optional.of(19), table.getValue(\"Casadei\", Esame.LAB)); // what did Casadei get in the lab exam\n\n\t\ttable.putValue(\"Casadei\", Esame.PROJECT, 25); // now Casadei got 25 in the project\n\t\tassertEquals(Optional.of(25), table.getValue(\"Casadei\", Esame.PROJECT));\n\n\t\tassertEquals(Map.of(Esame.LAB, 20, Esame.PROJECT, 28), table.asRowMap().get(\"Rossi\")); // Rossi's grades\n\t\tassertEquals(Map.of(Esame.LAB, 20), table.asRowMap().get(\"Verdi\")); // Verdi's grades\n\t\tassertEquals(Map.of(Esame.PROJECT, 19), table.asRowMap().get(\"Grandi\")); // Grandi's grades\n\n\t}\n\t\n\[email protected]\n\tpublic void testFromFunction() {\n\t\t// the classic \"*\" table, a table with integers (0..9) in rows and columns, and multiplications in cells\n\t\tfinal Set<Integer> range = Stream.iterate(0,x->x+1).limit(10).collect(Collectors.toSet());\n\t\tfinal Table<Integer,Integer,Integer> table = this.factory.fromFunction(range, range, (i,j)->i*j);\n\t\t\n\t\tassertEquals(range, table.columns()); // columns\n\t\tassertEquals(range, table.rows()); // rows\n\t\tassertEquals(Optional.empty(), table.getValue(100,100)); // 100,100 has no cell\n\t\tassertEquals(Optional.of(54), table.getValue(6,9)); // row 6, column 9 --> value 54\n\t\t\n\t\tassertEquals(Set.of(0,5,10,15,20,25,30,35,40,45),new HashSet<>(table.asRowMap().get(5).values())); // 5th row, the 5 times table\n\t}\n\t\n\[email protected]\n\tpublic void testGraph() {\n\t\tfinal Set<Pair<String,String>> edges = Set.of(\n\t\t\t\tnew Pair<>(\"a\",\"b\"), // a->b\n\t\t\t\tnew Pair<>(\"b\",\"c\"), // b->c\n\t\t\t\tnew Pair<>(\"c\",\"d\"), // c->d\n\t\t\t\tnew Pair<>(\"d\",\"a\"), // d->a\n\t\t\t\tnew Pair<>(\"a\",\"a\") // a->a\n\t\t);\n\t\t// a table that represents the graph above (with true where there is an edge, false where there is no edge)\n\t\tfinal Table<String,String,Boolean> table = this.factory.graph(edges);\n\t\t\n\t\tassertEquals(Set.of(\"a\",\"b\",\"c\",\"d\"), table.columns()); // columns\n\t\tassertEquals(Set.of(\"a\",\"b\",\"c\",\"d\"), table.rows()); // rows\n\t\t\n\t\tassertEquals(Optional.of(true), table.getValue(\"a\",\"b\")); // is there an edge from a to b?\n\t\tassertEquals(Optional.of(false), table.getValue(\"a\",\"c\")); // is there an edge from a to c?\n\t\t\n\t\tassertEquals(4,table.asRowMap().size()); // 4 rows\n\t\tassertEquals(4,table.asRowMap().get(\"a\").size()); // the first row has 4 columns\n\t\tassertTrue(table.asRowMap().get(\"a\").get(\"b\"));\n\t\tassertFalse(table.asRowMap().get(\"a\").get(\"c\"));\n\t}\n\t\n\[email protected]\n\tpublic void optionalTestArray() {\n\t\tfinal String[][] array = new String[][] {\n\t\t\tnew String[] {\"a\",\"b\"},\n\t\t\tnew String[] {\"c\",\"d\"}\n\t\t};\n\t\t// a table that represents a matrix, with increasing numbers (indices) in rows and columns\n\t\tfinal Table<Integer,Integer,String> table = this.factory.squareMatrix(array);\n\t\t\n\t\tassertEquals(Set.of(0,1), table.columns());\n\t\tassertEquals(Set.of(0,1), table.rows());\n\t\t\n\t\tassertEquals(Optional.of(\"a\"), table.getValue(0,0));\n\t\tassertEquals(Optional.of(\"b\"), table.getValue(0,1));\n\t\tassertEquals(Optional.of(\"c\"), table.getValue(1,0));\n\t\tassertEquals(Optional.of(\"d\"), table.getValue(1,1));\n\t\t\n\t\tassertEquals(2,table.asRowMap().size());\n\t\tassertEquals(2,table.asRowMap().get(0).size());\n\t\tassertEquals(\"a\", table.asRowMap().get(0).get(0));\n\t\tassertEquals(\"b\", table.asRowMap().get(0).get(1));\n\t}\n\t\n\[email protected]\n\tpublic void optionalTestColumnMap() {\n\t\t// like the example in testFromMap... but testing asColumnMap\n\t\tMap<Pair<String, Esame>, Integer> map = new HashMap<>();\n\t\tmap.put(new Pair<>(\"Rossi\", Esame.LAB), 20);\n\t\tmap.put(new Pair<>(\"Rossi\", Esame.PROJECT), 28);\n\t\tmap.put(new Pair<>(\"Verdi\", Esame.LAB), 20);\n\t\tmap.put(new Pair<>(\"Casadei\", Esame.LAB), 19);\n\t\tmap.put(new Pair<>(\"Grandi\", Esame.PROJECT), 19);\n\t\tvar table = this.factory.fromMap(map);\n\n\t\tassertEquals(Map.of(\"Rossi\", 20, \"Verdi\", 20, \"Casadei\", 19), table.asColumnMap().get(Esame.LAB));\n\t\tassertEquals(Map.of(\"Rossi\", 28, \"Grandi\", 19), table.asColumnMap().get(Esame.PROJECT));\n\t\t\n\t\t\n\t\t// like the example in testGraph... but testing asColumnMap\n\t\tfinal Set<Pair<String,String>> edges = Set.of(\n\t\t\t\tnew Pair<>(\"a\",\"b\"),\n\t\t\t\tnew Pair<>(\"b\",\"c\"),\n\t\t\t\tnew Pair<>(\"c\",\"d\"),\n\t\t\t\tnew Pair<>(\"d\",\"a\"),\n\t\t\t\tnew Pair<>(\"a\",\"a\")\n\t\t);\n\t\tfinal Table<String,String,Boolean> table2 = this.factory.graph(edges);\n\t\t\n\t\t\n\t\tassertEquals(4,table2.asColumnMap().size());\n\t\tassertEquals(4,table2.asColumnMap().get(\"a\").size());\n\t\tassertTrue(table2.asColumnMap().get(\"a\").get(\"d\"));\n\t\tassertTrue(table2.asColumnMap().get(\"a\").get(\"a\"));\n\t\tassertFalse(table2.asColumnMap().get(\"a\").get(\"b\"));\n\t}\n\n\t\n\t\n}", "filename": "Test.java" }
2020
a03b
[ { "content": "package a03b.sol1;\n\nimport java.util.Set;\n\n\npublic interface Equivalence<X> {\n\t\n\t\n\tboolean areEquivalent(X x1, X x2);\n\t\n\t\n\tSet<X> domain();\n\t\n\t\n\tSet<X> equivalenceSet(X x);\n\n\t\n\tSet<Set<X>> partition();\n\t\n\t\n\tboolean smallerThan(Equivalence<X> eq);\n\t\t\n}", "filename": "Equivalence.java" }, { "content": "package a03b.sol1;\n\nimport java.util.Set;\nimport java.util.function.BiPredicate;\nimport java.util.function.Function;\n\n\npublic interface EquivalenceFactory {\n\t\n\t\n\t<X> Equivalence<X> fromPartition(Set<Set<X>> partition);\n\t\n\t\n\t<X> Equivalence<X> fromPredicate(Set<X> domain, BiPredicate<X,X> predicate);\n\t\n\t\n\t<X> Equivalence<X> fromPairs(Set<Pair<X,X>> pairs);\n\t\n\t\n\t<X,Y> Equivalence<X> fromFunction(Set<X> domain, Function<X,Y> function);\n}", "filename": "EquivalenceFactory.java" }, { "content": "package a03b.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 a03b.sol1;\n\nimport java.util.Collections;\nimport java.util.HashSet;\nimport java.util.Set;\nimport java.util.function.BiPredicate;\nimport java.util.function.Function;\nimport java.util.stream.Collectors;\nimport java.util.stream.Stream;\n\npublic class EquivalenceFactoryImpl implements EquivalenceFactory {\n\n\t@Override\n\tpublic <X> Equivalence<X> fromPartition(Set<Set<X>> partition) {\n\t\tvar domain = partition.stream().flatMap(s -> s.stream()).collect(Collectors.toSet());\n\t\treturn fromFunction(domain, x -> partition.stream().filter(s -> s.contains(x)).findAny().get());\n\t}\n\n\t@Override\n\tpublic <X> Equivalence<X> fromPredicate(Set<X> domain, BiPredicate<X,X> predicate){\n\t\tSet<Set<X>> partition = new HashSet<>();\n\t\tfor (final var x: domain) {\n\t\t\tvar optSet = partition.stream().filter(s -> predicate.test(s.iterator().next(),x)).findAny();\n\t\t\tif (optSet.isEmpty()) {\n\t\t\t\tpartition.add(new HashSet<>(Collections.singleton(x)));\n\t\t\t} else {\n\t\t\t\toptSet.get().add(x);\n\t\t\t}\n\t\t}\n\t\treturn fromPartition(partition);\n\t}\n\t\n\t@Override\n\tpublic <X> Equivalence<X> fromPairs(Set<Pair<X, X>> pairs) {\n\t\tvar domain = pairs.stream().flatMap(p -> Stream.of(p.getX(),p.getY())).collect(Collectors.toSet());\n\t\treturn fromPredicate(domain, (x,y)-> pairs.stream().anyMatch(p -> p.equals(new Pair<>(x,y))));\n\t}\n\n\t@Override\n\tpublic <X, Y> Equivalence<X> fromFunction(Set<X> domain, Function<X, Y> function) {\n\t\treturn new Equivalence<>() {\n\n\t\t\t@Override\n\t\t\tpublic boolean areEquivalent(X x1, X x2) {\n\t\t\t\treturn domain.contains(x1) && domain.contains(x2) && function.apply(x1).equals(function.apply(x2));\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Set<X> domain() {\n\t\t\t\treturn domain;\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Set<X> equivalenceSet(X x) {\n\t\t\t\treturn domain.stream().filter(y -> areEquivalent(x,y)).collect(Collectors.toSet());\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Set<Set<X>> partition() {\n\t\t\t\treturn Set.copyOf(domain.stream().collect(Collectors.groupingBy(function,Collectors.toSet())).values());\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic boolean smallerThan(Equivalence<X> equivalence) {\n\t\t\t\tvar thatPartition = equivalence.partition();\n\t\t\t\treturn this.partition().stream().allMatch(s -> thatPartition.stream().anyMatch(s2 -> s2.containsAll(s)));\n\t\t\t}\n\t\t\t\n\t\t};\n\t}\n}", "filename": "EquivalenceFactoryImpl.java" } ]
{ "components": { "imports": "package a03b.sol1;\n\nimport static org.junit.Assert.*;\n\nimport java.util.Set;", "private_init": "\t/*\n\t * Implement the EquivalenceFactory interface as indicated in the initFactory method\n\t * below. Implement a factory for Equivalence objects, i.e., objects that implement\n\t * binary equivalence relations between values. Remember that an equivalence relation defines\n\t * in practice a partition on the values, defining subgroups (which do not intersect): the elements\n\t * of each subgroup are considered \"equivalent to each other,\" the others are not.\n\t * \n\t * The comments on the provided interfaces, and the test methods below\n\t * constitute the necessary explanation of the problem.\n\t * \n\t * The following are considered optional for the possibility of correcting\n\t * the exercise, but still contribute to achieving the totality of the\n\t * score:\n\t * \n\t * - implementation of the tests called optionalTestXYZ (related to\n\t * Equivalence.smallerThan and EquivalenceFactory.fromFunction)\n\t * \n\t * - good design of the solution, in particular using succinct code without repetitions\n\t * \n\t * Remove the comment from the initFactory method.\n\t * \n\t * Scoring indications:\n\t * \n\t * - correctness of the mandatory part: 10 points\n\t * \n\t * - correctness of the optional part: 4 points\n\t * \n\t * - quality of the solution: 3 points\n\t * \n\t */\n\n\tprivate EquivalenceFactory factory = null;\n\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.factory = new EquivalenceFactoryImpl();\n\t}", "test_functions": [ "\[email protected]\n\tpublic void testFromPartition() {\n\t\t// equivalence on [0..9], \"we are equivalent if we have the same remainder when dividing by 3\"\n\t\tSet<Set<Integer>> partition = Set.of(\n\t\t\t\tSet.of(0,3,6,9), // first equivalence set\n\t\t\t\tSet.of(1,4,7),\t// second equivalence set\n\t\t\t\tSet.of(2,5,8)\t// third equivalence set\n\t\t);\n\t\tEquivalence<Integer> equivalence = this.factory.fromPartition(partition);\n\t\t\n\t\tassertEquals(partition, equivalence.partition());\n\t\t\n\t\t// set of values\n\t\tassertEquals(Set.of(0,1,2,3,4,5,6,7,8,9), equivalence.domain());\n\t\t\n\t\tassertEquals(Set.of(0,3,6,9), equivalence.equivalenceSet(6)); // who is equivalent to 6?\n\t\tassertEquals(Set.of(1,4,7), equivalence.equivalenceSet(1)); // who is equivalent to 1?\n\t\t\n\t\tassertTrue(equivalence.areEquivalent(0, 6)); // are 0 and 6 equivalent?\n\t\tassertTrue(equivalence.areEquivalent(1, 4)); // ..\n\t\tassertTrue(equivalence.areEquivalent(5, 8));\n\t\t\n\t\tassertFalse(equivalence.areEquivalent(5, 7));\n\t\tassertFalse(equivalence.areEquivalent(0, 1));\n\t}", "\[email protected]\n\tpublic void testFromPredicate() {\n\t\tSet<String> domain = Set.of(\"\",\"a\",\"b\",\"c\",\"ab\",\"ac\",\"bc\",\"abc\");\n\t\t// we are equivalent if we have the same length\n\t\tEquivalence<String> equivalence = this.factory.fromPredicate(domain, (s1,s2)->s1.length()==s2.length());\n\t\t\n\t\tassertEquals(domain, equivalence.domain());\n\t\t\n\t\t// four equivalence sets\n\t\tassertEquals(\n\t\t\t\tSet.of(\n\t\t\t\t\t\tSet.of(\"\"), Set.of(\"a\",\"b\",\"c\"),Set.of(\"ab\",\"ac\",\"bc\"),Set.of(\"abc\")\n\t\t\t\t),equivalence.partition());\n\t\t\n\t\t\t\t\n\t\tassertEquals(Set.of(\"a\",\"b\",\"c\"), equivalence.equivalenceSet(\"a\")); // who is equivalent to \"a\"?\n\t\tassertEquals(Set.of(\"abc\"), equivalence.equivalenceSet(\"abc\")); // ...\n\t\t\n\t\tassertTrue(equivalence.areEquivalent(\"a\", \"c\")); // are \"a\" and \"c\" equivalent?\n\t\tassertTrue(equivalence.areEquivalent(\"ab\", \"ac\")); // ..\n\t\t\n\t\tassertFalse(equivalence.areEquivalent(\"ab\", \"abc\"));\n\t\tassertFalse(equivalence.areEquivalent(\"\", \"a\"));\n\t}", "\[email protected]\n\tpublic void testFromPairs() {\n\t\t// we are equivalent if as a pair we are in this set...\n\t\tSet<Pair<String,String>> pairs = Set.of(\n\t\t\t\tnew Pair<>(\"a\",\"a\"),\n\t\t\t\tnew Pair<>(\"a\",\"b\"),\n\t\t\t\tnew Pair<>(\"b\",\"a\"),\n\t\t\t\tnew Pair<>(\"b\",\"b\"),\n\t\t\t\tnew Pair<>(\"aa\",\"bb\"),\n\t\t\t\tnew Pair<>(\"bb\",\"aa\"),\n\t\t\t\tnew Pair<>(\"aa\",\"aa\"),\n\t\t\t\tnew Pair<>(\"bb\",\"bb\"));\n\t\tEquivalence<String> equivalence = this.factory.fromPairs(pairs);\n\t\t\n\t\t// domain\n\t\tassertEquals(Set.of(\"a\",\"b\",\"aa\",\"bb\"), equivalence.domain());\n\t\t\n\t\t// two equivalence sets\n\t\tassertEquals(Set.of(Set.of(\"aa\",\"bb\"), Set.of(\"a\",\"b\")),equivalence.partition());\n\t\t\t\t\n\t\tassertEquals(Set.of(\"a\",\"b\"), equivalence.equivalenceSet(\"a\"));\n\t\tassertEquals(Set.of(\"bb\",\"aa\"), equivalence.equivalenceSet(\"bb\"));\n\t\t\n\t\tassertTrue(equivalence.areEquivalent(\"a\", \"b\"));\n\t\tassertTrue(equivalence.areEquivalent(\"aa\", \"bb\"));\n\t\t\n\t\tassertFalse(equivalence.areEquivalent(\"a\", \"aa\"));\n\t\tassertFalse(equivalence.areEquivalent(\"aa\", \"ab\"));\n\t}", "\[email protected]\n\tpublic void optionalTestFromFunction() {\n\t\tSet<String> domain = Set.of(\"\",\"a\",\"b\",\"c\",\"ab\",\"ac\",\"bc\",\"abc\");\n\t\t// we are equivalent if we have the same length...\n\t\t// test equivalent to testFromPredicate above\n\t\tEquivalence<String> equivalence = this.factory.fromFunction(domain, s->s.length());\n\t\t\n\t\tassertEquals(domain, equivalence.domain());\n\t\t\n\t\tassertEquals(\n\t\t\t\tSet.of(\n\t\t\t\t\t\tSet.of(\"\"), Set.of(\"a\",\"b\",\"c\"),Set.of(\"ab\",\"ac\",\"bc\"),Set.of(\"abc\")\n\t\t\t\t),equivalence.partition());\n\t\t\t\t\n\t\tassertEquals(Set.of(\"a\",\"b\",\"c\"), equivalence.equivalenceSet(\"a\"));\n\t\tassertEquals(Set.of(\"abc\"), equivalence.equivalenceSet(\"abc\"));\n\t\t\n\t\tassertTrue(equivalence.areEquivalent(\"a\", \"c\"));\n\t\tassertTrue(equivalence.areEquivalent(\"ab\", \"ac\"));\n\t\t\n\t\tassertFalse(equivalence.areEquivalent(\"ab\", \"abc\"));\n\t\tassertFalse(equivalence.areEquivalent(\"\", \"a\"));\n\t}", "\[email protected]\n\tpublic void optionalTestSmaller() {\n\t\tSet<Set<Integer>> partition = Set.of(\n\t\t\t\tSet.of(0,3,6,9),\n\t\t\t\tSet.of(1,4,7),\n\t\t\t\tSet.of(2,5,8)\n\t\t);\n\t\tEquivalence<Integer> equivalence = this.factory.fromPartition(partition);\n\t\t\n\t\tSet<Set<Integer>> partition2 = Set.of(\n\t\t\t\tSet.of(0,3),\n\t\t\t\tSet.of(6,9),\n\t\t\t\tSet.of(1,4),\n\t\t\t\tSet.of(7),\n\t\t\t\tSet.of(2,5),\n\t\t\t\tSet.of(8)\n\t\t);\n\t\tEquivalence<Integer> equivalence2 = this.factory.fromPartition(partition2);\n\t\t\n\t\tSet<Set<Integer>> partition3 = Set.of(\n\t\t\t\tSet.of(0,3,7),\n\t\t\t\tSet.of(6,9),\n\t\t\t\tSet.of(1,4),\n\t\t\t\tSet.of(2,5),\n\t\t\t\tSet.of(8)\n\t\t);\n\t\tEquivalence<Integer> equivalence3 = this.factory.fromPartition(partition3);\n\t\t// eq2 is obtained by \"splitting the sets\" of eq, and is therefore finer, i.e., \"smaller\", etc. for the others\n\t\tassertTrue(equivalence2.smallerThan(equivalence));\n\t\tassertTrue(equivalence2.smallerThan(equivalence3));\n\t\t\n\t\tassertFalse(equivalence3.smallerThan(equivalence2));\n\t\tassertFalse(equivalence3.smallerThan(equivalence2));\n\t\tassertFalse(equivalence.smallerThan(equivalence3));\n\t}" ] }, "content": "package a03b.sol1;\n\nimport static org.junit.Assert.*;\n\nimport java.util.Set;\n\npublic class Test {\n\n\t/*\n\t * Implement the EquivalenceFactory interface as indicated in the initFactory method\n\t * below. Implement a factory for Equivalence objects, i.e., objects that implement\n\t * binary equivalence relations between values. Remember that an equivalence relation defines\n\t * in practice a partition on the values, defining subgroups (which do not intersect): the elements\n\t * of each subgroup are considered \"equivalent to each other,\" the others are not.\n\t * \n\t * The comments on the provided interfaces, and the test methods below\n\t * constitute the necessary explanation of the problem.\n\t * \n\t * The following are considered optional for the possibility of correcting\n\t * the exercise, but still contribute to achieving the totality of the\n\t * score:\n\t * \n\t * - implementation of the tests called optionalTestXYZ (related to\n\t * Equivalence.smallerThan and EquivalenceFactory.fromFunction)\n\t * \n\t * - good design of the solution, in particular using succinct code without repetitions\n\t * \n\t * Remove the comment from the initFactory method.\n\t * \n\t * Scoring indications:\n\t * \n\t * - correctness of the mandatory part: 10 points\n\t * \n\t * - correctness of the optional part: 4 points\n\t * \n\t * - quality of the solution: 3 points\n\t * \n\t */\n\n\tprivate EquivalenceFactory factory = null;\n\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.factory = new EquivalenceFactoryImpl();\n\t}\n\t\n\[email protected]\n\tpublic void testFromPartition() {\n\t\t// equivalence on [0..9], \"we are equivalent if we have the same remainder when dividing by 3\"\n\t\tSet<Set<Integer>> partition = Set.of(\n\t\t\t\tSet.of(0,3,6,9), // first equivalence set\n\t\t\t\tSet.of(1,4,7),\t// second equivalence set\n\t\t\t\tSet.of(2,5,8)\t// third equivalence set\n\t\t);\n\t\tEquivalence<Integer> equivalence = this.factory.fromPartition(partition);\n\t\t\n\t\tassertEquals(partition, equivalence.partition());\n\t\t\n\t\t// set of values\n\t\tassertEquals(Set.of(0,1,2,3,4,5,6,7,8,9), equivalence.domain());\n\t\t\n\t\tassertEquals(Set.of(0,3,6,9), equivalence.equivalenceSet(6)); // who is equivalent to 6?\n\t\tassertEquals(Set.of(1,4,7), equivalence.equivalenceSet(1)); // who is equivalent to 1?\n\t\t\n\t\tassertTrue(equivalence.areEquivalent(0, 6)); // are 0 and 6 equivalent?\n\t\tassertTrue(equivalence.areEquivalent(1, 4)); // ..\n\t\tassertTrue(equivalence.areEquivalent(5, 8));\n\t\t\n\t\tassertFalse(equivalence.areEquivalent(5, 7));\n\t\tassertFalse(equivalence.areEquivalent(0, 1));\n\t}\n\t\n\[email protected]\n\tpublic void testFromPredicate() {\n\t\tSet<String> domain = Set.of(\"\",\"a\",\"b\",\"c\",\"ab\",\"ac\",\"bc\",\"abc\");\n\t\t// we are equivalent if we have the same length\n\t\tEquivalence<String> equivalence = this.factory.fromPredicate(domain, (s1,s2)->s1.length()==s2.length());\n\t\t\n\t\tassertEquals(domain, equivalence.domain());\n\t\t\n\t\t// four equivalence sets\n\t\tassertEquals(\n\t\t\t\tSet.of(\n\t\t\t\t\t\tSet.of(\"\"), Set.of(\"a\",\"b\",\"c\"),Set.of(\"ab\",\"ac\",\"bc\"),Set.of(\"abc\")\n\t\t\t\t),equivalence.partition());\n\t\t\n\t\t\t\t\n\t\tassertEquals(Set.of(\"a\",\"b\",\"c\"), equivalence.equivalenceSet(\"a\")); // who is equivalent to \"a\"?\n\t\tassertEquals(Set.of(\"abc\"), equivalence.equivalenceSet(\"abc\")); // ...\n\t\t\n\t\tassertTrue(equivalence.areEquivalent(\"a\", \"c\")); // are \"a\" and \"c\" equivalent?\n\t\tassertTrue(equivalence.areEquivalent(\"ab\", \"ac\")); // ..\n\t\t\n\t\tassertFalse(equivalence.areEquivalent(\"ab\", \"abc\"));\n\t\tassertFalse(equivalence.areEquivalent(\"\", \"a\"));\n\t}\n\t\n\[email protected]\n\tpublic void testFromPairs() {\n\t\t// we are equivalent if as a pair we are in this set...\n\t\tSet<Pair<String,String>> pairs = Set.of(\n\t\t\t\tnew Pair<>(\"a\",\"a\"),\n\t\t\t\tnew Pair<>(\"a\",\"b\"),\n\t\t\t\tnew Pair<>(\"b\",\"a\"),\n\t\t\t\tnew Pair<>(\"b\",\"b\"),\n\t\t\t\tnew Pair<>(\"aa\",\"bb\"),\n\t\t\t\tnew Pair<>(\"bb\",\"aa\"),\n\t\t\t\tnew Pair<>(\"aa\",\"aa\"),\n\t\t\t\tnew Pair<>(\"bb\",\"bb\"));\n\t\tEquivalence<String> equivalence = this.factory.fromPairs(pairs);\n\t\t\n\t\t// domain\n\t\tassertEquals(Set.of(\"a\",\"b\",\"aa\",\"bb\"), equivalence.domain());\n\t\t\n\t\t// two equivalence sets\n\t\tassertEquals(Set.of(Set.of(\"aa\",\"bb\"), Set.of(\"a\",\"b\")),equivalence.partition());\n\t\t\t\t\n\t\tassertEquals(Set.of(\"a\",\"b\"), equivalence.equivalenceSet(\"a\"));\n\t\tassertEquals(Set.of(\"bb\",\"aa\"), equivalence.equivalenceSet(\"bb\"));\n\t\t\n\t\tassertTrue(equivalence.areEquivalent(\"a\", \"b\"));\n\t\tassertTrue(equivalence.areEquivalent(\"aa\", \"bb\"));\n\t\t\n\t\tassertFalse(equivalence.areEquivalent(\"a\", \"aa\"));\n\t\tassertFalse(equivalence.areEquivalent(\"aa\", \"ab\"));\n\t}\n\t\n\[email protected]\n\tpublic void optionalTestFromFunction() {\n\t\tSet<String> domain = Set.of(\"\",\"a\",\"b\",\"c\",\"ab\",\"ac\",\"bc\",\"abc\");\n\t\t// we are equivalent if we have the same length...\n\t\t// test equivalent to testFromPredicate above\n\t\tEquivalence<String> equivalence = this.factory.fromFunction(domain, s->s.length());\n\t\t\n\t\tassertEquals(domain, equivalence.domain());\n\t\t\n\t\tassertEquals(\n\t\t\t\tSet.of(\n\t\t\t\t\t\tSet.of(\"\"), Set.of(\"a\",\"b\",\"c\"),Set.of(\"ab\",\"ac\",\"bc\"),Set.of(\"abc\")\n\t\t\t\t),equivalence.partition());\n\t\t\t\t\n\t\tassertEquals(Set.of(\"a\",\"b\",\"c\"), equivalence.equivalenceSet(\"a\"));\n\t\tassertEquals(Set.of(\"abc\"), equivalence.equivalenceSet(\"abc\"));\n\t\t\n\t\tassertTrue(equivalence.areEquivalent(\"a\", \"c\"));\n\t\tassertTrue(equivalence.areEquivalent(\"ab\", \"ac\"));\n\t\t\n\t\tassertFalse(equivalence.areEquivalent(\"ab\", \"abc\"));\n\t\tassertFalse(equivalence.areEquivalent(\"\", \"a\"));\n\t}\n\t\n\t\n\[email protected]\n\tpublic void optionalTestSmaller() {\n\t\tSet<Set<Integer>> partition = Set.of(\n\t\t\t\tSet.of(0,3,6,9),\n\t\t\t\tSet.of(1,4,7),\n\t\t\t\tSet.of(2,5,8)\n\t\t);\n\t\tEquivalence<Integer> equivalence = this.factory.fromPartition(partition);\n\t\t\n\t\tSet<Set<Integer>> partition2 = Set.of(\n\t\t\t\tSet.of(0,3),\n\t\t\t\tSet.of(6,9),\n\t\t\t\tSet.of(1,4),\n\t\t\t\tSet.of(7),\n\t\t\t\tSet.of(2,5),\n\t\t\t\tSet.of(8)\n\t\t);\n\t\tEquivalence<Integer> equivalence2 = this.factory.fromPartition(partition2);\n\t\t\n\t\tSet<Set<Integer>> partition3 = Set.of(\n\t\t\t\tSet.of(0,3,7),\n\t\t\t\tSet.of(6,9),\n\t\t\t\tSet.of(1,4),\n\t\t\t\tSet.of(2,5),\n\t\t\t\tSet.of(8)\n\t\t);\n\t\tEquivalence<Integer> equivalence3 = this.factory.fromPartition(partition3);\n\t\t// eq2 is obtained by \"splitting the sets\" of eq, and is therefore finer, i.e., \"smaller\", etc. for the others\n\t\tassertTrue(equivalence2.smallerThan(equivalence));\n\t\tassertTrue(equivalence2.smallerThan(equivalence3));\n\t\t\n\t\tassertFalse(equivalence3.smallerThan(equivalence2));\n\t\tassertFalse(equivalence3.smallerThan(equivalence2));\n\t\tassertFalse(equivalence.smallerThan(equivalence3));\n\t}\n}", "filename": "Test.java" }
2020
a02c
[ { "content": "package a02c.sol1;\n\nimport java.util.List;\n\n\npublic interface ListSplitter<X>{\n\t\t\n\t\n\tList<List<X>> split(List<X> list);\n\n}", "filename": "ListSplitter.java" }, { "content": "package a02c.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 a02c.sol1;\n\nimport java.util.function.Predicate;\n\n\npublic interface ListSplitterFactory {\n\t\n\t\n\t<X> ListSplitter<X> asPairs();\n\t\n\t\n\t<X> ListSplitter<X> asTriplets();\n\t\n\t\n\t<X> ListSplitter<X> asTripletsWithRest();\n\t\n\t\n\t<X> ListSplitter<X> bySeparator(X separator);\n\t\n\t\n\t<X> ListSplitter<X> byPredicate(Predicate<X> predicate);\n\n}", "filename": "ListSplitterFactory.java" } ]
[ { "content": "package a02c.sol1;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Optional;\nimport java.util.function.BiPredicate;\nimport java.util.function.Predicate;\nimport java.util.stream.Stream;\n\npublic class ListSplitterFactoryImpl implements ListSplitterFactory {\n\n\t/**\n\t * Typical strategy-based technique: all splitters can be obtained by this default one,\n\t * by proper functional arguments\n\t */\n\tprivate static class ListSplitterImpl<X> implements ListSplitter<X> {\n\n\t\tprivate final BiPredicate<List<X>, Optional<X>> predicate;\n\t\t\n\t\tpublic ListSplitterImpl(BiPredicate<List<X>, Optional<X>> predicate) {\n\t\t\tthis.predicate = predicate;\n\t\t}\n\n\t\t@Override\n\t\tpublic List<List<X>> split(List<X> list) {\n\t\t\tList<X> accumulator = new ArrayList<>();\n\t\t\tfinal List<List<X>> output = new ArrayList<>();\n\t\t\tfor (final var x: list) {\n\t\t\t\tif (predicate.test(accumulator,Optional.of(x))) {\n\t\t\t\t\toutput.add(accumulator);\n\t\t\t\t\taccumulator = new ArrayList<>();\n\t\t\t\t} \n\t\t\t\taccumulator.add(x);\n\t\t\t}\n\t\t\tif (predicate.test(accumulator, Optional.empty())) {\n\t\t\t\toutput.add(accumulator);\n\t\t\t}\n\t\t\treturn output;\n\t\t}\n\n\t}\n\n\t@Override\n\tpublic <X> ListSplitter<X> asPairs() {\n\t\treturn new ListSplitterImpl<>((acc,o)->acc.size()==2);\n\t}\n\n\t@Override\n\tpublic <X> ListSplitter<X> asTriplets() {\n\t\treturn new ListSplitterImpl<>((acc,o)->acc.size()==3);\n\t}\n\t\n\t@Override\n\tpublic <X> ListSplitter<X> asTripletsWithRest() {\n\t\treturn new ListSplitterImpl<>((acc,o)->o.isEmpty() || acc.size()==3);\n\t}\n\n\t@Override\n\tpublic <X> ListSplitter<X> bySeparator(X separator) {\n\t\treturn new ListSplitterImpl<>((acc,o)-> o.isEmpty() || (acc.size()==1 && acc.get(0).equals(separator)) || o.get().equals(separator));\n\t}\n\n\t@Override\n\tpublic <X> ListSplitter<X> byPredicate(Predicate<X> predicate) {\n\t\treturn new ListSplitterImpl<>((acc,o)-> o.isEmpty() || (acc.size()>0 && predicate.test(o.get()) == !predicate.test(acc.get(acc.size()-1))));\n\t}\n\n}", "filename": "ListSplitterFactoryImpl.java" } ]
{ "components": { "imports": "package a02c.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;\n\n/**\n * Consult the documentation of the ListSplitterFactory interface, which models\n * a factory for ListSplitter, which in turn models a transformer from lists to\n * lists of lists, which works by splitting the input list into several pieces.\n * \n * The comment on the provided interfaces, and the test methods below constitute the necessary \n * explanation of the problem.\n * \n * The following are considered optional for the purpose of being able to correct\n * the exercise, but still contribute to achieving the entirety of the\n * score: \n * - implementation of optional tests (named 'optionalTestXYZ', i.e. those relating to \n * ListSplitterFactory.byPredicate \n * - conciseness of the code and removal of all repetitions with appropriate use of patterns\n *\n * Remove the comment from the init method.\n * \n * Scoring indications:\n * - correctness of the mandatory part: 10 points\n * - correctness of the optional part: 4 points \n * - quality of the solution: 3 points\n * \n */", "private_init": "\tprivate ListSplitterFactory factory;\n\n\[email protected]\n\tpublic void init() {\n\t\tthis.factory = new ListSplitterFactoryImpl();\n\t}", "test_functions": [ "\[email protected]\n\tpublic void testAsPairs() {\n\t\t// splits into pairs, without \"remainder\"\n\t\tListSplitter<Integer> ls = this.factory.asPairs();\n\t\tassertEquals(List.of(List.of(1,2),List.of(3,4),List.of(5,6)),ls.split(List.of(1,2,3,4,5,6)));\n\t\tassertEquals(List.of(List.of(1,2),List.of(3,4),List.of(5,6)),ls.split(List.of(1,2,3,4,5,6,7)));\n\t}", "\[email protected]\n\tpublic void testAsTriplets() {\n\t\t// splits into triplets, without \"remainder\"\n\t\tListSplitter<Integer> ls = this.factory.asTriplets();\n\t\tassertEquals(List.of(List.of(1,2,3),List.of(4,5,6)),ls.split(List.of(1,2,3,4,5,6)));\n\t\tassertEquals(List.of(List.of(1,2,3),List.of(4,5,6)),ls.split(List.of(1,2,3,4,5,6,7,8)));\n\t}", "\[email protected]\n\tpublic void testAsTripletsWithRest() {\n\t\t// splits into triplets, with \"remainder\"\n\t\tListSplitter<Integer> ls = this.factory.asTripletsWithRest();\n\t\tassertEquals(List.of(List.of(1,2,3),List.of(4,5,6)),ls.split(List.of(1,2,3,4,5,6)));\n\t\tassertEquals(List.of(List.of(1,2,3),List.of(4,5,6),List.of(7,8)),ls.split(List.of(1,2,3,4,5,6,7,8)));\n\t}", "\[email protected]\n\tpublic void testBySeparator() {\n\t\t// splits at each separator\n\t\tListSplitter<String> ls = this.factory.bySeparator(\":\");\n\t\tassertEquals(List.of(List.of(\"a\",\"b\"),List.of(\":\"),List.of(\"c\",\"d\",\"e\"),List.of(\":\"),List.of(\"f\")),\n\t\t\t\tls.split(List.of(\"a\",\"b\",\":\",\"c\",\"d\",\"e\",\":\",\"f\")));\n\t}", "\[email protected]\n\tpublic void optionalTestByPredicate() {\n\t\t// splits at each change of predicate validity\n\t\tListSplitter<Integer> ls = this.factory.byPredicate(x -> x>0);\n\t\tassertEquals(List.of(List.of(1,2),List.of(-5,-6),List.of(3,4),List.of(-10)),\n\t\t\t\tls.split(List.of(1,2,-5,-6,3,4,-10)));\n\t}" ] }, "content": "package a02c.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;\n\n/**\n * Consult the documentation of the ListSplitterFactory interface, which models\n * a factory for ListSplitter, which in turn models a transformer from lists to\n * lists of lists, which works by splitting the input list into several pieces.\n * \n * The comment on the provided interfaces, and the test methods below constitute the necessary \n * explanation of the problem.\n * \n * The following are considered optional for the purpose of being able to correct\n * the exercise, but still contribute to achieving the entirety of the\n * score: \n * - implementation of optional tests (named 'optionalTestXYZ', i.e. those relating to \n * ListSplitterFactory.byPredicate \n * - conciseness of the code and removal of all repetitions with appropriate use of patterns\n *\n * Remove the comment from the init method.\n * \n * Scoring indications:\n * - correctness of the mandatory part: 10 points\n * - correctness of the optional part: 4 points \n * - quality of the solution: 3 points\n * \n */\n\npublic class Test {\n\n\tprivate ListSplitterFactory factory;\n\n\[email protected]\n\tpublic void init() {\n\t\tthis.factory = new ListSplitterFactoryImpl();\n\t}\n\n\[email protected]\n\tpublic void testAsPairs() {\n\t\t// splits into pairs, without \"remainder\"\n\t\tListSplitter<Integer> ls = this.factory.asPairs();\n\t\tassertEquals(List.of(List.of(1,2),List.of(3,4),List.of(5,6)),ls.split(List.of(1,2,3,4,5,6)));\n\t\tassertEquals(List.of(List.of(1,2),List.of(3,4),List.of(5,6)),ls.split(List.of(1,2,3,4,5,6,7)));\n\t}\n\t\n\[email protected]\n\tpublic void testAsTriplets() {\n\t\t// splits into triplets, without \"remainder\"\n\t\tListSplitter<Integer> ls = this.factory.asTriplets();\n\t\tassertEquals(List.of(List.of(1,2,3),List.of(4,5,6)),ls.split(List.of(1,2,3,4,5,6)));\n\t\tassertEquals(List.of(List.of(1,2,3),List.of(4,5,6)),ls.split(List.of(1,2,3,4,5,6,7,8)));\n\t}\n\t\n\[email protected]\n\tpublic void testAsTripletsWithRest() {\n\t\t// splits into triplets, with \"remainder\"\n\t\tListSplitter<Integer> ls = this.factory.asTripletsWithRest();\n\t\tassertEquals(List.of(List.of(1,2,3),List.of(4,5,6)),ls.split(List.of(1,2,3,4,5,6)));\n\t\tassertEquals(List.of(List.of(1,2,3),List.of(4,5,6),List.of(7,8)),ls.split(List.of(1,2,3,4,5,6,7,8)));\n\t}\n\t\n\[email protected]\n\tpublic void testBySeparator() {\n\t\t// splits at each separator\n\t\tListSplitter<String> ls = this.factory.bySeparator(\":\");\n\t\tassertEquals(List.of(List.of(\"a\",\"b\"),List.of(\":\"),List.of(\"c\",\"d\",\"e\"),List.of(\":\"),List.of(\"f\")),\n\t\t\t\tls.split(List.of(\"a\",\"b\",\":\",\"c\",\"d\",\"e\",\":\",\"f\")));\n\t}\n\t\n\[email protected]\n\tpublic void optionalTestByPredicate() {\n\t\t// splits at each change of predicate validity\n\t\tListSplitter<Integer> ls = this.factory.byPredicate(x -> x>0);\n\t\tassertEquals(List.of(List.of(1,2),List.of(-5,-6),List.of(3,4),List.of(-10)),\n\t\t\t\tls.split(List.of(1,2,-5,-6,3,4,-10)));\n\t}\n\t\n\t\n}", "filename": "Test.java" }
2020
a01b
[ { "content": "package a01b.sol1;\n\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.function.Function;\nimport java.util.function.Predicate;\n\n\n\npublic interface MathematicalFunctionsFactory {\n\t\n\t\n\t<A,B> MathematicalFunction<A,B> constant(Predicate<A> domainPredicate, B value);\n\t\n\t\n\t<A,B> MathematicalFunction<A,A> identity(Predicate<A> domainPredicate);\n\t\n\t\n\t<A,B> MathematicalFunction<A,B> fromFunction(Predicate<A> domainPredicate, Function<A,B> function);\n\t\n\t\n\t<A,B> MathematicalFunction<A,B> fromMap(Map<A,B> map);\n}", "filename": "MathematicalFunctionsFactory.java" }, { "content": "package a01b.sol1;\n\nimport java.util.Optional;\nimport java.util.Set;\n\n\npublic interface MathematicalFunction<A,B> {\n\t\n\t\n\tOptional<B> apply(A a);\n\t\n\t\n\tboolean inDomain(A a);\n\n\t\n\t<C> MathematicalFunction<A,C> composeWith(MathematicalFunction<B,C> f); \n\t\n\t\n\tMathematicalFunction<A,B> withUpdatedValue(A domainValue, B codomainValue);\n\t\n\t\n\tMathematicalFunction<A,B> restrict(Set<A> subDomain);\n\n}", "filename": "MathematicalFunction.java" } ]
[ { "content": "package a01b.sol1;\n\nimport java.util.Map;\nimport java.util.Optional;\nimport java.util.Set;\nimport java.util.function.Function;\nimport java.util.function.Predicate;\n\npublic class MathematicalFunctionsFactoryImpl implements MathematicalFunctionsFactory {\n\n\t@Override\n\tpublic <A, B> MathematicalFunction<A, B> constant(Predicate<A> domainPredicate, B value) {\n\t\treturn fromFunction(domainPredicate,a->value);\n\t}\n\n\t@Override\n\tpublic <A, B> MathematicalFunction<A, A> identity(Predicate<A> domainPredicate) {\n\t\treturn fromFunction(domainPredicate,a->a);\n\t}\n\t\n\t@Override\n\tpublic <A, B> MathematicalFunction<A, B> fromMap(Map<A, B> map) {\n\t\treturn fromFunction(map::containsKey, map::get);\n\t}\n\n\t@Override\n\tpublic <A, B> MathematicalFunction<A, B> fromFunction(Predicate<A> domainPredicate, Function<A, B> function) {\n\t\treturn new MathematicalFunction<A,B>(){\n\n\t\t\t@Override\n\t\t\tpublic Optional<B> apply(A a) {\n\t\t\t\treturn Optional.of(a).filter(this::inDomain).map(function::apply);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic boolean inDomain(A a) {\n\t\t\t\treturn domainPredicate.test(a);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic <C> MathematicalFunction<A, C> composeWith(MathematicalFunction<B, C> function2) {\n\t\t\t\treturn fromFunction(domainPredicate, a -> function2.apply(function.apply(a)).get());\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic MathematicalFunction<A, B> restrict(Set<A> subDomain) {\n\t\t\t\treturn fromFunction(a -> domainPredicate.test(a) && subDomain.contains(a), function);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic MathematicalFunction<A, B> withUpdatedValue(A domainValue, B codomainValue) {\n\t\t\t\treturn fromFunction(a -> domainPredicate.test(a) || a.equals(domainValue), \n\t\t\t\t\t\t a -> a.equals(domainValue) ? codomainValue: function.apply(a) );\n\t\t\t}\n\t\t};\n\t}\n\n}", "filename": "MathematicalFunctionsFactoryImpl.java" } ]
{ "components": { "imports": "package a01b.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;\n\n/**\n * Consult the documentation of the MathematicalFunctionFactor interface, which models\n * a factory for MathematicalFunction, which in turn models a mathematical function,\n * which maps elements of a domain (which could be infinite) to a codomain.\n * \n * The comments on the provided interfaces, and the test methods below constitute the necessary \n * explanation of the problem.\n * \n * The following are considered optional for the purpose of being able to correct\n * the exercise, but still contribute to achieving the totality of the\n * score: \n * - implementation of optional tests (named 'optionalTestXYZ', i.e. those related to \n * MathematicalFunction.restrict and MathematicalFunctionFactory.fromMap \n * - minimization of repetitions \n * - conciseness of the code\n *\n * Remove the comment from the init method.\n * \n * Scoring indications:\n * - correctness of the mandatory part: 10 points\n * - correctness of the optional part: 4 points (2 for restrict, 2 for fromMap) \n * - quality of the solution: 3 points\n * \n */", "private_init": "\tprivate MathematicalFunctionsFactory factory;\n\n\[email protected]\n\tpublic void init() {\n\t\tthis.factory = new MathematicalFunctionsFactoryImpl();\n\t}", "test_functions": [ "\[email protected]\n\tpublic void testBasicConstant() {\n\t\t// Function that associates the real number 1.0 to every integer in [0,1,2,...,10]\n\t\tMathematicalFunction<Integer, Double> constant = this.factory.constant(i -> i >= 0 && i <= 10, 1.0);\n\t\tassertTrue(constant.inDomain(0));\n\t\tassertTrue(constant.inDomain(1));\n\t\tassertTrue(constant.inDomain(2));\n\t\tassertTrue(constant.inDomain(10));\n\t\tassertFalse(constant.inDomain(11));\n\t\tassertFalse(constant.inDomain(-1));\n\t\tassertEquals(Optional.of(1.0), constant.apply(0));\n\t\tassertEquals(Optional.of(1.0), constant.apply(1));\n\t\tassertEquals(Optional.of(1.0), constant.apply(9));\n\t\tassertEquals(Optional.of(1.0), constant.apply(10));\n\t\tassertEquals(Optional.empty(), constant.apply(11));\n\t\tassertEquals(Optional.empty(), constant.apply(-1));\n\t}", "\[email protected]\n\tpublic void testBasicIdentity() {\n\t\t// Function that associates each integer in [0,1,2,...,10] with itself\n\t\tMathematicalFunction<Integer, Integer> constant = this.factory.identity(i -> i >= 0 && i <= 10);\n\t\tassertTrue(constant.inDomain(0));\n\t\tassertTrue(constant.inDomain(1));\n\t\tassertTrue(constant.inDomain(2));\n\t\tassertTrue(constant.inDomain(10));\n\t\tassertFalse(constant.inDomain(11));\n\t\tassertFalse(constant.inDomain(-1));\n\t\tassertEquals(Optional.of(0), constant.apply(0));\n\t\tassertEquals(Optional.of(1), constant.apply(1));\n\t\tassertEquals(Optional.of(9), constant.apply(9));\n\t\tassertEquals(Optional.of(10), constant.apply(10));\n\t\tassertEquals(Optional.empty(), constant.apply(11));\n\t\tassertEquals(Optional.empty(), constant.apply(-1));\n\t}", "\[email protected]\n\tpublic void testBasicFunction() {\n\t\t// Function that associates each integer 'i' in [0,1,2,...,10] with the integer 'i+1'\n\t\tMathematicalFunction<Double, Double> function = this.factory.fromFunction(i -> i >= 0 && i <= 10, i->i+1);\n\t\tassertTrue(function.inDomain(0.0));\n\t\tassertTrue(function.inDomain(1.5));\n\t\tassertTrue(function.inDomain(2.9));\n\t\tassertTrue(function.inDomain(9.99));\n\t\tassertFalse(function.inDomain(10.1));\n\t\tassertFalse(function.inDomain(-0.1));\n\t\tassertEquals(Optional.of(1.0), function.apply(0.0));\n\t\tassertEquals(Optional.of(2.5), function.apply(1.5));\n\t\tassertEquals(Optional.of(3.9), function.apply(2.9));\n\t\tassertEquals(Optional.of(10.99), function.apply(9.99));\n\t\tassertEquals(Optional.empty(), function.apply(10.1));\n\t\tassertEquals(Optional.empty(), function.apply(-0.1));\n\t}", "\[email protected]\n\tpublic void testBasicFunction2() {\n\t\t// Function that associates each integer 'i' (any) with the integer 'i+1'\n\t\tMathematicalFunction<Integer, Integer> function = this.factory.fromFunction(i -> true, i->i+1);\n\t\tassertTrue(function.inDomain(0));\n\t\tassertTrue(function.inDomain(1));\n\t\tassertTrue(function.inDomain(10000));\n\t\tassertTrue(function.inDomain(-20000));\n\t\tassertEquals(Optional.of(1), function.apply(0));\n\t\tassertEquals(Optional.of(3), function.apply(2));\n\t\tassertEquals(Optional.of(10001), function.apply(10000));\n\t}", "\[email protected]\n\tpublic void testWithUpdated1() {\n\t\t// takes a constant and updates it with the mapping 0->1\n\t\t// Gives a function that is 0 everywhere, except at 0, where it gives 1 (a kind of dirac delta)\"\n\t\tMathematicalFunction<Integer, Integer> constant = this.factory.constant(a->true, 0);\n\t\tMathematicalFunction<Integer, Integer> diracLike= constant.withUpdatedValue(0, 1);\n\t\tassertTrue(diracLike.inDomain(0));\n\t\tassertTrue(diracLike.inDomain(1));\n\t\tassertTrue(diracLike.inDomain(2));\n\t\tassertTrue(diracLike.inDomain(-10000));\n\t\tassertEquals(Optional.of(1), diracLike.apply(0));\n\t\tassertEquals(Optional.of(0), diracLike.apply(1));\n\t\tassertEquals(Optional.of(0), diracLike.apply(2));\n\t\tassertEquals(Optional.of(0), diracLike.apply(-10000));\n\t}", "\[email protected]\n\tpublic void testWithUpdated2() {\n\t\t// Takes the function \"+1\" on the domain [0,..,10], and adds the mapping -10->-10 to it\n\t\tMathematicalFunction<Double, Double> function = this.factory.fromFunction(i -> i >= 0 && i <= 10, i->i+1);\n\t\tMathematicalFunction<Double, Double> strange = function.withUpdatedValue(0.0, 0.0).withUpdatedValue(-10.0, -10.0);\n\t\tassertTrue(strange.inDomain(0.0));\n\t\tassertTrue(strange.inDomain(5.0));\n\t\tassertTrue(strange.inDomain(10.0));\n\t\tassertTrue(strange.inDomain(-10.0));\n\t\tassertFalse(strange.inDomain(-9.9));\n\t\tassertFalse(strange.inDomain(20.0));\n\t\tassertEquals(Optional.of(0.0), strange.apply(0.0));\n\t\tassertEquals(Optional.of(2.0), strange.apply(1.0));\n\t\tassertEquals(Optional.of(11.0), strange.apply(10.0));\n\t\tassertEquals(Optional.of(3.5), strange.apply(2.5));\n\t\tassertEquals(Optional.of(-10.0), strange.apply(-10.0));\n\t\tassertEquals(Optional.empty(), strange.apply(-9.9));\n\t\tassertEquals(Optional.empty(), strange.apply(11.0));\n\t}", "\[email protected]\n\tpublic void testComposition1() {\n\t\t// Composes the constant 1 with the function \"+1\", giving the constant 2\n\t\tMathematicalFunction<Integer, Integer> f1 = this.factory.constant(a->true,1);\n\t\tMathematicalFunction<Integer, Integer> f2 = this.factory.fromFunction(a->true,i->i+1);\n\t\tMathematicalFunction<Integer, Integer> f3 = f1.composeWith(f2);\n\t\tassertTrue(f3.inDomain(0));\n\t\tassertTrue(f3.inDomain(1));\n\t\tassertTrue(f3.inDomain(2));\n\t\tassertTrue(f3.inDomain(-1));\n\t\tassertEquals(Optional.of(2), f3.apply(0));\n\t\tassertEquals(Optional.of(2), f3.apply(1));\n\t\tassertEquals(Optional.of(2), f3.apply(2));\n\t\tassertEquals(Optional.of(2), f3.apply(10));\n\t}", "\[email protected]\n\tpublic void testComposition2() {\n\t\t// Composes the function \"+1\" with the constant 1, giving the constant 1\n\t\tMathematicalFunction<Integer, Integer> f1 = this.factory.constant(a->true,1);\n\t\tMathematicalFunction<Integer, Integer> f2 = this.factory.fromFunction(a->true,i->i+1);\n\t\tMathematicalFunction<Integer, Integer> f3 = f2.composeWith(f1);\n\t\tassertTrue(f3.inDomain(0));\n\t\tassertTrue(f3.inDomain(1));\n\t\tassertTrue(f3.inDomain(2));\n\t\tassertTrue(f3.inDomain(-1));\n\t\tassertEquals(Optional.of(1), f3.apply(0));\n\t\tassertEquals(Optional.of(1), f3.apply(1));\n\t\tassertEquals(Optional.of(1), f3.apply(2));\n\t\tassertEquals(Optional.of(1), f3.apply(10));\n\t}", "\[email protected]\n\tpublic void optionalTestFromMap() {\n\t\tMap<Integer,String> map = new HashMap<>();\n\t\tmap.put(0, \"a\");\n\t\tmap.put(1, \"b\");\n\t\tmap.put(2, \"c\");\n\t\t// Function that associates each integer 'i' with a string 's', just like the map would\n\t\tMathematicalFunction<Integer, String> mapFunction = this.factory.fromMap(map);\n\t\tassertTrue(mapFunction.inDomain(0));\n\t\tassertTrue(mapFunction.inDomain(1));\n\t\tassertTrue(mapFunction.inDomain(2));\n\t\tassertFalse(mapFunction.inDomain(3));\n\t\tassertFalse(mapFunction.inDomain(-1));\n\t\tassertEquals(Optional.of(\"a\"), mapFunction.apply(0));\n\t\tassertEquals(Optional.of(\"b\"), mapFunction.apply(1));\n\t\tassertEquals(Optional.of(\"c\"), mapFunction.apply(2));\n\t\tassertEquals(Optional.empty(), mapFunction.apply(3));\n\t\tassertEquals(Optional.empty(), mapFunction.apply(-1));\n\t\tassertEquals(Optional.empty(), mapFunction.apply(-1));\n\t}", "\[email protected]\n\tpublic void optionalTestRestrict() {\n\t\t// takes a constant and restricts it to the domain with only the values 0,1,2,3\n\t\tMathematicalFunction<Integer, Integer> constant = this.factory.constant(a->true, 0);\n\t\tMathematicalFunction<Integer, Integer> fun = constant.restrict(Set.of(0,1,2,3));\n\t\tassertTrue(fun.inDomain(0));\n\t\tassertTrue(fun.inDomain(1));\n\t\tassertTrue(fun.inDomain(2));\n\t\tassertTrue(fun.inDomain(3));\n\t\tassertFalse(fun.inDomain(4));\n\t\tassertFalse(fun.inDomain(-1));\n\t\tassertEquals(Optional.of(0), fun.apply(0));\n\t\tassertEquals(Optional.of(0), fun.apply(1));\n\t\tassertEquals(Optional.of(0), fun.apply(2));\n\t\tassertEquals(Optional.empty(), fun.apply(-10000));\n\t}" ] }, "content": "package a01b.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;\n\n/**\n * Consult the documentation of the MathematicalFunctionFactor interface, which models\n * a factory for MathematicalFunction, which in turn models a mathematical function,\n * which maps elements of a domain (which could be infinite) to a codomain.\n * \n * The comments on the provided interfaces, and the test methods below constitute the necessary \n * explanation of the problem.\n * \n * The following are considered optional for the purpose of being able to correct\n * the exercise, but still contribute to achieving the totality of the\n * score: \n * - implementation of optional tests (named 'optionalTestXYZ', i.e. those related to \n * MathematicalFunction.restrict and MathematicalFunctionFactory.fromMap \n * - minimization of repetitions \n * - conciseness of the code\n *\n * Remove the comment from the init method.\n * \n * Scoring indications:\n * - correctness of the mandatory part: 10 points\n * - correctness of the optional part: 4 points (2 for restrict, 2 for fromMap) \n * - quality of the solution: 3 points\n * \n */\n\npublic class Test {\n\n\tprivate MathematicalFunctionsFactory factory;\n\n\[email protected]\n\tpublic void init() {\n\t\tthis.factory = new MathematicalFunctionsFactoryImpl();\n\t}\n\n\[email protected]\n\tpublic void testBasicConstant() {\n\t\t// Function that associates the real number 1.0 to every integer in [0,1,2,...,10]\n\t\tMathematicalFunction<Integer, Double> constant = this.factory.constant(i -> i >= 0 && i <= 10, 1.0);\n\t\tassertTrue(constant.inDomain(0));\n\t\tassertTrue(constant.inDomain(1));\n\t\tassertTrue(constant.inDomain(2));\n\t\tassertTrue(constant.inDomain(10));\n\t\tassertFalse(constant.inDomain(11));\n\t\tassertFalse(constant.inDomain(-1));\n\t\tassertEquals(Optional.of(1.0), constant.apply(0));\n\t\tassertEquals(Optional.of(1.0), constant.apply(1));\n\t\tassertEquals(Optional.of(1.0), constant.apply(9));\n\t\tassertEquals(Optional.of(1.0), constant.apply(10));\n\t\tassertEquals(Optional.empty(), constant.apply(11));\n\t\tassertEquals(Optional.empty(), constant.apply(-1));\n\t}\n\t\n\[email protected]\n\tpublic void testBasicIdentity() {\n\t\t// Function that associates each integer in [0,1,2,...,10] with itself\n\t\tMathematicalFunction<Integer, Integer> constant = this.factory.identity(i -> i >= 0 && i <= 10);\n\t\tassertTrue(constant.inDomain(0));\n\t\tassertTrue(constant.inDomain(1));\n\t\tassertTrue(constant.inDomain(2));\n\t\tassertTrue(constant.inDomain(10));\n\t\tassertFalse(constant.inDomain(11));\n\t\tassertFalse(constant.inDomain(-1));\n\t\tassertEquals(Optional.of(0), constant.apply(0));\n\t\tassertEquals(Optional.of(1), constant.apply(1));\n\t\tassertEquals(Optional.of(9), constant.apply(9));\n\t\tassertEquals(Optional.of(10), constant.apply(10));\n\t\tassertEquals(Optional.empty(), constant.apply(11));\n\t\tassertEquals(Optional.empty(), constant.apply(-1));\n\t}\n\t\n\[email protected]\n\tpublic void testBasicFunction() {\n\t\t// Function that associates each integer 'i' in [0,1,2,...,10] with the integer 'i+1'\n\t\tMathematicalFunction<Double, Double> function = this.factory.fromFunction(i -> i >= 0 && i <= 10, i->i+1);\n\t\tassertTrue(function.inDomain(0.0));\n\t\tassertTrue(function.inDomain(1.5));\n\t\tassertTrue(function.inDomain(2.9));\n\t\tassertTrue(function.inDomain(9.99));\n\t\tassertFalse(function.inDomain(10.1));\n\t\tassertFalse(function.inDomain(-0.1));\n\t\tassertEquals(Optional.of(1.0), function.apply(0.0));\n\t\tassertEquals(Optional.of(2.5), function.apply(1.5));\n\t\tassertEquals(Optional.of(3.9), function.apply(2.9));\n\t\tassertEquals(Optional.of(10.99), function.apply(9.99));\n\t\tassertEquals(Optional.empty(), function.apply(10.1));\n\t\tassertEquals(Optional.empty(), function.apply(-0.1));\n\t}\n\t\n\[email protected]\n\tpublic void testBasicFunction2() {\n\t\t// Function that associates each integer 'i' (any) with the integer 'i+1'\n\t\tMathematicalFunction<Integer, Integer> function = this.factory.fromFunction(i -> true, i->i+1);\n\t\tassertTrue(function.inDomain(0));\n\t\tassertTrue(function.inDomain(1));\n\t\tassertTrue(function.inDomain(10000));\n\t\tassertTrue(function.inDomain(-20000));\n\t\tassertEquals(Optional.of(1), function.apply(0));\n\t\tassertEquals(Optional.of(3), function.apply(2));\n\t\tassertEquals(Optional.of(10001), function.apply(10000));\n\t}\n\t\n\[email protected]\n\tpublic void testWithUpdated1() {\n\t\t// takes a constant and updates it with the mapping 0->1\n\t\t// Gives a function that is 0 everywhere, except at 0, where it gives 1 (a kind of dirac delta)\"\n\t\tMathematicalFunction<Integer, Integer> constant = this.factory.constant(a->true, 0);\n\t\tMathematicalFunction<Integer, Integer> diracLike= constant.withUpdatedValue(0, 1);\n\t\tassertTrue(diracLike.inDomain(0));\n\t\tassertTrue(diracLike.inDomain(1));\n\t\tassertTrue(diracLike.inDomain(2));\n\t\tassertTrue(diracLike.inDomain(-10000));\n\t\tassertEquals(Optional.of(1), diracLike.apply(0));\n\t\tassertEquals(Optional.of(0), diracLike.apply(1));\n\t\tassertEquals(Optional.of(0), diracLike.apply(2));\n\t\tassertEquals(Optional.of(0), diracLike.apply(-10000));\n\t}\n\t\n\[email protected]\n\tpublic void testWithUpdated2() {\n\t\t// Takes the function \"+1\" on the domain [0,..,10], and adds the mapping -10->-10 to it\n\t\tMathematicalFunction<Double, Double> function = this.factory.fromFunction(i -> i >= 0 && i <= 10, i->i+1);\n\t\tMathematicalFunction<Double, Double> strange = function.withUpdatedValue(0.0, 0.0).withUpdatedValue(-10.0, -10.0);\n\t\tassertTrue(strange.inDomain(0.0));\n\t\tassertTrue(strange.inDomain(5.0));\n\t\tassertTrue(strange.inDomain(10.0));\n\t\tassertTrue(strange.inDomain(-10.0));\n\t\tassertFalse(strange.inDomain(-9.9));\n\t\tassertFalse(strange.inDomain(20.0));\n\t\tassertEquals(Optional.of(0.0), strange.apply(0.0));\n\t\tassertEquals(Optional.of(2.0), strange.apply(1.0));\n\t\tassertEquals(Optional.of(11.0), strange.apply(10.0));\n\t\tassertEquals(Optional.of(3.5), strange.apply(2.5));\n\t\tassertEquals(Optional.of(-10.0), strange.apply(-10.0));\n\t\tassertEquals(Optional.empty(), strange.apply(-9.9));\n\t\tassertEquals(Optional.empty(), strange.apply(11.0));\n\t}\n\t\n\[email protected]\n\tpublic void testComposition1() {\n\t\t// Composes the constant 1 with the function \"+1\", giving the constant 2\n\t\tMathematicalFunction<Integer, Integer> f1 = this.factory.constant(a->true,1);\n\t\tMathematicalFunction<Integer, Integer> f2 = this.factory.fromFunction(a->true,i->i+1);\n\t\tMathematicalFunction<Integer, Integer> f3 = f1.composeWith(f2);\n\t\tassertTrue(f3.inDomain(0));\n\t\tassertTrue(f3.inDomain(1));\n\t\tassertTrue(f3.inDomain(2));\n\t\tassertTrue(f3.inDomain(-1));\n\t\tassertEquals(Optional.of(2), f3.apply(0));\n\t\tassertEquals(Optional.of(2), f3.apply(1));\n\t\tassertEquals(Optional.of(2), f3.apply(2));\n\t\tassertEquals(Optional.of(2), f3.apply(10));\n\t}\n\t\n\[email protected]\n\tpublic void testComposition2() {\n\t\t// Composes the function \"+1\" with the constant 1, giving the constant 1\n\t\tMathematicalFunction<Integer, Integer> f1 = this.factory.constant(a->true,1);\n\t\tMathematicalFunction<Integer, Integer> f2 = this.factory.fromFunction(a->true,i->i+1);\n\t\tMathematicalFunction<Integer, Integer> f3 = f2.composeWith(f1);\n\t\tassertTrue(f3.inDomain(0));\n\t\tassertTrue(f3.inDomain(1));\n\t\tassertTrue(f3.inDomain(2));\n\t\tassertTrue(f3.inDomain(-1));\n\t\tassertEquals(Optional.of(1), f3.apply(0));\n\t\tassertEquals(Optional.of(1), f3.apply(1));\n\t\tassertEquals(Optional.of(1), f3.apply(2));\n\t\tassertEquals(Optional.of(1), f3.apply(10));\n\t}\n\t\n\[email protected]\n\tpublic void optionalTestFromMap() {\n\t\tMap<Integer,String> map = new HashMap<>();\n\t\tmap.put(0, \"a\");\n\t\tmap.put(1, \"b\");\n\t\tmap.put(2, \"c\");\n\t\t// Function that associates each integer 'i' with a string 's', just like the map would\n\t\tMathematicalFunction<Integer, String> mapFunction = this.factory.fromMap(map);\n\t\tassertTrue(mapFunction.inDomain(0));\n\t\tassertTrue(mapFunction.inDomain(1));\n\t\tassertTrue(mapFunction.inDomain(2));\n\t\tassertFalse(mapFunction.inDomain(3));\n\t\tassertFalse(mapFunction.inDomain(-1));\n\t\tassertEquals(Optional.of(\"a\"), mapFunction.apply(0));\n\t\tassertEquals(Optional.of(\"b\"), mapFunction.apply(1));\n\t\tassertEquals(Optional.of(\"c\"), mapFunction.apply(2));\n\t\tassertEquals(Optional.empty(), mapFunction.apply(3));\n\t\tassertEquals(Optional.empty(), mapFunction.apply(-1));\n\t\tassertEquals(Optional.empty(), mapFunction.apply(-1));\n\t}\n\t\n\[email protected]\n\tpublic void optionalTestRestrict() {\n\t\t// takes a constant and restricts it to the domain with only the values 0,1,2,3\n\t\tMathematicalFunction<Integer, Integer> constant = this.factory.constant(a->true, 0);\n\t\tMathematicalFunction<Integer, Integer> fun = constant.restrict(Set.of(0,1,2,3));\n\t\tassertTrue(fun.inDomain(0));\n\t\tassertTrue(fun.inDomain(1));\n\t\tassertTrue(fun.inDomain(2));\n\t\tassertTrue(fun.inDomain(3));\n\t\tassertFalse(fun.inDomain(4));\n\t\tassertFalse(fun.inDomain(-1));\n\t\tassertEquals(Optional.of(0), fun.apply(0));\n\t\tassertEquals(Optional.of(0), fun.apply(1));\n\t\tassertEquals(Optional.of(0), fun.apply(2));\n\t\tassertEquals(Optional.empty(), fun.apply(-10000));\n\t}\n}", "filename": "Test.java" }
2021
a04
[ { "content": "package a04.sol1;\n\nimport java.util.List;\nimport java.util.function.Function;\nimport java.util.function.Supplier;\n\n\npublic interface EitherFactory {\n\t\n\t\n\t<A,B> Either<A,B> success(B b);\n\t\n\t\n\t<A,B> Either<A,B> failure(A a);\n\t\n\t\n\t<A> Either<Exception, A> of(Supplier<A> computation);\n\t\n\t\n\t<A,B,C> Either<A, List<C>> traverse(List<B> list, Function<B, Either<A,C>> function);\n\n}", "filename": "EitherFactory.java" }, { "content": "package a04.sol1;\n\nimport java.util.Optional;\nimport java.util.function.Function;\nimport java.util.function.Predicate;\nimport java.util.function.Supplier;\n\n\npublic interface Either<A, B> {\n\t\n\t\n\tboolean isFailure();\n\t\n\t\n\tboolean isSuccess();\n\t\n\t\n\tOptional<A> getFailure();\n\t\n\t\n\tOptional<B> getSuccess();\n\t\n\t\n\tB orElse(B other);\n\t\n\t\n\t<B1> Either<A, B1> map(Function<B, B1> function);\n\t\n\t\n\t<B1> Either<A, B1> flatMap(Function<B, Either<A, B1>> function);\n\t\t\n\t\n\t<A1> Either<A1,B> filterOrElse(Predicate<B> predicate, A1 failure);\n\t\n\t\n\t<C> C fold(Function<A,C> funFailure, Function<B,C> funSuccess);\n}", "filename": "Either.java" }, { "content": "package a04.sol1;\n\nimport java.util.Objects;\n\n\n\npublic class Pair<E1,E2> {\n\t\n\tprivate final E1 e1;\n\tprivate final E2 e2;\n\t\n\tpublic Pair(E1 x, E2 y) {\n\t\tsuper();\n\t\tthis.e1 = x;\n\t\tthis.e2 = y;\n\t}\n\n\tpublic E1 get1() {\n\t\treturn e1;\n\t}\n\n\tpublic E2 get2() {\n\t\treturn e2;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Objects.hash(e1, e2);\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj) {\n\t\t\treturn true;\n\t\t}\n\t\tif (obj == null) {\n\t\t\treturn false;\n\t\t}\n\t\tif (getClass() != obj.getClass()) {\n\t\t\treturn false;\n\t\t}\n\t\tPair other = (Pair) obj;\n\t\treturn Objects.equals(e1, other.e1) && Objects.equals(e2, other.e2);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Pair [e1=\" + e1 + \", e2=\" + e2 + \"]\";\n\t}\n\t\n\t\n\n}", "filename": "Pair.java" } ]
[ { "content": "package a04.sol1;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.stream.Stream;\nimport java.util.stream.Collectors;\nimport java.util.function.Function;\nimport java.util.function.Supplier;\n\npublic class EitherFactoryImpl implements EitherFactory {\n\n\t@Override\n\tpublic <A, B> Either<A, B> success(B b) {\n\t\treturn EitherImpl.createSuccess(b);\n\t}\n\n\t@Override\n\tpublic <A, B> Either<A, B> failure(A a) {\n\t\treturn EitherImpl.createFailure(a);\n\t}\n\n\t@Override\n\tpublic <A> Either<Exception, A> of(Supplier<A> computation) {\n\t\ttry {\n\t\t\treturn success(computation.get());\n\t\t} catch (Exception e) {\n\t\t\treturn failure(e);\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic <A, B, C> Either<A, List<C>> traverse(List<B> list, Function<B, Either<A, C>> function) {\n\t\treturn list\n\t\t\t\t.stream()\n\t\t\t\t.map(function::apply)\n\t\t\t\t.map(e -> e.map(Stream::of))\n\t\t\t\t.reduce(\n\t\t\t\t\t\tsuccess(Stream.of()),\n\t\t\t\t\t\t(e1, e2) -> e1.flatMap(l1 -> e2.map(l2 -> Stream.concat(l1,l2)))) // map2(e1,e2,Stream::concat)\n\t\t\t\t.map(s -> s.collect(Collectors.toList()));\n\t}\n\t\n\tpublic <A, B, C> Either<A, List<C>> alternativeTraverse(List<B> list, Function<B, Either<A, C>> function) {\n\t\tEither<A, List<C>> e = success(new ArrayList<>());\n\t\tfor (var b: list) {\n\t\t\tvar e2 = function.apply(b);\n\t\t\tif (e2.isFailure()) {\n\t\t\t\treturn failure(e2.getFailure().get());\n\t\t\t}\n\t\t\te.getSuccess().get().add(e2.getSuccess().get());\n\t\t}\n\t\treturn e;\n\t}\n\n}", "filename": "EitherFactoryImpl.java" }, { "content": "package a04.sol1;\n\nimport java.util.Optional;\nimport java.util.function.Function;\nimport java.util.function.Predicate;\n\npublic class EitherImpl<A,B> implements Either<A, B> {\n\t\n\tprivate final Optional<A> failurePart;\n\tprivate final Optional<B> successPart;\n\t\n\tstatic <A,B> Either<A,B> createFailure(A a){\n\t\treturn new EitherImpl<>(Optional.of(a), Optional.empty());\n\t}\n\t\n\tstatic <A,B> Either<A,B> createSuccess(B b){\n\t\treturn new EitherImpl<>(Optional.empty(), Optional.of(b));\n\t}\n\t\n\tprivate EitherImpl(Optional<A> failurePart, Optional<B> successPart) {\n\t\tif (failurePart.isEmpty() ^ successPart.isPresent()) {\n\t\t\tthrow new IllegalArgumentException();\n\t\t}\n\t\tthis.failurePart = failurePart;\n\t\tthis.successPart = successPart;\n\t}\n\n\t@Override\n\tpublic boolean isFailure() {\n\t\treturn this.failurePart.isPresent();\n\t}\n\n\t@Override\n\tpublic boolean isSuccess() {\n\t\treturn !this.isFailure();\n\t}\n\n\t@Override\n\tpublic Optional<A> getFailure() {\n\t\treturn this.failurePart;\n\t}\n\t\n\t@Override\n\tpublic Optional<B> getSuccess() {\n\t\treturn this.successPart;\n\t}\n\n\t@Override\n\tpublic B orElse(B other) {\n\t\treturn this.successPart.orElse(other);\n\t}\n\n\t@Override\n\tpublic <B1> Either<A, B1> map(Function<B, B1> function) {\n\t\treturn fold(EitherImpl::createFailure, function.andThen(EitherImpl::createSuccess)); // r -> ofRight(function.apply(r)));\n\t}\n\n\t@Override\n\tpublic <B1> Either<A, B1> flatMap(Function<B, Either<A, B1>> function) {\n\t\treturn fold(EitherImpl::createFailure, function::apply);\n\t}\n\n\t@Override\n\tpublic <A1> Either<A1,B> filterOrElse(Predicate<B> predicate, A1 failure) {\n\t\treturn this.isFailure() || !predicate.test(this.successPart.get()) ? createFailure(failure) : createSuccess(successPart.get()); \n\t}\n\n\t@Override\n\tpublic <C> C fold(Function<A,C> funFailure, Function<B,C> funSuccess) {\n\t\treturn this.isFailure() ? funFailure.apply(failurePart.get()) : funSuccess.apply(successPart.get());\n\t}\n}", "filename": "EitherImpl.java" } ]
{ "components": { "imports": "package a04.sol1;\n\nimport static org.junit.Assert.*;\n\nimport java.util.List;\nimport java.util.Optional;", "private_init": "\t/*\n\t * Implement the EitherFactory interface as indicated in the initFactory method below.\n\t * Create a factory for Either<A,B> (\"A or B\"), i.e., variations of Optional where a value\n\t * (of type B) can be present (in case of \"success\"), but if it is not there (case of \"failure\")\n\t * then a value representing the reason for the failure is present (of type A).\n\t * So inside an Either either the success value is present, or the failure value is present\n\t * (never both, and at least one of the two must be there).\n\t *\n\t * The comment on the provided interfaces, and the test methods below\n\t * constitute the necessary explanation of the problem.\n\t *\n\t * The following are considered optional for the purpose of being able to correct\n\t * the exercise, but still contribute to achieving the totality of the\n\t * score:\n\t *\n\t * - one of the three fold/flatMap/filterOrElse methods of Either, at choice\n\t * (i.e., in the mandatory part it is sufficient to implement 2 of these 3, the third is therefore optional)\n\t *\n\t * - the good design of the solution, reusing as much code as possible and keeping all the implementations\n\t * very succinct\n\t *\n\t * Remove the comment from the initFactory method.\n\t *\n\t * Scoring indications:\n\t *\n\t * - correctness of the mandatory part: 10 points\n\t *\n\t * - correctness of the optional part: 2 points (additional method)\n\t *\n\t * - quality of the solution: 5 points (for the good design of the solution, as indicated above)\n\t *\n\t */\n\n\n\n\tprivate EitherFactory factory;\n\t\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.factory = new EitherFactoryImpl();\n\t}", "test_functions": [ "\[email protected]\n\tpublic void testFailure() {\n\t\t// a failure is not a success\n\t\tEither<String, Integer> e = this.factory.failure(\"error\");\n\t\tassertTrue(e.isFailure());\n\t\tassertFalse(e.isSuccess());\n\t\tassertEquals(Optional.of(\"error\"), e.getFailure());\n\t\tassertEquals(Optional.empty(), e.getSuccess());\n\t}", "\[email protected]\n\tpublic void testSuccess() {\n\t\t// a success is not a failure\n\t\tEither<String, Integer> e = this.factory.success(100);\n\t\tassertFalse(e.isFailure());\n\t\tassertTrue(e.isSuccess());\n\t\tassertEquals(Optional.of(100), e.getSuccess());\n\t\tassertEquals(Optional.empty(), e.getFailure());\n\t}", "\[email protected]\n\tpublic void testException() {\n\t\t// the result of 0/0 is a failure, containing the exception thrown, i.e., ArithmeticException\n\t\tEither<Exception, Integer> e = this.factory.of(() -> 0/0);\n\t\tassertTrue(e.isFailure());\n\t\tassertEquals(ArithmeticException.class, e.getFailure().get().getClass());\n\t}", "\[email protected]\n\tpublic void testNoException() {\n\t\t// the result of 5/5 is a success\n\t\tEither<Exception, Integer> e = this.factory.of(() -> 5/5);\n\t\tassertTrue(e.isSuccess());\n\t\tassertEquals(Optional.of(1), e.getSuccess());\n\t}", "\[email protected]\n\tpublic void testOrElse() {\n\t\t// we get the success value, or a default -1 in case of failure\n\t\tassertEquals(Integer.valueOf(-1), this.factory.of(() -> 0/0).orElse(-1));\n\t\tassertEquals(Integer.valueOf(10), this.factory.of(() -> 10).orElse(-1));\n\t}", "\[email protected]\n\tpublic void testMap() {\n\t\t// having obtained a result, we add 1, but it only works if it was a success\n\t\tassertEquals(Optional.empty(), this.factory.of(() -> 0/0).map(x -> x+1).getSuccess());\n\t\tassertEquals(Optional.of(11), this.factory.of(() -> 10).map(x -> x+1).getSuccess());\n\t}", "\[email protected]\n\tpublic void testFlatMap() {\n\t\t// having obtained a result x, we convert it to 10/x, but it only works if it was a success and if 10/x can be done...\n\t\tassertTrue(this.factory.of(() -> 0/0).flatMap(x -> this.factory.of(() -> 10/x)).isFailure());\n\t\tassertTrue(this.factory.of(() -> 0).flatMap(x -> this.factory.of(() -> 10/x)).isFailure());\n\t\tassertEquals(Optional.of(5), this.factory.of(() -> 2).flatMap(x -> this.factory.of(() -> 10/x)).getSuccess());\n\t}", "\[email protected]\n\tpublic void testFilter() {\n\t\t// having obtained a result x, I only filter if it is positive, otherwise it gives me failure\n\t\tassertEquals(Optional.of(\"negative!\"), this.factory.of(() -> 0/0).filterOrElse(x -> x>0, \"negative!\").getFailure());\n\t\tassertEquals(Optional.of(\"negative!\"), this.factory.of(() -> -5).filterOrElse(x -> x>0, \"negative!\").getFailure());\n\t\tassertEquals(Optional.of(5), this.factory.of(() -> 5).filterOrElse(x -> x>0, \"negative!\").getSuccess());\n\t}", "\[email protected]\n\tpublic void testFold() {\n\t\t// applies a function in case of success and one in case of failure: something always returns then...\n\t\tEither<String, Integer> e1 = this.factory.failure(\"error\");\n\t\tEither<String, Integer> e2 = this.factory.success(10);\n\t\tassertEquals(\"error!\", e1.fold(s -> s + \"!\", i -> String.valueOf(i)));\n\t\tassertEquals(\"10\", e2.fold(s -> s + \"!\", i -> String.valueOf(i)));\n\t}", "\[email protected]\n\tpublic void testTraverseOK() {\n\t\t// applies /2 to a list of even integers: everything in this case is a success!\n\t\tvar list = List.of(10, 20, 30, 42);\n\t\tvar out = this.factory.traverse(list, i -> this.factory.of(()->i).filterOrElse(j -> j%2 == 0, \"dispari\").map(j -> j/2));\n\t\tassertEquals(List.of(5, 10, 15, 21), out.getSuccess().get());\n\t}", "\[email protected]\n\tpublic void testTraverseNO() {\n\t\t// applies /2 to a list of even integers: everything in this case is a failure!\n\t\tvar list = List.of(10, 20, 31, 42);\n\t\tvar out = this.factory.traverse(list, i -> this.factory.of(()->i).filterOrElse(j -> j%2 == 0, \"dispari\").map(j -> j/2));\n\t\tassertEquals(\"dispari\", out.getFailure().get());\n\t}" ] }, "content": "package a04.sol1;\n\nimport static org.junit.Assert.*;\n\nimport java.util.List;\nimport java.util.Optional;\n\npublic class Test {\n\n\t/*\n\t * Implement the EitherFactory interface as indicated in the initFactory method below.\n\t * Create a factory for Either<A,B> (\"A or B\"), i.e., variations of Optional where a value\n\t * (of type B) can be present (in case of \"success\"), but if it is not there (case of \"failure\")\n\t * then a value representing the reason for the failure is present (of type A).\n\t * So inside an Either either the success value is present, or the failure value is present\n\t * (never both, and at least one of the two must be there).\n\t *\n\t * The comment on the provided interfaces, and the test methods below\n\t * constitute the necessary explanation of the problem.\n\t *\n\t * The following are considered optional for the purpose of being able to correct\n\t * the exercise, but still contribute to achieving the totality of the\n\t * score:\n\t *\n\t * - one of the three fold/flatMap/filterOrElse methods of Either, at choice\n\t * (i.e., in the mandatory part it is sufficient to implement 2 of these 3, the third is therefore optional)\n\t *\n\t * - the good design of the solution, reusing as much code as possible and keeping all the implementations\n\t * very succinct\n\t *\n\t * Remove the comment from the initFactory method.\n\t *\n\t * Scoring indications:\n\t *\n\t * - correctness of the mandatory part: 10 points\n\t *\n\t * - correctness of the optional part: 2 points (additional method)\n\t *\n\t * - quality of the solution: 5 points (for the good design of the solution, as indicated above)\n\t *\n\t */\n\n\n\n\tprivate EitherFactory factory;\n\t\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.factory = new EitherFactoryImpl();\n\t}\n\t\n\[email protected]\n\tpublic void testFailure() {\n\t\t// a failure is not a success\n\t\tEither<String, Integer> e = this.factory.failure(\"error\");\n\t\tassertTrue(e.isFailure());\n\t\tassertFalse(e.isSuccess());\n\t\tassertEquals(Optional.of(\"error\"), e.getFailure());\n\t\tassertEquals(Optional.empty(), e.getSuccess());\n\t}\n\t\n\[email protected]\n\tpublic void testSuccess() {\n\t\t// a success is not a failure\n\t\tEither<String, Integer> e = this.factory.success(100);\n\t\tassertFalse(e.isFailure());\n\t\tassertTrue(e.isSuccess());\n\t\tassertEquals(Optional.of(100), e.getSuccess());\n\t\tassertEquals(Optional.empty(), e.getFailure());\n\t}\n\t\n\[email protected]\n\tpublic void testException() {\n\t\t// the result of 0/0 is a failure, containing the exception thrown, i.e., ArithmeticException\n\t\tEither<Exception, Integer> e = this.factory.of(() -> 0/0);\n\t\tassertTrue(e.isFailure());\n\t\tassertEquals(ArithmeticException.class, e.getFailure().get().getClass());\n\t}\n\t\n\[email protected]\n\tpublic void testNoException() {\n\t\t// the result of 5/5 is a success\n\t\tEither<Exception, Integer> e = this.factory.of(() -> 5/5);\n\t\tassertTrue(e.isSuccess());\n\t\tassertEquals(Optional.of(1), e.getSuccess());\n\t}\n\t\n\[email protected]\n\tpublic void testOrElse() {\n\t\t// we get the success value, or a default -1 in case of failure\n\t\tassertEquals(Integer.valueOf(-1), this.factory.of(() -> 0/0).orElse(-1));\n\t\tassertEquals(Integer.valueOf(10), this.factory.of(() -> 10).orElse(-1));\n\t}\n\t\n\[email protected]\n\tpublic void testMap() {\n\t\t// having obtained a result, we add 1, but it only works if it was a success\n\t\tassertEquals(Optional.empty(), this.factory.of(() -> 0/0).map(x -> x+1).getSuccess());\n\t\tassertEquals(Optional.of(11), this.factory.of(() -> 10).map(x -> x+1).getSuccess());\n\t}\n\t\n\[email protected]\n\tpublic void testFlatMap() {\n\t\t// having obtained a result x, we convert it to 10/x, but it only works if it was a success and if 10/x can be done...\n\t\tassertTrue(this.factory.of(() -> 0/0).flatMap(x -> this.factory.of(() -> 10/x)).isFailure());\n\t\tassertTrue(this.factory.of(() -> 0).flatMap(x -> this.factory.of(() -> 10/x)).isFailure());\n\t\tassertEquals(Optional.of(5), this.factory.of(() -> 2).flatMap(x -> this.factory.of(() -> 10/x)).getSuccess());\n\t}\n\t\n\[email protected]\n\tpublic void testFilter() {\n\t\t// having obtained a result x, I only filter if it is positive, otherwise it gives me failure\n\t\tassertEquals(Optional.of(\"negative!\"), this.factory.of(() -> 0/0).filterOrElse(x -> x>0, \"negative!\").getFailure());\n\t\tassertEquals(Optional.of(\"negative!\"), this.factory.of(() -> -5).filterOrElse(x -> x>0, \"negative!\").getFailure());\n\t\tassertEquals(Optional.of(5), this.factory.of(() -> 5).filterOrElse(x -> x>0, \"negative!\").getSuccess());\n\t}\n\t\n\[email protected]\n\tpublic void testFold() {\n\t\t// applies a function in case of success and one in case of failure: something always returns then...\n\t\tEither<String, Integer> e1 = this.factory.failure(\"error\");\n\t\tEither<String, Integer> e2 = this.factory.success(10);\n\t\tassertEquals(\"error!\", e1.fold(s -> s + \"!\", i -> String.valueOf(i)));\n\t\tassertEquals(\"10\", e2.fold(s -> s + \"!\", i -> String.valueOf(i)));\n\t}\n\t\n\[email protected]\n\tpublic void testTraverseOK() {\n\t\t// applies /2 to a list of even integers: everything in this case is a success!\n\t\tvar list = List.of(10, 20, 30, 42);\n\t\tvar out = this.factory.traverse(list, i -> this.factory.of(()->i).filterOrElse(j -> j%2 == 0, \"dispari\").map(j -> j/2));\n\t\tassertEquals(List.of(5, 10, 15, 21), out.getSuccess().get());\n\t}\n\t\n\[email protected]\n\tpublic void testTraverseNO() {\n\t\t// applies /2 to a list of even integers: everything in this case is a failure!\n\t\tvar list = List.of(10, 20, 31, 42);\n\t\tvar out = this.factory.traverse(list, i -> this.factory.of(()->i).filterOrElse(j -> j%2 == 0, \"dispari\").map(j -> j/2));\n\t\tassertEquals(\"dispari\", out.getFailure().get());\n\t}\n}", "filename": "Test.java" }
2021
a03a
[ { "content": "package a03a.sol1;\n\nimport java.util.List;\nimport java.util.function.Predicate;\n\n\npublic interface DecisionChainFactory {\n\t\n\t\n\t<A,B> DecisionChain<A,B> oneResult(B b);\n\t\n\t\n\t<A,B> DecisionChain<A,B> simpleTwoWay(Predicate<A> predicate, B positive, B negative);\n\t\n\t\n\t<A,B> DecisionChain<A,B> enumerationLike(List<Pair<A,B>> mapList, B defaultReply);\n\t\n\t\n\t<A,B> DecisionChain<A,B> twoWay(Predicate<A> predicate, DecisionChain<A,B> positive, DecisionChain<A,B> negative);\n\t\n\t\n\t<A,B> DecisionChain<A,B> switchChain(List<Pair<Predicate<A>,B>> cases, B defaultReply);\n\n}", "filename": "DecisionChainFactory.java" }, { "content": "package a03a.sol1;\n\nimport java.util.Objects;\n\n\n\npublic class Pair<E1,E2> {\n\t\n\tprivate final E1 e1;\n\tprivate final E2 e2;\n\t\n\tpublic Pair(E1 x, E2 y) {\n\t\tsuper();\n\t\tthis.e1 = x;\n\t\tthis.e2 = y;\n\t}\n\n\tpublic E1 get1() {\n\t\treturn e1;\n\t}\n\n\tpublic E2 get2() {\n\t\treturn e2;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Objects.hash(e1, e2);\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj) {\n\t\t\treturn true;\n\t\t}\n\t\tif (obj == null) {\n\t\t\treturn false;\n\t\t}\n\t\tif (getClass() != obj.getClass()) {\n\t\t\treturn false;\n\t\t}\n\t\tPair other = (Pair) obj;\n\t\treturn Objects.equals(e1, other.e1) && Objects.equals(e2, other.e2);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Pair [e1=\" + e1 + \", e2=\" + e2 + \"]\";\n\t}\n\t\n\t\n\n}", "filename": "Pair.java" }, { "content": "package a03a.sol1;\n\nimport java.util.Optional;\n\n\npublic interface DecisionChain<A,B> {\n\t\n\t\n\tOptional<B> result(A a);\n\t\n\t\n\tDecisionChain<A,B> next(A a);\n\t\n\t\n\tdefault B finalResult(A a) {\n\t\treturn this.result(a).orElseGet(()->this.next(a).finalResult(a));\n\t}\n}", "filename": "DecisionChain.java" } ]
[ { "content": "package a03a.sol1;\n\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.NoSuchElementException;\nimport java.util.Optional;\nimport java.util.function.Predicate;\nimport java.util.stream.Collectors;\n\npublic class DecisionChainFactoryImpl implements DecisionChainFactory {\n\t\n\t@Override\n\tpublic <A, B> DecisionChain<A, B> oneResult(B b) {\n\t\treturn new DecisionChain<>() {\n\n\t\t\t@Override\n\t\t\tpublic Optional<B> result(A a) {\n\t\t\t\treturn Optional.of(b);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic DecisionChain<A, B> next(A a) {\n\t\t\t\tthrow new NoSuchElementException();\n\t\t\t}\n\t\t\t\n\t\t};\n\t}\n\n\t@Override\n\tpublic <A, B> DecisionChain<A, B> simpleTwoWay(Predicate<A> predicate, B positive, B negative) {\n\t\treturn this.twoWay(predicate, oneResult(positive), oneResult(negative));\n\t}\n\n\t@Override\n\tpublic <A, B> DecisionChain<A, B> enumerationLike(List<Pair<A,B>> map, B defaultReply) {\n\t\tvar list = map.stream().map(e -> new Pair<Predicate<A>,B>(a -> a.equals(e.get1()),e.get2())).collect(Collectors.toList());\n\t\treturn this.switchChain(list,defaultReply);\n\t}\n\n\t@Override\n\tpublic <A, B> DecisionChain<A, B> twoWay(Predicate<A> predicate, DecisionChain<A, B> positive, DecisionChain<A, B> negative) {\n\t\treturn new DecisionChain<>() {\n\n\t\t\t@Override\n\t\t\tpublic Optional<B> result(A a) {\n\t\t\t\treturn Optional.empty();\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic DecisionChain<A, B> next(A a) {\n\t\t\t\treturn predicate.test(a) ? positive : negative;\n\t\t\t}\n\t\t};\n\t}\n\n\t@Override\n\tpublic <A, B> DecisionChain<A, B> switchChain(List<Pair<Predicate<A>, B>> cases, B defaultReply) {\n\t\treturn new DecisionChain<>() {\n\n\t\t\t@Override\n\t\t\tpublic Optional<B> result(A a) {\n\t\t\t\tif (cases.isEmpty()) {\n\t\t\t\t\treturn Optional.of(defaultReply);\n\t\t\t\t}\n\t\t\t\tif (cases.get(0).get1().test(a)) {\n\t\t\t\t\treturn Optional.of(cases.get(0).get2());\n\t\t\t\t}\n\t\t\t\treturn Optional.empty();\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic DecisionChain<A, B> next(A a) {\n\t\t\t\tvar recursiveCases = new LinkedList<>(cases);\n\t\t\t\trecursiveCases.poll();\n\t\t\t\treturn switchChain(recursiveCases, defaultReply);\n\t\t\t}\t\t\t\n\t\t};\n\t}\n}", "filename": "DecisionChainFactoryImpl.java" } ]
{ "components": { "imports": "package a03a.sol1;\n\nimport static org.junit.Assert.*;\n\nimport java.util.List;\nimport java.util.Optional;\nimport java.util.function.Predicate;", "private_init": "\t/*\n\t * Implement the DecisionChainFactory interface as indicated in the\n\t * initFactory method below. Create a factory for DecisionChains, i.e.,\n\t * objects that, given an input, must decide whether to immediately return a\n\t * certain output, or request the delegation of the decision to another\n\t * DecisionChain (and to which one) -- an exercise that illustrates the pattern\n\t * called \"Chain of Responsibility\".\n\t * \n\t * The comment on the provided interfaces, and the test methods below\n\t * constitute the necessary explanation of the problem.\n\t * \n\t * The following are considered optional for the purpose of being able to correct\n\t * the exercise, but still contribute to achieving the totality of the\n\t * score:\n\t * \n\t * - implementation of the five methods in the factory (i.e., in the mandatory\n\t * part it is sufficient to implement 4 at will)\n\t * \n\t * - the good design of the solution, avoiding repetitions\n\t * \n\t * Remove the comment from the initFactory method.\n\t * \n\t * Scoring indications:\n\t * \n\t * - correctness of the mandatory part: 10 points (2+2+3+3 for the necessary\n\t * factory methods)\n\t * \n\t * - correctness of the optional part: 3 points (additional method)\n\t * \n\t * - quality of the solution: 4 points (for a solution that minimizes\n\t * repetitions and follows good programming practices)\n\t * \n\t */\n\n\tprivate DecisionChainFactory factory = null;\n\t\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.factory = new DecisionChainFactoryImpl();\n\t}", "test_functions": [ "\[email protected]\n\tpublic void testOneResult() {\n\t\tDecisionChain<Integer,Integer> dt = this.factory.oneResult(10);\n\t\t// always returns 10, and immediately\n\t\tassertEquals(Optional.of(10), dt.result(5));\n\t\tassertEquals(Optional.of(10), dt.result(-1));\n\t\tassertEquals(Optional.of(10), dt.result(11));\n\t\tassertEquals(10, dt.finalResult(-2).intValue());\n\t}", "\[email protected]\n\tpublic void testSimpleTwoWay() {\n\t\tDecisionChain<Integer,Integer> dt = this.factory.simpleTwoWay(x -> x > 0, +1, -1);\n\t\t// at the end of the chain of decisions, +1 is produced receiving a positive, -1 otherwise\n\t\tassertEquals(1, dt.finalResult(100).intValue());\n\t\tassertEquals(-1, dt.finalResult(-20).intValue());\n\t\t// ...but the thing is always decided by passing to another decider, so the direct result is \"empty\"\n\t\tassertEquals(Optional.empty(), dt.result(10));\n\t\tassertEquals(Optional.empty(), dt.result(-10));\n\t\t// for example, receiving 10 delegates to a dt2 that will always give me 1, and vice versa on dt3\n\t\tvar dt2 = dt.next(10);\n\t\tassertEquals(Optional.of(1), dt2.result(10));\n\t\tvar dt3 = dt.next(-10);\n\t\tassertEquals(Optional.of(-1), dt3.result(-10));\n\t}", "\[email protected]\n\tpublic void testEnumerationLike() {\n\t\tvar map = List.of(new Pair<>(\"a\",1), new Pair<>(\"b\",2), new Pair<>(\"c\",3));\n\t\t// at the end of the chain, 1 is produced receiving \"a\", 2 receiving \"b\"... and -1 in other cases\n\t\tDecisionChain<String,Integer> dt = this.factory.enumerationLike(map,-1);\n\t\tassertEquals(1, dt.finalResult(\"a\").intValue());\n\t\tassertEquals(2, dt.finalResult(\"b\").intValue());\n\t\tassertEquals(3, dt.finalResult(\"c\").intValue());\n\t\tassertEquals(-1, dt.finalResult(\"ddd\").intValue());\n\t\t// but dt responds immediately for \"a\", while for \"b\" it delegates to the next decider dt2\n\t\tassertEquals(Optional.of(1), dt.result(\"a\"));\n\t\tassertEquals(Optional.empty(), dt.result(\"b\"));\n\t\tvar dt2 = dt.next(\"b\");\n\t\tassertEquals(2, dt2.finalResult(\"b\").intValue());\n\t\tassertEquals(3, dt2.finalResult(\"c\").intValue());\n\t\tassertEquals(-1, dt2.finalResult(\"ddd\").intValue());\n\t\tassertEquals(-1, dt2.finalResult(\"a\").intValue());\n\t\tassertEquals(Optional.of(3), dt.next(\"c\").next(\"c\").result(\"c\"));\n\t}", "\[email protected]\n\tpublic void testTwoWay() {\n\t\tDecisionChain<String,Integer> dt1 = this.factory.oneResult(0);\n\t\tvar map = List.of(new Pair<>(\"a\",1), new Pair<>(\"b\",2), new Pair<>(\"c\",3));\n\t\tDecisionChain<String,Integer> dt2 = this.factory.enumerationLike(map,-1);\n\t\t// if the string is empty, dt delegates to dt1, otherwise to dt2\n\t\tDecisionChain<String,Integer> dt = this.factory.twoWay(String::isEmpty, dt1, dt2);\n\t\tassertEquals(0, dt.finalResult(\"\").intValue());\n\t\tassertEquals(1, dt.finalResult(\"a\").intValue());\n\t\tassertEquals(2, dt.finalResult(\"b\").intValue());\n\t\tassertEquals(3, dt.finalResult(\"c\").intValue());\n\t\tassertEquals(-1, dt.finalResult(\"ddd\").intValue());\n\t\tvar dt3 = dt.next(\"\");\n\t\t// dt3 behaves like dt1...\n\t\tassertEquals(Optional.of(0), dt3.result(\"\"));\n\t}", "\[email protected]\n\tpublic void testSwitchChain() {\n\t\tvar chain = List.<Pair<Predicate<Integer>,String>>of(\n\t\t\t\tnew Pair<>(x -> x<10, \"<10\"), // if x<10 decides and returns \"<10\", otherwise delegates...\n\t\t\t\tnew Pair<>(x -> x<20, \"<20\"), // if x<20 decides and returns \"<20\", otherwise delegates...\n\t\t\t\tnew Pair<>(x -> x<30, \"<30\"), // ...\n\t\t\t\tnew Pair<>(x -> x<40, \"<40\"));\n\t\tvar dt = this.factory.switchChain(chain, \"bigger\"); // if no one has decided, returns \"bigger\"\n\t\tassertEquals(\"<10\", dt.finalResult(0));\n\t\tassertEquals(\"<20\", dt.finalResult(15));\n\t\tassertEquals(\"<30\", dt.finalResult(21));\n\t\tassertEquals(\"<40\", dt.finalResult(39));\n\t\tassertEquals(\"bigger\", dt.finalResult(100));\n\t\tassertEquals(Optional.empty(), dt.result(11));\n\t}" ] }, "content": "package a03a.sol1;\n\nimport static org.junit.Assert.*;\n\nimport java.util.List;\nimport java.util.Optional;\nimport java.util.function.Predicate;\n\npublic class Test {\n\n\t/*\n\t * Implement the DecisionChainFactory interface as indicated in the\n\t * initFactory method below. Create a factory for DecisionChains, i.e.,\n\t * objects that, given an input, must decide whether to immediately return a\n\t * certain output, or request the delegation of the decision to another\n\t * DecisionChain (and to which one) -- an exercise that illustrates the pattern\n\t * called \"Chain of Responsibility\".\n\t * \n\t * The comment on the provided interfaces, and the test methods below\n\t * constitute the necessary explanation of the problem.\n\t * \n\t * The following are considered optional for the purpose of being able to correct\n\t * the exercise, but still contribute to achieving the totality of the\n\t * score:\n\t * \n\t * - implementation of the five methods in the factory (i.e., in the mandatory\n\t * part it is sufficient to implement 4 at will)\n\t * \n\t * - the good design of the solution, avoiding repetitions\n\t * \n\t * Remove the comment from the initFactory method.\n\t * \n\t * Scoring indications:\n\t * \n\t * - correctness of the mandatory part: 10 points (2+2+3+3 for the necessary\n\t * factory methods)\n\t * \n\t * - correctness of the optional part: 3 points (additional method)\n\t * \n\t * - quality of the solution: 4 points (for a solution that minimizes\n\t * repetitions and follows good programming practices)\n\t * \n\t */\n\n\tprivate DecisionChainFactory factory = null;\n\t\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.factory = new DecisionChainFactoryImpl();\n\t}\n\t\n\[email protected]\n\tpublic void testOneResult() {\n\t\tDecisionChain<Integer,Integer> dt = this.factory.oneResult(10);\n\t\t// always returns 10, and immediately\n\t\tassertEquals(Optional.of(10), dt.result(5));\n\t\tassertEquals(Optional.of(10), dt.result(-1));\n\t\tassertEquals(Optional.of(10), dt.result(11));\n\t\tassertEquals(10, dt.finalResult(-2).intValue());\n\t}\n\t\n\[email protected]\n\tpublic void testSimpleTwoWay() {\n\t\tDecisionChain<Integer,Integer> dt = this.factory.simpleTwoWay(x -> x > 0, +1, -1);\n\t\t// at the end of the chain of decisions, +1 is produced receiving a positive, -1 otherwise\n\t\tassertEquals(1, dt.finalResult(100).intValue());\n\t\tassertEquals(-1, dt.finalResult(-20).intValue());\n\t\t// ...but the thing is always decided by passing to another decider, so the direct result is \"empty\"\n\t\tassertEquals(Optional.empty(), dt.result(10));\n\t\tassertEquals(Optional.empty(), dt.result(-10));\n\t\t// for example, receiving 10 delegates to a dt2 that will always give me 1, and vice versa on dt3\n\t\tvar dt2 = dt.next(10);\n\t\tassertEquals(Optional.of(1), dt2.result(10));\n\t\tvar dt3 = dt.next(-10);\n\t\tassertEquals(Optional.of(-1), dt3.result(-10));\n\t}\n\t\n\[email protected]\n\tpublic void testEnumerationLike() {\n\t\tvar map = List.of(new Pair<>(\"a\",1), new Pair<>(\"b\",2), new Pair<>(\"c\",3));\n\t\t// at the end of the chain, 1 is produced receiving \"a\", 2 receiving \"b\"... and -1 in other cases\n\t\tDecisionChain<String,Integer> dt = this.factory.enumerationLike(map,-1);\n\t\tassertEquals(1, dt.finalResult(\"a\").intValue());\n\t\tassertEquals(2, dt.finalResult(\"b\").intValue());\n\t\tassertEquals(3, dt.finalResult(\"c\").intValue());\n\t\tassertEquals(-1, dt.finalResult(\"ddd\").intValue());\n\t\t// but dt responds immediately for \"a\", while for \"b\" it delegates to the next decider dt2\n\t\tassertEquals(Optional.of(1), dt.result(\"a\"));\n\t\tassertEquals(Optional.empty(), dt.result(\"b\"));\n\t\tvar dt2 = dt.next(\"b\");\n\t\tassertEquals(2, dt2.finalResult(\"b\").intValue());\n\t\tassertEquals(3, dt2.finalResult(\"c\").intValue());\n\t\tassertEquals(-1, dt2.finalResult(\"ddd\").intValue());\n\t\tassertEquals(-1, dt2.finalResult(\"a\").intValue());\n\t\tassertEquals(Optional.of(3), dt.next(\"c\").next(\"c\").result(\"c\"));\n\t}\n\t\n\[email protected]\n\tpublic void testTwoWay() {\n\t\tDecisionChain<String,Integer> dt1 = this.factory.oneResult(0);\n\t\tvar map = List.of(new Pair<>(\"a\",1), new Pair<>(\"b\",2), new Pair<>(\"c\",3));\n\t\tDecisionChain<String,Integer> dt2 = this.factory.enumerationLike(map,-1);\n\t\t// if the string is empty, dt delegates to dt1, otherwise to dt2\n\t\tDecisionChain<String,Integer> dt = this.factory.twoWay(String::isEmpty, dt1, dt2);\n\t\tassertEquals(0, dt.finalResult(\"\").intValue());\n\t\tassertEquals(1, dt.finalResult(\"a\").intValue());\n\t\tassertEquals(2, dt.finalResult(\"b\").intValue());\n\t\tassertEquals(3, dt.finalResult(\"c\").intValue());\n\t\tassertEquals(-1, dt.finalResult(\"ddd\").intValue());\n\t\tvar dt3 = dt.next(\"\");\n\t\t// dt3 behaves like dt1...\n\t\tassertEquals(Optional.of(0), dt3.result(\"\"));\n\t}\n\t\n\[email protected]\n\tpublic void testSwitchChain() {\n\t\tvar chain = List.<Pair<Predicate<Integer>,String>>of(\n\t\t\t\tnew Pair<>(x -> x<10, \"<10\"), // if x<10 decides and returns \"<10\", otherwise delegates...\n\t\t\t\tnew Pair<>(x -> x<20, \"<20\"), // if x<20 decides and returns \"<20\", otherwise delegates...\n\t\t\t\tnew Pair<>(x -> x<30, \"<30\"), // ...\n\t\t\t\tnew Pair<>(x -> x<40, \"<40\"));\n\t\tvar dt = this.factory.switchChain(chain, \"bigger\"); // if no one has decided, returns \"bigger\"\n\t\tassertEquals(\"<10\", dt.finalResult(0));\n\t\tassertEquals(\"<20\", dt.finalResult(15));\n\t\tassertEquals(\"<30\", dt.finalResult(21));\n\t\tassertEquals(\"<40\", dt.finalResult(39));\n\t\tassertEquals(\"bigger\", dt.finalResult(100));\n\t\tassertEquals(Optional.empty(), dt.result(11));\n\t}\n\n\t\n}", "filename": "Test.java" }
2021
a02b
[ { "content": "package a02b.sol1;\n\npublic interface UniversityProgramFactory {\n\t\n\t\n\tUniversityProgram flexible();\n\t\n\t\n\tUniversityProgram scientific();\n\t\n\t\n\tUniversityProgram shortComputerScience();\n\t\n\t\n\tUniversityProgram realistic();\n\n}", "filename": "UniversityProgramFactory.java" }, { "content": "package a02b.sol1;\n\nimport java.util.Set;\n\n\npublic interface UniversityProgram {\n\t\n\t\n\tenum Sector {\n\t\tCOMPUTER_SCIENCE, COMPUTER_ENGINEERING, MATHEMATICS, PHYSICS, THESIS\n\t}\n\t\n\t\n\tvoid addCourse(String name, Sector sector, int credits);\t\n\t\n\t\n\tboolean isValid(Set<String> courseNames);\n}", "filename": "UniversityProgram.java" }, { "content": "package a02b.sol1;\n\nimport java.util.Objects;\n\n\n\npublic class Pair<E1,E2> {\n\t\n\tprivate final E1 e1;\n\tprivate final E2 e2;\n\t\n\tpublic Pair(E1 x, E2 y) {\n\t\tsuper();\n\t\tthis.e1 = x;\n\t\tthis.e2 = y;\n\t}\n\n\tpublic E1 get1() {\n\t\treturn e1;\n\t}\n\n\tpublic E2 get2() {\n\t\treturn e2;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Objects.hash(e1, e2);\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj) {\n\t\t\treturn true;\n\t\t}\n\t\tif (obj == null) {\n\t\t\treturn false;\n\t\t}\n\t\tif (getClass() != obj.getClass()) {\n\t\t\treturn false;\n\t\t}\n\t\tPair other = (Pair) obj;\n\t\treturn Objects.equals(e1, other.e1) && Objects.equals(e2, other.e2);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Pair [e1=\" + e1 + \", e2=\" + e2 + \"]\";\n\t}\n\t\n\t\n\n}", "filename": "Pair.java" } ]
[ { "content": "package a02b.sol1;\n\nimport static a02b.sol1.UniversityProgram.Sector.*;\n\nimport java.util.Set;\nimport java.util.function.Predicate;\n\nimport a02b.sol1.UniversityProgram.Sector;\n\npublic class UniversityProgramFactoryImpl implements UniversityProgramFactory {\n\t\n\tprivate static Pair<Predicate<Sector>,Predicate<Integer>> constraint(Predicate<Sector> p1, Predicate<Integer> p2) {\n\t\treturn new Pair<>(p1,p2);\n\t}\n\t\n\t@Override\n\tpublic UniversityProgram flexible() {\n\t\treturn new AbstractUniversityProgram() {\n\n\t\t\t@Override\n\t\t\tprotected Set<Pair<Predicate<Sector>,Predicate<Integer>>> getConstraints() {\n\t\t\t\treturn Set.of(\n\t\t\t\t\tconstraint(sector -> true, credits -> credits == 60)\n\t\t\t\t);\n\t\t\t}\n\t\t};\n\t}\n\t\n\t@Override\n\tpublic UniversityProgram scientific() {\n\t\treturn new AbstractUniversityProgram() {\n\n\t\t\t@Override\n\t\t\tprotected Set<Pair<Predicate<Sector>,Predicate<Integer>>> getConstraints() {\n\t\t\t\treturn Set.of(\n\t\t\t\t\t\tconstraint(sector -> true, credits -> credits == 60),\n\t\t\t\t\t\tconstraint(sector -> sector == MATHEMATICS, credits -> credits >= 12),\n\t\t\t\t\t\tconstraint(sector -> sector == COMPUTER_SCIENCE, credits -> credits >= 12),\n\t\t\t\t\t\tconstraint(sector -> sector == PHYSICS, credits -> credits >= 12)\n\t\t\t\t);\n\t\t\t}\n\t\t};\n\t}\n\n\t@Override\n\tpublic UniversityProgram shortComputerScience() {\n\t\treturn new AbstractUniversityProgram() {\n\n\t\t\t@Override\n\t\t\tprotected Set<Pair<Predicate<Sector>,Predicate<Integer>>> getConstraints() {\n\t\t\t\treturn Set.of(\n\t\t\t\t\t\tconstraint(sector -> true, credits -> credits >= 48),\n\t\t\t\t\t\tconstraint(sector -> sector == COMPUTER_SCIENCE || sector == COMPUTER_ENGINEERING, credits -> credits >= 30)\n\t\t\t\t);\n\t\t\t}\n\t\t};\n\t}\n\n\t@Override\n\tpublic UniversityProgram realistic() {\n\t\treturn new AbstractUniversityProgram() {\n\n\t\t\t@Override\n\t\t\tprotected Set<Pair<Predicate<Sector>,Predicate<Integer>>> getConstraints() {\n\t\t\t\treturn Set.of(\n\t\t\t\t\t\tconstraint(sector -> true, credits -> credits == 120),\n\t\t\t\t\t\tconstraint(sector -> sector == COMPUTER_ENGINEERING | sector == COMPUTER_SCIENCE, credits -> credits >= 60),\n\t\t\t\t\t\tconstraint(sector -> sector == MATHEMATICS | sector == PHYSICS, credits -> credits <= 18),\n\t\t\t\t\t\tconstraint(sector -> sector == THESIS, credits -> credits == 24)\n\t\t\t\t);\n\t\t\t}\n\t\t};\n\t}\n}", "filename": "UniversityProgramFactoryImpl.java" }, { "content": "package a02b.sol1;\n\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Objects;\nimport java.util.Set;\nimport java.util.function.Predicate;\nimport java.util.stream.*;\n\npublic abstract class AbstractUniversityProgram implements UniversityProgram {\n\t\n\t// could have been a Map<String,Pair<Sector,Integer>>\n\tprivate final Map<String,Course> coursesMap = new HashMap<>();\n\t\n\t@Override\n\tpublic void addCourse(String name, Sector sector, int credits) {\n\t\tif (this.coursesMap.containsKey(name)) {\n\t\t\tthrow new IllegalArgumentException();\n\t\t}\n\t\tthis.coursesMap.put(name, new Course(name, sector, credits));\n\t}\n\n\t@Override\n\tpublic boolean isValid(Set<String> courseNames) {\n\t\tSet<Course> courses = courseNames.stream().map(this.coursesMap::get).collect(Collectors.toSet());\n\t\treturn this.getConstraints().stream().allMatch(constraint -> this.isConstraintSatisfied(constraint, courses));\n\t}\n\t\n\tprivate boolean isConstraintSatisfied(Pair<Predicate<Sector>,Predicate<Integer>> constraint, Set<Course> courses) {\n\t\treturn constraint.get2().test(courses.stream()\n\t\t\t\t.filter(c -> constraint.get1().test(c.getSector()))\n\t\t\t\t.mapToInt(Course::getCredits)\n\t\t\t\t.sum());\n\t}\n\n\tprotected abstract Set<Pair<Predicate<Sector>,Predicate<Integer>>> getConstraints();\n\t\n\tprivate static class Course {\n\t\tprivate String name;\n\t\tprivate Sector sector;\n\t\tprivate int credits;\n\t\t\n\t\tpublic Course(String name, Sector sector, int credits) {\n\t\t\tsuper();\n\t\t\tthis.name = name;\n\t\t\tthis.sector = sector;\n\t\t\tthis.credits = credits;\n\t\t}\n\n\t\tpublic String getName() {\n\t\t\treturn name;\n\t\t}\n\n\t\tpublic Sector getSector() {\n\t\t\treturn sector;\n\t\t}\n\n\t\tpublic int getCredits() {\n\t\t\treturn credits;\n\t\t}\n\n\t\t@Override\n\t\tpublic int hashCode() {\n\t\t\treturn Objects.hash(credits, name, sector);\n\t\t}\n\n\t\t@Override\n\t\tpublic boolean equals(Object obj) {\n\t\t\tif (this == obj) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (obj == null) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (getClass() != obj.getClass()) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tCourse other = (Course) obj;\n\t\t\treturn credits == other.credits && Objects.equals(name, other.name)\n\t\t\t\t\t&& sector == other.sector;\n\t\t}\n\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\treturn \"Course [name=\" + name + \", sector=\" + sector + \", credits=\"\n\t\t\t\t\t+ credits + \"]\";\n\t\t}\n\t}\n}", "filename": "AbstractUniversityProgram.java" } ]
{ "components": { "imports": "package a02b.sol1;\n\nimport static a02b.sol1.UniversityProgram.Sector.*;\nimport static org.junit.Assert.*;\n\nimport java.util.List;\nimport java.util.NoSuchElementException;\nimport java.util.Optional;\nimport java.util.Set;", "private_init": "\t/*\n\t * Implement the UniversityProgramFactory interface as indicated in the initFactory method below.\n\t * Create a factory for a bachelor's degree concept (program), captured by the UniversityProgram interface.\n\t * \n\t * As can be seen in the fillProgram method below, a degree program is first associated with a set of courses,\n\t * each with a certain number of credits and a sector, for example: (\"OOP\", COMPUTER_ENGINEERING, 12)\n\t * \n\t * At that point, the degree program has a method to establish whether a certain selection of courses (i.e.,\n\t * a curriculum presented by a student) satisfies the requirements, expressed by a CDL-specific logic,\n\t * in terms of the number of credits (minimum and/or maximum) for each sector or group of sectors.\n\t * \n\t * The following are considered optional for the purpose of being able to correct the exercise,\n\t * but still contribute to achieving the full score:\n\t * \n\t * - implementation of the four factory methods (i.e., in the mandatory part it is sufficient\n\t * to implement 3 at will)\n\t * - the good design of the solution, using patterns that lead to succinct code\n\t * that avoids repetitions\n\t * \n\t * Remove the comment from the initFactory method.\n\t * \n\t * Scoring indications:\n\t * - correctness of the mandatory part: 10 points\n\t * - correctness of the optional part: 3 points (additional factory method)\n\t * - quality of the solution: 4 points (for good design)\n\t * \n\t */\n\n\tprivate UniversityProgramFactory factory = null;\n\t\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.factory = new UniversityProgramFactoryImpl();\n\t}\n\t\n\tprivate void fillProgram(UniversityProgram program) {\n\t\tprogram.addCourse(\"PRG\", COMPUTER_SCIENCE, 12);\n\t\tprogram.addCourse(\"ALG\", COMPUTER_SCIENCE, 12);\n\t\tprogram.addCourse(\"SISOP\", COMPUTER_SCIENCE, 12);\n\t\tprogram.addCourse(\"WEB\", COMPUTER_SCIENCE, 6);\n\t\t\n\t\tprogram.addCourse(\"ARCH\", COMPUTER_ENGINEERING, 12);\n\t\tprogram.addCourse(\"OOP\", COMPUTER_ENGINEERING, 12);\n\t\tprogram.addCourse(\"NETWORKS\", COMPUTER_ENGINEERING, 6);\n\t\tprogram.addCourse(\"SOFTENG\", COMPUTER_ENGINEERING, 6);\n\t\t\n\t\tprogram.addCourse(\"MAT1\", MATHEMATICS, 6);\n\t\tprogram.addCourse(\"MAT2\", MATHEMATICS, 6);\n\t\t\n\t\tprogram.addCourse(\"FIS1\", PHYSICS, 6);\n\t\tprogram.addCourse(\"FIS2\", PHYSICS, 6);\n\t\t\n\t\tprogram.addCourse(\"THESIS-\", THESIS,6);\n\t\tprogram.addCourse(\"THESIS\", THESIS, 12);\n\t\tprogram.addCourse(\"THESIS++\", THESIS, 24);\n\t}", "test_functions": [ "\[email protected]\n\tpublic void testFlexible() {\n\t\tvar program = this.factory.flexible();\n\t\tfillProgram(program);\n\t\tassertTrue(program.isValid(Set.of(\"PRG\",\"ALG\",\"ARCH\",\"MAT1\",\"FIS1\",\"THESIS\"))); // 60 cfu\n\t\tassertTrue(program.isValid(Set.of(\"PRG\",\"ALG\",\"WEB\",\"SOFTENG\", \"MAT1\",\"FIS1\",\"THESIS\"))); // 60 cfu\n\t\tassertFalse(program.isValid(Set.of(\"PRG\",\"ALG\",\"WEB\",\"SOFTENG\", \"MAT1\",\"FIS1\",\"THESIS++\"))); // 66 cfu\n\t\tassertFalse(program.isValid(Set.of(\"PRG\",\"ALG\",\"WEB\"))); // 36 cfu\n\t\tassertFalse(program.isValid(Set.of())); // 0 cfu\n\t}", "\[email protected]\n\tpublic void testScientific() {\n\t\tvar program = this.factory.scientific();\n\t\tfillProgram(program);\n\t\tassertTrue(program.isValid(Set.of(\"PRG\",\"ALG\",\"MAT1\",\"MAT2\",\"FIS1\",\"FIS2\",\"OOP\"))); // ok\n\t\tassertFalse(program.isValid(Set.of(\"PRG\",\"ALG\",\"MAT1\",\"WEB\",\"FIS1\",\"FIS2\",\"OOP\"))); // not enough Math\n\t\tassertFalse(program.isValid(Set.of(\"PRG\",\"ALG\",\"MAT1\",\"MAT2\",\"WEB\",\"FIS2\",\"OOP\"))); // not enough Phys\n\t\tassertFalse(program.isValid(Set.of(\"OOP\",\"SOFTENG\",\"NETWORKS\",\"ARCH\",\"MAT1\",\"MAT2\",\"FIS1\",\"FIS2\",\"THESIS\"))); // too much CFUs\n\t}", "\[email protected]\n\tpublic void testShortCS() {\n\t\tvar program = this.factory.shortComputerScience();\n\t\tfillProgram(program);\n\t\tassertTrue(program.isValid(Set.of(\"PRG\",\"ALG\",\"ARCH\",\"THESIS\"))); // ok\n\t\tassertTrue(program.isValid(Set.of(\"PRG\",\"ALG\",\"ARCH\",\"THESIS\",\"MAT1\"))); // ok\n\t\tassertFalse(program.isValid(Set.of(\"PRG\",\"ALG\",\"THESIS\",\"MAT1\",\"MAT2\"))); // not enough Computers\n\t\tassertFalse(program.isValid(Set.of(\"PRG\",\"ALG\",\"THESIS\"))); // not enough CFUs\n\t}", "\[email protected]\n\tpublic void testRealistic() {\n\t\tvar program = this.factory.realistic();\n\t\tfillProgram(program);\n\t\tassertTrue(program.isValid(Set.of(\"PRG\",\"ALG\",\"ARCH\",\"OOP\",\"SISOP\",\"WEB\",\"SOFTENG\",\n\t\t\t\t\"NETWORKS\",\"MAT1\",\"MAT2\",\"FIS1\",\"THESIS++\"))); // ok\n\t\tassertFalse(program.isValid(Set.of(\"PRG\",\"ALG\",\"ARCH\",\"OOP\",\"SISOP\",\"WEB\",\"SOFTENG\",\n\t\t\t\t\"NETWORKS\",\"MAT1\",\"MAT2\",\"FIS1\",\"THESIS\"))); // not enough CFUs\n\t\tassertFalse(program.isValid(Set.of(\"PRG\",\"ALG\",\"ARCH\",\"OOP\",\"SISOP\",\"WEB\",\"SOFTENG\",\n\t\t\t\t\"MAT1\",\"MAT2\",\"FIS1\",\"FIS2\",\"THESIS++\"))); // too much MATH+FIS\n\t}" ] }, "content": "package a02b.sol1;\n\nimport static a02b.sol1.UniversityProgram.Sector.*;\nimport static org.junit.Assert.*;\n\nimport java.util.List;\nimport java.util.NoSuchElementException;\nimport java.util.Optional;\nimport java.util.Set;\n\npublic class Test {\n\n\t/*\n\t * Implement the UniversityProgramFactory interface as indicated in the initFactory method below.\n\t * Create a factory for a bachelor's degree concept (program), captured by the UniversityProgram interface.\n\t * \n\t * As can be seen in the fillProgram method below, a degree program is first associated with a set of courses,\n\t * each with a certain number of credits and a sector, for example: (\"OOP\", COMPUTER_ENGINEERING, 12)\n\t * \n\t * At that point, the degree program has a method to establish whether a certain selection of courses (i.e.,\n\t * a curriculum presented by a student) satisfies the requirements, expressed by a CDL-specific logic,\n\t * in terms of the number of credits (minimum and/or maximum) for each sector or group of sectors.\n\t * \n\t * The following are considered optional for the purpose of being able to correct the exercise,\n\t * but still contribute to achieving the full score:\n\t * \n\t * - implementation of the four factory methods (i.e., in the mandatory part it is sufficient\n\t * to implement 3 at will)\n\t * - the good design of the solution, using patterns that lead to succinct code\n\t * that avoids repetitions\n\t * \n\t * Remove the comment from the initFactory method.\n\t * \n\t * Scoring indications:\n\t * - correctness of the mandatory part: 10 points\n\t * - correctness of the optional part: 3 points (additional factory method)\n\t * - quality of the solution: 4 points (for good design)\n\t * \n\t */\n\n\tprivate UniversityProgramFactory factory = null;\n\t\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.factory = new UniversityProgramFactoryImpl();\n\t}\n\t\n\tprivate void fillProgram(UniversityProgram program) {\n\t\tprogram.addCourse(\"PRG\", COMPUTER_SCIENCE, 12);\n\t\tprogram.addCourse(\"ALG\", COMPUTER_SCIENCE, 12);\n\t\tprogram.addCourse(\"SISOP\", COMPUTER_SCIENCE, 12);\n\t\tprogram.addCourse(\"WEB\", COMPUTER_SCIENCE, 6);\n\t\t\n\t\tprogram.addCourse(\"ARCH\", COMPUTER_ENGINEERING, 12);\n\t\tprogram.addCourse(\"OOP\", COMPUTER_ENGINEERING, 12);\n\t\tprogram.addCourse(\"NETWORKS\", COMPUTER_ENGINEERING, 6);\n\t\tprogram.addCourse(\"SOFTENG\", COMPUTER_ENGINEERING, 6);\n\t\t\n\t\tprogram.addCourse(\"MAT1\", MATHEMATICS, 6);\n\t\tprogram.addCourse(\"MAT2\", MATHEMATICS, 6);\n\t\t\n\t\tprogram.addCourse(\"FIS1\", PHYSICS, 6);\n\t\tprogram.addCourse(\"FIS2\", PHYSICS, 6);\n\t\t\n\t\tprogram.addCourse(\"THESIS-\", THESIS,6);\n\t\tprogram.addCourse(\"THESIS\", THESIS, 12);\n\t\tprogram.addCourse(\"THESIS++\", THESIS, 24);\n\t}\n\t\n\[email protected]\n\tpublic void testFlexible() {\n\t\tvar program = this.factory.flexible();\n\t\tfillProgram(program);\n\t\tassertTrue(program.isValid(Set.of(\"PRG\",\"ALG\",\"ARCH\",\"MAT1\",\"FIS1\",\"THESIS\"))); // 60 cfu\n\t\tassertTrue(program.isValid(Set.of(\"PRG\",\"ALG\",\"WEB\",\"SOFTENG\", \"MAT1\",\"FIS1\",\"THESIS\"))); // 60 cfu\n\t\tassertFalse(program.isValid(Set.of(\"PRG\",\"ALG\",\"WEB\",\"SOFTENG\", \"MAT1\",\"FIS1\",\"THESIS++\"))); // 66 cfu\n\t\tassertFalse(program.isValid(Set.of(\"PRG\",\"ALG\",\"WEB\"))); // 36 cfu\n\t\tassertFalse(program.isValid(Set.of())); // 0 cfu\n\t}\n\t\n\[email protected]\n\tpublic void testScientific() {\n\t\tvar program = this.factory.scientific();\n\t\tfillProgram(program);\n\t\tassertTrue(program.isValid(Set.of(\"PRG\",\"ALG\",\"MAT1\",\"MAT2\",\"FIS1\",\"FIS2\",\"OOP\"))); // ok\n\t\tassertFalse(program.isValid(Set.of(\"PRG\",\"ALG\",\"MAT1\",\"WEB\",\"FIS1\",\"FIS2\",\"OOP\"))); // not enough Math\n\t\tassertFalse(program.isValid(Set.of(\"PRG\",\"ALG\",\"MAT1\",\"MAT2\",\"WEB\",\"FIS2\",\"OOP\"))); // not enough Phys\n\t\tassertFalse(program.isValid(Set.of(\"OOP\",\"SOFTENG\",\"NETWORKS\",\"ARCH\",\"MAT1\",\"MAT2\",\"FIS1\",\"FIS2\",\"THESIS\"))); // too much CFUs\n\t}\n\t\n\[email protected]\n\tpublic void testShortCS() {\n\t\tvar program = this.factory.shortComputerScience();\n\t\tfillProgram(program);\n\t\tassertTrue(program.isValid(Set.of(\"PRG\",\"ALG\",\"ARCH\",\"THESIS\"))); // ok\n\t\tassertTrue(program.isValid(Set.of(\"PRG\",\"ALG\",\"ARCH\",\"THESIS\",\"MAT1\"))); // ok\n\t\tassertFalse(program.isValid(Set.of(\"PRG\",\"ALG\",\"THESIS\",\"MAT1\",\"MAT2\"))); // not enough Computers\n\t\tassertFalse(program.isValid(Set.of(\"PRG\",\"ALG\",\"THESIS\"))); // not enough CFUs\n\t}\n\t\n\[email protected]\n\tpublic void testRealistic() {\n\t\tvar program = this.factory.realistic();\n\t\tfillProgram(program);\n\t\tassertTrue(program.isValid(Set.of(\"PRG\",\"ALG\",\"ARCH\",\"OOP\",\"SISOP\",\"WEB\",\"SOFTENG\",\n\t\t\t\t\"NETWORKS\",\"MAT1\",\"MAT2\",\"FIS1\",\"THESIS++\"))); // ok\n\t\tassertFalse(program.isValid(Set.of(\"PRG\",\"ALG\",\"ARCH\",\"OOP\",\"SISOP\",\"WEB\",\"SOFTENG\",\n\t\t\t\t\"NETWORKS\",\"MAT1\",\"MAT2\",\"FIS1\",\"THESIS\"))); // not enough CFUs\n\t\tassertFalse(program.isValid(Set.of(\"PRG\",\"ALG\",\"ARCH\",\"OOP\",\"SISOP\",\"WEB\",\"SOFTENG\",\n\t\t\t\t\"MAT1\",\"MAT2\",\"FIS1\",\"FIS2\",\"THESIS++\"))); // too much MATH+FIS\n\t}\n}", "filename": "Test.java" }
2021
a06
[ { "content": "package a06.sol1;\n\n\npublic interface CirclerFactory {\n\t\n\t\n\t<T> Circler<T> leftToRight(); \n\t\n\t\n\t<T> Circler<T> alternate();\n\t\n\t\n\t<T> Circler<T> stayToLast();\n\t\n\t\n\t<T> Circler<T> leftToRightSkipOne();\n\t\n\t\n\t<T> Circler<T> alternateSkipOne();\n\t\n\t\n\t<T> Circler<T> stayToLastSkipOne();\n}", "filename": "CirclerFactory.java" }, { "content": "package a06.sol1;\n\nimport java.util.List;\n\n\npublic interface Circler<T> {\n\t\n\t\n\tvoid setSource(List<T> elements);\n\t\n\t\n\tT produceOne();\n\t\n\t\n\tList<T> produceMany(int n);\n\n}", "filename": "Circler.java" }, { "content": "package a06.sol1;\n\nimport java.util.Objects;\n\n\n\npublic class Pair<E1,E2> {\n\t\n\tprivate final E1 e1;\n\tprivate final E2 e2;\n\t\n\tpublic Pair(E1 x, E2 y) {\n\t\tsuper();\n\t\tthis.e1 = x;\n\t\tthis.e2 = y;\n\t}\n\n\tpublic E1 get1() {\n\t\treturn e1;\n\t}\n\n\tpublic E2 get2() {\n\t\treturn e2;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Objects.hash(e1, e2);\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj) {\n\t\t\treturn true;\n\t\t}\n\t\tif (obj == null) {\n\t\t\treturn false;\n\t\t}\n\t\tif (getClass() != obj.getClass()) {\n\t\t\treturn false;\n\t\t}\n\t\tPair other = (Pair) obj;\n\t\treturn Objects.equals(e1, other.e1) && Objects.equals(e2, other.e2);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Pair [e1=\" + e1 + \", e2=\" + e2 + \"]\";\n\t}\n\t\n\t\n\n}", "filename": "Pair.java" } ]
[ { "content": "package a06.sol1;\n\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.function.Function;\nimport java.util.stream.Stream;\nimport java.util.stream.Collectors;\n\n\n\n/**\n * An alternative solution would be to use template method, with CirclerTemplate\n * being an asbtract class with an abstract method:\n * \n * Stream<Integer> indexes(int size)\n * \n * In this case, each method in the factory relies on a different implementation\n * of CirclerTemplate. Possibly, ...SkipOne versions could be Obtained in one shot\n * by a wrapper/decorator.\n *\n */\npublic class CirclerFactoryImpl implements CirclerFactory {\n\t\n\tprivate class CirclerTemplate<T> implements Circler<T> {\n\t\t\n\t\tprivate Iterator<T> iterator = null;\n\t\tprivate final Function<Integer, Stream<Integer>> indexes;\n\t\t\n\t\tprotected CirclerTemplate(Function<Integer, Stream<Integer>> indexes) {\n\t\t\tthis.indexes = indexes;\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic void setSource(List<T> elements) {\n\t\t\tthis.iterator = indexes.apply(elements.size()).map(elements::get).iterator();\n\t\t}\n\n\t\t@Override\n\t\tpublic T produceOne() {\n\t\t\treturn this.iterator.next();\n\t\t}\n\n\t\t@Override\n\t\tpublic List<T> produceMany(int n) {\n\t\t\treturn Stream.generate(this::produceOne).limit(n).collect(Collectors.toList());\n\t\t}\n\t}\n\t\n\tprivate Stream<Integer> lr(int n) { \n\t\treturn Stream.iterate(0, i -> i + 1).map(i -> i % n);\n\t}\n\t\n\tprivate Stream<Integer> alt(int n) { \n\t\treturn Stream.iterate(0, i -> i+1).map(i -> (i / n) % 2 == 0 ? i % n : n - 1 - (i % n));\n\t}\n\n\tprivate Stream<Integer> last(int n) { \n\t\treturn Stream.iterate(0, i -> i == n-1 ? i : i+1);\n\t}\n\t\n\tprivate Stream<Integer> skipOne(Stream<Integer> stream) {\n\t\tvar it = stream.iterator();\n\t\treturn Stream.generate(()-> it.next()).peek(i -> it.next());\n\t}\n\t\t\t\t\n\t@Override\n\tpublic <T> Circler<T> leftToRight() {\n\t\treturn new CirclerTemplate<>(this::lr);\n\t}\n\t\n\t\n\t@Override\n\tpublic <T> Circler<T> alternate() {\n\t\treturn new CirclerTemplate<>(this::alt);\n\t}\n\n\t@Override\n\tpublic <T> Circler<T> stayToLast() {\n\t\treturn new CirclerTemplate<>(this::last);\n\t}\n\n\t@Override\n\tpublic <T> Circler<T> leftToRightSkipOne() {\n\t\treturn new CirclerTemplate<>(n -> skipOne(this.lr(n)));\n\t}\n\n\t@Override\n\tpublic <T> Circler<T> alternateSkipOne() {\n\t\treturn new CirclerTemplate<>(n -> skipOne(this.alt(n)));\n\t}\n\n\t@Override\n\tpublic <T> Circler<T> stayToLastSkipOne() {\n\t\treturn new CirclerTemplate<>(n -> skipOne(this.last(n)));\n\t}\n\t\n}", "filename": "CirclerFactoryImpl.java" } ]
{ "components": { "imports": "package a06.sol1;\n\nimport static org.junit.Assert.*;\n\nimport java.util.List;", "private_init": "\t/*\n\t * Implement the CirclerFactory interface as indicated in the initFactory method below.\n\t * Create a factory for Circler<T> objects, which are objects with functionalities to iterate over the data\n\t * of a source consisting of a (finite) list of elements of type T.\n\t *\n\t * The comments on the provided interfaces, and the test methods below\n\t * constitute the necessary explanation of the problem.\n\t *\n\t * The following are considered optional for the purpose of being able to correct\n\t * the exercise, but still contribute to achieving the totality of the\n\t * score:\n\t *\n\t * - the stayToLastSkipOne and alternateSkipOne methods (whose tests start with \"optional...\")\n\t *\n\t * - the good design of the solution, reusing as much code as possible and keeping all\n\t * implementations very succinct\n\t *\n\t * Remove the comment from the initFactory method.\n\t *\n\t * Scoring indications:\n\t *\n\t * - correctness of the mandatory part: 9 points\n\t *\n\t * - correctness of the optional part: 3 points (2 additional methods)\n\t *\n\t * - quality of the solution: 5 points (for the good design of the solution, as indicated above)\n\t *\n\t */\n\n\tprivate CirclerFactory factory;\n\t\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.factory = new CirclerFactoryImpl();\n\t}", "test_functions": [ "\[email protected]\n\tpublic void testLeftToRight() {\n\t\tvar circler = this.factory.leftToRight();\n\t\tcircler.setSource(List.of(10,20,30)); // iteration: 10,20,30,10,20,30,10,20,30,...\n\t\t\n\t\tassertEquals(10, circler.produceOne());\n\t\tassertEquals(20, circler.produceOne());\n\t\tassertEquals(30, circler.produceOne());\n\t\tassertEquals(10, circler.produceOne());\n\t\tassertEquals(20, circler.produceOne());\n\t\t\n\t\t// produce the next 5\n\t\tassertEquals(List.of(30,10,20,30,10), circler.produceMany(5));\n\t\t\n\t\t// new source: reset and start again with the new iteration\n\t\tcircler.setSource(List.of(\"1\",\"2\",\"3\",\"4\"));\n\t\tassertEquals(\"1\", circler.produceOne());\n\t\tassertEquals(\"2\", circler.produceOne());\n\t\tassertEquals(\"3\", circler.produceOne());\n\t\tassertEquals(\"4\", circler.produceOne());\n\t\tassertEquals(\"1\", circler.produceOne());\n\t}", "\[email protected]\n\tpublic void testAlternate() {\n\t\tvar circler = this.factory.alternate();\n\t\tcircler.setSource(List.of(10,20,30)); // iteration: 10,20,30,30,20,10,10,20,30,...\n\t\t\n\t\tassertEquals(10, circler.produceOne());\n\t\tassertEquals(20, circler.produceOne());\n\t\tassertEquals(30, circler.produceOne());\n\t\tassertEquals(30, circler.produceOne());\n\t\tassertEquals(20, circler.produceOne());\n\t\t\n\t\tassertEquals(List.of(10,10,20,30,30), circler.produceMany(5));\n\t\t\n\t\tcircler.setSource(List.of(\"1\",\"2\",\"3\",\"4\"));\n\t\tassertEquals(\"1\", circler.produceOne());\n\t\tassertEquals(\"2\", circler.produceOne());\n\t\tassertEquals(\"3\", circler.produceOne());\n\t\tassertEquals(\"4\", circler.produceOne());\n\t\tassertEquals(\"4\", circler.produceOne());\n\t\tassertEquals(\"3\", circler.produceOne());\n\t}", "\[email protected]\n\tpublic void testStayToLast() {\n\t\tvar circler = this.factory.stayToLast();\n\t\tcircler.setSource(List.of(10,20,30));\n\t\t\n\t\tassertEquals(10, circler.produceOne());\n\t\tassertEquals(20, circler.produceOne());\n\t\tassertEquals(30, circler.produceOne());\n\t\tassertEquals(30, circler.produceOne());\n\t\tassertEquals(30, circler.produceOne());\n\t\tassertEquals(30, circler.produceOne());\n\t\t\n\t\tcircler.setSource(List.of(\"1\",\"2\",\"3\",\"4\"));\n\t\tassertEquals(\"1\", circler.produceOne());\n\t\tassertEquals(List.of(\"2\",\"3\",\"4\",\"4\",\"4\",\"4\",\"4\",\"4\",\"4\",\"4\"), circler.produceMany(10));\n\t}", "\[email protected]\n\tpublic void testLeftToRightSkipOne() {\n\t\tvar circler = this.factory.leftToRightSkipOne();\n\t\t\n\t\tcircler.setSource(List.of(10,20,30,40,50));\n\t\tassertEquals(List.of(10,30,50,20,40,10,30,50,20,40), circler.produceMany(10));\n\t\t\n\t\tcircler.setSource(List.of(10,20,30,40));\n\t\tassertEquals(List.of(10,30,10,30,10,30,10,30,10,30), circler.produceMany(10));\n\t}", "\[email protected]\n\tpublic void optionalTestAlternateSkipOne() {\n\t\tvar circler = this.factory.alternateSkipOne();\n\t\t\n\t\tcircler.setSource(List.of(10,20,30,40,50));\n\t\tassertEquals(List.of(10,30,50,40,20,10,30,50,40,20), circler.produceMany(10));\n\t\t\n\t\tcircler.setSource(List.of(10,20,30,40));\n\t\tassertEquals(List.of(10,30,40,20,10,30,40,20,10,30), circler.produceMany(10));\n\t}", "\[email protected]\n\tpublic void optionalTestStayToLastSkipOne() {\n\t\tvar circler = this.factory.stayToLastSkipOne();\n\t\t\n\t\tcircler.setSource(List.of(10,20,30,40,50));\n\t\tassertEquals(List.of(10,30,50,50,50,50,50,50,50,50), circler.produceMany(10));\n\t\t\n\t\tcircler.setSource(List.of(10,20,30,40));\n\t\tassertEquals(List.of(10,30,40,40,40,40,40,40,40,40), circler.produceMany(10));\n\t}" ] }, "content": "package a06.sol1;\n\nimport static org.junit.Assert.*;\n\nimport java.util.List;\n\npublic class Test {\n\n\t/*\n\t * Implement the CirclerFactory interface as indicated in the initFactory method below.\n\t * Create a factory for Circler<T> objects, which are objects with functionalities to iterate over the data\n\t * of a source consisting of a (finite) list of elements of type T.\n\t *\n\t * The comments on the provided interfaces, and the test methods below\n\t * constitute the necessary explanation of the problem.\n\t *\n\t * The following are considered optional for the purpose of being able to correct\n\t * the exercise, but still contribute to achieving the totality of the\n\t * score:\n\t *\n\t * - the stayToLastSkipOne and alternateSkipOne methods (whose tests start with \"optional...\")\n\t *\n\t * - the good design of the solution, reusing as much code as possible and keeping all\n\t * implementations very succinct\n\t *\n\t * Remove the comment from the initFactory method.\n\t *\n\t * Scoring indications:\n\t *\n\t * - correctness of the mandatory part: 9 points\n\t *\n\t * - correctness of the optional part: 3 points (2 additional methods)\n\t *\n\t * - quality of the solution: 5 points (for the good design of the solution, as indicated above)\n\t *\n\t */\n\n\tprivate CirclerFactory factory;\n\t\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.factory = new CirclerFactoryImpl();\n\t}\n\t\n\[email protected]\n\tpublic void testLeftToRight() {\n\t\tvar circler = this.factory.leftToRight();\n\t\tcircler.setSource(List.of(10,20,30)); // iteration: 10,20,30,10,20,30,10,20,30,...\n\t\t\n\t\tassertEquals(10, circler.produceOne());\n\t\tassertEquals(20, circler.produceOne());\n\t\tassertEquals(30, circler.produceOne());\n\t\tassertEquals(10, circler.produceOne());\n\t\tassertEquals(20, circler.produceOne());\n\t\t\n\t\t// produce the next 5\n\t\tassertEquals(List.of(30,10,20,30,10), circler.produceMany(5));\n\t\t\n\t\t// new source: reset and start again with the new iteration\n\t\tcircler.setSource(List.of(\"1\",\"2\",\"3\",\"4\"));\n\t\tassertEquals(\"1\", circler.produceOne());\n\t\tassertEquals(\"2\", circler.produceOne());\n\t\tassertEquals(\"3\", circler.produceOne());\n\t\tassertEquals(\"4\", circler.produceOne());\n\t\tassertEquals(\"1\", circler.produceOne());\n\t}\n\t\n\[email protected]\n\tpublic void testAlternate() {\n\t\tvar circler = this.factory.alternate();\n\t\tcircler.setSource(List.of(10,20,30)); // iteration: 10,20,30,30,20,10,10,20,30,...\n\t\t\n\t\tassertEquals(10, circler.produceOne());\n\t\tassertEquals(20, circler.produceOne());\n\t\tassertEquals(30, circler.produceOne());\n\t\tassertEquals(30, circler.produceOne());\n\t\tassertEquals(20, circler.produceOne());\n\t\t\n\t\tassertEquals(List.of(10,10,20,30,30), circler.produceMany(5));\n\t\t\n\t\tcircler.setSource(List.of(\"1\",\"2\",\"3\",\"4\"));\n\t\tassertEquals(\"1\", circler.produceOne());\n\t\tassertEquals(\"2\", circler.produceOne());\n\t\tassertEquals(\"3\", circler.produceOne());\n\t\tassertEquals(\"4\", circler.produceOne());\n\t\tassertEquals(\"4\", circler.produceOne());\n\t\tassertEquals(\"3\", circler.produceOne());\n\t}\n\t\n\[email protected]\n\tpublic void testStayToLast() {\n\t\tvar circler = this.factory.stayToLast();\n\t\tcircler.setSource(List.of(10,20,30));\n\t\t\n\t\tassertEquals(10, circler.produceOne());\n\t\tassertEquals(20, circler.produceOne());\n\t\tassertEquals(30, circler.produceOne());\n\t\tassertEquals(30, circler.produceOne());\n\t\tassertEquals(30, circler.produceOne());\n\t\tassertEquals(30, circler.produceOne());\n\t\t\n\t\tcircler.setSource(List.of(\"1\",\"2\",\"3\",\"4\"));\n\t\tassertEquals(\"1\", circler.produceOne());\n\t\tassertEquals(List.of(\"2\",\"3\",\"4\",\"4\",\"4\",\"4\",\"4\",\"4\",\"4\",\"4\"), circler.produceMany(10));\n\t}\n\t\n\[email protected]\n\tpublic void testLeftToRightSkipOne() {\n\t\tvar circler = this.factory.leftToRightSkipOne();\n\t\t\n\t\tcircler.setSource(List.of(10,20,30,40,50));\n\t\tassertEquals(List.of(10,30,50,20,40,10,30,50,20,40), circler.produceMany(10));\n\t\t\n\t\tcircler.setSource(List.of(10,20,30,40));\n\t\tassertEquals(List.of(10,30,10,30,10,30,10,30,10,30), circler.produceMany(10));\n\t}\n\t\n\[email protected]\n\tpublic void optionalTestAlternateSkipOne() {\n\t\tvar circler = this.factory.alternateSkipOne();\n\t\t\n\t\tcircler.setSource(List.of(10,20,30,40,50));\n\t\tassertEquals(List.of(10,30,50,40,20,10,30,50,40,20), circler.produceMany(10));\n\t\t\n\t\tcircler.setSource(List.of(10,20,30,40));\n\t\tassertEquals(List.of(10,30,40,20,10,30,40,20,10,30), circler.produceMany(10));\n\t}\n\t\n\[email protected]\n\tpublic void optionalTestStayToLastSkipOne() {\n\t\tvar circler = this.factory.stayToLastSkipOne();\n\t\t\n\t\tcircler.setSource(List.of(10,20,30,40,50));\n\t\tassertEquals(List.of(10,30,50,50,50,50,50,50,50,50), circler.produceMany(10));\n\t\t\n\t\tcircler.setSource(List.of(10,20,30,40));\n\t\tassertEquals(List.of(10,30,40,40,40,40,40,40,40,40), circler.produceMany(10));\n\t}\n}", "filename": "Test.java" }
2021
a01a
[ { "content": "package a01a.sol1;\n\nimport java.util.Optional;\n\n\npublic interface Acceptor<E,R> {\n\t\n\t\n\tboolean accept(E e);\n\t\n\t\n\tOptional<R> end();\n}", "filename": "Acceptor.java" }, { "content": "package a01a.sol1;\n\nimport java.util.Optional;\nimport java.util.function.BiFunction;\nimport java.util.function.Function;\n\n\npublic interface AcceptorFactory {\n\t\n\t\n\tAcceptor<String,Integer> countEmptyStringsOnAnySequence();\n\n\t\n\tAcceptor<Integer,String> showAsStringOnlyOnIncreasingSequences();\n\t\n\t\n\tAcceptor<Integer,Integer> sumElementsOnlyInTriples();\n\t\n\t\n\t<E,O1,O2> Acceptor<E,Pair<O1,O2>> acceptBoth(Acceptor<E,O1> a1, Acceptor<E,O2> a2);\n\t\n\t\n\t<E, O, S> Acceptor<E, O> generalised(S initial, BiFunction<E, S, Optional<S>> stateFun, Function<S,Optional<O>> outputFun);\n\t\t\n}", "filename": "AcceptorFactory.java" }, { "content": "package a01a.sol1;\n\nimport java.util.Objects;\n\n\n\npublic class Pair<E1,E2> {\n\t\n\tprivate final E1 e1;\n\tprivate final E2 e2;\n\t\n\tpublic Pair(E1 x, E2 y) {\n\t\tsuper();\n\t\tthis.e1 = x;\n\t\tthis.e2 = y;\n\t}\n\n\tpublic E1 get1() {\n\t\treturn e1;\n\t}\n\n\tpublic E2 get2() {\n\t\treturn e2;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Objects.hash(e1, e2);\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj) {\n\t\t\treturn true;\n\t\t}\n\t\tif (obj == null) {\n\t\t\treturn false;\n\t\t}\n\t\tif (getClass() != obj.getClass()) {\n\t\t\treturn false;\n\t\t}\n\t\tPair other = (Pair) obj;\n\t\treturn Objects.equals(e1, other.e1) && Objects.equals(e2, other.e2);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Pair [e1=\" + e1 + \", e2=\" + e2 + \"]\";\n\t}\n\t\n\t\n\n}", "filename": "Pair.java" } ]
[ { "content": "package a01a.sol1;\n\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Optional;\nimport java.util.function.BiFunction;\nimport java.util.function.Function;\nimport java.util.stream.Collectors;\n\n// Soluzione base, senza rimozione ripetizioni via pattern\n\npublic class AcceptorFactoryImpl implements AcceptorFactory {\n\n\t@Override\n\tpublic Acceptor<String, Integer> countEmptyStringsOnAnySequence() {\n\t\treturn new Acceptor<>() {\n\t\t\tprivate int count = 0;\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic boolean accept(String e) {\n\t\t\t\tif (e.length()==0) {\n\t\t\t\t\tthis.count++;\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Optional<Integer> end() {\n\t\t\t\treturn Optional.of(count);\n\t\t\t}\n\t\t};\n\t}\n\t\n\t@Override\n\tpublic Acceptor<Integer, Integer> sumElementsOnlyInTriples() {\n\t\treturn new Acceptor<>() {\n\t\t\tprivate List<Integer> list = new LinkedList<>();\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic boolean accept(Integer e) {\n\t\t\t\tif (list.size()>3) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tthis.list.add(e);\n\t\t\t\treturn list.size()<=3;\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Optional<Integer> end() {\n\t\t\t\treturn Optional.of(list)\n\t\t\t\t\t\t.filter(l -> l.size()==3)\n\t\t\t\t\t\t.map(l -> l.stream().collect(Collectors.summingInt(i->i)));\n\t\t\t}\n\t\t};\n\t}\n\n\n\t@Override\n\tpublic Acceptor<Integer, String> showAsStringOnlyOnIncreasingSequences() {\n\t\treturn new Acceptor<>() {\n\t\t\tprivate String string = \"\";\n\t\t\tprivate Optional<Integer> last = Optional.empty();\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic boolean accept(Integer e) {\n\t\t\t\tif (this.string.length()>0 && (this.last.isEmpty() || e <= this.last.get())) {\n\t\t\t\t\tthis.last = Optional.empty();\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tthis.last = Optional.of(e);\n\t\t\t\tstring = string + (string.length()>0 ? \":\" : \"\") + e;\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Optional<String> end() {\n\t\t\t\treturn this.last.map(i -> string);\n\t\t\t}\n\t\t};\n\t}\n\n\t@Override\n\tpublic <E, O1, O2> Acceptor<E, Pair<O1, O2>> acceptBoth(Acceptor<E, O1> a1, Acceptor<E, O2> a2) {\n\t\treturn new Acceptor<>() {\n\n\t\t\t@Override\n\t\t\tpublic boolean accept(E e) {\n\t\t\t\treturn a1.accept(e) && a2.accept(e);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Optional<Pair<O1, O2>> end() {\n\t\t\t\treturn a1.end().flatMap(o1 -> a2.end().map( o2 -> new Pair<>(o1,o2)));\n\t\t\t}\n\t\t\t\n\t\t}; \n\t}\n\n\t@Override\n\tpublic <E, O, S> Acceptor<E, O> generalised(S initial, BiFunction<E, S, Optional<S>> stateFunction,\n\t\t\tFunction<S, Optional<O>> outputFunction) {\n\t\treturn new Acceptor<>() {\n\t\t\tprivate Optional<S> state = Optional.of(initial);\n\n\t\t\t@Override\n\t\t\tpublic boolean accept(E e) {\n\t\t\t\tif (state.isEmpty()) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tstate = stateFunction.apply(e, state.get());\n\t\t\t\treturn state.isPresent();\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Optional<O> end() {\n\t\t\t\tif (state.isEmpty()) {\n\t\t\t\t\treturn Optional.empty();\n\t\t\t\t}\n\t\t\t\treturn outputFunction.apply(state.get());\n\t\t\t}\n\t\t};\n\t}\n}", "filename": "AcceptorFactoryImpl.java" }, { "content": "package a01a.sol1;\n\nimport java.util.LinkedList;\nimport java.util.Optional;\nimport java.util.function.BiFunction;\nimport java.util.function.Function;\nimport java.util.stream.Collectors;\n\n// Soluzione avanzata in stile funzionale, con uso di strategy e interfacce funzionali \n\n\npublic class AcceptorFactoryAdvancedImpl implements AcceptorFactory {\n\n\t@Override\n\tpublic Acceptor<String, Integer> countEmptyStringsOnAnySequence() {\n\t\treturn generalised(0,(str,i) -> Optional.of(i + (str.isEmpty() ? 1 : 0)),Optional::of);\t\n\t}\n\n\t@Override\n\tpublic Acceptor<Integer, Integer> sumElementsOnlyInTriples() {\n\t\treturn generalised(\n\t\t\t\tnew LinkedList<Integer>(),\n\t\t\t\t(e,l) -> {l.add(e); return Optional.of(l).filter(ll -> ll.size()<=3);},\n\t\t\t\tl -> Optional.of(l)\n\t\t\t\t\t\t\t.filter(ll -> ll.size()==3)\n\t\t\t\t\t\t\t.map(ll -> ll.stream().collect(Collectors.summingInt(i->i))));\n\t}\n\n\n\t@Override\n\tpublic Acceptor<Integer, String> showAsStringOnlyOnIncreasingSequences() {\n\t\treturn generalised(\n\t\t\t\tnew LinkedList<Integer>(),\n\t\t\t\t(e,l) -> Optional.<LinkedList<Integer>>of(l)\n\t\t\t\t\t\t.filter(ll -> ll.isEmpty() || e > ll.getLast())\n\t\t\t\t\t\t.map(ll -> {ll.add(e); return ll;}),\n\t\t\t\tl -> Optional.of(l.stream().map(String::valueOf).collect(Collectors.joining(\":\"))));\n\t}\n\n\t@Override\n\tpublic <E, O1, O2> Acceptor<E, Pair<O1, O2>> acceptBoth(Acceptor<E, O1> a1, Acceptor<E, O2> a2) {\n\t\treturn new Acceptor<>() {\n\n\t\t\t@Override\n\t\t\tpublic boolean accept(E e) {\n\t\t\t\treturn a1.accept(e) && a2.accept(e);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Optional<Pair<O1, O2>> end() {\n\t\t\t\treturn a1.end().flatMap(o1 -> a2.end().map( o2 -> new Pair<>(o1,o2)));\n\t\t\t}\n\t\t\t\n\t\t}; \n\t}\n\n\t@Override\n\tpublic <E, O, S> Acceptor<E, O> generalised(S initial, BiFunction<E, S, Optional<S>> stateFunction,\n\t\t\tFunction<S, Optional<O>> outputFunction) {\n\t\treturn new Acceptor<>() {\n\t\t\tprivate Optional<S> state = Optional.of(initial);\n\n\t\t\t@Override\n\t\t\tpublic boolean accept(E e) {\n\t\t\t\tstate = state.flatMap(s -> stateFunction.apply(e, s));\n\t\t\t\treturn state.isPresent();\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Optional<O> end() {\n\t\t\t\treturn this.state.flatMap(outputFunction::apply);\n\t\t\t}\n\t\t};\n\t}\n}", "filename": "AcceptorFactoryAdvancedImpl.java" } ]
{ "components": { "imports": "package a01a.sol1;\n\nimport static org.junit.Assert.*;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.NoSuchElementException;\nimport java.util.Optional;\nimport java.util.function.BiFunction;\nimport java.util.function.Function;", "private_init": "\t/*\n\t * Implement the AcceptorFactory interface as indicated in the initFactory method below.\n\t * Create a factory for Acceptors, which are objects that take a sequence of elements one-by-one,\n\t * producing a result if the sequence is correctly accepted.\n\t * \n\t * The comments on the provided interfaces, and the test methods below,\n\t * constitute the necessary explanation of the problem.\n\t * \n\t * The following are considered optional for the possibility of correcting\n\t * the exercise, but still contribute to achieving the totality of the\n\t * score:\n\t * \n\t * - implementation of the five methods in the factory (i.e., in the mandatory part it is sufficient\n\t * to implement 4 at will)\n\t * \n\t * - good design of the solution, using some pattern to avoid repetitions\n\t * \n\t * - avoid creating unnecessary data structures\n\t * \n\t * Remove the comment from the initFactory method.\n\t * \n\t * Scoring indications:\n\t * \n\t * - correctness of the mandatory part: 10 points (2+2+3+3 for the necessary factory methods)\n\t * \n\t * - correctness of the optional part: 3 points (generalised method)\n\t * \n\t * - quality of the solution: 4 points (3 points for pattern, 1 point for no unnecessary structures)\n\t * \n\t */\n\n\tprivate AcceptorFactory factory = null;\n\t\n\t\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.factory = new AcceptorFactoryAdvancedImpl();\n\t}", "test_functions": [ "\[email protected]\n\tpublic void testCountEmptyString() {\n\t\tvar acceptor = this.factory.countEmptyStringsOnAnySequence();\n\t\tassertTrue(acceptor.accept(\"aa\"));\n\t\tassertTrue(acceptor.accept(\"\"));\n\t\tassertTrue(acceptor.accept(\"bbb\"));\n\t\tassertTrue(acceptor.accept(\"\"));\n\t\t// Accepts the sequence \"aa\",\"\",\"bbb\",\"\" and therefore returns 2\n\t\tassertEquals(Optional.of(2), acceptor.end());\n\n\t\tacceptor = this.factory.countEmptyStringsOnAnySequence();\n\t\t// Accepts the empty sequence and therefore returns 0\n\t\tassertEquals(Optional.of(0), acceptor.end());\n\t}", "\[email protected]\n\tpublic void testSumElementsInTriples() {\n\t\tvar acceptor = this.factory.sumElementsOnlyInTriples();\n\t\tassertTrue(acceptor.accept(10));\n\t\tassertTrue(acceptor.accept(20));\n\t\tassertTrue(acceptor.accept(30));\n\t\t// Accepts the sequence 10,20,30 and therefore returns 60\n\t\tassertEquals(Optional.of(60), acceptor.end());\n\t\t\n\t\tacceptor = this.factory.sumElementsOnlyInTriples();\n\t\tassertTrue(acceptor.accept(10));\n\t\tassertTrue(acceptor.accept(20));\n\t\t// Does not accept the sequence 10,20\n\t\tassertEquals(Optional.empty(), acceptor.end());\n\t\t\n\t\tacceptor = this.factory.sumElementsOnlyInTriples();\n\t\tassertTrue(acceptor.accept(10));\n\t\tassertTrue(acceptor.accept(20));\n\t\tassertTrue(acceptor.accept(30));\n\t\tassertFalse(acceptor.accept(40));\n\t\t// Does not accept the sequence 10,20,30,40\n\t\tassertEquals(Optional.empty(), acceptor.end());\n\t}", "\[email protected]\n\tpublic void testShowAnIncreasingSequence() {\n\t\tvar acceptor = this.factory.showAsStringOnlyOnIncreasingSequences();\n\t\tassertTrue(acceptor.accept(10));\n\t\tassertTrue(acceptor.accept(15));\n\t\tassertTrue(acceptor.accept(20));\n\t\t// Accepts the sequence 10,15,20 and therefore returns the string below\n\t\tassertEquals(Optional.of(\"10:15:20\"), acceptor.end());\n\n\t\tacceptor = this.factory.showAsStringOnlyOnIncreasingSequences();\n\t\tassertTrue(acceptor.accept(10));\n\t\tassertFalse(acceptor.accept(8)); // not accepted\n\t\tassertFalse(acceptor.accept(9)); // not accepted\n\t\t// Does not accept the sequence 10,9,8\n\t\tassertEquals(Optional.empty(), acceptor.end());\n\t}", "\[email protected]\n\tpublic void testBoth1() {\n\t\tvar acceptor1 = this.factory.showAsStringOnlyOnIncreasingSequences();\n\t\tvar acceptor2 = this.factory.sumElementsOnlyInTriples();\n\t\tvar acceptor = this.factory.acceptBoth(acceptor1, acceptor2);\n\t\tassertTrue(acceptor.accept(10));\n\t\tassertTrue(acceptor.accept(15));\n\t\tassertTrue(acceptor.accept(20));\n\t\t// Accepts the sequence 10,15,20 and therefore returns the pair of the two results\n\t\tassertEquals(Optional.of(new Pair<>(\"10:15:20\",45)), acceptor.end());\t\n\t}", "\[email protected]\n\tpublic void testBoth2() {\n\t\tvar acceptor1 = this.factory.showAsStringOnlyOnIncreasingSequences();\n\t\tvar acceptor2 = this.factory.sumElementsOnlyInTriples();\n\t\tvar acceptor = this.factory.acceptBoth(acceptor1, acceptor2);\n\t\tassertTrue(acceptor.accept(10));\n\t\tassertFalse(acceptor.accept(8)); // not accepted by acceptor1\n\t\tassertFalse(acceptor.accept(9));\n\t\t// Does not accept the sequence 10,8,9\n\t\tassertEquals(Optional.empty(), acceptor.end());\t\n\t}", "\[email protected]\n\tpublic void testBoth3() {\n\t\tvar acceptor1 = this.factory.showAsStringOnlyOnIncreasingSequences();\n\t\tvar acceptor2 = this.factory.sumElementsOnlyInTriples();\n\t\tvar acceptor = this.factory.acceptBoth(acceptor1, acceptor2);\n\t\tassertTrue(acceptor.accept(10));\n\t\tassertTrue(acceptor.accept(12));\n\t\t// Does not accept the sequence 10,12, because acceptor2 does not accept it\n\t\tassertEquals(Optional.empty(), acceptor.end());\t\n\t}", "\[email protected]\n\tpublic void testGeneralised1() {\n\t\t// updates the state by incrementing 1 if the string length is 0\n\t\tBiFunction<String,Integer,Optional<Integer>> stateFunction =\n\t\t\t\t(s,i) -> Optional.of(i + (s.length()==0 ? 1 : 0));\n\t\t// outputs the accumulated state\n\t\tFunction<Integer, Optional<Integer>> outputFunction = s -> Optional.of(s);\n\t\t// This acceptor is the same as the testCountEmptyString\n\t\tvar acceptor = this.factory.generalised(0,stateFunction,outputFunction);\n\t\tassertTrue(acceptor.accept(\"aa\"));\n\t\tassertTrue(acceptor.accept(\"\"));\n\t\tassertTrue(acceptor.accept(\"bbb\"));\n\t\tassertTrue(acceptor.accept(\"\"));\n\t\tassertEquals(Optional.of(2), acceptor.end());\n\t\tacceptor = this.factory.generalised(0,stateFunction,outputFunction);\n\t\tassertEquals(Optional.of(0), acceptor.end());\n\t}", "\[email protected]\n\tpublic void testGeneralised2() {\n\t\t// updates the state by adding to an internal list, if it does not exceed size 3\n\t\tBiFunction<Integer,List<Integer>,Optional<List<Integer>>> stateFunction =\n\t\t\t\t(i,l) -> { l.add(i); return Optional.of(l).filter(ll -> ll.size()<=3);}" ] }, "content": "package a01a.sol1;\n\nimport static org.junit.Assert.*;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.NoSuchElementException;\nimport java.util.Optional;\nimport java.util.function.BiFunction;\nimport java.util.function.Function;\n\npublic class Test {\n\n\t/*\n\t * Implement the AcceptorFactory interface as indicated in the initFactory method below.\n\t * Create a factory for Acceptors, which are objects that take a sequence of elements one-by-one,\n\t * producing a result if the sequence is correctly accepted.\n\t * \n\t * The comments on the provided interfaces, and the test methods below,\n\t * constitute the necessary explanation of the problem.\n\t * \n\t * The following are considered optional for the possibility of correcting\n\t * the exercise, but still contribute to achieving the totality of the\n\t * score:\n\t * \n\t * - implementation of the five methods in the factory (i.e., in the mandatory part it is sufficient\n\t * to implement 4 at will)\n\t * \n\t * - good design of the solution, using some pattern to avoid repetitions\n\t * \n\t * - avoid creating unnecessary data structures\n\t * \n\t * Remove the comment from the initFactory method.\n\t * \n\t * Scoring indications:\n\t * \n\t * - correctness of the mandatory part: 10 points (2+2+3+3 for the necessary factory methods)\n\t * \n\t * - correctness of the optional part: 3 points (generalised method)\n\t * \n\t * - quality of the solution: 4 points (3 points for pattern, 1 point for no unnecessary structures)\n\t * \n\t */\n\n\tprivate AcceptorFactory factory = null;\n\t\n\t\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.factory = new AcceptorFactoryAdvancedImpl();\n\t}\n\t\n\[email protected]\n\tpublic void testCountEmptyString() {\n\t\tvar acceptor = this.factory.countEmptyStringsOnAnySequence();\n\t\tassertTrue(acceptor.accept(\"aa\"));\n\t\tassertTrue(acceptor.accept(\"\"));\n\t\tassertTrue(acceptor.accept(\"bbb\"));\n\t\tassertTrue(acceptor.accept(\"\"));\n\t\t// Accepts the sequence \"aa\",\"\",\"bbb\",\"\" and therefore returns 2\n\t\tassertEquals(Optional.of(2), acceptor.end());\n\n\t\tacceptor = this.factory.countEmptyStringsOnAnySequence();\n\t\t// Accepts the empty sequence and therefore returns 0\n\t\tassertEquals(Optional.of(0), acceptor.end());\n\t}\n\t\n\[email protected]\n\tpublic void testSumElementsInTriples() {\n\t\tvar acceptor = this.factory.sumElementsOnlyInTriples();\n\t\tassertTrue(acceptor.accept(10));\n\t\tassertTrue(acceptor.accept(20));\n\t\tassertTrue(acceptor.accept(30));\n\t\t// Accepts the sequence 10,20,30 and therefore returns 60\n\t\tassertEquals(Optional.of(60), acceptor.end());\n\t\t\n\t\tacceptor = this.factory.sumElementsOnlyInTriples();\n\t\tassertTrue(acceptor.accept(10));\n\t\tassertTrue(acceptor.accept(20));\n\t\t// Does not accept the sequence 10,20\n\t\tassertEquals(Optional.empty(), acceptor.end());\n\t\t\n\t\tacceptor = this.factory.sumElementsOnlyInTriples();\n\t\tassertTrue(acceptor.accept(10));\n\t\tassertTrue(acceptor.accept(20));\n\t\tassertTrue(acceptor.accept(30));\n\t\tassertFalse(acceptor.accept(40));\n\t\t// Does not accept the sequence 10,20,30,40\n\t\tassertEquals(Optional.empty(), acceptor.end());\n\t}\n\t\n\[email protected]\n\tpublic void testShowAnIncreasingSequence() {\n\t\tvar acceptor = this.factory.showAsStringOnlyOnIncreasingSequences();\n\t\tassertTrue(acceptor.accept(10));\n\t\tassertTrue(acceptor.accept(15));\n\t\tassertTrue(acceptor.accept(20));\n\t\t// Accepts the sequence 10,15,20 and therefore returns the string below\n\t\tassertEquals(Optional.of(\"10:15:20\"), acceptor.end());\n\n\t\tacceptor = this.factory.showAsStringOnlyOnIncreasingSequences();\n\t\tassertTrue(acceptor.accept(10));\n\t\tassertFalse(acceptor.accept(8)); // not accepted\n\t\tassertFalse(acceptor.accept(9)); // not accepted\n\t\t// Does not accept the sequence 10,9,8\n\t\tassertEquals(Optional.empty(), acceptor.end());\n\t}\n\t\n\[email protected]\n\tpublic void testBoth1() {\n\t\tvar acceptor1 = this.factory.showAsStringOnlyOnIncreasingSequences();\n\t\tvar acceptor2 = this.factory.sumElementsOnlyInTriples();\n\t\tvar acceptor = this.factory.acceptBoth(acceptor1, acceptor2);\n\t\tassertTrue(acceptor.accept(10));\n\t\tassertTrue(acceptor.accept(15));\n\t\tassertTrue(acceptor.accept(20));\n\t\t// Accepts the sequence 10,15,20 and therefore returns the pair of the two results\n\t\tassertEquals(Optional.of(new Pair<>(\"10:15:20\",45)), acceptor.end());\t\n\t}\n\t\n\[email protected]\n\tpublic void testBoth2() {\n\t\tvar acceptor1 = this.factory.showAsStringOnlyOnIncreasingSequences();\n\t\tvar acceptor2 = this.factory.sumElementsOnlyInTriples();\n\t\tvar acceptor = this.factory.acceptBoth(acceptor1, acceptor2);\n\t\tassertTrue(acceptor.accept(10));\n\t\tassertFalse(acceptor.accept(8)); // not accepted by acceptor1\n\t\tassertFalse(acceptor.accept(9));\n\t\t// Does not accept the sequence 10,8,9\n\t\tassertEquals(Optional.empty(), acceptor.end());\t\n\t}\n\t\n\[email protected]\n\tpublic void testBoth3() {\n\t\tvar acceptor1 = this.factory.showAsStringOnlyOnIncreasingSequences();\n\t\tvar acceptor2 = this.factory.sumElementsOnlyInTriples();\n\t\tvar acceptor = this.factory.acceptBoth(acceptor1, acceptor2);\n\t\tassertTrue(acceptor.accept(10));\n\t\tassertTrue(acceptor.accept(12));\n\t\t// Does not accept the sequence 10,12, because acceptor2 does not accept it\n\t\tassertEquals(Optional.empty(), acceptor.end());\t\n\t}\n\n\[email protected]\n\tpublic void testGeneralised1() {\n\t\t// updates the state by incrementing 1 if the string length is 0\n\t\tBiFunction<String,Integer,Optional<Integer>> stateFunction =\n\t\t\t\t(s,i) -> Optional.of(i + (s.length()==0 ? 1 : 0));\n\t\t// outputs the accumulated state\n\t\tFunction<Integer, Optional<Integer>> outputFunction = s -> Optional.of(s);\n\t\t// This acceptor is the same as the testCountEmptyString\n\t\tvar acceptor = this.factory.generalised(0,stateFunction,outputFunction);\n\t\tassertTrue(acceptor.accept(\"aa\"));\n\t\tassertTrue(acceptor.accept(\"\"));\n\t\tassertTrue(acceptor.accept(\"bbb\"));\n\t\tassertTrue(acceptor.accept(\"\"));\n\t\tassertEquals(Optional.of(2), acceptor.end());\n\t\tacceptor = this.factory.generalised(0,stateFunction,outputFunction);\n\t\tassertEquals(Optional.of(0), acceptor.end());\n\t}\n\t\n\[email protected]\n\tpublic void testGeneralised2() {\n\t\t// updates the state by adding to an internal list, if it does not exceed size 3\n\t\tBiFunction<Integer,List<Integer>,Optional<List<Integer>>> stateFunction =\n\t\t\t\t(i,l) -> { l.add(i); return Optional.of(l).filter(ll -> ll.size()<=3);};\n\t\t// outputs the list if it has length 3\n\t\tFunction<List<Integer>, Optional<List<Integer>>> outputFunction = l -> Optional.of(l).filter(ll -> ll.size()==3);\n\t\t// This acceptor is similar to the one in testSumElementsInTriples, but returns the list\n\t\tvar acceptor = this.factory.generalised(new ArrayList<Integer>(),stateFunction,outputFunction);\n\t\tassertTrue(acceptor.accept(10));\n\t\tassertTrue(acceptor.accept(20));\n\t\tassertTrue(acceptor.accept(30));\n\t\tassertEquals(Optional.of(List.of(10,20,30)), acceptor.end());\n\t\tacceptor = this.factory.generalised(new ArrayList<Integer>(),stateFunction,outputFunction);\n\t\tassertTrue(acceptor.accept(10));\n\t\tassertTrue(acceptor.accept(20));\n\t\tassertEquals(Optional.empty(), acceptor.end());\n\t\tacceptor = this.factory.generalised(new ArrayList<Integer>(),stateFunction,outputFunction);\n\t\tassertTrue(acceptor.accept(10));\n\t\tassertTrue(acceptor.accept(20));\n\t\tassertTrue(acceptor.accept(30));\n\t\tassertFalse(acceptor.accept(40));\n\t\tassertEquals(Optional.empty(), acceptor.end());\n\t}\n}", "filename": "Test.java" }
2021
a02a
[ { "content": "package a02a.sol1;\n\nimport java.util.Map;\n\n\npublic interface Diet {\n\t\n\t\n\tenum Nutrient {\n\t\tCARBS, PROTEINS, FAT\n\t}\n\t\n\t\n\tvoid addFood(String name, Map<Nutrient,Integer> nutritionMap);\n\t\n\t\n\tboolean isValid(Map<String, Double> dietMap);\n\n}", "filename": "Diet.java" }, { "content": "package a02a.sol1;\n\nimport java.util.Objects;\n\n\n\npublic class Pair<E1,E2> {\n\t\n\tprivate final E1 e1;\n\tprivate final E2 e2;\n\t\n\tpublic Pair(E1 x, E2 y) {\n\t\tsuper();\n\t\tthis.e1 = x;\n\t\tthis.e2 = y;\n\t}\n\n\tpublic E1 get1() {\n\t\treturn e1;\n\t}\n\n\tpublic E2 get2() {\n\t\treturn e2;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Objects.hash(e1, e2);\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj) {\n\t\t\treturn true;\n\t\t}\n\t\tif (obj == null) {\n\t\t\treturn false;\n\t\t}\n\t\tif (getClass() != obj.getClass()) {\n\t\t\treturn false;\n\t\t}\n\t\tPair other = (Pair) obj;\n\t\treturn Objects.equals(e1, other.e1) && Objects.equals(e2, other.e2);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Pair [e1=\" + e1 + \", e2=\" + e2 + \"]\";\n\t}\n\t\n\t\n\n}", "filename": "Pair.java" }, { "content": "package a02a.sol1;\n\npublic interface DietFactory {\n\t\n\t\n\tDiet standard();\n\t\n\t\n\tDiet lowCarb();\n\t\n\t\n\tDiet highProtein();\n\t\n\t\n\tDiet balanced();\n}", "filename": "DietFactory.java" } ]
[ { "content": "package a02a.sol1;\n\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.function.Predicate;\n\npublic abstract class AbstractDiet implements Diet {\n\t\n\tprivate final Map<String,Map<Nutrient, Integer>> products = new HashMap<>();\n\n\t@Override\n\tpublic void addFood(String name, Map<Nutrient, Integer> nutritionMap) {\n\t\tif (this.products.containsKey(name)) {\n\t\t\tthrow new IllegalArgumentException();\n\t\t}\n\t\tthis.products.put(name, nutritionMap);\n\n\t}\n\n\t@Override\n\tpublic boolean isValid(Map<String, Double> dietMap) {\n\t\tMap<Nutrient,Double> calories = new HashMap<>();\n\t\tSystem.out.println(dietMap);\t\n\t\tfor (var e: dietMap.entrySet()) {\n\t\t\tfor (var e2: this.products.get(e.getKey()).entrySet()) {\n\t\t\t\tcalories.merge(e2.getKey(), e.getValue()/100.0*e2.getValue(), (a,b) -> a+b);\n\t\t\t}\n\t\t}\n\t\tSystem.out.println(calories);\n\t\treturn this.getConstraints().stream().allMatch(c -> isConstraintValid(c,calories));\n\t}\n\t\n\tprivate boolean isConstraintValid(Pair<Predicate<Nutrient>, Predicate<Double>> c, Map<Nutrient, Double> calories) {\n\t\treturn c.get2().test(calories.entrySet()\n\t\t\t\t.stream()\n\t\t\t\t.filter(e -> c.get1().test(e.getKey()))\n\t\t\t\t.mapToDouble(Map.Entry::getValue)\n\t\t\t\t.sum());\n\t}\n\n\tprotected abstract Set<Pair<Predicate<Nutrient>,Predicate<Double>>> getConstraints();\n\n}", "filename": "AbstractDiet.java" }, { "content": "package a02a.sol1;\n\nimport static a02a.sol1.Diet.Nutrient.*;\n\nimport java.util.Set;\nimport java.util.function.Predicate;\n\npublic class DietFactoryImpl implements DietFactory {\n\n\t@Override\n\tpublic Diet standard() {\n\t\treturn new AbstractDiet() {\n\n\t\t\t@Override\n\t\t\tprotected Set<Pair<Predicate<Nutrient>, Predicate<Double>>> getConstraints() {\n\t\t\t\treturn Set.<Pair<Predicate<Nutrient>, Predicate<Double>>>of(\n\t\t\t\t\t\tnew Pair<>(n -> true, d -> d>=1500 && d<=2000)\n\t\t\t\t);\n\t\t\t}\n\t\t};\n\t}\n\n\t@Override\n\tpublic Diet lowCarb() {\n\t\treturn new AbstractDiet() {\n\n\t\t\t@Override\n\t\t\tprotected Set<Pair<Predicate<Nutrient>, Predicate<Double>>> getConstraints() {\n\t\t\t\treturn Set.<Pair<Predicate<Nutrient>, Predicate<Double>>>of(\n\t\t\t\t\t\tnew Pair<>(n -> true, d -> d>=1000 && d<=1500),\n\t\t\t\t\t\tnew Pair<>(n -> n == CARBS , d -> d<=300)\n\t\t\t\t);\n\t\t\t}\n\t\t};\n\t}\n\n\t@Override\n\tpublic Diet highProtein() {\n\t\treturn new AbstractDiet() {\n\n\t\t\t@Override\n\t\t\tprotected Set<Pair<Predicate<Nutrient>, Predicate<Double>>> getConstraints() {\n\t\t\t\treturn Set.<Pair<Predicate<Nutrient>, Predicate<Double>>>of(\n\t\t\t\t\t\tnew Pair<>(n -> true, d -> d>=2000 && d<=2500),\n\t\t\t\t\t\tnew Pair<>(n -> n == CARBS , d -> d<=300),\n\t\t\t\t\t\tnew Pair<>(n -> n == PROTEINS , d -> d>=1300)\n\t\t\t\t);\n\t\t\t}\n\t\t};\n\t}\n\n\t@Override\n\tpublic Diet balanced() {\n\t\treturn new AbstractDiet() {\n\n\t\t\t@Override\n\t\t\tprotected Set<Pair<Predicate<Nutrient>, Predicate<Double>>> getConstraints() {\n\t\t\t\treturn Set.<Pair<Predicate<Nutrient>, Predicate<Double>>>of(\n\t\t\t\t\t\tnew Pair<>(n -> true, d -> d>=1600 && d<=2000),\n\t\t\t\t\t\tnew Pair<>(n -> n == CARBS , d -> d>=600),\n\t\t\t\t\t\tnew Pair<>(n -> n == PROTEINS , d -> d>=600),\n\t\t\t\t\t\tnew Pair<>(n -> n == FAT , d -> d>=400),\n\t\t\t\t\t\tnew Pair<>(n -> n == FAT || n == PROTEINS, d -> d<=1100)\n\t\t\t\t);\n\t\t\t}\n\t\t};\n\t}\n\n}", "filename": "DietFactoryImpl.java" } ]
{ "components": { "imports": "package a02a.sol1;\n\nimport static a02a.sol1.Diet.Nutrient.*;\nimport static org.junit.Assert.*;\n\nimport java.util.Map;", "private_init": "\t/*\n\t * Implement the DietFactory interface as indicated in the\n\t * initFactory method below. Create a factory for a diet concept, captured\n\t * by the Diet interface.\n\t * \n\t * As can be seen in the fillProduct method below, a diet is\n\t * first associated with a nutritional table. For example, below it says\n\t * that pasta (100 grams) provides 280 calories of carbohydrates, 70 of protein\n\t * and 50 of fat.\n\t * \n\t * At that point, the diet has a method to determine if a certain selection of products,\n\t * for example 200 grams of pasta, 300 of chicken, and 200 of grana cheese (see the first assert\n\t * of testStandard) is correct with respect to the type of diet in question (there are 4\n\t * to be created in the factory).\n\t * \n\t * Note that:\n\t * - 200 grams of pasta provide 280*2=560 calories of CARBS, 140 of PROT, 50 of FAT\n\t * - 300 grams of chicken provide 10*3=30 calories of CARBS, 180 of PROT, 90 of FAT\n\t * - 200 grams of grana cheese provide 0*2=0 calories of CARBS, 400 of PROT, 400 of FAT\n\t * and therefore in total: 590 of CARBS, 720 of PROT, 540 of FAT\n\t * Calculating this simple map, from nutrients to total calories, is probably useful then.\n\t * \n\t * The following are considered optional for the purpose of being able to correct\n\t * the exercise, but still contribute to achieving the totality of the\n\t * score:\n\t * \n\t * - implementation of the four methods of the factory (i.e., in the mandatory part it is sufficient\n\t * to implement 3 at will)\n\t * - the good design of the solution, using patterns that lead to concise code\n\t * that avoids repetitions\n\t * \n\t * Remove the comment from the initFactory method.\n\t * \n\t * Scoring indications:\n\t * - correctness of the mandatory part: 10 points\n\t * - correctness of the optional part: 3 points (additional method of the factory)\n\t * - quality of the solution: 4 points (for good design)\n\t * \n\t */\n\n\tprivate DietFactory factory = new DietFactoryImpl();\n\t\n\tprivate void fillProducts(Diet diet) {\n\t\tdiet.addFood(\"pasta\", Map.of(CARBS,280,PROTEINS,70,FAT,50)); // 400 calories overall\n\t\tdiet.addFood(\"riso\", Map.of(CARBS,250,PROTEINS,70,FAT,30)); // 350 calories overall\n\t\tdiet.addFood(\"pollo\", Map.of(CARBS,10,PROTEINS,60,FAT,30)); // 100 calories overall\n\t\tdiet.addFood(\"insalata\", Map.of(CARBS,10,PROTEINS,3,FAT,2)); // 15 calories overall\n\t\tdiet.addFood(\"broccoli\", Map.of(CARBS,20,PROTEINS,10,FAT,5));// 35 calories overall\n\t\tdiet.addFood(\"grana\", Map.of(CARBS,0,PROTEINS,200,FAT,200)); // 400 calories overall\n\t}\n\t\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.factory = new DietFactoryImpl();\n\t}", "test_functions": [ "\[email protected]\n\tpublic void testStandard() {\n\t\tvar diet = this.factory.standard();\n\t\tthis.fillProducts(diet);\n\t\tassertTrue(diet.isValid(Map.of(\"pasta\",200.0,\"pollo\",300.0,\"grana\",200.0))); // 800+300+800 calories\n\t\tassertFalse(diet.isValid(Map.of(\"pasta\",200.0,\"pollo\",300.0,\"grana\",50.0))); // 800+300+200 calories: too low!!\n\t\tassertFalse(diet.isValid(Map.of(\"pasta\",300.0,\"pollo\",300.0,\"grana\",200.0,\"broccoli\",300.0))); // 1200+300+800+105 calories: too much!!\n\t}", "\[email protected]\n\tpublic void testLowCarb() {\n\t\tvar diet = this.factory.lowCarb();\n\t\tthis.fillProducts(diet);\n\t\tassertTrue(diet.isValid(Map.of(\"pollo\",1000.0))); // ok calories, ok carbs\n\t\tassertFalse(diet.isValid(Map.of(\"pasta\",200.0,\"pollo\",300.0,\"grana\",200.0))); // 800+300+800 calories, too much!\n\t\tassertFalse(diet.isValid(Map.of(\"pasta\",400.0))); // ok calories, but too much carbs\n\t}", "\[email protected]\n\tpublic void testHighProtein() {\n\t\tvar diet = this.factory.highProtein();\n\t\tthis.fillProducts(diet);\n\t\tassertTrue(diet.isValid(Map.of(\"pollo\",2500.0))); // ok calories, ok proteins\n\t\tassertFalse(diet.isValid(Map.of(\"pasta\",200.0,\"pollo\",300.0,\"grana\",200.0))); // 800+300+800 calories, too few!\n\t\tassertFalse(diet.isValid(Map.of(\"grana\",500.0))); // ok calories, but too few proteins\n\t}", "\[email protected]\n\tpublic void testBalanced() {\n\t\tvar diet = this.factory.balanced();\n\t\tthis.fillProducts(diet);\n\t\tassertTrue(diet.isValid(Map.of(\"pasta\", 200.0, \"pollo\", 400.0, \"grana\", 100.0, \"broccoli\", 300.0))); // OK\n\t\tassertFalse(diet.isValid(Map.of(\"pasta\",200.0,\"pollo\",300.0,\"grana\",200.0))); \n\t\tassertFalse(diet.isValid(Map.of(\"pollo\",1000.0))); \n\t\tassertFalse(diet.isValid(Map.of(\"pollo\",2000.0)));\n\t}" ] }, "content": "package a02a.sol1;\n\nimport static a02a.sol1.Diet.Nutrient.*;\nimport static org.junit.Assert.*;\n\nimport java.util.Map;\n\npublic class Test {\n\n\t/*\n\t * Implement the DietFactory interface as indicated in the\n\t * initFactory method below. Create a factory for a diet concept, captured\n\t * by the Diet interface.\n\t * \n\t * As can be seen in the fillProduct method below, a diet is\n\t * first associated with a nutritional table. For example, below it says\n\t * that pasta (100 grams) provides 280 calories of carbohydrates, 70 of protein\n\t * and 50 of fat.\n\t * \n\t * At that point, the diet has a method to determine if a certain selection of products,\n\t * for example 200 grams of pasta, 300 of chicken, and 200 of grana cheese (see the first assert\n\t * of testStandard) is correct with respect to the type of diet in question (there are 4\n\t * to be created in the factory).\n\t * \n\t * Note that:\n\t * - 200 grams of pasta provide 280*2=560 calories of CARBS, 140 of PROT, 50 of FAT\n\t * - 300 grams of chicken provide 10*3=30 calories of CARBS, 180 of PROT, 90 of FAT\n\t * - 200 grams of grana cheese provide 0*2=0 calories of CARBS, 400 of PROT, 400 of FAT\n\t * and therefore in total: 590 of CARBS, 720 of PROT, 540 of FAT\n\t * Calculating this simple map, from nutrients to total calories, is probably useful then.\n\t * \n\t * The following are considered optional for the purpose of being able to correct\n\t * the exercise, but still contribute to achieving the totality of the\n\t * score:\n\t * \n\t * - implementation of the four methods of the factory (i.e., in the mandatory part it is sufficient\n\t * to implement 3 at will)\n\t * - the good design of the solution, using patterns that lead to concise code\n\t * that avoids repetitions\n\t * \n\t * Remove the comment from the initFactory method.\n\t * \n\t * Scoring indications:\n\t * - correctness of the mandatory part: 10 points\n\t * - correctness of the optional part: 3 points (additional method of the factory)\n\t * - quality of the solution: 4 points (for good design)\n\t * \n\t */\n\n\tprivate DietFactory factory = new DietFactoryImpl();\n\t\n\tprivate void fillProducts(Diet diet) {\n\t\tdiet.addFood(\"pasta\", Map.of(CARBS,280,PROTEINS,70,FAT,50)); // 400 calories overall\n\t\tdiet.addFood(\"riso\", Map.of(CARBS,250,PROTEINS,70,FAT,30)); // 350 calories overall\n\t\tdiet.addFood(\"pollo\", Map.of(CARBS,10,PROTEINS,60,FAT,30)); // 100 calories overall\n\t\tdiet.addFood(\"insalata\", Map.of(CARBS,10,PROTEINS,3,FAT,2)); // 15 calories overall\n\t\tdiet.addFood(\"broccoli\", Map.of(CARBS,20,PROTEINS,10,FAT,5));// 35 calories overall\n\t\tdiet.addFood(\"grana\", Map.of(CARBS,0,PROTEINS,200,FAT,200)); // 400 calories overall\n\t}\n\t\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.factory = new DietFactoryImpl();\n\t}\n\t\n\t\t\n\[email protected]\n\tpublic void testStandard() {\n\t\tvar diet = this.factory.standard();\n\t\tthis.fillProducts(diet);\n\t\tassertTrue(diet.isValid(Map.of(\"pasta\",200.0,\"pollo\",300.0,\"grana\",200.0))); // 800+300+800 calories\n\t\tassertFalse(diet.isValid(Map.of(\"pasta\",200.0,\"pollo\",300.0,\"grana\",50.0))); // 800+300+200 calories: too low!!\n\t\tassertFalse(diet.isValid(Map.of(\"pasta\",300.0,\"pollo\",300.0,\"grana\",200.0,\"broccoli\",300.0))); // 1200+300+800+105 calories: too much!!\n\t}\n\t\n\[email protected]\n\tpublic void testLowCarb() {\n\t\tvar diet = this.factory.lowCarb();\n\t\tthis.fillProducts(diet);\n\t\tassertTrue(diet.isValid(Map.of(\"pollo\",1000.0))); // ok calories, ok carbs\n\t\tassertFalse(diet.isValid(Map.of(\"pasta\",200.0,\"pollo\",300.0,\"grana\",200.0))); // 800+300+800 calories, too much!\n\t\tassertFalse(diet.isValid(Map.of(\"pasta\",400.0))); // ok calories, but too much carbs\n\t}\n\t\n\[email protected]\n\tpublic void testHighProtein() {\n\t\tvar diet = this.factory.highProtein();\n\t\tthis.fillProducts(diet);\n\t\tassertTrue(diet.isValid(Map.of(\"pollo\",2500.0))); // ok calories, ok proteins\n\t\tassertFalse(diet.isValid(Map.of(\"pasta\",200.0,\"pollo\",300.0,\"grana\",200.0))); // 800+300+800 calories, too few!\n\t\tassertFalse(diet.isValid(Map.of(\"grana\",500.0))); // ok calories, but too few proteins\n\t}\n\t\n\[email protected]\n\tpublic void testBalanced() {\n\t\tvar diet = this.factory.balanced();\n\t\tthis.fillProducts(diet);\n\t\tassertTrue(diet.isValid(Map.of(\"pasta\", 200.0, \"pollo\", 400.0, \"grana\", 100.0, \"broccoli\", 300.0))); // OK\n\t\tassertFalse(diet.isValid(Map.of(\"pasta\",200.0,\"pollo\",300.0,\"grana\",200.0))); \n\t\tassertFalse(diet.isValid(Map.of(\"pollo\",1000.0))); \n\t\tassertFalse(diet.isValid(Map.of(\"pollo\",2000.0)));\n\t}\n}", "filename": "Test.java" }
2021
a05
[ { "content": "package a05.sol1;\n\nimport java.util.Iterator;\nimport java.util.function.Function;\n\n\npublic interface State<S,A> {\n\t\n\t\n\tS nextState(S s);\n\t\n\t\n\tA value(S s);\n\t\n\t\n\t<B> State<S,B> map(Function<A,B> fun);\n\t\n\t\n\tIterator<A> iterator(S s0);\n}", "filename": "State.java" }, { "content": "package a05.sol1;\n\nimport java.util.function.Function;\n\n\npublic interface StateFactory {\n\t\n\t\n\t<S,A> State<S,A> fromFunction(Function<S,Pair<S,A>> fun);\n\t\n\t\n\t<S,A,B> State<S,B> compose(State<S,A> state1, State<S,B> state2);\n\t\n\t\n\tState<Integer, String> incSquareHalve();\n\t\n\tenum CounterOp {\n\t\tINC, RESET, GET;\n\t}\n\t\n\t\n\tState<Integer, Integer> counterOp(CounterOp op);\n}", "filename": "StateFactory.java" }, { "content": "package a05.sol1;\n\nimport java.util.Objects;\n\n\n\npublic class Pair<E1,E2> {\n\t\n\tprivate final E1 e1;\n\tprivate final E2 e2;\n\t\n\tpublic Pair(E1 x, E2 y) {\n\t\tsuper();\n\t\tthis.e1 = x;\n\t\tthis.e2 = y;\n\t}\n\n\tpublic E1 get1() {\n\t\treturn e1;\n\t}\n\n\tpublic E2 get2() {\n\t\treturn e2;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Objects.hash(e1, e2);\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj) {\n\t\t\treturn true;\n\t\t}\n\t\tif (obj == null) {\n\t\t\treturn false;\n\t\t}\n\t\tif (getClass() != obj.getClass()) {\n\t\t\treturn false;\n\t\t}\n\t\tPair other = (Pair) obj;\n\t\treturn Objects.equals(e1, other.e1) && Objects.equals(e2, other.e2);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Pair [e1=\" + e1 + \", e2=\" + e2 + \"]\";\n\t}\n\t\n\t\n\n}", "filename": "Pair.java" } ]
[ { "content": "package a05.sol1;\n\nimport java.util.Iterator;\nimport java.util.function.Function;\nimport java.util.stream.Stream;\n\npublic class StateFactoryImpl implements StateFactory {\n\n\t@Override\n\tpublic <S, A> State<S, A> fromFunction(Function<S, Pair<S, A>> fun) {\n\t\treturn new State<S,A>(){\n\n\t\t\t@Override\n\t\t\tpublic S nextState(S s) {\n\t\t\t\treturn fun.apply(s).get1();\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic A value(S s) {\n\t\t\t\treturn fun.apply(s).get2();\n\t\t\t}\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic <B> State<S, B> map(Function<A, B> mapper) {\n\t\t\t\treturn fromFunction(s -> new Pair<>(nextState(s), mapper.apply(value(s))));\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Iterator<A> iterator(S s0) {\n\t\t\t\treturn Stream.iterate(next(this,s0), p -> next(this,p.get1())).map(p -> p.get2()).iterator();\n\t\t\t}\n\t\t};\n\t}\n\t\n\tprivate <S2,A2> Pair<S2,A2> next(State<S2,A2> state, S2 s) {\n\t\treturn new Pair<>(state.nextState(s), state.value(s));\n\t}\n\t\n\t@Override\n\tpublic <S,A,B> State<S,B> compose(State<S,A> state1, State<S,B> state2) {\n\t\treturn fromFunction(s -> {\n\t\t\tvar p1 = next(state1, s);\n\t\t\tvar p2 = next(state2, p1.get1());\n\t\t\treturn new Pair<>(p2.get1(), p2.get2());\n\t\t});\n\t}\n\n\t@Override\n\tpublic State<Integer, String> incSquareHalve() {\n\t\tvar s = this.<Integer,Integer>fromFunction(i -> new Pair<>(i+1,i+1));\n\t\ts = compose(s, this.<Integer,Integer>fromFunction(i -> new Pair<>(i*i,i*i)));\n\t\ts = compose(s, this.<Integer,Integer>fromFunction(i -> new Pair<>(i/2,i/2)));\n\t\treturn s.map(String::valueOf);\n\t}\n\t\n\t@Override\n\tpublic State<Integer, Integer> counterOp(CounterOp op) {\n\t\treturn this.fromFunction(\n\t\t\t\top == CounterOp.INC ? i -> new Pair<>(i+1,null) :\n\t\t\t op == CounterOp.RESET ? i -> new Pair<>(0, null) :\n\t\t\t op == CounterOp.GET ? i -> new Pair<>(i,i) : \n\t\t\t null);\t\n\t}\n}", "filename": "StateFactoryImpl.java" } ]
{ "components": { "imports": "package a05.sol1;\n\nimport static org.junit.Assert.*;\n\nimport java.util.Iterator;\n\nimport a05.sol1.StateFactory.CounterOp;", "private_init": "\t/*\n\t * Implement the StateFactory interface as indicated in the initFactory method below.\n\t * Create a factory for State<S,A>, which are functions to represent updates to\n\t * a state of type S, with contextual extraction of an output value of type A.\n\t * So, a State<S,A> is effectively similar to a pure function that takes an S and returns\n\t * a pair S,A (new state + output value).\n\t *\n\t * The comment on the provided interfaces, and the test methods below\n\t * constitute the necessary explanation of the problem.\n\t *\n\t * The following are considered optional for the purpose of being able to correct\n\t * the exercise, but still contribute to achieving the totality of the\n\t * score:\n\t *\n\t * - one of the four methods of the factory, at choice\n\t * (i.e., in the mandatory part it is sufficient to implement 3 of the 4 present, the fourth is therefore optional)\n\t *\n\t * - the good design of the solution, reusing as much code as possible and keeping all the implementations\n\t * very succinct\n\t *\n\t * Remove the comment from the initFactory method.\n\t *\n\t * Scoring indications:\n\t *\n\t * - correctness of the mandatory part: 10 points\n\t *\n\t * - correctness of the optional part: 2 points (additional method)\n\t *\n\t * - quality of the solution: 5 points (for the good design of the solution, as indicated above)\n\t *\n\t */\n\n\tprivate StateFactory factory;\n\t\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.factory = new StateFactoryImpl();\n\t}", "test_functions": [ "\[email protected]\n\tpublic void testIncrementingStateWithTransparentOutput() {\n\t\t// a state that increments a numeric value and returns it each time\n\t\tState<Integer, Integer> state = this.factory.fromFunction(i -> new Pair<>(i+1, i+1));\n\t\t\n\t\t// with state 0, the next is 1 and the output is also 1\n\t\tassertEquals(Integer.valueOf(1), state.nextState(0));\n\t\tassertEquals(Integer.valueOf(1), state.value(0));\n\t\t\n\t\t// with state 3, the next is 4 and the output is also 4\n\t\tassertEquals(Integer.valueOf(4), state.nextState(3));\n\t\tassertEquals(Integer.valueOf(4), state.value(3));\n\t}", "\[email protected]\n\tpublic void testConstantStateWithStringOutput() {\n\t\t// a state that does not change, and returns a string representation\n\t\tState<Integer, String> state = this.factory.fromFunction(i -> new Pair<>(i,String.valueOf(i)));\n\t\t\n\t\t// with state 0, the next is 0 and the output is \"0\"\n\t\tassertEquals(Integer.valueOf(0), state.nextState(0));\n\t\tassertEquals(\"0\", state.value(0));\n\t\t\n\t\t// with state 3, the next is 3 and the output is \"3\"\n\t\tassertEquals(Integer.valueOf(3), state.nextState(3));\n\t\tassertEquals(\"3\", state.value(3));\n\t}", "\[email protected]\n\tpublic void testMap() {\n\t\t// preState is the same state in the testIncrementingStateWithTransparentOutput() method\n\t\tState<Integer, Integer> preState = this.factory.fromFunction(i -> new Pair<>(i+1, i+1));\n\t\t// state is obtained from preState simply converting the output values to be strings\n\t\tState<Integer, String> state = preState.map(i -> String.valueOf(i));\n\t\t\n\t\t// with state 0, the next is 1 and the output is \"1\"\n\t\tassertEquals(Integer.valueOf(1), state.nextState(0));\n\t\tassertEquals(\"1\", state.value(0));\n\t\t\n\t\t// with state 3, the next is 4 and the output is \"4\"\n\t\tassertEquals(Integer.valueOf(4), state.nextState(3));\n\t\tassertEquals(\"4\", state.value(3));\n\t}", "\[email protected]\n\tpublic void testCompose() {\n\t\t// state1 is the same state in the testIncrementingStateWithTransparentOutput() method\n\t\tState<Integer, Integer> state1 = this.factory.fromFunction(i -> new Pair<>(i+1, i+1));\n\t\t// state2 is the state that doubles a numeric value and returns it as a string\n\t\tState<Integer, String> state2 = this.factory.fromFunction(i -> new Pair<>(i*2, String.valueOf(i*2)));\n\t\t// the composition of the two realizes s-> (s+1)*2, and returns the string representation\n\t\tState<Integer, String> state = this.factory.compose(state1, state2);\n\t\t\n\t\t// with state 0, the next is 2 and the output is \"2\"\n\t\tassertEquals(Integer.valueOf(2), state.nextState(0));\n\t\tassertEquals(\"2\", state.value(0));\n\t\t\n\t\t// with state 3, the next is 8 and the output is \"8\"\n\t\tassertEquals(Integer.valueOf(8), state.nextState(3));\n\t\tassertEquals(\"8\", state.value(3));\n\t}", "\[email protected]\n\tpublic void testIterator() {\n\t\t// state is the same state in the testIncrementingStateWithTransparentOutput() method\n\t\tState<Integer, String> state = this.factory.fromFunction(i -> new Pair<>(i+1,String.valueOf(i+1)));\n\t\t// the iterator produces the output values obtained by calling next iteratively, i.e.: 1,2,3,4,...\n\t\tIterator<String> it = state.iterator(0);\n\t\tassertEquals(\"1\", it.next());\n\t\tassertEquals(\"2\", it.next());\n\t\tassertEquals(\"3\", it.next());\n\t}", "\[email protected]\n\tpublic void testIncSquareHalve() {\n\t\t// an iterator that starts from 1, and at each step applies s -> square(s+1)/2, showing its string\n\t\t// ideally it should be produced by composing three states...\n\t\tIterator<String> it = this.factory.incSquareHalve().iterator(1);\n\t\tassertEquals(String.valueOf(2), it.next()); // (1+1)^2/2\n\t\tassertEquals(String.valueOf(4), it.next()); // (2+1)^2/2\n\t\tassertEquals(String.valueOf(12), it.next()); // (4+1)^2/2\n\t\tassertEquals(String.valueOf(84), it.next()); // (12+1)^2/2\n\t}", "\[email protected]\n\tpublic void testCounter() {\n\t\t// an application of State to model objects with state\n\t\t// state represents an increment\n\t\tvar state = this.factory.counterOp(CounterOp.INC);\n\t\t// state represents an increment followed by an increment\n\t\tstate = this.factory.compose(state, this.factory.counterOp(CounterOp.INC));\n\t\t// state represents an increment followed by an increment followed by a get\n\t\tstate = this.factory.compose(state, this.factory.counterOp(CounterOp.GET));\n\t\t// state therefore represents a state that is updated by incrementing by 2\n\t\tassertEquals(Integer.valueOf(2), state.value(0));\n\t\tstate = this.factory.compose(state, this.factory.counterOp(CounterOp.RESET));\n\t\tstate = this.factory.compose(state, this.factory.counterOp(CounterOp.GET));\n\t\t// state therefore represents a state that is updated by incrementing by 2, then resets, then emits the value 0\n\t\tassertEquals(Integer.valueOf(0), state.value(0));\n\t}" ] }, "content": "package a05.sol1;\n\nimport static org.junit.Assert.*;\n\nimport java.util.Iterator;\n\nimport a05.sol1.StateFactory.CounterOp;\n\npublic class Test {\n\n\t/*\n\t * Implement the StateFactory interface as indicated in the initFactory method below.\n\t * Create a factory for State<S,A>, which are functions to represent updates to\n\t * a state of type S, with contextual extraction of an output value of type A.\n\t * So, a State<S,A> is effectively similar to a pure function that takes an S and returns\n\t * a pair S,A (new state + output value).\n\t *\n\t * The comment on the provided interfaces, and the test methods below\n\t * constitute the necessary explanation of the problem.\n\t *\n\t * The following are considered optional for the purpose of being able to correct\n\t * the exercise, but still contribute to achieving the totality of the\n\t * score:\n\t *\n\t * - one of the four methods of the factory, at choice\n\t * (i.e., in the mandatory part it is sufficient to implement 3 of the 4 present, the fourth is therefore optional)\n\t *\n\t * - the good design of the solution, reusing as much code as possible and keeping all the implementations\n\t * very succinct\n\t *\n\t * Remove the comment from the initFactory method.\n\t *\n\t * Scoring indications:\n\t *\n\t * - correctness of the mandatory part: 10 points\n\t *\n\t * - correctness of the optional part: 2 points (additional method)\n\t *\n\t * - quality of the solution: 5 points (for the good design of the solution, as indicated above)\n\t *\n\t */\n\n\tprivate StateFactory factory;\n\t\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.factory = new StateFactoryImpl();\n\t}\n\t\n\[email protected]\n\tpublic void testIncrementingStateWithTransparentOutput() {\n\t\t// a state that increments a numeric value and returns it each time\n\t\tState<Integer, Integer> state = this.factory.fromFunction(i -> new Pair<>(i+1, i+1));\n\t\t\n\t\t// with state 0, the next is 1 and the output is also 1\n\t\tassertEquals(Integer.valueOf(1), state.nextState(0));\n\t\tassertEquals(Integer.valueOf(1), state.value(0));\n\t\t\n\t\t// with state 3, the next is 4 and the output is also 4\n\t\tassertEquals(Integer.valueOf(4), state.nextState(3));\n\t\tassertEquals(Integer.valueOf(4), state.value(3));\n\t}\n\n\[email protected]\n\tpublic void testConstantStateWithStringOutput() {\n\t\t// a state that does not change, and returns a string representation\n\t\tState<Integer, String> state = this.factory.fromFunction(i -> new Pair<>(i,String.valueOf(i)));\n\t\t\n\t\t// with state 0, the next is 0 and the output is \"0\"\n\t\tassertEquals(Integer.valueOf(0), state.nextState(0));\n\t\tassertEquals(\"0\", state.value(0));\n\t\t\n\t\t// with state 3, the next is 3 and the output is \"3\"\n\t\tassertEquals(Integer.valueOf(3), state.nextState(3));\n\t\tassertEquals(\"3\", state.value(3));\n\t}\n\t\n\[email protected]\n\tpublic void testMap() {\n\t\t// preState is the same state in the testIncrementingStateWithTransparentOutput() method\n\t\tState<Integer, Integer> preState = this.factory.fromFunction(i -> new Pair<>(i+1, i+1));\n\t\t// state is obtained from preState simply converting the output values to be strings\n\t\tState<Integer, String> state = preState.map(i -> String.valueOf(i));\n\t\t\n\t\t// with state 0, the next is 1 and the output is \"1\"\n\t\tassertEquals(Integer.valueOf(1), state.nextState(0));\n\t\tassertEquals(\"1\", state.value(0));\n\t\t\n\t\t// with state 3, the next is 4 and the output is \"4\"\n\t\tassertEquals(Integer.valueOf(4), state.nextState(3));\n\t\tassertEquals(\"4\", state.value(3));\n\t}\n\t\n\[email protected]\n\tpublic void testCompose() {\n\t\t// state1 is the same state in the testIncrementingStateWithTransparentOutput() method\n\t\tState<Integer, Integer> state1 = this.factory.fromFunction(i -> new Pair<>(i+1, i+1));\n\t\t// state2 is the state that doubles a numeric value and returns it as a string\n\t\tState<Integer, String> state2 = this.factory.fromFunction(i -> new Pair<>(i*2, String.valueOf(i*2)));\n\t\t// the composition of the two realizes s-> (s+1)*2, and returns the string representation\n\t\tState<Integer, String> state = this.factory.compose(state1, state2);\n\t\t\n\t\t// with state 0, the next is 2 and the output is \"2\"\n\t\tassertEquals(Integer.valueOf(2), state.nextState(0));\n\t\tassertEquals(\"2\", state.value(0));\n\t\t\n\t\t// with state 3, the next is 8 and the output is \"8\"\n\t\tassertEquals(Integer.valueOf(8), state.nextState(3));\n\t\tassertEquals(\"8\", state.value(3));\n\t}\n\t\n\[email protected]\n\tpublic void testIterator() {\n\t\t// state is the same state in the testIncrementingStateWithTransparentOutput() method\n\t\tState<Integer, String> state = this.factory.fromFunction(i -> new Pair<>(i+1,String.valueOf(i+1)));\n\t\t// the iterator produces the output values obtained by calling next iteratively, i.e.: 1,2,3,4,...\n\t\tIterator<String> it = state.iterator(0);\n\t\tassertEquals(\"1\", it.next());\n\t\tassertEquals(\"2\", it.next());\n\t\tassertEquals(\"3\", it.next());\n\t}\n\t\n\[email protected]\n\tpublic void testIncSquareHalve() {\n\t\t// an iterator that starts from 1, and at each step applies s -> square(s+1)/2, showing its string\n\t\t// ideally it should be produced by composing three states...\n\t\tIterator<String> it = this.factory.incSquareHalve().iterator(1);\n\t\tassertEquals(String.valueOf(2), it.next()); // (1+1)^2/2\n\t\tassertEquals(String.valueOf(4), it.next()); // (2+1)^2/2\n\t\tassertEquals(String.valueOf(12), it.next()); // (4+1)^2/2\n\t\tassertEquals(String.valueOf(84), it.next()); // (12+1)^2/2\n\t}\n\t\n\[email protected]\n\tpublic void testCounter() {\n\t\t// an application of State to model objects with state\n\t\t// state represents an increment\n\t\tvar state = this.factory.counterOp(CounterOp.INC);\n\t\t// state represents an increment followed by an increment\n\t\tstate = this.factory.compose(state, this.factory.counterOp(CounterOp.INC));\n\t\t// state represents an increment followed by an increment followed by a get\n\t\tstate = this.factory.compose(state, this.factory.counterOp(CounterOp.GET));\n\t\t// state therefore represents a state that is updated by incrementing by 2\n\t\tassertEquals(Integer.valueOf(2), state.value(0));\n\t\tstate = this.factory.compose(state, this.factory.counterOp(CounterOp.RESET));\n\t\tstate = this.factory.compose(state, this.factory.counterOp(CounterOp.GET));\n\t\t// state therefore represents a state that is updated by incrementing by 2, then resets, then emits the value 0\n\t\tassertEquals(Integer.valueOf(0), state.value(0));\n\t}\n}", "filename": "Test.java" }
2021
a01c
[ { "content": "package a01c.sol1;\n\n\npublic interface EventHistory<E> {\n\t\n\t\n\tdouble getTimeOfEvent();\n\t\n\t\n\tE getEventContent();\n\t\n\t\n\tboolean moveToNextEvent();\n}", "filename": "EventHistory.java" }, { "content": "package a01c.sol1;\n\nimport java.util.Objects;\n\n\n\npublic class Pair<E1,E2> {\n\t\n\tprivate final E1 e1;\n\tprivate final E2 e2;\n\t\n\tpublic Pair(E1 x, E2 y) {\n\t\tsuper();\n\t\tthis.e1 = x;\n\t\tthis.e2 = y;\n\t}\n\n\tpublic E1 get1() {\n\t\treturn e1;\n\t}\n\n\tpublic E2 get2() {\n\t\treturn e2;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Objects.hash(e1, e2);\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj) {\n\t\t\treturn true;\n\t\t}\n\t\tif (obj == null) {\n\t\t\treturn false;\n\t\t}\n\t\tif (getClass() != obj.getClass()) {\n\t\t\treturn false;\n\t\t}\n\t\tPair other = (Pair) obj;\n\t\treturn Objects.equals(e1, other.e1) && Objects.equals(e2, other.e2);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Pair [e1=\" + e1 + \", e2=\" + e2 + \"]\";\n\t}\n\t\n\t\n\n}", "filename": "Pair.java" }, { "content": "package a01c.sol1;\n\nimport java.io.IOException;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.function.Supplier;\n\n\npublic interface EventHistoryFactory {\n\n\t\n\t<E> EventHistory<E> fromMap(Map<Double, E> map);\n\n\t\n\t<E> EventHistory<E> fromIterators(Iterator<Double> times, Iterator<E> content);\n\t\n\t\n\t<E> EventHistory<E> fromListAndDelta(List<E> content, double initial, double delta);\n\t\n\t\n\t<E> EventHistory<E> fromRandomTimesAndSupplier(Supplier<E> content, int size);\n\t\n\t\n\tEventHistory<String> fromFile(String file) throws IOException;\n\n}", "filename": "EventHistoryFactory.java" } ]
[ { "content": "package a01c.sol1;\n\nimport java.io.BufferedReader;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.io.Reader;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.NoSuchElementException;\nimport java.util.Optional;\nimport java.util.function.Supplier;\nimport java.util.stream.Stream;\n\npublic class EventHistoryFactoryImpl implements EventHistoryFactory {\n\n\tprivate <E> EventHistory<E> historyFromIterator(Iterator<Pair<Double,E>> iterator){\n\t\treturn new EventHistory<>() {\n\t\t\tprivate Pair<Double,E> p = iterator.next();\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic double getTimeOfEvent() {\n\t\t\t\treturn p.get1();\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic E getEventContent() {\n\t\t\t\treturn p.get2();\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic boolean moveToNextEvent() {\n\t\t\t\tif (iterator.hasNext()) {\n\t\t\t\t\tp = iterator.next();\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\treturn false;\n\t\t\t}\n\t\t};\n\t}\n\n\t@Override\n\tpublic <E> EventHistory<E> fromMap(Map<Double, E> map) {\n\t\treturn this.historyFromIterator(map\n\t\t\t\t.entrySet()\n\t\t\t\t.stream()\n\t\t\t\t.sorted( (p1,p2) -> p1.getKey()-p2.getKey() > 0.0 ? 1 : -1)\n\t\t\t\t.map( p -> new Pair<>(p.getKey(),p.getValue()))\n\t\t\t\t.iterator());\n\t}\n\n\t@Override\n\tpublic <E> EventHistory<E> fromIterators(Iterator<Double> times, Iterator<E> content) {\n\t\treturn this.historyFromIterator(new Iterator<>() {\n\n\t\t\t@Override\n\t\t\tpublic boolean hasNext() {\n\t\t\t\treturn times.hasNext() && content.hasNext();\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Pair<Double, E> next() {\n\t\t\t\treturn Optional.of(this.hasNext())\n\t\t\t\t\t\t.filter(b->b)\n\t\t\t\t\t\t.map(b->new Pair<>(times.next(),content.next()))\n\t\t\t\t\t\t.orElseThrow();\n\t\t\t}\n\t\t});\n\t}\n\t\n\t@Override\n\tpublic <E> EventHistory<E> fromRandomTimesAndSupplier(Supplier<E> content, int size) {\n\t\treturn fromIterators(\n\t\t\t\tStream.iterate(0.0, x -> x + Math.random()).limit(size).iterator(),\n\t\t\t\tStream.generate(content).iterator());\n\t}\n\n\t@Override\n\tpublic <E> EventHistory<E> fromListAndDelta(List<E> content, double initial, double delta) {\n\t\treturn fromIterators(Stream.iterate(initial, d->d+delta).iterator(), content.iterator());\n\t}\n\n\t@Override\n\tpublic EventHistory<String> fromFile(String file) throws IOException {\n\t\tMap<Double,String> map = new HashMap<>();\n\t\ttry ( BufferedReader br = new BufferedReader(new FileReader(file))){\n\t\t\tString str = null;\n\t\t\twhile ((str = br.readLine())!=null) {\n\t\t\t\tString[] s = str.split(\":\",2);\n\t\t\t\tmap.put(Double.parseDouble(s[0]), s[1]);\n\t\t\t}\n\t\t}\n\t\tSystem.out.println(map);\n\t\treturn this.fromMap(map);\n\t}\n}", "filename": "EventHistoryFactoryImpl.java" } ]
{ "components": { "imports": "package a01c.sol1;\n\nimport static org.junit.Assert.*;\n\nimport java.io.IOException;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.NoSuchElementException;\nimport java.util.Random;\nimport java.util.function.Supplier;\nimport java.util.stream.Stream;", "private_init": "\t/*\n\t * Implement the EventHistoryFactory interface as indicated in the initFactory method below.\n\t * Create a set of factories for EventHistory, i.e., series of events (time + content pairs).\n\t * \n\t * The comment on the provided interfaces, and the test methods below\n\t * constitute the necessary explanation of the problem.\n\t * \n\t * The following are considered optional for the purpose of being able to correct\n\t * the exercise, but still contribute to achieving the totality of the\n\t * score:\n\t * \n\t * - implementation of the five methods in the factory (i.e., in the mandatory part it is sufficient to\n\t * implement 4 at will)\n\t * \n\t * - good design of the solution, in particular using concise code that avoids repetitions\n\t * \n\t * - avoid creating unnecessary data structures\n\t * \n\t * Remove the comment from the initFactory method.\n\t * \n\t * Scoring indications:\n\t * \n\t * - correctness of the mandatory part: 10 points (2.5+2.5+2.5+2.5)\n\t * \n\t * - correctness of the optional part: 3 points\n\t * \n\t * - quality of the solution: 4 points (3 points for good design, 1 point for no unnecessary structures)\n\t * \n\t */\n\n\t\n\tprivate static final double TOLERANCE = 0.01;\n\n\tprivate EventHistoryFactory factory = null;\n\t\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.factory = new EventHistoryFactoryImpl();\n\t}", "test_functions": [ "\[email protected]\n\tpublic void testFromMap() {\n\t\tvar h = this.factory.fromMap(Map.of(1.0,\"uno\", 2.0, \"due\", 3.0, \"tre\"));\n\t\tassertEquals(1.0, h.getTimeOfEvent(), TOLERANCE);\n\t\tassertEquals(\"uno\", h.getEventContent());\n\t\tassertTrue(h.moveToNextEvent());\n\t\tassertEquals(2.0, h.getTimeOfEvent(), TOLERANCE);\n\t\tassertEquals(\"due\", h.getEventContent());\n\t\tassertTrue(h.moveToNextEvent());\n\t\tassertEquals(3.0, h.getTimeOfEvent(), TOLERANCE);\n\t\tassertEquals(\"tre\", h.getEventContent());\n\t\tassertFalse(h.moveToNextEvent());\n\t}", "\[email protected]\n\tpublic void testFromIterators() {\n\t\tvar i1 = Stream.iterate(1.0, x -> x + 1.0).iterator();\n\t\tvar i2 = Stream.of(\"uno\", \"due\", \"tre\").iterator();\n\t\tvar h = this.factory.fromIterators(i1,i2);\n\t\tassertEquals(1.0, h.getTimeOfEvent(), TOLERANCE);\n\t\tassertEquals(\"uno\", h.getEventContent());\n\t\tassertTrue(h.moveToNextEvent());\n\t\tassertEquals(2.0, h.getTimeOfEvent(), TOLERANCE);\n\t\tassertEquals(\"due\", h.getEventContent());\n\t\tassertTrue(h.moveToNextEvent());\n\t\tassertEquals(3.0, h.getTimeOfEvent(), TOLERANCE);\n\t\tassertEquals(\"tre\", h.getEventContent());\n\t\tassertFalse(h.moveToNextEvent());\n\t}", "\[email protected]\n\tpublic void testFromListAndDelta() {\n\t\tvar i = List.of(100, 200, 300, 400);\n\t\tvar h = this.factory.fromListAndDelta(i,1.0,0.1);\n\t\tassertEquals(1.0, h.getTimeOfEvent(), TOLERANCE);\n\t\tassertEquals(100, h.getEventContent().intValue());\n\t\tassertTrue(h.moveToNextEvent());\n\t\tassertEquals(1.1, h.getTimeOfEvent(), TOLERANCE);\n\t\tassertEquals(200, h.getEventContent().intValue());\n\t\tassertTrue(h.moveToNextEvent());\n\t\tassertEquals(1.2, h.getTimeOfEvent(), TOLERANCE);\n\t\tassertEquals(300, h.getEventContent().intValue());\n\t\tassertTrue(h.moveToNextEvent());\n\t\tassertEquals(1.3, h.getTimeOfEvent(), TOLERANCE);\n\t\tassertEquals(400, h.getEventContent().intValue());\n\t\tassertFalse(h.moveToNextEvent());\n\t}", "\[email protected]\n\tpublic void testFromRandomTimesAndSupplier() {\n\t\tRandom random = new Random();\n\t\tSupplier<Boolean> supplier = () -> random.nextBoolean();\n\t\tvar h = this.factory.fromRandomTimesAndSupplier(supplier,3);\n\t\tdouble t1 = h.getTimeOfEvent();\n\t\tboolean b1 = h.getEventContent();\n\t\th.moveToNextEvent();\n\t\tdouble t2 = h.getTimeOfEvent();\n\t\tboolean b2 = h.getEventContent();\n\t\th.moveToNextEvent();\n\t\tdouble t3 = h.getTimeOfEvent();\n\t\tboolean b3 = h.getEventContent();\n\t\tassertFalse(h.moveToNextEvent());\n\t\tSystem.out.println(t1+\" \"+b1);\n\t\tSystem.out.println(t2+\" \"+b2);\n\t\tSystem.out.println(t3+\" \"+b3);\n\t\tassertTrue(t1 <= 1.0);\n\t\tassertTrue(t2 <= t1 + 1.0);\n\t\tassertTrue(t3 <= t2 + 1.0);\n\t}", "\[email protected]\n\tpublic void testFromFile() throws IOException {\n\t\tvar h = this.factory.fromFile(\"file.txt\");\n\t\tassertEquals(15.5, h.getTimeOfEvent(), TOLERANCE);\n\t\tassertEquals(\"aaa\", h.getEventContent());\n\t\tassertTrue(h.moveToNextEvent());\n\t\tassertEquals(16.6, h.getTimeOfEvent(), TOLERANCE);\n\t\tassertEquals(\"bbb\", h.getEventContent());\n\t\tassertTrue(h.moveToNextEvent());\n\t\tassertEquals(17.7, h.getTimeOfEvent(), TOLERANCE);\n\t\tassertEquals(\"ccc\", h.getEventContent());\n\t\tassertFalse(h.moveToNextEvent());\n\t}" ] }, "content": "package a01c.sol1;\n\nimport static org.junit.Assert.*;\n\nimport java.io.IOException;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.NoSuchElementException;\nimport java.util.Random;\nimport java.util.function.Supplier;\nimport java.util.stream.Stream;\n\npublic class Test {\n\n\t/*\n\t * Implement the EventHistoryFactory interface as indicated in the initFactory method below.\n\t * Create a set of factories for EventHistory, i.e., series of events (time + content pairs).\n\t * \n\t * The comment on the provided interfaces, and the test methods below\n\t * constitute the necessary explanation of the problem.\n\t * \n\t * The following are considered optional for the purpose of being able to correct\n\t * the exercise, but still contribute to achieving the totality of the\n\t * score:\n\t * \n\t * - implementation of the five methods in the factory (i.e., in the mandatory part it is sufficient to\n\t * implement 4 at will)\n\t * \n\t * - good design of the solution, in particular using concise code that avoids repetitions\n\t * \n\t * - avoid creating unnecessary data structures\n\t * \n\t * Remove the comment from the initFactory method.\n\t * \n\t * Scoring indications:\n\t * \n\t * - correctness of the mandatory part: 10 points (2.5+2.5+2.5+2.5)\n\t * \n\t * - correctness of the optional part: 3 points\n\t * \n\t * - quality of the solution: 4 points (3 points for good design, 1 point for no unnecessary structures)\n\t * \n\t */\n\n\t\n\tprivate static final double TOLERANCE = 0.01;\n\n\tprivate EventHistoryFactory factory = null;\n\t\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.factory = new EventHistoryFactoryImpl();\n\t}\n\t\n\[email protected]\n\tpublic void testFromMap() {\n\t\tvar h = this.factory.fromMap(Map.of(1.0,\"uno\", 2.0, \"due\", 3.0, \"tre\"));\n\t\tassertEquals(1.0, h.getTimeOfEvent(), TOLERANCE);\n\t\tassertEquals(\"uno\", h.getEventContent());\n\t\tassertTrue(h.moveToNextEvent());\n\t\tassertEquals(2.0, h.getTimeOfEvent(), TOLERANCE);\n\t\tassertEquals(\"due\", h.getEventContent());\n\t\tassertTrue(h.moveToNextEvent());\n\t\tassertEquals(3.0, h.getTimeOfEvent(), TOLERANCE);\n\t\tassertEquals(\"tre\", h.getEventContent());\n\t\tassertFalse(h.moveToNextEvent());\n\t}\n\t\n\[email protected]\n\tpublic void testFromIterators() {\n\t\tvar i1 = Stream.iterate(1.0, x -> x + 1.0).iterator();\n\t\tvar i2 = Stream.of(\"uno\", \"due\", \"tre\").iterator();\n\t\tvar h = this.factory.fromIterators(i1,i2);\n\t\tassertEquals(1.0, h.getTimeOfEvent(), TOLERANCE);\n\t\tassertEquals(\"uno\", h.getEventContent());\n\t\tassertTrue(h.moveToNextEvent());\n\t\tassertEquals(2.0, h.getTimeOfEvent(), TOLERANCE);\n\t\tassertEquals(\"due\", h.getEventContent());\n\t\tassertTrue(h.moveToNextEvent());\n\t\tassertEquals(3.0, h.getTimeOfEvent(), TOLERANCE);\n\t\tassertEquals(\"tre\", h.getEventContent());\n\t\tassertFalse(h.moveToNextEvent());\n\t}\n\t\n\[email protected]\n\tpublic void testFromListAndDelta() {\n\t\tvar i = List.of(100, 200, 300, 400);\n\t\tvar h = this.factory.fromListAndDelta(i,1.0,0.1);\n\t\tassertEquals(1.0, h.getTimeOfEvent(), TOLERANCE);\n\t\tassertEquals(100, h.getEventContent().intValue());\n\t\tassertTrue(h.moveToNextEvent());\n\t\tassertEquals(1.1, h.getTimeOfEvent(), TOLERANCE);\n\t\tassertEquals(200, h.getEventContent().intValue());\n\t\tassertTrue(h.moveToNextEvent());\n\t\tassertEquals(1.2, h.getTimeOfEvent(), TOLERANCE);\n\t\tassertEquals(300, h.getEventContent().intValue());\n\t\tassertTrue(h.moveToNextEvent());\n\t\tassertEquals(1.3, h.getTimeOfEvent(), TOLERANCE);\n\t\tassertEquals(400, h.getEventContent().intValue());\n\t\tassertFalse(h.moveToNextEvent());\n\t}\n\t\n\[email protected]\n\tpublic void testFromRandomTimesAndSupplier() {\n\t\tRandom random = new Random();\n\t\tSupplier<Boolean> supplier = () -> random.nextBoolean();\n\t\tvar h = this.factory.fromRandomTimesAndSupplier(supplier,3);\n\t\tdouble t1 = h.getTimeOfEvent();\n\t\tboolean b1 = h.getEventContent();\n\t\th.moveToNextEvent();\n\t\tdouble t2 = h.getTimeOfEvent();\n\t\tboolean b2 = h.getEventContent();\n\t\th.moveToNextEvent();\n\t\tdouble t3 = h.getTimeOfEvent();\n\t\tboolean b3 = h.getEventContent();\n\t\tassertFalse(h.moveToNextEvent());\n\t\tSystem.out.println(t1+\" \"+b1);\n\t\tSystem.out.println(t2+\" \"+b2);\n\t\tSystem.out.println(t3+\" \"+b3);\n\t\tassertTrue(t1 <= 1.0);\n\t\tassertTrue(t2 <= t1 + 1.0);\n\t\tassertTrue(t3 <= t2 + 1.0);\n\t}\n\t\n\[email protected]\n\tpublic void testFromFile() throws IOException {\n\t\tvar h = this.factory.fromFile(\"file.txt\");\n\t\tassertEquals(15.5, h.getTimeOfEvent(), TOLERANCE);\n\t\tassertEquals(\"aaa\", h.getEventContent());\n\t\tassertTrue(h.moveToNextEvent());\n\t\tassertEquals(16.6, h.getTimeOfEvent(), TOLERANCE);\n\t\tassertEquals(\"bbb\", h.getEventContent());\n\t\tassertTrue(h.moveToNextEvent());\n\t\tassertEquals(17.7, h.getTimeOfEvent(), TOLERANCE);\n\t\tassertEquals(\"ccc\", h.getEventContent());\n\t\tassertFalse(h.moveToNextEvent());\n\t}\n}", "filename": "Test.java" }
2021
a03c
[ { "content": "package a03c.sol1;\n\n\npublic interface DeterministicParserFactory {\n\n\t\n\tDeterministicParser oneSymbol(String s);\n\t\n\t\n\tDeterministicParser twoSymbols(String s1, String s2);\n\t\n\t\n\tDeterministicParser possiblyEmptyIncreasingSequenceOfPositiveNumbers();\n\t\n\t\n\tDeterministicParser sequenceOfParsersWithDelimiter(String start, String stop, String delimiter, DeterministicParser element);\n\t\n\t\n\tDeterministicParser sequence(DeterministicParser first, DeterministicParser second);\n}", "filename": "DeterministicParserFactory.java" }, { "content": "package a03c.sol1;\n\nimport java.util.Objects;\n\n\n\npublic class Pair<E1,E2> {\n\t\n\tprivate final E1 e1;\n\tprivate final E2 e2;\n\t\n\tpublic Pair(E1 x, E2 y) {\n\t\tsuper();\n\t\tthis.e1 = x;\n\t\tthis.e2 = y;\n\t}\n\n\tpublic E1 get1() {\n\t\treturn e1;\n\t}\n\n\tpublic E2 get2() {\n\t\treturn e2;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Objects.hash(e1, e2);\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj) {\n\t\t\treturn true;\n\t\t}\n\t\tif (obj == null) {\n\t\t\treturn false;\n\t\t}\n\t\tif (getClass() != obj.getClass()) {\n\t\t\treturn false;\n\t\t}\n\t\tPair other = (Pair) obj;\n\t\treturn Objects.equals(e1, other.e1) && Objects.equals(e2, other.e2);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Pair [e1=\" + e1 + \", e2=\" + e2 + \"]\";\n\t}\n\t\n\t\n\n}", "filename": "Pair.java" }, { "content": "package a03c.sol1;\n\nimport java.util.List;\nimport java.util.Optional;\n\n\n@FunctionalInterface\npublic interface DeterministicParser { \n\t\n\t\n\tOptional<List<String>> accepts(List<String> tokens);\n}", "filename": "DeterministicParser.java" } ]
[ { "content": "package a03c.sol1;\n\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Optional;\nimport java.util.function.Predicate;\n\npublic class DeterministicParserFactoryImpl implements DeterministicParserFactory {\n\t\n\tprivate static <E> Optional<List<E>> takeTail(List<E> list){\n\t\tif (list.isEmpty()) {\n\t\t\treturn Optional.empty();\n\t\t}\n\t\tvar l = new LinkedList<>(list);\n\t\tl.removeFirst();\n\t\treturn Optional.of(l);\n\t}\n\n\t@Override\n\tpublic DeterministicParser oneSymbol(String s) {\n\t\treturn filteredSymbol(str -> str.equals(s));\n\t}\n\n\t@Override\n\tpublic DeterministicParser twoSymbols(String s1, String s2) {\n\t\treturn sequence(oneSymbol(s1), oneSymbol(s2));\n\t}\n\n\t@Override\n\tpublic DeterministicParser sequence(DeterministicParser first, DeterministicParser second) {\n\t\treturn tokens -> first.accepts(tokens).flatMap(second::accepts);\n\t}\n\n\tprivate DeterministicParser fullSequence(List<DeterministicParser> list) {\n\t\treturn list.size() == 1 ? list.get(0) : sequence(list.get(0),fullSequence(takeTail(list).get()));\n\t}\n\n\t@Override\n\tpublic DeterministicParser possiblyEmptyIncreasingSequenceOfPositiveNumbers() {\n\t\treturn increasingSequenceOfNumbers(0); \n\t}\n\t\n\tprivate DeterministicParser increasingSequenceOfNumbers(int lowerBound){\n\t\treturn tokens -> {\n\t\t\tvar res1 = filteredSymbol(str -> Integer.parseInt(str)>lowerBound).accepts(tokens);\n\t\t\treturn res1.flatMap(t -> increasingSequenceOfNumbers(Integer.parseInt(tokens.get(0))).accepts(t)).or(()->Optional.of(tokens));\n\t\t};\n\t}\n\t\n\tprivate DeterministicParser filteredSymbol(Predicate<String> predicate) {\n\t\treturn tokens ->\n\t\ttakeTail(tokens).filter(t-> predicate.test(tokens.get(0)));\n\t}\n\t\n\tprivate DeterministicParser many(DeterministicParser parser) {\n\t\treturn tokens ->\n\t\t\tparser.accepts(tokens).isEmpty() ? Optional.of(tokens) : this.sequence(parser, many(parser)).accepts(tokens);\n\t}\n\n\t@Override\n\tpublic DeterministicParser sequenceOfParsersWithDelimiter(String start, String stop, String delimiter,\n\t\t\tDeterministicParser element) {\n\t\treturn this.fullSequence(List.of(\n\t\t\t\toneSymbol(start), element, many(sequence(oneSymbol(delimiter),element)), oneSymbol(stop)\n\t\t\t\t));\n\t}\n\n}", "filename": "DeterministicParserFactoryImpl.java" } ]
{ "components": { "imports": "package a03c.sol1;\n\nimport static org.junit.Assert.*;\n\nimport java.util.List;\nimport java.util.Optional;", "private_init": "\t/*\n\t * Implement the DeterministicParserFactory interface as indicated in the method\n\t * initFactory below. Create a factory for DeterministicParser, i.e.\n\t * parsers of various types, which analyze lists of tokens (strings) to understand\n\t * if they have the desired structure. Note that the design of these parsers is designed to\n\t * be easily composed sequentially.\n\t * \n\t * The comment on the provided interfaces, and the test methods below\n\t * constitute the necessary explanation of the problem.\n\t * \n\t * The following are considered optional for the purpose of being able to correct\n\t * the exercise, but still contribute to achieving the totality of the\n\t * score: \n\t * \n\t * - implementation of the five methods in the factory (i.e., in the mandatory part it is sufficient to \n\t * implement 4 at will) \n\t * \n\t * - the good design of the solution, avoiding repetitions\n\t * \n\t * Remove the comment from the initFactory method.\n\t * \n\t * Scoring indications: \n\t * \n\t * - correctness of the mandatory part: 10 points (2+2+3+3 for the necessary factory methods) \n\t * \n\t * - correctness of the optional part: 3 points (additional method)\n\t * \n\t * - quality of the solution: 4 points (for a solution that minimizes repetitions and follows good programming practices)\n\t * \n\t */\n\n\tprivate DeterministicParserFactory factory = null;\n\t\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.factory = new DeterministicParserFactoryImpl();\n\t}", "test_functions": [ "\[email protected]\n\tpublic void testOneSymbol() {\n\t\tvar dp = this.factory.oneSymbol(\"a\");\n\t\t// with a,b,c it succeeds, returning b,c\n\t\tassertEquals(Optional.of(List.of(\"b\",\"c\")),dp.accepts(List.of(\"a\",\"b\",\"c\")));\n\t\t// with b,b,c it fails\n\t\tassertEquals(Optional.empty(),dp.accepts(List.of(\"b\",\"b\",\"c\")));\n\t}", "\[email protected]\n\tpublic void testTwoSymbols() {\n\t\tvar dp = this.factory.twoSymbols(\"a\",\"b\");\n\t\t// with a,b,c it succeeds, returning c\n\t\tassertEquals(Optional.of(List.of(\"c\")),dp.accepts(List.of(\"a\",\"b\",\"c\")));\n\t\t// with a,a,c it fails\n\t\tassertEquals(Optional.empty(),dp.accepts(List.of(\"a\",\"a\",\"c\")));\n\t}", "\[email protected]\n\tpublic void testIncreasingSequence() {\n\t\tvar dp = this.factory.possiblyEmptyIncreasingSequenceOfPositiveNumbers();\n\t\t// with 10,20,30,29,7 only 10,20,30 is consumed\n\t\tassertEquals(Optional.of(List.of(\"29\",\"7\")),dp.accepts(List.of(\"10\",\"20\",\"30\",\"29\",\"7\")));\n\t\t// here nothing is consumed, but it doesn't fail, because it's an empty sequence\n\t\tassertEquals(Optional.of(List.of(\"-5\",\"20\",\"30\",\"-5\",\"7\")),dp.accepts(List.of(\"-5\",\"20\",\"30\",\"-5\",\"7\")));\n\t\t\n\t}", "\[email protected]\n\tpublic void testSequence() {\n\t\tvar dp = this.factory.sequence(this.factory.oneSymbol(\"a\"), this.factory.twoSymbols(\"b\",\"c\"));\n\t\t// first a is consumed and then b,c\n\t\tassertEquals(Optional.of(List.of(\"d\")),dp.accepts(List.of(\"a\",\"b\",\"c\",\"d\")));\n\t\t// here it fails\n\t\tassertEquals(Optional.empty(),dp.accepts(List.of(\"a\",\"b\",\"d\",\"d\")));\n\t}", "\[email protected]\n\tpublic void testSequenceWithDelimiters() {\n\t\tvar dp = this.factory.sequenceOfParsersWithDelimiter(\"[\", \"]\", \";\", this.factory.oneSymbol(\"a\"));\n\t\t// examples of acceptance\n\t\tassertEquals(Optional.of(List.of(\"-\")),dp.accepts(List.of(\"[\",\"a\",\";\",\"a\",\";\",\"a\",\"]\",\"-\")));\n\t\tassertEquals(Optional.of(List.of(\"-\")),dp.accepts(List.of(\"[\",\"a\",\"]\",\"-\")));\n\t\t// wrong start\n\t\tassertEquals(Optional.empty(),dp.accepts(List.of(\"<\",\"a\",\";\",\"a\",\";\",\"a\",\"]\",\"-\")));\n\t\t// wrong stop\n\t\tassertEquals(Optional.empty(),dp.accepts(List.of(\"[\",\"a\",\";\",\"a\",\";\",\"a\",\">\",\"-\")));\n\t\t// wrong delimiter\n\t\tassertEquals(Optional.empty(),dp.accepts(List.of(\"[\",\"a\",\";\",\"a\",\";;\",\"a\",\"]\",\"-\")));\n\t\t// wrong element\n\t\tassertEquals(Optional.empty(),dp.accepts(List.of(\"[\",\"a\",\";\",\"a\",\"b\",\";\",\"a\",\"]\",\"-\")));\n\t\t// at least one element is required\n\t\tassertEquals(Optional.empty(),dp.accepts(List.of(\"[\",\"]\",\"-\")));\n\t}" ] }, "content": "package a03c.sol1;\n\nimport static org.junit.Assert.*;\n\nimport java.util.List;\nimport java.util.Optional;\n\npublic class Test {\n\n\t/*\n\t * Implement the DeterministicParserFactory interface as indicated in the method\n\t * initFactory below. Create a factory for DeterministicParser, i.e.\n\t * parsers of various types, which analyze lists of tokens (strings) to understand\n\t * if they have the desired structure. Note that the design of these parsers is designed to\n\t * be easily composed sequentially.\n\t * \n\t * The comment on the provided interfaces, and the test methods below\n\t * constitute the necessary explanation of the problem.\n\t * \n\t * The following are considered optional for the purpose of being able to correct\n\t * the exercise, but still contribute to achieving the totality of the\n\t * score: \n\t * \n\t * - implementation of the five methods in the factory (i.e., in the mandatory part it is sufficient to \n\t * implement 4 at will) \n\t * \n\t * - the good design of the solution, avoiding repetitions\n\t * \n\t * Remove the comment from the initFactory method.\n\t * \n\t * Scoring indications: \n\t * \n\t * - correctness of the mandatory part: 10 points (2+2+3+3 for the necessary factory methods) \n\t * \n\t * - correctness of the optional part: 3 points (additional method)\n\t * \n\t * - quality of the solution: 4 points (for a solution that minimizes repetitions and follows good programming practices)\n\t * \n\t */\n\n\tprivate DeterministicParserFactory factory = null;\n\t\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.factory = new DeterministicParserFactoryImpl();\n\t}\n\t\n\[email protected]\n\tpublic void testOneSymbol() {\n\t\tvar dp = this.factory.oneSymbol(\"a\");\n\t\t// with a,b,c it succeeds, returning b,c\n\t\tassertEquals(Optional.of(List.of(\"b\",\"c\")),dp.accepts(List.of(\"a\",\"b\",\"c\")));\n\t\t// with b,b,c it fails\n\t\tassertEquals(Optional.empty(),dp.accepts(List.of(\"b\",\"b\",\"c\")));\n\t}\n\t\n\[email protected]\n\tpublic void testTwoSymbols() {\n\t\tvar dp = this.factory.twoSymbols(\"a\",\"b\");\n\t\t// with a,b,c it succeeds, returning c\n\t\tassertEquals(Optional.of(List.of(\"c\")),dp.accepts(List.of(\"a\",\"b\",\"c\")));\n\t\t// with a,a,c it fails\n\t\tassertEquals(Optional.empty(),dp.accepts(List.of(\"a\",\"a\",\"c\")));\n\t}\n\t\n\[email protected]\n\tpublic void testIncreasingSequence() {\n\t\tvar dp = this.factory.possiblyEmptyIncreasingSequenceOfPositiveNumbers();\n\t\t// with 10,20,30,29,7 only 10,20,30 is consumed\n\t\tassertEquals(Optional.of(List.of(\"29\",\"7\")),dp.accepts(List.of(\"10\",\"20\",\"30\",\"29\",\"7\")));\n\t\t// here nothing is consumed, but it doesn't fail, because it's an empty sequence\n\t\tassertEquals(Optional.of(List.of(\"-5\",\"20\",\"30\",\"-5\",\"7\")),dp.accepts(List.of(\"-5\",\"20\",\"30\",\"-5\",\"7\")));\n\t\t\n\t}\n\t\n\[email protected]\n\tpublic void testSequence() {\n\t\tvar dp = this.factory.sequence(this.factory.oneSymbol(\"a\"), this.factory.twoSymbols(\"b\",\"c\"));\n\t\t// first a is consumed and then b,c\n\t\tassertEquals(Optional.of(List.of(\"d\")),dp.accepts(List.of(\"a\",\"b\",\"c\",\"d\")));\n\t\t// here it fails\n\t\tassertEquals(Optional.empty(),dp.accepts(List.of(\"a\",\"b\",\"d\",\"d\")));\n\t}\n\t\n\[email protected]\n\tpublic void testSequenceWithDelimiters() {\n\t\tvar dp = this.factory.sequenceOfParsersWithDelimiter(\"[\", \"]\", \";\", this.factory.oneSymbol(\"a\"));\n\t\t// examples of acceptance\n\t\tassertEquals(Optional.of(List.of(\"-\")),dp.accepts(List.of(\"[\",\"a\",\";\",\"a\",\";\",\"a\",\"]\",\"-\")));\n\t\tassertEquals(Optional.of(List.of(\"-\")),dp.accepts(List.of(\"[\",\"a\",\"]\",\"-\")));\n\t\t// wrong start\n\t\tassertEquals(Optional.empty(),dp.accepts(List.of(\"<\",\"a\",\";\",\"a\",\";\",\"a\",\"]\",\"-\")));\n\t\t// wrong stop\n\t\tassertEquals(Optional.empty(),dp.accepts(List.of(\"[\",\"a\",\";\",\"a\",\";\",\"a\",\">\",\"-\")));\n\t\t// wrong delimiter\n\t\tassertEquals(Optional.empty(),dp.accepts(List.of(\"[\",\"a\",\";\",\"a\",\";;\",\"a\",\"]\",\"-\")));\n\t\t// wrong element\n\t\tassertEquals(Optional.empty(),dp.accepts(List.of(\"[\",\"a\",\";\",\"a\",\"b\",\";\",\"a\",\"]\",\"-\")));\n\t\t// at least one element is required\n\t\tassertEquals(Optional.empty(),dp.accepts(List.of(\"[\",\"]\",\"-\")));\n\t}\n}", "filename": "Test.java" }
2021
a03b
[ { "content": "package a03b.sol1;\n\n\n\npublic interface Lens<S,A> {\n\t\n\t\n\tA get(S s);\n\t\n\t\n\tS set(A a, S s);\n}", "filename": "Lens.java" }, { "content": "package a03b.sol1;\n\nimport java.util.List;\nimport java.util.function.BiFunction;\nimport java.util.function.Function;\n\n\npublic interface LensFactory {\n\t\n\t\n\t<E> Lens<List<E>,E> indexer(int i);\n\t\n\t\n\t<E> Lens<List<List<E>>,E> doubleIndexer(int i, int j);\n\t\n\t\n\t<A,B> Lens<Pair<A,B>,A> left();\n\t\n\t\n\t<A,B> Lens<Pair<A,B>,B> right();\n\t\n\t\n\t<A,B,C> Lens<List<Pair<A,Pair<B,C>>>,C> rightRightAtPos(int i); \n\n}", "filename": "LensFactory.java" }, { "content": "package a03b.sol1;\n\nimport java.util.Objects;\n\n\n\npublic class Pair<E1,E2> {\n\t\n\tprivate final E1 e1;\n\tprivate final E2 e2;\n\t\n\tpublic Pair(E1 x, E2 y) {\n\t\tsuper();\n\t\tthis.e1 = x;\n\t\tthis.e2 = y;\n\t}\n\n\tpublic E1 get1() {\n\t\treturn e1;\n\t}\n\n\tpublic E2 get2() {\n\t\treturn e2;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Objects.hash(e1, e2);\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj) {\n\t\t\treturn true;\n\t\t}\n\t\tif (obj == null) {\n\t\t\treturn false;\n\t\t}\n\t\tif (getClass() != obj.getClass()) {\n\t\t\treturn false;\n\t\t}\n\t\tPair other = (Pair) obj;\n\t\treturn Objects.equals(e1, other.e1) && Objects.equals(e2, other.e2);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Pair [e1=\" + e1 + \", e2=\" + e2 + \"]\";\n\t}\n\t\n\t\n\n}", "filename": "Pair.java" } ]
[ { "content": "package a03b.sol1;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.function.BiFunction;\nimport java.util.function.Function;\n\npublic class LensFactoryImpl implements LensFactory {\n\n\tprivate static <E> List<E> copyAndSet(List<E> l, int index, E e){\n\t\tvar lo = new ArrayList<>(l);\n\t\tlo.set(index, e);\n\t\treturn lo;\t\t\n\t}\n\t\n\t@Override\n\tpublic <E> Lens<List<E>, E> indexer(int i) {\n\t\treturn general(s -> s.get(i), (a,s) -> copyAndSet(s,i,a));\n\t}\n\n\t@Override\n\tpublic <A, B> Lens<Pair<A, B>, A> left() {\n\t\treturn general(Pair::get1, (a,s) -> new Pair<>(a, s.get2()));\n\t}\n\n\t@Override\n\tpublic <A, B> Lens<Pair<A, B>, B> right() {\n\t\treturn general(Pair::get2, (b,s) -> new Pair<>(s.get1(), b));\n\t}\n\n\t@Override\n\tpublic <A,B,C> Lens<List<Pair<A,Pair<B,C>>>,C> rightRightAtPos(int i){\n\t\treturn compose(indexer(i),compose(right(),right()));\n\t}\n\t\n\t@Override\n\tpublic <E> Lens<List<List<E>>, E> doubleIndexer(int i, int j) {\n\t\treturn compose(indexer(i),indexer(j));\n\t}\n\t\n\tprivate <S, A, B> Lens<S, B> compose(Lens<S, A> l1, Lens<A, B> l2) {\n\t\treturn general(s -> l2.get(l1.get(s)), (b,s) -> l1.set(l2.set(b, l1.get(s)),s));\n\t}\n\n\n\tprivate <S, A> Lens<S, A> general(Function<S, A> getter, BiFunction<A, S, S> setter) {\n\t\treturn new Lens<>() {\n\n\t\t\t@Override\n\t\t\tpublic A get(S s) {\n\t\t\t\treturn getter.apply(s);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic S set(A a, S s) {\n\t\t\t\treturn setter.apply(a, s);\n\t\t\t}\n\t\t\t\n\t\t};\n\t}\n}", "filename": "LensFactoryImpl.java" } ]
{ "components": { "imports": "package a03b.sol1;\n\nimport static org.junit.Assert.*;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.NoSuchElementException;\nimport java.util.Optional;\nimport java.util.function.BiFunction;\nimport java.util.function.Function;", "private_init": "\t/*\n\t * Implement the LensFactory interface as indicated in the method\n\t * initFactory below. Create a factory for Lenses, which model the\n\t * ability to access a certain point in a data structure (even complex)\n\t * to read (get) or modify by copy (set) a subpart of it.\n\t * \n\t * The comment on the provided interfaces, and the test methods below\n\t * constitute the necessary explanation of the problem.\n\t * \n\t * The following are considered optional for the purpose of being able to correct\n\t * the exercise, but still contribute to achieving the totality of the\n\t * score:\n\t * \n\t * - implementation of the five methods in the factory (i.e., in the mandatory part it is sufficient\n\t * to implement 4 at will)\n\t * \n\t * - the good design of the solution, avoiding repetitions\n\t * \n\t * Remove the comment from the initFactory method.\n\t * \n\t * Scoring indications:\n\t * \n\t * - correctness of the mandatory part: 10 points (2+2+3+3 for the necessary factory methods)\n\t * \n\t * - correctness of the optional part: 3 points (additional method)\n\t * \n\t * - quality of the solution: 4 points (for a solution that minimizes repetitions and follows good programming practices)\n\t * \n\t */\n\n\tprivate LensFactory factory = null;\n\t\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.factory = new LensFactoryImpl();\n\t}", "test_functions": [ "\[email protected]\n\tpublic void testIndexer() {\n\t\tvar lens = this.factory.indexer(1);\n\t\t// getter and copy-setter on the 1st element (i.e. the second) of a list\n\t\tassertEquals(20,lens.get(List.of(10,20,30,40,50)));\n\t\tassertEquals(List.of(10,21,30,40,50),lens.set(21,List.of(10,20,30,40,50)));\n\t\t\n\t\tvar lens2 = this.factory.indexer(3);\n\t\t// getter and copy-setter on the 3rd element (i.e. the fourth) of a list\n\t\tassertEquals(40,lens2.get(List.of(10,20,30,40,50)));\n\t\tassertEquals(List.of(10,20,30,41,50),lens2.set(41,List.of(10,20,30,40,50)));\n\t}", "\[email protected]\n\tpublic void testDoubleIndexer() {\n\t\tvar lens = this.factory.doubleIndexer(2,1);\n\t\t// getter and copy-setter on the element of row 2 and column 1 of a list of lists (matrix)\n\t\tassertEquals(31,lens.get(List.of(List.of(10,11,12), List.of(20,21,22), List.of(30,31,32))));\n\t\tassertEquals(\n\t\t\t\tList.of(List.of(10,11,12), List.of(20,21,22), List.of(30,0,32)),\n\t\t\t\tlens.set(0,List.of(List.of(10,11,12), List.of(20,21,22), List.of(30,31,32))));\n\t}", "\[email protected]\n\tpublic void testLeft() {\n\t\tvar lens = this.factory.left();\n\t\t// getter and copy-setter on the first component of the pair\n\t\tassertEquals(\"a\",lens.get(new Pair<>(\"a\",\"b\")));\n\t\tassertEquals(new Pair<>(\"a2\",\"b\"),lens.set(\"a2\",new Pair<>(\"a\",\"b\")));\n\t}", "\[email protected]\n\tpublic void testRight() {\n\t\tvar lens = this.factory.right();\n\t\t// getter and copy-setter on the second component of the pair\n\t\tassertEquals(\"b\",lens.get(new Pair<>(\"a\",\"b\")));\n\t\tassertEquals(new Pair<>(\"a\",\"b2\"),lens.set(\"b2\",new Pair<>(\"a\",\"b\")));\n\t}", "\[email protected]\n\tpublic void testRightRightAtPos() {\n\t\tvar lens = this.factory.rightRightAtPos(2);\n\t\t// getter and setter that access a \"deep\" subpart of a list of pair of pairs\n\t\tassertEquals(222,lens.get(List.of(\n\t\t\t\tnew Pair<>(\"a\",new Pair<>(1,2)),\n\t\t\t\tnew Pair<>(\"b\",new Pair<>(11,22)),\n\t\t\t\tnew Pair<>(\"c\",new Pair<>(111,222)),\n\t\t\t\tnew Pair<>(\"d\",new Pair<>(1111,2222)))));\n\t\tassertEquals(List.of(\n\t\t\t\tnew Pair<>(\"a\",new Pair<>(1,2)),\n\t\t\t\tnew Pair<>(\"b\",new Pair<>(11,22)),\n\t\t\t\tnew Pair<>(\"c\",new Pair<>(111,0)),\n\t\t\t\tnew Pair<>(\"d\",new Pair<>(1111,2222))),\n\t\t\t\tlens.set(0,List.of(\n\t\t\t\t\t\tnew Pair<>(\"a\",new Pair<>(1,2)),\n\t\t\t\t\t\tnew Pair<>(\"b\",new Pair<>(11,22)),\n\t\t\t\t\t\tnew Pair<>(\"c\",new Pair<>(111,222)),\n\t\t\t\t\t\tnew Pair<>(\"d\",new Pair<>(1111,2222)))));\n\t}" ] }, "content": "package a03b.sol1;\n\nimport static org.junit.Assert.*;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.NoSuchElementException;\nimport java.util.Optional;\nimport java.util.function.BiFunction;\nimport java.util.function.Function;\n\npublic class Test {\n\n\t/*\n\t * Implement the LensFactory interface as indicated in the method\n\t * initFactory below. Create a factory for Lenses, which model the\n\t * ability to access a certain point in a data structure (even complex)\n\t * to read (get) or modify by copy (set) a subpart of it.\n\t * \n\t * The comment on the provided interfaces, and the test methods below\n\t * constitute the necessary explanation of the problem.\n\t * \n\t * The following are considered optional for the purpose of being able to correct\n\t * the exercise, but still contribute to achieving the totality of the\n\t * score:\n\t * \n\t * - implementation of the five methods in the factory (i.e., in the mandatory part it is sufficient\n\t * to implement 4 at will)\n\t * \n\t * - the good design of the solution, avoiding repetitions\n\t * \n\t * Remove the comment from the initFactory method.\n\t * \n\t * Scoring indications:\n\t * \n\t * - correctness of the mandatory part: 10 points (2+2+3+3 for the necessary factory methods)\n\t * \n\t * - correctness of the optional part: 3 points (additional method)\n\t * \n\t * - quality of the solution: 4 points (for a solution that minimizes repetitions and follows good programming practices)\n\t * \n\t */\n\n\tprivate LensFactory factory = null;\n\t\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.factory = new LensFactoryImpl();\n\t}\n\t\n\[email protected]\n\tpublic void testIndexer() {\n\t\tvar lens = this.factory.indexer(1);\n\t\t// getter and copy-setter on the 1st element (i.e. the second) of a list\n\t\tassertEquals(20,lens.get(List.of(10,20,30,40,50)));\n\t\tassertEquals(List.of(10,21,30,40,50),lens.set(21,List.of(10,20,30,40,50)));\n\t\t\n\t\tvar lens2 = this.factory.indexer(3);\n\t\t// getter and copy-setter on the 3rd element (i.e. the fourth) of a list\n\t\tassertEquals(40,lens2.get(List.of(10,20,30,40,50)));\n\t\tassertEquals(List.of(10,20,30,41,50),lens2.set(41,List.of(10,20,30,40,50)));\n\t}\n\t\n\[email protected]\n\tpublic void testDoubleIndexer() {\n\t\tvar lens = this.factory.doubleIndexer(2,1);\n\t\t// getter and copy-setter on the element of row 2 and column 1 of a list of lists (matrix)\n\t\tassertEquals(31,lens.get(List.of(List.of(10,11,12), List.of(20,21,22), List.of(30,31,32))));\n\t\tassertEquals(\n\t\t\t\tList.of(List.of(10,11,12), List.of(20,21,22), List.of(30,0,32)),\n\t\t\t\tlens.set(0,List.of(List.of(10,11,12), List.of(20,21,22), List.of(30,31,32))));\n\t}\n\t\n\[email protected]\n\tpublic void testLeft() {\n\t\tvar lens = this.factory.left();\n\t\t// getter and copy-setter on the first component of the pair\n\t\tassertEquals(\"a\",lens.get(new Pair<>(\"a\",\"b\")));\n\t\tassertEquals(new Pair<>(\"a2\",\"b\"),lens.set(\"a2\",new Pair<>(\"a\",\"b\")));\n\t}\n\t\n\[email protected]\n\tpublic void testRight() {\n\t\tvar lens = this.factory.right();\n\t\t// getter and copy-setter on the second component of the pair\n\t\tassertEquals(\"b\",lens.get(new Pair<>(\"a\",\"b\")));\n\t\tassertEquals(new Pair<>(\"a\",\"b2\"),lens.set(\"b2\",new Pair<>(\"a\",\"b\")));\n\t}\n\t\n\[email protected]\n\tpublic void testRightRightAtPos() {\n\t\tvar lens = this.factory.rightRightAtPos(2);\n\t\t// getter and setter that access a \"deep\" subpart of a list of pair of pairs\n\t\tassertEquals(222,lens.get(List.of(\n\t\t\t\tnew Pair<>(\"a\",new Pair<>(1,2)),\n\t\t\t\tnew Pair<>(\"b\",new Pair<>(11,22)),\n\t\t\t\tnew Pair<>(\"c\",new Pair<>(111,222)),\n\t\t\t\tnew Pair<>(\"d\",new Pair<>(1111,2222)))));\n\t\tassertEquals(List.of(\n\t\t\t\tnew Pair<>(\"a\",new Pair<>(1,2)),\n\t\t\t\tnew Pair<>(\"b\",new Pair<>(11,22)),\n\t\t\t\tnew Pair<>(\"c\",new Pair<>(111,0)),\n\t\t\t\tnew Pair<>(\"d\",new Pair<>(1111,2222))),\n\t\t\t\tlens.set(0,List.of(\n\t\t\t\t\t\tnew Pair<>(\"a\",new Pair<>(1,2)),\n\t\t\t\t\t\tnew Pair<>(\"b\",new Pair<>(11,22)),\n\t\t\t\t\t\tnew Pair<>(\"c\",new Pair<>(111,222)),\n\t\t\t\t\t\tnew Pair<>(\"d\",new Pair<>(1111,2222)))));\n\t}\n}", "filename": "Test.java" }
2021
a02c
[ { "content": "package a02c.sol1;\n\npublic interface UniversityProgramFactory {\n\t\n\t\n\tUniversityProgram flexible();\n\t\n\t\n\tUniversityProgram fixed();\n\t\n\t\n\tUniversityProgram balanced();\n\t\n\t\n\tUniversityProgram structured();\n\n}", "filename": "UniversityProgramFactory.java" }, { "content": "package a02c.sol1;\n\nimport java.util.Map;\nimport java.util.Set;\n\n\n\npublic interface UniversityProgram {\n\t\n\t\n\tenum Group {\n\t\tMANDATORY, OPTIONAL, OPTIONAL_A, OPTIONAL_B, FREE, THESIS\n\t}\n\t\n\t\n\tvoid setCourses(Map<String,Pair<Set<Group>,Integer>> courses);\t\n\t\n\t\n\tboolean isValid(Set<String> courseNames);\n}", "filename": "UniversityProgram.java" }, { "content": "package a02c.sol1;\n\nimport java.util.Objects;\n\n\n\npublic class Pair<E1,E2> {\n\t\n\tprivate final E1 e1;\n\tprivate final E2 e2;\n\t\n\tpublic Pair(E1 x, E2 y) {\n\t\tsuper();\n\t\tthis.e1 = x;\n\t\tthis.e2 = y;\n\t}\n\n\tpublic E1 get1() {\n\t\treturn e1;\n\t}\n\n\tpublic E2 get2() {\n\t\treturn e2;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Objects.hash(e1, e2);\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj) {\n\t\t\treturn true;\n\t\t}\n\t\tif (obj == null) {\n\t\t\treturn false;\n\t\t}\n\t\tif (getClass() != obj.getClass()) {\n\t\t\treturn false;\n\t\t}\n\t\tPair other = (Pair) obj;\n\t\treturn Objects.equals(e1, other.e1) && Objects.equals(e2, other.e2);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Pair [e1=\" + e1 + \", e2=\" + e2 + \"]\";\n\t}\n\t\n\t\n\n}", "filename": "Pair.java" } ]
[ { "content": "package a02c.sol1;\n\nimport java.util.Set;\nimport java.util.function.Predicate;\nimport static a02c.sol1.UniversityProgram.Group.*;\n\npublic class UniversityProgramFactoryImpl implements UniversityProgramFactory {\n\n\t@Override\n\tpublic UniversityProgram flexible() {\n\t\treturn new AbstractUniversityProgram() {\n\n\t\t\t@Override\n\t\t\tprotected Set<Pair<Predicate<Group>, Predicate<Integer>>> getConstraints() {\n\t\t\t\treturn Set.<Pair<Predicate<Group>, Predicate<Integer>>>of(\n\t\t\t\t\t\tnew Pair<>(g -> true, c -> c == 48)\n\t\t\t\t);\n\t\t\t}\n\n\t\t};\n\t}\n\n\t@Override\n\tpublic UniversityProgram fixed() {\n\t\treturn new AbstractUniversityProgram() {\n\n\t\t\t@Override\n\t\t\tprotected Set<Pair<Predicate<Group>, Predicate<Integer>>> getConstraints() {\n\t\t\t\treturn Set.<Pair<Predicate<Group>, Predicate<Integer>>>of(\n\t\t\t\t\t\tnew Pair<>(g -> true, c -> c == 60),\n\t\t\t\t\t\tnew Pair<>(g -> g == MANDATORY, c -> c == 12),\n\t\t\t\t\t\tnew Pair<>(g -> g == OPTIONAL, c -> c == 36),\n\t\t\t\t\t\tnew Pair<>(g -> g == THESIS, c -> c == 12)\n\t\t\t\t);\n\t\t\t}\n\t\t};\n\t}\n\n\t@Override\n\tpublic UniversityProgram balanced() {\n\t\treturn new AbstractUniversityProgram() {\n\n\t\t\t@Override\n\t\t\tprotected Set<Pair<Predicate<Group>, Predicate<Integer>>> getConstraints() {\n\t\t\t\treturn Set.<Pair<Predicate<Group>, Predicate<Integer>>>of(\n\t\t\t\t\t\tnew Pair<>(g -> true, c -> c == 60),\n\t\t\t\t\t\tnew Pair<>(g -> g == MANDATORY, c -> c == 24),\n\t\t\t\t\t\tnew Pair<>(g -> g == OPTIONAL, c -> c >= 24),\n\t\t\t\t\t\tnew Pair<>(g -> g == FREE, c -> c <= 12),\n\t\t\t\t\t\tnew Pair<>(g -> g == THESIS, c -> c <= 12)\n\t\t\t\t);\n\t\t\t}\n\t\t};\n\t}\n\n\t@Override\n\tpublic UniversityProgram structured() {\n\t\treturn new AbstractUniversityProgram() {\n\n\t\t\t@Override\n\t\t\tprotected Set<Pair<Predicate<Group>, Predicate<Integer>>> getConstraints() {\n\t\t\t\treturn Set.<Pair<Predicate<Group>, Predicate<Integer>>>of(\n\t\t\t\t\t\tnew Pair<>(g -> true, c -> c == 60),\n\t\t\t\t\t\tnew Pair<>(g -> g == MANDATORY, c -> c == 12),\n\t\t\t\t\t\tnew Pair<>(g -> g == OPTIONAL_A, c -> c >= 6),\n\t\t\t\t\t\tnew Pair<>(g -> g == OPTIONAL_B, c -> c >= 6),\n\t\t\t\t\t\tnew Pair<>(g -> g == OPTIONAL_A || g == OPTIONAL_B, c -> c == 30),\n\t\t\t\t\t\tnew Pair<>(g -> g == FREE | g == THESIS, c -> c == 18)\n\t\t\t\t);\n\t\t\t}\n\t\t};\n\t}\n}", "filename": "UniversityProgramFactoryImpl.java" }, { "content": "package a02c.sol1;\n\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.function.Predicate;\n\npublic abstract class AbstractUniversityProgram implements UniversityProgram {\n\t\n\tprivate Map<String,Pair<Set<Group>,Integer>> coursesMap = new HashMap<>();\n\t\n\t@Override\n\tpublic void setCourses(Map<String,Pair<Set<Group>,Integer>> map) {\n\t\tthis.coursesMap = Collections.unmodifiableMap(map);\n\t}\t\n\t\n\t@Override\n\tpublic boolean isValid(Set<String> courses) {\n\t\treturn this.getConstraints().stream().allMatch(c -> this.isConstraintSatisfied(c, courses));\n\t}\n\t\n\tprivate boolean isConstraintSatisfied(Pair<Predicate<Group>,Predicate<Integer>> constraint, Set<String> courses) {\n\t\tint credits = courses.stream()\n\t\t\t\t.filter(c -> this.coursesMap.get(c).get1().stream().anyMatch(constraint.get1()))\n\t\t\t\t.mapToInt(c -> this.coursesMap.get(c).get2()).sum();\n\t\tSystem.out.println(courses+\" \"+credits);\n\t\treturn constraint.get2().test(credits);\n\t}\n\n\tprotected abstract Set<Pair<Predicate<Group>,Predicate<Integer>>> getConstraints();\n\t\n}", "filename": "AbstractUniversityProgram.java" } ]
{ "components": { "imports": "package a02c.sol1;\n\nimport static org.junit.Assert.*;\n\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Set;\n\nimport a02c.sol1.UniversityProgram.Group;\n\nimport static a02c.sol1.UniversityProgram.Group.*;", "private_init": "\t/*\n\t * Implement the UniversityProgramFactory interface as indicated in the initFactory\n\t * method below. Create a factory for a degree course concept (program),\n\t * captured by the UniversityProgram interface.\n\t * \n\t * As can be seen in the fillProgram method below, a degree program is first\n\t * associated with a set of courses (key of the map), each with a certain number of\n\t * credits and a set of course groups (as a pair, value of the map),\n\t * for example:\n\t * map.put(\"AI\", new Pair<>(Set.of(OPTIONAL, OPTIONAL_A), 6));\n\t * means that the AI course has 6 credits and can be used in both the OPTIONAL and OPTIONAL_A groups.\n\t * \n\t * At that point, the degree program has a method to determine whether a certain selection of courses (i.e.,\n\t * a curriculum presented by a student) meets the requirements, expressed by a\n\t * degree program-specific logic, in terms of the number of credits (minimum and/or maximum) for each group. This\n\t * logic is specified in the factory. For example, if it is said that the OPTIONAL courses must be at\n\t * most 12 credits, it means that the sum of the credits of the courses that can belong to the\n\t * OPTIONAL group must be at most 12 credits.\n\t *\n\t * The following are considered optional for the purpose of being able to correct\n\t * the exercise, but still contribute to achieving the totality of the\n\t * score:\n\t * \n\t * - implementation of the four methods of the factory (i.e., in the mandatory part it is sufficient\n\t * to implement 3 at will)\n\t * - good design of the solution, using patterns that lead to succinct code\n\t * that avoids repetitions\n\t * \n\t * Remove the comment from the initFactory method.\n\t * \n\t * Scoring indications:\n\t * - correctness of the mandatory part: 10 points\n\t * - correctness of the optional part: 3 points (additional method of the factory)\n\t * - quality of the solution: 4 points (for good design)\n\t * \n\t */\n\n\tprivate UniversityProgramFactory factory = null;\n\t\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.factory = new UniversityProgramFactoryImpl();\n\t}\n\t\n\tprivate void fillProgram(UniversityProgram program) {\n\t\tMap<String,Pair<Set<Group>,Integer>> map = new HashMap<>();\n\t\tmap.put(\"PROG_LANGS\", new Pair<>(Set.of(MANDATORY), 12));\n\t\tmap.put(\"DIST_SYS\", new Pair<>(Set.of(MANDATORY), 6));\n\t\tmap.put(\"SOFT_ENG\", new Pair<>(Set.of(MANDATORY), 12));\n\t\tmap.put(\"TECH_WEB\", new Pair<>(Set.of(MANDATORY), 6));\n\t\tmap.put(\"AI\", new Pair<>(Set.of(OPTIONAL, OPTIONAL_A), 6));\n\t\tmap.put(\"SMART_CITY\", new Pair<>(Set.of(OPTIONAL, OPTIONAL_A), 6));\n\t\tmap.put(\"ROBOTICS\", new Pair<>(Set.of(OPTIONAL, OPTIONAL_A), 6));\n\t\tmap.put(\"DATA_MINING\", new Pair<>(Set.of(OPTIONAL, OPTIONAL_B), 12));\n\t\tmap.put(\"BUS_ANALYTICS\", new Pair<>(Set.of(OPTIONAL, OPTIONAL_B), 6));\n\t\tmap.put(\"SEM_WEB\", new Pair<>(Set.of(OPTIONAL, OPTIONAL_B), 6));\n\t\tmap.put(\"DEEP_LEARN\", new Pair<>(Set.of(OPTIONAL, OPTIONAL_A, OPTIONAL_B), 12));\n\t\tmap.put(\"NETWORKS\", new Pair<>(Set.of(FREE), 6));\n\t\tmap.put(\"VISION\", new Pair<>(Set.of(FREE), 6));\n\t\tmap.put(\"THESIS\", new Pair<>(Set.of(THESIS), 12));\n\t\tprogram.setCourses(map);\n\t}", "test_functions": [ "\[email protected]\n\tpublic void testFlexible() {\n\t\tvar program = this.factory.flexible();\n\t\tfillProgram(program);\n\t\tassertTrue(program.isValid(Set.of(\"PROG_LANGS\", \"AI\", \"DEEP_LEARN\", \"NETWORKS\", \"THESIS\"))); // 48 CFU\n\t\tassertFalse(program.isValid(Set.of(\"PROG_LANGS\", \"AI\", \"DEEP_LEARN\", \"NETWORKS\"))); // not 48 CFU\n\t\tassertFalse(program.isValid(Set.of(\"PROG_LANGS\", \"AI\", \"DEEP_LEARN\", \"NETWORKS\", \"THESIS\",\"SEM_WEB\"))); // not 48 CFU\n\t}", "\[email protected]\n\tpublic void testFixed() {\n\t\tvar program = this.factory.fixed();\n\t\tfillProgram(program);\n\t\tassertTrue(program.isValid(Set.of(\"PROG_LANGS\", \"AI\", \"ROBOTICS\", \"DEEP_LEARN\", \"DATA_MINING\", \"THESIS\"))); // OK\n\t\tassertFalse(program.isValid(Set.of(\"PROG_LANGS\", \"TECH_WEB\", \"ROBOTICS\", \"DEEP_LEARN\", \"DATA_MINING\", \"THESIS\"))); // Too much \"mandatory\"\n\t\tassertFalse(program.isValid(Set.of(\"PROG_LANGS\", \"VISION\", \"ROBOTICS\", \"DEEP_LEARN\", \"DATA_MINING\", \"THESIS\"))); // No Free course allowed\n\t}", "\[email protected]\n\tpublic void testBalanced() {\n\t\tvar program = this.factory.balanced();\n\t\tfillProgram(program);\n\t\tassertTrue(program.isValid(Set.of(\"PROG_LANGS\", \"SOFT_ENG\", \"DEEP_LEARN\", \"DATA_MINING\", \"THESIS\"))); // ok\n\t\tassertFalse(program.isValid(Set.of(\"PROG_LANGS\", \"SOFT_ENG\", \"DEEP_LEARN\", \"ROBOTICS\", \"VISION\", \"THESIS\"))); // Thesis+Free > 12\n\t\tassertFalse(program.isValid(Set.of(\"PROG_LANGS\", \"AI\", \"ROBOTICS\", \"DEEP_LEARN\", \"DATA_MINING\", \"THESIS\"))); // not enough mandatory\n\t}", "\[email protected]\n\tpublic void testStructured() {\n\t\tvar program = this.factory.structured();\n\t\tfillProgram(program);\n\t\tassertTrue(program.isValid(Set.of(\"PROG_LANGS\", \"SMART_CITY\", \"DATA_MINING\", \"DEEP_LEARN\", \"NETWORKS\", \"THESIS\"))); // ok\n\t\tassertFalse(program.isValid(Set.of(\"PROG_LANGS\", \"SEM_WEB\", \"DATA_MINING\", \"BUS_ANALYTICS\", \"NETWORKS\", \"THESIS\"))); // not ok\n\t}" ] }, "content": "package a02c.sol1;\n\nimport static org.junit.Assert.*;\n\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Set;\n\nimport a02c.sol1.UniversityProgram.Group;\n\nimport static a02c.sol1.UniversityProgram.Group.*;\n\npublic class Test {\n\n\t/*\n\t * Implement the UniversityProgramFactory interface as indicated in the initFactory\n\t * method below. Create a factory for a degree course concept (program),\n\t * captured by the UniversityProgram interface.\n\t * \n\t * As can be seen in the fillProgram method below, a degree program is first\n\t * associated with a set of courses (key of the map), each with a certain number of\n\t * credits and a set of course groups (as a pair, value of the map),\n\t * for example:\n\t * map.put(\"AI\", new Pair<>(Set.of(OPTIONAL, OPTIONAL_A), 6));\n\t * means that the AI course has 6 credits and can be used in both the OPTIONAL and OPTIONAL_A groups.\n\t * \n\t * At that point, the degree program has a method to determine whether a certain selection of courses (i.e.,\n\t * a curriculum presented by a student) meets the requirements, expressed by a\n\t * degree program-specific logic, in terms of the number of credits (minimum and/or maximum) for each group. This\n\t * logic is specified in the factory. For example, if it is said that the OPTIONAL courses must be at\n\t * most 12 credits, it means that the sum of the credits of the courses that can belong to the\n\t * OPTIONAL group must be at most 12 credits.\n\t *\n\t * The following are considered optional for the purpose of being able to correct\n\t * the exercise, but still contribute to achieving the totality of the\n\t * score:\n\t * \n\t * - implementation of the four methods of the factory (i.e., in the mandatory part it is sufficient\n\t * to implement 3 at will)\n\t * - good design of the solution, using patterns that lead to succinct code\n\t * that avoids repetitions\n\t * \n\t * Remove the comment from the initFactory method.\n\t * \n\t * Scoring indications:\n\t * - correctness of the mandatory part: 10 points\n\t * - correctness of the optional part: 3 points (additional method of the factory)\n\t * - quality of the solution: 4 points (for good design)\n\t * \n\t */\n\n\tprivate UniversityProgramFactory factory = null;\n\t\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.factory = new UniversityProgramFactoryImpl();\n\t}\n\t\n\tprivate void fillProgram(UniversityProgram program) {\n\t\tMap<String,Pair<Set<Group>,Integer>> map = new HashMap<>();\n\t\tmap.put(\"PROG_LANGS\", new Pair<>(Set.of(MANDATORY), 12));\n\t\tmap.put(\"DIST_SYS\", new Pair<>(Set.of(MANDATORY), 6));\n\t\tmap.put(\"SOFT_ENG\", new Pair<>(Set.of(MANDATORY), 12));\n\t\tmap.put(\"TECH_WEB\", new Pair<>(Set.of(MANDATORY), 6));\n\t\tmap.put(\"AI\", new Pair<>(Set.of(OPTIONAL, OPTIONAL_A), 6));\n\t\tmap.put(\"SMART_CITY\", new Pair<>(Set.of(OPTIONAL, OPTIONAL_A), 6));\n\t\tmap.put(\"ROBOTICS\", new Pair<>(Set.of(OPTIONAL, OPTIONAL_A), 6));\n\t\tmap.put(\"DATA_MINING\", new Pair<>(Set.of(OPTIONAL, OPTIONAL_B), 12));\n\t\tmap.put(\"BUS_ANALYTICS\", new Pair<>(Set.of(OPTIONAL, OPTIONAL_B), 6));\n\t\tmap.put(\"SEM_WEB\", new Pair<>(Set.of(OPTIONAL, OPTIONAL_B), 6));\n\t\tmap.put(\"DEEP_LEARN\", new Pair<>(Set.of(OPTIONAL, OPTIONAL_A, OPTIONAL_B), 12));\n\t\tmap.put(\"NETWORKS\", new Pair<>(Set.of(FREE), 6));\n\t\tmap.put(\"VISION\", new Pair<>(Set.of(FREE), 6));\n\t\tmap.put(\"THESIS\", new Pair<>(Set.of(THESIS), 12));\n\t\tprogram.setCourses(map);\n\t}\n\t\n\[email protected]\n\tpublic void testFlexible() {\n\t\tvar program = this.factory.flexible();\n\t\tfillProgram(program);\n\t\tassertTrue(program.isValid(Set.of(\"PROG_LANGS\", \"AI\", \"DEEP_LEARN\", \"NETWORKS\", \"THESIS\"))); // 48 CFU\n\t\tassertFalse(program.isValid(Set.of(\"PROG_LANGS\", \"AI\", \"DEEP_LEARN\", \"NETWORKS\"))); // not 48 CFU\n\t\tassertFalse(program.isValid(Set.of(\"PROG_LANGS\", \"AI\", \"DEEP_LEARN\", \"NETWORKS\", \"THESIS\",\"SEM_WEB\"))); // not 48 CFU\n\t}\n\t\n\[email protected]\n\tpublic void testFixed() {\n\t\tvar program = this.factory.fixed();\n\t\tfillProgram(program);\n\t\tassertTrue(program.isValid(Set.of(\"PROG_LANGS\", \"AI\", \"ROBOTICS\", \"DEEP_LEARN\", \"DATA_MINING\", \"THESIS\"))); // OK\n\t\tassertFalse(program.isValid(Set.of(\"PROG_LANGS\", \"TECH_WEB\", \"ROBOTICS\", \"DEEP_LEARN\", \"DATA_MINING\", \"THESIS\"))); // Too much \"mandatory\"\n\t\tassertFalse(program.isValid(Set.of(\"PROG_LANGS\", \"VISION\", \"ROBOTICS\", \"DEEP_LEARN\", \"DATA_MINING\", \"THESIS\"))); // No Free course allowed\n\t}\n\t\n\[email protected]\n\tpublic void testBalanced() {\n\t\tvar program = this.factory.balanced();\n\t\tfillProgram(program);\n\t\tassertTrue(program.isValid(Set.of(\"PROG_LANGS\", \"SOFT_ENG\", \"DEEP_LEARN\", \"DATA_MINING\", \"THESIS\"))); // ok\n\t\tassertFalse(program.isValid(Set.of(\"PROG_LANGS\", \"SOFT_ENG\", \"DEEP_LEARN\", \"ROBOTICS\", \"VISION\", \"THESIS\"))); // Thesis+Free > 12\n\t\tassertFalse(program.isValid(Set.of(\"PROG_LANGS\", \"AI\", \"ROBOTICS\", \"DEEP_LEARN\", \"DATA_MINING\", \"THESIS\"))); // not enough mandatory\n\t}\n\t\n\[email protected]\n\tpublic void testStructured() {\n\t\tvar program = this.factory.structured();\n\t\tfillProgram(program);\n\t\tassertTrue(program.isValid(Set.of(\"PROG_LANGS\", \"SMART_CITY\", \"DATA_MINING\", \"DEEP_LEARN\", \"NETWORKS\", \"THESIS\"))); // ok\n\t\tassertFalse(program.isValid(Set.of(\"PROG_LANGS\", \"SEM_WEB\", \"DATA_MINING\", \"BUS_ANALYTICS\", \"NETWORKS\", \"THESIS\"))); // not ok\n\t}\n}", "filename": "Test.java" }
2021
a01b
[ { "content": "package a01b.sol1;\n\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Optional;\nimport java.util.function.Predicate;\n\n\npublic interface EventSequenceProducerHelpers {\n\t\n\t\n\t<E> EventSequenceProducer<E> fromIterator(Iterator<Pair<Double,E>> iterator);\n\t\n\t\n\t<E> List<E> window(EventSequenceProducer<E> sequence, double fromTime, double toTime);\n\t\n\t\n\t<E> Iterable<E> asEventContentIterable(EventSequenceProducer<E> sequence);\n\t\n\t\n\t<E> Optional<Pair<Double,E>> nextAt(EventSequenceProducer<E> sequence, double time);\n\t\n\t\n\t<E> EventSequenceProducer<E> filter(EventSequenceProducer<E> sequence, Predicate<E> predicate);\n}", "filename": "EventSequenceProducerHelpers.java" }, { "content": "package a01b.sol1;\n\nimport java.util.Objects;\n\n\n\npublic class Pair<E1,E2> {\n\t\n\tprivate final E1 e1;\n\tprivate final E2 e2;\n\t\n\tpublic Pair(E1 x, E2 y) {\n\t\tsuper();\n\t\tthis.e1 = x;\n\t\tthis.e2 = y;\n\t}\n\n\tpublic E1 get1() {\n\t\treturn e1;\n\t}\n\n\tpublic E2 get2() {\n\t\treturn e2;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Objects.hash(e1, e2);\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj) {\n\t\t\treturn true;\n\t\t}\n\t\tif (obj == null) {\n\t\t\treturn false;\n\t\t}\n\t\tif (getClass() != obj.getClass()) {\n\t\t\treturn false;\n\t\t}\n\t\tPair other = (Pair) obj;\n\t\treturn Objects.equals(e1, other.e1) && Objects.equals(e2, other.e2);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Pair [e1=\" + e1 + \", e2=\" + e2 + \"]\";\n\t}\n\t\n\t\n\n}", "filename": "Pair.java" }, { "content": "package a01b.sol1;\n\nimport java.util.NoSuchElementException;\n\n\npublic interface EventSequenceProducer<E> {\n\t\n\t\n\tPair<Double,E> getNext() throws NoSuchElementException;\n}", "filename": "EventSequenceProducer.java" } ]
[ { "content": "package a01b.sol1;\n\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.NoSuchElementException;\nimport java.util.Optional;\nimport java.util.function.Predicate;\nimport java.util.function.Supplier;\nimport java.util.stream.Stream;\nimport java.util.stream.Collectors;\n\npublic class EventSequenceProducerHelpersImpl implements EventSequenceProducerHelpers {\n\t\n\tprivate <E> Optional<E> optionalOfFaulty(Supplier<E> supplier) {\n\t\ttry {\n\t\t\treturn Optional.of(supplier.get());\n\t\t} catch (Exception e) {\n\t\t\treturn Optional.empty();\n\t\t}\n\t}\n\t\n\tprivate <E> Stream<Pair<Double,E>> producerToStream(EventSequenceProducer<E> producer){\n\t\treturn Stream.generate(()->optionalOfFaulty(producer::getNext))\n\t\t\t\t.takeWhile(Optional::isPresent)\n\t\t\t\t.map(Optional::get);\n\t}\n\t\n\t@Override\n\tpublic <E> List<E> window(EventSequenceProducer<E> history, double fromTime, double toTime) {\n\t\treturn this.producerToStream(history)\n\t\t\t\t.dropWhile(p -> p.get1()<fromTime)\n\t\t\t\t.takeWhile(p -> p.get1()<toTime)\n\t\t\t\t.map(Pair::get2)\n\t\t\t\t.collect(Collectors.toList());\n\t}\n\n\t@Override\n\tpublic <E> Iterable<E> asEventContentIterable(EventSequenceProducer<E> history) {\n\t\treturn ()->this.producerToStream(history).map(Pair::get2).iterator();\n\t}\n\n\t@Override\n\tpublic <E> Optional<Pair<Double, E>> nextAt(EventSequenceProducer<E> history, double time) {\n\t\treturn this.producerToStream(history)\n\t\t\t\t.dropWhile(p -> p.get1()<time)\n\t\t\t\t.findFirst();\n\t}\n\n\t@Override\n\tpublic <E> EventSequenceProducer<E> fromIterator(Iterator<Pair<Double, E>> iterator) {\n\t\treturn () -> {\n\t\t\t\tif (iterator.hasNext()) {\n\t\t\t\t\treturn iterator.next();\n\t\t\t\t}\n\t\t\t\tthrow new NoSuchElementException();\n\t\t};\n\t}\n\n\t@Override\n\tpublic <E> EventSequenceProducer<E> filter(EventSequenceProducer<E> sequence, Predicate<E> predicate) {\n\t\treturn this.fromIterator(producerToStream(sequence).filter(p -> predicate.test(p.get2())).iterator());\n\t}\n}", "filename": "EventSequenceProducerHelpersImpl.java" } ]
{ "components": { "imports": "package a01b.sol1;\n\nimport static org.junit.Assert.*;\n\nimport java.util.List;\nimport java.util.NoSuchElementException;\nimport java.util.Optional;", "private_init": "\t/*\n\t * Implement the EventSequenceProducerHelpers interface as indicated in the method\n\t * initFactory below. Implement a set of helper functionalities for\n\t * EventSequenceProducer, i.e., event sources (time + content pairs).\n\t * \n\t * The comment on the provided interfaces, and the test methods below\n\t * constitute the necessary explanation of the problem.\n\t * \n\t * The following are considered optional for the purpose of being able to correct\n\t * the exercise, but still contribute to achieving the totality of the\n\t * score:\n\t * \n\t * - implementation of the five methods in the helper (i.e., in the mandatory part it is sufficient\n\t * to implement 4 at will)\n\t * \n\t * - good design of the solution, in particular using succinct code that avoids repetitions\n\t * \n\t * - avoid creating unnecessary data structures\n\t * \n\t * Remove the comment from the initFactory method.\n\t * \n\t * Scoring indications:\n\t * \n\t * - correctness of the mandatory part: 10 points (2.5 for each method of the helper)\n\t * \n\t * - correctness of the optional part: 3 points (last method)\n\t * \n\t * - quality of the solution: 4 points (3 points for good design, 1 point for no unnecessary structures)\n\t * \n\t */\n\n\tprivate EventSequenceProducerHelpers helpers = null;\n\t\n\tprivate final static List<Pair<Double,String>> EVENTS = List.of(\n\t\t\tnew Pair<>(1.1, \"uno\"),\n\t\t\tnew Pair<>(2.2, \"due\"),\n\t\t\tnew Pair<>(3.3, \"tre\"),\n\t\t\tnew Pair<>(4.4, \"quattro\")\n\t);\n\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.helpers = new EventSequenceProducerHelpersImpl();\n\t}", "test_functions": [ "\[email protected]\n\tpublic void testFromIterator() {\n\t\tfinal var producer = this.helpers.fromIterator(EVENTS.iterator());\n\t\t// produces the 4 elements of EVENTS, and then fails in trying to produce the fifth\n\t\tassertEquals(new Pair<>(1.1, \"uno\"),producer.getNext());\n\t\tassertEquals(new Pair<>(2.2, \"due\"),producer.getNext());\n\t\tassertEquals(new Pair<>(3.3, \"tre\"),producer.getNext());\n\t\tassertEquals(new Pair<>(4.4, \"quattro\"),producer.getNext());\n\t\tassertThrows(NoSuchElementException.class, ()->producer.getNext());\n\t}", "\[email protected]\n\tpublic void testWindow() {\n\t\tvar producer = this.helpers.fromIterator(EVENTS.iterator());\n\t\t// the window [2.0,4.0] produces only the events \"due\" and \"tre\"\n\t\tassertEquals(List.of(\"due\", \"tre\"), this.helpers.window(producer, 2.0, 4.0));\n\t\tproducer = this.helpers.fromIterator(EVENTS.iterator());\n\t\t// the window [1.0,4.0] produces only the events \"uno\",\"due\" and \"tre\"\n\t\tassertEquals(List.of(\"uno\", \"due\", \"tre\"), this.helpers.window(producer, 1.0, 4.0));\n\t\tproducer = this.helpers.fromIterator(EVENTS.iterator());\n\t\t// the window [1.5,2.0] produces nothing\n\t\tassertEquals(List.of(), this.helpers.window(producer, 1.5, 2.0));\n\t}", "\[email protected]\n\tpublic void testAsIterable() {\n\t\tfinal var producer = this.helpers.fromIterator(EVENTS.iterator());\n\t\tfinal var iterable = this.helpers.asEventContentIterable(producer);\n\t\t// the iterable obtained generates an iterator that behaves by producing only the 4 events\n\t\tfinal var iterator = iterable.iterator();\n\t\tassertTrue(iterator.hasNext());\n\t\tassertEquals(\"uno\", iterator.next());\n\t\tassertTrue(iterator.hasNext());\n\t\tassertEquals(\"due\", iterator.next());\n\t\tassertTrue(iterator.hasNext());\n\t\tassertEquals(\"tre\", iterator.next());\n\t\tassertTrue(iterator.hasNext());\n\t\tassertEquals(\"quattro\", iterator.next());\n\t\tassertFalse(iterator.hasNext());\n\t}", "\[email protected]\n\tpublic void testNextAt() {\n\t\tvar producer = this.helpers.fromIterator(EVENTS.iterator());\n\t\t// the event after time 2.0 is (2.2, \"due\")\n\t\tassertEquals(Optional.of(new Pair<>(2.2, \"due\")), this.helpers.nextAt(producer, 2.0));\n\t\tproducer = this.helpers.fromIterator(EVENTS.iterator());\n\t\t// the event after time 4.0 is (4.4, \"quattro\")\n\t\tassertEquals(Optional.of(new Pair<>(4.4, \"quattro\")), this.helpers.nextAt(producer, 4.0));\n\t\tproducer = this.helpers.fromIterator(EVENTS.iterator());\n\t\t// the event after time 5.0 does not exist\n\t\tassertEquals(Optional.empty(), this.helpers.nextAt(producer, 5.0));\n\t}", "\[email protected]\n\tpublic void optionalTestFilter1() {\n\t\tvar producer = this.helpers.fromIterator(EVENTS.iterator());\n\t\tvar out = this.helpers.filter(producer, s -> s.length()==3);\n\t\t// a producer of only three events remains by filtering those with content of length 3\n\t\tassertEquals(new Pair<>(1.1, \"uno\"),out.getNext());\n\t\tassertEquals(new Pair<>(2.2, \"due\"),out.getNext());\n\t\tassertEquals(new Pair<>(3.3, \"tre\"),out.getNext());\n\t\tassertThrows(NoSuchElementException.class, ()->out.getNext());\t\n\t}", "\[email protected]\n\tpublic void optionalTestFilter2() {\n\t\tvar producer = this.helpers.fromIterator(EVENTS.iterator());\n\t\tvar out = this.helpers.filter(producer, s -> s.length()==4);\n\t\t// an empty producer remains by filtering those with content of length 4\n\t\tassertThrows(NoSuchElementException.class, ()->out.getNext());\t\n\t}" ] }, "content": "package a01b.sol1;\n\nimport static org.junit.Assert.*;\n\nimport java.util.List;\nimport java.util.NoSuchElementException;\nimport java.util.Optional;\n\npublic class Test {\n\n\t/*\n\t * Implement the EventSequenceProducerHelpers interface as indicated in the method\n\t * initFactory below. Implement a set of helper functionalities for\n\t * EventSequenceProducer, i.e., event sources (time + content pairs).\n\t * \n\t * The comment on the provided interfaces, and the test methods below\n\t * constitute the necessary explanation of the problem.\n\t * \n\t * The following are considered optional for the purpose of being able to correct\n\t * the exercise, but still contribute to achieving the totality of the\n\t * score:\n\t * \n\t * - implementation of the five methods in the helper (i.e., in the mandatory part it is sufficient\n\t * to implement 4 at will)\n\t * \n\t * - good design of the solution, in particular using succinct code that avoids repetitions\n\t * \n\t * - avoid creating unnecessary data structures\n\t * \n\t * Remove the comment from the initFactory method.\n\t * \n\t * Scoring indications:\n\t * \n\t * - correctness of the mandatory part: 10 points (2.5 for each method of the helper)\n\t * \n\t * - correctness of the optional part: 3 points (last method)\n\t * \n\t * - quality of the solution: 4 points (3 points for good design, 1 point for no unnecessary structures)\n\t * \n\t */\n\n\tprivate EventSequenceProducerHelpers helpers = null;\n\t\n\tprivate final static List<Pair<Double,String>> EVENTS = List.of(\n\t\t\tnew Pair<>(1.1, \"uno\"),\n\t\t\tnew Pair<>(2.2, \"due\"),\n\t\t\tnew Pair<>(3.3, \"tre\"),\n\t\t\tnew Pair<>(4.4, \"quattro\")\n\t);\n\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.helpers = new EventSequenceProducerHelpersImpl();\n\t}\n\t\n\[email protected]\n\tpublic void testFromIterator() {\n\t\tfinal var producer = this.helpers.fromIterator(EVENTS.iterator());\n\t\t// produces the 4 elements of EVENTS, and then fails in trying to produce the fifth\n\t\tassertEquals(new Pair<>(1.1, \"uno\"),producer.getNext());\n\t\tassertEquals(new Pair<>(2.2, \"due\"),producer.getNext());\n\t\tassertEquals(new Pair<>(3.3, \"tre\"),producer.getNext());\n\t\tassertEquals(new Pair<>(4.4, \"quattro\"),producer.getNext());\n\t\tassertThrows(NoSuchElementException.class, ()->producer.getNext());\n\t}\n\t\n\[email protected]\n\tpublic void testWindow() {\n\t\tvar producer = this.helpers.fromIterator(EVENTS.iterator());\n\t\t// the window [2.0,4.0] produces only the events \"due\" and \"tre\"\n\t\tassertEquals(List.of(\"due\", \"tre\"), this.helpers.window(producer, 2.0, 4.0));\n\t\tproducer = this.helpers.fromIterator(EVENTS.iterator());\n\t\t// the window [1.0,4.0] produces only the events \"uno\",\"due\" and \"tre\"\n\t\tassertEquals(List.of(\"uno\", \"due\", \"tre\"), this.helpers.window(producer, 1.0, 4.0));\n\t\tproducer = this.helpers.fromIterator(EVENTS.iterator());\n\t\t// the window [1.5,2.0] produces nothing\n\t\tassertEquals(List.of(), this.helpers.window(producer, 1.5, 2.0));\n\t}\n\t\n\[email protected]\n\tpublic void testAsIterable() {\n\t\tfinal var producer = this.helpers.fromIterator(EVENTS.iterator());\n\t\tfinal var iterable = this.helpers.asEventContentIterable(producer);\n\t\t// the iterable obtained generates an iterator that behaves by producing only the 4 events\n\t\tfinal var iterator = iterable.iterator();\n\t\tassertTrue(iterator.hasNext());\n\t\tassertEquals(\"uno\", iterator.next());\n\t\tassertTrue(iterator.hasNext());\n\t\tassertEquals(\"due\", iterator.next());\n\t\tassertTrue(iterator.hasNext());\n\t\tassertEquals(\"tre\", iterator.next());\n\t\tassertTrue(iterator.hasNext());\n\t\tassertEquals(\"quattro\", iterator.next());\n\t\tassertFalse(iterator.hasNext());\n\t}\n\t\n\[email protected]\n\tpublic void testNextAt() {\n\t\tvar producer = this.helpers.fromIterator(EVENTS.iterator());\n\t\t// the event after time 2.0 is (2.2, \"due\")\n\t\tassertEquals(Optional.of(new Pair<>(2.2, \"due\")), this.helpers.nextAt(producer, 2.0));\n\t\tproducer = this.helpers.fromIterator(EVENTS.iterator());\n\t\t// the event after time 4.0 is (4.4, \"quattro\")\n\t\tassertEquals(Optional.of(new Pair<>(4.4, \"quattro\")), this.helpers.nextAt(producer, 4.0));\n\t\tproducer = this.helpers.fromIterator(EVENTS.iterator());\n\t\t// the event after time 5.0 does not exist\n\t\tassertEquals(Optional.empty(), this.helpers.nextAt(producer, 5.0));\n\t}\n\t\n\[email protected]\n\tpublic void optionalTestFilter1() {\n\t\tvar producer = this.helpers.fromIterator(EVENTS.iterator());\n\t\tvar out = this.helpers.filter(producer, s -> s.length()==3);\n\t\t// a producer of only three events remains by filtering those with content of length 3\n\t\tassertEquals(new Pair<>(1.1, \"uno\"),out.getNext());\n\t\tassertEquals(new Pair<>(2.2, \"due\"),out.getNext());\n\t\tassertEquals(new Pair<>(3.3, \"tre\"),out.getNext());\n\t\tassertThrows(NoSuchElementException.class, ()->out.getNext());\t\n\t}\n\t\n\[email protected]\n\tpublic void optionalTestFilter2() {\n\t\tvar producer = this.helpers.fromIterator(EVENTS.iterator());\n\t\tvar out = this.helpers.filter(producer, s -> s.length()==4);\n\t\t// an empty producer remains by filtering those with content of length 4\n\t\tassertThrows(NoSuchElementException.class, ()->out.getNext());\t\n\t}\n}", "filename": "Test.java" }
2022
a04
[ { "content": "package a04.sol1;\n\n\npublic interface BankAccount {\n\n \n int getBalance();\n\n \n void deposit(int amount);\n\n \n boolean withdraw(int amount);\n \n}", "filename": "BankAccount.java" }, { "content": "package a04.sol1;\n\nimport java.util.function.BiPredicate;\nimport java.util.function.Predicate;\nimport java.util.function.UnaryOperator;\n\n\npublic interface BankAccountFactory {\n\n \n BankAccount createBasic();\n\n \n BankAccount createWithFee(UnaryOperator<Integer> feeFunction);\n\n \n BankAccount createWithCredit(Predicate<Integer> allowedCredit, UnaryOperator<Integer> rateFunction);\n\n \n BankAccount createWithBlock(BiPredicate<Integer,Integer> blockingPolicy);\n \n \n BankAccount createWithFeeAndCredit(UnaryOperator<Integer> feeFunction, Predicate<Integer> allowedCredit, UnaryOperator<Integer> rateFunction);\n}", "filename": "BankAccountFactory.java" }, { "content": "package a04.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 a04.sol1;\n\nimport java.util.function.BiPredicate;\nimport java.util.function.Predicate;\nimport java.util.function.UnaryOperator;\n\npublic class BankAccountFactoryImpl implements BankAccountFactory {\n\n private static abstract class AbstractBankAccount implements BankAccount {\n protected abstract void setBalance(int amount);\n }\n\n private static class BankAccountDecorator extends AbstractBankAccount {\n private final AbstractBankAccount base;\n public BankAccountDecorator(AbstractBankAccount base){\n this.base = base;\n }\n public int getBalance() {\n return base.getBalance();\n }\n public void deposit(int amount) {\n base.deposit(amount);\n }\n public boolean withdraw(int amount) {\n return base.withdraw(amount);\n }\n \n protected void setBalance(int amount) {\n base.setBalance(amount);\n }\n }\n\n @Override\n public BankAccount createBasic() {\n return refinedCreateBasic();\n }\n\n private AbstractBankAccount refinedCreateBasic() {\n return new AbstractBankAccount() {\n\n private int balance = 0;\n\n @Override\n public int getBalance() {\n return this.balance;\n }\n\n @Override\n protected void setBalance(int amount){\n this.balance = amount;\n }\n\n @Override\n public void deposit(int amount) {\n this.balance = this.balance + amount;\n }\n\n @Override\n public boolean withdraw(int amount) {\n if (this.balance < amount){\n return false;\n }\n this.balance = this.balance - amount;\n return true;\n }\n };\n }\n\n @Override\n public BankAccount createWithFee(UnaryOperator<Integer> feeFunction) {\n return refinedCreateWithFee(feeFunction, refinedCreateBasic());\n }\n\n private AbstractBankAccount refinedCreateWithFee(UnaryOperator<Integer> feeFunction, AbstractBankAccount base) {\n return new BankAccountDecorator(base){\n @Override\n public boolean withdraw(int amount){\n return super.withdraw(amount + feeFunction.apply(amount));\n }\n };\n }\n\n @Override\n public BankAccount createWithCredit(Predicate<Integer> allowedCredit, UnaryOperator<Integer> rateFunction){\n return refinedCreateWithCredit(allowedCredit, rateFunction);\n }\n\n public AbstractBankAccount refinedCreateWithCredit(Predicate<Integer> allowedCredit, UnaryOperator<Integer> rateFunction) {\n return new BankAccountDecorator(refinedCreateBasic()){\n @Override\n public boolean withdraw(int amount){\n if (super.withdraw(amount)){\n return true;\n }\n final var credit = amount - this.getBalance();\n if (allowedCredit.test(credit)){\n setBalance(-credit-rateFunction.apply(-credit));\n return true;\n }\n return false;\n }\n };\n }\n\n @Override\n public BankAccount createWithBlock(BiPredicate<Integer, Integer> blockingPolicy) {\n return new BankAccountDecorator(refinedCreateBasic()){\n private boolean blocked = false;\n\n @Override\n public boolean withdraw(int amount){\n if (blocked) {\n return false;\n }\n if (blockingPolicy.test(amount, super.getBalance())){\n blocked = true;\n return false;\n }\n return super.withdraw(amount);\n }\n };\n }\n\n @Override\n public BankAccount createWithFeeAndCredit(UnaryOperator<Integer> feeFunction, Predicate<Integer> allowedCredit,\n UnaryOperator<Integer> rateFunction) {\n return refinedCreateWithFee(feeFunction, refinedCreateWithCredit(allowedCredit, rateFunction));\n }\n\n \n}", "filename": "BankAccountFactoryImpl.java" } ]
{ "components": { "imports": "package a04.sol1;\n\nimport static org.junit.Assert.*;\n\n/**\n * See the documentation of the BankAccountFactory interface, which models\n * a factory for BankAccount, which in turn models a current account with a certain balance,\n * and the possibility of depositing money (deposit) and withdrawing (withdrawal): depending on the implementation\n * the withdrawal could be subject to taxes, blocks, or credit, or combinations of these.\n * \n * The comment to the provided interfaces, and the test methods below constitute the necessary \n * explanation of the problem.\n * \n * The following are considered optional for the purpose of being able to correct\n * the exercise, but still contribute to achieving the totality of the\n * score: \n * - implementation of the fifth factory method (i.e., choose to implement 4,\n * but considering the first testBasic() method as mandatory)\n * - quality elements such as code conciseness, use of patterns, removal of repetitions\n *\n * Remove the comment from the init method.\n * \n * Score indications:\n * - correctness of the mandatory part: 10 points\n * - correctness of the optional part: 4 points \n * - quality of the solution: 3 points\n * - programming bugs, or violation of basic Java programming rules, entail a reduction of the\n * overall score, even in case of bonus\n * - ATTENTION: do not attempt any approach to removing repetitions between the various factories may involve \n * a reduction of the score even in case of bonus (1-2 points)\n */", "private_init": "\tprivate BankAccountFactory factory;\n\n\[email protected]\n\tpublic void init() {\n\t\tthis.factory = new BankAccountFactoryImpl();\n\t}", "test_functions": [ "\[email protected]\n\tpublic void testBasic() {\n\t\tvar account = this.factory.createBasic();\n\t\t// what I withdraw, if available, is removed\n\t\tassertEquals(0, account.getBalance());\n\t\taccount.deposit(100);\n\t\taccount.deposit(30);\n\t\tassertEquals(130, account.getBalance());\n\t\tassertTrue(account.withdraw(40));\n\t\tassertEquals(90, account.getBalance());\n\t\tassertFalse(account.withdraw(200));\n\t\tassertEquals(90, account.getBalance());\n\t}", "\[email protected]\n\tpublic void testWithFee() {\n\t\tvar account = this.factory.createWithFee(amount -> amount > 35 ? 1 : 0);\n\t\t// what I withdraw, if available, is removed, taking an extra euro if I withdraw more than 35\n\t\tassertEquals(0, account.getBalance());\n\t\taccount.deposit(100);\n\t\taccount.deposit(30);\n\t\tassertEquals(130, account.getBalance());\n\t\tassertTrue(account.withdraw(40));\n\t\tassertEquals(89, account.getBalance()); // the fee is applied\n\t\tassertTrue(account.withdraw(20));\n\t\tassertEquals(69, account.getBalance()); // the fee is NOT applied\n\t\tassertFalse(account.withdraw(80));\n\t\tassertEquals(69, account.getBalance());\n\t}", "\[email protected]\n\tpublic void testWithCredit() {\n\t\tvar account = this.factory.createWithCredit(credit -> credit < 100, credit -> 10);\n\t\t// the account can go \"red\" up to 99 euros, but every operation that sends me red is taxed by 10 euros\n\t\tassertEquals(0, account.getBalance());\n\t\taccount.deposit(100);\n\t\taccount.deposit(30);\n\t\tassertEquals(130, account.getBalance());\n\t\tassertTrue(account.withdraw(60));\n\t\tassertEquals(70, account.getBalance()); \n\t\tassertFalse(account.withdraw(170)); // 100 of credit is too much!!\n\t\tassertEquals(70, account.getBalance()); \n\t\tassertTrue(account.withdraw(150)); // 80 of credit is ok, but it becomes 80+10!\n\t\tassertEquals(-90, account.getBalance()); \n\t\tassertFalse(account.withdraw(20)); // 110 of credit is too much!!\n\t\tassertEquals(-90, account.getBalance()); \n\t\tassertTrue(account.withdraw(9)); // 99 of credit is ok, but it becomes 99+10\n\t\tassertEquals(-109, account.getBalance()); \n\t}", "\[email protected]\n\tpublic void testWithBlock() {\n\t\tvar account = this.factory.createWithBlock((amount,balance) -> amount > balance);\n\t\t// if you try to withdraw more than what you have, the account is blocked and you can no longer withdraw anything\n\t\tassertEquals(0, account.getBalance());\n\t\taccount.deposit(100);\n\t\taccount.deposit(30);\n\t\tassertEquals(130, account.getBalance());\n\t\tassertTrue(account.withdraw(60));\n\t\tassertEquals(70, account.getBalance()); \n\t\tassertTrue(account.withdraw(30));\n\t\tassertEquals(40, account.getBalance()); \n\t\tassertFalse(account.withdraw(50)); // now it is blocked, from now on\n\t\tassertEquals(40, account.getBalance()); \n\t\tassertFalse(account.withdraw(10));\n\t\tassertEquals(40, account.getBalance()); \n\t\tassertFalse(account.withdraw(2));\n\t\tassertEquals(40, account.getBalance()); \n\t}", "\[email protected]\n\tpublic void testWithFeeAndCredit() {\n\t\tvar account = this.factory.createWithFeeAndCredit(amount -> 1, credit -> credit < 100, credit -> 10);\n\t\t// fixed fee 1 euro per withdrawal, credit up to max 100 euros excluded, and 10 euros fee when you go into the red\n\t\t// that is a combination of Fee and Credit\n\t\tassertEquals(0, account.getBalance());\n\t\taccount.deposit(100);\n\t\taccount.deposit(30);\n\t\tassertEquals(130, account.getBalance());\n\t\tassertTrue(account.withdraw(60));\n\t\tassertEquals(69, account.getBalance()); \n\t\tassertFalse(account.withdraw(170)); // 100 of credit is too much!!\n\t\tassertEquals(69, account.getBalance()); \n\t\tassertTrue(account.withdraw(150)); // 81 of credit is ok, but it becomes 81+11!\n\t\tassertEquals(-92, account.getBalance()); \n\t\tassertFalse(account.withdraw(20)); // 110 of credit is too much!!\n\t\tassertEquals(-92, account.getBalance()); \n\t\tassertTrue(account.withdraw(5)); // 92+5+1 of credit is ok, but it becomes 108\n\t\tassertEquals(-108, account.getBalance()); \n\t}" ] }, "content": "package a04.sol1;\n\nimport static org.junit.Assert.*;\n\n/**\n * See the documentation of the BankAccountFactory interface, which models\n * a factory for BankAccount, which in turn models a current account with a certain balance,\n * and the possibility of depositing money (deposit) and withdrawing (withdrawal): depending on the implementation\n * the withdrawal could be subject to taxes, blocks, or credit, or combinations of these.\n * \n * The comment to the provided interfaces, and the test methods below constitute the necessary \n * explanation of the problem.\n * \n * The following are considered optional for the purpose of being able to correct\n * the exercise, but still contribute to achieving the totality of the\n * score: \n * - implementation of the fifth factory method (i.e., choose to implement 4,\n * but considering the first testBasic() method as mandatory)\n * - quality elements such as code conciseness, use of patterns, removal of repetitions\n *\n * Remove the comment from the init method.\n * \n * Score indications:\n * - correctness of the mandatory part: 10 points\n * - correctness of the optional part: 4 points \n * - quality of the solution: 3 points\n * - programming bugs, or violation of basic Java programming rules, entail a reduction of the\n * overall score, even in case of bonus\n * - ATTENTION: do not attempt any approach to removing repetitions between the various factories may involve \n * a reduction of the score even in case of bonus (1-2 points)\n */\n\npublic class Test {\n\n\tprivate BankAccountFactory factory;\n\n\[email protected]\n\tpublic void init() {\n\t\tthis.factory = new BankAccountFactoryImpl();\n\t}\n\n\[email protected]\n\tpublic void testBasic() {\n\t\tvar account = this.factory.createBasic();\n\t\t// what I withdraw, if available, is removed\n\t\tassertEquals(0, account.getBalance());\n\t\taccount.deposit(100);\n\t\taccount.deposit(30);\n\t\tassertEquals(130, account.getBalance());\n\t\tassertTrue(account.withdraw(40));\n\t\tassertEquals(90, account.getBalance());\n\t\tassertFalse(account.withdraw(200));\n\t\tassertEquals(90, account.getBalance());\n\t}\n\n\[email protected]\n\tpublic void testWithFee() {\n\t\tvar account = this.factory.createWithFee(amount -> amount > 35 ? 1 : 0);\n\t\t// what I withdraw, if available, is removed, taking an extra euro if I withdraw more than 35\n\t\tassertEquals(0, account.getBalance());\n\t\taccount.deposit(100);\n\t\taccount.deposit(30);\n\t\tassertEquals(130, account.getBalance());\n\t\tassertTrue(account.withdraw(40));\n\t\tassertEquals(89, account.getBalance()); // the fee is applied\n\t\tassertTrue(account.withdraw(20));\n\t\tassertEquals(69, account.getBalance()); // the fee is NOT applied\n\t\tassertFalse(account.withdraw(80));\n\t\tassertEquals(69, account.getBalance());\n\t}\n\n\[email protected]\n\tpublic void testWithCredit() {\n\t\tvar account = this.factory.createWithCredit(credit -> credit < 100, credit -> 10);\n\t\t// the account can go \"red\" up to 99 euros, but every operation that sends me red is taxed by 10 euros\n\t\tassertEquals(0, account.getBalance());\n\t\taccount.deposit(100);\n\t\taccount.deposit(30);\n\t\tassertEquals(130, account.getBalance());\n\t\tassertTrue(account.withdraw(60));\n\t\tassertEquals(70, account.getBalance()); \n\t\tassertFalse(account.withdraw(170)); // 100 of credit is too much!!\n\t\tassertEquals(70, account.getBalance()); \n\t\tassertTrue(account.withdraw(150)); // 80 of credit is ok, but it becomes 80+10!\n\t\tassertEquals(-90, account.getBalance()); \n\t\tassertFalse(account.withdraw(20)); // 110 of credit is too much!!\n\t\tassertEquals(-90, account.getBalance()); \n\t\tassertTrue(account.withdraw(9)); // 99 of credit is ok, but it becomes 99+10\n\t\tassertEquals(-109, account.getBalance()); \n\t}\n\n\[email protected]\n\tpublic void testWithBlock() {\n\t\tvar account = this.factory.createWithBlock((amount,balance) -> amount > balance);\n\t\t// if you try to withdraw more than what you have, the account is blocked and you can no longer withdraw anything\n\t\tassertEquals(0, account.getBalance());\n\t\taccount.deposit(100);\n\t\taccount.deposit(30);\n\t\tassertEquals(130, account.getBalance());\n\t\tassertTrue(account.withdraw(60));\n\t\tassertEquals(70, account.getBalance()); \n\t\tassertTrue(account.withdraw(30));\n\t\tassertEquals(40, account.getBalance()); \n\t\tassertFalse(account.withdraw(50)); // now it is blocked, from now on\n\t\tassertEquals(40, account.getBalance()); \n\t\tassertFalse(account.withdraw(10));\n\t\tassertEquals(40, account.getBalance()); \n\t\tassertFalse(account.withdraw(2));\n\t\tassertEquals(40, account.getBalance()); \n\t}\n\n\[email protected]\n\tpublic void testWithFeeAndCredit() {\n\t\tvar account = this.factory.createWithFeeAndCredit(amount -> 1, credit -> credit < 100, credit -> 10);\n\t\t// fixed fee 1 euro per withdrawal, credit up to max 100 euros excluded, and 10 euros fee when you go into the red\n\t\t// that is a combination of Fee and Credit\n\t\tassertEquals(0, account.getBalance());\n\t\taccount.deposit(100);\n\t\taccount.deposit(30);\n\t\tassertEquals(130, account.getBalance());\n\t\tassertTrue(account.withdraw(60));\n\t\tassertEquals(69, account.getBalance()); \n\t\tassertFalse(account.withdraw(170)); // 100 of credit is too much!!\n\t\tassertEquals(69, account.getBalance()); \n\t\tassertTrue(account.withdraw(150)); // 81 of credit is ok, but it becomes 81+11!\n\t\tassertEquals(-92, account.getBalance()); \n\t\tassertFalse(account.withdraw(20)); // 110 of credit is too much!!\n\t\tassertEquals(-92, account.getBalance()); \n\t\tassertTrue(account.withdraw(5)); // 92+5+1 of credit is ok, but it becomes 108\n\t\tassertEquals(-108, account.getBalance()); \n\t}\n}", "filename": "Test.java" }
2022
a02b
[ { "content": "package a02b.sol1;\n\n\npublic interface Cursor<X>{\n\t\t\n\t\n\tX getElement(); \n\t\n\t\n\tboolean advance(); \n\n}", "filename": "Cursor.java" }, { "content": "package a02b.sol1;\n\nimport java.util.List;\nimport java.util.function.Consumer;\n\n\npublic interface CursorHelpers {\n\t\n\t\n\t<X> Cursor<X> fromNonEmptyList(List<X> list);\n\n\t\n\tCursor<Integer> naturals();\n\n\t\n\t<X> Cursor<X> take(Cursor<X> input, int max);\n\n\t\n\t<X> void forEach(Cursor<X> input, Consumer<X> consumer);\n\n\t\n\t<X> List<X> toList(Cursor<X> input, int max);\n\n}", "filename": "CursorHelpers.java" }, { "content": "package 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 a02b.sol1;\n\nimport java.util.ArrayList;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.function.Consumer;\nimport java.util.stream.Stream;\n\npublic class CursorHelpersImpl implements CursorHelpers {\n\n private <X> Cursor<X> fromNonEmptyIterator(Iterator<X> iterator) {\n return new Cursor<X>() {\n\n X element = iterator.next();\n\n @Override\n public X getElement() {\n return element;\n }\n\n @Override\n public boolean advance() {\n if (iterator.hasNext()){\n element = iterator.next();\n return true;\n }\n return false;\n }\n };\n }\n \n @Override\n public <X> Cursor<X> fromNonEmptyList(List<X> list) {\n return this.fromNonEmptyIterator(list.iterator());\n }\n\n @Override\n public Cursor<Integer> naturals() {\n return this.fromNonEmptyIterator(Stream.iterate(0, x->x+1).iterator());\n }\n\n\n @Override\n public <X> Cursor<X> take(Cursor<X> input, int max) {\n return new Cursor<>(){\n\n int count = 0;\n\n @Override\n public X getElement() {\n return input.getElement();\n }\n\n @Override\n public boolean advance() {\n if (count < max-1){\n count++;\n return input.advance();\n }\n return false;\n }\n };\n }\n\n @Override\n public <X> void forEach(Cursor<X> cursor, Consumer<X> consumer) {\n do {\n consumer.accept(cursor.getElement());\n } while (cursor.advance());\n }\n\n @Override\n public <X> List<X> toList(Cursor<X> cursor, int max) {\n var list = new ArrayList<X>();\n this.forEach(take(cursor, max), list::add);\n return list;\n }\n}", "filename": "CursorHelpersImpl.java" } ]
{ "components": { "imports": "package a02b.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;\n\n/**\n * Please consult the documentation of the CursorHelpers interface, which models\n * helpers (factories and transformers) for Cursor, which in turn models a cursor,\n * essentially equivalent to an iterator.\n * \n * The comments on the provided interfaces, and the test methods below constitute the necessary\n * explanation of the problem.\n * \n * The following are considered optional for the purpose of being able to correct\n * the exercise, but still contribute to achieving the totality of the\n * score:\n * - implementation of the fifth helper method (i.e., choose to implement 4 of them,\n * but considering the fromNonEmptyList method as mandatory)\n * - quality elements such as code conciseness, removal of repetitions, parsimonious use of memory\n *\n * Remove the comment from the init method.\n * \n * Scoring indications:\n * - correctness of the mandatory part: 10 points\n * - correctness of the optional part: 4 points\n * - quality of the solution: 3 points\n * - programming bugs, or violation of basic Java programming rules, involve deduction of the\n * overall score, even in case of bonus\n */", "private_init": "\tprivate CursorHelpers helpers;\n\n\[email protected]\n\tpublic void init() {\n\t\tthis.helpers = new CursorHelpersImpl();\n\t}", "test_functions": [ "\[email protected]\n\tpublic void testFromNonEmptyList() {\n\t\tvar cursor = this.helpers.fromNonEmptyList(List.of(10,20,30));\n\t\tassertEquals(10, cursor.getElement().intValue()); // 10 is the first element\n\t\tassertEquals(10, cursor.getElement().intValue()); // nothing has changed, still 10\n\t\tassertEquals(10, cursor.getElement().intValue());\n\t\tassertTrue(cursor.advance());\t\t\t\t // it is possible to advance\n\t\tassertEquals(20, cursor.getElement().intValue()); // 20 is the next element\n\t\tassertEquals(20, cursor.getElement().intValue());\n\t\tassertTrue(cursor.advance());\t\t\t\t\t // it is possible to advance\n\t\tassertEquals(30, cursor.getElement().intValue()); // 30 is the next element\n\t\tassertFalse(cursor.advance());\t\t\t\t\t // it is NOT possible to advance\n\t\tassertEquals(30, cursor.getElement().intValue()); // nothing has changed, still 30\n\t\tassertEquals(30, cursor.getElement().intValue());\n\t\tassertFalse(cursor.advance());\n\t}", "\[email protected]\n\tpublic void testNaturals() {\n\t\tvar cursor = this.helpers.naturals();\n\t\tassertEquals(0, cursor.getElement().intValue());\n\t\tassertTrue(cursor.advance());\t\t\t\t \n\t\tassertEquals(1, cursor.getElement().intValue()); \n\t\tassertEquals(1, cursor.getElement().intValue());\n\t\tassertTrue(cursor.advance());\t\t\t\t \n\t\tassertEquals(2, cursor.getElement().intValue()); \n\t\tassertEquals(2, cursor.getElement().intValue());\n\t\tassertTrue(cursor.advance());\t\t\t\t\t \n\t\tassertTrue(cursor.advance());\t\t\t\t\t \n\t\tassertTrue(cursor.advance());\t\t\t\t\t\n\t\tassertEquals(5, cursor.getElement().intValue()); \n\t\tfor (int i=0; i<100; i++){\n\t\t\tcursor.advance();\n\t\t}", "\[email protected]\n\tpublic void testTake() {\n\t\tvar cursor = this.helpers.take(this.helpers.fromNonEmptyList(List.of(\"a\",\"b\",\"c\",\"d\",\"e\")),4);\n\t\tassertEquals(\"a\", cursor.getElement());\n\t\tassertTrue(cursor.advance());\t\t\t\t \n\t\tassertEquals(\"b\", cursor.getElement());\n\t\tassertTrue(cursor.advance());\t\t\t\t \n\t\tassertEquals(\"c\", cursor.getElement());\n\t\tassertTrue(cursor.advance());\t\t\t\t \n\t\tassertEquals(\"d\", cursor.getElement());\n\t\tassertFalse(cursor.advance());\t\n\t\t\n\t\tcursor = this.helpers.take(this.helpers.fromNonEmptyList(List.of(\"a\",\"b\",\"c\",\"d\",\"e\")),10);\n\t\tassertEquals(\"a\", cursor.getElement());\n\t\tassertTrue(cursor.advance());\t\t\t\t \n\t\tassertEquals(\"b\", cursor.getElement());\n\t\tassertTrue(cursor.advance());\t\t\t\t \n\t\tassertEquals(\"c\", cursor.getElement());\n\t\tassertTrue(cursor.advance());\t\t\t\t \n\t\tassertEquals(\"d\", cursor.getElement());\n\t\tassertTrue(cursor.advance());\t\n\t\tassertEquals(\"e\", cursor.getElement());\n\t\tassertFalse(cursor.advance());\t\n\t}", "\[email protected]\n\tpublic void testForEach() {\n\t\tfinal StringBuilder stringBuilder = new StringBuilder();\n\t\tvar cursor = this.helpers.fromNonEmptyList(List.of(\"a\",\"b\",\"a\",\"d\",\"e\"));\n\t\t// for each element of cursor, append it to the stringbuilder\n\t\tthis.helpers.forEach(cursor, s -> stringBuilder.append(s));\n\n\t\t// in the end we find \"abade\"\n\t\tassertEquals(\"abade\", stringBuilder.toString());\n\t}", "\[email protected]\n\tpublic void testToList() {\n\t\tvar cursor = this.helpers.fromNonEmptyList(List.of(\"a\",\"b\",\"c\",\"d\",\"e\"));\n\t\t// list obtained from the first 3 elements of the cursor\n\t\tvar list = this.helpers.toList(cursor, 3);\n\t\tassertEquals(List.of(\"a\",\"b\",\"c\"), list);\n\t\t\n\t\tcursor = this.helpers.fromNonEmptyList(List.of(\"a\",\"b\",\"c\",\"d\",\"e\"));\n\t\t// list obtained from the first 7 elements of the cursor, which are too many, so take the 5 from the cursor\n\t\tlist = this.helpers.toList(cursor, 7);\n\t\tassertEquals(List.of(\"a\",\"b\",\"c\",\"d\",\"e\"), list);\n\t}" ] }, "content": "package a02b.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;\n\n/**\n * Please consult the documentation of the CursorHelpers interface, which models\n * helpers (factories and transformers) for Cursor, which in turn models a cursor,\n * essentially equivalent to an iterator.\n * \n * The comments on the provided interfaces, and the test methods below constitute the necessary\n * explanation of the problem.\n * \n * The following are considered optional for the purpose of being able to correct\n * the exercise, but still contribute to achieving the totality of the\n * score:\n * - implementation of the fifth helper method (i.e., choose to implement 4 of them,\n * but considering the fromNonEmptyList method as mandatory)\n * - quality elements such as code conciseness, removal of repetitions, parsimonious use of memory\n *\n * Remove the comment from the init method.\n * \n * Scoring indications:\n * - correctness of the mandatory part: 10 points\n * - correctness of the optional part: 4 points\n * - quality of the solution: 3 points\n * - programming bugs, or violation of basic Java programming rules, involve deduction of the\n * overall score, even in case of bonus\n */\n\npublic class Test {\n\n\tprivate CursorHelpers helpers;\n\n\[email protected]\n\tpublic void init() {\n\t\tthis.helpers = new CursorHelpersImpl();\n\t}\n\n\[email protected]\n\tpublic void testFromNonEmptyList() {\n\t\tvar cursor = this.helpers.fromNonEmptyList(List.of(10,20,30));\n\t\tassertEquals(10, cursor.getElement().intValue()); // 10 is the first element\n\t\tassertEquals(10, cursor.getElement().intValue()); // nothing has changed, still 10\n\t\tassertEquals(10, cursor.getElement().intValue());\n\t\tassertTrue(cursor.advance());\t\t\t\t // it is possible to advance\n\t\tassertEquals(20, cursor.getElement().intValue()); // 20 is the next element\n\t\tassertEquals(20, cursor.getElement().intValue());\n\t\tassertTrue(cursor.advance());\t\t\t\t\t // it is possible to advance\n\t\tassertEquals(30, cursor.getElement().intValue()); // 30 is the next element\n\t\tassertFalse(cursor.advance());\t\t\t\t\t // it is NOT possible to advance\n\t\tassertEquals(30, cursor.getElement().intValue()); // nothing has changed, still 30\n\t\tassertEquals(30, cursor.getElement().intValue());\n\t\tassertFalse(cursor.advance());\n\t}\n\n\[email protected]\n\tpublic void testNaturals() {\n\t\tvar cursor = this.helpers.naturals();\n\t\tassertEquals(0, cursor.getElement().intValue());\n\t\tassertTrue(cursor.advance());\t\t\t\t \n\t\tassertEquals(1, cursor.getElement().intValue()); \n\t\tassertEquals(1, cursor.getElement().intValue());\n\t\tassertTrue(cursor.advance());\t\t\t\t \n\t\tassertEquals(2, cursor.getElement().intValue()); \n\t\tassertEquals(2, cursor.getElement().intValue());\n\t\tassertTrue(cursor.advance());\t\t\t\t\t \n\t\tassertTrue(cursor.advance());\t\t\t\t\t \n\t\tassertTrue(cursor.advance());\t\t\t\t\t\n\t\tassertEquals(5, cursor.getElement().intValue()); \n\t\tfor (int i=0; i<100; i++){\n\t\t\tcursor.advance();\n\t\t}\n\t\tassertEquals(105, cursor.getElement().intValue()); \n\t}\n\n\[email protected]\n\tpublic void testTake() {\n\t\tvar cursor = this.helpers.take(this.helpers.fromNonEmptyList(List.of(\"a\",\"b\",\"c\",\"d\",\"e\")),4);\n\t\tassertEquals(\"a\", cursor.getElement());\n\t\tassertTrue(cursor.advance());\t\t\t\t \n\t\tassertEquals(\"b\", cursor.getElement());\n\t\tassertTrue(cursor.advance());\t\t\t\t \n\t\tassertEquals(\"c\", cursor.getElement());\n\t\tassertTrue(cursor.advance());\t\t\t\t \n\t\tassertEquals(\"d\", cursor.getElement());\n\t\tassertFalse(cursor.advance());\t\n\t\t\n\t\tcursor = this.helpers.take(this.helpers.fromNonEmptyList(List.of(\"a\",\"b\",\"c\",\"d\",\"e\")),10);\n\t\tassertEquals(\"a\", cursor.getElement());\n\t\tassertTrue(cursor.advance());\t\t\t\t \n\t\tassertEquals(\"b\", cursor.getElement());\n\t\tassertTrue(cursor.advance());\t\t\t\t \n\t\tassertEquals(\"c\", cursor.getElement());\n\t\tassertTrue(cursor.advance());\t\t\t\t \n\t\tassertEquals(\"d\", cursor.getElement());\n\t\tassertTrue(cursor.advance());\t\n\t\tassertEquals(\"e\", cursor.getElement());\n\t\tassertFalse(cursor.advance());\t\n\t}\n\n\[email protected]\n\tpublic void testForEach() {\n\t\tfinal StringBuilder stringBuilder = new StringBuilder();\n\t\tvar cursor = this.helpers.fromNonEmptyList(List.of(\"a\",\"b\",\"a\",\"d\",\"e\"));\n\t\t// for each element of cursor, append it to the stringbuilder\n\t\tthis.helpers.forEach(cursor, s -> stringBuilder.append(s));\n\n\t\t// in the end we find \"abade\"\n\t\tassertEquals(\"abade\", stringBuilder.toString());\n\t}\n\n\[email protected]\n\tpublic void testToList() {\n\t\tvar cursor = this.helpers.fromNonEmptyList(List.of(\"a\",\"b\",\"c\",\"d\",\"e\"));\n\t\t// list obtained from the first 3 elements of the cursor\n\t\tvar list = this.helpers.toList(cursor, 3);\n\t\tassertEquals(List.of(\"a\",\"b\",\"c\"), list);\n\t\t\n\t\tcursor = this.helpers.fromNonEmptyList(List.of(\"a\",\"b\",\"c\",\"d\",\"e\"));\n\t\t// list obtained from the first 7 elements of the cursor, which are too many, so take the 5 from the cursor\n\t\tlist = this.helpers.toList(cursor, 7);\n\t\tassertEquals(List.of(\"a\",\"b\",\"c\",\"d\",\"e\"), list);\n\t}\n\n}", "filename": "Test.java" }
2022
a01a
[ { "content": "package a01a.sol1;\n\nimport java.util.List;\nimport java.util.function.Function;\n\n\npublic interface SubsequenceCombinerFactory {\n\n\t\n\tSubsequenceCombiner<Integer,Integer> tripletsToSum();\n\t\n\t\n\t<X> SubsequenceCombiner<X,List<X>> tripletsToList();\n\t\n\t\n\tSubsequenceCombiner<Integer,Integer> countUntilZero();\n\n\t\n\t<X,Y> SubsequenceCombiner<X,Y> singleReplacer(Function<X,Y> function);\n\t\n\t\n\tSubsequenceCombiner<Integer,List<Integer>> cumulateToList(int threshold);\n\n}", "filename": "SubsequenceCombinerFactory.java" }, { "content": "package 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 a01a.sol1;\n\nimport java.util.List;\n\n\npublic interface SubsequenceCombiner<X,Y>{\n\t\t\n\t\n\tList<Y> combine(List<X> list);\n\n}", "filename": "SubsequenceCombiner.java" } ]
[ { "content": "package a01a.sol1;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.function.Function;\nimport java.util.function.Predicate;\n\npublic class SubsequenceCombinerFactoryImpl implements SubsequenceCombinerFactory {\n\n private <X,Y> SubsequenceCombiner<X,Y> generic(Predicate<List<X>> ready, Function<List<X>,Y> mapper){\n return new SubsequenceCombiner<X,Y>() {\n\n @Override\n public List<Y> combine(List<X> list) {\n final List<Y> outList = new ArrayList<>();\n final List<X> tempList = new ArrayList<>();\n for (final var x: list){\n tempList.add(x);\n if (ready.test(tempList)){\n outList.add(mapper.apply(tempList));\n tempList.clear();\n }\n }\n if (!tempList.isEmpty()){\n outList.add(mapper.apply(tempList));\n }\n return outList;\n }\n };\n } \n\n @Override\n public SubsequenceCombiner<Integer,Integer> tripletsToSum() {\n return generic(l -> l.size() == 3, l -> l.stream().mapToInt(i -> i).sum());\n }\n\n @Override\n public <X> SubsequenceCombiner<X,List<X>> tripletsToList() {\n return generic(l -> l.size() == 3, ArrayList::new);\n }\n \n @Override\n public SubsequenceCombiner<Integer, Integer> countUntilZero() {\n return generic(l -> !l.isEmpty() && l.get(l.size()-1) == 0, \n l -> l.get(l.size()-1) == 0 ? l.size() - 1 : l.size());\n }\n\n @Override\n public <X, Y> SubsequenceCombiner<X, Y> singleReplacer(Function<X, Y> function) {\n return generic(l -> l.size() == 1, l -> function.apply(l.get(0)));\n }\n\n @Override\n public SubsequenceCombiner<Integer, List<Integer>> cumulateToList(int threshold) {\n return generic(l -> l.stream().mapToInt(i -> i).sum() >= threshold, ArrayList::new);\n }\n\n}", "filename": "SubsequenceCombinerFactoryImpl.java" } ]
{ "components": { "imports": "package a01a.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;\n\n/**\n * Please consult the documentation of the SubsequenceCombinerFactory interface, which models\n * a factory for SubsequenceCombiner, which in turn models a transformer from lists to\n * lists, which works by breaking the input list into various pieces, obtaining an element\n * in output for each of them.\n *\n * The comment on the provided interfaces, and the test methods below constitute the necessary\n * explanation of the problem.\n *\n * The following are considered optional for the purpose of being able to correct\n * the exercise, but still contribute to achieving the totality of the\n * score:\n * - implementation of the fifth method of the factory (i.e., choose to implement 4, the fifth is optional)\n * - conciseness of the code and removal of all repetitions with any appropriate use of patterns\n *\n * Remove the comment from the init method.\n *\n * Scoring indications:\n * - correctness of the mandatory part: 10 points\n * - correctness of the optional part: 3 points\n * - quality of the solution (eliminating code repetitions): 4 points\n * - programming errors lead to a reduction in the overall score\n */", "private_init": "\tprivate SubsequenceCombinerFactory factory;\n\n\[email protected]\n\tpublic void init() {\n\t\tthis.factory = new SubsequenceCombinerFactoryImpl();\n\t}", "test_functions": [ "\[email protected]\n\tpublic void testTripletsToSum() {\n\t\tSubsequenceCombiner<Integer,Integer> sc = this.factory.tripletsToSum();\n\t\t// Triplets are isolated, and their sum is provided: a final part of 1 or 2 elements is still summed\n\t\tassertEquals(List.of(30,300,3000,30),\n\t\t\tsc.combine(List.of(10, 10, 10, 100, 100, 100, 1000, 1000, 1000, 10, 20))\n\t\t);\n\t\tassertEquals(List.of(18,300),\n\t\t\tsc.combine(List.of(5, 6, 7, 100, 100, 100))\n\t\t);\n\t}", "\[email protected]\n\tpublic void testTripletsToList() {\n\t\tSubsequenceCombiner<Integer,List<Integer>> sc = this.factory.tripletsToList();\n\t\t// As in the previous case, but form lists\n\t\tassertEquals(List.of(List.of(10,10,10), List.of(100,100,100), List.of(1000,1000,1000), List.of(10,20)),\n\t\t\tsc.combine(List.of(10, 10, 10, 100, 100, 100, 1000, 1000, 1000, 10, 20))\n\t\t);\n\t\tassertEquals(List.of(List.of(10,10,10), List.of(100,100,100)),\n\t\t\tsc.combine(List.of(10, 10, 10, 100, 100, 100))\n\t\t);\n\t}", "\[email protected]\n\tpublic void testCountUntilZero() {\n\t\tSubsequenceCombiner<Integer,Integer> sc = this.factory.countUntilZero();\n\t\t// Once a zero is found (or the end of the list), the number of elements so far is produced\n\t\tassertEquals(List.of(3,2,4,2),\n\t\t\tsc.combine(List.of(1,1,1,0,2,2,0,3,3,3,3,0,5,6))\n\t\t);\n\t\tassertEquals(List.of(3,2),\n\t\t\tsc.combine(List.of(10,10,10,0,2,3,0))\n\t\t);\n\t}", "\[email protected]\n\tpublic void testSingleReplacer(){\n\t\t// the combine in this case is like the map of the streams\n\t\tSubsequenceCombiner<String,String> sc = this.factory.singleReplacer(s -> s + s);\n\t\tassertEquals(List.of(\"aa\", \"bb\", \"cc\"),\n\t\t\tsc.combine(List.of(\"a\", \"b\", \"c\")));\n\t\tSubsequenceCombiner<String,Integer> sc2 = this.factory.singleReplacer(s -> s.length());\n\t\tassertEquals(List.of(1, 3, 2),\n\t\t\tsc2.combine(List.of(\"a\", \"bbb\", \"cc\")));\n\t}", "\[email protected]\n\tpublic void testCumulativeToList(){\n\t\tSubsequenceCombiner<Integer,List<Integer>> sc = this.factory.cumulateToList(100);\n\t\t// Threshold 100: as soon as the sum of the elements found becomes >=100 (or there is end of list)\n\t\t// the subsequence is given as output\n\t\tassertEquals(List.of(List.of(10,50,70), List.of(80,20), List.of(30,30,39,30), List.of(40)),\n\t\t\tsc.combine(List.of(10,50,70,80,20,30,30,39,30,40)));\n\t}" ] }, "content": "package a01a.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;\n\n/**\n * Please consult the documentation of the SubsequenceCombinerFactory interface, which models\n * a factory for SubsequenceCombiner, which in turn models a transformer from lists to\n * lists, which works by breaking the input list into various pieces, obtaining an element\n * in output for each of them.\n *\n * The comment on the provided interfaces, and the test methods below constitute the necessary\n * explanation of the problem.\n *\n * The following are considered optional for the purpose of being able to correct\n * the exercise, but still contribute to achieving the totality of the\n * score:\n * - implementation of the fifth method of the factory (i.e., choose to implement 4, the fifth is optional)\n * - conciseness of the code and removal of all repetitions with any appropriate use of patterns\n *\n * Remove the comment from the init method.\n *\n * Scoring indications:\n * - correctness of the mandatory part: 10 points\n * - correctness of the optional part: 3 points\n * - quality of the solution (eliminating code repetitions): 4 points\n * - programming errors lead to a reduction in the overall score\n */\n\npublic class Test {\n\n\tprivate SubsequenceCombinerFactory factory;\n\n\[email protected]\n\tpublic void init() {\n\t\tthis.factory = new SubsequenceCombinerFactoryImpl();\n\t}\n\n\[email protected]\n\tpublic void testTripletsToSum() {\n\t\tSubsequenceCombiner<Integer,Integer> sc = this.factory.tripletsToSum();\n\t\t// Triplets are isolated, and their sum is provided: a final part of 1 or 2 elements is still summed\n\t\tassertEquals(List.of(30,300,3000,30),\n\t\t\tsc.combine(List.of(10, 10, 10, 100, 100, 100, 1000, 1000, 1000, 10, 20))\n\t\t);\n\t\tassertEquals(List.of(18,300),\n\t\t\tsc.combine(List.of(5, 6, 7, 100, 100, 100))\n\t\t);\n\t}\n\n\[email protected]\n\tpublic void testTripletsToList() {\n\t\tSubsequenceCombiner<Integer,List<Integer>> sc = this.factory.tripletsToList();\n\t\t// As in the previous case, but form lists\n\t\tassertEquals(List.of(List.of(10,10,10), List.of(100,100,100), List.of(1000,1000,1000), List.of(10,20)),\n\t\t\tsc.combine(List.of(10, 10, 10, 100, 100, 100, 1000, 1000, 1000, 10, 20))\n\t\t);\n\t\tassertEquals(List.of(List.of(10,10,10), List.of(100,100,100)),\n\t\t\tsc.combine(List.of(10, 10, 10, 100, 100, 100))\n\t\t);\n\t}\n\n\[email protected]\n\tpublic void testCountUntilZero() {\n\t\tSubsequenceCombiner<Integer,Integer> sc = this.factory.countUntilZero();\n\t\t// Once a zero is found (or the end of the list), the number of elements so far is produced\n\t\tassertEquals(List.of(3,2,4,2),\n\t\t\tsc.combine(List.of(1,1,1,0,2,2,0,3,3,3,3,0,5,6))\n\t\t);\n\t\tassertEquals(List.of(3,2),\n\t\t\tsc.combine(List.of(10,10,10,0,2,3,0))\n\t\t);\n\t}\n\n\[email protected]\n\tpublic void testSingleReplacer(){\n\t\t// the combine in this case is like the map of the streams\n\t\tSubsequenceCombiner<String,String> sc = this.factory.singleReplacer(s -> s + s);\n\t\tassertEquals(List.of(\"aa\", \"bb\", \"cc\"),\n\t\t\tsc.combine(List.of(\"a\", \"b\", \"c\")));\n\t\tSubsequenceCombiner<String,Integer> sc2 = this.factory.singleReplacer(s -> s.length());\n\t\tassertEquals(List.of(1, 3, 2),\n\t\t\tsc2.combine(List.of(\"a\", \"bbb\", \"cc\")));\n\t}\n\n\[email protected]\n\tpublic void testCumulativeToList(){\n\t\tSubsequenceCombiner<Integer,List<Integer>> sc = this.factory.cumulateToList(100);\n\t\t// Threshold 100: as soon as the sum of the elements found becomes >=100 (or there is end of list)\n\t\t// the subsequence is given as output\n\t\tassertEquals(List.of(List.of(10,50,70), List.of(80,20), List.of(30,30,39,30), List.of(40)),\n\t\t\tsc.combine(List.of(10,50,70,80,20,30,30,39,30,40)));\n\t}\n}", "filename": "Test.java" }
2022
a02a
[ { "content": "package a02a.sol1;\n\nimport java.util.List;\n\n\npublic interface RecursiveIteratorHelpers {\n \n \n\t<X> RecursiveIterator<X> fromList(List<X> list);\n\n \n\t<X> List<X> toList(RecursiveIterator<X> input, int max);\n\n \n <X,Y> RecursiveIterator<Pair<X,Y>> zip(RecursiveIterator<X> first, RecursiveIterator<Y> second);\n\n \n <X> RecursiveIterator<Pair<X,Integer>> zipWithIndex(RecursiveIterator<X> iterator);\n\n \n <X> RecursiveIterator<X> alternate(RecursiveIterator<X> first, RecursiveIterator<X> second);\n}", "filename": "RecursiveIteratorHelpers.java" }, { "content": "package a02a.sol1;\n\n\npublic interface RecursiveIterator<X>{\n\t\t\n\t\n\tX getElement();\n\t\n\t\n\tRecursiveIterator<X> next();\n\n}", "filename": "RecursiveIterator.java" }, { "content": "package 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 a02a.sol1;\n\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.function.Supplier;\nimport java.util.function.UnaryOperator;\nimport java.util.stream.Collectors;\nimport java.util.stream.Stream;\n\npublic class RecursiveIteratorHelpersImpl implements RecursiveIteratorHelpers {\n\n private <X> RecursiveIterator<X> cons(X element, Supplier<RecursiveIterator<X>> next){\n return new RecursiveIterator<X>() {\n\n @Override\n public X getElement() {\n return element;\n }\n\n @Override\n public RecursiveIterator<X> next() {\n return next.get();\n }\n };\n }\n\n @Override\n public <X> RecursiveIterator<X> fromList(List<X> list) {\n return fromIterator(list.iterator());\n }\n\n private <X> RecursiveIterator<X> fromIterator(Iterator<X> iterator) {\n if (iterator.hasNext()) {\n return cons(iterator.next(), ()->fromIterator(iterator));\n }\n return null;\n }\n\n @Override\n public <X> List<X> toList(RecursiveIterator<X> iterator, int max) {\n return toStream(iterator,max).collect(Collectors.toList());\n }\n\n private <X> Stream<X> toStream(RecursiveIterator<X> iterator, int max) {\n if (max == 0 || iterator == null){\n return Stream.empty();\n }\n return Stream.concat(Stream.of(iterator.getElement()), toStream(iterator.next(), max-1));\n }\n\n \n private <X> RecursiveIterator<X> iterate(X first, UnaryOperator<X> next) {\n return cons(first, ()->iterate(next.apply(first), next));\n }\n\n @Override\n public <X, Y> RecursiveIterator<Pair<X, Y>> zip(RecursiveIterator<X> first, RecursiveIterator<Y> second) {\n if (first != null && second != null){\n return cons(new Pair<>(first.getElement(),second.getElement()), ()->zip(first.next(),second.next()));\n } \n return null;\n }\n\n @Override\n public <X> RecursiveIterator<Pair<X, Integer>> zipWithIndex(RecursiveIterator<X> iterator) {\n return zip(iterator,iterate(0,x->x+1));\n }\n\n @Override\n public <X> RecursiveIterator<X> alternate(RecursiveIterator<X> first, RecursiveIterator<X> second) {\n if (first != null) {\n return cons(first.getElement(), ()->alternate(second,first.next()));\n }\n return second;\n }\n}", "filename": "RecursiveIteratorHelpersImpl.java" } ]
{ "components": { "imports": "package a02a.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;\n\n/**\n * Please consult the documentation of the RecursiveIteratorHelpers interface, which models\n * helpers (factories and transformers) for RecursiveIterator, which in turn models an iterator,\n * i.e., an essentially equivalent variant of an iterator.\n * \n * The comments on the provided interfaces, and the test methods below constitute the necessary\n * explanation of the problem.\n * \n * The following are considered optional for the purpose of being able to correct\n * the exercise, but still contribute to achieving the totality of the\n * score:\n * - implementation of the fifth helper method (i.e., choosing to implement 4 of them,\n * but considering the fromList method as mandatory)\n * - quality elements such as code conciseness, removal of repetitions, parsimonious use of memory\n *\n * Remove the comment from the init method.\n * \n * Scoring indications:\n * - correctness of the mandatory part: 10 points\n * - correctness of the optional part: 4 points\n * - solution quality: 3 points\n * - programming bugs, or violation of basic Java programming rules, result in a deduction of the\n * overall score, even in case of bonus\n */", "private_init": "\tprivate RecursiveIteratorHelpers factory;\n\n\[email protected]\n\tpublic void init() {\n\t\tthis.factory = new RecursiveIteratorHelpersImpl();\n\t}", "test_functions": [ "\[email protected]\n\tpublic void testFromList() {\n\t\tvar rit = this.factory.fromList(List.of(10,20,30));\n\t\tassertEquals(10, rit.getElement().intValue()); // 10 is the first element\n\t\tassertEquals(10, rit.getElement().intValue()); // even in subsequent calls\n\t\tassertEquals(10, rit.getElement().intValue());\n\t\trit = rit.next();\t\t\t\t\t\t\t // the next iterator is obtained\n\t\tassertEquals(20, rit.getElement().intValue()); // 20 is the next element\n\t\tassertEquals(20, rit.getElement().intValue());\n\t\trit = rit.next();\t\t\t\t\t\t\t // the next iterator is obtained\n\t\tassertEquals(30, rit.getElement().intValue());\n\t\tassertEquals(30, rit.getElement().intValue());\n\t\tassertEquals(30, rit.getElement().intValue());\n\t\trit = rit.next();\n\t\tassertNull(rit);\t// iteration finished\n\n\t\tassertNull(this.factory.fromList(List.of())); // empty iteration\n\t}", "\[email protected]\n\tpublic void testToList() {\n\t\tvar rit = this.factory.fromList(List.of(10,20,30));\n\t\t// list obtained from the first 10 elements of the iterator, which are too many, so take the 3 from the iterator\n\t\tassertEquals(List.of(10,20,30), this.factory.toList(rit,10));\n\t\tvar rit2 = this.factory.fromList(List.of(10,20,30));\n\t\t// list obtained from the first 2 elements of the iterator\n\t\tassertEquals(List.of(10,20), this.factory.toList(rit2,2));\n\t}", "\[email protected]\n\tpublic void testZip() {\n\t\tvar rit = this.factory.fromList(List.of(10,20,30,40));\n\t\tvar rit2 = this.factory.fromList(List.of(\"a\",\"b\",\"c\"));\n\t\tvar ritZip = this.factory.zip(rit,rit2);\n\t\tassertEquals(new Pair<>(10,\"a\"), ritZip.getElement());\n\t\tritZip = ritZip.next();\n\t\tassertEquals(new Pair<>(20,\"b\"), ritZip.getElement());\n\t\tritZip = ritZip.next();\n\t\tassertEquals(new Pair<>(30,\"c\"), ritZip.getElement());\n\t\tritZip = ritZip.next();\n\t\t// note, there are no more than 3 elements...\n\t\tassertNull(ritZip);\n\t}", "\[email protected]\n\tpublic void testZipWithIndex() {\n\t\tvar rit = this.factory.fromList(List.of(10,20,30));\n\t\t// zip with the iterator that produces 0,1,2,3,4,...\n\t\tvar ritZip = this.factory.zipWithIndex(rit);\n\t\tassertEquals(new Pair<>(10,0), ritZip.getElement());\n\t\tritZip = ritZip.next();\n\t\tassertEquals(new Pair<>(20,1), ritZip.getElement());\n\t\tritZip = ritZip.next();\n\t\tassertEquals(new Pair<>(30,2), ritZip.getElement());\n\t\tritZip = ritZip.next();\n\t\tassertNull(ritZip);\n\t}", "\[email protected]\n\tpublic void testAlternate() {\n\t\tvar rit = this.factory.fromList(List.of(10,20));\n\t\tvar rit2 = this.factory.fromList(List.of(1,2,3,4));\n\t\tvar ritAlt = this.factory.alternate(rit,rit2);\n\t\tassertEquals(10, ritAlt.getElement().intValue());\n\t\tritAlt = ritAlt.next();\n\t\tassertEquals(1, ritAlt.getElement().intValue());\n\t\tritAlt = ritAlt.next();\n\t\tassertEquals(20, ritAlt.getElement().intValue());\n\t\tritAlt = ritAlt.next();\n\t\tassertEquals(2, ritAlt.getElement().intValue());\n\t\tritAlt = ritAlt.next();\n\t\t// the first iterator is finished, proceed with the second\n\t\tassertEquals(3, ritAlt.getElement().intValue());\n\t\tritAlt = ritAlt.next();\n\t\tassertEquals(4, ritAlt.getElement().intValue());\n\t\tritAlt = ritAlt.next();\n\t\tassertNull(ritAlt);\n\t}" ] }, "content": "package a02a.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;\n\n/**\n * Please consult the documentation of the RecursiveIteratorHelpers interface, which models\n * helpers (factories and transformers) for RecursiveIterator, which in turn models an iterator,\n * i.e., an essentially equivalent variant of an iterator.\n * \n * The comments on the provided interfaces, and the test methods below constitute the necessary\n * explanation of the problem.\n * \n * The following are considered optional for the purpose of being able to correct\n * the exercise, but still contribute to achieving the totality of the\n * score:\n * - implementation of the fifth helper method (i.e., choosing to implement 4 of them,\n * but considering the fromList method as mandatory)\n * - quality elements such as code conciseness, removal of repetitions, parsimonious use of memory\n *\n * Remove the comment from the init method.\n * \n * Scoring indications:\n * - correctness of the mandatory part: 10 points\n * - correctness of the optional part: 4 points\n * - solution quality: 3 points\n * - programming bugs, or violation of basic Java programming rules, result in a deduction of the\n * overall score, even in case of bonus\n */\n\npublic class Test {\n\n\tprivate RecursiveIteratorHelpers factory;\n\n\[email protected]\n\tpublic void init() {\n\t\tthis.factory = new RecursiveIteratorHelpersImpl();\n\t}\n\n\[email protected]\n\tpublic void testFromList() {\n\t\tvar rit = this.factory.fromList(List.of(10,20,30));\n\t\tassertEquals(10, rit.getElement().intValue()); // 10 is the first element\n\t\tassertEquals(10, rit.getElement().intValue()); // even in subsequent calls\n\t\tassertEquals(10, rit.getElement().intValue());\n\t\trit = rit.next();\t\t\t\t\t\t\t // the next iterator is obtained\n\t\tassertEquals(20, rit.getElement().intValue()); // 20 is the next element\n\t\tassertEquals(20, rit.getElement().intValue());\n\t\trit = rit.next();\t\t\t\t\t\t\t // the next iterator is obtained\n\t\tassertEquals(30, rit.getElement().intValue());\n\t\tassertEquals(30, rit.getElement().intValue());\n\t\tassertEquals(30, rit.getElement().intValue());\n\t\trit = rit.next();\n\t\tassertNull(rit);\t// iteration finished\n\n\t\tassertNull(this.factory.fromList(List.of())); // empty iteration\n\t}\n\n\[email protected]\n\tpublic void testToList() {\n\t\tvar rit = this.factory.fromList(List.of(10,20,30));\n\t\t// list obtained from the first 10 elements of the iterator, which are too many, so take the 3 from the iterator\n\t\tassertEquals(List.of(10,20,30), this.factory.toList(rit,10));\n\t\tvar rit2 = this.factory.fromList(List.of(10,20,30));\n\t\t// list obtained from the first 2 elements of the iterator\n\t\tassertEquals(List.of(10,20), this.factory.toList(rit2,2));\n\t}\n\n\[email protected]\n\tpublic void testZip() {\n\t\tvar rit = this.factory.fromList(List.of(10,20,30,40));\n\t\tvar rit2 = this.factory.fromList(List.of(\"a\",\"b\",\"c\"));\n\t\tvar ritZip = this.factory.zip(rit,rit2);\n\t\tassertEquals(new Pair<>(10,\"a\"), ritZip.getElement());\n\t\tritZip = ritZip.next();\n\t\tassertEquals(new Pair<>(20,\"b\"), ritZip.getElement());\n\t\tritZip = ritZip.next();\n\t\tassertEquals(new Pair<>(30,\"c\"), ritZip.getElement());\n\t\tritZip = ritZip.next();\n\t\t// note, there are no more than 3 elements...\n\t\tassertNull(ritZip);\n\t}\n\n\[email protected]\n\tpublic void testZipWithIndex() {\n\t\tvar rit = this.factory.fromList(List.of(10,20,30));\n\t\t// zip with the iterator that produces 0,1,2,3,4,...\n\t\tvar ritZip = this.factory.zipWithIndex(rit);\n\t\tassertEquals(new Pair<>(10,0), ritZip.getElement());\n\t\tritZip = ritZip.next();\n\t\tassertEquals(new Pair<>(20,1), ritZip.getElement());\n\t\tritZip = ritZip.next();\n\t\tassertEquals(new Pair<>(30,2), ritZip.getElement());\n\t\tritZip = ritZip.next();\n\t\tassertNull(ritZip);\n\t}\n\n\[email protected]\n\tpublic void testAlternate() {\n\t\tvar rit = this.factory.fromList(List.of(10,20));\n\t\tvar rit2 = this.factory.fromList(List.of(1,2,3,4));\n\t\tvar ritAlt = this.factory.alternate(rit,rit2);\n\t\tassertEquals(10, ritAlt.getElement().intValue());\n\t\tritAlt = ritAlt.next();\n\t\tassertEquals(1, ritAlt.getElement().intValue());\n\t\tritAlt = ritAlt.next();\n\t\tassertEquals(20, ritAlt.getElement().intValue());\n\t\tritAlt = ritAlt.next();\n\t\tassertEquals(2, ritAlt.getElement().intValue());\n\t\tritAlt = ritAlt.next();\n\t\t// the first iterator is finished, proceed with the second\n\t\tassertEquals(3, ritAlt.getElement().intValue());\n\t\tritAlt = ritAlt.next();\n\t\tassertEquals(4, ritAlt.getElement().intValue());\n\t\tritAlt = ritAlt.next();\n\t\tassertNull(ritAlt);\n\t}\n}", "filename": "Test.java" }
2022
a03b
[ { "content": "package a03b.sol1;\n\nimport java.util.Map;\nimport java.util.Optional;\nimport java.util.function.Supplier;\nimport java.util.function.UnaryOperator;\n\n\npublic interface LazyTreeFactory {\n\n \n <X> LazyTree<X> constantInfinite(X value);\n \n \n <X> LazyTree<X> fromMap(X root, Map<X,Pair<X,X>> map);\n\n \n <X> LazyTree<X> cons(Optional<X> root, Supplier<LazyTree<X>> leftSupp, Supplier<LazyTree<X>> rightSupp);\n\n \n <X> LazyTree<X> fromTwoIterations(X root, UnaryOperator<X> leftOp, UnaryOperator<X> rightOp);\n\n \n <X> LazyTree<X> fromTreeWithBound(LazyTree<X> tree, int bound);\n\n}", "filename": "LazyTreeFactory.java" }, { "content": "package a03b.sol1;\n\n\npublic interface LazyTree<X> {\n\n \n boolean hasRoot();\n\n \n X root();\n\n \n LazyTree<X> left();\n\n \n LazyTree<X> right();\n \n}", "filename": "LazyTree.java" }, { "content": "package a03b.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 a03b.sol1;\n\nimport java.util.Map;\nimport java.util.NoSuchElementException;\nimport java.util.Optional;\nimport java.util.function.Supplier;\nimport java.util.function.UnaryOperator;\n\npublic class LazyTreeFactoryImpl implements LazyTreeFactory {\n\n @Override\n public <X> LazyTree<X> cons(Optional<X> root, Supplier<LazyTree<X>> left, Supplier<LazyTree<X>> right) {\n return new LazyTree<X>() {\n\n @Override\n public boolean hasRoot() {\n return root.isPresent();\n }\n\n @Override\n public X root() {\n return root.get();\n }\n\n @Override\n public LazyTree<X> left() {\n if (!hasRoot()){\n throw new NoSuchElementException();\n }\n return left.get();\n }\n\n @Override\n public LazyTree<X> right() {\n if (!hasRoot()){\n throw new NoSuchElementException();\n }\n return right.get();\n }\n \n };\n }\n\n private <X> LazyTree<X> empty() {\n return cons(Optional.empty(),null,null);\n }\n\n @Override\n public <X> LazyTree<X> fromMap(X root, Map<X, Pair<X, X>> map) {\n var p = map.get(root);\n return this.cons(\n Optional.of(root), \n () -> p == null ? empty() : fromMap(p.getX(),map),\n () -> p == null ? empty() : fromMap(p.getY(),map));\n }\n\n @Override\n public <X> LazyTree<X> fromTwoIterations(X root, UnaryOperator<X> left, UnaryOperator<X> right) {\n return cons(Optional.of(root), \n () -> fromTwoIterations(left.apply(root), left, right),\n () -> fromTwoIterations(right.apply(root), left, right)\n );\n }\n\n @Override\n public <X> LazyTree<X> constantInfinite(X value) {\n return this.fromTwoIterations(value, v -> v, v -> v);\n }\n\n @Override\n public <X> LazyTree<X> fromTreeWithBound(LazyTree<X> tree, int bound) {\n if (bound == 0 || !tree.hasRoot()){\n return this.empty();\n }\n return cons(Optional.of(tree.root()), () -> fromTreeWithBound(tree.left(), bound - 1), () -> fromTreeWithBound(tree.right(),bound-1));\n } \n}", "filename": "LazyTreeFactoryImpl.java" } ]
{ "components": { "imports": "package a03b.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;\n\n/**\n * See the documentation of the LazyTreeFactory interface, which models\n * a factory for LazyTree, which in turn models a \"lazy\" binary tree, i.e.\n * where the left and right child of a node are calculated only when needed, if accessed,\n * and therefore can potentially be infinite.\n * \n * The comment to the provided interfaces, and the test methods below constitute the necessary \n * explanation of the problem.\n * \n * The following are considered optional for the purpose of being able to correct\n * the exercise, but still contribute to achieving the totality of the\n * score: \n * - implementation of the fifth factory method (i.e., choose to implement 4,\n * but considering the first method constantInfinite() as mandatory)\n * - quality elements such as code conciseness, removal of repetitions, parsimonious use of memory\n *\n * Remove the comment from the init method.\n * \n * Scoring indications:\n * - correctness of the mandatory part: 10 points\n * - correctness of the optional part: 4 points \n * - quality of the solution: 3 points\n * - programming bugs, or violation of basic Java programming rules, result in a reduction of the\n * overall score, even in the case of a bonus\n */", "private_init": "\tprivate LazyTreeFactory factory;\n\n\[email protected]\n\tpublic void init() {\n\t\tthis.factory = new LazyTreeFactoryImpl();\n\t}", "test_functions": [ "\[email protected]\n\tpublic void testConstant() {\n\t\t// an infinite tree of \"a\" everywhere\n\t\tvar tree = this.factory.constantInfinite(\"a\");\n\t\tassertEquals(\"a\", tree.root());\n\t\tassertEquals(\"a\", tree.left().root());\n\t\tassertEquals(\"a\", tree.left().left().root());\n\t\tassertEquals(\"a\", tree.left().left().left().root());\n\t\tassertEquals(\"a\", tree.left().right().root());\n\t\tassertEquals(\"a\", tree.left().right().right().root());\n\t\tassertEquals(\"a\", tree.right().root());\n\t\tassertEquals(\"a\", tree.right().left().root());\n\t\tassertEquals(\"a\", tree.right().right().root());\n\t\t// going as deep as you like, you always find an element\n\t\tassertTrue(tree.right().right().right().right().hasRoot());\n\t}", "\[email protected]\n\tpublic void testFromMap() {\n\t\t// a tree with root \"1\", left child \"2\", right child \"3\"\n\t\t// left child of \"2\" again \"1\", right child of \"2\" again \"2\"\n\t\t// to be treated as \"loops\"\n\t\t// \"4\" has no children\n\t\tvar tree = this.factory.fromMap(\"1\", Map.of(\n\t\t\t\"1\", new Pair<>(\"2\",\"3\"),\n\t\t\t\"2\", new Pair<>(\"1\",\"2\"),\n\t\t\t\"3\", new Pair<>(\"3\",\"4\")));\n\t\tassertEquals(\"1\", tree.root());\n\t\tassertEquals(\"2\", tree.left().root());\n\t\tassertEquals(\"1\", tree.left().left().root());\n\t\tassertEquals(\"2\", tree.left().left().left().root());\n\t\tassertEquals(\"2\", tree.left().right().root());\n\t\tassertEquals(\"2\", tree.left().right().right().root());\n\t\tassertEquals(\"3\", tree.right().root());\n\t\tassertEquals(\"3\", tree.right().left().root());\n\t\tassertEquals(\"4\", tree.right().right().root());\n\t\tassertTrue(tree.right().right().hasRoot());\n\t\tassertFalse(tree.right().right().left().hasRoot());\n\t\tassertFalse(tree.right().right().right().hasRoot());\n\t}", "\[email protected]\n\tpublic void testCons() {\n\t\t// subtree on the left: an infinite tree of \"a\"\n\t\tLazyTree<String> treeL = this.factory.constantInfinite(\"a\");\n\t\t// subtree on the right: an empty tree\n\t\tLazyTree<String> treeR = this.factory.cons(Optional.empty(), () -> null,() -> null);\n\t\t// tree with root \"b\" and the two subtrees above\n\t\tLazyTree<String> tree = this.factory.cons(Optional.of(\"b\"), ()->treeL, ()->treeR);\n\t\tassertEquals(\"b\", tree.root());\n\t\tassertEquals(\"a\", tree.left().root());\n\t\tassertFalse(tree.right().hasRoot());\n\t\tassertEquals(\"a\", tree.left().left().root());\n\t\tassertEquals(\"a\", tree.left().right().root());\n\t\tassertEquals(\"a\", tree.left().left().left().root());\n\t}", "\[email protected]\n\tpublic void testTwoIterations() {\n\t\t// an infinite tree with root 0, and where each node with value x has \n\t\t// x-1 on the left and x+1 on the right\n\t\tvar tree = this.factory.fromTwoIterations(0, x -> x-1, x-> x+1);\n\t\tassertEquals(0, tree.root().intValue());\n\t\tassertEquals(-1, tree.left().root().intValue());\n\t\tassertEquals(-2, tree.left().left().root().intValue());\n\t\tassertEquals(-3, tree.left().left().left().root().intValue());\n\t\tassertEquals(0, tree.left().right().root().intValue());\n\t\tassertEquals(1, tree.left().right().right().root().intValue());\n\t\tassertEquals(1, tree.right().root().intValue());\n\t\tassertEquals(0, tree.right().left().root().intValue());\n\t\tassertEquals(2, tree.right().right().root().intValue());\n\t\tassertTrue(tree.right().right().right().right().right().hasRoot());\n\t}", "\[email protected]\n\tpublic void testBound() {\n\t\t// from an infinite tree of \"a\", it is cut at depth 2\n\t\tvar tree = this.factory.fromTreeWithBound(factory.constantInfinite(\"a\"),2);\n\t\tassertEquals(\"a\", tree.root());\n\t\tassertEquals(\"a\", tree.left().root());\n\t\tassertEquals(\"a\", tree.right().root());\n\t\tassertFalse(tree.left().left().hasRoot());\n\t\tassertFalse(tree.left().right().hasRoot());\n\t\tassertFalse(tree.right().left().hasRoot());\n\t\tassertFalse(tree.right().right().hasRoot());\n\t}" ] }, "content": "package a03b.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;\n\n/**\n * See the documentation of the LazyTreeFactory interface, which models\n * a factory for LazyTree, which in turn models a \"lazy\" binary tree, i.e.\n * where the left and right child of a node are calculated only when needed, if accessed,\n * and therefore can potentially be infinite.\n * \n * The comment to the provided interfaces, and the test methods below constitute the necessary \n * explanation of the problem.\n * \n * The following are considered optional for the purpose of being able to correct\n * the exercise, but still contribute to achieving the totality of the\n * score: \n * - implementation of the fifth factory method (i.e., choose to implement 4,\n * but considering the first method constantInfinite() as mandatory)\n * - quality elements such as code conciseness, removal of repetitions, parsimonious use of memory\n *\n * Remove the comment from the init method.\n * \n * Scoring indications:\n * - correctness of the mandatory part: 10 points\n * - correctness of the optional part: 4 points \n * - quality of the solution: 3 points\n * - programming bugs, or violation of basic Java programming rules, result in a reduction of the\n * overall score, even in the case of a bonus\n */\n\npublic class Test {\n\n\tprivate LazyTreeFactory factory;\n\n\[email protected]\n\tpublic void init() {\n\t\tthis.factory = new LazyTreeFactoryImpl();\n\t}\n\n\[email protected]\n\tpublic void testConstant() {\n\t\t// an infinite tree of \"a\" everywhere\n\t\tvar tree = this.factory.constantInfinite(\"a\");\n\t\tassertEquals(\"a\", tree.root());\n\t\tassertEquals(\"a\", tree.left().root());\n\t\tassertEquals(\"a\", tree.left().left().root());\n\t\tassertEquals(\"a\", tree.left().left().left().root());\n\t\tassertEquals(\"a\", tree.left().right().root());\n\t\tassertEquals(\"a\", tree.left().right().right().root());\n\t\tassertEquals(\"a\", tree.right().root());\n\t\tassertEquals(\"a\", tree.right().left().root());\n\t\tassertEquals(\"a\", tree.right().right().root());\n\t\t// going as deep as you like, you always find an element\n\t\tassertTrue(tree.right().right().right().right().hasRoot());\n\t}\n\t\n\[email protected]\n\tpublic void testFromMap() {\n\t\t// a tree with root \"1\", left child \"2\", right child \"3\"\n\t\t// left child of \"2\" again \"1\", right child of \"2\" again \"2\"\n\t\t// to be treated as \"loops\"\n\t\t// \"4\" has no children\n\t\tvar tree = this.factory.fromMap(\"1\", Map.of(\n\t\t\t\"1\", new Pair<>(\"2\",\"3\"),\n\t\t\t\"2\", new Pair<>(\"1\",\"2\"),\n\t\t\t\"3\", new Pair<>(\"3\",\"4\")));\n\t\tassertEquals(\"1\", tree.root());\n\t\tassertEquals(\"2\", tree.left().root());\n\t\tassertEquals(\"1\", tree.left().left().root());\n\t\tassertEquals(\"2\", tree.left().left().left().root());\n\t\tassertEquals(\"2\", tree.left().right().root());\n\t\tassertEquals(\"2\", tree.left().right().right().root());\n\t\tassertEquals(\"3\", tree.right().root());\n\t\tassertEquals(\"3\", tree.right().left().root());\n\t\tassertEquals(\"4\", tree.right().right().root());\n\t\tassertTrue(tree.right().right().hasRoot());\n\t\tassertFalse(tree.right().right().left().hasRoot());\n\t\tassertFalse(tree.right().right().right().hasRoot());\n\t}\n\n\n\[email protected]\n\tpublic void testCons() {\n\t\t// subtree on the left: an infinite tree of \"a\"\n\t\tLazyTree<String> treeL = this.factory.constantInfinite(\"a\");\n\t\t// subtree on the right: an empty tree\n\t\tLazyTree<String> treeR = this.factory.cons(Optional.empty(), () -> null,() -> null);\n\t\t// tree with root \"b\" and the two subtrees above\n\t\tLazyTree<String> tree = this.factory.cons(Optional.of(\"b\"), ()->treeL, ()->treeR);\n\t\tassertEquals(\"b\", tree.root());\n\t\tassertEquals(\"a\", tree.left().root());\n\t\tassertFalse(tree.right().hasRoot());\n\t\tassertEquals(\"a\", tree.left().left().root());\n\t\tassertEquals(\"a\", tree.left().right().root());\n\t\tassertEquals(\"a\", tree.left().left().left().root());\n\t}\n\n\[email protected]\n\tpublic void testTwoIterations() {\n\t\t// an infinite tree with root 0, and where each node with value x has \n\t\t// x-1 on the left and x+1 on the right\n\t\tvar tree = this.factory.fromTwoIterations(0, x -> x-1, x-> x+1);\n\t\tassertEquals(0, tree.root().intValue());\n\t\tassertEquals(-1, tree.left().root().intValue());\n\t\tassertEquals(-2, tree.left().left().root().intValue());\n\t\tassertEquals(-3, tree.left().left().left().root().intValue());\n\t\tassertEquals(0, tree.left().right().root().intValue());\n\t\tassertEquals(1, tree.left().right().right().root().intValue());\n\t\tassertEquals(1, tree.right().root().intValue());\n\t\tassertEquals(0, tree.right().left().root().intValue());\n\t\tassertEquals(2, tree.right().right().root().intValue());\n\t\tassertTrue(tree.right().right().right().right().right().hasRoot());\n\t}\n\n\[email protected]\n\tpublic void testBound() {\n\t\t// from an infinite tree of \"a\", it is cut at depth 2\n\t\tvar tree = this.factory.fromTreeWithBound(factory.constantInfinite(\"a\"),2);\n\t\tassertEquals(\"a\", tree.root());\n\t\tassertEquals(\"a\", tree.left().root());\n\t\tassertEquals(\"a\", tree.right().root());\n\t\tassertFalse(tree.left().left().hasRoot());\n\t\tassertFalse(tree.left().right().hasRoot());\n\t\tassertFalse(tree.right().left().hasRoot());\n\t\tassertFalse(tree.right().right().hasRoot());\n\t}\n\n}", "filename": "Test.java" }
2022
a01b
[ { "content": "package a01b.sol1;\n\nimport java.util.List;\nimport java.util.function.Function;\n\n\npublic interface FlattenerFactory {\n\t\n\t\n\tFlattener<Integer,Integer> sumEach();\n\n\t\n\t<X> Flattener<X,X> flattenAll();\n\n\t\n\tFlattener<String, String> concatPairs();\n\n\t\n\t<I,O> Flattener<I,O> each(Function<List<I>,O> mapper);\n\n\t\n\tFlattener<Integer,Integer> sumVectors();\n}", "filename": "FlattenerFactory.java" }, { "content": "package a01b.sol1;\n\nimport java.util.List;\n\n\npublic interface Flattener<I,O>{\n\t\t\n\t\n\tList<O> flatten(List<List<I>> list);\n\n}", "filename": "Flattener.java" }, { "content": "package a01b.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 a01b.sol1;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.function.BiFunction;\nimport java.util.function.Function;\nimport java.util.function.Predicate;\nimport java.util.stream.Collectors;\nimport java.util.stream.IntStream;\nimport java.util.stream.Stream;\n\npublic class FlattenerFactoryImpl implements FlattenerFactory {\n\n private <I,O> Flattener<I,O> generic(BiFunction<List<O>, List<I>, List<O>> folder, Predicate<List<O>> toEmit){\n return new Flattener<I,O>() {\n\n @Override\n public List<O> flatten(List<List<I>> list) {\n final List<O> outList = new ArrayList<>();\n List<O> state = new ArrayList<>();\n for (var l: list){\n if (toEmit.test(state)){\n state = folder.apply(state,l);\n outList.addAll(state);\n state = new ArrayList<>();\n } else {\n state = folder.apply(state,l);\n }\n }\n outList.addAll(state);\n return outList;\n }\n \n };\n }\n\n private <X> List<X> append(List<X> list1, List<X> list2){\n return Stream.concat(list1.stream(), list2.stream()).collect(Collectors.toList());\n }\n\n private List<Integer> sumTwoVectors(List<Integer> list1, List<Integer> list2){\n return list1.isEmpty() ? list2 : IntStream.range(0, list1.size()).mapToObj(i -> list1.get(i) + list2.get(i)).collect(Collectors.toList());\n }\n \n\n @Override\n public <X, Y> Flattener<X, Y> each(Function<List<X>, Y> mapper) {\n return generic((s,l) -> List.of(mapper.apply(l)), s -> true);\n }\n\n\n @Override\n public Flattener<Integer,Integer> sumEach() {\n return each(l -> l.stream().mapToInt(i->i).sum());\n }\n\n @Override\n public <X> Flattener<X, X> flattenAll() {\n return generic(this::append, s -> false);\n }\n\n @Override\n public Flattener<String, String> concatPairs() {\n return generic((s,l) -> List.of(append(s,l).stream().reduce(\"\",String::concat)), s -> !s.isEmpty());\n }\n\n @Override\n public Flattener<Integer, Integer> sumVectors() {\n return generic(this::sumTwoVectors, s -> false);\n }\n\n}", "filename": "FlattenerFactoryImpl.java" } ]
{ "components": { "imports": "package a01b.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;\nimport java.util.stream.Collectors;\n\n/**\n * Consult the documentation of the FlattenerFactory interface, which models\n * a factory for Flattener, which in turn models a transformer from lists of lists to\n * lists, which works by recombining the inner lists in input producing (at the end, or gradually)\n * output elements.\n * \n * The comment to the provided interfaces, and the test methods below constitute the necessary\n * explanation of the problem.\n * \n * The following are considered optional for the purpose of being able to correct the exercise, but still contribute\n * to achieving the totality of the score:\n * - implementation of the fifth method of the factory (i.e., choose to implement 4, the fifth is optional)\n * - conciseness of the code and removal of all repetitions with eventual appropriate use of patterns\n *\n * Remove the comment from the init method.\n * \n * Scoring indications:\n * - correctness of the mandatory part: 10 points\n * - correctness of the optional part: 3 points\n * - quality of the solution (eliminating code repetitions): 4 points\n * - programming errors lead to a reduction of the overall score\n */", "private_init": "\tprivate FlattenerFactory factory;\n\n\[email protected]\n\tpublic void init() {\n\t\tthis.factory = new FlattenerFactoryImpl();\n\t}", "test_functions": [ "\[email protected]\n\tpublic void testSumEach() {\n\t\tFlattener<Integer,Integer> f = this.factory.sumEach();\n\t\t// each inner list produces as output the sum of its elements, i.e. 1+2+3+4, 0, 20, 10+10+10, 0\n\t\tassertEquals(List.of(10, 0, 20, 30, 0),\n\t\t\tf.flatten(List.of(List.of(1,2,3,4), List.of(), List.of(20), List.of(10,10,10), List.of(0))));\n\t}", "\[email protected]\n\tpublic void testFlattenAll() {\n\t\tFlattener<String,String> f = this.factory.flattenAll();\n\t\t// all the inner lists are appended to each other producing the list in output\n\t\tassertEquals(List.of(\"a\",\"b\",\"c\",\"d\",\"e\"),\n\t\t\tf.flatten(List.of(List.of(\"a\",\"b\"), List.of(), List.of(\"c\"), List.of(\"d\",\"e\"))));\n\t}", "\[email protected]\n\tpublic void testConcatPairs() {\n\t\tFlattener<String,String> f = this.factory.concatPairs();\n\t\t// the inner lists are taken in pairs: for each pair all their strings are joined\n\t\t// if there is a final inner list, it is treated alone\n\t\tassertEquals(List.of(\"abc\",\"cdef\",\"gh\"),\n\t\t\tf.flatten(List.of(List.of(\"a\",\"b\"), List.of(\"c\"), List.of(\"c\",\"d\",\"e\"),List.of(\"f\"),List.of(\"g\",\"h\"))));\n\t\tassertEquals(List.of(\"abc\",\"cdef\"),\n\t\t\tf.flatten(List.of(List.of(\"a\",\"b\"), List.of(\"c\"), List.of(\"c\",\"d\"),List.of(\"e\", \"f\"))));\n\t}", "\[email protected]\n\tpublic void testEach() {\n\t\tFlattener<String,String> f = this.factory.each(l -> l.stream().collect(Collectors.joining()));\n\t\t// each inner list produces the concatenation of its elements -- which are strings\n\t\tassertEquals(List.of(\"ab\",\"c\",\"cde\",\"f\",\"g\"),\n\t\t\tf.flatten(List.of(List.of(\"a\",\"b\"), List.of(\"c\"), List.of(\"c\",\"d\",\"e\"),List.of(\"f\"),List.of(\"g\"))));\n\t\tFlattener<String,Integer> f2 = this.factory.each(l -> l.size());\n\t\t// each inner list produces its length\n\t\tassertEquals(List.of(2,1,3,1,1),\n\t\t\tf2.flatten(List.of(List.of(\"a\",\"b\"), List.of(\"c\"), List.of(\"c\",\"d\",\"e\"),List.of(\"f\"),List.of(\"g\"))));\n\t}", "\[email protected]\n\tpublic void testSumVectors() {\n\t\tFlattener<Integer,Integer> f = this.factory.sumVectors();\n\t\t// the output is produced at the end of the iteration: the inner lists are considered as vectors (in the algebraic sense) to be summed\n\t\tassertEquals(List.of(1111, 2222, 3333),\n\t\t\tf.flatten(List.of(List.of(1,2,3), List.of(10,20,30), List.of(100,200,300), List.of(1000,2000,3000))));\n\t}" ] }, "content": "package a01b.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;\nimport java.util.stream.Collectors;\n\n/**\n * Consult the documentation of the FlattenerFactory interface, which models\n * a factory for Flattener, which in turn models a transformer from lists of lists to\n * lists, which works by recombining the inner lists in input producing (at the end, or gradually)\n * output elements.\n * \n * The comment to the provided interfaces, and the test methods below constitute the necessary\n * explanation of the problem.\n * \n * The following are considered optional for the purpose of being able to correct the exercise, but still contribute\n * to achieving the totality of the score:\n * - implementation of the fifth method of the factory (i.e., choose to implement 4, the fifth is optional)\n * - conciseness of the code and removal of all repetitions with eventual appropriate use of patterns\n *\n * Remove the comment from the init method.\n * \n * Scoring indications:\n * - correctness of the mandatory part: 10 points\n * - correctness of the optional part: 3 points\n * - quality of the solution (eliminating code repetitions): 4 points\n * - programming errors lead to a reduction of the overall score\n */\n\npublic class Test {\n\n\tprivate FlattenerFactory factory;\n\n\[email protected]\n\tpublic void init() {\n\t\tthis.factory = new FlattenerFactoryImpl();\n\t}\n\n\[email protected]\n\tpublic void testSumEach() {\n\t\tFlattener<Integer,Integer> f = this.factory.sumEach();\n\t\t// each inner list produces as output the sum of its elements, i.e. 1+2+3+4, 0, 20, 10+10+10, 0\n\t\tassertEquals(List.of(10, 0, 20, 30, 0),\n\t\t\tf.flatten(List.of(List.of(1,2,3,4), List.of(), List.of(20), List.of(10,10,10), List.of(0))));\n\t}\n\n\[email protected]\n\tpublic void testFlattenAll() {\n\t\tFlattener<String,String> f = this.factory.flattenAll();\n\t\t// all the inner lists are appended to each other producing the list in output\n\t\tassertEquals(List.of(\"a\",\"b\",\"c\",\"d\",\"e\"),\n\t\t\tf.flatten(List.of(List.of(\"a\",\"b\"), List.of(), List.of(\"c\"), List.of(\"d\",\"e\"))));\n\t}\n\n\[email protected]\n\tpublic void testConcatPairs() {\n\t\tFlattener<String,String> f = this.factory.concatPairs();\n\t\t// the inner lists are taken in pairs: for each pair all their strings are joined\n\t\t// if there is a final inner list, it is treated alone\n\t\tassertEquals(List.of(\"abc\",\"cdef\",\"gh\"),\n\t\t\tf.flatten(List.of(List.of(\"a\",\"b\"), List.of(\"c\"), List.of(\"c\",\"d\",\"e\"),List.of(\"f\"),List.of(\"g\",\"h\"))));\n\t\tassertEquals(List.of(\"abc\",\"cdef\"),\n\t\t\tf.flatten(List.of(List.of(\"a\",\"b\"), List.of(\"c\"), List.of(\"c\",\"d\"),List.of(\"e\", \"f\"))));\n\t}\n\n\[email protected]\n\tpublic void testEach() {\n\t\tFlattener<String,String> f = this.factory.each(l -> l.stream().collect(Collectors.joining()));\n\t\t// each inner list produces the concatenation of its elements -- which are strings\n\t\tassertEquals(List.of(\"ab\",\"c\",\"cde\",\"f\",\"g\"),\n\t\t\tf.flatten(List.of(List.of(\"a\",\"b\"), List.of(\"c\"), List.of(\"c\",\"d\",\"e\"),List.of(\"f\"),List.of(\"g\"))));\n\t\tFlattener<String,Integer> f2 = this.factory.each(l -> l.size());\n\t\t// each inner list produces its length\n\t\tassertEquals(List.of(2,1,3,1,1),\n\t\t\tf2.flatten(List.of(List.of(\"a\",\"b\"), List.of(\"c\"), List.of(\"c\",\"d\",\"e\"),List.of(\"f\"),List.of(\"g\"))));\n\t}\n\n\[email protected]\n\tpublic void testSumVectors() {\n\t\tFlattener<Integer,Integer> f = this.factory.sumVectors();\n\t\t// the output is produced at the end of the iteration: the inner lists are considered as vectors (in the algebraic sense) to be summed\n\t\tassertEquals(List.of(1111, 2222, 3333),\n\t\t\tf.flatten(List.of(List.of(1,2,3), List.of(10,20,30), List.of(100,200,300), List.of(1000,2000,3000))));\n\t}\n}", "filename": "Test.java" }
2023
a01d
[ { "content": "package a01d.sol1;\n\npublic interface TimetableFactory {\n \n \n Timetable empty();\n}", "filename": "TimetableFactory.java" }, { "content": "package a01d.sol1;\n\nimport java.util.*;\n\n\npublic interface Timetable {\n\n public static enum Day { MON, TUE, WED, THU, FRI }\n\n\n \n Set<String> rooms();\n\n \n Set<String> courses();\n\n \n List<Integer> hours();\n\n \n Timetable addBooking(String room, String course, Day day, int hour, int duration);\n\n \n Optional<Integer> findPlaceForBooking(String room, Day day, int duration);\n\n \n Map<Integer, String> getDayAtRoom(String room, Day day); \n\n \n Optional<Pair<String, String>> getDayAndHour(Day day, int hour); \n\n \n Map<Day, Map<Integer, String>> getCourseTable(String course); \n\n}", "filename": "Timetable.java" }, { "content": "package a01d.sol1;\n\nimport java.util.Objects;\n\n\n\npublic class Pair<E1,E2> {\n\t\n\tprivate final E1 e1;\n\tprivate final E2 e2;\n\t\n\tpublic Pair(E1 x, E2 y) {\n\t\tsuper();\n\t\tthis.e1 = x;\n\t\tthis.e2 = y;\n\t}\n\n\tpublic E1 get1() {\n\t\treturn e1;\n\t}\n\n\tpublic E2 get2() {\n\t\treturn e2;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Objects.hash(e1, e2);\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj) {\n\t\t\treturn true;\n\t\t}\n\t\tif (obj == null) {\n\t\t\treturn false;\n\t\t}\n\t\tif (getClass() != obj.getClass()) {\n\t\t\treturn false;\n\t\t}\n\t\tPair other = (Pair) obj;\n\t\treturn Objects.equals(e1, other.e1) && Objects.equals(e2, other.e2);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Pair [e1=\" + e1 + \", e2=\" + e2 + \"]\";\n\t}\n\t\n\t\n\n}", "filename": "Pair.java" } ]
[ { "content": "package a01d.sol1;\n\nimport java.util.*;\nimport java.util.stream.*;\n\npublic class TimetableFactoryImpl implements TimetableFactory {\n\n // An implementation of a Booking as an immutable class with a room, course, day and (single) hour\n // Since it is immutable, we use a record, which automatically gives fields, getters, constructors, hashcode, equals, toString.\n private static record BookingSlot(String room, String course, Timetable.Day day, int hour){}\n\n // An implementation of a Timetable as an immutable set of Bookings\n private static record TimetableImpl(Set<BookingSlot> data) implements Timetable {\n\n @Override\n public Set<String> rooms() {\n return data.stream().map(BookingSlot::room).collect(Collectors.toSet());\n }\n\n @Override\n public Set<String> courses() {\n return data.stream().map(BookingSlot::course).collect(Collectors.toSet());\n }\n\n @Override\n public List<Integer> hours() {\n return data.stream().map(BookingSlot::hour).distinct().sorted().collect(Collectors.toList());\n }\n\n @Override\n public Timetable addBooking(String room, String course, Day day, int hour, int duration) {\n return new TimetableImpl(Stream.concat(\n Stream.iterate(hour, i->i+1).limit(duration).map(h -> new BookingSlot(room, course, day, h)),\n data.stream()\n ).collect(Collectors.toSet()));\n }\n\n @Override\n public Optional<Integer> findPlaceForBooking(String room, Day day, int duration){\n return this.hours()\n .stream()\n .filter(h -> Stream.iterate(h, i->i+1)\n .limit(duration)\n .allMatch(hh -> data.stream().noneMatch(b -> b.room.equals(room) && b.hour == hh)))\n .findFirst();\n }\n\n @Override\n public Map<Integer, String> getDayAtRoom(String room, Day day) {\n return data.stream()\n .filter(b -> b.room.equals(room))\n .filter(b -> b.day == day)\n .collect(Collectors.toMap(BookingSlot::hour, BookingSlot::course));\n }\n\n @Override\n public Optional<Pair<String, String>> getDayAndHour(Day day, int hour) {\n return data.stream()\n .filter(b -> b.day == day)\n .filter(b -> b.hour == hour)\n .map(b -> new Pair<>(b.course, b.room))\n .findAny();\n }\n\n @Override\n public Map<Day, Map<Integer, String>> getCourseTable(String course) {\n return data.stream()\n .filter(b -> b.course.equals(course))\n .collect(Collectors.groupingBy(\n b -> b.day, \n Collectors.toMap(BookingSlot::hour, BookingSlot::room))\n );\n }\n\n }\n\n @Override\n public Timetable empty() {\n return new TimetableImpl(Set.of());\n }\n\n}", "filename": "TimetableFactoryImpl.java" } ]
{ "components": { "imports": "package a01d.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;", "private_init": "\t/*\n\t * Implement the TimetableFactory interface as indicated in the initFactory method below.\n\t * Create a factory for a concept of \"weekly university lesson timetable\", captured by the\n\t * Timesheet interface: essentially, it tracks on which days of the week lessons of which\n\t * course are held, and in which classroom.\n\t * \n\t * The following are considered optional for the purpose of being able to correct\n\t * the exercise, but still contribute to achieving the total\n\t * score:\n\t * \n\t * - implementation of all Timetable methods (i.e., in the\n\t * mandatory part it is sufficient to implement all of them except for one of the three getXYZ methods, as desired)\n\t * - the good design of the solution, using design solutions that lead to\n\t * succinct code that avoids repetitions\n\t * \n\t * Remove the comment from the initFactory method.\n\t * \n\t * Scoring indications:\n\t * - correctness of the mandatory part: 10 points\n\t * - correctness of the optional part: 3 points (additional Timetable method)\n\t * - quality of the solution: 4 points (for good design)\n\t * \n\t */\n\n\n\tprivate TimetableFactory factory;\n\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.factory = new TimetableFactoryImpl();\n\t}\n\n\t// realistic lesson timetable (1st semester of the 2nd year, just finished, without labs)\n\tprivate Timetable real(){\n\t\treturn this.factory.empty()\n\t\t\t.addBooking(\"2.12\", \"OOP\", Timetable.Day.WED, 9, 3)\n\t\t\t.addBooking(\"3.4\", \"MDP\", Timetable.Day.WED, 13, 3)\n\t\t\t.addBooking(\"2.12\", \"SISOP\", Timetable.Day.THU, 9, 3)\n\t\t\t.addBooking(\"2.12\", \"OOP\", Timetable.Day.THU, 13, 3)\n\t\t\t.addBooking(\"2.12\", \"MDP\", Timetable.Day.FRI, 9, 2)\n\t\t\t.addBooking(\"2.12\", \"SISOP\", Timetable.Day.FRI, 11, 3);\n\t}", "test_functions": [ "\[email protected]\n\tpublic void testEmpty() {\n\t\t// \"empty\" lesson timetable, let's say during the exam period...\n\t\tTimetable t = this.factory.empty();\n\t\tassertEquals(Set.of(), t.courses());\n\t\tassertEquals(Set.of(), t.rooms());\n\t\tassertEquals(List.of(), t.hours());\n\t\tassertEquals(Map.of(), t.getCourseTable(\"OOP\"));\n\t\tassertEquals(Optional.empty(), t.getDayAndHour(Timetable.Day.MON, 9));\n\t\tassertEquals(Map.of(), t.getDayAtRoom(\"2.12\", Timetable.Day.WED));\n\t}", "\[email protected]\n\tpublic void testBookings() {\n\t\t// realistic lesson timetable, test of the methods courses, rooms and hours\n\t\tTimetable t = real();\n\t\tassertEquals(Set.of(\"OOP\", \"SISOP\", \"MDP\"), t.courses()); // the courses\n\t\tassertEquals(Set.of(\"2.12\", \"3.4\"), t.rooms()); // the rooms used\n\t\tassertEquals(List.of(9,10,11,12,13,14,15), t.hours()); // the hours of classroom used\n\t}", "\[email protected]\n\tpublic void testFindPlace() {\n\t\t// realistic lesson timetable\n\t\tTimetable t = real();\n\t\t// is there space in room 3.4 on Wednesday for 3 hours in a row? yes, at 9 (I provide the first possibility)\n\t\tassertEquals(Optional.of(9), t.findPlaceForBooking(\"3.4\", Timetable.Day.WED, 3));\n\t // is there space in room 2.12 on Thursday for 2 hours in a row? no, completely full\n\t\tassertEquals(Optional.empty(), t.findPlaceForBooking(\"2.12\", Timetable.Day.THU, 2));\n\t}", "\[email protected]\n\tpublic void testCourseTable() {\n\t\t// test of the getCourseTable method\n\t\tTimetable t = real();\n\t\t// test OOP timetable\n\t\tassertEquals(Map.of( \n\t\t\tTimetable.Day.WED, Map.of(9, \"2.12\", 10, \"2.12\", 11, \"2.12\"),\n\t\t\tTimetable.Day.THU, Map.of(13, \"2.12\", 14, \"2.12\", 15, \"2.12\")\n\t\t), t.getCourseTable(\"OOP\"));\n\t\t// test MDP timetable\n\t\tassertEquals(Map.of( \n\t\t\tTimetable.Day.WED, Map.of(13, \"3.4\", 14, \"3.4\", 15, \"3.4\"),\n\t\t\tTimetable.Day.FRI, Map.of(9, \"2.12\", 10, \"2.12\")\n\t\t), t.getCourseTable(\"MDP\"));\n\t}", "\[email protected]\n\tpublic void testDayAndHour() {\n\t\t// test of the getDayAndHour method\n\t\tTimetable t = real();\n\t\t// test of what is there on Wednesday at 9\n\t\tassertEquals(Optional.of(new Pair<>(\"OOP\", \"2.12\")), t.getDayAndHour(Timetable.Day.WED, 9));\n\t\t// test of what is there on Thursday at 9\n\t\tassertEquals(Optional.of(new Pair<>(\"SISOP\", \"2.12\")), t.getDayAndHour(Timetable.Day.THU, 9));\n\t\t// test of what is there on Wednesday at 12: nothing\n\t\tassertEquals(Optional.empty(), t.getDayAndHour(Timetable.Day.WED, 12));\n\t}", "\[email protected]\n\tpublic void testDayAtRoom() {\n\t\t// test of the getDayAtRoom method\n\t\tTimetable t = real();\n\t\t// test of what is there in 2.12 on Wednesday\n\t\tassertEquals(Map.of(9, \"OOP\", 10, \"OOP\", 11, \"OOP\"), t.getDayAtRoom(\"2.12\", Timetable.Day.WED));\n\t\t// test of what is there in 2.12 on Thursday\n\t\tassertEquals(\n\t\t\tMap.of(9, \"SISOP\", 10, \"SISOP\", 11, \"SISOP\", 13, \"OOP\", 14, \"OOP\", 15, \"OOP\"), \n\t\t\tt.getDayAtRoom(\"2.12\", Timetable.Day.THU));\n\t}" ] }, "content": "package a01d.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;\n\npublic class Test {\n\n\t/*\n\t * Implement the TimetableFactory interface as indicated in the initFactory method below.\n\t * Create a factory for a concept of \"weekly university lesson timetable\", captured by the\n\t * Timesheet interface: essentially, it tracks on which days of the week lessons of which\n\t * course are held, and in which classroom.\n\t * \n\t * The following are considered optional for the purpose of being able to correct\n\t * the exercise, but still contribute to achieving the total\n\t * score:\n\t * \n\t * - implementation of all Timetable methods (i.e., in the\n\t * mandatory part it is sufficient to implement all of them except for one of the three getXYZ methods, as desired)\n\t * - the good design of the solution, using design solutions that lead to\n\t * succinct code that avoids repetitions\n\t * \n\t * Remove the comment from the initFactory method.\n\t * \n\t * Scoring indications:\n\t * - correctness of the mandatory part: 10 points\n\t * - correctness of the optional part: 3 points (additional Timetable method)\n\t * - quality of the solution: 4 points (for good design)\n\t * \n\t */\n\n\n\tprivate TimetableFactory factory;\n\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.factory = new TimetableFactoryImpl();\n\t}\n\n\t// realistic lesson timetable (1st semester of the 2nd year, just finished, without labs)\n\tprivate Timetable real(){\n\t\treturn this.factory.empty()\n\t\t\t.addBooking(\"2.12\", \"OOP\", Timetable.Day.WED, 9, 3)\n\t\t\t.addBooking(\"3.4\", \"MDP\", Timetable.Day.WED, 13, 3)\n\t\t\t.addBooking(\"2.12\", \"SISOP\", Timetable.Day.THU, 9, 3)\n\t\t\t.addBooking(\"2.12\", \"OOP\", Timetable.Day.THU, 13, 3)\n\t\t\t.addBooking(\"2.12\", \"MDP\", Timetable.Day.FRI, 9, 2)\n\t\t\t.addBooking(\"2.12\", \"SISOP\", Timetable.Day.FRI, 11, 3);\n\t}\n\n\[email protected]\n\tpublic void testEmpty() {\n\t\t// \"empty\" lesson timetable, let's say during the exam period...\n\t\tTimetable t = this.factory.empty();\n\t\tassertEquals(Set.of(), t.courses());\n\t\tassertEquals(Set.of(), t.rooms());\n\t\tassertEquals(List.of(), t.hours());\n\t\tassertEquals(Map.of(), t.getCourseTable(\"OOP\"));\n\t\tassertEquals(Optional.empty(), t.getDayAndHour(Timetable.Day.MON, 9));\n\t\tassertEquals(Map.of(), t.getDayAtRoom(\"2.12\", Timetable.Day.WED));\n\t}\n\n\[email protected]\n\tpublic void testBookings() {\n\t\t// realistic lesson timetable, test of the methods courses, rooms and hours\n\t\tTimetable t = real();\n\t\tassertEquals(Set.of(\"OOP\", \"SISOP\", \"MDP\"), t.courses()); // the courses\n\t\tassertEquals(Set.of(\"2.12\", \"3.4\"), t.rooms()); // the rooms used\n\t\tassertEquals(List.of(9,10,11,12,13,14,15), t.hours()); // the hours of classroom used\n\t}\n\n\[email protected]\n\tpublic void testFindPlace() {\n\t\t// realistic lesson timetable\n\t\tTimetable t = real();\n\t\t// is there space in room 3.4 on Wednesday for 3 hours in a row? yes, at 9 (I provide the first possibility)\n\t\tassertEquals(Optional.of(9), t.findPlaceForBooking(\"3.4\", Timetable.Day.WED, 3));\n\t // is there space in room 2.12 on Thursday for 2 hours in a row? no, completely full\n\t\tassertEquals(Optional.empty(), t.findPlaceForBooking(\"2.12\", Timetable.Day.THU, 2));\n\t}\n\n\n\[email protected]\n\tpublic void testCourseTable() {\n\t\t// test of the getCourseTable method\n\t\tTimetable t = real();\n\t\t// test OOP timetable\n\t\tassertEquals(Map.of( \n\t\t\tTimetable.Day.WED, Map.of(9, \"2.12\", 10, \"2.12\", 11, \"2.12\"),\n\t\t\tTimetable.Day.THU, Map.of(13, \"2.12\", 14, \"2.12\", 15, \"2.12\")\n\t\t), t.getCourseTable(\"OOP\"));\n\t\t// test MDP timetable\n\t\tassertEquals(Map.of( \n\t\t\tTimetable.Day.WED, Map.of(13, \"3.4\", 14, \"3.4\", 15, \"3.4\"),\n\t\t\tTimetable.Day.FRI, Map.of(9, \"2.12\", 10, \"2.12\")\n\t\t), t.getCourseTable(\"MDP\"));\n\t}\n\n\[email protected]\n\tpublic void testDayAndHour() {\n\t\t// test of the getDayAndHour method\n\t\tTimetable t = real();\n\t\t// test of what is there on Wednesday at 9\n\t\tassertEquals(Optional.of(new Pair<>(\"OOP\", \"2.12\")), t.getDayAndHour(Timetable.Day.WED, 9));\n\t\t// test of what is there on Thursday at 9\n\t\tassertEquals(Optional.of(new Pair<>(\"SISOP\", \"2.12\")), t.getDayAndHour(Timetable.Day.THU, 9));\n\t\t// test of what is there on Wednesday at 12: nothing\n\t\tassertEquals(Optional.empty(), t.getDayAndHour(Timetable.Day.WED, 12));\n\t}\n\n\[email protected]\n\tpublic void testDayAtRoom() {\n\t\t// test of the getDayAtRoom method\n\t\tTimetable t = real();\n\t\t// test of what is there in 2.12 on Wednesday\n\t\tassertEquals(Map.of(9, \"OOP\", 10, \"OOP\", 11, \"OOP\"), t.getDayAtRoom(\"2.12\", Timetable.Day.WED));\n\t\t// test of what is there in 2.12 on Thursday\n\t\tassertEquals(\n\t\t\tMap.of(9, \"SISOP\", 10, \"SISOP\", 11, \"SISOP\", 13, \"OOP\", 14, \"OOP\", 15, \"OOP\"), \n\t\t\tt.getDayAtRoom(\"2.12\", Timetable.Day.THU));\n\t}\n\n\n}", "filename": "Test.java" }
2023
a04
[ { "content": "package a04.sol1;\n\nimport java.util.List;\nimport java.util.Optional;\nimport java.util.function.*;\n\npublic interface ListExtractorFactory {\n\t\n\t\n\t<X> ListExtractor<X, Optional<X>> head();\n\n\t\n\t<X, Y> ListExtractor<X, List<Y>> collectUntil(Function<X,Y> mapper, Predicate<X> stopCondition);\n\n\t\n\t<X> ListExtractor<X, List<List<X>>> scanFrom(Predicate<X> startCondition);\n\n\t\n\t<X> ListExtractor<X, Integer> countConsecutive(X x);\n}", "filename": "ListExtractorFactory.java" }, { "content": "package a04.sol1;\n\nimport java.util.*;\n\n\npublic interface ListExtractor<A, B> {\n\t\n\t\n\tB extract(List<A> list);\n}", "filename": "ListExtractor.java" }, { "content": "package a04.sol1;\n\nimport java.util.Objects;\n\n\n\npublic class Pair<E1,E2> {\n\t\n\tprivate final E1 e1;\n\tprivate final E2 e2;\n\t\n\tpublic Pair(E1 x, E2 y) {\n\t\tsuper();\n\t\tthis.e1 = x;\n\t\tthis.e2 = y;\n\t}\n\n\tpublic E1 get1() {\n\t\treturn e1;\n\t}\n\n\tpublic E2 get2() {\n\t\treturn e2;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Objects.hash(e1, e2);\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj) {\n\t\t\treturn true;\n\t\t}\n\t\tif (obj == null) {\n\t\t\treturn false;\n\t\t}\n\t\tif (getClass() != obj.getClass()) {\n\t\t\treturn false;\n\t\t}\n\t\tPair other = (Pair) obj;\n\t\treturn Objects.equals(e1, other.e1) && Objects.equals(e2, other.e2);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Pair [e1=\" + e1 + \", e2=\" + e2 + \"]\";\n\t}\n\t\n\t\n\n}", "filename": "Pair.java" } ]
[ { "content": "package a04.sol1;\n\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Optional;\nimport java.util.function.Function;\nimport java.util.function.Predicate;\n\npublic class ListExtractorFactoryImpl implements ListExtractorFactory {\n\n abstract class AbstractListExtractor<X,Y> implements ListExtractor<X,Y> {\n\n @Override\n public Y extract(List<X> list) {\n boolean extracting = false;\n Y output = initialResult();\n for (var x: list){\n if (!extracting && start(x)){\n extracting = true;\n }\n if (extracting && stop(output, x)){\n break;\n } \n if (extracting){\n output = compute(output, x);\n } \n }\n return output;\n }\n\n protected abstract Y compute(Y output, X x);\n\n protected abstract boolean stop(Y output, X x);\n\n protected abstract boolean start(X x);\n\n protected abstract Y initialResult();\n }\n\n @Override\n public <X> ListExtractor<X, Optional<X>> head() {\n return new AbstractListExtractor<X,Optional<X>>() {\n\n @Override\n protected Optional<X> compute(Optional<X> output, X x) {\n return Optional.of(x);\n }\n\n @Override\n protected boolean stop(Optional<X> output, X x) {\n return output.isPresent();\n }\n\n @Override\n protected boolean start(X x) {\n return true;\n }\n\n @Override\n protected Optional<X> initialResult() {\n return Optional.empty();\n } \n };\n }\n\n @Override\n public <X, Y> ListExtractor<X, List<Y>> collectUntil(Function<X, Y> mapper, Predicate<X> stopCondition) {\n return new AbstractListExtractor<X,List<Y>>() {\n\n @Override\n protected List<Y> compute(List<Y> output, X x) {\n output.add(mapper.apply(x));\n return output;\n }\n\n @Override\n protected boolean stop(List<Y> output, X x) {\n return stopCondition.test(x);\n }\n\n @Override\n protected boolean start(X x) {\n return true;\n }\n\n @Override\n protected List<Y> initialResult() {\n return new LinkedList<>();\n }\n };\n }\n\n @Override\n public <X> ListExtractor<X, List<List<X>>> scanFrom(Predicate<X> startCondition) {\n return new AbstractListExtractor<X,List<List<X>>>() {\n\n @Override\n protected List<List<X>> compute(List<List<X>> output, X x) {\n var newList = new LinkedList<>(output.isEmpty()? new LinkedList<>() : output.get(output.size()-1));\n newList.add(x);\n output.add(newList);\n return output;\n }\n\n @Override\n protected boolean stop(List<List<X>> output, X x) {\n return false;\n }\n\n @Override\n protected boolean start(X x) {\n return startCondition.test(x);\n }\n\n @Override\n protected List<List<X>> initialResult() {\n return new LinkedList<>();\n }\n };\n }\n\n @Override\n public <X> ListExtractor<X, Integer> countConsecutive(X x0) {\n return new AbstractListExtractor<X,Integer>() {\n\n @Override\n protected Integer compute(Integer output, X x) {\n return output + 1;\n }\n\n @Override\n protected boolean stop(Integer output, X x) {\n return !x0.equals(x);\n }\n\n @Override\n protected boolean start(X x) {\n return x.equals(x0);\n }\n\n @Override\n protected Integer initialResult() {\n return 0;\n }\n \n }; \n }\n\n}", "filename": "ListExtractorFactoryImpl.java" } ]
{ "components": { "imports": "package a04.sol1;\n\nimport static org.junit.Assert.*;\n\nimport java.util.*;", "private_init": "\t/*\n\t * Implement the ListExtractorFactory interface as indicated in the initFactory\n\t * method below. Create a factory for a ListExtractor concept, captured by the\n\t * interface of the same name: essentially it contains a pure function that,\n\t * given a list, extracts a certain subsequence of it and uses it to produce,\n\t * element by element, a result.\n\t * In the complete exercise, reuse via inheritance must be applied.\n\t * \n\t * The following are considered optional for the purpose of being able to correct\n\t * the exercise, but still contribute to achieving the total score:\n\t * \n\t * - implementation of all factory methods (i.e., in the\n\t * mandatory part it is sufficient to implement all but one at will)\n\t * - the good design of the solution, using reuse via inheritance for all the various versions\n\t * of the ListExtractor (i.e., in the mandatory part\n\t * it is fine if reuse via inheritance is used for at least two ListExtractors)\n\t * \n\t * Remove the comment from the initFactory method.\n\t * \n\t * Scoring indications:\n\t * - correctness of the mandatory part: 10 points\n\t * - correctness of the optional part: 3 points (additional factory method)\n\t * - quality of the solution: 4 points (for good design)\n\t * \n\t */\n\n\tprivate ListExtractorFactory factory;\n\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.factory = new ListExtractorFactoryImpl();\n\t}", "test_functions": [ "\[email protected]\n\tpublic void testHead() {\n\t\t// an extractor that produces the first element of the list, if available\n\t\tfinal ListExtractor<Integer, Optional<Integer>> le = this.factory.head();\n\t\tassertEquals(Optional.of(10), le.extract(List.of(10,20,30,40,50)));\n\t\tassertEquals(Optional.of(10), le.extract(List.of(10)));\n\t\tassertEquals(Optional.empty(), le.extract(List.of()));\n\t}", "\[email protected]\n\tpublic void testCollectUntil() {\n\t\tfinal ListExtractor<Integer, List<Integer>> le = this.factory.<Integer, Integer>collectUntil(x -> x + 1, x -> x >= 30);\n\t\t// collects the elements of the list until they reach 30, adding one to each\n\t\tassertEquals(List.of(11, 21), le.extract(List.of(10,20,30,40,50)));\n\t\tassertEquals(List.of(11), le.extract(List.of(10,50,20,40,50)));\n\t\tassertEquals(List.of(), le.extract(List.of(30,50,20,40,50)));\n\t\tassertEquals(List.of(), le.extract(List.of()));\n\t}", "\[email protected]\n\tpublic void testScanFrom() {\n\t\tfinal ListExtractor<Integer, List<List<Integer>>> le = this.factory.<Integer>scanFrom(x -> x >= 30);\n\t\t// collects the elements from when there is one >= 30 to the end, producing lists of incremental lists\n\t\tassertEquals(List.of(List.of(30), List.of(30,20), List.of(30,20,50)), le.extract(List.of(10,20,30,20,50)));\n\t\tassertEquals(List.of(List.of(30)), le.extract(List.of(30)));\n\t\tassertEquals(List.of(), le.extract(List.of(10,20,25)));\n\t}", "\[email protected]\n\tpublic void testCount() {\n\t\tfinal ListExtractor<String, Integer> le = this.factory.countConsecutive(\"a\");\n\t\t// counts how many consecutive \"a\"s there are starting from the first occurrence\n\t\tassertEquals(3, le.extract(List.of(\"b\", \"a\", \"a\",\"a\",\"c\",\"d\",\"a\")).intValue());\n\t\tassertEquals(1, le.extract(List.of(\"a\", \"b\", \"a\", \"a\",\"a\",\"c\",\"d\",\"a\")).intValue());\n\t\tassertEquals(1, le.extract(List.of(\"b\", \"c\", \"d\",\"a\")).intValue());\n\t\tassertEquals(0, le.extract(List.of(\"b\", \"c\", \"d\")).intValue());\n\t\tassertEquals(0, le.extract(List.of()).intValue());\n\t}" ] }, "content": "package a04.sol1;\n\nimport static org.junit.Assert.*;\n\nimport java.util.*;\n\npublic class Test {\n\n\t/*\n\t * Implement the ListExtractorFactory interface as indicated in the initFactory\n\t * method below. Create a factory for a ListExtractor concept, captured by the\n\t * interface of the same name: essentially it contains a pure function that,\n\t * given a list, extracts a certain subsequence of it and uses it to produce,\n\t * element by element, a result.\n\t * In the complete exercise, reuse via inheritance must be applied.\n\t * \n\t * The following are considered optional for the purpose of being able to correct\n\t * the exercise, but still contribute to achieving the total score:\n\t * \n\t * - implementation of all factory methods (i.e., in the\n\t * mandatory part it is sufficient to implement all but one at will)\n\t * - the good design of the solution, using reuse via inheritance for all the various versions\n\t * of the ListExtractor (i.e., in the mandatory part\n\t * it is fine if reuse via inheritance is used for at least two ListExtractors)\n\t * \n\t * Remove the comment from the initFactory method.\n\t * \n\t * Scoring indications:\n\t * - correctness of the mandatory part: 10 points\n\t * - correctness of the optional part: 3 points (additional factory method)\n\t * - quality of the solution: 4 points (for good design)\n\t * \n\t */\n\n\tprivate ListExtractorFactory factory;\n\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.factory = new ListExtractorFactoryImpl();\n\t}\n\n\[email protected]\n\tpublic void testHead() {\n\t\t// an extractor that produces the first element of the list, if available\n\t\tfinal ListExtractor<Integer, Optional<Integer>> le = this.factory.head();\n\t\tassertEquals(Optional.of(10), le.extract(List.of(10,20,30,40,50)));\n\t\tassertEquals(Optional.of(10), le.extract(List.of(10)));\n\t\tassertEquals(Optional.empty(), le.extract(List.of()));\n\t}\n\n\[email protected]\n\tpublic void testCollectUntil() {\n\t\tfinal ListExtractor<Integer, List<Integer>> le = this.factory.<Integer, Integer>collectUntil(x -> x + 1, x -> x >= 30);\n\t\t// collects the elements of the list until they reach 30, adding one to each\n\t\tassertEquals(List.of(11, 21), le.extract(List.of(10,20,30,40,50)));\n\t\tassertEquals(List.of(11), le.extract(List.of(10,50,20,40,50)));\n\t\tassertEquals(List.of(), le.extract(List.of(30,50,20,40,50)));\n\t\tassertEquals(List.of(), le.extract(List.of()));\n\t}\n\n\[email protected]\n\tpublic void testScanFrom() {\n\t\tfinal ListExtractor<Integer, List<List<Integer>>> le = this.factory.<Integer>scanFrom(x -> x >= 30);\n\t\t// collects the elements from when there is one >= 30 to the end, producing lists of incremental lists\n\t\tassertEquals(List.of(List.of(30), List.of(30,20), List.of(30,20,50)), le.extract(List.of(10,20,30,20,50)));\n\t\tassertEquals(List.of(List.of(30)), le.extract(List.of(30)));\n\t\tassertEquals(List.of(), le.extract(List.of(10,20,25)));\n\t}\n\n\[email protected]\n\tpublic void testCount() {\n\t\tfinal ListExtractor<String, Integer> le = this.factory.countConsecutive(\"a\");\n\t\t// counts how many consecutive \"a\"s there are starting from the first occurrence\n\t\tassertEquals(3, le.extract(List.of(\"b\", \"a\", \"a\",\"a\",\"c\",\"d\",\"a\")).intValue());\n\t\tassertEquals(1, le.extract(List.of(\"a\", \"b\", \"a\", \"a\",\"a\",\"c\",\"d\",\"a\")).intValue());\n\t\tassertEquals(1, le.extract(List.of(\"b\", \"c\", \"d\",\"a\")).intValue());\n\t\tassertEquals(0, le.extract(List.of(\"b\", \"c\", \"d\")).intValue());\n\t\tassertEquals(0, le.extract(List.of()).intValue());\n\t}\n}", "filename": "Test.java" }
2023
a03a
[ { "content": "package a03a.sol1;\n\nimport java.util.*;\n\n\n\npublic interface Windowing<X, Y> {\n\n \n Optional<Y> process(X x);\n}", "filename": "Windowing.java" }, { "content": "package a03a.sol1;\n\nimport java.util.List;\n\n\npublic interface WindowingFactory {\n\n \n <X> Windowing<X, X> trivial();\n\n \n <X> Windowing<X, Pair<X, X>> pairing();\n\n \n Windowing<Integer, Integer> sumLastFour();\n\n \n <X> Windowing<X, List<X>> lastN(int n);\n\n \n Windowing<Integer, List<Integer>> lastWhoseSumIsAtLeast(int n);\n\n}", "filename": "WindowingFactory.java" }, { "content": "package a03a.sol1;\n\nimport java.util.Objects;\n\n\n\npublic class Pair<E1,E2> {\n\t\n\tprivate final E1 e1;\n\tprivate final E2 e2;\n\t\n\tpublic Pair(E1 x, E2 y) {\n\t\tsuper();\n\t\tthis.e1 = x;\n\t\tthis.e2 = y;\n\t}\n\n\tpublic E1 get1() {\n\t\treturn e1;\n\t}\n\n\tpublic E2 get2() {\n\t\treturn e2;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Objects.hash(e1, e2);\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj) {\n\t\t\treturn true;\n\t\t}\n\t\tif (obj == null) {\n\t\t\treturn false;\n\t\t}\n\t\tif (getClass() != obj.getClass()) {\n\t\t\treturn false;\n\t\t}\n\t\tPair other = (Pair) obj;\n\t\treturn Objects.equals(e1, other.e1) && Objects.equals(e2, other.e2);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Pair [e1=\" + e1 + \", e2=\" + e2 + \"]\";\n\t}\n\t\n\t\n\n}", "filename": "Pair.java" } ]
[ { "content": "package a03a.sol1;\n\nimport java.util.*;\nimport java.util.function.*;\n\npublic class WindowingFactoryImpl implements WindowingFactory {\n\n private <X,Y> Windowing<X,Y> genericWindowing(Predicate<List<X>> ready, Function<List<X>, Y> mapper){\n return new Windowing<X,Y>() {\n\n private final LinkedList<X> cache = new LinkedList<>();\n\n @Override\n public Optional<Y> process(X x) {\n cache.addLast(x);\n if (!ready.test(cache)){\n return Optional.empty();\n }\n while (!cache.isEmpty() && ready.test(cache.subList(1, cache.size()))){\n cache.removeFirst();\n }\n return Optional.of(cache).map(mapper);\n }\n };\n }\n\n @Override\n public <X> Windowing<X, X> trivial() {\n return genericWindowing(l -> l.size() >= 1, l -> l.get(0));\n }\n\n @Override\n public <X> Windowing<X, Pair<X, X>> pairing() {\n return genericWindowing(l -> l.size() >= 2, l -> new Pair<>(l.get(0), l.get(1)));\n }\n\n @Override\n public Windowing<Integer, Integer> sumLastFour() {\n return genericWindowing(l -> l.size() >= 4, l -> listSum(l));\n }\n\n @Override\n public <X> Windowing<X, List<X>> lastN(int n) {\n return genericWindowing(l -> l.size() >= n, l -> l);\n }\n\n\n @Override\n public Windowing<Integer, List<Integer>> lastWhoseSumIsAtLeast(int n) {\n return genericWindowing(l -> listSum(l) >= n, l -> l);\n }\n\n private int listSum(List<Integer> l) {\n return l.stream().mapToInt(i->i).sum();\n }\n}", "filename": "WindowingFactoryImpl.java" } ]
{ "components": { "imports": "package a03a.sol1;\n\nimport static org.junit.Assert.*;\n\nimport java.util.*;", "private_init": "\t/*\n\t * Implement the WindowingFactory interface as indicated in the initFactory method below.\n\t * Create a factory for a Windowing concept, which is a particular type of transformation\n\t * from sequences to sequences.\n\t * \n\t * The following are considered optional for the possibility of correcting\n\t * the exercise, but still contribute to the achievement of the total\n\t * score:\n\t * \n\t * - implementation of all methods of the factory (i.e., in the\n\t * obligatory part it is sufficient to implement all of them except one at will)\n\t * - good design of the solution, using design solutions that lead to\n\t * succinct code that avoids repetitions\n\t * \n\t * Remove the comment from the initFactory method.\n\t * \n\t * Scoring indications:\n\t * - correctness of the mandatory part: 10 points\n\t * - correctness of the optional part: 3 points (additional factory method)\n\t * - quality of the solution: 4 points (for good design)\n\t * \n\t */\n\n\tprivate WindowingFactory factory;\n\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.factory = new WindowingFactoryImpl();\n\t}", "test_functions": [ "\[email protected]\n\tpublic void testTrivial() {\n\t\tWindowing<String, String> windowing = this.factory.trivial();\n\t\t// the input corresponds to the output\n\t\tassertEquals(Optional.of(\"a\"), windowing.process(\"a\"));\n\t\tassertEquals(Optional.of(\"b\"), windowing.process(\"b\"));\n\t\tassertEquals(Optional.of(\"a\"), windowing.process(\"a\"));\n\t}", "\[email protected]\n\tpublic void testPairing() {\n\t\tWindowing<Integer, Pair<Integer, Integer>> windowing = this.factory.pairing();\n\t\t// the last two inputs provided to process form a pair, the first time Optional.empty\n\t\tassertEquals(Optional.empty(), windowing.process(1));\n\t\tassertEquals(Optional.of(new Pair<>(1, 3)), windowing.process(3));\n\t\tassertEquals(Optional.of(new Pair<>(3, 2)), windowing.process(2));\n\t\tassertEquals(Optional.of(new Pair<>(2, 1)), windowing.process(1));\n\t}", "\[email protected]\n\tpublic void testSumFour() {\n\t\tWindowing<Integer, Integer> windowing = this.factory.sumLastFour();\n\t\t// the last four inputs provided to process produce their sum, the first 3 times Optional.empty\n\t\tassertEquals(Optional.empty(), windowing.process(1));\n\t\tassertEquals(Optional.empty(), windowing.process(10));\n\t\tassertEquals(Optional.empty(), windowing.process(100));\n\t\tassertEquals(Optional.of(1111), windowing.process(1000)); //1+10+100+1000\n\t\tassertEquals(Optional.of(1112), windowing.process(2)); // 10+100+1000+2\n\t\tassertEquals(Optional.of(1122), windowing.process(20)); // 100+1000+2+20\n\t}", "\[email protected]\n\tpublic void testLastN() {\n\t\tWindowing<Integer, List<Integer>> windowing = this.factory.lastN(4);\n\t\t// the last N inputs provided to process produce a list, the first N-1 times Optional.empty\n\t\tassertEquals(Optional.empty(), windowing.process(1));\n\t\tassertEquals(Optional.empty(), windowing.process(10));\n\t\tassertEquals(Optional.empty(), windowing.process(100));\n\t\tassertEquals(Optional.of(List.of(1, 10, 100, 1000)), windowing.process(1000));\n\t\tassertEquals(Optional.of(List.of(10, 100, 1000, 2)), windowing.process(2));\n\t\tassertEquals(Optional.of(List.of(100, 1000, 2, 20)), windowing.process(20));\n\t}", "\[email protected]\n\tpublic void testSumAtLeast() {\n\t\tWindowing<Integer, List<Integer>> windowing = this.factory.lastWhoseSumIsAtLeast(10);\n\t\t// the list of the last elements whose sum is at least N (N=10 in this case) produce a list\n\t\tassertEquals(Optional.empty(), windowing.process(5)); // not yet reached 10\n\t\tassertEquals(Optional.empty(), windowing.process(3)); // not yet reached 10\n\t\tassertEquals(Optional.empty(), windowing.process(1)); // not yet reached 10\n\t\tassertEquals(Optional.of(List.of(5,3,1,1)), windowing.process(1)); // 5+3+1+1 >= 10\n\t\tassertEquals(Optional.of(List.of(5,3,1,1, 2)), windowing.process(2)); // 5+3+1+1+2 >= 10, while 3+1+1+2 < 10\n\t\tassertEquals(Optional.of(List.of(3,1,1, 2, 4)), windowing.process(4)); // 3+1+1+2+4 >= 10, while 1+1+2+4 < 10\n\t\tassertEquals(Optional.of(List.of(4, 8)), windowing.process(8)); // etc...\n\t\tassertEquals(Optional.of(List.of(20)), windowing.process(20));\n\t}" ] }, "content": "package a03a.sol1;\n\nimport static org.junit.Assert.*;\n\nimport java.util.*;\n\npublic class Test {\n\n\t/*\n\t * Implement the WindowingFactory interface as indicated in the initFactory method below.\n\t * Create a factory for a Windowing concept, which is a particular type of transformation\n\t * from sequences to sequences.\n\t * \n\t * The following are considered optional for the possibility of correcting\n\t * the exercise, but still contribute to the achievement of the total\n\t * score:\n\t * \n\t * - implementation of all methods of the factory (i.e., in the\n\t * obligatory part it is sufficient to implement all of them except one at will)\n\t * - good design of the solution, using design solutions that lead to\n\t * succinct code that avoids repetitions\n\t * \n\t * Remove the comment from the initFactory method.\n\t * \n\t * Scoring indications:\n\t * - correctness of the mandatory part: 10 points\n\t * - correctness of the optional part: 3 points (additional factory method)\n\t * - quality of the solution: 4 points (for good design)\n\t * \n\t */\n\n\tprivate WindowingFactory factory;\n\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.factory = new WindowingFactoryImpl();\n\t}\n\n\[email protected]\n\tpublic void testTrivial() {\n\t\tWindowing<String, String> windowing = this.factory.trivial();\n\t\t// the input corresponds to the output\n\t\tassertEquals(Optional.of(\"a\"), windowing.process(\"a\"));\n\t\tassertEquals(Optional.of(\"b\"), windowing.process(\"b\"));\n\t\tassertEquals(Optional.of(\"a\"), windowing.process(\"a\"));\n\t}\n\n\[email protected]\n\tpublic void testPairing() {\n\t\tWindowing<Integer, Pair<Integer, Integer>> windowing = this.factory.pairing();\n\t\t// the last two inputs provided to process form a pair, the first time Optional.empty\n\t\tassertEquals(Optional.empty(), windowing.process(1));\n\t\tassertEquals(Optional.of(new Pair<>(1, 3)), windowing.process(3));\n\t\tassertEquals(Optional.of(new Pair<>(3, 2)), windowing.process(2));\n\t\tassertEquals(Optional.of(new Pair<>(2, 1)), windowing.process(1));\n\t}\n\n\[email protected]\n\tpublic void testSumFour() {\n\t\tWindowing<Integer, Integer> windowing = this.factory.sumLastFour();\n\t\t// the last four inputs provided to process produce their sum, the first 3 times Optional.empty\n\t\tassertEquals(Optional.empty(), windowing.process(1));\n\t\tassertEquals(Optional.empty(), windowing.process(10));\n\t\tassertEquals(Optional.empty(), windowing.process(100));\n\t\tassertEquals(Optional.of(1111), windowing.process(1000)); //1+10+100+1000\n\t\tassertEquals(Optional.of(1112), windowing.process(2)); // 10+100+1000+2\n\t\tassertEquals(Optional.of(1122), windowing.process(20)); // 100+1000+2+20\n\t}\n\n\[email protected]\n\tpublic void testLastN() {\n\t\tWindowing<Integer, List<Integer>> windowing = this.factory.lastN(4);\n\t\t// the last N inputs provided to process produce a list, the first N-1 times Optional.empty\n\t\tassertEquals(Optional.empty(), windowing.process(1));\n\t\tassertEquals(Optional.empty(), windowing.process(10));\n\t\tassertEquals(Optional.empty(), windowing.process(100));\n\t\tassertEquals(Optional.of(List.of(1, 10, 100, 1000)), windowing.process(1000));\n\t\tassertEquals(Optional.of(List.of(10, 100, 1000, 2)), windowing.process(2));\n\t\tassertEquals(Optional.of(List.of(100, 1000, 2, 20)), windowing.process(20));\n\t}\n\n\[email protected]\n\tpublic void testSumAtLeast() {\n\t\tWindowing<Integer, List<Integer>> windowing = this.factory.lastWhoseSumIsAtLeast(10);\n\t\t// the list of the last elements whose sum is at least N (N=10 in this case) produce a list\n\t\tassertEquals(Optional.empty(), windowing.process(5)); // not yet reached 10\n\t\tassertEquals(Optional.empty(), windowing.process(3)); // not yet reached 10\n\t\tassertEquals(Optional.empty(), windowing.process(1)); // not yet reached 10\n\t\tassertEquals(Optional.of(List.of(5,3,1,1)), windowing.process(1)); // 5+3+1+1 >= 10\n\t\tassertEquals(Optional.of(List.of(5,3,1,1, 2)), windowing.process(2)); // 5+3+1+1+2 >= 10, while 3+1+1+2 < 10\n\t\tassertEquals(Optional.of(List.of(3,1,1, 2, 4)), windowing.process(4)); // 3+1+1+2+4 >= 10, while 1+1+2+4 < 10\n\t\tassertEquals(Optional.of(List.of(4, 8)), windowing.process(8)); // etc...\n\t\tassertEquals(Optional.of(List.of(20)), windowing.process(20));\n\t}\n\n}", "filename": "Test.java" }
2023
a02b
[ { "content": "package a02b.sol1;\n\nimport java.util.List;\n\npublic interface RulesEngineFactory {\n\n \n <T> List<List<T>> applyRule(Pair<T, List<T>> rule, List<T> input);\n\n \n <T> RulesEngine<T> singleRuleEngine(Pair<T, List<T>> rule);\n\n \n <T> RulesEngine<T> cascadingRulesEngine(Pair<T, List<T>> baseRule, Pair<T, List<T>> cascadeRule);\n\n \n <T> RulesEngine<T> conflictingRulesEngine(Pair<T, List<T>> rule1, Pair<T, List<T>> rule2);\n\n}", "filename": "RulesEngineFactory.java" }, { "content": "package a02b.sol1;\n\nimport java.util.List;\n\n\npublic interface RulesEngine<T> {\n\n \n void resetInput(List<T> input);\n\n \n boolean hasOtherSolutions();\n\n \n List<T> nextSolution();\n}", "filename": "RulesEngine.java" }, { "content": "package a02b.sol1;\n\nimport java.util.Objects;\n\n\n\npublic class Pair<E1,E2> {\n\t\n\tprivate final E1 e1;\n\tprivate final E2 e2;\n\t\n\tpublic Pair(E1 x, E2 y) {\n\t\tsuper();\n\t\tthis.e1 = x;\n\t\tthis.e2 = y;\n\t}\n\n\tpublic E1 get1() {\n\t\treturn e1;\n\t}\n\n\tpublic E2 get2() {\n\t\treturn e2;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Objects.hash(e1, e2);\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj) {\n\t\t\treturn true;\n\t\t}\n\t\tif (obj == null) {\n\t\t\treturn false;\n\t\t}\n\t\tif (getClass() != obj.getClass()) {\n\t\t\treturn false;\n\t\t}\n\t\tPair other = (Pair) obj;\n\t\treturn Objects.equals(e1, other.e1) && Objects.equals(e2, other.e2);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Pair [e1=\" + e1 + \", e2=\" + e2 + \"]\";\n\t}\n\t\n\t\n\n}", "filename": "Pair.java" } ]
[ { "content": "package a02b.sol1;\n\nimport java.util.Iterator;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.stream.Stream;\n\n/*\n * Idea of the solution: a single rule engine can capture all cases!\n * For each element in the input checks which rules can apply, each rule\n * is applied and will give certains solutions -- all solutions are then combined.\n * The use of flatMap facilitates production of all algorithms here.\n */\npublic class RulesEngineFactoryImpl implements RulesEngineFactory {\n\n // Utility to replace from 'source' the element in index-position with 'toReplace'\n private <T> List<T> replaceAtPosition(int index, List<T> source, List<T> newElements){\n var l = new LinkedList<>(source);\n l.remove(index);\n var it = newElements.listIterator(newElements.size());\n while (it.hasPrevious()){\n l.add(index, it.previous());\n }\n return l;\n }\n\n public <T> List<List<T>> applyRule(Pair<T, List<T>> rule, List<T> input){\n return Stream\n .iterate(0, i -> i < input.size(), i -> i + 1)\n .flatMap(i -> input.get(i).equals(rule.get1()) ? Stream.of(replaceAtPosition(i, input, rule.get2())): Stream.empty())\n .toList();\n }\n\n private <T> boolean applicable(List<Pair<T, List<T>>> rules, List<T> input){\n return rules.stream().anyMatch(r -> input.contains(r.get1()));\n }\n\n // this method does the whole job: essentially by nesting two flatMaps\n private <T> Stream<List<T>> applyRules(List<Pair<T, List<T>>> rules, List<T> input){\n return !applicable(rules, input) \n ? Stream.of(input) \n : rules\n .stream()\n .flatMap(rule -> applyRule(rule, input).stream().flatMap(list -> applyRules(rules, list)).distinct())\n .distinct();\n }\n\n private <T> RulesEngine<T> fromRules(List<Pair<T, List<T>>> rules){\n return new RulesEngine<T>() {\n private Iterator<List<T>> iterator = null;\n\n @Override\n public void resetInput(List<T> input) {\n this.iterator = applyRules(rules, input).iterator();\n }\n\n @Override\n public boolean hasOtherSolutions() {\n return this.iterator.hasNext();\n }\n\n @Override\n public List<T> nextSolution() {\n return this.iterator.next();\n }\n \n };\n }\n\n @Override\n public <T> RulesEngine<T> singleRuleEngine(Pair<T, List<T>> rule) {\n return fromRules(List.of(rule));\n }\n\n @Override\n public <T> RulesEngine<T> cascadingRulesEngine(Pair<T, List<T>> rule1, Pair<T, List<T>> rule2) {\n return fromRules(List.of(rule1, rule2));\n }\n\n @Override\n public <T> RulesEngine<T> conflictingRulesEngine(Pair<T, List<T>> rule1, Pair<T, List<T>> rule2) {\n return fromRules(List.of(rule1, rule2));\n }\n\n}", "filename": "RulesEngineFactoryImpl.java" } ]
{ "components": { "imports": "package a02b.sol1;\n\nimport static org.junit.Assert.*;\n\nimport java.util.*;", "private_init": "\t/*\n\t * Implement the RulesEngineFactory interface as indicated in the initFactory method below.\n\t * Create a factory for a \"rules engine\" concept, captured by the RulesEngine interface:\n\t * essentially it is a rewriting system of data sequences (lists), which starting from an input\n\t * produces several outputs, applying rewriting rules.\n\t * \n\t * The following are considered optional for the purpose of being able to correct\n\t * the exercise, but still contribute to achieving the totality of the\n\t * score:\n\t * \n\t * - implementation of all factory methods (i.e., in the mandatory part it is\n\t * sufficient to implement all but one at will)\n\t * - the good design of the solution, using design solutions that lead to\n\t * succinct code that avoids repetitions\n\t * \n\t * Remove the comment from the initFactory method.\n\t * \n\t * Score indications:\n\t * - correctness of the mandatory part: 10 points\n\t * - correctness of the optional part: 3 points (additional factory method)\n\t * - quality of the solution: 4 points (for good design)\n\t * \n\t */\n\n\tprivate RulesEngineFactory factory;\n\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.factory = new RulesEngineFactoryImpl();\n\t}", "test_functions": [ "\[email protected]\n\tpublic void testApplyRule() {\n\t\t// test of the method that implements the application of a single rule\n\t\t// rule: 10 --> (11,12)\n\t\t// if the input is (1,10,100) and therefore has only one 10, we get a single solution, i.e. (1,11,12,100)\n\t\tassertEquals(List.of(List.of(1, 11, 12,100)),\n\t\t\tthis.factory.applyRule(new Pair<>(10, List.of(11, 12)), List.of(1, 10, 100)));\n\n\t\t// rule: a --> (b)\n\t\t// if the input is (a,a,a) we get 3 solutions, in each one we replace an a with b, in order\n\t\tassertEquals(List.of(List.of(\"b\", \"a\", \"a\"),List.of(\"a\", \"b\", \"a\"),List.of(\"a\", \"a\", \"b\")),\n\t\t\tthis.factory.applyRule(new Pair<>(\"a\", List.of(\"b\")), List.of(\"a\", \"a\", \"a\")));\n\n\t\t// rule: 10 --> ()\n\t\t// if the input is (1,10,100) we have only one solution, where 10 is replaced by nothing, i.e. it is removed\n\t\tassertEquals(List.of(List.of(1,100)),\n\t\t\tthis.factory.applyRule(new Pair<>(10, List.of()), List.of(1, 10, 100)));\n\n\t\t// rule: 10 --> (11,12,13)\n\t\t// if the input is (1,100) there is no solution\n\t\tassertEquals(List.of(),\n\t\t\tthis.factory.applyRule(new Pair<>(10, List.of(11, 12, 13)), List.of(1, 100)));\n\t}", "\[email protected]\n\tpublic void testSingle() {\n\t\t// singleRule creates a RulesEngine, which works with the logic of the method above, only that:\n\t\t// 1 - applies the rule from left to right as long as it can, so there is always only one solution\n\t\t// 2 - must allow to iterate the different solutions (without replication),\n\t\t// 3 - it must be possible to reset the input to start again\n\t\t\n\t\t// rule: a --> (b,c)\n\t\tvar res = this.factory.singleRuleEngine(new Pair<>(\"a\", List.of(\"b\", \"c\")));\n\t\t// input: (a,z,z)\n\t\tres.resetInput(List.of(\"a\",\"z\",\"z\"));\n\t\t// only one solution\n\t\tassertTrue(res.hasOtherSolutions());\n\t\tassertEquals(List.of(\"b\", \"c\", \"z\", \"z\"), res.nextSolution());\n\t\tassertFalse(res.hasOtherSolutions());\n\n\t\t// input: (a,z,a)\n\t\tres.resetInput(List.of(\"a\",\"z\",\"a\"));\n\t\t// only one solution, transforming both \"a\"s\n\t\tassertTrue(res.hasOtherSolutions());\n\t\tassertEquals(List.of(\"b\", \"c\", \"z\", \"b\", \"c\"), res.nextSolution());\n\t\tassertFalse(res.hasOtherSolutions());\n\n\t\t// input: (z, z)\n\t\tres.resetInput(List.of(\"z\", \"z\"));\n\t\t// no possible transformation, so I have only one solution, which does not modify the input\n\t\tassertTrue(res.hasOtherSolutions());\n\t\tassertEquals(List.of(\"z\", \"z\"), res.nextSolution());\n\t\tassertFalse(res.hasOtherSolutions());\n\t}", "\[email protected]\n\tpublic void testCascadingRules() {\n\t\t// This tests the case of two rules, where the result of the first one results in\n\t\t// a sequence that activates the second rule\n\t\t// a --> (b,c), and c-->d\n\t\t// in fact here, we have the same result that we would have with the rule: a-->b,d and c-->d\n\t\tvar res = this.factory.cascadingRulesEngine(\n\t\t\tnew Pair<>(\"a\", List.of(\"b\", \"c\")),\n\t\t\tnew Pair<>(\"c\", List.of(\"d\"))\n\t\t);\n\t\tres.resetInput(List.of(\"a\",\"z\"));\n\t\tassertTrue(res.hasOtherSolutions());\n\t\tassertEquals(List.of(\"b\", \"d\", \"z\"), res.nextSolution());\n\t\tassertFalse(res.hasOtherSolutions());\n\n\t\t// here the \"a\" becomes \"b,d\", and the \"c\" becomes \"d\"\n\t\tres.resetInput(List.of(\"a\",\"c\",\"z\"));\n\t\tassertTrue(res.hasOtherSolutions());\n\t\tassertEquals(List.of(\"b\", \"d\", \"d\", \"z\"), res.nextSolution());\n\t\tassertFalse(res.hasOtherSolutions());\n\t}", "\[email protected]\n\tpublic void testConflictingRules() {\n\t\t// This tests the case of two rules with the same \"head\", for each application of the rule\n\t\t// 2 cases are generated, whose solutions are then combined (eliminating duplicates).\n\t\t// That is, every time the rule has to be applied, one is applied with SingleRule,\n\t\t// the other with SingleRule, and the results are combined.\n\t\t\n\t\t// a --> b, and a-->c, d\n\t\tvar res = this.factory.conflictingRulesEngine(\n\t\t\tnew Pair<>(\"a\", List.of(\"b\")),\n\t\t\tnew Pair<>(\"a\", List.of(\"c\", \"d\"))\n\t\t);\n\t\tres.resetInput(List.of(\"a\",\"a\"));\n\t\t// 4 solutions, i.e. the combinations\n\t\tassertTrue(res.hasOtherSolutions());\n\t\tassertEquals(List.of(\"b\", \"b\"), res.nextSolution());\n\t\tassertTrue(res.hasOtherSolutions());\n\t\tassertEquals(List.of(\"b\", \"c\", \"d\"), res.nextSolution());\n\t\tassertTrue(res.hasOtherSolutions());\n\t\tassertEquals(List.of(\"c\", \"d\", \"b\"), res.nextSolution());\n\t\tassertTrue(res.hasOtherSolutions());\n\t\tassertEquals(List.of(\"c\", \"d\", \"c\", \"d\"), res.nextSolution());\n\t\tassertFalse(res.hasOtherSolutions());\n\t}" ] }, "content": "package a02b.sol1;\n\nimport static org.junit.Assert.*;\n\nimport java.util.*;\n\npublic class Test {\n\n\t/*\n\t * Implement the RulesEngineFactory interface as indicated in the initFactory method below.\n\t * Create a factory for a \"rules engine\" concept, captured by the RulesEngine interface:\n\t * essentially it is a rewriting system of data sequences (lists), which starting from an input\n\t * produces several outputs, applying rewriting rules.\n\t * \n\t * The following are considered optional for the purpose of being able to correct\n\t * the exercise, but still contribute to achieving the totality of the\n\t * score:\n\t * \n\t * - implementation of all factory methods (i.e., in the mandatory part it is\n\t * sufficient to implement all but one at will)\n\t * - the good design of the solution, using design solutions that lead to\n\t * succinct code that avoids repetitions\n\t * \n\t * Remove the comment from the initFactory method.\n\t * \n\t * Score indications:\n\t * - correctness of the mandatory part: 10 points\n\t * - correctness of the optional part: 3 points (additional factory method)\n\t * - quality of the solution: 4 points (for good design)\n\t * \n\t */\n\n\tprivate RulesEngineFactory factory;\n\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.factory = new RulesEngineFactoryImpl();\n\t}\n\n\[email protected]\n\tpublic void testApplyRule() {\n\t\t// test of the method that implements the application of a single rule\n\t\t// rule: 10 --> (11,12)\n\t\t// if the input is (1,10,100) and therefore has only one 10, we get a single solution, i.e. (1,11,12,100)\n\t\tassertEquals(List.of(List.of(1, 11, 12,100)),\n\t\t\tthis.factory.applyRule(new Pair<>(10, List.of(11, 12)), List.of(1, 10, 100)));\n\n\t\t// rule: a --> (b)\n\t\t// if the input is (a,a,a) we get 3 solutions, in each one we replace an a with b, in order\n\t\tassertEquals(List.of(List.of(\"b\", \"a\", \"a\"),List.of(\"a\", \"b\", \"a\"),List.of(\"a\", \"a\", \"b\")),\n\t\t\tthis.factory.applyRule(new Pair<>(\"a\", List.of(\"b\")), List.of(\"a\", \"a\", \"a\")));\n\n\t\t// rule: 10 --> ()\n\t\t// if the input is (1,10,100) we have only one solution, where 10 is replaced by nothing, i.e. it is removed\n\t\tassertEquals(List.of(List.of(1,100)),\n\t\t\tthis.factory.applyRule(new Pair<>(10, List.of()), List.of(1, 10, 100)));\n\n\t\t// rule: 10 --> (11,12,13)\n\t\t// if the input is (1,100) there is no solution\n\t\tassertEquals(List.of(),\n\t\t\tthis.factory.applyRule(new Pair<>(10, List.of(11, 12, 13)), List.of(1, 100)));\n\t}\n\n\[email protected]\n\tpublic void testSingle() {\n\t\t// singleRule creates a RulesEngine, which works with the logic of the method above, only that:\n\t\t// 1 - applies the rule from left to right as long as it can, so there is always only one solution\n\t\t// 2 - must allow to iterate the different solutions (without replication),\n\t\t// 3 - it must be possible to reset the input to start again\n\t\t\n\t\t// rule: a --> (b,c)\n\t\tvar res = this.factory.singleRuleEngine(new Pair<>(\"a\", List.of(\"b\", \"c\")));\n\t\t// input: (a,z,z)\n\t\tres.resetInput(List.of(\"a\",\"z\",\"z\"));\n\t\t// only one solution\n\t\tassertTrue(res.hasOtherSolutions());\n\t\tassertEquals(List.of(\"b\", \"c\", \"z\", \"z\"), res.nextSolution());\n\t\tassertFalse(res.hasOtherSolutions());\n\n\t\t// input: (a,z,a)\n\t\tres.resetInput(List.of(\"a\",\"z\",\"a\"));\n\t\t// only one solution, transforming both \"a\"s\n\t\tassertTrue(res.hasOtherSolutions());\n\t\tassertEquals(List.of(\"b\", \"c\", \"z\", \"b\", \"c\"), res.nextSolution());\n\t\tassertFalse(res.hasOtherSolutions());\n\n\t\t// input: (z, z)\n\t\tres.resetInput(List.of(\"z\", \"z\"));\n\t\t// no possible transformation, so I have only one solution, which does not modify the input\n\t\tassertTrue(res.hasOtherSolutions());\n\t\tassertEquals(List.of(\"z\", \"z\"), res.nextSolution());\n\t\tassertFalse(res.hasOtherSolutions());\n\t}\n\n\[email protected]\n\tpublic void testCascadingRules() {\n\t\t// This tests the case of two rules, where the result of the first one results in\n\t\t// a sequence that activates the second rule\n\t\t// a --> (b,c), and c-->d\n\t\t// in fact here, we have the same result that we would have with the rule: a-->b,d and c-->d\n\t\tvar res = this.factory.cascadingRulesEngine(\n\t\t\tnew Pair<>(\"a\", List.of(\"b\", \"c\")),\n\t\t\tnew Pair<>(\"c\", List.of(\"d\"))\n\t\t);\n\t\tres.resetInput(List.of(\"a\",\"z\"));\n\t\tassertTrue(res.hasOtherSolutions());\n\t\tassertEquals(List.of(\"b\", \"d\", \"z\"), res.nextSolution());\n\t\tassertFalse(res.hasOtherSolutions());\n\n\t\t// here the \"a\" becomes \"b,d\", and the \"c\" becomes \"d\"\n\t\tres.resetInput(List.of(\"a\",\"c\",\"z\"));\n\t\tassertTrue(res.hasOtherSolutions());\n\t\tassertEquals(List.of(\"b\", \"d\", \"d\", \"z\"), res.nextSolution());\n\t\tassertFalse(res.hasOtherSolutions());\n\t}\n\n\[email protected]\n\tpublic void testConflictingRules() {\n\t\t// This tests the case of two rules with the same \"head\", for each application of the rule\n\t\t// 2 cases are generated, whose solutions are then combined (eliminating duplicates).\n\t\t// That is, every time the rule has to be applied, one is applied with SingleRule,\n\t\t// the other with SingleRule, and the results are combined.\n\t\t\n\t\t// a --> b, and a-->c, d\n\t\tvar res = this.factory.conflictingRulesEngine(\n\t\t\tnew Pair<>(\"a\", List.of(\"b\")),\n\t\t\tnew Pair<>(\"a\", List.of(\"c\", \"d\"))\n\t\t);\n\t\tres.resetInput(List.of(\"a\",\"a\"));\n\t\t// 4 solutions, i.e. the combinations\n\t\tassertTrue(res.hasOtherSolutions());\n\t\tassertEquals(List.of(\"b\", \"b\"), res.nextSolution());\n\t\tassertTrue(res.hasOtherSolutions());\n\t\tassertEquals(List.of(\"b\", \"c\", \"d\"), res.nextSolution());\n\t\tassertTrue(res.hasOtherSolutions());\n\t\tassertEquals(List.of(\"c\", \"d\", \"b\"), res.nextSolution());\n\t\tassertTrue(res.hasOtherSolutions());\n\t\tassertEquals(List.of(\"c\", \"d\", \"c\", \"d\"), res.nextSolution());\n\t\tassertFalse(res.hasOtherSolutions());\n\t}\n}", "filename": "Test.java" }
2023
a01a
[ { "content": "package a01a.sol1;\n\nimport java.util.function.*;\n\npublic interface TimetableFactory {\n\t\n\t\n\tTimetable empty();\n\n\t\n\tTimetable single(String activity, String day);\n\n\t\n\tTimetable join(Timetable table1, Timetable table2);\n\n\t\n\tTimetable cut(Timetable table, BiFunction<String, String, Integer> bounds);\n\n}", "filename": "TimetableFactory.java" }, { "content": "package a01a.sol1;\n\nimport java.util.*;\n\n\npublic interface Timetable {\n\t\n\t\n\tTimetable addHour(String activity, String day);\n\t\n\t\n\tSet<String> activities();\n\n\t\n\tSet<String> days();\n\n\t\n\tint getSingleData(String activity, String day);\n\n\t\n\tint sums(Set<String> activities, Set<String> days);\n}", "filename": "Timetable.java" }, { "content": "package a01a.sol1;\n\nimport java.util.Objects;\n\n\n\npublic class Pair<E1,E2> {\n\t\n\tprivate final E1 e1;\n\tprivate final E2 e2;\n\t\n\tpublic Pair(E1 x, E2 y) {\n\t\tsuper();\n\t\tthis.e1 = x;\n\t\tthis.e2 = y;\n\t}\n\n\tpublic E1 get1() {\n\t\treturn e1;\n\t}\n\n\tpublic E2 get2() {\n\t\treturn e2;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Objects.hash(e1, e2);\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj) {\n\t\t\treturn true;\n\t\t}\n\t\tif (obj == null) {\n\t\t\treturn false;\n\t\t}\n\t\tif (getClass() != obj.getClass()) {\n\t\t\treturn false;\n\t\t}\n\t\tPair other = (Pair) obj;\n\t\treturn Objects.equals(e1, other.e1) && Objects.equals(e2, other.e2);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Pair [e1=\" + e1 + \", e2=\" + e2 + \"]\";\n\t}\n\t\n\t\n\n}", "filename": "Pair.java" } ]
[ { "content": "package a01a.sol1;\n\nimport java.util.*;\nimport java.util.stream.*;\n\nimport java.util.function.*;\n\npublic class TimetableFactoryImpl implements TimetableFactory {\n\n private static <T> Set<T> addToSet(Set<T> s, T t){\n return concatSet(s, Set.of(t));\n }\n\n private static <T> Set<T> concatSet(Set<T> s, Set<T> s2){\n return Stream.concat(s.stream(), s2.stream()).collect(Collectors.toSet());\n }\n\n // An implementation of a Timetable as an immutable class with activities, days, and an association of activities+days to hours\n // Since it is immutable, we use a record, which automatically gives fields, getters, constructors, hashcode, equals, toString.\n private static record TimetableData(Set<String> activities, Set<String> days, BiFunction<String, String, Integer> data) implements Timetable {\n\n @Override\n public int getSingleData(String activity, String day) {\n return data.apply(activity, day);\n }\n\n @Override\n public Timetable addHour(String activity, String day) {\n return new TimetableData(\n addToSet(activities, activity), \n addToSet(days, day), \n (a,d) -> data.apply(a,d) + (activity.equals(a) && day.equals(d) ? 1 : 0)\n );\n }\n\n private int statistics(BiPredicate<String, String> predicate) {\n return activities.stream()\n .flatMap(a -> days.stream()\n .filter(d -> predicate.test(a,d))\n .map(d -> this.getSingleData(a, d)))\n .collect(Collectors.summingInt(i -> i));\n }\n\n @Override\n public int sums(Set<String> activies, Set<String> days) {\n return statistics((a,d) -> activies.contains(a) && days.contains(d));\n }\n }\n\n @Override\n public Timetable empty() {\n return new TimetableData(Set.of(), Set.of(), (a,d) -> 0);\n }\n\n @Override\n public Timetable single(String activity, String day) {\n return empty().addHour(activity, day);\n }\n\n @Override\n public Timetable join(Timetable table1, Timetable table2) {\n return new TimetableData(\n concatSet(table1.activities(), table2.activities()),\n concatSet(table1.days(), table2.days()),\n (a,d) -> table1.getSingleData(a, d) + table2.getSingleData(a, d)\n );\n }\n\n @Override\n public Timetable cut(Timetable table, BiFunction<String, String, Integer> bounds) {\n return new TimetableData(\n table.activities(),\n table.days(),\n (a, d) -> Math.min(table.getSingleData(a, d), bounds.apply(a, d)));\n }\n \n}", "filename": "TimetableFactoryImpl.java" } ]
{ "components": { "imports": "package a01a.sol1;\n\nimport static org.junit.Assert.*;\n\nimport java.util.*;", "private_init": "\t/*\n\t * Implement the TimetableFactory interface as indicated in the initFactory\n\t * method below. Create a factory for a timetable concept, captured by the\n\t * Timetable interface: essentially it is a table that associates a number of\n\t * hours spent (>=0) with each day and type of activity.\n\t * \n\t * The following are considered optional for the purpose of being able to correct\n\t * the exercise, but still contribute to achieving the totality of the score:\n\t * \n\t * - implementation of all factory methods (i.e., in the\n\t * mandatory part it is sufficient to implement all of them except one at will --\n\t * the first, empty, is mandatory)\n\t * - the good design of the solution, using design solutions that lead to\n\t * succinct code that avoids repetitions\n\t * \n\t * Remove the comment from the initFactory method.\n\t * \n\t * Scoring indications:\n\t * - correctness of the mandatory part: 10 points\n\t * - correctness of the optional part: 3 points (additional factory method)\n\t * - quality of the solution: 4 points (for good design)\n\t * \n\t */\n\n\tprivate TimetableFactory factory;\n\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.factory = new TimetableFactoryImpl();\n\t}", "test_functions": [ "\[email protected]\n\tpublic void testEmpty() {\n\t\t// an empty table, without days and activities\n\t\tTimetable table = this.factory.empty();\n\t\tassertEquals(Set.of(), table.activities());\n\t\tassertEquals(Set.of(), table.days());\n\t\tassertEquals(0, table.getSingleData(\"act1\", \"day2\"));\n\t\tassertEquals(0, table.sums(Set.of(\"act\"), Set.of(\"day\")));\n\n\t\t// now a table with one hour of activity \"act\" on day \"day\"\n\t\ttable = table.addHour(\"act\", \"day\");\n\t\tassertEquals(Set.of(\"act\"), table.activities());\n\t\tassertEquals(Set.of(\"day\"), table.days());\n\t\tassertEquals(1, table.getSingleData(\"act\", \"day\"));\n\t\tassertEquals(0, table.getSingleData(\"act0\", \"day0\")); // no\n\t\tassertEquals(1, table.sums(Set.of(\"act\"), Set.of(\"day\"))); // hours of \"act\" on day \"day\"\n\t\tassertEquals(0, table.sums(Set.of(\"act\"), Set.of(\"day0\"))); // no\n\t}", "\[email protected]\n\tpublic void testSingle() {\n\t\t// single behaves like an empty one with the addition of an hour, as above\n\t\tTimetable table = this.factory.single(\"act1\", \"day1\");\n\t\tassertEquals(Set.of(\"act1\"), table.activities());\n\t\tassertEquals(Set.of(\"day1\"), table.days());\n\t\tassertEquals(1, table.getSingleData(\"act1\", \"day1\"));\n\t\tassertEquals(0, table.getSingleData(\"act0\", \"day0\"));\n\t\tassertEquals(1, table.sums(Set.of(\"act1\"), Set.of(\"day1\")));\n\t\tassertEquals(0, table.sums(Set.of(\"act1\"), Set.of()));\n\n\t\t// I add 3 hours to table, it becomes 4\n\t\ttable = table.addHour(\"act1\", \"day1\"); // note now I have 2 hours for act1 in day1\n\t\ttable = table.addHour(\"act1\", \"day2\");\n\t\ttable = table.addHour(\"act2\", \"day2\");\n\t\tassertEquals(Set.of(\"act1\", \"act2\"), table.activities());\n\t\tassertEquals(Set.of(\"day1\", \"day2\"), table.days());\n\t\tassertEquals(2, table.getSingleData(\"act1\", \"day1\"));\n\t\tassertEquals(1, table.getSingleData(\"act1\", \"day2\"));\n\t\tassertEquals(1, table.getSingleData(\"act2\", \"day2\"));\n\t\tassertEquals(0, table.getSingleData(\"act2\", \"day1\"));\n\t\tassertEquals(2, table.sums(Set.of(\"act1\"), Set.of(\"day1\")));\n\t\tassertEquals(0, table.sums(Set.of(\"act2\"), Set.of(\"day1\")));\n\t\tassertEquals(4, table.sums(Set.of(\"act1\", \"act2\"), Set.of(\"day1\", \"day2\"))); // total hours\n\t}", "\[email protected]\n\tpublic void testJoin() {\n\t\tTimetable table1 = this.factory.empty()\n\t\t\t.addHour(\"act1\", \"day1\")\n\t\t\t.addHour(\"act1\", \"day1\")\n\t\t\t.addHour(\"act2\", \"day2\");\n\n\t\tTimetable table2 = this.factory.empty()\n\t\t\t.addHour(\"act2\", \"day1\")\n\t\t\t.addHour(\"act2\", \"day2\")\n\t\t\t.addHour(\"act1\", \"day3\")\n\t\t\t.addHour(\"act3\", \"day3\");\n\n\t\t// I join the hours of two different tables: they are added up\n\t\tTimetable table = this.factory.join(table1, table2);\n\t\tassertEquals(Set.of(\"act1\", \"act2\", \"act3\"), table.activities());\n\t\tassertEquals(Set.of(\"day1\", \"day2\", \"day3\"), table.days());\n\t\tassertEquals(2, table.getSingleData(\"act1\", \"day1\"));\n\t\tassertEquals(2, table.getSingleData(\"act2\", \"day2\"));\n\t\tassertEquals(1, table.getSingleData(\"act1\", \"day3\"));\n\t\tassertEquals(0, table.getSingleData(\"act2\", \"day3\"));\n\t\t\n\t\tassertEquals(7, table.sums(Set.of(\"act1\", \"act2\", \"act3\"), Set.of(\"day1\", \"day2\", \"day3\")));\n\t\tassertEquals(6, table.sums(Set.of(\"act1\", \"act2\"), Set.of(\"day1\", \"day2\", \"day3\")));\n\t\tassertEquals(2, table.sums(Set.of(\"act1\", \"act2\", \"act3\"), Set.of(\"day3\")));\n\t\t\n\t\t// I can add a single hour to the usual\n\t\ttable = table.addHour(\"act1\", \"day1\");\n\t\tassertEquals(8, table.sums(Set.of(\"act1\", \"act2\", \"act3\"), Set.of(\"day1\", \"day2\", \"day3\")));\n\t\t\n\t}", "\[email protected]\n\tpublic void testBounds() {\n\t\tTimetable table = this.factory.empty()\n\t\t\t.addHour(\"act1\", \"day1\")\n\t\t\t.addHour(\"act1\", \"day1\")\n\t\t\t.addHour(\"act1\", \"day1\")\n\t\t\t.addHour(\"act1\", \"day2\")\n\t\t\t.addHour(\"act1\", \"day3\")\n\t\t\t.addHour(\"act1\", \"day3\")\n\t\t\t.addHour(\"act2\", \"day1\")\n\t\t\t.addHour(\"act2\", \"day1\")\n\t\t\t.addHour(\"act3\", \"day2\")\n\t\t\t.addHour(\"act3\", \"day3\");\n\n\t\t// given a table with 10 hours as above, I remove them all\n\t\ttable = this.factory.cut(table, (a,d) -> 0);\n\t\tassertEquals(Set.of(\"act1\", \"act2\", \"act3\"), table.activities());\n\t\tassertEquals(Set.of(\"day1\", \"day2\", \"day3\"), table.days());\n\t\tassertEquals(0, table.sums(Set.of(\"act1\", \"act2\", \"act3\"), Set.of(\"day1\", \"day2\", \"day3\")));\n\n\t\ttable = this.factory.empty()\n\t\t\t.addHour(\"act1\", \"day1\")\n\t\t\t.addHour(\"act1\", \"day1\")\n\t\t\t.addHour(\"act1\", \"day1\")\n\t\t\t.addHour(\"act1\", \"day2\")\n\t\t\t.addHour(\"act1\", \"day3\")\n\t\t\t.addHour(\"act1\", \"day3\")\n\t\t\t.addHour(\"act2\", \"day1\")\n\t\t\t.addHour(\"act2\", \"day1\")\n\t\t\t.addHour(\"act3\", \"day2\")\n\t\t\t.addHour(\"act3\", \"day3\");\n\n\t\t// given a table with 10 hours as above, I allow a maximum of 1 per day per activity, they become 6\n\t\ttable = this.factory.cut(table, (a,d) -> 1);\n\t\tassertEquals(Set.of(\"act1\", \"act2\", \"act3\"), table.activities());\n\t\tassertEquals(Set.of(\"day1\", \"day2\", \"day3\"), table.days());\n\t\tassertEquals(1, table.getSingleData(\"act1\", \"day1\"));\n\t\tassertEquals(6, table.sums(Set.of(\"act1\", \"act2\", \"act3\"), Set.of(\"day1\", \"day2\", \"day3\")));\n\t}" ] }, "content": "package a01a.sol1;\n\nimport static org.junit.Assert.*;\n\nimport java.util.*;\n\npublic class Test {\n\n\t/*\n\t * Implement the TimetableFactory interface as indicated in the initFactory\n\t * method below. Create a factory for a timetable concept, captured by the\n\t * Timetable interface: essentially it is a table that associates a number of\n\t * hours spent (>=0) with each day and type of activity.\n\t * \n\t * The following are considered optional for the purpose of being able to correct\n\t * the exercise, but still contribute to achieving the totality of the score:\n\t * \n\t * - implementation of all factory methods (i.e., in the\n\t * mandatory part it is sufficient to implement all of them except one at will --\n\t * the first, empty, is mandatory)\n\t * - the good design of the solution, using design solutions that lead to\n\t * succinct code that avoids repetitions\n\t * \n\t * Remove the comment from the initFactory method.\n\t * \n\t * Scoring indications:\n\t * - correctness of the mandatory part: 10 points\n\t * - correctness of the optional part: 3 points (additional factory method)\n\t * - quality of the solution: 4 points (for good design)\n\t * \n\t */\n\n\tprivate TimetableFactory factory;\n\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.factory = new TimetableFactoryImpl();\n\t}\n\n\[email protected]\n\tpublic void testEmpty() {\n\t\t// an empty table, without days and activities\n\t\tTimetable table = this.factory.empty();\n\t\tassertEquals(Set.of(), table.activities());\n\t\tassertEquals(Set.of(), table.days());\n\t\tassertEquals(0, table.getSingleData(\"act1\", \"day2\"));\n\t\tassertEquals(0, table.sums(Set.of(\"act\"), Set.of(\"day\")));\n\n\t\t// now a table with one hour of activity \"act\" on day \"day\"\n\t\ttable = table.addHour(\"act\", \"day\");\n\t\tassertEquals(Set.of(\"act\"), table.activities());\n\t\tassertEquals(Set.of(\"day\"), table.days());\n\t\tassertEquals(1, table.getSingleData(\"act\", \"day\"));\n\t\tassertEquals(0, table.getSingleData(\"act0\", \"day0\")); // no\n\t\tassertEquals(1, table.sums(Set.of(\"act\"), Set.of(\"day\"))); // hours of \"act\" on day \"day\"\n\t\tassertEquals(0, table.sums(Set.of(\"act\"), Set.of(\"day0\"))); // no\n\t}\n\n\[email protected]\n\tpublic void testSingle() {\n\t\t// single behaves like an empty one with the addition of an hour, as above\n\t\tTimetable table = this.factory.single(\"act1\", \"day1\");\n\t\tassertEquals(Set.of(\"act1\"), table.activities());\n\t\tassertEquals(Set.of(\"day1\"), table.days());\n\t\tassertEquals(1, table.getSingleData(\"act1\", \"day1\"));\n\t\tassertEquals(0, table.getSingleData(\"act0\", \"day0\"));\n\t\tassertEquals(1, table.sums(Set.of(\"act1\"), Set.of(\"day1\")));\n\t\tassertEquals(0, table.sums(Set.of(\"act1\"), Set.of()));\n\n\t\t// I add 3 hours to table, it becomes 4\n\t\ttable = table.addHour(\"act1\", \"day1\"); // note now I have 2 hours for act1 in day1\n\t\ttable = table.addHour(\"act1\", \"day2\");\n\t\ttable = table.addHour(\"act2\", \"day2\");\n\t\tassertEquals(Set.of(\"act1\", \"act2\"), table.activities());\n\t\tassertEquals(Set.of(\"day1\", \"day2\"), table.days());\n\t\tassertEquals(2, table.getSingleData(\"act1\", \"day1\"));\n\t\tassertEquals(1, table.getSingleData(\"act1\", \"day2\"));\n\t\tassertEquals(1, table.getSingleData(\"act2\", \"day2\"));\n\t\tassertEquals(0, table.getSingleData(\"act2\", \"day1\"));\n\t\tassertEquals(2, table.sums(Set.of(\"act1\"), Set.of(\"day1\")));\n\t\tassertEquals(0, table.sums(Set.of(\"act2\"), Set.of(\"day1\")));\n\t\tassertEquals(4, table.sums(Set.of(\"act1\", \"act2\"), Set.of(\"day1\", \"day2\"))); // total hours\n\t}\n\n\[email protected]\n\tpublic void testJoin() {\n\t\tTimetable table1 = this.factory.empty()\n\t\t\t.addHour(\"act1\", \"day1\")\n\t\t\t.addHour(\"act1\", \"day1\")\n\t\t\t.addHour(\"act2\", \"day2\");\n\n\t\tTimetable table2 = this.factory.empty()\n\t\t\t.addHour(\"act2\", \"day1\")\n\t\t\t.addHour(\"act2\", \"day2\")\n\t\t\t.addHour(\"act1\", \"day3\")\n\t\t\t.addHour(\"act3\", \"day3\");\n\n\t\t// I join the hours of two different tables: they are added up\n\t\tTimetable table = this.factory.join(table1, table2);\n\t\tassertEquals(Set.of(\"act1\", \"act2\", \"act3\"), table.activities());\n\t\tassertEquals(Set.of(\"day1\", \"day2\", \"day3\"), table.days());\n\t\tassertEquals(2, table.getSingleData(\"act1\", \"day1\"));\n\t\tassertEquals(2, table.getSingleData(\"act2\", \"day2\"));\n\t\tassertEquals(1, table.getSingleData(\"act1\", \"day3\"));\n\t\tassertEquals(0, table.getSingleData(\"act2\", \"day3\"));\n\t\t\n\t\tassertEquals(7, table.sums(Set.of(\"act1\", \"act2\", \"act3\"), Set.of(\"day1\", \"day2\", \"day3\")));\n\t\tassertEquals(6, table.sums(Set.of(\"act1\", \"act2\"), Set.of(\"day1\", \"day2\", \"day3\")));\n\t\tassertEquals(2, table.sums(Set.of(\"act1\", \"act2\", \"act3\"), Set.of(\"day3\")));\n\t\t\n\t\t// I can add a single hour to the usual\n\t\ttable = table.addHour(\"act1\", \"day1\");\n\t\tassertEquals(8, table.sums(Set.of(\"act1\", \"act2\", \"act3\"), Set.of(\"day1\", \"day2\", \"day3\")));\n\t\t\n\t}\n\n\[email protected]\n\tpublic void testBounds() {\n\t\tTimetable table = this.factory.empty()\n\t\t\t.addHour(\"act1\", \"day1\")\n\t\t\t.addHour(\"act1\", \"day1\")\n\t\t\t.addHour(\"act1\", \"day1\")\n\t\t\t.addHour(\"act1\", \"day2\")\n\t\t\t.addHour(\"act1\", \"day3\")\n\t\t\t.addHour(\"act1\", \"day3\")\n\t\t\t.addHour(\"act2\", \"day1\")\n\t\t\t.addHour(\"act2\", \"day1\")\n\t\t\t.addHour(\"act3\", \"day2\")\n\t\t\t.addHour(\"act3\", \"day3\");\n\n\t\t// given a table with 10 hours as above, I remove them all\n\t\ttable = this.factory.cut(table, (a,d) -> 0);\n\t\tassertEquals(Set.of(\"act1\", \"act2\", \"act3\"), table.activities());\n\t\tassertEquals(Set.of(\"day1\", \"day2\", \"day3\"), table.days());\n\t\tassertEquals(0, table.sums(Set.of(\"act1\", \"act2\", \"act3\"), Set.of(\"day1\", \"day2\", \"day3\")));\n\n\t\ttable = this.factory.empty()\n\t\t\t.addHour(\"act1\", \"day1\")\n\t\t\t.addHour(\"act1\", \"day1\")\n\t\t\t.addHour(\"act1\", \"day1\")\n\t\t\t.addHour(\"act1\", \"day2\")\n\t\t\t.addHour(\"act1\", \"day3\")\n\t\t\t.addHour(\"act1\", \"day3\")\n\t\t\t.addHour(\"act2\", \"day1\")\n\t\t\t.addHour(\"act2\", \"day1\")\n\t\t\t.addHour(\"act3\", \"day2\")\n\t\t\t.addHour(\"act3\", \"day3\");\n\n\t\t// given a table with 10 hours as above, I allow a maximum of 1 per day per activity, they become 6\n\t\ttable = this.factory.cut(table, (a,d) -> 1);\n\t\tassertEquals(Set.of(\"act1\", \"act2\", \"act3\"), table.activities());\n\t\tassertEquals(Set.of(\"day1\", \"day2\", \"day3\"), table.days());\n\t\tassertEquals(1, table.getSingleData(\"act1\", \"day1\"));\n\t\tassertEquals(6, table.sums(Set.of(\"act1\", \"act2\", \"act3\"), Set.of(\"day1\", \"day2\", \"day3\")));\n\t}\n}", "filename": "Test.java" }
2023
a02a
[ { "content": "package a02a.sol1;\n\nimport java.util.*;\n\n\npublic interface ListBuilderFactory {\n\n \n <T> ListBuilder<T> empty();\n\n \n <T> ListBuilder<T> fromElement(T t);\n\n \n <T> ListBuilder<T> fromList(List<T> list);\n\n \n <T> ListBuilder<T> join(T start, T stop, List<ListBuilder<T>> builderList);\n}", "filename": "ListBuilderFactory.java" }, { "content": "package a02a.sol1;\n\nimport java.util.*;\n\n\npublic interface ListBuilder<T> {\n\n \n ListBuilder<T> add(List<T> list);\n\n \n ListBuilder<T> concat(ListBuilder<T> lb);\n\n \n ListBuilder<T> replaceAll(T t, ListBuilder<T> lb);\n\n \n ListBuilder<T> reverse();\n\n \n List<T> build();\n}", "filename": "ListBuilder.java" }, { "content": "package a02a.sol1;\n\nimport java.util.Objects;\n\n\n\npublic class Pair<E1,E2> {\n\t\n\tprivate final E1 e1;\n\tprivate final E2 e2;\n\t\n\tpublic Pair(E1 x, E2 y) {\n\t\tsuper();\n\t\tthis.e1 = x;\n\t\tthis.e2 = y;\n\t}\n\n\tpublic E1 get1() {\n\t\treturn e1;\n\t}\n\n\tpublic E2 get2() {\n\t\treturn e2;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Objects.hash(e1, e2);\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj) {\n\t\t\treturn true;\n\t\t}\n\t\tif (obj == null) {\n\t\t\treturn false;\n\t\t}\n\t\tif (getClass() != obj.getClass()) {\n\t\t\treturn false;\n\t\t}\n\t\tPair other = (Pair) obj;\n\t\treturn Objects.equals(e1, other.e1) && Objects.equals(e2, other.e2);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Pair [e1=\" + e1 + \", e2=\" + e2 + \"]\";\n\t}\n\t\n\t\n\n}", "filename": "Pair.java" } ]
[ { "content": "package a02a.sol1;\n\nimport java.util.*;\nimport java.util.stream.*;\nimport java.util.function.Function;\n\npublic class ListBuilderFactoryImpl implements ListBuilderFactory {\n\n // a utility function, essentially a flatMap for builders\n private <R,T> ListBuilder<R> flatMap(ListBuilder<T> builder, Function<T, ListBuilder<R>> fun) {\n return new ListBuilderImpl<>(builder.build().stream().flatMap(t -> fun.apply(t).build().stream()));\n }\n\n // A builder can just be an immutable wrapper of a list!\n private class ListBuilderImpl<T> implements ListBuilder<T> {\n private final List<T> list;\n\n public ListBuilderImpl(Stream<T> stream){\n this.list = stream.toList();\n }\n\n @Override\n public ListBuilder<T> add(List<T> list) {\n return new ListBuilderImpl<>(Stream.concat(this.list.stream(), list.stream()));\n }\n\n @Override\n public ListBuilder<T> concat(ListBuilder<T> lb) {\n return add(lb.build());\n }\n\n @Override\n public ListBuilder<T> replaceAll(T t, ListBuilder<T> lb) {\n return flatMap(this, tt -> tt.equals(t) ? lb : fromElement(tt));\n }\n\n @Override\n public ListBuilder<T> reverse() {\n var l2 = new ArrayList<>(list);\n Collections.reverse(l2);\n return new ListBuilderImpl<>(l2.stream());\n }\n\n @Override\n public List<T> build() {\n return this.list;\n }\n\n }\n\n @Override\n public <T> ListBuilder<T> empty() {\n return new ListBuilderImpl<>(Stream.empty());\n }\n\n @Override\n public <T> ListBuilder<T> fromElement(T t) {\n return new ListBuilderImpl<>(Stream.of(t));\n }\n\n @Override\n public <T> ListBuilder<T> fromList(List<T> list) {\n return new ListBuilderImpl<>(list.stream());\n }\n\n\n @Override\n public <T> ListBuilder<T> join(T start, T stop, List<ListBuilder<T>> list) {\n return this\n .fromElement(start)\n .add(list.stream().flatMap(lb -> lb.build().stream()).toList())\n .add(List.of(stop));\n }\n}", "filename": "ListBuilderFactoryImpl.java" } ]
{ "components": { "imports": "package a02a.sol1;\n\nimport static org.junit.Assert.*;\n\nimport java.util.*;", "private_init": "\t/*\n\t * Implement the ListBuilderFactory interface as indicated in the initFactory method\n\t * below. Create a factory for a ListBuilder concept,\n\t * i.e., an immutable object that can be used to facilitate the creation of lists\n\t * with an articulated structure (intent of the Builder pattern).\n\t * \n\t * The following are considered optional for the purpose of being able to correct\n\t * the exercise, but still contribute to achieving the totality of the\n\t * score:\n\t * \n\t * - implementation of all methods of the factory (i.e., in the\n\t * mandatory part it is sufficient to implement all but one at will --\n\t * the first 3 are still mandatory)\n\t * - the good design of the solution, using design solutions\n\t * that lead to\n\t * succinct code that avoids repetition\n\t * \n\t * Remove the comment from the initFactory method.\n\t * \n\t * Score indications:\n\t * - correctness of the mandatory part: 10 points\n\t * - correctness of the optional part: 3 points (additional method of the factory)\n\t * - quality of the solution: 4 points (for good design)\n\t * \n\t */\n\n\tprivate ListBuilderFactory factory;\n\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.factory = new ListBuilderFactoryImpl();\n\t}", "test_functions": [ "\[email protected]\n\tpublic void testEmpty() {\n\t\t// empty() represents the builder of an empty list\n\t\tListBuilder<Integer> empty = this.factory.<Integer>empty();\n\t\tassertEquals(List.of(), empty.build());\n\t\t// if I add 10 and 20 it becomes the builder of a list (10, 20)\n\t\tassertEquals(List.of(10, 20),\n\t\t\t\tempty.add(List.of(10, 20))\n\t\t\t\t\t\t.build());\n\t\t// I can do two consecutive adds, concatenating the calls\n\t\tassertEquals(List.of(10, 20, 30),\n\t\t\t\tempty.add(List.of(10, 20))\n\t\t\t\t\t\t.add(List.of(30))\n\t\t\t\t\t\t.build());\n\t\t// with concat I get a builder that represents the concatenation of the lists\n\t\tassertEquals(List.of(10, 20, 30),\n\t\t\t\tempty.add(List.of(10, 20))\n\t\t\t\t\t\t.concat(empty.add(List.of(30)))\n\t\t\t\t\t\t.build());\n\t\t// another example with concat\n\t\tassertEquals(List.of(10, 20, 30),\n\t\t\t\tempty.add(List.of(10, 20))\n\t\t\t\t\t\t.concat(empty.add(List.of(30)))\n\t\t\t\t\t\t.build());\n\t}", "\[email protected]\n\tpublic void testFromElement() {\n\t\t// fromElement() represents the builder of a list with one element\n\t\tListBuilder<Integer> one = this.factory.fromElement(1);\n\t\t// add and concat work as expected\n\t\tassertEquals(List.of(1), one.build());\n\t\tassertEquals(List.of(1, 2, 3, 4),\n\t\t\t\tone.add(List.of(2, 3, 4)).build());\n\t\tassertEquals(List.of(1, 2, 1),\n\t\t\t\tone.concat(this.factory.fromElement(2))\n\t\t\t\t\t\t.concat(one)\n\t\t\t\t\t\t.build());\n\t}", "\[email protected]\n\tpublic void testBasicFromList() {\n\t\t// fromList() represents the builder of a list with n elements\n\t\tListBuilder<Integer> l = this.factory.fromList(List.of(1, 2, 3));\n\t\tassertEquals(List.of(1, 2, 3), l.build());\n\t\t// concat work as expected\n\t\tassertEquals(List.of(1, 2, 3, 1, 2, 3),\n\t\t\t\tl.concat(l).build());\n\t\t// replaceAll here replaces the \"1\"s with pairs \"-1, -2\"\n\t\tassertEquals(List.of(-1, -2, 2, 3, -1, -2, 2, 3),\n\t\t\t\tl.concat(l)\n\t\t\t\t\t\t.replaceAll(1, this.factory.fromList(List.of(-1, -2)))\n\t\t\t\t\t\t.build());\n\t\t// if there is no match, replaceAll does nothing\n\t\tassertEquals(List.of(1, 2, 3, 1, 2, 3),\n\t\t\t\tl.concat(l)\n\t\t\t\t\t\t.replaceAll(10, this.factory.fromList(List.of(-1, -2)))\n\t\t\t\t\t\t.build());\n\t}", "\[email protected]\n\tpublic void testReverseFromList() {\n\t\tListBuilder<Integer> l = this.factory.fromList(List.of(1, 2, 3));\n\t\tassertEquals(List.of(1, 2, 3), l.build());\n\t\t// reverse makes you get a builder that represents the inverted list\n\t\tassertEquals(List.of(3, 2, 1), l.reverse().build());\n\t\tassertEquals(List.of(1, 2, 3), l.reverse().reverse().build());\n\t\tassertEquals(List.of(1, 2, 3, 3, 2, 1),\n\t\t\t\tl.reverse().reverse().concat(l.reverse()).build());\n\t}", "\[email protected]\n\tpublic void testJoin() {\n \t\t// join can be used to concatenate multiple builders, with an initial and a final element\n\t\tassertEquals(List.of(\"(\", \"1\", \"2\", \"3\", \"4\",\")\"),\n\t\t\t\tthis.factory.join(\"(\", \")\", \n\t\t\t\t\t\tList.of(this.factory.fromElement(\"1\"), \n\t\t\t\t\t\t\t\tthis.factory.fromElement(\"2\"),\n\t\t\t\t\t\t\t\tthis.factory.fromList(List.of(\"3\",\"4\")))).build());\n\t}" ] }, "content": "package a02a.sol1;\n\nimport static org.junit.Assert.*;\n\nimport java.util.*;\n\npublic class Test {\n\n\t/*\n\t * Implement the ListBuilderFactory interface as indicated in the initFactory method\n\t * below. Create a factory for a ListBuilder concept,\n\t * i.e., an immutable object that can be used to facilitate the creation of lists\n\t * with an articulated structure (intent of the Builder pattern).\n\t * \n\t * The following are considered optional for the purpose of being able to correct\n\t * the exercise, but still contribute to achieving the totality of the\n\t * score:\n\t * \n\t * - implementation of all methods of the factory (i.e., in the\n\t * mandatory part it is sufficient to implement all but one at will --\n\t * the first 3 are still mandatory)\n\t * - the good design of the solution, using design solutions\n\t * that lead to\n\t * succinct code that avoids repetition\n\t * \n\t * Remove the comment from the initFactory method.\n\t * \n\t * Score indications:\n\t * - correctness of the mandatory part: 10 points\n\t * - correctness of the optional part: 3 points (additional method of the factory)\n\t * - quality of the solution: 4 points (for good design)\n\t * \n\t */\n\n\tprivate ListBuilderFactory factory;\n\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.factory = new ListBuilderFactoryImpl();\n\t}\n\n\[email protected]\n\tpublic void testEmpty() {\n\t\t// empty() represents the builder of an empty list\n\t\tListBuilder<Integer> empty = this.factory.<Integer>empty();\n\t\tassertEquals(List.of(), empty.build());\n\t\t// if I add 10 and 20 it becomes the builder of a list (10, 20)\n\t\tassertEquals(List.of(10, 20),\n\t\t\t\tempty.add(List.of(10, 20))\n\t\t\t\t\t\t.build());\n\t\t// I can do two consecutive adds, concatenating the calls\n\t\tassertEquals(List.of(10, 20, 30),\n\t\t\t\tempty.add(List.of(10, 20))\n\t\t\t\t\t\t.add(List.of(30))\n\t\t\t\t\t\t.build());\n\t\t// with concat I get a builder that represents the concatenation of the lists\n\t\tassertEquals(List.of(10, 20, 30),\n\t\t\t\tempty.add(List.of(10, 20))\n\t\t\t\t\t\t.concat(empty.add(List.of(30)))\n\t\t\t\t\t\t.build());\n\t\t// another example with concat\n\t\tassertEquals(List.of(10, 20, 30),\n\t\t\t\tempty.add(List.of(10, 20))\n\t\t\t\t\t\t.concat(empty.add(List.of(30)))\n\t\t\t\t\t\t.build());\n\t}\n\n\[email protected]\n\tpublic void testFromElement() {\n\t\t// fromElement() represents the builder of a list with one element\n\t\tListBuilder<Integer> one = this.factory.fromElement(1);\n\t\t// add and concat work as expected\n\t\tassertEquals(List.of(1), one.build());\n\t\tassertEquals(List.of(1, 2, 3, 4),\n\t\t\t\tone.add(List.of(2, 3, 4)).build());\n\t\tassertEquals(List.of(1, 2, 1),\n\t\t\t\tone.concat(this.factory.fromElement(2))\n\t\t\t\t\t\t.concat(one)\n\t\t\t\t\t\t.build());\n\t}\n\n\[email protected]\n\tpublic void testBasicFromList() {\n\t\t// fromList() represents the builder of a list with n elements\n\t\tListBuilder<Integer> l = this.factory.fromList(List.of(1, 2, 3));\n\t\tassertEquals(List.of(1, 2, 3), l.build());\n\t\t// concat work as expected\n\t\tassertEquals(List.of(1, 2, 3, 1, 2, 3),\n\t\t\t\tl.concat(l).build());\n\t\t// replaceAll here replaces the \"1\"s with pairs \"-1, -2\"\n\t\tassertEquals(List.of(-1, -2, 2, 3, -1, -2, 2, 3),\n\t\t\t\tl.concat(l)\n\t\t\t\t\t\t.replaceAll(1, this.factory.fromList(List.of(-1, -2)))\n\t\t\t\t\t\t.build());\n\t\t// if there is no match, replaceAll does nothing\n\t\tassertEquals(List.of(1, 2, 3, 1, 2, 3),\n\t\t\t\tl.concat(l)\n\t\t\t\t\t\t.replaceAll(10, this.factory.fromList(List.of(-1, -2)))\n\t\t\t\t\t\t.build());\n\t}\n\n\[email protected]\n\tpublic void testReverseFromList() {\n\t\tListBuilder<Integer> l = this.factory.fromList(List.of(1, 2, 3));\n\t\tassertEquals(List.of(1, 2, 3), l.build());\n\t\t// reverse makes you get a builder that represents the inverted list\n\t\tassertEquals(List.of(3, 2, 1), l.reverse().build());\n\t\tassertEquals(List.of(1, 2, 3), l.reverse().reverse().build());\n\t\tassertEquals(List.of(1, 2, 3, 3, 2, 1),\n\t\t\t\tl.reverse().reverse().concat(l.reverse()).build());\n\t}\n\n\[email protected]\n\tpublic void testJoin() {\n \t\t// join can be used to concatenate multiple builders, with an initial and a final element\n\t\tassertEquals(List.of(\"(\", \"1\", \"2\", \"3\", \"4\",\")\"),\n\t\t\t\tthis.factory.join(\"(\", \")\", \n\t\t\t\t\t\tList.of(this.factory.fromElement(\"1\"), \n\t\t\t\t\t\t\t\tthis.factory.fromElement(\"2\"),\n\t\t\t\t\t\t\t\tthis.factory.fromList(List.of(\"3\",\"4\")))).build());\n\t}\n\n}", "filename": "Test.java" }
2023
a01c
[ { "content": "package a01c.sol1;\n\nimport java.util.*;\n\npublic interface TimeSheetFactory {\n\t\n\t\n\tTimeSheet ofRawData(List<Pair<String, String>> data);\n\n\t\n\tTimeSheet withBoundsPerActivity(List<Pair<String, String>> data, Map<String, Integer> boundsOnActivities);\n\n\t\n\tTimeSheet withBoundsPerDay(List<Pair<String, String>> data, Map<String, Integer> boundsOnDays);\n\n\t\n\tTimeSheet withBounds(List<Pair<String, String>> data, Map<String, Integer> boundsOnActivities, Map<String, Integer> boundsOnDays);\n}", "filename": "TimeSheetFactory.java" }, { "content": "package a01c.sol1;\n\nimport java.util.*;\n\n\npublic interface TimeSheet {\n\t\n\t\n\tSet<String> activities();\n\n\t\n\tSet<String> days();\n\n\t\n\tint getSingleData(String activity, String day);\n\n\t\n\tboolean isValid();\n\n}", "filename": "TimeSheet.java" }, { "content": "package a01c.sol1;\n\nimport java.util.Objects;\n\n\n\npublic class Pair<E1,E2> {\n\t\n\tprivate final E1 e1;\n\tprivate final E2 e2;\n\t\n\tpublic Pair(E1 x, E2 y) {\n\t\tsuper();\n\t\tthis.e1 = x;\n\t\tthis.e2 = y;\n\t}\n\n\tpublic E1 get1() {\n\t\treturn e1;\n\t}\n\n\tpublic E2 get2() {\n\t\treturn e2;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Objects.hash(e1, e2);\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj) {\n\t\t\treturn true;\n\t\t}\n\t\tif (obj == null) {\n\t\t\treturn false;\n\t\t}\n\t\tif (getClass() != obj.getClass()) {\n\t\t\treturn false;\n\t\t}\n\t\tPair other = (Pair) obj;\n\t\treturn Objects.equals(e1, other.e1) && Objects.equals(e2, other.e2);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Pair [e1=\" + e1 + \", e2=\" + e2 + \"]\";\n\t}\n\t\n\t\n\n}", "filename": "Pair.java" } ]
[ { "content": "package a01c.sol1;\n\nimport java.util.*;\nimport java.util.stream.*;\n\nimport java.util.function.*;\n\npublic class TimeSheetFactoryImpl implements TimeSheetFactory {\n\n // An implementation of a Timesheet as an immutable class with activities, days, and an association of activities+days to hours\n // Since it is immutable, we use a record, which automatically gives fields, getters, constructors, hashcode, equals, toString.\n private static record TimeSheetData(Set<String> activities, Set<String> days, BiFunction<String, String, Integer> fun) implements TimeSheet {\n\n @Override\n public int getSingleData(String activity, String day) {\n return fun.apply(activity,day);\n }\n\n @Override\n public boolean isValid() {\n return true;\n }\n }\n\n // We handle various validy policies, and combine them, by the decorator pattern\n private static class TimeSheetDecorator implements TimeSheet {\n private final TimeSheet base;\n\n public TimeSheetDecorator(TimeSheet base) {\n this.base = base;\n }\n\n public Set<String> activities() {\n return base.activities();\n }\n\n public Set<String> days() {\n return base.days();\n }\n\n public int getSingleData(String activity, String day) {\n return base.getSingleData(activity, day);\n }\n\n public boolean isValid() {\n return base.isValid();\n }\n\n public int sumPerActivity(String activity) {\n return days().stream()\n .map(day -> getSingleData(activity,day))\n .collect(Collectors.summingInt(i->i));\n }\n\n public int sumPerDay(String day) {\n return activities().stream()\n .map(act -> getSingleData(act,day))\n .collect(Collectors.summingInt(i->i));\n }\n }\n\n @Override\n public TimeSheet ofRawData(List<Pair<String, String>> data) {\n var activities = data.stream().map(Pair::get1).sorted().collect(Collectors.toSet());\n var days = data.stream().map(Pair::get2).sorted().collect(Collectors.toSet());\n return new TimeSheetData(\n activities,\n days, \n (a,d) -> (int)data.stream().filter(p -> p.get1().equals(a) && p.get2().equals(d)).count());\n }\n\n private TimeSheet decorateWithBoundsPerActivity(TimeSheet base, Map<String, Integer> bounds) {\n return new TimeSheetDecorator(base){\n public boolean isValid() {\n return base.isValid() && bounds.entrySet()\n .stream()\n .allMatch(e -> sumPerActivity(e.getKey()) <= e.getValue());\n }\n };\n\n }\n\n private TimeSheet decorateWithBoundsPerDay(TimeSheet base, Map<String, Integer> bounds) {\n return new TimeSheetDecorator(base){\n public boolean isValid() {\n return base.isValid() && bounds.entrySet()\n .stream()\n .allMatch(e -> sumPerDay(e.getKey()) <= e.getValue());\n }\n };\n\n }\n\n private TimeSheet decorateWithBounds(TimeSheet base, Map<String, Integer> boundsPerActivity, Map<String, Integer> boundsPerDay){\n return decorateWithBoundsPerActivity(decorateWithBoundsPerDay(base, boundsPerDay), boundsPerActivity);\n }\n\n @Override\n public TimeSheet withBoundsPerActivity(List<Pair<String, String>> data, Map<String, Integer> bounds) {\n return decorateWithBoundsPerActivity(ofRawData(data), bounds);\n }\n\n @Override\n public TimeSheet withBoundsPerDay(List<Pair<String, String>> data, Map<String, Integer> bounds) {\n return decorateWithBoundsPerDay(ofRawData(data), bounds);\n }\n\n @Override\n public TimeSheet withBounds(List<Pair<String, String>> data, Map<String, Integer> boundsOnActivities, Map<String, Integer> boundsOnDays) {\n return decorateWithBounds(ofRawData(data), boundsOnActivities, boundsOnDays);\n }\n\n}", "filename": "TimeSheetFactoryImpl.java" } ]
{ "components": { "imports": "package a01c.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;", "private_init": "\t/*\n\t * Implement the TimeSheetFactory interface as indicated in the initFactory\n\t * method below. Creates a factory for a Timesheet concept, captured by the\n\t * Timesheet interface: essentially it is a table with days (typically days of\n\t * a month) in the columns, and work activities in the rows (for example:\n\t * \"teaching\", \"project research 1\", \"project research 2\",...) where in each\n\t * cell it reports how many hours (>=0) have been spent on a certain day for a\n\t * certain activity.\n\t * \n\t * The following are considered optional for the purpose of being able to correct\n\t * the exercise, but still contribute to achieving the totality of the score:\n\t * \n\t * - implementation of all methods of the factory (i.e., in the mandatory part\n\t * it is sufficient to implement all of them except one at will)\n\t * - the good design of the solution, using design solutions that lead to\n\t * succinct code that avoids repetitions\n\t * \n\t * Remove the comment from the initFactory method.\n\t * \n\t * Scoring indications:\n\t * - correctness of the mandatory part: 10 points\n\t * - correctness of the optional part: 3 points (additional factory method)\n\t * - quality of the solution: 4 points (for good design)\n\t * \n\t */\n\n\tprivate TimeSheetFactory factory;\n\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.factory = new TimeSheetFactoryImpl();\n\t}\n\n\tprivate List<Pair<String, String>> basicData(){\n\t\t// An example of data for a timesheet, used in the tests below\n\t\treturn List.of(\n\t\t\t\tnew Pair<>(\"act1\", \"day1\"),\n\t\t\t\tnew Pair<>(\"act1\", \"day2\"),\n\t\t\t\tnew Pair<>(\"act1\", \"day2\"), // so two hours of activity act1 in day2\n\t\t\t\tnew Pair<>(\"act1\", \"day3\"),\n\t\t\t\tnew Pair<>(\"act1\", \"day3\"),\n\t\t\t\tnew Pair<>(\"act1\", \"day3\"), // so three hours of activity act1 in day2\n\t\t\t\tnew Pair<>(\"act2\", \"day3\"));\n\t}\n\n\tprivate void testExampleTimeSheet(TimeSheet sheet) {\n\t\t// a set of tests for a timesheet obtained from basicData()\n\t\tassertEquals(Set.of(\"act1\", \"act2\"), sheet.activities()); // two activities extracted from the timesheet data\n\t\tassertEquals(Set.of(\"day1\", \"day2\", \"day3\"), sheet.days()); // three days extracted from the timesheet data\n\t\tassertEquals(1, sheet.getSingleData(\"act1\", \"day1\"));\n\t\tassertEquals(2, sheet.getSingleData(\"act1\", \"day2\")); // 2 hours present in the data\n\t\tassertEquals(3, sheet.getSingleData(\"act1\", \"day3\")); // 3 hours present in the data\n\t\tassertEquals(0, sheet.getSingleData(\"act2\", \"day2\"));\n\t\tassertEquals(1, sheet.getSingleData(\"act2\", \"day3\"));\n\t}", "test_functions": [ "\[email protected]\n\tpublic void testOfRawData() {\n\t\t// the timesheet obtained from an empty list has no activities or days\n\t\tTimeSheet empty = this.factory.ofRawData(List.of());\n\t\tassertEquals(Set.of(), empty.activities());\n\t\tassertEquals(Set.of(), empty.days());\n\n\t\t// the timesheet obtained from basicData() passes the test of testExampleTimeSheet\n\t\ttestExampleTimeSheet(this.factory.ofRawData(basicData()));\n\t}", "\[email protected]\n\tpublic void testWithBoundsPerActivity() {\n\t\tTimeSheet sheet = this.factory.withBoundsPerActivity(\n\t\t\tbasicData(),\n\t\t\tMap.of(\"act1\", 7, \"act2\", 7) // max 7 hours on act1, and 7 on act2\n\t\t);\n\t\ttestExampleTimeSheet(sheet);\n\t\t// it is a valid timesheet\n\t\tassertTrue(sheet.isValid());\n\n\t\t// Same test below, but with stricter constraints, which do not make it valid\n\t\tTimeSheet sheet2 = this.factory.withBoundsPerActivity(\n\t\t\tbasicData(),\n\t\t\tMap.of(\"act1\", 4, \"act2\", 3)\n\t\t);\n\t\ttestExampleTimeSheet(sheet2);\n\t\tassertFalse(sheet2.isValid());\n\t}", "\[email protected]\n\tpublic void testWithBoundsPerDay() {\n\t\tTimeSheet sheet = this.factory.withBoundsPerDay(\n\t\t\tbasicData(),\n\t\t\tMap.of(\"day1\", 8, \"day2\", 8, \"day3\", 8) // max 8 hours on day,...\n\t\t);\n\t\ttestExampleTimeSheet(sheet);\n\t\t// it is a valid timesheet\n\t\tassertTrue(sheet.isValid());\n\n\t\t// Same test below, but with stricter constraints, which do not make it valid\n\t\tTimeSheet sheet2 = this.factory.withBoundsPerDay(\n\t\t\tbasicData(),\n\t\t\tMap.of(\"day1\", 2, \"day2\", 2, \"day3\", 2)\n\t\t);\n\t\ttestExampleTimeSheet(sheet2);\n\t\tassertFalse(sheet2.isValid());\n\t}", "\[email protected]\n\tpublic void testWithBounds() {\n\t\tTimeSheet sheet = this.factory.withBounds(\n\t\t\tbasicData(),\n\t\t\tMap.of(\"act1\", 7, \"act2\", 4), // max 7 hours on act1...\n\t\t\tMap.of(\"day1\", 8, \"day2\", 8, \"day3\", 8) // max 8 hours on day1...\n\t\t);\n\t\ttestExampleTimeSheet(sheet);\n\t\t// it is a valid timesheet\n\t\tassertTrue(sheet.isValid());\n\n\t\t// Same test below, but with stricter constraints, which do not make it valid\n\t\tTimeSheet sheet2 = this.factory.withBounds(\n\t\t\tbasicData(),\n\t\t\tMap.of(\"act1\", 4, \"act2\", 4),\n\t\t\tMap.of(\"day1\", 2, \"day2\", 2, \"day3\", 2)\n\t\t);\n\t\ttestExampleTimeSheet(sheet2);\n\t\tassertFalse(sheet2.isValid());\n\t}" ] }, "content": "package a01c.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;\n\npublic class Test {\n\n\t/*\n\t * Implement the TimeSheetFactory interface as indicated in the initFactory\n\t * method below. Creates a factory for a Timesheet concept, captured by the\n\t * Timesheet interface: essentially it is a table with days (typically days of\n\t * a month) in the columns, and work activities in the rows (for example:\n\t * \"teaching\", \"project research 1\", \"project research 2\",...) where in each\n\t * cell it reports how many hours (>=0) have been spent on a certain day for a\n\t * certain activity.\n\t * \n\t * The following are considered optional for the purpose of being able to correct\n\t * the exercise, but still contribute to achieving the totality of the score:\n\t * \n\t * - implementation of all methods of the factory (i.e., in the mandatory part\n\t * it is sufficient to implement all of them except one at will)\n\t * - the good design of the solution, using design solutions that lead to\n\t * succinct code that avoids repetitions\n\t * \n\t * Remove the comment from the initFactory method.\n\t * \n\t * Scoring indications:\n\t * - correctness of the mandatory part: 10 points\n\t * - correctness of the optional part: 3 points (additional factory method)\n\t * - quality of the solution: 4 points (for good design)\n\t * \n\t */\n\n\tprivate TimeSheetFactory factory;\n\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.factory = new TimeSheetFactoryImpl();\n\t}\n\n\tprivate List<Pair<String, String>> basicData(){\n\t\t// An example of data for a timesheet, used in the tests below\n\t\treturn List.of(\n\t\t\t\tnew Pair<>(\"act1\", \"day1\"),\n\t\t\t\tnew Pair<>(\"act1\", \"day2\"),\n\t\t\t\tnew Pair<>(\"act1\", \"day2\"), // so two hours of activity act1 in day2\n\t\t\t\tnew Pair<>(\"act1\", \"day3\"),\n\t\t\t\tnew Pair<>(\"act1\", \"day3\"),\n\t\t\t\tnew Pair<>(\"act1\", \"day3\"), // so three hours of activity act1 in day2\n\t\t\t\tnew Pair<>(\"act2\", \"day3\"));\n\t}\n\n\tprivate void testExampleTimeSheet(TimeSheet sheet) {\n\t\t// a set of tests for a timesheet obtained from basicData()\n\t\tassertEquals(Set.of(\"act1\", \"act2\"), sheet.activities()); // two activities extracted from the timesheet data\n\t\tassertEquals(Set.of(\"day1\", \"day2\", \"day3\"), sheet.days()); // three days extracted from the timesheet data\n\t\tassertEquals(1, sheet.getSingleData(\"act1\", \"day1\"));\n\t\tassertEquals(2, sheet.getSingleData(\"act1\", \"day2\")); // 2 hours present in the data\n\t\tassertEquals(3, sheet.getSingleData(\"act1\", \"day3\")); // 3 hours present in the data\n\t\tassertEquals(0, sheet.getSingleData(\"act2\", \"day2\"));\n\t\tassertEquals(1, sheet.getSingleData(\"act2\", \"day3\"));\n\t}\n\n\[email protected]\n\tpublic void testOfRawData() {\n\t\t// the timesheet obtained from an empty list has no activities or days\n\t\tTimeSheet empty = this.factory.ofRawData(List.of());\n\t\tassertEquals(Set.of(), empty.activities());\n\t\tassertEquals(Set.of(), empty.days());\n\n\t\t// the timesheet obtained from basicData() passes the test of testExampleTimeSheet\n\t\ttestExampleTimeSheet(this.factory.ofRawData(basicData()));\n\t}\n\n\[email protected]\n\tpublic void testWithBoundsPerActivity() {\n\t\tTimeSheet sheet = this.factory.withBoundsPerActivity(\n\t\t\tbasicData(),\n\t\t\tMap.of(\"act1\", 7, \"act2\", 7) // max 7 hours on act1, and 7 on act2\n\t\t);\n\t\ttestExampleTimeSheet(sheet);\n\t\t// it is a valid timesheet\n\t\tassertTrue(sheet.isValid());\n\n\t\t// Same test below, but with stricter constraints, which do not make it valid\n\t\tTimeSheet sheet2 = this.factory.withBoundsPerActivity(\n\t\t\tbasicData(),\n\t\t\tMap.of(\"act1\", 4, \"act2\", 3)\n\t\t);\n\t\ttestExampleTimeSheet(sheet2);\n\t\tassertFalse(sheet2.isValid());\n\t}\n\n\[email protected]\n\tpublic void testWithBoundsPerDay() {\n\t\tTimeSheet sheet = this.factory.withBoundsPerDay(\n\t\t\tbasicData(),\n\t\t\tMap.of(\"day1\", 8, \"day2\", 8, \"day3\", 8) // max 8 hours on day,...\n\t\t);\n\t\ttestExampleTimeSheet(sheet);\n\t\t// it is a valid timesheet\n\t\tassertTrue(sheet.isValid());\n\n\t\t// Same test below, but with stricter constraints, which do not make it valid\n\t\tTimeSheet sheet2 = this.factory.withBoundsPerDay(\n\t\t\tbasicData(),\n\t\t\tMap.of(\"day1\", 2, \"day2\", 2, \"day3\", 2)\n\t\t);\n\t\ttestExampleTimeSheet(sheet2);\n\t\tassertFalse(sheet2.isValid());\n\t}\n\n\[email protected]\n\tpublic void testWithBounds() {\n\t\tTimeSheet sheet = this.factory.withBounds(\n\t\t\tbasicData(),\n\t\t\tMap.of(\"act1\", 7, \"act2\", 4), // max 7 hours on act1...\n\t\t\tMap.of(\"day1\", 8, \"day2\", 8, \"day3\", 8) // max 8 hours on day1...\n\t\t);\n\t\ttestExampleTimeSheet(sheet);\n\t\t// it is a valid timesheet\n\t\tassertTrue(sheet.isValid());\n\n\t\t// Same test below, but with stricter constraints, which do not make it valid\n\t\tTimeSheet sheet2 = this.factory.withBounds(\n\t\t\tbasicData(),\n\t\t\tMap.of(\"act1\", 4, \"act2\", 4),\n\t\t\tMap.of(\"day1\", 2, \"day2\", 2, \"day3\", 2)\n\t\t);\n\t\ttestExampleTimeSheet(sheet2);\n\t\tassertFalse(sheet2.isValid());\n\t}\n}", "filename": "Test.java" }
2023
a03b
[ { "content": "package a03b.sol1;\n\nimport java.util.List;\n\n\npublic interface InfiniteIteratorsHelpers {\n\t\n\t\n\t<X> InfiniteIterator<X> of(X x);\n\t\n\t\n\t<X> InfiniteIterator<X> cyclic(List<X> l);\n\t\n\t\n\tInfiniteIterator<Integer> incrementing(int start, int increment);\n\n\t\n\t<X> InfiniteIterator<X> alternating(InfiniteIterator<X> i, InfiniteIterator<X> j);\n\n\t\n\t<X> InfiniteIterator<List<X>> window(InfiniteIterator<X> i, int n);\n}", "filename": "InfiniteIteratorsHelpers.java" }, { "content": "package a03b.sol1;\n\nimport java.util.List;\nimport java.util.stream.*;\n\n\npublic interface InfiniteIterator<X> {\n\t\n\t\n\tX nextElement();\n\t\n\t\n\tdefault List<X> nextListOfElements(int size) {\n\t\treturn Stream.generate(this::nextElement).limit(size).toList();\n\t}\n\t\n}", "filename": "InfiniteIterator.java" }, { "content": "package a03b.sol1;\n\nimport java.util.Objects;\n\n\n\npublic class Pair<E1,E2> {\n\t\n\tprivate final E1 e1;\n\tprivate final E2 e2;\n\t\n\tpublic Pair(E1 x, E2 y) {\n\t\tsuper();\n\t\tthis.e1 = x;\n\t\tthis.e2 = y;\n\t}\n\n\tpublic E1 get1() {\n\t\treturn e1;\n\t}\n\n\tpublic E2 get2() {\n\t\treturn e2;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Objects.hash(e1, e2);\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj) {\n\t\t\treturn true;\n\t\t}\n\t\tif (obj == null) {\n\t\t\treturn false;\n\t\t}\n\t\tif (getClass() != obj.getClass()) {\n\t\t\treturn false;\n\t\t}\n\t\tPair other = (Pair) obj;\n\t\treturn Objects.equals(e1, other.e1) && Objects.equals(e2, other.e2);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Pair [e1=\" + e1 + \", e2=\" + e2 + \"]\";\n\t}\n\t\n\t\n\n}", "filename": "Pair.java" } ]
[ { "content": "package a03b.sol1;\n\nimport java.util.Collections;\nimport java.util.Iterator;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.stream.Stream;\n\n// Soluzione con stream\npublic class InfiniteIteratorHelpersImpl implements InfiniteIteratorsHelpers {\n\n\tprivate <X> InfiniteIterator<X> ofStream(Stream<X> s){\n\t\tfinal Iterator<X> it = s.iterator();\n\t\treturn () -> it.next();\n\t}\n\n\t@Override\n\tpublic <X> InfiniteIterator<X> of(X x) {\n\t\treturn () -> x;\n\t}\n\n\t@Override\n\tpublic <X> InfiniteIterator<X> cyclic(List<X> x) {\n\t\treturn ofStream(Stream.generate(x::stream).flatMap(e->e));\n\t}\n\t\n\t\n\t@Override\n\tpublic InfiniteIterator<Integer> incrementing(int start, int increment) {\n\t\treturn ofStream(Stream.iterate(start, i -> i + increment));\n\t}\n\n\t@Override\n\tpublic <X> InfiniteIterator<X> alternating(InfiniteIterator<X> input1, InfiniteIterator<X> input2) {\n\t\treturn ofStream(Stream\n\t\t\t\t.iterate(new Pair<>(input1, input2), p -> new Pair<>(p.get2(), p.get1()))\n\t\t\t\t.map(p -> p.get1().nextElement()));\n\t}\n\n\t@Override\n\tpublic <X> InfiniteIterator<List<X>> window(InfiniteIterator<X> i, int n) {\n\t\treturn ofStream(Stream\n\t\t\t\t.iterate(Collections.<X>emptyList(), l -> Stream.concat(l.stream(), Stream.of(i.nextElement())).toList())\n\t\t\t\t.filter(l -> l.size() >= n)\n\t\t\t\t.map(l -> new LinkedList<>(l.subList(l.size()-n, l.size())))\n\t\t);\n\t}\n}", "filename": "InfiniteIteratorHelpersImpl.java" }, { "content": "package a03b.sol1;\n\nimport java.util.LinkedList;\nimport java.util.List;\n\n// Soluzione con generazione di iteratori imperativi\npublic class InfiniteIteratorHelpersImpl2 implements InfiniteIteratorsHelpers {\n\n\t@Override\n\tpublic <X> InfiniteIterator<X> of(X x) {\n\t\treturn () -> x;\n\t}\n\n\t@Override\n\tpublic <X> InfiniteIterator<X> cyclic(List<X> l) {\n\t\treturn new InfiniteIterator<>() {\n\t\t\tLinkedList<X> ll = new LinkedList<>(l);\n\t\t\t@Override\n\t\t\tpublic X nextElement() {\n\t\t\t\tvar e = ll.removeFirst();\n\t\t\t\tll.addLast(e);\n\t\t\t\treturn e;\n\t\t\t}\t\t\t\n\t\t};\n\t}\n\t\n\t@Override\n\tpublic InfiniteIterator<Integer> incrementing(int start, int increment) {\n\t\treturn new InfiniteIterator<>() {\n\t\t\tint state = start;\n\t\t\t@Override\n\t\t\tpublic Integer nextElement() {\n\t\t\t\tvar itemp = state;\n\t\t\t\tstate = state + increment;\n\t\t\t\treturn itemp;\n\t\t\t}\t\t\t\n\t\t};\n\t}\n\n\t@Override\n\tpublic <X> InfiniteIterator<X> alternating(InfiniteIterator<X> input1, InfiniteIterator<X> input2) {\n\t\treturn new InfiniteIterator<X>() {\n\t\t\tprivate InfiniteIterator<X> i1 = input1;\n\t\t\tprivate InfiniteIterator<X> i2 = input2;\n\t\t\t@Override\n\t\t\tpublic X nextElement() {\n\t\t\t\tvar itemp = i1;\n\t\t\t\ti1 = i2;\n\t\t\t\ti2 = itemp;\n\t\t\t\treturn i2.nextElement();\n\t\t\t}\t\t\t\n\t\t};\n\t}\n\n\t@Override\n\tpublic <X> InfiniteIterator<List<X>> window(InfiniteIterator<X> s, int n) {\n\t\treturn new InfiniteIterator<List<X>>() {\n\t\t\tLinkedList<X> cache = new LinkedList<>();\n\t\t\t@Override\n\t\t\tpublic List<X> nextElement() {\n\t\t\t\tcache.addLast(s.nextElement());\n\t\t\t\twhile (cache.size()<n) {\n\t\t\t\t\tcache.addLast(s.nextElement());\n\t\t\t\t}\n\t\t\t\treturn new LinkedList<>(cache.subList(cache.size()-n, cache.size()));\n\t\t\t}\t\t\t\n\t\t};\n\t}\n\n}", "filename": "InfiniteIteratorHelpersImpl2.java" } ]
{ "components": { "imports": "package a03b.sol1;\n\nimport static org.junit.Assert.*;\n\nimport java.util.*;", "private_init": "\t/*\n\t * Implement the InfiniteIteratorHelpers interface as indicated in the method\n\t * initFactory below. Implement an interface of utility functions for an\n\t * infinite iterator concept, captured by the InfiniteIterator interface:\n\t * essentially it is an iterator that continues to provide values indefinitely.\n\t *\n\t * The following are considered optional for the purpose of being able to correct\n\t * the exercise, but still contribute to achieving the totality of the\n\t * score:\n\t *\n\t * - implementation of all methods of the factory (i.e., in the\n\t * mandatory part it is sufficient to implement all of them except one at will)\n\t * - the good design of the solution, using design solutions that lead to\n\t * succinct code that avoids repetitions\n\t *\n\t * Remove the comment from the initFactory method.\n\t *\n\t * Scoring indications:\n\t * - correctness of the mandatory part: 10 points\n\t * - correctness of the optional part: 3 points (additional factory method)\n\t * - quality of the solution: 4 points (for good design)\n\t *\n\t */\n\n\tprivate InfiniteIteratorsHelpers iih;\n\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.iih = new InfiniteIteratorHelpersImpl();\n\t}", "test_functions": [ "\[email protected]\n public void testValue() {\n // Test on sequences consisting of a single element\n assertEquals(List.of(\"a\",\"a\",\"a\",\"a\",\"a\"), iih.of(\"a\").nextListOfElements(5));\n assertEquals(List.of(\"a\"), iih.of(\"a\").nextListOfElements(1));\n assertEquals(List.of(\"a\",\"a\",\"a\",\"a\",\"a\",\"a\",\"a\",\"a\",\"a\",\"a\"), iih.of(\"a\").nextListOfElements(10));\n assertEquals(List.of(1,1,1,1,1,1,1,1,1,1), iih.of(1).nextListOfElements(10));\n }", "\[email protected]\n public void testCyclic() {\n // Test on cyclic sequences\n // sequence: a,b,a,b,a,b,a,b,a,b,....\n assertEquals(List.of(\"a\",\"b\",\"a\",\"b\",\"a\"), iih.cyclic(List.of(\"a\",\"b\")).nextListOfElements(5));\n // sequence: 1,2,3,1,2,3,1,2,3,1,2,3,1,2,....\n assertEquals(List.of(1,2,3,1,2,3,1,2,3,1), iih.cyclic(List.of(1,2,3)).nextListOfElements(10));\n }", "\[email protected]\n public void testIncrementing() {\n\t\t// Test on constructing increment sequence\n\t\tassertEquals(List.of(1,3,5,7,9), iih.incrementing(1, 2).nextListOfElements(5)); \t\n assertEquals(List.of(0,-3,-6,-9), iih.incrementing(0, -3).nextListOfElements(4)); \t\n }", "\[email protected]\n public void testAlternating() {\n\t\t// Test on constructing alternating sequences\n\t\tvar i1 = iih.incrementing(1, 1);\n\t\tvar i2 = iih.of(0);\n assertEquals(List.of(1,0,2,0,3,0), iih.alternating(i1, i2).nextListOfElements(6));\n }", "\[email protected]\n public void testWindow() {\n\t\t// Test on constructing \"window\" sequences\n\t\tassertEquals(List.of(\n\t\t\t\tList.of(1,2,3,4),\n\t\t\t\tList.of(2,3,4,5),\n\t\t\t\tList.of(3, 4, 5 ,6)),\n\t\t\tiih.window(iih.incrementing(1, 1), 4).nextListOfElements(3));\n\t\t\t\n }" ] }, "content": "package a03b.sol1;\n\nimport static org.junit.Assert.*;\n\nimport java.util.*;\n\npublic class Test {\n\n\t/*\n\t * Implement the InfiniteIteratorHelpers interface as indicated in the method\n\t * initFactory below. Implement an interface of utility functions for an\n\t * infinite iterator concept, captured by the InfiniteIterator interface:\n\t * essentially it is an iterator that continues to provide values indefinitely.\n\t *\n\t * The following are considered optional for the purpose of being able to correct\n\t * the exercise, but still contribute to achieving the totality of the\n\t * score:\n\t *\n\t * - implementation of all methods of the factory (i.e., in the\n\t * mandatory part it is sufficient to implement all of them except one at will)\n\t * - the good design of the solution, using design solutions that lead to\n\t * succinct code that avoids repetitions\n\t *\n\t * Remove the comment from the initFactory method.\n\t *\n\t * Scoring indications:\n\t * - correctness of the mandatory part: 10 points\n\t * - correctness of the optional part: 3 points (additional factory method)\n\t * - quality of the solution: 4 points (for good design)\n\t *\n\t */\n\n\tprivate InfiniteIteratorsHelpers iih;\n\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.iih = new InfiniteIteratorHelpersImpl();\n\t}\n\n\[email protected]\n public void testValue() {\n // Test on sequences consisting of a single element\n assertEquals(List.of(\"a\",\"a\",\"a\",\"a\",\"a\"), iih.of(\"a\").nextListOfElements(5));\n assertEquals(List.of(\"a\"), iih.of(\"a\").nextListOfElements(1));\n assertEquals(List.of(\"a\",\"a\",\"a\",\"a\",\"a\",\"a\",\"a\",\"a\",\"a\",\"a\"), iih.of(\"a\").nextListOfElements(10));\n assertEquals(List.of(1,1,1,1,1,1,1,1,1,1), iih.of(1).nextListOfElements(10));\n }\n \n\[email protected]\n public void testCyclic() {\n // Test on cyclic sequences\n // sequence: a,b,a,b,a,b,a,b,a,b,....\n assertEquals(List.of(\"a\",\"b\",\"a\",\"b\",\"a\"), iih.cyclic(List.of(\"a\",\"b\")).nextListOfElements(5));\n // sequence: 1,2,3,1,2,3,1,2,3,1,2,3,1,2,....\n assertEquals(List.of(1,2,3,1,2,3,1,2,3,1), iih.cyclic(List.of(1,2,3)).nextListOfElements(10));\n }\n\t\n\[email protected]\n public void testIncrementing() {\n\t\t// Test on constructing increment sequence\n\t\tassertEquals(List.of(1,3,5,7,9), iih.incrementing(1, 2).nextListOfElements(5)); \t\n assertEquals(List.of(0,-3,-6,-9), iih.incrementing(0, -3).nextListOfElements(4)); \t\n }\n\t\n\[email protected]\n public void testAlternating() {\n\t\t// Test on constructing alternating sequences\n\t\tvar i1 = iih.incrementing(1, 1);\n\t\tvar i2 = iih.of(0);\n assertEquals(List.of(1,0,2,0,3,0), iih.alternating(i1, i2).nextListOfElements(6));\n }\n\n\[email protected]\n public void testWindow() {\n\t\t// Test on constructing \"window\" sequences\n\t\tassertEquals(List.of(\n\t\t\t\tList.of(1,2,3,4),\n\t\t\t\tList.of(2,3,4,5),\n\t\t\t\tList.of(3, 4, 5 ,6)),\n\t\t\tiih.window(iih.incrementing(1, 1), 4).nextListOfElements(3));\n\t\t\t\n }\n\n\t\n}", "filename": "Test.java" }
2023
a02c
[ { "content": "package a02c.sol1;\n\nimport java.util.*;\n\n\n@FunctionalInterface\npublic interface Replacer<T> {\n\n \n List<List<T>> replace(List<T> input, T t);\n\n}", "filename": "Replacer.java" }, { "content": "package a02c.sol1;\n\nimport java.util.*;\n\n\npublic interface ReplacersFactory {\n\n \n <T> Replacer<T> noReplacement();\n\n \n <T> Replacer<T> duplicateFirst();\n\n \n <T> Replacer<T> translateLastWith(List<T> target);\n\n \n <T> Replacer<T> removeEach();\n\n \n <T> Replacer<T> replaceEachFromSequence(List<T> sequence);\n\n}", "filename": "ReplacersFactory.java" }, { "content": "package a02c.sol1;\n\nimport java.util.Objects;\n\n\n\npublic class Pair<E1,E2> {\n\t\n\tprivate final E1 e1;\n\tprivate final E2 e2;\n\t\n\tpublic Pair(E1 x, E2 y) {\n\t\tsuper();\n\t\tthis.e1 = x;\n\t\tthis.e2 = y;\n\t}\n\n\tpublic E1 get1() {\n\t\treturn e1;\n\t}\n\n\tpublic E2 get2() {\n\t\treturn e2;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Objects.hash(e1, e2);\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj) {\n\t\t\treturn true;\n\t\t}\n\t\tif (obj == null) {\n\t\t\treturn false;\n\t\t}\n\t\tif (getClass() != obj.getClass()) {\n\t\t\treturn false;\n\t\t}\n\t\tPair other = (Pair) obj;\n\t\treturn Objects.equals(e1, other.e1) && Objects.equals(e2, other.e2);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Pair [e1=\" + e1 + \", e2=\" + e2 + \"]\";\n\t}\n\t\n\t\n\n}", "filename": "Pair.java" } ]
[ { "content": "package a02c.sol1;\n\nimport java.util.*;\nimport java.util.function.*;\nimport java.util.stream.*;\n\npublic class ReplacersFactoryImpl implements ReplacersFactory {\n\n private <T> List<T> replaceAtPosition(int index, List<T> source, List<T> destination){\n var l = new LinkedList<>(source);\n l.remove(index);\n var it = destination.listIterator(destination.size());\n while (it.hasPrevious()){\n l.add(index, it.previous());\n }\n return l;\n }\n\n /**\n * This is the key function of this solution\n * @param <T>\n * @param left is the simbol to be replaced\n * @param right is a supplier that gives the list to put in place of {@code right}\n * @param where is a function taking the indexes where {@code left} occurs, and returning the index where to replace\n * @return the resulting replacer\n */\n private <T> Replacer<T> generalReplacer(T left, Supplier<List<T>> right, Function<List<Integer>, List<Integer>> where){\n return (input, t) -> {\n var whereToReplace = where.apply(Stream\n .iterate(0, i -> i < input.size(), i -> i+1)\n .flatMap(i -> Stream.of(i).filter(j -> input.get(j).equals(t)))\n .toList());\n return whereToReplace.stream().map(index -> replaceAtPosition(index, input, right.get())).toList();\n };\n }\n\n @Override\n public <T> Replacer<T> noReplacement() {\n return (input, t) -> generalReplacer(t, ()->List.of(), l ->List.of()).replace(input, t);\n }\n\n @Override\n public <T> Replacer<T> duplicateFirst() {\n return (input, t) -> generalReplacer(t, ()->List.of(t, t), l -> l.isEmpty() ? l : l.subList(0, 1)).replace(input, t);\n }\n\n @Override\n public <T> Replacer<T> translateLastWith(List<T> target) {\n return (input, t) -> generalReplacer(t, ()->target, l -> l.isEmpty() ? l : l.subList(l.size()-1, l.size())).replace(input, t);\n }\n\n @Override\n public <T> Replacer<T> removeEach() {\n return (input, t) -> generalReplacer(t, ()->List.of(), l -> l).replace(input, t);\n }\n\n @Override\n public <T> Replacer<T> replaceEachFromSequence(List<T> sequence) {\n return (input, t) -> {\n var it = sequence.iterator();\n return generalReplacer(t, ()->List.of(it.next()), l -> l.subList(0, Math.min(l.size(), sequence.size()))).replace(input, t);\n };\n }\n\n}", "filename": "ReplacersFactoryImpl.java" } ]
{ "components": { "imports": "package a02c.sol1;\n\nimport static org.junit.Assert.*;\n\nimport java.util.*;", "private_init": "\t/*\n\t * Implement the ReplacerFactory interface as indicated in the initFactory method below.\n\t * Create a factory for a Replacer concept, i.e., a functionality that, given a list and an element as input, modifies\n\t * the list by replacing certain occurrences of the element with a new sub-list,\n\t * depending on the implementation. It therefore provides in general n solutions,\n\t * one for each replaced occurrence.\n\t * \n\t * The following are considered optional for the purpose of being able to correct\n\t * the exercise, but still contribute to achieving the totality of the\n\t * score:\n\t * \n\t * - implementation of all factory methods (i.e., in the\n\t * mandatory part it is sufficient to implement all of them except one of your choice)\n\t * - the good design of the solution, using design solutions that lead to\n\t * succinct code that avoids repetitions\n\t * \n\t * Remove the comment from the initFactory method.\n\t * \n\t * Scoring indications:\n\t * - correctness of the mandatory part: 10 points\n\t * - correctness of the optional part: 3 points (further factory method)\n\t * - quality of the solution: 4 points (for good design)\n\t * \n\t */\n\n\tprivate ReplacersFactory factory;\n\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.factory = new ReplacersFactoryImpl();\n\t}", "test_functions": [ "\[email protected]\n\tpublic void testNone() {\n\t\t// a replacer that does not replace anything, therefore does not provide solutions\n\t\tvar replacer = this.factory.noReplacement();\n\t\tassertEquals(List.of(), replacer.replace(List.of(10,20,30), 10));\n\t\tassertEquals(List.of(), replacer.replace(List.of(10,20,30), 11));\n\t}", "\[email protected]\n\tpublic void testDuplicateFirst() {\n\t\t// a replacer that duplicates the first occurrence of a certain number, therefore provides 0 or 1 solution\n\t\tvar replacer = this.factory.duplicateFirst();\n\t\t// 10 is present, replaces its first occurrence with 10,20,30\n\t\tassertEquals(List.of(List.of(10, 10, 20, 30)), replacer.replace(List.of(10,20,30), 10));\n\t\tassertEquals(List.of(List.of(0, 10, 10, 20, 10)), replacer.replace(List.of(0, 10,20,10), 10));\n\t\t// 11 is not present: no solution\n\t\tassertEquals(List.of(), replacer.replace(List.of(0, 10,20,10), 11));\n\t}", "\[email protected]\n\tpublic void testTranslateLastWith() {\n\t\t// a replacer that replaces the last occurrence of a certain number with a certain sublist (-1, -1)\n\t\tvar replacer = this.factory.translateLastWith(List.of(-1,-1));\n\t\t// 10 is present: its last (and only) occurrence is replaced with -1,-1\n\t\tassertEquals(List.of(List.of(-1, -1, 20, 30)), replacer.replace(List.of(10,20,30), 10));\n\t\t// 10 is present multiple times: its last occurrence is replaced with -1,-1\n\t\tassertEquals(List.of(List.of(0, 10, 20, -1, -1)), replacer.replace(List.of(0, 10,20,10), 10));\n\t\t// 11 is not present, no solution\n\t\tassertEquals(List.of(), replacer.replace(List.of(0, 10,20,10), 11));\n\t}", "\[email protected]\n\tpublic void testRemoveEach() {\n\t\t// a replacer that removes each occurrence of a certain number one by one, giving n solutions in general\n\t\tvar replacer = this.factory.removeEach();\n\t\t// there is only one 10, there is one solution where it is removed\n\t\tassertEquals(List.of(List.of(20, 30)), replacer.replace(List.of(10,20,30), 10));\n\t\t// there are two 10s, there are two solutions where they are removed one at a time\n\t\tassertEquals(List.of(\n\t\t\tList.of(0,20,10),\n\t\t\tList.of(0, 10,20)\n\t\t), replacer.replace(List.of(0, 10,20,10), 10));\n\t\t// 11 is not present, no solution\n\t\tassertEquals(List.of(), replacer.replace(List.of(0, 10,20,10), 11));\n\t}", "\[email protected]\n\tpublic void testReplaceEachFromSequence() {\n\t\t// the first 3 occurrences of the number are replaced by -100, -101 and -102, respectively\n\t\t// giving therefore at most 3 solutions (but less if there are fewer occurrences)\n\t\tvar replacer = this.factory.replaceEachFromSequence(List.of(-100, -101, -102));\n\t\t// 1 single occurrence, replaced with -100\n\t\tassertEquals(List.of(List.of(0, -100, 20, 30)), replacer.replace(List.of(0,10,20,30), 10));\n\t\t// 2 occurrences, replaced with -100 and -101 respectively\n\t\tassertEquals(List.of(\n\t\t\tList.of(0, -100, 20,10),\n\t\t\tList.of(0, 10,20, -101)\n\t\t), replacer.replace(List.of(0, 10,20,10), 10));\n\t\t// 3 occurrences...\n\t\tassertEquals(List.of(\n\t\t\tList.of(-100, 10, 10, 10),\n\t\t\tList.of(10, -101, 10, 10),\n\t\t\tList.of(10, 10, -102, 10)\n\t\t), replacer.replace(List.of(10, 10, 10, 10), 10));\n\t\t// 0 occurrences...\n\t\tassertEquals(List.of(), replacer.replace(List.of(0, 10,20,10), 11));\n\t}" ] }, "content": "package a02c.sol1;\n\nimport static org.junit.Assert.*;\n\nimport java.util.*;\n\npublic class Test {\n\n\t/*\n\t * Implement the ReplacerFactory interface as indicated in the initFactory method below.\n\t * Create a factory for a Replacer concept, i.e., a functionality that, given a list and an element as input, modifies\n\t * the list by replacing certain occurrences of the element with a new sub-list,\n\t * depending on the implementation. It therefore provides in general n solutions,\n\t * one for each replaced occurrence.\n\t * \n\t * The following are considered optional for the purpose of being able to correct\n\t * the exercise, but still contribute to achieving the totality of the\n\t * score:\n\t * \n\t * - implementation of all factory methods (i.e., in the\n\t * mandatory part it is sufficient to implement all of them except one of your choice)\n\t * - the good design of the solution, using design solutions that lead to\n\t * succinct code that avoids repetitions\n\t * \n\t * Remove the comment from the initFactory method.\n\t * \n\t * Scoring indications:\n\t * - correctness of the mandatory part: 10 points\n\t * - correctness of the optional part: 3 points (further factory method)\n\t * - quality of the solution: 4 points (for good design)\n\t * \n\t */\n\n\tprivate ReplacersFactory factory;\n\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.factory = new ReplacersFactoryImpl();\n\t}\n\n\[email protected]\n\tpublic void testNone() {\n\t\t// a replacer that does not replace anything, therefore does not provide solutions\n\t\tvar replacer = this.factory.noReplacement();\n\t\tassertEquals(List.of(), replacer.replace(List.of(10,20,30), 10));\n\t\tassertEquals(List.of(), replacer.replace(List.of(10,20,30), 11));\n\t}\n\n\[email protected]\n\tpublic void testDuplicateFirst() {\n\t\t// a replacer that duplicates the first occurrence of a certain number, therefore provides 0 or 1 solution\n\t\tvar replacer = this.factory.duplicateFirst();\n\t\t// 10 is present, replaces its first occurrence with 10,20,30\n\t\tassertEquals(List.of(List.of(10, 10, 20, 30)), replacer.replace(List.of(10,20,30), 10));\n\t\tassertEquals(List.of(List.of(0, 10, 10, 20, 10)), replacer.replace(List.of(0, 10,20,10), 10));\n\t\t// 11 is not present: no solution\n\t\tassertEquals(List.of(), replacer.replace(List.of(0, 10,20,10), 11));\n\t}\n\n\[email protected]\n\tpublic void testTranslateLastWith() {\n\t\t// a replacer that replaces the last occurrence of a certain number with a certain sublist (-1, -1)\n\t\tvar replacer = this.factory.translateLastWith(List.of(-1,-1));\n\t\t// 10 is present: its last (and only) occurrence is replaced with -1,-1\n\t\tassertEquals(List.of(List.of(-1, -1, 20, 30)), replacer.replace(List.of(10,20,30), 10));\n\t\t// 10 is present multiple times: its last occurrence is replaced with -1,-1\n\t\tassertEquals(List.of(List.of(0, 10, 20, -1, -1)), replacer.replace(List.of(0, 10,20,10), 10));\n\t\t// 11 is not present, no solution\n\t\tassertEquals(List.of(), replacer.replace(List.of(0, 10,20,10), 11));\n\t}\n\n\[email protected]\n\tpublic void testRemoveEach() {\n\t\t// a replacer that removes each occurrence of a certain number one by one, giving n solutions in general\n\t\tvar replacer = this.factory.removeEach();\n\t\t// there is only one 10, there is one solution where it is removed\n\t\tassertEquals(List.of(List.of(20, 30)), replacer.replace(List.of(10,20,30), 10));\n\t\t// there are two 10s, there are two solutions where they are removed one at a time\n\t\tassertEquals(List.of(\n\t\t\tList.of(0,20,10),\n\t\t\tList.of(0, 10,20)\n\t\t), replacer.replace(List.of(0, 10,20,10), 10));\n\t\t// 11 is not present, no solution\n\t\tassertEquals(List.of(), replacer.replace(List.of(0, 10,20,10), 11));\n\t}\n\n\[email protected]\n\tpublic void testReplaceEachFromSequence() {\n\t\t// the first 3 occurrences of the number are replaced by -100, -101 and -102, respectively\n\t\t// giving therefore at most 3 solutions (but less if there are fewer occurrences)\n\t\tvar replacer = this.factory.replaceEachFromSequence(List.of(-100, -101, -102));\n\t\t// 1 single occurrence, replaced with -100\n\t\tassertEquals(List.of(List.of(0, -100, 20, 30)), replacer.replace(List.of(0,10,20,30), 10));\n\t\t// 2 occurrences, replaced with -100 and -101 respectively\n\t\tassertEquals(List.of(\n\t\t\tList.of(0, -100, 20,10),\n\t\t\tList.of(0, 10,20, -101)\n\t\t), replacer.replace(List.of(0, 10,20,10), 10));\n\t\t// 3 occurrences...\n\t\tassertEquals(List.of(\n\t\t\tList.of(-100, 10, 10, 10),\n\t\t\tList.of(10, -101, 10, 10),\n\t\t\tList.of(10, 10, -102, 10)\n\t\t), replacer.replace(List.of(10, 10, 10, 10), 10));\n\t\t// 0 occurrences...\n\t\tassertEquals(List.of(), replacer.replace(List.of(0, 10,20,10), 11));\n\t}\n}", "filename": "Test.java" }
2023
a01b
[ { "content": "package a01b.sol1;\n\nimport java.util.*;\n\npublic interface TimeSheetFactory {\n\t\n\t\n\tTimeSheet flat(int numActivities, int numNames, int hours);\n\n\t\n\tTimeSheet ofListsOfLists(List<String> activities, List<String> days, List<List<Integer>> data);\n\n\t\n\tTimeSheet ofRawData(int numActivities, int numDays, List<Pair<Integer,Integer>> data);\n\n\t\n\tTimeSheet ofPartialMap(List<String> activities, List<String> days, Map<Pair<String,String>,Integer> data);\n}", "filename": "TimeSheetFactory.java" }, { "content": "package a01b.sol1;\n\nimport java.util.List;\nimport java.util.Map;\n\n\npublic interface TimeSheet {\n\t\n\t\n\tList<String> activities();\n\n\t\n\tList<String> days();\n\n\t\n\tint getSingleData(String activity, String day);\n\n\t\n\tMap<String, Integer> sumsPerActivity();\n\n\t\n\tMap<String, Integer> sumsPerDay();\n}", "filename": "TimeSheet.java" }, { "content": "package a01b.sol1;\n\nimport java.util.Objects;\n\n\n\npublic class Pair<E1,E2> {\n\t\n\tprivate final E1 e1;\n\tprivate final E2 e2;\n\t\n\tpublic Pair(E1 x, E2 y) {\n\t\tsuper();\n\t\tthis.e1 = x;\n\t\tthis.e2 = y;\n\t}\n\n\tpublic E1 get1() {\n\t\treturn e1;\n\t}\n\n\tpublic E2 get2() {\n\t\treturn e2;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Objects.hash(e1, e2);\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj) {\n\t\t\treturn true;\n\t\t}\n\t\tif (obj == null) {\n\t\t\treturn false;\n\t\t}\n\t\tif (getClass() != obj.getClass()) {\n\t\t\treturn false;\n\t\t}\n\t\tPair other = (Pair) obj;\n\t\treturn Objects.equals(e1, other.e1) && Objects.equals(e2, other.e2);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Pair [e1=\" + e1 + \", e2=\" + e2 + \"]\";\n\t}\n\t\n\t\n\n}", "filename": "Pair.java" } ]
[ { "content": "package a01b.sol1;\n\nimport java.util.*;\nimport java.util.stream.*;\n\nimport java.util.function.*;\n\npublic class TimeSheetFactoryImpl implements TimeSheetFactory {\n\n // An implementation of a Timetable as an immutable class with activities, days, and an association of activities+days to hours\n // Since it is immutable, we use a record, which automatically gives fields, getters, constructors, hashcode, equals, toString.\n private static record TimeSheetData(List<String> activities, List<String> days, BiFunction<String, String, Integer> fun) implements TimeSheet {\n\n @Override\n public Map<String, Integer> sumsPerActivity() {\n return activities.stream()\n .map(act -> new Pair<>(act, days.stream()\n .map(day -> fun.apply(act,day))\n .collect(Collectors.summingInt(i->i))))\n .collect(Collectors.toMap(Pair::get1, Pair::get2));\n }\n\n @Override\n public Map<String, Integer> sumsPerDay() {\n return days.stream()\n .map(day -> new Pair<>(day,activities.stream()\n .map(act -> fun.apply(act,day))\n .collect(Collectors.summingInt(i->i))))\n .collect(Collectors.toMap(Pair::get1, Pair::get2));\n }\n\n @Override\n public int getSingleData(String activity, String day) {\n return activities.contains(activity) && days.contains(day) ? fun.apply(activity,day) : 0;\n }\n }\n\n private static List<String> createActivities(int numActivities){\n return Stream.iterate(1, i -> i + 1).map(i -> \"act\"+i).limit(numActivities).collect(Collectors.toList());\n }\n\n private static List<String> createDays(int numDays){\n return Stream.iterate(1, i -> i + 1).map(i -> \"day\"+i).limit(numDays).collect(Collectors.toList());\n }\n\n\n @Override\n public TimeSheet flat(int numActivities, int numDays, int hours) {\n var activities = createActivities(numActivities);\n var days = createDays(numDays);\n return new TimeSheetData(\n activities,\n days, \n (a,d) -> hours);\n }\n\n @Override\n public TimeSheet ofRawData(int numActivities, int numDays, List<Pair<Integer, Integer>> data) {\n var activities = createActivities(numActivities);\n var days = createDays(numDays);\n return new TimeSheetData(\n activities,\n days, \n (a,d) -> (int)data.stream().filter(p -> p.get1().equals(activities.indexOf(a)) && p.get2().equals(days.indexOf(d))).count());\n }\n\n @Override\n public TimeSheet ofListsOfLists(List<String> activities, List<String> days, List<List<Integer>> data) {\n return new TimeSheetData(\n List.copyOf(activities),\n List.copyOf(days), \n (a,d) -> data.get(activities.indexOf(a)).get(days.indexOf(d)));\n }\n\n @Override\n public TimeSheet ofPartialMap(List<String> activities, List<String> days, Map<Pair<String, String>, Integer> data) {\n return new TimeSheetData(\n List.copyOf(activities),\n List.copyOf(days), \n (a,d) -> data.getOrDefault(new Pair<>(a,d),0));\n }\n}", "filename": "TimeSheetFactoryImpl.java" } ]
{ "components": { "imports": "package a01b.sol1;\n\nimport static org.junit.Assert.*;\n\nimport java.util.*;", "private_init": "\t/*\n\t * Implement the TimeSheetFactory interface as indicated in the initFactory\n\t * method below. Implement a factory for a Timesheet concept, captured by the\n\t * Timesheet interface: essentially it is a table with days (typically days of\n\t * a month) in the columns, and work activities in the rows (for example:\n\t * \"teaching\", \"research project 1\", \"research project 2\",...) where each cell\n\t * shows how many hours (>=0) have been spent on a certain day for a certain\n\t * activity.\n\t * \n\t * The following are considered optional for the purpose of being able to correct\n\t * the exercise, but still contribute to achieving the totality of the score:\n\t * \n\t * - Implementation of all factory methods (i.e., in the mandatory part it is\n\t * sufficient to implement all but one at will)\n\t * - Good design of the solution, using design solutions that lead to\n\t * succinct code that avoids repetitions\n\t * \n\t * Remove the comment from the initFactory method.\n\t * \n\t * Scoring indications:\n\t * - correctness of the mandatory part: 10 points\n\t * - correctness of the optional part: 3 points (additional factory method)\n\t * - quality of the solution: 4 points (for good design)\n\t * \n\t */\n\n\n\tprivate TimeSheetFactory factory;\n\t\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.factory = new TimeSheetFactoryImpl();\n\t}", "test_functions": [ "\[email protected]\n\tpublic void testFlat() {\n\t\t// a time sheet with 3 activities over 5 days, with one hour per day on each activity on each day\n\t\tTimeSheet sheet = this.factory.flat(3, 5, 1);\n\t\tassertEquals(List.of(\"act1\", \"act2\", \"act3\"), sheet.activities());\n\t\tassertEquals(List.of(\"day1\", \"day2\", \"day3\", \"day4\", \"day5\"), sheet.days());\n\t\tassertEquals(1, sheet.getSingleData(\"act1\", \"day2\"));\n\t\tassertEquals(1, sheet.getSingleData(\"act2\", \"day3\"));\n\t\tassertEquals(0, sheet.getSingleData(\"act22\", \"day30\")); // activities/days not present, return 0\n\t\tassertEquals(Map.of(\"act1\",5, \"act2\",5,\"act3\",5), sheet.sumsPerActivity()); // 5 hours per each activity\n\t\tassertEquals(Map.of(\"day1\",3, \"day2\",3,\"day3\",3, \"day4\",3, \"day5\",3), sheet.sumsPerDay()); // 3 hours on each day\n\t}", "\[email protected]\n\tpublic void testOfListsOfLists() {\n\t\t// a timesheet with 2 activities over 3 days, with provided names\n\t\tTimeSheet sheet = this.factory.ofListsOfLists(\n\t\t\tList.of(\"a1\",\"a2\"), \n\t\t\tList.of(\"d1\", \"d2\", \"d3\"),\n\t\t\tList.of(\n\t\t\t\tList.of(1,2,3), // activity a1: 1,2,3 hours in the 3 days d1, d2, d3, orderly\n\t\t\t\tList.of(0,0,1) // activity a2: 0,0,1 hours in the 3 days d1, d2, d3, orderly\n\t\t\t));\n\t\tassertEquals(List.of(\"a1\", \"a2\"), sheet.activities());\n\t\tassertEquals(List.of(\"d1\", \"d2\", \"d3\"), sheet.days());\n\t\tassertEquals(2, sheet.getSingleData(\"a1\", \"d2\"));\n\t\tassertEquals(3, sheet.getSingleData(\"a1\", \"d3\"));\n\t\tassertEquals(0, sheet.getSingleData(\"a2\", \"d2\"));\n\t\tassertEquals(1, sheet.getSingleData(\"a2\", \"d3\"));\n\t\tassertEquals(Map.of(\"a1\",6, \"a2\",1), sheet.sumsPerActivity()); // hours per activity\n\t\tassertEquals(Map.of(\"d1\",1, \"d2\",2,\"d3\",4), sheet.sumsPerDay()); // hours per day\n\t}", "\[email protected]\n\tpublic void testOfRawData() {\n\t\t// a timesheet with 2 activities over 3 days, with standard names\n\t\tTimeSheet sheet = this.factory.ofRawData(2, 3, List.of(\n\t\t\tnew Pair<>(0,0), // one hour on act1 and day1\n\t\t\tnew Pair<>(0,1), // one hour on act1 and day2\n\t\t\tnew Pair<>(0,1), // one hour on act1 and day2 (become two in total)\n\t\t\tnew Pair<>(0,2), // one hour on act1 and day3\n\t\t\tnew Pair<>(0,2), // one hour on act1 and day3 (become two in total)\n\t\t\tnew Pair<>(0,2), // one hour on act1 and day3 (become three in total)\n\t\t\tnew Pair<>(1,2)));// one hour on act2 and day3\n\t\tassertEquals(List.of(\"act1\", \"act2\"), sheet.activities());\n\t\tassertEquals(List.of(\"day1\", \"day2\", \"day3\"), sheet.days());\n\t\tassertEquals(2, sheet.getSingleData(\"act1\", \"day2\"));\n\t\tassertEquals(3, sheet.getSingleData(\"act1\", \"day3\"));\n\t\tassertEquals(0, sheet.getSingleData(\"act2\", \"day2\"));\n\t\tassertEquals(1, sheet.getSingleData(\"act2\", \"day3\"));\n\t\tassertEquals(Map.of(\"act1\",6, \"act2\",1), sheet.sumsPerActivity());\n\t\tassertEquals(Map.of(\"day1\",1, \"day2\",2,\"day3\",4), sheet.sumsPerDay());\n\t}", "\[email protected]\n\tpublic void testOfMap() {\n\t\t// a timesheet with 2 activities over 3 days, with provided names\n\t\tTimeSheet sheet = this.factory.ofPartialMap(\n\t\t\tList.of(\"act1\",\"act2\"), \n\t\t\tList.of(\"day1\", \"day2\", \"day3\"),\n\t\t\tMap.of( // map (activity, day) -> n_hours\n\t\t\t\tnew Pair<>(\"act1\",\"day1\"),1, \n\t\t\t\tnew Pair<>(\"act1\",\"day2\"),2,\n\t\t\t\tnew Pair<>(\"act1\",\"day3\"),3,\n\t\t\t\tnew Pair<>(\"act2\",\"day3\"),1));\n\t\tassertEquals(List.of(\"act1\", \"act2\"), sheet.activities());\n\t\tassertEquals(List.of(\"day1\", \"day2\", \"day3\"), sheet.days());\n\t\tassertEquals(2, sheet.getSingleData(\"act1\", \"day2\"));\n\t\tassertEquals(3, sheet.getSingleData(\"act1\", \"day3\"));\n\t\tassertEquals(0, sheet.getSingleData(\"act2\", \"day2\"));\n\t\tassertEquals(1, sheet.getSingleData(\"act2\", \"day3\"));\n\t\tassertEquals(Map.of(\"act1\",6, \"act2\",1), sheet.sumsPerActivity());\n\t\tassertEquals(Map.of(\"day1\",1, \"day2\",2,\"day3\",4), sheet.sumsPerDay());\n\t}" ] }, "content": "package a01b.sol1;\n\nimport static org.junit.Assert.*;\n\nimport java.util.*;\n\npublic class Test {\n\n\t/*\n\t * Implement the TimeSheetFactory interface as indicated in the initFactory\n\t * method below. Implement a factory for a Timesheet concept, captured by the\n\t * Timesheet interface: essentially it is a table with days (typically days of\n\t * a month) in the columns, and work activities in the rows (for example:\n\t * \"teaching\", \"research project 1\", \"research project 2\",...) where each cell\n\t * shows how many hours (>=0) have been spent on a certain day for a certain\n\t * activity.\n\t * \n\t * The following are considered optional for the purpose of being able to correct\n\t * the exercise, but still contribute to achieving the totality of the score:\n\t * \n\t * - Implementation of all factory methods (i.e., in the mandatory part it is\n\t * sufficient to implement all but one at will)\n\t * - Good design of the solution, using design solutions that lead to\n\t * succinct code that avoids repetitions\n\t * \n\t * Remove the comment from the initFactory method.\n\t * \n\t * Scoring indications:\n\t * - correctness of the mandatory part: 10 points\n\t * - correctness of the optional part: 3 points (additional factory method)\n\t * - quality of the solution: 4 points (for good design)\n\t * \n\t */\n\n\n\tprivate TimeSheetFactory factory;\n\t\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.factory = new TimeSheetFactoryImpl();\n\t}\n\t\n\[email protected]\n\tpublic void testFlat() {\n\t\t// a time sheet with 3 activities over 5 days, with one hour per day on each activity on each day\n\t\tTimeSheet sheet = this.factory.flat(3, 5, 1);\n\t\tassertEquals(List.of(\"act1\", \"act2\", \"act3\"), sheet.activities());\n\t\tassertEquals(List.of(\"day1\", \"day2\", \"day3\", \"day4\", \"day5\"), sheet.days());\n\t\tassertEquals(1, sheet.getSingleData(\"act1\", \"day2\"));\n\t\tassertEquals(1, sheet.getSingleData(\"act2\", \"day3\"));\n\t\tassertEquals(0, sheet.getSingleData(\"act22\", \"day30\")); // activities/days not present, return 0\n\t\tassertEquals(Map.of(\"act1\",5, \"act2\",5,\"act3\",5), sheet.sumsPerActivity()); // 5 hours per each activity\n\t\tassertEquals(Map.of(\"day1\",3, \"day2\",3,\"day3\",3, \"day4\",3, \"day5\",3), sheet.sumsPerDay()); // 3 hours on each day\n\t}\n\n\[email protected]\n\tpublic void testOfListsOfLists() {\n\t\t// a timesheet with 2 activities over 3 days, with provided names\n\t\tTimeSheet sheet = this.factory.ofListsOfLists(\n\t\t\tList.of(\"a1\",\"a2\"), \n\t\t\tList.of(\"d1\", \"d2\", \"d3\"),\n\t\t\tList.of(\n\t\t\t\tList.of(1,2,3), // activity a1: 1,2,3 hours in the 3 days d1, d2, d3, orderly\n\t\t\t\tList.of(0,0,1) // activity a2: 0,0,1 hours in the 3 days d1, d2, d3, orderly\n\t\t\t));\n\t\tassertEquals(List.of(\"a1\", \"a2\"), sheet.activities());\n\t\tassertEquals(List.of(\"d1\", \"d2\", \"d3\"), sheet.days());\n\t\tassertEquals(2, sheet.getSingleData(\"a1\", \"d2\"));\n\t\tassertEquals(3, sheet.getSingleData(\"a1\", \"d3\"));\n\t\tassertEquals(0, sheet.getSingleData(\"a2\", \"d2\"));\n\t\tassertEquals(1, sheet.getSingleData(\"a2\", \"d3\"));\n\t\tassertEquals(Map.of(\"a1\",6, \"a2\",1), sheet.sumsPerActivity()); // hours per activity\n\t\tassertEquals(Map.of(\"d1\",1, \"d2\",2,\"d3\",4), sheet.sumsPerDay()); // hours per day\n\t}\n\n\[email protected]\n\tpublic void testOfRawData() {\n\t\t// a timesheet with 2 activities over 3 days, with standard names\n\t\tTimeSheet sheet = this.factory.ofRawData(2, 3, List.of(\n\t\t\tnew Pair<>(0,0), // one hour on act1 and day1\n\t\t\tnew Pair<>(0,1), // one hour on act1 and day2\n\t\t\tnew Pair<>(0,1), // one hour on act1 and day2 (become two in total)\n\t\t\tnew Pair<>(0,2), // one hour on act1 and day3\n\t\t\tnew Pair<>(0,2), // one hour on act1 and day3 (become two in total)\n\t\t\tnew Pair<>(0,2), // one hour on act1 and day3 (become three in total)\n\t\t\tnew Pair<>(1,2)));// one hour on act2 and day3\n\t\tassertEquals(List.of(\"act1\", \"act2\"), sheet.activities());\n\t\tassertEquals(List.of(\"day1\", \"day2\", \"day3\"), sheet.days());\n\t\tassertEquals(2, sheet.getSingleData(\"act1\", \"day2\"));\n\t\tassertEquals(3, sheet.getSingleData(\"act1\", \"day3\"));\n\t\tassertEquals(0, sheet.getSingleData(\"act2\", \"day2\"));\n\t\tassertEquals(1, sheet.getSingleData(\"act2\", \"day3\"));\n\t\tassertEquals(Map.of(\"act1\",6, \"act2\",1), sheet.sumsPerActivity());\n\t\tassertEquals(Map.of(\"day1\",1, \"day2\",2,\"day3\",4), sheet.sumsPerDay());\n\t}\n\n\[email protected]\n\tpublic void testOfMap() {\n\t\t// a timesheet with 2 activities over 3 days, with provided names\n\t\tTimeSheet sheet = this.factory.ofPartialMap(\n\t\t\tList.of(\"act1\",\"act2\"), \n\t\t\tList.of(\"day1\", \"day2\", \"day3\"),\n\t\t\tMap.of( // map (activity, day) -> n_hours\n\t\t\t\tnew Pair<>(\"act1\",\"day1\"),1, \n\t\t\t\tnew Pair<>(\"act1\",\"day2\"),2,\n\t\t\t\tnew Pair<>(\"act1\",\"day3\"),3,\n\t\t\t\tnew Pair<>(\"act2\",\"day3\"),1));\n\t\tassertEquals(List.of(\"act1\", \"act2\"), sheet.activities());\n\t\tassertEquals(List.of(\"day1\", \"day2\", \"day3\"), sheet.days());\n\t\tassertEquals(2, sheet.getSingleData(\"act1\", \"day2\"));\n\t\tassertEquals(3, sheet.getSingleData(\"act1\", \"day3\"));\n\t\tassertEquals(0, sheet.getSingleData(\"act2\", \"day2\"));\n\t\tassertEquals(1, sheet.getSingleData(\"act2\", \"day3\"));\n\t\tassertEquals(Map.of(\"act1\",6, \"act2\",1), sheet.sumsPerActivity());\n\t\tassertEquals(Map.of(\"day1\",1, \"day2\",2,\"day3\",4), sheet.sumsPerDay());\n\t}\n}", "filename": "Test.java" }
2024
a03a
[ { "content": "package a03a.sol1;\n\nimport java.util.Set;\n\n\npublic interface Cell<E> {\n\n \n E getResult();\n\n \n boolean isModifiable();\n\n \n Set<Cell<E>> dependsFrom();\n\n \n void write(E value);\n\n}", "filename": "Cell.java" }, { "content": "package a03a.sol1;\n\nimport java.util.List;\nimport java.util.function.BinaryOperator;\n\n\npublic interface CellsFactory {\n\n \n <E> Cell<E> mutableValueCell(E initial);\n\n \n Cell<Integer> sumOfTwo(Cell<Integer> c1, Cell<Integer> c2);\n\n \n Cell<String> concatOfThree(Cell<String> c1, Cell<String> c2, Cell<String> c3);\n\n \n List<Cell<Integer>> cellsWithSumOnLast(List<Integer> values);\n\n \n List<Cell<String>> addConcatenationOnAll(List<Cell<String>> cellList);\n\n \n <E> Cell<E> fromReduction(List<Cell<E>> cellList, BinaryOperator<E> op);\n \n}", "filename": "CellsFactory.java" }, { "content": "package a03a.sol1;\n\nimport java.util.Objects;\n\n\n\npublic class Pair<E1,E2> {\n\t\n\tprivate final E1 e1;\n\tprivate final E2 e2;\n\t\n\tpublic Pair(E1 x, E2 y) {\n\t\tsuper();\n\t\tthis.e1 = x;\n\t\tthis.e2 = y;\n\t}\n\n\tpublic E1 get1() {\n\t\treturn e1;\n\t}\n\n\tpublic E2 get2() {\n\t\treturn e2;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Objects.hash(e1, e2);\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj) {\n\t\t\treturn true;\n\t\t}\n\t\tif (obj == null) {\n\t\t\treturn false;\n\t\t}\n\t\tif (getClass() != obj.getClass()) {\n\t\t\treturn false;\n\t\t}\n\t\tPair other = (Pair) obj;\n\t\treturn Objects.equals(e1, other.e1) && Objects.equals(e2, other.e2);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Pair [e1=\" + e1 + \", e2=\" + e2 + \"]\";\n\t}\n\t\n\t\n\n}", "filename": "Pair.java" } ]
[ { "content": "package a03a.sol1;\n\nimport java.util.Collections;\nimport java.util.HashSet;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Set;\nimport java.util.function.BinaryOperator;\n\npublic class CellsFactoryImpl implements CellsFactory {\n\n private static class ValueCell<E> implements Cell<E>{\n private E value;\n\n\n public ValueCell(E value) {\n this.value = value;\n }\n\n @Override\n public E getResult() {\n return this.value;\n }\n\n @Override\n public boolean isModifiable() {\n return true;\n }\n\n @Override\n public Set<Cell<E>> dependsFrom() {\n return Collections.emptySet();\n }\n\n @Override\n public void write(E value) {\n this.value = value;\n }\n }\n \n @Override\n public <E> Cell<E> mutableValueCell(E e) {\n return new ValueCell<>(e);\n }\n\n @Override\n public Cell<Integer> sumOfTwo(Cell<Integer> c1, Cell<Integer> c2) {\n return fromReduction(List.of(c1, c2), Integer::sum);\n }\n\n @Override\n public Cell<String> concatOfThree(Cell<String> c1, Cell<String> c2, Cell<String> c3) {\n return fromReduction(List.of(c1, c2, c3), String::concat);\n }\n\n @Override\n public <E> Cell<E> fromReduction(List<Cell<E>> cellsSet, BinaryOperator<E> op) {\n return new Cell<>(){\n\n @Override\n public E getResult() {\n return cellsSet.stream().map(Cell::getResult).reduce(op).get();\n }\n\n @Override\n public boolean isModifiable() {\n return false;\n }\n\n @Override\n public Set<Cell<E>> dependsFrom() {\n return new HashSet<>(cellsSet);\n }\n\n @Override\n public void write(E value) {\n throw new UnsupportedOperationException(\"Unimplemented method 'write'\");\n }\n };\n }\n\n @Override\n public List<Cell<Integer>> cellsWithSumOnLast(List<Integer> values) {\n return addOperationOnAll(values.stream().map(v -> mutableValueCell(v)).toList(), Integer::sum);\n }\n\n private <E> List<Cell<E>> addOperationOnAll(List<Cell<E>> cells, BinaryOperator<E> op) {\n var outCells = new LinkedList<>(cells);\n outCells.add(fromReduction(cells, op));\n return outCells;\n }\n\n @Override\n public List<Cell<String>> addConcatenationOnAll(List<Cell<String>> cellList){\n var outCells = new LinkedList<>(cellList);\n outCells.add(fromReduction(cellList, String::concat));\n return outCells;\n }\n}", "filename": "CellsFactoryImpl.java" } ]
{ "components": { "imports": "package a03a.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;", "private_init": "\t/*\n\t * Implement the CellsFactory interface as indicated in the init method below.\n\t * Implements a factory for \"cells\" similar to those in a spreadsheet (like Excel),\n\t * which can contain values or operations on the value of other cells. Read\n\t * the comments in the provided interface and especially the tests below for details.\n\t *\n\t * The following are considered optional for the purpose of correcting\n\t * the exercise, but still contribute to achieving the totality of the\n\t * score:\n\t *\n\t * - make all tests pass (i.e., in the mandatory part it is sufficient\n\t * that all tests below pass except one of your choice)\n\t * - the good design of the solution, using design solutions that lead to\n\t * succinct code that avoids repetition and memory waste.\n\t *\n\t * Remove the comment from the init method.\n\t *\n\t * Scoring indications:\n\t * - correctness of the mandatory part (and absence of code defects): 10 points\n\t * - correctness of the optional part: 3 points (additional factory method)\n\t * - quality of the solution: 4 points (for good design)\n\t */\n\n\tprivate CellsFactory factory;\n\n\[email protected]\n\tpublic void init() {\n\t\tthis.factory = new CellsFactoryImpl();\n\t}", "test_functions": [ "\[email protected]\n\tpublic void testMutableValue() {\n\t\t// cell with value 10\n\t\tvar cell = this.factory.mutableValueCell(10);\n\t\tassertTrue(cell.isModifiable());\n\t\tassertTrue(cell.dependsFrom().isEmpty());\n\t\tassertEquals(10, cell.getResult().intValue());\n\t\t// change the value to 20\n\t\tcell.write(20);\n\t\tassertTrue(cell.isModifiable());\n\t\tassertTrue(cell.dependsFrom().isEmpty());\n\t\tassertEquals(20, cell.getResult().intValue());\n\t}", "\[email protected]\n\tpublic void testSumOfTwo() {\n\t\tvar cell1 = this.factory.mutableValueCell(10);\n\t\tvar cell2 = this.factory.mutableValueCell(20);\n\t\t// cell that will contain the sum of the values contained in cell1 and cell2\n\t\tvar sum = this.factory.sumOfTwo(cell1, cell2);\n\t\tassertFalse(sum.isModifiable());\n\t\tassertEquals(Set.of(cell1, cell2), sum.dependsFrom());\n\t\tassertEquals(30, sum.getResult().intValue());\n\t\t// if I change cell1, the sum then changes, etc...\n\t\tcell1.write(11);\n\t\tassertEquals(31, sum.getResult().intValue());\n\t\tcell2.write(21);\n\t\tassertEquals(32, sum.getResult().intValue());\n\t\tassertThrows(UnsupportedOperationException.class, () -> sum.write(0));\n\t}", "\[email protected]\n\tpublic void testConcatOfThree() {\n\t\tvar cell1 = this.factory.mutableValueCell(\"10\");\n\t\tvar cell2 = this.factory.mutableValueCell(\"20\");\n\t\tvar cell3 = this.factory.mutableValueCell(\"30\");\n\t\t// cell that will contain the concatenation of the values contained in three other cells\n\t\tvar c = this.factory.concatOfThree(cell1, cell2, cell3);\n\t\tassertFalse(c.isModifiable());\n\t\tassertEquals(Set.of(cell1, cell2, cell3), c.dependsFrom());\n\t\tassertEquals(\"102030\", c.getResult());\n\t\t// if I change cell1, the result of the concatenation changes, etc...\n\t\tcell1.write(\"11\");\n\t\tassertEquals(\"112030\", c.getResult());\n\t\tassertThrows(UnsupportedOperationException.class, () -> c.write(\"\"));\n\t}", "\[email protected]\n\tpublic void testWithSumOnLast() {\n\t\t// creates 4 cells, 3 with values and then one with the sum\n\t\tvar list = this.factory.cellsWithSumOnLast(List.of(10,20,30));\n\t\tassertEquals(4, list.size());\n\t\tassertTrue(list.get(0).isModifiable());\n\t\tassertTrue(list.get(1).isModifiable());\n\t\tassertTrue(list.get(2).isModifiable());\n\t\tassertFalse(list.get(3).isModifiable());\n\t\tassertEquals(Set.of(list.get(0),list.get(1),list.get(2)), list.get(3).dependsFrom());\n\t\tassertEquals(10, list.get(0).getResult().intValue());\n\t\tassertEquals(20, list.get(1).getResult().intValue());\n\t\tassertEquals(30, list.get(2).getResult().intValue());\n\t\tassertEquals(60, list.get(3).getResult().intValue());\n\t\tlist.get(1).write(21);\n\t\tassertEquals(61, list.get(3).getResult().intValue());\n\t\tassertThrows(UnsupportedOperationException.class, () -> list.get(3).write(0));\n\t}", "\[email protected]\n\tpublic void testAddConcatenationOnAll() {\n\t\tvar cell1 = this.factory.mutableValueCell(\"10\");\n\t\tvar cell2 = this.factory.mutableValueCell(\"20\");\n\t\tvar cell3 = this.factory.mutableValueCell(\"30\");\n\t\t// creates a list with 4 cells, 3 are those given, adds one with the concatenation\n\t\tvar list = this.factory.addConcatenationOnAll(List.of(cell1, cell2, cell3));\n\t\tassertEquals(4, list.size());\n\t\tassertTrue(list.get(0).isModifiable());\n\t\tassertTrue(list.get(1).isModifiable());\n\t\tassertTrue(list.get(2).isModifiable());\n\t\tassertFalse(list.get(3).isModifiable());\n\t\tassertEquals(Set.of(list.get(0),list.get(1),list.get(2)), list.get(3).dependsFrom());\n\t\tassertEquals(\"10\", list.get(0).getResult());\n\t\tassertEquals(\"20\", list.get(1).getResult());\n\t\tassertEquals(\"30\", list.get(2).getResult());\n\t\tassertEquals(\"102030\", list.get(3).getResult());\n\t\tlist.get(1).write(\"21\");\n\t\tassertEquals(\"102130\", list.get(3).getResult());\n\t\tassertThrows(UnsupportedOperationException.class, () -> list.get(3).write(\"0s\"));\n\t\t// list2 has 5 elements, operates on the previous 4 concatenating them with a \",\"\n\t\tvar list2 = this.factory.addConcatenationOnAll(list);\n\t\tassertEquals(\"102130102130\", list2.get(4).getResult());\n\t}", "\[email protected]\n\tpublic void testFromReduction() {\n\t\tvar cell1 = this.factory.mutableValueCell(\"10\");\n\t\tvar cell2 = this.factory.mutableValueCell(\"20\");\n\t\tvar cell3 = this.factory.mutableValueCell(\"30\");\n\t\t// creates a cell that concatenates the results of 3 cells\n\t\tvar cell = this.factory.fromReduction(List.of(cell1, cell2, cell3), String::concat);\n\t\tassertFalse(cell.isModifiable());\n\t\tassertEquals(Set.of(cell1, cell2, cell3), cell.dependsFrom());\n\t\tassertEquals(\"102030\", cell.getResult());\n\t\tcell2.write(\"21\");\n\t\tassertEquals(\"102130\", cell.getResult());\n\t\tassertThrows(UnsupportedOperationException.class, () -> cell.write(\"0\"));\n\t\t// creates another cell that concatenates with comma\n\t\tvar anotherCell = this.factory.fromReduction(List.of(cell1, cell2, cell3, cell), (x, y) -> x + \",\" + y);\n\t\tassertEquals(\"10,21,30,102130\", anotherCell.getResult());\n\t}" ] }, "content": "package a03a.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;\n\npublic class Test {\n\n\t/*\n\t * Implement the CellsFactory interface as indicated in the init method below.\n\t * Implements a factory for \"cells\" similar to those in a spreadsheet (like Excel),\n\t * which can contain values or operations on the value of other cells. Read\n\t * the comments in the provided interface and especially the tests below for details.\n\t *\n\t * The following are considered optional for the purpose of correcting\n\t * the exercise, but still contribute to achieving the totality of the\n\t * score:\n\t *\n\t * - make all tests pass (i.e., in the mandatory part it is sufficient\n\t * that all tests below pass except one of your choice)\n\t * - the good design of the solution, using design solutions that lead to\n\t * succinct code that avoids repetition and memory waste.\n\t *\n\t * Remove the comment from the init method.\n\t *\n\t * Scoring indications:\n\t * - correctness of the mandatory part (and absence of code defects): 10 points\n\t * - correctness of the optional part: 3 points (additional factory method)\n\t * - quality of the solution: 4 points (for good design)\n\t */\n\n\tprivate CellsFactory factory;\n\n\[email protected]\n\tpublic void init() {\n\t\tthis.factory = new CellsFactoryImpl();\n\t}\n\t\n\[email protected]\n\tpublic void testMutableValue() {\n\t\t// cell with value 10\n\t\tvar cell = this.factory.mutableValueCell(10);\n\t\tassertTrue(cell.isModifiable());\n\t\tassertTrue(cell.dependsFrom().isEmpty());\n\t\tassertEquals(10, cell.getResult().intValue());\n\t\t// change the value to 20\n\t\tcell.write(20);\n\t\tassertTrue(cell.isModifiable());\n\t\tassertTrue(cell.dependsFrom().isEmpty());\n\t\tassertEquals(20, cell.getResult().intValue());\n\t}\n\n\[email protected]\n\tpublic void testSumOfTwo() {\n\t\tvar cell1 = this.factory.mutableValueCell(10);\n\t\tvar cell2 = this.factory.mutableValueCell(20);\n\t\t// cell that will contain the sum of the values contained in cell1 and cell2\n\t\tvar sum = this.factory.sumOfTwo(cell1, cell2);\n\t\tassertFalse(sum.isModifiable());\n\t\tassertEquals(Set.of(cell1, cell2), sum.dependsFrom());\n\t\tassertEquals(30, sum.getResult().intValue());\n\t\t// if I change cell1, the sum then changes, etc...\n\t\tcell1.write(11);\n\t\tassertEquals(31, sum.getResult().intValue());\n\t\tcell2.write(21);\n\t\tassertEquals(32, sum.getResult().intValue());\n\t\tassertThrows(UnsupportedOperationException.class, () -> sum.write(0));\n\t}\n\n\[email protected]\n\tpublic void testConcatOfThree() {\n\t\tvar cell1 = this.factory.mutableValueCell(\"10\");\n\t\tvar cell2 = this.factory.mutableValueCell(\"20\");\n\t\tvar cell3 = this.factory.mutableValueCell(\"30\");\n\t\t// cell that will contain the concatenation of the values contained in three other cells\n\t\tvar c = this.factory.concatOfThree(cell1, cell2, cell3);\n\t\tassertFalse(c.isModifiable());\n\t\tassertEquals(Set.of(cell1, cell2, cell3), c.dependsFrom());\n\t\tassertEquals(\"102030\", c.getResult());\n\t\t// if I change cell1, the result of the concatenation changes, etc...\n\t\tcell1.write(\"11\");\n\t\tassertEquals(\"112030\", c.getResult());\n\t\tassertThrows(UnsupportedOperationException.class, () -> c.write(\"\"));\n\t}\n\n\[email protected]\n\tpublic void testWithSumOnLast() {\n\t\t// creates 4 cells, 3 with values and then one with the sum\n\t\tvar list = this.factory.cellsWithSumOnLast(List.of(10,20,30));\n\t\tassertEquals(4, list.size());\n\t\tassertTrue(list.get(0).isModifiable());\n\t\tassertTrue(list.get(1).isModifiable());\n\t\tassertTrue(list.get(2).isModifiable());\n\t\tassertFalse(list.get(3).isModifiable());\n\t\tassertEquals(Set.of(list.get(0),list.get(1),list.get(2)), list.get(3).dependsFrom());\n\t\tassertEquals(10, list.get(0).getResult().intValue());\n\t\tassertEquals(20, list.get(1).getResult().intValue());\n\t\tassertEquals(30, list.get(2).getResult().intValue());\n\t\tassertEquals(60, list.get(3).getResult().intValue());\n\t\tlist.get(1).write(21);\n\t\tassertEquals(61, list.get(3).getResult().intValue());\n\t\tassertThrows(UnsupportedOperationException.class, () -> list.get(3).write(0));\n\t}\n\n\[email protected]\n\tpublic void testAddConcatenationOnAll() {\n\t\tvar cell1 = this.factory.mutableValueCell(\"10\");\n\t\tvar cell2 = this.factory.mutableValueCell(\"20\");\n\t\tvar cell3 = this.factory.mutableValueCell(\"30\");\n\t\t// creates a list with 4 cells, 3 are those given, adds one with the concatenation\n\t\tvar list = this.factory.addConcatenationOnAll(List.of(cell1, cell2, cell3));\n\t\tassertEquals(4, list.size());\n\t\tassertTrue(list.get(0).isModifiable());\n\t\tassertTrue(list.get(1).isModifiable());\n\t\tassertTrue(list.get(2).isModifiable());\n\t\tassertFalse(list.get(3).isModifiable());\n\t\tassertEquals(Set.of(list.get(0),list.get(1),list.get(2)), list.get(3).dependsFrom());\n\t\tassertEquals(\"10\", list.get(0).getResult());\n\t\tassertEquals(\"20\", list.get(1).getResult());\n\t\tassertEquals(\"30\", list.get(2).getResult());\n\t\tassertEquals(\"102030\", list.get(3).getResult());\n\t\tlist.get(1).write(\"21\");\n\t\tassertEquals(\"102130\", list.get(3).getResult());\n\t\tassertThrows(UnsupportedOperationException.class, () -> list.get(3).write(\"0s\"));\n\t\t// list2 has 5 elements, operates on the previous 4 concatenating them with a \",\"\n\t\tvar list2 = this.factory.addConcatenationOnAll(list);\n\t\tassertEquals(\"102130102130\", list2.get(4).getResult());\n\t}\n\n\[email protected]\n\tpublic void testFromReduction() {\n\t\tvar cell1 = this.factory.mutableValueCell(\"10\");\n\t\tvar cell2 = this.factory.mutableValueCell(\"20\");\n\t\tvar cell3 = this.factory.mutableValueCell(\"30\");\n\t\t// creates a cell that concatenates the results of 3 cells\n\t\tvar cell = this.factory.fromReduction(List.of(cell1, cell2, cell3), String::concat);\n\t\tassertFalse(cell.isModifiable());\n\t\tassertEquals(Set.of(cell1, cell2, cell3), cell.dependsFrom());\n\t\tassertEquals(\"102030\", cell.getResult());\n\t\tcell2.write(\"21\");\n\t\tassertEquals(\"102130\", cell.getResult());\n\t\tassertThrows(UnsupportedOperationException.class, () -> cell.write(\"0\"));\n\t\t// creates another cell that concatenates with comma\n\t\tvar anotherCell = this.factory.fromReduction(List.of(cell1, cell2, cell3, cell), (x, y) -> x + \",\" + y);\n\t\tassertEquals(\"10,21,30,102130\", anotherCell.getResult());\n\t}\n\n}", "filename": "Test.java" }
2024
a02b
[ { "content": "package a02b.sol1;\n\nimport java.util.Objects;\n\n\n\npublic class Pair<E1,E2> {\n\t\n\tprivate final E1 e1;\n\tprivate final E2 e2;\n\t\n\tpublic Pair(E1 x, E2 y) {\n\t\tsuper();\n\t\tthis.e1 = x;\n\t\tthis.e2 = y;\n\t}\n\n\tpublic E1 get1() {\n\t\treturn e1;\n\t}\n\n\tpublic E2 get2() {\n\t\treturn e2;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Objects.hash(e1, e2);\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj) {\n\t\t\treturn true;\n\t\t}\n\t\tif (obj == null) {\n\t\t\treturn false;\n\t\t}\n\t\tif (getClass() != obj.getClass()) {\n\t\t\treturn false;\n\t\t}\n\t\tPair other = (Pair) obj;\n\t\treturn Objects.equals(e1, other.e1) && Objects.equals(e2, other.e2);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Pair [e1=\" + e1 + \", e2=\" + e2 + \"]\";\n\t}\n\t\n\t\n\n}", "filename": "Pair.java" }, { "content": "package a02b.sol1;\n\nimport java.util.Map;\nimport java.util.Set;\n\n\npublic interface SimpleDB {\n\n \n void createTable(String name);\n\n \n void addTuple(String tableName, int id, String description, Object value);\n\n \n Set<Integer> ids(String name);\n\n \n Map<String, Object> values(String name, int id);\n\n \n void createViewOfSingleDescription(String viewName, String originName, String description);\n\n \n void createViewOfSingleId(String viewName, String originName, int id);\n}", "filename": "SimpleDB.java" } ]
[ { "content": "package a02b.sol1;\n\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.function.Function;\nimport java.util.function.Supplier;\nimport java.util.stream.Collectors;\n\npublic class SimpleDBImpl implements SimpleDB {\n\n // a Table or View\n interface DBObject { \n Set<Integer> ids();\n Function<Integer, Set<Pair<String, Object>>> elements();\n }\n // Table implementation\n record Table(Map<Integer, Set<Pair<String, Object>>> values) implements DBObject{\n\n @Override\n public Function<Integer, Set<Pair<String, Object>>> elements() {\n return values::get;\n }\n\n @Override\n public Set<Integer> ids() {\n return values.keySet();\n }\n }\n\n // View implementation, note elements are not a data structure, but a function\n record View(Supplier<Set<Integer>> idsSupplier, Function<Integer, Set<Pair<String, Object>>> elements) implements DBObject{\n\n @Override\n public Set<Integer> ids() {\n return idsSupplier.get();\n }\n\n }\n\n private final Map<String, DBObject> objects = new HashMap<>();\n\n @Override\n public void createTable(String name) {\n this.objects.put(name, new Table(new HashMap<>()));\n }\n\n @Override\n public void addTuple(String tableName, int id, String description, Object value) {\n ((Table)this.objects.get(tableName)).values().merge(id, new HashSet<>(Set.of(new Pair<>(description, value))), (s1,s2) -> {s1.addAll(s2); return s1;});\n }\n\n @Override\n public Set<Integer> ids(String name) {\n return this.objects.get(name).ids();\n }\n\n @Override\n public Map<String, Object> values(String name, int id) {\n return this.objects.get(name).elements().apply(id).stream().collect(Collectors.toMap(Pair::get1, Pair::get2));\n }\n\n @Override\n public void createViewOfSingleDescription(String viewName, String originName, String description) {\n this.objects.put(viewName, new View(\n () -> this.objects.get(originName).ids(),\n id -> this.objects.get(originName).elements().apply(id).stream().filter(p -> p.get1().equals(description)).collect(Collectors.toSet())));\n }\n\n @Override\n public void createViewOfSingleId(String viewName, String originName, int id) {\n this.objects.put(viewName, new View(\n () -> Set.of(id),\n i -> this.objects.get(originName).elements().apply(i)));\n }\n}", "filename": "SimpleDBImpl.java" } ]
{ "components": { "imports": "package a02b.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;", "private_init": "\t/*\n\t * Implement the SimpleDB interface as indicated in the init method below.\n\t * Implement a DB made of tables and views (a view shows a part of a table). Read\n\t * the comments in the provided interface and especially the tests below for details.\n\t *\n\t * The following are considered optional for the purpose of being able to correct\n\t * the exercise, but still contribute to achieving the full\n\t * score:\n\t *\n\t * - passing all tests (i.e., in the mandatory part it is sufficient\n\t * that all the tests below pass except for one of your choice)\n\t * - good design of the solution, using design solutions that lead to\n\t * succinct code that avoids repetitions and memory waste.\n\t *\n\t * Remove the comment from the init method.\n\t *\n\t * Scoring indications:\n\t * - correctness of the mandatory part (and absence of defects in the code): 10 points\n\t * - correctness of the optional part: 3 points (additional factory method)\n\t * - quality of the solution: 4 points (for good design)\n\t */\n\n\tprivate SimpleDB simpleDB;\n\n\[email protected]\n\tpublic void init() {\n\t\tthis.simpleDB = new SimpleDBImpl();\n\t\tthis.prepareDB();\n\t}\n\n\tprivate void prepareDB(){\n\t\t// prepares a test DB, made of two tables, containing 3 students (101,102,103) and 2 courses (1001,1002)\n\t\tthis.simpleDB.createTable(\"Student\");\n\t\tthis.simpleDB.createTable(\"Course\");\n\t\t// adds the tuple 101,Name,Red to the Student table, and similarly for the others\n\t\tthis.simpleDB.addTuple(\"Student\", 101, \"Name\", \"Red\");\n\t\tthis.simpleDB.addTuple(\"Student\", 101, \"Year\", 2020);\n\t\tthis.simpleDB.addTuple(\"Student\", 101, \"Course\", 1001);\n\t\tthis.simpleDB.addTuple(\"Student\", 102, \"Name\", \"White\");\n\t\tthis.simpleDB.addTuple(\"Student\", 102, \"Year\", 2021);\n\t\tthis.simpleDB.addTuple(\"Student\", 102, \"Course\", 1002);\n\t\tthis.simpleDB.addTuple(\"Student\", 103, \"Name\", \"Green\");\n\t\tthis.simpleDB.addTuple(\"Student\", 103, \"Year\", 2020);\n\t\tthis.simpleDB.addTuple(\"Student\", 103, \"Course\", 1002);\n\t\tthis.simpleDB.addTuple(\"Course\", 1001, \"Name\", \"OOP\");\n\t\tthis.simpleDB.addTuple(\"Course\", 1002, \"Name\", \"SISOP\");\n\t}", "test_functions": [ "\[email protected]\n\tpublic void testTable() {\n\t\t// verification on the ids of the two tables\n\t\tassertEquals(Set.of(101, 102, 103), this.simpleDB.ids(\"Student\"));\n\t\tassertEquals(Set.of(1001, 1002), this.simpleDB.ids(\"Course\"));\n\t\t// verification on the descriptions of the student table (in id 101)\n\t\tassertEquals(Set.of(\"Name\", \"Year\", \"Course\"), this.simpleDB.values(\"Student\", 101).keySet());\n\t\t// verification on certain tuples of the student table\n\t\tassertEquals(\"Red\", this.simpleDB.values(\"Student\", 101).get(\"Name\"));\n\t\tassertEquals(2021, this.simpleDB.values(\"Student\", 102).get(\"Year\"));\n\t\t// verification on the descriptions of the course table (in id 1001)\n\t\tassertEquals(Set.of(\"Name\"), this.simpleDB.values(\"Course\", 1001).keySet());\n\t\t// verification on a certain tuple of the course table\n\t\tassertEquals(\"SISOP\", this.simpleDB.values(\"Course\", 1002).get(\"Name\"));\n\t}", "\[email protected]\n\tpublic void testViewBySingleDescription() {\n\t\t// a Student_Name view is added, which reports only the name for each student\n\t\t// it is like student, but only shows data on \"Name\"\n\t\tthis.simpleDB.createViewOfSingleDescription(\"Student_Name\", \"Student\", \"Name\");\n\t\tassertEquals(Set.of(101, 102, 103), this.simpleDB.ids(\"Student_Name\"));\n\t\t// the only information for id 101 is that the name is Red, and similarly for the others\n\t\tassertEquals(Map.of(\"Name\", \"Red\"), this.simpleDB.values(\"Student_Name\", 101));\n\t\tassertEquals(Map.of(\"Name\", \"White\"), this.simpleDB.values(\"Student_Name\", 102));\n\t\tassertEquals(Map.of(\"Name\", \"Green\"), this.simpleDB.values(\"Student_Name\", 103));\n\t}", "\[email protected]\n\tpublic void testViewBySingleId() {\n\t\t// a Student_101 view is added, which reports only the data of student 101\n\t\tthis.simpleDB.createViewOfSingleId(\"Student_101\", \"Student\", 101);\n\t\tassertEquals(Set.of(101), this.simpleDB.ids(\"Student_101\"));\n\t\tassertEquals(Map.of(\"Name\", \"Red\", \"Year\", 2020, \"Course\", 1001), this.simpleDB.values(\"Student_101\", 101));\n\t}", "\[email protected]\n\tpublic void testViewOfView() {\n\t\t// two views are combined, creating a Student_101_Name view, which reports only the name of student 101\n\t\tthis.simpleDB.createViewOfSingleDescription(\"Student_Name\", \"Student\", \"Name\");\n\t\tthis.simpleDB.createViewOfSingleId(\"Student_101_Name\", \"Student_Name\", 101);\n\t\tassertEquals(Set.of(101), this.simpleDB.ids(\"Student_101_Name\"));\n\t\tassertEquals(Map.of(\"Name\", \"Red\"), this.simpleDB.values(\"Student_101_Name\", 101));\n\t}" ] }, "content": "package a02b.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;\n\npublic class Test {\n\n\t/*\n\t * Implement the SimpleDB interface as indicated in the init method below.\n\t * Implement a DB made of tables and views (a view shows a part of a table). Read\n\t * the comments in the provided interface and especially the tests below for details.\n\t *\n\t * The following are considered optional for the purpose of being able to correct\n\t * the exercise, but still contribute to achieving the full\n\t * score:\n\t *\n\t * - passing all tests (i.e., in the mandatory part it is sufficient\n\t * that all the tests below pass except for one of your choice)\n\t * - good design of the solution, using design solutions that lead to\n\t * succinct code that avoids repetitions and memory waste.\n\t *\n\t * Remove the comment from the init method.\n\t *\n\t * Scoring indications:\n\t * - correctness of the mandatory part (and absence of defects in the code): 10 points\n\t * - correctness of the optional part: 3 points (additional factory method)\n\t * - quality of the solution: 4 points (for good design)\n\t */\n\n\tprivate SimpleDB simpleDB;\n\n\[email protected]\n\tpublic void init() {\n\t\tthis.simpleDB = new SimpleDBImpl();\n\t\tthis.prepareDB();\n\t}\n\n\tprivate void prepareDB(){\n\t\t// prepares a test DB, made of two tables, containing 3 students (101,102,103) and 2 courses (1001,1002)\n\t\tthis.simpleDB.createTable(\"Student\");\n\t\tthis.simpleDB.createTable(\"Course\");\n\t\t// adds the tuple 101,Name,Red to the Student table, and similarly for the others\n\t\tthis.simpleDB.addTuple(\"Student\", 101, \"Name\", \"Red\");\n\t\tthis.simpleDB.addTuple(\"Student\", 101, \"Year\", 2020);\n\t\tthis.simpleDB.addTuple(\"Student\", 101, \"Course\", 1001);\n\t\tthis.simpleDB.addTuple(\"Student\", 102, \"Name\", \"White\");\n\t\tthis.simpleDB.addTuple(\"Student\", 102, \"Year\", 2021);\n\t\tthis.simpleDB.addTuple(\"Student\", 102, \"Course\", 1002);\n\t\tthis.simpleDB.addTuple(\"Student\", 103, \"Name\", \"Green\");\n\t\tthis.simpleDB.addTuple(\"Student\", 103, \"Year\", 2020);\n\t\tthis.simpleDB.addTuple(\"Student\", 103, \"Course\", 1002);\n\t\tthis.simpleDB.addTuple(\"Course\", 1001, \"Name\", \"OOP\");\n\t\tthis.simpleDB.addTuple(\"Course\", 1002, \"Name\", \"SISOP\");\n\t}\n\n\[email protected]\n\tpublic void testTable() {\n\t\t// verification on the ids of the two tables\n\t\tassertEquals(Set.of(101, 102, 103), this.simpleDB.ids(\"Student\"));\n\t\tassertEquals(Set.of(1001, 1002), this.simpleDB.ids(\"Course\"));\n\t\t// verification on the descriptions of the student table (in id 101)\n\t\tassertEquals(Set.of(\"Name\", \"Year\", \"Course\"), this.simpleDB.values(\"Student\", 101).keySet());\n\t\t// verification on certain tuples of the student table\n\t\tassertEquals(\"Red\", this.simpleDB.values(\"Student\", 101).get(\"Name\"));\n\t\tassertEquals(2021, this.simpleDB.values(\"Student\", 102).get(\"Year\"));\n\t\t// verification on the descriptions of the course table (in id 1001)\n\t\tassertEquals(Set.of(\"Name\"), this.simpleDB.values(\"Course\", 1001).keySet());\n\t\t// verification on a certain tuple of the course table\n\t\tassertEquals(\"SISOP\", this.simpleDB.values(\"Course\", 1002).get(\"Name\"));\n\t}\n\n\[email protected]\n\tpublic void testViewBySingleDescription() {\n\t\t// a Student_Name view is added, which reports only the name for each student\n\t\t// it is like student, but only shows data on \"Name\"\n\t\tthis.simpleDB.createViewOfSingleDescription(\"Student_Name\", \"Student\", \"Name\");\n\t\tassertEquals(Set.of(101, 102, 103), this.simpleDB.ids(\"Student_Name\"));\n\t\t// the only information for id 101 is that the name is Red, and similarly for the others\n\t\tassertEquals(Map.of(\"Name\", \"Red\"), this.simpleDB.values(\"Student_Name\", 101));\n\t\tassertEquals(Map.of(\"Name\", \"White\"), this.simpleDB.values(\"Student_Name\", 102));\n\t\tassertEquals(Map.of(\"Name\", \"Green\"), this.simpleDB.values(\"Student_Name\", 103));\n\t}\n\n\[email protected]\n\tpublic void testViewBySingleId() {\n\t\t// a Student_101 view is added, which reports only the data of student 101\n\t\tthis.simpleDB.createViewOfSingleId(\"Student_101\", \"Student\", 101);\n\t\tassertEquals(Set.of(101), this.simpleDB.ids(\"Student_101\"));\n\t\tassertEquals(Map.of(\"Name\", \"Red\", \"Year\", 2020, \"Course\", 1001), this.simpleDB.values(\"Student_101\", 101));\n\t}\n\n\n\[email protected]\n\tpublic void testViewOfView() {\n\t\t// two views are combined, creating a Student_101_Name view, which reports only the name of student 101\n\t\tthis.simpleDB.createViewOfSingleDescription(\"Student_Name\", \"Student\", \"Name\");\n\t\tthis.simpleDB.createViewOfSingleId(\"Student_101_Name\", \"Student_Name\", 101);\n\t\tassertEquals(Set.of(101), this.simpleDB.ids(\"Student_101_Name\"));\n\t\tassertEquals(Map.of(\"Name\", \"Red\"), this.simpleDB.values(\"Student_101_Name\", 101));\n\t}\n}", "filename": "Test.java" }
2024
a01a
[ { "content": "package a01a.sol1;\n\nimport java.util.List;\nimport java.util.Set;\n\n\npublic interface ComposableParserFactory {\n\n \n <X> ComposableParser<X> empty();\n \n \n <X> ComposableParser<X> one(X x);\n \n \n <X> ComposableParser<X> fromList(List<X> list);\n\n \n <X> ComposableParser<X> fromAnyList(Set<List<X>> input);\n\n \n <X> ComposableParser<X> seq(ComposableParser<X> parser, List<X> list);\n\n \n <X> ComposableParser<X> or(ComposableParser<X> p1, ComposableParser<X> p2);\n}", "filename": "ComposableParserFactory.java" }, { "content": "package a01a.sol1;\n\nimport java.util.List;\n\n\npublic interface ComposableParser<T> {\n\n \n boolean parse(T t);\n\n \n boolean end();\n\n \n default boolean parseMany(List<T> list){\n return list.stream().allMatch(this::parse);\n }\n\n \n default boolean parseToEnd(List<T> list){\n return parseMany(list) && end();\n }\n\n}", "filename": "ComposableParser.java" }, { "content": "package a01a.sol1;\n\nimport java.util.Objects;\n\n\n\npublic class Pair<E1,E2> {\n\t\n\tprivate final E1 e1;\n\tprivate final E2 e2;\n\t\n\tpublic Pair(E1 x, E2 y) {\n\t\tsuper();\n\t\tthis.e1 = x;\n\t\tthis.e2 = y;\n\t}\n\n\tpublic E1 get1() {\n\t\treturn e1;\n\t}\n\n\tpublic E2 get2() {\n\t\treturn e2;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Objects.hash(e1, e2);\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj) {\n\t\t\treturn true;\n\t\t}\n\t\tif (obj == null) {\n\t\t\treturn false;\n\t\t}\n\t\tif (getClass() != obj.getClass()) {\n\t\t\treturn false;\n\t\t}\n\t\tPair other = (Pair) obj;\n\t\treturn Objects.equals(e1, other.e1) && Objects.equals(e2, other.e2);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Pair [e1=\" + e1 + \", e2=\" + e2 + \"]\";\n\t}\n\t\n\t\n\n}", "filename": "Pair.java" } ]
[ { "content": "package a01a.sol1;\n\nimport java.util.Collections;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Set;\nimport static java.util.stream.Collectors.*;\nimport java.util.stream.Stream;\n\npublic class ComposableParserFactoryImpl implements ComposableParserFactory {\n\n private static class ComposableParserImpl<T> implements ComposableParser<T>{\n private Set<Iterator<T>> iterators;\n public ComposableParserImpl(Set<Iterator<T>> iterators){\n this.iterators = Set.copyOf(iterators);\n }\n @Override\n public boolean parse(T t) { \n iterators = iterators // at each parsing, less iterators remain!\n .stream()\n .filter(Iterator::hasNext)\n .filter(it -> it.next().equals(t))\n .collect(toSet());\n return !iterators.isEmpty();\n }\n @Override\n public boolean end() {\n return iterators.stream().anyMatch(it -> !it.hasNext());\n }\n }\n\n private static <X> Stream<Iterator<X>> asStream(ComposableParser<X> parser){\n return ((ComposableParserImpl<X>)parser).iterators.stream();\n }\n\n @Override\n public <X> ComposableParser<X> empty() {\n return fromList(Collections.emptyList());\n }\n\n @Override\n public <X> ComposableParser<X> one(X x) {\n return fromList(List.of(x));\n }\n\n @Override\n public <X> ComposableParser<X> fromList(List<X> elements) {\n return fromAnyList(Set.of(elements));\n }\n\n @Override\n public <X> ComposableParser<X> fromAnyList(Set<List<X>> elements) {\n return new ComposableParserImpl<>(elements.stream().map(List::iterator).collect(toSet()));\n }\n\n @Override\n public <X> ComposableParser<X> seq(ComposableParser<X> p, List<X> elements){\n return new ComposableParserImpl<>(asStream(p).map(it -> seq(it, elements.stream())).collect(toSet()));\n }\n\n @Override\n public <X> ComposableParser<X> or(ComposableParser<X> p1, ComposableParser<X> p2) {\n return new ComposableParserImpl<>(Stream.concat(asStream(p1), asStream(p2)).collect(toSet()));\n }\n\n private <X> Iterator<X> seq(Iterator<X> i1, Stream<X> i2){\n return Stream.concat(Stream.iterate(i1, Iterator::hasNext, it -> it).map(Iterator::next), i2).iterator();\n }\n}", "filename": "ComposableParserFactoryImpl.java" } ]
{ "components": { "imports": "package a01a.sol1;\n\nimport static org.junit.Assert.*;\n\nimport java.util.*;\nimport java.util.function.Supplier;", "private_init": "\t/*\n\t * Implement the ComposableParserFactory interface as indicated in the method\n\t * initFactory below. Create a factory for a concept of ComposableParser:\n\t * essentially a parser (recognizer) of finite sequences of elements.\n\t *\n\t * The following are considered optional for the purpose of being able to correct\n\t * the exercise, but still contribute to achieving the totality of the\n\t * score:\n\t *\n\t * - implementation of all methods of the factory (i.e., in the mandatory part it is sufficient to implement all of them except one at will --\n\t * considering that fromList and fromAnyList are in fact mandatory)\n\t * - the good design of the solution, using design solutions that lead to\n\t * succinct code that avoids repetitions and waste of memory\n\t *\n\t * Remove the comment from the initFactory method.\n\t *\n\t * Scoring indications:\n\t * - correctness of the mandatory part (and absence of defects to the code): 10 points\n\t * - correctness of the optional part: 3 points (additional method of the factory)\n\t * - quality of the solution: 4 points (for good design)\n\t */\n\n\tprivate ComposableParserFactory factory;\n\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.factory = new ComposableParserFactoryImpl();\n\t}", "test_functions": [ "\[email protected]\n\tpublic void testEmpty() {\n\t\t// Recognizer of an empty sequence: parsing must end immediately\n\t\tvar p1 = this.factory.empty();\n\t\tassertTrue(p1.end());\n\n\t\tp1 = this.factory.empty();\n\t\tassertTrue(this.factory.empty().parseToEnd(List.of()));\n\t}", "\[email protected]\n\tpublic void testOne() {\n\t\t// Recognizer of sequence (\"a\"): it must recognize \"a\" and then terminate\n\t\tvar p1 = this.factory.one(\"a\");\n\t\tassertFalse(p1.end());\n\n\t\tp1 = this.factory.one(\"a\");\n\t\tassertTrue(p1.parse(\"a\"));\n\t\tassertTrue(p1.end());\n\n\t\tp1 = this.factory.one(\"a\");\n\t\tassertFalse(p1.parse(\"b\"));\n\n\t\t// verification of correct operation of parseToEnd and parseMany\n\t\tassertTrue(this.factory.one(\"a\").parseToEnd(List.of(\"a\")));\n\t\tassertTrue(this.factory.one(\"a\").parseMany(List.of(\"a\")));\n\t\tassertTrue(this.factory.one(\"a\").parseMany(List.of()));\n\t}", "\[email protected]\n\tpublic void testFromList() {\n\t\t// Recognizer of sequence (10,20,30)\n\t\tvar p1 = this.factory.fromList(List.of(10,20,30));\n\t\tassertTrue(p1.parse(10));\n\t\tassertTrue(p1.parse(20));\n\t\tassertTrue(p1.parse(30));\n\t\tassertTrue(p1.end());\n\n\t\tp1 = this.factory.fromList(List.of(10,20,30));\n\t\tassertTrue(p1.parseMany(List.of(10,20)));\n\t\tassertTrue(p1.parse(30));\n\t\tassertTrue(p1.end());\n\n\t\tassertTrue(this.factory.fromList(List.of(10,20,30)).parseMany(List.of(10,20,30)));\n\t\tassertTrue(this.factory.fromList(List.of(10,20,30)).parseMany(List.of(10,20)));\n\t\tassertTrue(this.factory.fromList(List.of(10,20,30)).parseMany(List.of(10)));\n\t\tassertTrue(this.factory.fromList(List.of(10,20,30)).parseToEnd(List.of(10,20,30)));\n\n\t\tassertFalse(this.factory.fromList(List.of(10,20,30)).parseMany(List.of(10,30)));\n\t\tassertFalse(this.factory.fromList(List.of(10,20,30)).parseMany(List.of(10,20,30,40)));\n\t\tassertFalse(this.factory.fromList(List.of(10,20,30)).parseToEnd(List.of(10,20)));\n\t}", "\[email protected]\n\tpublic void testFromAnyList() {\n\t\t// Recognizer of (10,20,30) or (10,100,200)\n\t\tSet<List<Integer>> input = Set.of(List.of(10,20,30), List.of(10,100,200));\n\t\tassertTrue(this.factory.fromAnyList(input).parseMany(List.of(10,20,30)));\n\t\tassertTrue(this.factory.fromAnyList(input).parseMany(List.of(10,20)));\n\t\tassertTrue(this.factory.fromAnyList(input).parseMany(List.of(10)));\n\t\tassertTrue(this.factory.fromAnyList(input).parseMany(List.of(10,100)));\n\t\tassertTrue(this.factory.fromAnyList(input).parseMany(List.of(10,100,200)));\n\t\tassertTrue(this.factory.fromAnyList(input).parseToEnd(List.of(10,20,30)));\n\t\tassertTrue(this.factory.fromAnyList(input).parseToEnd(List.of(10,100,200)));\n\n\t\tassertFalse(this.factory.fromAnyList(input).parseMany(List.of(10,20,200)));\n\t\tassertFalse(this.factory.fromAnyList(input).parseMany(List.of(10,100,30)));\n\t\tassertFalse(this.factory.fromAnyList(input).parseToEnd(List.of(10,20)));\n\t\tassertFalse(this.factory.fromAnyList(input).parseToEnd(List.of(10,100)));\n\t}", "\[email protected]\n\tpublic void testOr() {\n\t\t// Recognizer of (10,20,30) or (10,100,200), or (10,2000,3000)\n\t\t// note: p1 and p2 as Supplier are used to generate a new parser each time,\n\t\t// \t\tto avoid redefining the variables\n\t\tSupplier<ComposableParser<Integer>> p1 = () -> this.factory.fromAnyList(Set.of(List.of(10,20,30), List.of(10,100,200)));\n\t\tSupplier<ComposableParser<Integer>> p2 = () -> this.factory.fromList(List.of(10,2000,3000));\n\t\tassertTrue(this.factory.or(p1.get(), p2.get()).parseToEnd(List.of(10,20,30)));\n\t\tassertTrue(this.factory.or(p1.get(), p2.get()).parseToEnd(List.of(10,100,200)));\n\t\tassertTrue(this.factory.or(p1.get(), p2.get()).parseToEnd(List.of(10,2000,3000)));\n\n\t\tassertFalse(this.factory.or(p1.get(), p2.get()).parseToEnd(List.of(10,20)));\n\t\tassertFalse(this.factory.or(p1.get(), p2.get()).parseToEnd(List.of(10,100,200,3000)));\n\t\tassertFalse(this.factory.or(p1.get(), p2.get()).parseToEnd(List.of(10,2000)));\n\t}", "\[email protected]\n\tpublic void testSeq() {\n\t\t// Recognizer of (10,20,30) or (10,100,200), which then proceeds recognizing (1000,2000)\n\t\tSupplier<ComposableParser<Integer>> p = ()->this.factory.fromAnyList(Set.of(List.of(10,20,30), List.of(10,100,200)));\n\t\tassertTrue(this.factory.seq(p.get(), List.of(1000,2000)).parseToEnd(List.of(10,20,30,1000,2000)));\n\t\tassertTrue(this.factory.seq(p.get(), List.of(1000,2000)).parseToEnd(List.of(10,100,200,1000,2000)));\n\n\t\tassertFalse(this.factory.seq(p.get(), List.of(1000,2000)).parseToEnd(List.of(10,20,30)));\n\t\tassertFalse(this.factory.seq(p.get(), List.of(1000,2000)).parseToEnd(List.of(10,20,30,2000)));\n\t}" ] }, "content": "package a01a.sol1;\n\nimport static org.junit.Assert.*;\n\nimport java.util.*;\nimport java.util.function.Supplier;\n\npublic class Test {\n\n\t/*\n\t * Implement the ComposableParserFactory interface as indicated in the method\n\t * initFactory below. Create a factory for a concept of ComposableParser:\n\t * essentially a parser (recognizer) of finite sequences of elements.\n\t *\n\t * The following are considered optional for the purpose of being able to correct\n\t * the exercise, but still contribute to achieving the totality of the\n\t * score:\n\t *\n\t * - implementation of all methods of the factory (i.e., in the mandatory part it is sufficient to implement all of them except one at will --\n\t * considering that fromList and fromAnyList are in fact mandatory)\n\t * - the good design of the solution, using design solutions that lead to\n\t * succinct code that avoids repetitions and waste of memory\n\t *\n\t * Remove the comment from the initFactory method.\n\t *\n\t * Scoring indications:\n\t * - correctness of the mandatory part (and absence of defects to the code): 10 points\n\t * - correctness of the optional part: 3 points (additional method of the factory)\n\t * - quality of the solution: 4 points (for good design)\n\t */\n\n\tprivate ComposableParserFactory factory;\n\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.factory = new ComposableParserFactoryImpl();\n\t}\n\n\[email protected]\n\tpublic void testEmpty() {\n\t\t// Recognizer of an empty sequence: parsing must end immediately\n\t\tvar p1 = this.factory.empty();\n\t\tassertTrue(p1.end());\n\n\t\tp1 = this.factory.empty();\n\t\tassertTrue(this.factory.empty().parseToEnd(List.of()));\n\t}\n\n\[email protected]\n\tpublic void testOne() {\n\t\t// Recognizer of sequence (\"a\"): it must recognize \"a\" and then terminate\n\t\tvar p1 = this.factory.one(\"a\");\n\t\tassertFalse(p1.end());\n\n\t\tp1 = this.factory.one(\"a\");\n\t\tassertTrue(p1.parse(\"a\"));\n\t\tassertTrue(p1.end());\n\n\t\tp1 = this.factory.one(\"a\");\n\t\tassertFalse(p1.parse(\"b\"));\n\n\t\t// verification of correct operation of parseToEnd and parseMany\n\t\tassertTrue(this.factory.one(\"a\").parseToEnd(List.of(\"a\")));\n\t\tassertTrue(this.factory.one(\"a\").parseMany(List.of(\"a\")));\n\t\tassertTrue(this.factory.one(\"a\").parseMany(List.of()));\n\t}\n\n\[email protected]\n\tpublic void testFromList() {\n\t\t// Recognizer of sequence (10,20,30)\n\t\tvar p1 = this.factory.fromList(List.of(10,20,30));\n\t\tassertTrue(p1.parse(10));\n\t\tassertTrue(p1.parse(20));\n\t\tassertTrue(p1.parse(30));\n\t\tassertTrue(p1.end());\n\n\t\tp1 = this.factory.fromList(List.of(10,20,30));\n\t\tassertTrue(p1.parseMany(List.of(10,20)));\n\t\tassertTrue(p1.parse(30));\n\t\tassertTrue(p1.end());\n\n\t\tassertTrue(this.factory.fromList(List.of(10,20,30)).parseMany(List.of(10,20,30)));\n\t\tassertTrue(this.factory.fromList(List.of(10,20,30)).parseMany(List.of(10,20)));\n\t\tassertTrue(this.factory.fromList(List.of(10,20,30)).parseMany(List.of(10)));\n\t\tassertTrue(this.factory.fromList(List.of(10,20,30)).parseToEnd(List.of(10,20,30)));\n\n\t\tassertFalse(this.factory.fromList(List.of(10,20,30)).parseMany(List.of(10,30)));\n\t\tassertFalse(this.factory.fromList(List.of(10,20,30)).parseMany(List.of(10,20,30,40)));\n\t\tassertFalse(this.factory.fromList(List.of(10,20,30)).parseToEnd(List.of(10,20)));\n\t}\n\n\[email protected]\n\tpublic void testFromAnyList() {\n\t\t// Recognizer of (10,20,30) or (10,100,200)\n\t\tSet<List<Integer>> input = Set.of(List.of(10,20,30), List.of(10,100,200));\n\t\tassertTrue(this.factory.fromAnyList(input).parseMany(List.of(10,20,30)));\n\t\tassertTrue(this.factory.fromAnyList(input).parseMany(List.of(10,20)));\n\t\tassertTrue(this.factory.fromAnyList(input).parseMany(List.of(10)));\n\t\tassertTrue(this.factory.fromAnyList(input).parseMany(List.of(10,100)));\n\t\tassertTrue(this.factory.fromAnyList(input).parseMany(List.of(10,100,200)));\n\t\tassertTrue(this.factory.fromAnyList(input).parseToEnd(List.of(10,20,30)));\n\t\tassertTrue(this.factory.fromAnyList(input).parseToEnd(List.of(10,100,200)));\n\n\t\tassertFalse(this.factory.fromAnyList(input).parseMany(List.of(10,20,200)));\n\t\tassertFalse(this.factory.fromAnyList(input).parseMany(List.of(10,100,30)));\n\t\tassertFalse(this.factory.fromAnyList(input).parseToEnd(List.of(10,20)));\n\t\tassertFalse(this.factory.fromAnyList(input).parseToEnd(List.of(10,100)));\n\t}\n\n\[email protected]\n\tpublic void testOr() {\n\t\t// Recognizer of (10,20,30) or (10,100,200), or (10,2000,3000)\n\t\t// note: p1 and p2 as Supplier are used to generate a new parser each time,\n\t\t// \t\tto avoid redefining the variables\n\t\tSupplier<ComposableParser<Integer>> p1 = () -> this.factory.fromAnyList(Set.of(List.of(10,20,30), List.of(10,100,200)));\n\t\tSupplier<ComposableParser<Integer>> p2 = () -> this.factory.fromList(List.of(10,2000,3000));\n\t\tassertTrue(this.factory.or(p1.get(), p2.get()).parseToEnd(List.of(10,20,30)));\n\t\tassertTrue(this.factory.or(p1.get(), p2.get()).parseToEnd(List.of(10,100,200)));\n\t\tassertTrue(this.factory.or(p1.get(), p2.get()).parseToEnd(List.of(10,2000,3000)));\n\n\t\tassertFalse(this.factory.or(p1.get(), p2.get()).parseToEnd(List.of(10,20)));\n\t\tassertFalse(this.factory.or(p1.get(), p2.get()).parseToEnd(List.of(10,100,200,3000)));\n\t\tassertFalse(this.factory.or(p1.get(), p2.get()).parseToEnd(List.of(10,2000)));\n\t}\n\n\[email protected]\n\tpublic void testSeq() {\n\t\t// Recognizer of (10,20,30) or (10,100,200), which then proceeds recognizing (1000,2000)\n\t\tSupplier<ComposableParser<Integer>> p = ()->this.factory.fromAnyList(Set.of(List.of(10,20,30), List.of(10,100,200)));\n\t\tassertTrue(this.factory.seq(p.get(), List.of(1000,2000)).parseToEnd(List.of(10,20,30,1000,2000)));\n\t\tassertTrue(this.factory.seq(p.get(), List.of(1000,2000)).parseToEnd(List.of(10,100,200,1000,2000)));\n\n\t\tassertFalse(this.factory.seq(p.get(), List.of(1000,2000)).parseToEnd(List.of(10,20,30)));\n\t\tassertFalse(this.factory.seq(p.get(), List.of(1000,2000)).parseToEnd(List.of(10,20,30,2000)));\n\t}\n}", "filename": "Test.java" }
2024
a02a
[ { "content": "package a02a.sol1;\n\nimport java.util.List;\nimport java.util.Optional;\nimport java.util.Set;\n\n\npublic interface SpreadRow {\n\n \n int size();\n\n \n boolean isFormula(int index);\n\n \n boolean isNumber(int index);\n\n \n boolean isEmpty(int index);\n\n \n List<Optional<Integer>> computeValues();\n\n \n void putNumber(int index, int number);\n \n \n void putSumOfTwoFormula(int resultIndex, int index1, int index2);\n\n \n void putMultiplyElementsFormula(int resultIndex, Set<Integer> indexes);\n\n}", "filename": "SpreadRow.java" }, { "content": "package a02a.sol1;\n\nimport java.util.Objects;\n\n\n\npublic class Pair<E1,E2> {\n\t\n\tprivate final E1 e1;\n\tprivate final E2 e2;\n\t\n\tpublic Pair(E1 x, E2 y) {\n\t\tsuper();\n\t\tthis.e1 = x;\n\t\tthis.e2 = y;\n\t}\n\n\tpublic E1 get1() {\n\t\treturn e1;\n\t}\n\n\tpublic E2 get2() {\n\t\treturn e2;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Objects.hash(e1, e2);\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj) {\n\t\t\treturn true;\n\t\t}\n\t\tif (obj == null) {\n\t\t\treturn false;\n\t\t}\n\t\tif (getClass() != obj.getClass()) {\n\t\t\treturn false;\n\t\t}\n\t\tPair other = (Pair) obj;\n\t\treturn Objects.equals(e1, other.e1) && Objects.equals(e2, other.e2);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Pair [e1=\" + e1 + \", e2=\" + e2 + \"]\";\n\t}\n\t\n\t\n\n}", "filename": "Pair.java" } ]
[ { "content": "package a02a.sol1;\n\nimport java.util.Collections;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Optional;\nimport java.util.Set;\nimport java.util.function.BinaryOperator;\n\npublic class SpreadRowImpl implements SpreadRow {\n\n private static record Cell(BinaryOperator<Integer> op, int base, Set<Integer> cells){\n public int result(List<Optional<Integer>> results){\n return cells.stream().map(results::get).map(Optional::get).reduce(base, op);\n }\n }\n private List<Cell> row = new LinkedList<>();\n\n public SpreadRowImpl(int size) {\n for (int i = 0; i < size; i++){\n this.row.add(null);\n }\n }\n\n @Override\n public int size() {\n return this.row.size();\n }\n\n @Override\n public boolean isFormula(int index) {\n return !this.isEmpty(index) && !this.row.get(index).cells().isEmpty();\n }\n\n @Override\n public boolean isNumber(int index) {\n return !this.isEmpty(index) && !this.isFormula(index);\n }\n\n @Override\n public boolean isEmpty(int index) {\n return this.row.get(index) == null;\n }\n\n @Override\n public List<Optional<Integer>> computeValues() {\n final List<Optional<Integer>> results = new LinkedList<>(); // used to store elements during stream computation\n return this.row\n .stream()\n .map(Optional::ofNullable)\n .map(opt -> opt.map(c -> c.result(results)))\n .peek(results::add)\n .toList();\n }\n\n @Override\n public void putNumber(int index, int number) {\n this.row.set(index, new Cell((x, y) -> 0, number, Collections.emptySet()));\n }\n\n @Override\n public void putSumOfTwoFormula(int resultIndex, int index1, int index2) {\n this.row.set(resultIndex, new Cell((x, y) -> x+y, 0, Set.of(index1, index2)));\n }\n\n @Override\n public void putMultiplyElementsFormula(int index, Set<Integer> indexes) {\n this.row.set(index, new Cell((x, y) -> x*y, 1, Set.copyOf(indexes)));\n }\n}", "filename": "SpreadRowImpl.java" } ]
{ "components": { "imports": "package a02a.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;", "private_init": "\t/*\n\t * Implement the SpreadRow interface as indicated in the init method below.\n\t * Create a sort of \"excel sheet\" (Spreadsheet) made of a single row.\n\t * Read the comments in the provided interface and the tests below for details.\n\t *\n\t * The following are considered optional for the purpose of being able to correct\n\t * the exercise, but still contribute to achieving the full\n\t * score:\n\t *\n\t * - passing all tests (i.e., in the mandatory part it is sufficient\n\t * that all the tests below pass except for one of your choice)\n\t * - good design of the solution, using design solutions that lead to\n\t * succinct code that avoids repetitions and memory waste.\n\t *\n\t * Remove the comment from the initFactory method.\n\t *\n\t * Scoring indications:\n\t * - correctness of the mandatory part (and absence of code defects): 10 points\n\t * - correctness of the optional part: 3 points (additional factory method)\n\t * - quality of the solution: 4 points (for good design)\n\t */\n\n\tprivate SpreadRow spreadRow;\n\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.spreadRow = new SpreadRowImpl(5); // 5 cells\n\t}", "test_functions": [ "\[email protected]\n\tpublic void testInitial() {\n\t\t// a SpreadRow with all empty cells: _,_,_,_,_\n\t\tassertEquals(5, this.spreadRow.size());\n\t\tassertTrue(this.spreadRow.isEmpty(0));\n\t\tassertTrue(this.spreadRow.isEmpty(1));\n\t\tassertTrue(this.spreadRow.isEmpty(2));\n\t\tassertTrue(this.spreadRow.isEmpty(3));\n\t\tassertTrue(this.spreadRow.isEmpty(4));\n\t\tassertFalse(this.spreadRow.isFormula(0));\n\t\tassertFalse(this.spreadRow.isNumber(0));\n\t}", "\[email protected]\n\tpublic void testAddNumbers() {\n\t\t// a SpreadRow with values 10,20,30 in the first three cells: 10,20,30,_,_\n\t\tassertEquals(5, this.spreadRow.size());\n\t\tthis.spreadRow.putNumber(0, 10);\n\t\tthis.spreadRow.putNumber(1, 20);\n\t\tthis.spreadRow.putNumber(2, 30);\n\t\tassertFalse(this.spreadRow.isEmpty(0));\n\t\tassertFalse(this.spreadRow.isEmpty(1));\n\t\tassertFalse(this.spreadRow.isEmpty(2));\n\t\tassertTrue(this.spreadRow.isEmpty(3));\n\t\tassertTrue(this.spreadRow.isEmpty(4));\n\t\tassertTrue(this.spreadRow.isNumber(0));\n\t\tassertTrue(this.spreadRow.isNumber(1));\n\t\tassertTrue(this.spreadRow.isNumber(2));\n\t\tassertEquals(List.of(Optional.of(10), Optional.of(20), Optional.of(30), Optional.empty(), Optional.empty()),\n\t\t\tthis.spreadRow.computeValues());\n\t}", "\[email protected]\n\tpublic void testSumOfTwo() {\n\t\t// SpreadRow: _,10,20,_,#1+#2\n\t\tassertEquals(5, this.spreadRow.size());\n\t\tthis.spreadRow.putNumber(1, 10);\n\t\tthis.spreadRow.putNumber(2, 20);\n\t\tthis.spreadRow.putSumOfTwoFormula(4, 1, 2);\n\t\tassertTrue(this.spreadRow.isFormula(4));\n\t\tassertEquals(List.of(Optional.empty(), Optional.of(10), Optional.of(20), Optional.empty(), Optional.of(30)),\n\t\t\tthis.spreadRow.computeValues());\n\t\t// SpreadRow: _,11,20,_,#1+#2\n\t\tthis.spreadRow.putNumber(1, 11);\n\t\tassertEquals(List.of(Optional.empty(), Optional.of(11), Optional.of(20), Optional.empty(), Optional.of(31)),\n\t\t\tthis.spreadRow.computeValues());\n\t}", "\[email protected]\n\tpublic void testMultiply() {\n\t\t// SpreadRow: -1,10,20,30,#0*#2*#3\n\t\tassertEquals(5, this.spreadRow.size());\n\t\tthis.spreadRow.putNumber(0, -1);\n\t\tthis.spreadRow.putNumber(1, 10);\n\t\tthis.spreadRow.putNumber(2, 20);\n\t\tthis.spreadRow.putNumber(3, 30);\n\t\tthis.spreadRow.putMultiplyElementsFormula(4, Set.of(0, 2, 3));\n\t\tassertTrue(this.spreadRow.isFormula(4));\n\t\tassertEquals(List.of(Optional.of(-1), Optional.of(10), Optional.of(20), Optional.of(30), Optional.of(-600)),\n\t\t\tthis.spreadRow.computeValues());\n\t\t// SpreadRow: 1,10,20,30,#0*#2*#3\n\t\tthis.spreadRow.putNumber(0, 1);\n\t\tassertEquals(List.of(Optional.of(1), Optional.of(10), Optional.of(20), Optional.of(30), Optional.of(600)),\n\t\t\tthis.spreadRow.computeValues());\n\t}", "\[email protected]\n\tpublic void testCombined() {\n\t\t// SpreadRow: 10,20,#0+#1,#1+#2,#2*#3\n\t\tassertEquals(5, this.spreadRow.size());\n\t\tthis.spreadRow.putNumber(0, 10);\n\t\tthis.spreadRow.putNumber(1, 20);\n\t\tthis.spreadRow.putSumOfTwoFormula(2, 0, 1); // 30\n\t\tthis.spreadRow.putSumOfTwoFormula(3, 1, 2); // 50\n\t\tthis.spreadRow.putMultiplyElementsFormula(4, Set.of(2, 3)); // 1500\n\t\tassertEquals(List.of(Optional.of(10), Optional.of(20), Optional.of(30), Optional.of(50), Optional.of(1500)),\n\t\t\tthis.spreadRow.computeValues());\n\t}" ] }, "content": "package a02a.sol1;\n\nimport static org.junit.Assert.*;\nimport java.util.*;\n\npublic class Test {\n\n\t/*\n\t * Implement the SpreadRow interface as indicated in the init method below.\n\t * Create a sort of \"excel sheet\" (Spreadsheet) made of a single row.\n\t * Read the comments in the provided interface and the tests below for details.\n\t *\n\t * The following are considered optional for the purpose of being able to correct\n\t * the exercise, but still contribute to achieving the full\n\t * score:\n\t *\n\t * - passing all tests (i.e., in the mandatory part it is sufficient\n\t * that all the tests below pass except for one of your choice)\n\t * - good design of the solution, using design solutions that lead to\n\t * succinct code that avoids repetitions and memory waste.\n\t *\n\t * Remove the comment from the initFactory method.\n\t *\n\t * Scoring indications:\n\t * - correctness of the mandatory part (and absence of code defects): 10 points\n\t * - correctness of the optional part: 3 points (additional factory method)\n\t * - quality of the solution: 4 points (for good design)\n\t */\n\n\tprivate SpreadRow spreadRow;\n\n\[email protected]\n\tpublic void initFactory() {\n\t\tthis.spreadRow = new SpreadRowImpl(5); // 5 cells\n\t}\n\n\[email protected]\n\tpublic void testInitial() {\n\t\t// a SpreadRow with all empty cells: _,_,_,_,_\n\t\tassertEquals(5, this.spreadRow.size());\n\t\tassertTrue(this.spreadRow.isEmpty(0));\n\t\tassertTrue(this.spreadRow.isEmpty(1));\n\t\tassertTrue(this.spreadRow.isEmpty(2));\n\t\tassertTrue(this.spreadRow.isEmpty(3));\n\t\tassertTrue(this.spreadRow.isEmpty(4));\n\t\tassertFalse(this.spreadRow.isFormula(0));\n\t\tassertFalse(this.spreadRow.isNumber(0));\n\t}\n\n\[email protected]\n\tpublic void testAddNumbers() {\n\t\t// a SpreadRow with values 10,20,30 in the first three cells: 10,20,30,_,_\n\t\tassertEquals(5, this.spreadRow.size());\n\t\tthis.spreadRow.putNumber(0, 10);\n\t\tthis.spreadRow.putNumber(1, 20);\n\t\tthis.spreadRow.putNumber(2, 30);\n\t\tassertFalse(this.spreadRow.isEmpty(0));\n\t\tassertFalse(this.spreadRow.isEmpty(1));\n\t\tassertFalse(this.spreadRow.isEmpty(2));\n\t\tassertTrue(this.spreadRow.isEmpty(3));\n\t\tassertTrue(this.spreadRow.isEmpty(4));\n\t\tassertTrue(this.spreadRow.isNumber(0));\n\t\tassertTrue(this.spreadRow.isNumber(1));\n\t\tassertTrue(this.spreadRow.isNumber(2));\n\t\tassertEquals(List.of(Optional.of(10), Optional.of(20), Optional.of(30), Optional.empty(), Optional.empty()),\n\t\t\tthis.spreadRow.computeValues());\n\t}\n\n\[email protected]\n\tpublic void testSumOfTwo() {\n\t\t// SpreadRow: _,10,20,_,#1+#2\n\t\tassertEquals(5, this.spreadRow.size());\n\t\tthis.spreadRow.putNumber(1, 10);\n\t\tthis.spreadRow.putNumber(2, 20);\n\t\tthis.spreadRow.putSumOfTwoFormula(4, 1, 2);\n\t\tassertTrue(this.spreadRow.isFormula(4));\n\t\tassertEquals(List.of(Optional.empty(), Optional.of(10), Optional.of(20), Optional.empty(), Optional.of(30)),\n\t\t\tthis.spreadRow.computeValues());\n\t\t// SpreadRow: _,11,20,_,#1+#2\n\t\tthis.spreadRow.putNumber(1, 11);\n\t\tassertEquals(List.of(Optional.empty(), Optional.of(11), Optional.of(20), Optional.empty(), Optional.of(31)),\n\t\t\tthis.spreadRow.computeValues());\n\t}\n\n\[email protected]\n\tpublic void testMultiply() {\n\t\t// SpreadRow: -1,10,20,30,#0*#2*#3\n\t\tassertEquals(5, this.spreadRow.size());\n\t\tthis.spreadRow.putNumber(0, -1);\n\t\tthis.spreadRow.putNumber(1, 10);\n\t\tthis.spreadRow.putNumber(2, 20);\n\t\tthis.spreadRow.putNumber(3, 30);\n\t\tthis.spreadRow.putMultiplyElementsFormula(4, Set.of(0, 2, 3));\n\t\tassertTrue(this.spreadRow.isFormula(4));\n\t\tassertEquals(List.of(Optional.of(-1), Optional.of(10), Optional.of(20), Optional.of(30), Optional.of(-600)),\n\t\t\tthis.spreadRow.computeValues());\n\t\t// SpreadRow: 1,10,20,30,#0*#2*#3\n\t\tthis.spreadRow.putNumber(0, 1);\n\t\tassertEquals(List.of(Optional.of(1), Optional.of(10), Optional.of(20), Optional.of(30), Optional.of(600)),\n\t\t\tthis.spreadRow.computeValues());\n\t}\n\n\[email protected]\n\tpublic void testCombined() {\n\t\t// SpreadRow: 10,20,#0+#1,#1+#2,#2*#3\n\t\tassertEquals(5, this.spreadRow.size());\n\t\tthis.spreadRow.putNumber(0, 10);\n\t\tthis.spreadRow.putNumber(1, 20);\n\t\tthis.spreadRow.putSumOfTwoFormula(2, 0, 1); // 30\n\t\tthis.spreadRow.putSumOfTwoFormula(3, 1, 2); // 50\n\t\tthis.spreadRow.putMultiplyElementsFormula(4, Set.of(2, 3)); // 1500\n\t\tassertEquals(List.of(Optional.of(10), Optional.of(20), Optional.of(30), Optional.of(50), Optional.of(1500)),\n\t\t\tthis.spreadRow.computeValues());\n\t}\n}", "filename": "Test.java" }