- Notifications
You must be signed in to change notification settings - Fork1
Practical tasks of the EPAM course on the LEARN platform. Tasks refer to the Java Basics course.
denys-taranenko/learn-java-basic-epam
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
This document contains descriptions of various problems for practicing Java programming. Each problem is accompanied by a link to the corresponding class in which it can be solved and detailed instructions.
Task
The purpose of this exercise is to make you familiar with the Autocode platform.Estimated workload of this exercise is5 minutes.
Please, proceed toHelloAutocode
classand write a simple program that prints "Hello, Autocode!" (don't print quote marks).
Task
The purpose of this exercise is to familiarize you with basic usage of standard input stream.
Estimated workload of this exercise is5 minutes.
Please, proceed to the classMeetAStranger
.The program must read a string from System.in and print a message "Hello,input".
Note that when entering an input string consisting of several words, the entire input must be printed.
Input:Mrs. Robinson
Output:Hello, Mrs. Robinson
Task
The purpose of this exercise is to familiarize you with basicint
operations.
Estimated workload of this exercise is30 minutes.
Please, proceed toElectronicWatch
class.The program must print an electronic watch screen output for a given value of seconds since midnight.
Input value is given viaSystem.in
. Output value must be printed toSystem.out
It is guaranteed, that input number is non-negative.
Output format ish:mm:ss
(possible values: [0:00:00; 23:59:59]).
Extra challenge: try to solve the task without usingif
statements or cycles.
Input:60
Output:0:01:00
Input:3599
Output:0:59:59
Input:86229
Output:23:57:09
Input:86400
Output:0:00:00
Input:89999
Output:0:59:59
Input:86460
Output:0:01:00
Task
The purpose of this exercise is to familiarize you with simple conditional statements.
Estimated workload of this exercise is20 min.
Please, proceed toMeetAnAgent
classand write a program that:
- asks for an input number,
- if the input equals to the secret password number, prints "Hello, Agent",
- otherwise, prints "Access denied"
Secret password is stored infinal static int PASSWORD
.
Input:133976
Output:Hello, Agent
Input:711
Output:Access denied
Task
The purpose of this exercise is to train you in usage of simple cycles and conditional statements.
Estimated workload of this exercise is20 min.
Please, proceed toHelloStrangers
classand write a program that:
- asks for a number - amount of strangers to meet,
- then reads stranger names line by line
- and, finally, prints line by line "Hello,stranger name" for each stranger.
It is guaranteed that the input is not null.It is guaranteed that the input of strangers count is int number.
Consider special cases:
- If strangers count is zero, then program must print "Oh, it looks like there is no one here".
- If strangers count is negative, then program must print "Seriously? Why so negative?".
Hint: In case you use the Scanner class, it might be helpful sure to check strings it reads be non-empty.
Input:
3AthosPorthosAramis
Output:
Hello, AthosHello, PorthosHello, Aramis
Input:
0
Output:
Oh, it looks like there is no one here
Input:
-3
Output:
Seriously? Why so negative?
Task
The purpose of this exercise is to train you in usage of simple integer operations.
Estimated workload of this exercise is30 min.
Consider a snail travels up a treea
feet each day. Then snail slides downb
feet each night. Height of the tree ish
feet.
Please, proceed toSnail
classand write a program that prints number of days for the snail to reach the top of the tree.
Program readsa
,b
,h
line by line. Input values are guaranteed to be positive integers.
If the snail cannot reach the top of the tree, print the messageImpossible
.
Input:
4214
Output:
6
Input:
4310
Output:
7
Input:
4410
Output:
Impossible
Input:
441
Output:
1
Task
The purpose of this exercise is to familiarize you with basic conditional and cyclic operations.
Estimated workload of this exercise is20 minutes.
Consider a company of friends visiting a restaurant.They decided to equally split the bill.
Friends decided to add 10 percent of the bill total amount as tips.Then they cover the total payment in equal parts.
Please, proceed toGoDutch
classand write a program that reads a bill total amount and a number of friends, and then prints part to pay.
Consider some details:
- Program must read data from System.in
- Bill total amount cannot be negative. If input value is negative, the program stops, printing:
Bill total amount cannot be negative
- Number of friends cannot be negative or zero. If input value is, then the program stops, printing:
Number of friends cannot be negative or zero
- Bill total amount, number of friends and part to pay are integers
Input:
1000 5
Output:
220
Task
The purpose of this exercise is to train you to use simple loops and conditional statements.
Estimated workload of this exercise is20 min.
Please, proceed toFindMaxInSeq
and write a program that reads a sequence of integer values from standard output and finds the maximum value. You mustplace your solution into themax
method to pass tests.
Details:
- You must read sequence values until the next one is
0
. Zero value means end of the input sequence. - The sequence is guaranteed to contain at least one value.
Input:
2 4 6 9 2 4 5 0
Output:
9
Task
The purpose of this exercise is to train you to use simple loops and conditional statements.
Estimated workload of this exercise is20 min.
Please, proceed toAverage
classand write a program that reads a sequence of integer values from standard input and finds the average value.
Details:
- You must read sequence values until the next one is
0
. Zero value means end of the input sequence. - The sequence is guaranteed to contain at least one value.
- Average value is also aninteger. Useinteger operations.
Input:1 2 3 4 5 0
Output:3
Input:1 2 3 4 6 0
Output:3
Input:1 2 3 4 0
Output:2
Input:1 1 9 0
Output:3
Task
The purpose of this exercise is to familiarize you with basic conditional and cyclic operations.
Estimated workload of this exercise is20 minutes.
Please, proceed toPizzaSplit
class.The program must read two values fromSystem.in
:
- number of people;
- number of pieces per pizza.
It is guaranteed that this values are positive integers.
Then the program must print the minimum number of pizzas (not zero) so that everyone has an equal number of slices and no slice is left.
Input:12 8
Output:3
Task
The purpose of this exercise is to train you to design programs that need decision trees.
Estimated workload of this exercise is30 min.
Please, proceed to theQuadraticEquation
class and implement a program to solve quadratic equations.
For the given quadratic equation coefficients (ax2 + bx + c = 0),return one or two roots of the equation if there is any in the set of real numbers.
Input value is given viaSystem.in
. Output value must be printed toSystem.out
.
Output format is:
- "x1 x2" (two roots in any order separated by space) if there are two roots,
- "x" (just the value of the root) if there is the only root,
- "no roots" (just a string value "no roots") if there is no root.
Thea
parameter is guaranteed to be not zero.
Hint:Quadratic formula reference
Input:1 -2 1
Output:1
Input:2 5 -3
Output:-3 0.5
Input:2 2 2
Output:no roots
Task
The purpose of this exercise is to train you to work with arrays.
Estimated workload of this exercise is20 min.
Please, proceed to theMaxMethod
classand implement themax
method.
The correct implementation should receive an array ofint
values and return its maximum value.
Details:
- An input array is guaranteed to not be an empty array or
null
. max
method must not modify the array.- Input array may contain any
int
value betweenInteger.MIN_VALUE
andInteger.MAX_VALUE
.
int[]vals =newint[]{-2,0,10,5};intresult =MaxMethod.max(vals);System.out.println(result ==10);// true
Task
The purpose of this exercise is to train you to work with arrays.
Estimated workload of this exercise is20 min.
Please, proceed to theSumOfEvenNumbers
class andimplement thesum
method.
The correct implementation should receive an array ofint
values and return the sum of even numbers.
Details:
- If given array is null or empty, method returns 0.
sum
method must not modify the array.- Input array may contain any
int
value betweenInteger.MIN_VALUE
andInteger.MAX_VALUE
.
int[]vals =newint[]{-2,10,0,5};intresult =SumOfEvenNumbers.sum(vals);System.out.println(result ==8);// true
Task
The purpose of this exercise is to train you to work with arrays.
Estimated workload of this exercise is20 min.
Please, proceed toSumOfPrevious
classand implementgetSumCheckArray
method.
The correct implementation should receive an array ofint
valuesand return an array of booleans where each element is a resultof a check if a corresponding element is a sumof two previous elements in given array.
Details:
- The length of given array is guaranteed to be 2 or more.
- Given array is guaranteed to be not null.
- Method returns an array of booleans where each element is a result for corresponding element in given array.
- First two elements of the boolean array are always false.
Input array:[1, -1, 0, 4, 6, 10, 15, 25]
Output array:[false, false, true, false, false, true, false, true]
Task
The purpose of this exercise is to train you to work with arrays.
Estimated workload of this exercise is30 min.
Please, proceed to theLocalMaximaRemove
class andimplement theremoveLocalMaxima
method.
The correct implementation should receive an array ofint
valuesand return a copy of a given array with all local maxima removed in it.The original array must not be changed.
Local maximum is an element that is bigger that any of its neighbour elements.You should remove elements that are local maxima in the original array.
Details:
- The size of given array is guaranteed to be more than 1.
- Given array is guaranteed to be not null.
- If the array has no local maxima, then you should return its copy without changes.
- You may use java.util.Arrays.* methods.
Input array:[18, 1, 3, 6, 7, -5]
Output array:[1, 3, 6, -5]
Task
The purpose of this exercise is to train you to work with arrays.
Estimated workload of this exercise is30 min.
Please, proceed toCycleSwap
classand implement its static methods:
void cycleSwap(int[] array)
Shifts all the elements in the given array to the right by 1 position.
In this case, the last array element becomes first.
For example,1 3 2 7 4
becomes4 1 3 2 7
.void cycleSwap(int[] array, int shift)
Shift all the elements in the given array to the right in the cycle manner byshift
positions.
Shift value is guaranteed to be non-negative and not bigger than the array length.
For example,1 3 2 7 4
with a shift of3
becomes2 7 4 1 3
.
For a greater challenge, try not using loops in your code (not mandatory).
Note that input array may be empty.
Code Sample:
...int[]array =newint[]{1,3,2,7,4};CycleSwap.cycleSwap(array);System.out.println(Arrays.toString(array));
Output:
[4, 1, 3, 2, 7]
Code Sample:
...int[]array =newint[]{1,3,2,7,4};CycleSwap.cycleSwap(array,2);System.out.println(Arrays.toString(array));
Output:
[7, 4, 1, 3, 2]
Code Sample:
...int[]array =newint[]{1,3,2,7,4};CycleSwap.cycleSwap(array,5);System.out.println(Arrays.toString(array));
Output:
[1, 3, 2, 7, 4]
Task
The purpose of this exercise is to train you to work with arrays.
Estimated workload of this exercise is45 min.
Please, proceed toSpiral
class and implement its static method:
int[][] spiral(int rows, int columns)
Return a two-dimensional array coming in the form of a table and containing numbers from1
up torows * columns
. The size of the table will be specified by the given parameters.
Numbers fill the "table" clockwise from the top-level corner in a spiral manner.
For example, for parameter values(3, 4)
, the output array should be:1 2 3 410 11 12 5 9 8 7 6
Code Sample:
...int[][]spiral =Spiral.spiral(3,4);for (inti =0;i <spiral.length;i++) {for (intj =0;j <spiral[i].length;j++) {System.out.print(String.format("%4s",spiral[i][j])); }System.out.println();}
Output:
1 2 3 4 10 11 12 5 9 8 7 6
Code Sample:
...int[][]spiral =Spiral.spiral(4,3);for (inti =0;i <spiral.length;i++) {for (intj =0;j <spiral[i].length;j++) {System.out.print(String.format("%4s",spiral[i][j])); }System.out.println();}
Output:
1 2 3 10 11 4 9 12 5 8 7 6
Code Sample:
...int[][]spiral =Spiral.spiral(5,6);for (inti =0;i <spiral.length;i++) {for (intj =0;j <spiral[i].length;j++) {System.out.print(String.format("%4s",spiral[i][j])); }System.out.println();}
Output:
1 2 3 4 5 6 18 19 20 21 22 7 17 28 29 30 23 8 16 27 26 25 24 9 15 14 13 12 11 10
Code Sample:
...int[][]spiral =Spiral.spiral(5,5);for (inti =0;i <spiral.length;i++) {for (intj =0;j <spiral[i].length;j++) {System.out.print(String.format("%4s",spiral[i][j])); }System.out.println();}
Output:
1 2 3 4 5 16 17 18 19 6 15 24 25 20 7 14 23 22 21 8 13 12 11 10 9
Task
The purpose of this exercise is to train you to work with arrays.
Estimated workload of this exercise is45 min.
Please, proceed toTransposeMatrix
class an implement its methodmultiply
.
It takes a rectangular integer array (matrix) as a parameter and returns it transposed.
Consider an integer matrix represented as arectangular array.The task is totranspose a given matrix over its main diagonal.Thetransposition of a matrix over its main diagonal is simply a flipped version of the original matrix.
Hint:Transpose Reference
Input:
{ {0, 1, 2}, {3, 4, 5}, {6, 7, 8} }
Output:
{ {0, 3, 6}, {1, 4, 7}, {2, 5, 8} }
Task
The purpose of this exercise is to train you to work with arrays.
Estimated workload of this exercise is60 min.
Please, proceed toMultiplyMatrix
class and implement itsmultiply
method.
It takes two rectangular integer arrays (matrices) and returns the result of their multiplication.
Consider two integer matrices represented asrectangular arrays. The task is tomultiply given matrices. Thedefinition ofmatrix multiplication indicates a row-by-column multiplication,where the entries in thei-th row ofAare multiplied by the corresponding entries in thej-th column ofBand then theij-th element of the resulting matrix is the sum of that multiplication results.
Note that it is guaranteed thatthe number of columns in the first matrixis equal to the number of rows in the second matrix.
Input:
{{1, 2, 3}, {4, 5, 6}}, {{7 , 8 }, {9 , 10}, {11, 12}}
Output:
{{58 , 64 }, {139, 154}}
Task
The purpose of this exercise is to train you to work with classes and methods.
Estimated workload of this exercise is45 min.
Please, implement the methodintersection(Line)
in classLine
.It must return aPoint
of intersection of two lines.
Note that lines are defined by linear equations:y = k * x + b
.Line constructor takesk
andb
coefficients as parameters.
If lines coincide or do not intersect, the method must return null.It may seem surprising that we useint
for arguments and fields of coordinates.The point is that usingdouble
will bring some extra complexity we want to avoid for this basic exercise.All tests are selected in to induce calculations without remainders.
You may check your result in classMain
.
publicclassMain {publicstaticvoidmain(String[]args) {Lineline1 =newLine(1,1);Lineline2 =newLine(-1,3);System.out.println(line1.intersection(line2));// (1;2) }}
Task
The purpose of this exercise is to train you to work with classes and methods.
Estimated workload of this exercise is45 min.
Please, implement the following methods of classSegment
:
- constructor with start and end points as parameters
Ensure that a created segment exists and is not degenerativewhich means that the start and the end of the segment is not the same point.
If it is, usethrow new IllegalArgumentException()
to raise an error. double length()
Return length of the segment.Point middle()
Return a middle point of the segment.Point intersection(Segment another)
Return a point of the intersection of the current segment and the given one.
Returnnull
if there is no such point.
Returnnull
if segments are collinear.
Please, note that intersection point must lay on both segments.
ClassPoint
is already there.
Hints:
You may useMain
class to try your code.There are some examples below.
Sample code:
...doublelength =newSegment(newPoint(0,0),newPoint(3,4)).length();System.out.println(length);
Output:5
Sample code:
...Segmentfirst =newSegment(newPoint(0,0),newPoint(4,4));Segmentsecond =newSegment(newPoint(2,0),newPoint(0,2));Pointintersection =first.intersection(second);System.out.println(intersection.getX());System.out.println(intersection.getY());
Output:
11
Sample code:
...Segmentsegment =newSegment(newPoint(2,0),newPoint(0,2));Pointmidpoint =segment.middle();System.out.println(midpoint.getX());System.out.println(midpoint.getY());
Output:
11
Sample code:
...Segmentfirst =newSegment(newPoint(0,0),newPoint(4,0));Segmentsecond =newSegment(newPoint(2,1),newPoint(1,2));Pointintersection =first.intersection(second);System.out.println(intersection ==null);
Output:
true
Task
The purpose of this exercise is to train you to work with classes and methods.
Estimated workload of this exercise is45 min.
Please, implement methods of classTriangle
:
- constructor, which has three points as parameters.
Consider these points as vertices of the triangle.
Ensure that the created triangle exists, and it is not degenerative.
If it is, usethrow new IllegalArgumentException()
to raise an error. double area()
Return the area of the triangle.Point centroid()
Return the centroid of the triangle.
ClassPoint
is already there.
Hints:
Please note that you may benefit from introducing more classes.
Sample code:
...newTriangle(newPoint(0,0),newPoint(1,0),newPoint(2,0));
Result: Exception because such a triangle would be degenerative.
Sample code:
...doublearea =newTriangle(newPoint(0,0),newPoint(3,0),newPoint(0,4)).area();System.out.println(area);
Output:
6
Sample code:
...Pointcentroid =newTriangle(newPoint(0,0),newPoint(3,0),newPoint(0,3)).centroid();System.out.println(centroid.getX());System.out.println(centroid.getY());
Output:
11
Task
The purpose of this exercise is to train you designing simple classes and their relations.
Estimated workload of this exercise is2h.
Decrementing Carousel
is a container, acceptingint
elements.DecrementingCarousel
has a maximum capacity, specified via the constructor.When created,DecrementingCarousel
is in accumulating state: you may add elements via theaddElement
method and can produce aCarouselRun
object via therun
method.Once therun
method is called,DecrementingCarousel
is in running state: it refuses adding more elements.
TheCarouselRun
allows to iterate over elements of the carousel decrementing them one by one with thenext
method.Thenext
returns the value of the current element:
Then it decreases the current element by one and switches to the next element:
TheCarouselRun
iterates over elements in the order of their insertion.
When an element is decreased to zero, theCarouselRun
will skip it in further iterations.When there are no more elements available for decrementing, theCarouselRun
returns-1
.
TheCarouselRun
also has theisFinished
method, which indicates, if the carousel has run out of the elements to decrement.
DecrementingCarousel
has two public methods:
boolean addElement(int element)
- adds an element.If element is negative or zero, do not add the element.If container is full, do not add the element.If therun
method was called to create aCarouselRun
, do not add the element.If element is added successfully, returntrue
. Returnfalse
otherwise.CarouselRun run()
- returns aCarouselRun
to iterate over the elements.If therun
method has already been called earlier, it must returnnull
:DecrementingCarousel
may generate only oneCarouselRun
object.
CarouselRun
has two public methods:
int next()
- returns the current value of the current element,then decreases the current element by one and switches to the next element in insertion order.Skips zero elements. When there is no more elements to decrease, returns-1
.boolean isFinished()
- when there is no more elements to decrease, returnstrue
. Otherwise, returnsfalse
.
Empty case:
CarouselRunrun =newDecrementingCarousel(7).run();System.out.println(run.isFinished());//trueSystem.out.println(run.next());//-1
Regular case:
DecrementingCarouselcarousel =newDecrementingCarousel(7);carousel.addElement(2);carousel.addElement(3);carousel.addElement(1);CarouselRunrun =carousel.run();System.out.println(run.isFinished());//falseSystem.out.println(run.next());//2System.out.println(run.next());//3System.out.println(run.next());//1System.out.println(run.next());//1System.out.println(run.next());//2System.out.println(run.next());//1System.out.println(run.isFinished());//trueSystem.out.println(run.next());//-1
Refusing adding more elements case:
DecrementingCarouselcarousel =newDecrementingCarousel(3);System.out.println(carousel.addElement(-2));//falseSystem.out.println(carousel.addElement(0));//falseSystem.out.println(carousel.addElement(2));//trueSystem.out.println(carousel.addElement(3));//trueSystem.out.println(carousel.addElement(1));//true//carousel is fullSystem.out.println(carousel.addElement(2));//falseCarouselRunrun =carousel.run();System.out.println(run.next());//2System.out.println(run.next());//3System.out.println(run.next());//1System.out.println(run.next());//1System.out.println(run.next());//2System.out.println(run.next());//1System.out.println(run.isFinished());//trueSystem.out.println(run.next());//-1
Refusing to add more elements after "run" was called:
DecrementingCarouselcarousel =newDecrementingCarousel(10);System.out.println(carousel.addElement(2));//trueSystem.out.println(carousel.addElement(3));//trueSystem.out.println(carousel.addElement(1));//truecarousel.run();System.out.println(carousel.addElement(2));//falseSystem.out.println(carousel.addElement(3));//falseSystem.out.println(carousel.addElement(1));//false
Refusing to create more than one CarouselRun:
DecrementingCarouselcarousel =newDecrementingCarousel(10);System.out.println(carousel.run() ==null);//falseSystem.out.println(carousel.run() ==null);//true
Task
The purpose of this exercise is to train you to use extend classes withextends
keyword.
Estimated workload of this exercise is30 min.
Note, that if you have not done the "Decrementing Carousel" exercise,you have to implementDecrementingCarousel
andCarouselRun
classes.
In this exercise you need to extendDecrementingCarousel
.You need to implementHalvingCarousel
.This subclass must halve elements instead of decrementing it by one.Note that you need to apply regular integer division, discarding the remainder.For example,5 / 2 = 2
.
Empty case:
CarouselRunrun =newHalvingCarousel(7).run();System.out.println(run.isFinished());//trueSystem.out.println(run.next());//-1
Regular case:
DecrementingCarouselcarousel =newHalvingCarousel(7);carousel.addElement(20);carousel.addElement(30);carousel.addElement(10);CarouselRunrun =carousel.run();System.out.println(run.isFinished());//falseSystem.out.println(run.next());//20System.out.println(run.next());//30System.out.println(run.next());//10System.out.println(run.next());//10System.out.println(run.next());//15System.out.println(run.next());//5System.out.println(run.next());//5System.out.println(run.next());//7System.out.println(run.next());//2System.out.println(run.next());//2System.out.println(run.next());//3System.out.println(run.next());//1System.out.println(run.next());//1System.out.println(run.next());//1System.out.println(run.isFinished());//trueSystem.out.println(run.next());//-1
Task
The purpose of this exercise is to train you to use extend classes withextends
keyword.
Estimated workload of this exercise is30 min.
Note, that if you have not done the "Decrementing Carousel" exercise,you have to implementDecrementingCarousel
andCarouselRun
classes.
In this exercise you need to extendDecrementingCarousel
.You need to implementGraduallyDecreasingCarousel
.This subclass must decrement elements by gradually increasing decrement.When you need to decrement an element for the first time, decrease it by1
.Next time you need to decrement the same element, decrease it by2
.Next time decrease by3
, then by4
and so on.Remember that you must not make process non-positive elements.
Empty case:
CarouselRunrun =newGraduallyDecreasingCarousel(7).run();System.out.println(run.isFinished());//trueSystem.out.println(run.next());//-1
Regular case:
DecrementingCarouselcarousel =newGraduallyDecreasingCarousel(7);carousel.addElement(20);carousel.addElement(30);carousel.addElement(10);CarouselRunrun =carousel.run();System.out.println(run.isFinished());//falseSystem.out.println(run.next());//20System.out.println(run.next());//30System.out.println(run.next());//10System.out.println(run.next());//19System.out.println(run.next());//29System.out.println(run.next());//9System.out.println(run.next());//17System.out.println(run.next());//27System.out.println(run.next());//7System.out.println(run.next());//14System.out.println(run.next());//24System.out.println(run.next());//4System.out.println(run.next());//10System.out.println(run.next());//20System.out.println(run.next());//5System.out.println(run.next());//15System.out.println(run.next());//9System.out.println(run.next());//2System.out.println(run.isFinished());//trueSystem.out.println(run.next());//-1
Task
The purpose of this exercise is to train you to use extend classes withextends
keyword.
Estimated workload of this exercise is30 min.
Note, that if you have not done the "Decrementing Carousel" exercise,you have to implementDecrementingCarousel
andCarouselRun
classes.
In this exercise you need to extendDecrementingCarousel
.You need to implementDecrementingCarouselWithLimitedRun
.This subclass must decrement elements as a usual DecrementingCarousel.The difference is that this implementation must produce a carousel run,which limits number of calls to thenext
method.When the limit of calls reached carousel run must consider itself finished.
Empty case:
CarouselRunrun =newDecrementingCarouselWithLimitedRun(7,5).run();System.out.println(run.isFinished());//trueSystem.out.println(run.next());//-1
Regular case:
DecrementingCarouselcarousel =newDecrementingCarouselWithLimitedRun(7,10);carousel.addElement(20);carousel.addElement(30);carousel.addElement(10);CarouselRunrun =carousel.run();System.out.println(run.isFinished());//falseSystem.out.println(run.next());//20System.out.println(run.next());//30System.out.println(run.next());//10System.out.println(run.next());//19System.out.println(run.next());//29System.out.println(run.next());//9System.out.println(run.next());//18System.out.println(run.next());//28System.out.println(run.next());//8System.out.println(run.next());//17System.out.println(run.isFinished());//trueSystem.out.println(run.next());//-1
Task
The purpose of this exercise is to train basic inheritance features.
Estimated workload of this exercise is120 min.
In this exercise we are going to manage business logic of planning a sprint.A sprint is the basic unit of software development in SCRUM.Sprints are time boxed. Time capacity of a sprint is agreed while planning.Then we consider a sprint to be filled with some tasks.
We consider a task to be implemented with general-purposeTicket
class.But we also consider a sprint to accept only subtypes of theTicket
class:Bug
andUserStory
.
Here is a diagram depicting the public interface of these classes and their relations:
Here are API details:
Ticket
Every ticket has an id, a name and an estimate of hours to complete it.One provides them via the constructor of theTicket
class.Also, a ticket may be completed or not. When a ticket is created, it is not completed.getId()
- Returns the id of the ticket.getName()
- Returns the name of the ticket.getEstimate()
- Returns the estimate of the ticket.isCompleted()
- Returnstrue
if the ticket is completed,false
otherwise.complete()
- Sets the ticket to completed state.
UserStory
We consider a user story to be a ticket that may contain some dependencies.A dependency is another user story that must be completed first to allow the dependent user story to complete.One provides dependencies of the UserStory via the constructor of theUserStory
class.complete()
- Like theTicket#complete()
method, this sets the ticket to completed state.The difference is that the user story may not be completed if its dependencies are not completed yet.getDependencies()
- Returns a defensive copy of dependencies array.toString()
- Returns a String representing this user story, using its id and name.Example: "[US 1] User Registration Entity"
Bug
We consider a bug to be a ticket, that is related to some completed user story.Bugs may not exist by their on, without a related user story.createBug(int id, String name, int estimate, UserStory userStory)
- A static method to create a Bug instance.
Returnsnull
if the related user story isnull
or is not completed. Otherwise, returns a created Bug instance.toString()
- Returns a String representing this bug, using its id, name and the name of the related user story.
Example: with id = 2, name = "Add password repeat" and the related user story name = "Registration Form"the resulting string would be "[Bug 2] Registration Form: Add password repeat"
Sprint
Sprints has the time capacity and the tickets limit, specified via constructor.It is not allowed for a Sprint to contain tickets with total estimate greater than time capacity.It is not allowed for a Sprint to contain total amount of tickets greater than tickets limit.
We consider a sprint to accept tickets viaadd*
methods.That methods returntrue
when an input ticket was accepted andfalse
otherwise.Note that we consider a sprint to not accept:null
values,- tickets, that are already completed
- tickets, that has an estimate value that will lead to capacity overflow if added
- any ticket, if the sprint ticket limit is reached.
addUserStory(UserStory userStory)
- accepts a userStory, if it is notnull
, not completedand its uncompleted dependencies are already accepted to the sprint.Returnstrue
if the user story is accepted,false
otherwise.addBug(Bug bugReport)
- accepts a bug, if it is notnull
and not completed.Returnstrue
if the bug is accepted,false
otherwise.getTickets()
- Returns a defensive copy of the array of the sprint tickets.Make sure the order of tickets is as they were accepted to the sprint.getTotalEstimate()
- Returns the sum of estimates of all the tickets accepted to the sprint.
Important restriction: Note that in this exercise youmay not useCollections andStreams.
Wikipedia on the Scrum Sprint:https://en.wikipedia.org/wiki/Scrum_(software_development)#Sprint
Task
The purpose of this exercise is to train you designing simple interface implementations and use them.
Estimated workload of this exercise is2h.
In this exercise you need to design two implementations of theTask
interface:
CountDownTask
:- The constructor of
CountDownTask
takes a single int value as a parameter.It is the initial value of the countdown.Input value must not be negative. If it is, set zero value. - Each time the
execute
method is called, this value decrements by one, until it reaches zero.Then theexecute
method no longer decrements the value and the task is considered finished. - If the task is initialized with zero value, consider it finished right upon creating.
- Value of the task is accessible via getter.
- The constructor of
CompleteByRequestTask
:- Constructor of the
CompleteByRequestTask
takes no parameters. - Calling
execute
method on the task does not make it finished until thecomplete
method is called. - Once the
complete
method is called, the next call toexecute
makes the task finished.Note that the task is not finished right after calling thecomplete
method.The task finishesonly when subsequent call toexecute
occurs.
- Constructor of the
Also, you need to implement theTaskCarousel
:
- A task carousel has a capacity provided as a constructor parameter.
- The
TaskCarousel
hasisEmpty
method.It returnstrue
if there is no task in the carousel for execution.Returnsfalse
otherwise. - The
TaskCarousel
hasisFull
method.It returnstrue
if there is no more room in the carousel to add another task.Returnsfalse
otherwise. - You may add tasks to the carousel via
addTask
method. It returnstrue
if the task is accepted andfalse
otherwise.Task may be not accepted due to following reasons:- Task argument is null.
- Task is already finished.
- Carousel is full.
- You may execute tasks in the carousel via
execute
method.- Each time when this method is invoked, carousel must switch to the next task within and execute it.
- Iteration is in circular manner.If there are 4 tasks inside a carousel,then if we call
execute
method on the carousel 4 times in a row,each task must be executed once. - If the task is finished after execution, remove it from the carousel.
- The method returns
true
if any task was executed. Returnsfalse
otherwise.
Single task case:
TaskCarouselcarousel =newTaskCarousel(4);System.out.println(carousel.isEmpty());//trueSystem.out.println(carousel.isFull());//falseSystem.out.println(carousel.execute());//falseCountDownTasktask =newCountDownTask(2);System.out.println(carousel.addTask(task));//trueSystem.out.println(carousel.isEmpty());//falseSystem.out.println(carousel.isFull());// falseSystem.out.println(task.getValue());//2System.out.println(carousel.execute());//trueSystem.out.println(task.getValue());//1System.out.println(carousel.execute());//trueSystem.out.println(task.getValue());//0System.out.println(carousel.execute());//falseSystem.out.println(carousel.isEmpty());//true
Three tasks case:
TaskCarouselcarousel =newTaskCarousel(3);CountDownTasktask1 =newCountDownTask(2);CountDownTasktask2 =newCountDownTask(2);CompleteByRequestTasktask3 =newCompleteByRequestTask();System.out.println(carousel.addTask(task1));//trueSystem.out.println(carousel.addTask(task2));//trueSystem.out.println(carousel.addTask(task3));//trueSystem.out.println(carousel.isFull());// truefor(inti =0;i <100;i++){System.out.println(carousel.execute());// true}System.out.println(task1.isFinished());// trueSystem.out.println(task2.isFinished());// trueSystem.out.println(task3.isFinished());// falsetask3.complete();System.out.println(task3.isFinished());// falseSystem.out.println(carousel.execute());// trueSystem.out.println(task3.isFinished());// trueSystem.out.println(carousel.isEmpty());// true
Task
The purpose of this exercise is to train you to work with classes, methods and inheritance.
Estimated workload of this exercise is60 min.
Please, makeTriangle
,Quadrilateral
,Circle
classesextendFigure
abstract class.
Implement methods inTriangle
,Quadrilateral
,Circle
:
- constructors with following parameters:
Triangle
- three vertices (points) as parameters.Quadrilateral
- four vertices (points) as parameters.Circle
- point of the center anddouble
value of the radius.
All the input datasets in tests are guaranteed to form a non-degenerative figures.For Quadrilaterals, it is guaranteed that all test datasets would form a convex quadrilaterals.
public double area()
Return the area of the figure.
Note: Convex quadrilaterals can be divided into two triangles by any of their diagonals.public String pointsToString()
Return a String value in following formats:
Triangle
-- Format:
(a.x,a.y)(b.x,b.y)(c.x,c.y)
- Example:
(0.0,0.0)(0.1,5.8)(7.0,7.0)
- Format:
Quadrilateral
-- Format:
(a.x,a.y)(b.x,b.y)(c.x,c.y)(d.x, d.y)
- Example:
(0.0,0.0)(0.0,7.1)(7.0,7.0)(7.0,0.0)
- Format:
Circle
-- Format:
(center.x,center.y)
- Example:
(0.0,0.6)
- Format:
Note:: you may benefit from implementing toString() in thePoint
class
public String toString()
Return a String value in following formats:
Triangle
-- Format:
Triangle[(a.x,a.y)(b.x,b.y)(c.x,c.y)]
- Example:
Triangle[(0.0,0.0)(0.1,5.8)(7.0,7.0)]
- Format:
Quadrilateral
-- Format:
Quadrilateral[(a.x,a.y)(b.x,b.y)(c.x,c.y)(d.x, d.y)]
- Example:
Quadrilateral[(0.0,0.0)(0.0,7.1)(7.0,7.0)(7.0,0.0)]
- Format:
Circle
-- Format:
Circle[(center.x,center.y)radius]
- Example:
Circle[(0.0,0.6)4.5]
- Format:
Note: you may use default implementation given in theFigure
class, when it suits a case well.
public Point leftmostPoint()
Return a leftmost point of the figure: the one having the leastX
coordinate.
If there are many leftmost points, return any of them.
Point
class is already there.
Hints:
- Degeneracy reference
- Convex quadrilateral reference
- Triangle area reference
- Circle area reference
- Quadrilateral area reference
You may useMain
class to try your code.There are some examples below.
Sample code:
...doublearea =newTriangle(newPoint(0,0),newPoint(3,0),newPoint(0,4)).area();System.out.println(area);
Output:
6
Sample code:
...doublearea =newQuarilateral(newPoint(1,0),newPoint(2,1),newPoint(1,2),newPoint(0,1)).area();System.out.println(area);
Output:
2
Sample code:
...doublearea =newCircle(newPoint(1,1),3).area();System.out.println(area);
Output:
28.274333882308138
Task
The purpose of this exercise is to train you to work with classes, methods and inheritance.
Estimated workload of this exercise is60 min.
Please, makeTriangle
,Quadrilateral
,Circle
classesextendFigure
abstract class.
Implement methods inTriangle
,Quadrilateral
,Circle
:
- Constructors with following parameters:
Triangle
- three vertices (points) as parameters.Quadrilateral
- four vertices (points) as parameters.Circle
- point of the center and double value of the radius.Ensure figures are not degenerative.
All of them must have non-zero area.
Quadrilateral is also must be convex.
If a figure is not good, throw an IllegalArgumentException.
Note: A non-degenerative convex quadrilateral is divided into four non-degenerative triangles by its diagonals.Note: double calculations are not completely accurate, useerror delta, where applies.
public Point centroid()
Return the centroid of the figure.
Centroid refers to center of mass of the plain figure, not the baricenter.
In other words it should be"area centroid".public boolean isTheSame(Figure figure)
Two figures are considered to be the same only:
if they have the same type
and if they coincide (e.g. have same vertices).
Note: order of the vertices have not to be the same.
Note: double calculations are not completely accurate, useerror delta, where applies.
Note for curious: it is almost likeequals()
but it is not. Methodequals
requires consistent behavior alongsidehashCode()
and it is quite complicated to establish in terms of approximate equality like in this exercise
Point
class is already there.
You may usemain
method ofFigure
class to try out your code.
Hints:
Task
The purpose of this exercise is to train using nested classes.
Estimated workload of this exercise is60 min.
In this exercise we are going to manage contacts information.
AContact
is a class containingdifferent information of how to reach a person or a company: phone number, emails, social media.
A contact has a name, which is provided via the class constructor.Also, a contact contains limited amount of entries:
- a phone number (only a single one)
- emails (up to 3 entries)
- social media links (up to 5 entries)
A contact info entry is described withContactInfo
interface.Each entry has a title and a value.You need to implemented them as nested classes of theContact
class:
Contact.NameContactInfo
- AContactInfo
implementation providing the name of the contact.Implement as private non-static nested class. Use"Name"
for the entry title.It must not have its own fields. It must use fields of the boundedContact
instance instead.Contact.Email
- AContactInfo
implementation containing an email.Implement as public static nested class. Use"Email"
for the entry title.Contact.Social
- AContactInfo
implementation containing a social media link/id.Implement as public static nested class. Let the user of the class define the title.- Other implementations must be anonymous. Do not provide other non-anonymous classes.
It is possible to add contact info entries viaadd*
methods.All such methods return the created entry as the result,null
if nothing was added to the contact.
addEmail(String localPart, String domain)
Adds an email entry.addEmail("someone", "somewhere.com").getValue()
will result tosomeone@somewhere.com
.addEpamEmail(String firstname, String lastname)
Adds a special email entry with "epam.com" domain.Please, implement this method using an anonymous extension of theEmail
class.Use"Epam Email"
for the entry title.addEpamEmail("some", "one").getValue()
will result tosome_one@epam.com
addPhoneNumber(int code, String number)
Adds a contact info entry for the phone number.Please, implement this method using an anonymous class.Use"Tel"
for the entry title.addPhoneNumber(44, "444 444-44-44").getValue()
will result to+44 444 444-44-44
addTwitter(String twitterId)
Adds a contact info entry for the Twitter social media id.Use"Twitter"
for the entry title, the given id for the value.addInstagram(String instagramId)
Adds a contact info entry for the Instagram social media id.Use"Instagram"
for the entry title, the given id for the value.addSocialMedia(String title, String id)
Adds a contact info entry for the generic social media id.Use the given title for the entry title, the given id for the value.
Note that it is possible to rename contact with therename
method.Make sure it is not possible to rename contact to havenull
or empty value as the name.
One more method that theContact
class have is thegetInfo()
method.This method returns an array containing theContactInfo
entries in the following order:
- name contact info
- phone number contact info (if set)
- email entries in order of addition (if any added)
- social media entries in order of addition (if any added)Resulting array must not contain any null values.
Important restriction: Note that in this exercise youmay not useCollections andStreams.
Task
The purpose of this exercise is to train using nested classes.
Estimated workload of this exercise is60 min.
In this exercise we are going to design a DSL of arithmetic expressions.
AnExpression
is an interface.It describes two methods:
int evaluate()
- returns the result of evaluating of the expression.String toExpressionString()
- returns string representation of the expression.
The only non-anonymous implementation of theExpression
istheVariable
class.Please, implement its methods:
public Variable(String name, int value)
- a constructor of theVariable
class.Sets name and value of the variable.public void setValue(int value)
- a method to change the value of the variable.public int evaluate()
- returns the value of the variable.public String toExpressionString()
- returns the name of the variable.
All other implementations of theExpression
interface must be anonymous, defined in static methods oftheExpressions
class:
Variable var(String name, int value)
- returns aVariable
with given name and value. A simple convenience method.Expression val(int value)
- returns anExpression
holding a value.Consider following methods' implementation details:int evaluate()
- returns the given value.String toExpressionString()
- returns a string representation of the given value.Enclose with(
,)
braces if the value is negative.
Expression sum(Expression... members)
- returns anExpression
holding a sum of the given members.Consider that it is guaranteed that at least two members will be given each method call.Consider following methods' implementation details:int evaluate()
- returns the sum of evaluation result of all the given members.String toExpressionString()
- returns a string representation of the given sum.Example:sum(val(1), val(2), val(3)).toExpressionString()
results to(1 + 2 + 3)
.
Expression product(Expression... members)
- returns anExpression
holding a product of the given members.Consider that it is guaranteed that at least two members will be given each method call.Consider following methods' implementation details:int evaluate()
- returns the product of evaluation result of all the given members.String toExpressionString()
- returns a string representation of the given product.Example:product(val(1), val(2), val(3)).toExpressionString()
results to(1 * 2 * 3)
.
Expression difference(Expression minuend, Expression subtrahend)
- returns anExpression
holding a differencebetween the given minuend and the given subtrahend.Consider following methods' implementation details:int evaluate()
- returns the difference betweenthe given minuend evaluation result andthe given subtrahend evaluation result.String toExpressionString()
- returns a string representation of the given difference.Example:product(val(1), val(2)).toExpressionString()
results to(1 - 3)
.
Expression fraction(Expression dividend, Expression divisor)
- returns anExpression
holding a ratioof the given dividend to the given divisor.Note that it refers to aninteger division operation, i.e.fraction(val(3), val(4)).evaluate()
result to0
.Consider following methods' implementation details:int evaluate()
- returns the ratio of the given dividend evaluation result to the given divisor evaluation result.String toExpressionString()
- returns a string representation of the given fraction.Example:fraction(val(1), val(2)).toExpressionString()
results to(1 / 2)
.
Important restriction: Note that in this exercise youmay not add more non-anonymous classes.
Task
The purpose of this exercise is to train you to work with strings.
Estimated workload of this exercise is60 min.
Please, implementStringUtil
class methods:
Method signature:
publicstaticintcountEqualIgnoreCaseAndSpaces(String[]words,Stringsample)
Return the number of words fromwords
array that are equal tosample
ignoring characters case and leading and trailing spaces.
Ifsample
isnull
orwords
isnull
or empty, return0
.words
is guaranteed to not containnull
values.
Method signature:
publicstaticString[]splitWords(Stringtext)
Splittext
string into array of words using following separating characters:",", ".", ";", ":", " ", "?", "!"
.
For empty string,null
string, and string consisting only of separating characters returnnull
Method signature:
publicstaticStringconvertPath(Stringpath,booleantoWin)
Convertpath
to Unix\Windows path depending on a boolean parameter.
Unix path may start with~
or/
. Every subdirectory must end with/
character except the last one.Path elements.
and..
refer to current directory and parent directory.Filename doesn't necessarily have the extension.
Unix path examples:
/folder/../folder/file.txt
/dev/null
file.txt
folder/logs/
~/user/some_logs
Windows path may start withC:
. Every subdirectory must end with\
character except the last one.Path elements.
and..
refer to current directory and parent directory.Filename doesn't necessarily have the extension.
Windows path examples:
file.txt
\Program Files\some_file.exe
.\to_do_list.txt
C:\Users\..\Cygwin
.\file
Let's consider Unix~
path to correspond to WindowsC:\User
path and vice versa.
Let's consider Unix/
root folder (i.e., when the path starts with/
) to correspond to WindowsC:\
drive and viceversa (butC:\User
still corresponds to~
).
Ifpath
already corresponds to the required format (for instance, is Windows path when Windows paths is needed andtoWin
boolean parameter istrue
) returnpath
.
Ifpath
isnull
, empty, or doesn't correspond to any path format (Unix, Windows), returnnull
.
It is guaranteed thatpath
is either a correct path, or it has some of the following errors:
- More than one
~
~
is not at the start~
mixed with\
(~
in Windows path)- More than one
C:
C:
is not at the startC:
mixed with/
(C:
in Unix path)\
mixed with/
Illegal paths example:
/folder1/folder2\folder3
C:\User/root
/dev/~/
C:/a/b/c/d
~\folder
~/~
~~
C:\Folder\Subfolder\C:\
Method signature:
publicstaticStringjoinWords(String[]words)
Join words fromwords
array and return as a string in the following format:"[str_1, str_2, ..., str_n]"
.
Ifwords
isnull
or empty returnnull
.words
is guaranteed to not containnull
values.words
may contain empty strings, ignore them, i. e. don't put them in the resulting string. Ifwords
contains only empty strings returnnull
.
- While implementing the methods you might need to come up with
regular expressions
. You may consider usingregex101.com to easier design of regular expressions. - You can and should use following methods\classes (click on the name):
You may usemain
method ofStringUtil
class to test your implementation.
String[]words =newString[] {" nice ","nICE","nic3"};Stringsample ="NICE";intresult =StringUtil.countEqualIgnoreCaseAndSpaces(words,sample);// 2words =newString[]{" zoOm "," z oom"," Z O O M "};sample ="ZOOM";result =StringUtil.countEqualIgnoreCaseAndSpaces(words,sample);// 1
Stringtext =" go with ...the:; FLOW ";String[]result =StringUtil.splitWords(text);// ["go", "with", "the", "FLOW"]text =":..,,,::: ;;; ";result =StringUtil.splitWords(text);// null
StringwinPath ="C:\\Program Files\\my_prog_file.py";StringunixPath =StringUtil.convertPath(winPath,false);// "/Program Files/my_prog_file.py"unixPath ="../script.sh";winPath =StringUtil.convertPath(unixPath,true);// "..\\script.sh"unixPath =StringUtil.convertPath(unixPath,false);// "../script.sh"unixPath ="//home/user/somefile";winPath =StringUtil.convertPath(unixPath,true);// "C:\\home\\user\\somefile"
String[]words =newString[]{"go","with","the","","FLOW"};Stringresult =StringUtil.joinWords(words);// "[go, with, the, FLOW]"
Task
The purpose of this exercise is to train you to work with string values.
Estimated workload of this exercise is45 min.
Please, implementvalidateColorCode
method inColorCodeValidation
:
This method checks the input string for compliance with the rules for writingHTML Color Codes.
While implementing the methods you might need to come up withregular expressions.You may consider usingregex101.com to ease designing them.
Note that input String may be null.
You can and should use following methods\classes:
Examples of valid hex codes:
#0B79E1 #6a8daf #002950
Examples of invalid hex codes:
123456#afafah #-123
Task
The purpose of this exercise is to train you to work with string values.
Estimated workload of this exercise is45 min.
Please, implementvalidateEpamEmail
methodinEpamEmailValidation
:
This method checks the input string for compliance with the rules for a regular EPAM email. Let us define them:
- A regular EPAM email includes firstname and lastname (in English), separated by underscore ("_").
- EPAM email always ends with "@epam.com"
- When a person gets new EPAM email, but email with this firstname and lastname is already registered, we add "1" to thenew email. If such email is registered as well, we use "2" and so on.
While implementing the method you might need to come up withregular expressions. You may considerusingregex101.com to ease designing them.
Note that input value may be null.
You can and should use following methods\classes:
Valid examples
william_shakespeare@epam.comlu_e@epam.comwilliam_shakespeare1@epam.com william_shakespeare2@epam.com
Invalid examples
william@epam.com william.shakespeare@epam.com william...shakespeare@epam.com william-shakespeare@epam.com shakespeare123@epam.com william_$hakespeare@epam.com
Task
The purpose of this exercise is to train you to work with exceptions, to raise them in particular.
Estimated workload of this exercise is30 min.
Please, implementRequirements
methods:
requireNonNull(Object)
should throw new NullPointerException if object isnull
requireNonNull(Object, String)
should throw new NullPointerException with message if object isnull
checkArgument(boolean)
if boolean isfalse
should throw new IllegalArgumentExceptioncheckArgument(boolean, String)
if boolean isfalse
should throw new IllegalArgumentException with messagecheckState(boolean)
if boolean isfalse
should throw new IllegalStateExceptioncheckState(boolean, String)
if boolean isfalse
should throw new IllegalStateException with messagecheckIndex(int, int)
if index out of bounds throw new IndexOutOfBoundsException. Index must be inside[0, size)
section.
Such methods might be helpful to check arguments, object states.
Task
The purpose of this exercise is to train you to work with exceptions, to handle them in particular.
Estimated workload of this exercise is30 min.
Please, implement the main method inCatchEmAll
class.It must handle a call to a risky method that can throw different types of exceptions.
Please, note that some types of exceptions should be handled, while others – shouldn’t.
Details:
What is thrown | How to handle |
---|---|
IOException | Wrap in an IllegalArgumentException with a message "Resource error" and throw it |
FileNotFoundException | Wrap in an IllegalArgumentException with a message "Resource is missing" and throw it |
ArithmeticException or NumberFormatException | Print a message of the thrown exception to System.err and do not throw anything |
Any other Exceptions | Should not be caught |
Task
The purpose of this exercise is to train you to work with generics.
Estimated workload of this exercise is30 min.
Please, use generics to changeHouse
class in order to dogs cannot enter cats' house and cats cannot enter dogs' house.
You need to alterresidents
field andenter
methods of theHouse
class.
Note that if you have done everything right, then two particular lines in theMain
class may prevent successful compilation, so you may need to remove them.See details in theMain
class.
Task
The purpose of this exercise is to train you to work with enums.
Estimated workload of this exercise is60 min.
Please, implement methods inDirection
class:
ofDegrees
- Return a Direction instance by input degrees ornull
if there is none.closestToDegrees
- Return the closest Direction instance to input degrees.opposite
- Return a Direction instance that is opposite to this.differenceDegreesTo
- Return the difference in degrees between this and input Direction instance.
Note that degrees input value may be out of the [0; 360) range. Adjust them accordingly.
Task
The purpose of this exercise is to train you to work with wrapper classes and their static methods.
Estimated workload of this exercise is3 hours.
Please, implement methods inBattleship8x8
class.
Battleship8x8 represents a 8x8 map forBattleship game.An important detail is that Battleship8x8 uses aships
field of long type to store ships locationsand ashots
field of long type to register shots.
Fields of long type value store 64 bits each. Consider them as 8 rows per 8 cells.'0' bits represent empty cells, '1' bits represent cells seized by ships or registered shots.
public boolean shoot(String shot)
- Registers a shot and returnstrue
if the shot hits a ship.A shot is a combination of one of A-H letters and one of 1-8 digitspublic String state()
- Returns a string representing state of the map.Map string is 8 lines per 8 characters separated by "\n". Use following symbols:- '.' - an empty cell
- '×' - an empty cell that has been shot
- '☐' - a cell seized by a ship
- '☒'- a cell seized by a ship that has been shot
You must not add or change new fields.Consider using static methods of wrapper classes.
Consider a map information encoded as a long value:
longmap = -1150950973573693440L;
You may consider it represented as binary literal:
/* 11110000 00000111 00000000 00110000 00000010 01000000 00000000 00000000 */longmap = 0b11110000_00000111_00000000_00110000_00000010_01000000_00000000_00000000L;
Consider rows be marked with digits and columns be marked with letters:
/* ABCDEFGH ┌──────── 1│11110000 2│00000111 3│00000000 4│00110000 5│00000010 6│01000000 7│00000000 8│00000000 */
Consider the following list of shots:
List<>shots =List.of("A1","B2","C3","D4");
Then we could useBattleship8x8
API:
Battleship8x8battle =newBattleship8x8(map);shots.forEach(battle::shoot);System.out.println(battle.state());
The result would be the following:
☒☐☐☐.....×...☐☐☐..×.......☐☒..........☐..☐......................
Task
The purpose of this exercise is to train you to work with arrays and optional.
Estimated workload of this exercise is45 min.
Implementmax
method ofMaxMethod
class.
The correct implementation should receive an array ofint
values and return its maximum value.
Details:
- the method returns the result as OptionalInt
- if the input array is empty or
null
, return empty OptionalInt.
int[]vals =newint[]{-2,0,10,5};OptionalIntresult =MaxMethod.max(vals);System.out.println(result.getAsInt() ==10);// true
Task
The purpose of this exercise is to prepare you to work with collections—to create and add elements and iterate through them to perform operations on each element.
Duration:45 minutes
In this task, you will simulate the work of a new post office that takes parcels weighing between 0.5 and 20 kg and with a maximum volume of 0.25 m3
TheBox
class describes parcels. A parcel has the following characteristics: sender, recipient, weight, volume, and shipping cost. All characteristics except for the shipping cost are passed to the constructor to create an object. The shipping cost is calculated based on the weight, volume, and value of the parcel.
TheNewPostOffice
class has:
NewPostOffice()
Creates an office (an empty collection of parcels)Collection<Box> getListBox()
Returns a collection of parcels in the officestatic BigDecimal calculateCostOfBox(double weight, double volume, int value)
Calculates the cost of a parcel
Please proceed to the NewPostOffice class and implement its methods using an iterator:
Collection<Box> deliveryBoxToRecipient(String recipient)
Returns all parcels of a specified recipient; any parcels found must be removed from the officevoid declineCostOfBox(double percent)
Changes the cost of each parcel in the office by the percentage specifiedboolean addBox(String sender, String recipient, double weight, double volume, int value)
Creates a parcel, calculates its shipping cost, and adds it to the office
- The sender and receiver must exist.
- The weight must be 0.5–20.0 kg.
- The volume must be greater than 0 and less than 0.25 m3.
- The value must be greater than zero.
- The cost of a parcel is calculated as follows: the weight is multiplied by the cost of one kilogram, the volume is multiplied by the cost of one cubic meter, the value is multiplied by a given coefficient, then everything is summed up.
- If the values of the data above are set incorrectly (by specifying invalid values), the java.lang.IllegalArgumentException is thrown.
You may not use the Lambdas or the Streams API.
Task
The purpose of this exercise is to describe, create, and use lists that are built according to special rules.
Duration:45 minutes
In this task, you will describe a list that is based on a dynamic array. The internal structure of the list is a one-dimensional array of theObject
type with an initial capacity/size of 10 and a size field that stores the number of elements in the list. You must provide for the expansion of the array (list) capacity when the number of elements reaches 75% (load factor 0.75) of its size. Use the following expression to calculate the increase in capacity: Doub le the current capacity of the array and then multiply it by the load factor.
Now, please proceed to theSimpleArrayListImpl
class, which implements theSimpleArrayList
interface, and provide implementations of the following methods:
int size()
Returns the number of elementsString toString()
Makes a string representation of the listboolean add(Object element)
Appends the specified element to the end of the listObject get(int index)
Returns an element at a specified position in the listOptional<Object> remove(Object element)
Searches for and removes the specified elementint capacity()
Returns the current length of the listboolean decreaseCapacity()
Decreases the capacity of the list if it is 40% full or less
- The list is created by the default constructor, which creates an internal array with an initial length of 10 elements.
- The list cannot contain
null
elements. The add and remove methods must throw aNullPointerException
if they get null. - The get method must throw
IndexOutOfBoundsException
if the index is outside the [0 … size - 1] range. - The size field specifies the number of elements in the list and where to place the next element.
- The method for adding a new element must first check whether the capacity of the list should be increased before adding it.
- The
decreaseCapacity()
method calculates the new capacity by doubling the current number of elements. - You can add any private methods to the
SimpleArrayListImp
class.
You may not:
- Use any type from the
java.util
package (or its subpackages) except for:java.util.Iterator
java.util.Optional
- Add any additional fields into the
SingleArrayListImpl
class. - Add any additional public methods to the
SingleArrayListImpl
class.
Task
The purpose of this exercise is to create and use a custom doubly linked list.
Duration:1 hour
In this task, you will describe a bidirectional list based on a linked representation. The internal structure of the list is a node chain (nested classNode
) where each node encapsulates a list element and has one reference to the previous node and one reference to the following node. The first node has no reference to the previous node, and the last node has no reference to the next one.
Now, please proceed to theDoublyLinkedListImpl
class, which implements theDoublyLinkedList
interface, and provide implementations of the following methods:
boolean addFirst(Object element)
Inserts an element at the beginning of the list and returns true if an element is successfully added and, if not, falseboolean addLast(Object element)
Appends an element to the end of this list and returns true if an element is successfully added and, if not, falseboolean delete(int index)
Deletes an element by index and throwsIndexOutOfBoundsException
if the index is out of rangeOptional<Object> remove(Object element)
Returns and deletes the first occurrence of the specified element in the listboolean set(int index, Object element)
Finds the element at the specified index and replaces it or throws theIndexOutOfBoundsException
if the index is out of rangeint size()
Returns the number of elements in the listObject[] toArray()
Returns an array containing all the elements in order from first to lastString toString()
Returns a string representation of the list
- The
DoublyLinkedListImpl
class has two fields, head and tail, and should not contain a size field to store the number of elements. - The list is created by the default constructor, which initializes the head and tail fields to null.
- The list cannot contain null elements. The add, remove, and set methods must throw a
NullPointerException
if they get null. - The remove method must use the equals method to find the occurrence of the object in the list.
- The string representation of a list consists of all its elements separated by a space. For example, if a list contains three elements, o1, o2, and o3, the
toString
method returns "s1 s2 s3", wheres1=o1.toString()
,s2=o2.toStribng()
, ands3=o3.toString()
.
You may not:
- Use any type from the
java.util
package or its subpackages except forjava.util.Optional
- Add additional fields to the
DoublyLinkedListImpl
andDoublyLinkedListImpl.Node
classes - Add any additional methods to the
DoublyLinkedListImpl.Node
class except constructors
Task
The purpose of this exercise is to work with List implementations, add/delete elements, and iterate over a collection to perform operations on each element.
Duration:1 hour
In this task, you will simulate the work of the New Post Storage service, which accepts parcels (boxes) and prepares them for distribution to New Post offices.TheBox
class describes a parcel with the following characteristics:sender
,recipient
,weight
,volume
,cost
,city
, andoffice
. All characteristics are passed to the constructor to create an object. You must not change this class.
TheNewPostOfficeStorage
interface has several methods that performadd
,delete
,filter
, andupdate
operations in a storage:
boolean acceptBox(Box box)
Appends the specified parcel to the end of this storageboolean acceptAllBoxes(Collection<Box> boxes)
Appends to this storage all parcels that are contained inthe specified collection. It must add either all the parcelsor nothing, if an exception occursboolean carryOutBoxes(Collection<Box> boxes)
Removes from this storage all of its parcels that are containedin the specified collectionList<Box> carryOutBoxes(Predicate<Box> predicate)
Removes from this storage all of its parcels that are satisfied thespecified predicateList<Box> getAllWeightLessThan(double weight)
Selects all parcels whose weight is less than the parameter value.List<Box> getAllCostGreaterThan(BigDecimal cost)
Selects all parcels whose cost is greater than the parameter value.List<Box> getAllVolumeGreaterOrEqual(double volume)
Selects all parcels whose volume is greater than or equalto the parameter valueList<Box> searchBoxes(Predicate<Box> predicate)
Searches parcels using a predicate. This method doesnot change the original storagevoid updateOfficeNumber(Predicate<Box> predicate, int newOfficeNumber)
Updates theoffice
field in each box of this storage
Please, proceed to theNewPostOfficeStorageImpl
that the implementor ofNewPostOfficeStorage
interface.
Its highly recommended avoid indexed access to elements of a collection.
TheMain
class is not under tests. You can use it for your own purposes.
- Because the
Box
class does not have any identity field theimplementationmust not check uniqueness ofBox
instances. - Because the
NewPostOfficeStorage
describes business logicnot a collection, an implementationmust not extend anyexisting implementation ofList
interface or implement itinternallybut must aggregate it instead. - You should choose the best existing implementation of the
java.util.List
interface from the Java collection framework. - The implementationmust not permit null values and must throw
NullPointerException
in such cases. - It is forbidden to use:
- lambda when you implement functional interfaces.
stream()
,contains()
,containsAll()
indexOf()
methodsofList
interface.for ( i )
loop (use aforeach
loop orIterator
with awhile()
loop or theforeach()
method instead).
Task
The purpose of this exercise is for you to practice using collections, namely Set.
Duration:45 minutes
In this task, you need to demonstrate how to work with a set of integers encapsulated in theRangedOpsIntegerSet
class.
Please proceed to the RangedOpsIntegerSet class and provide implementations of the following methods:
boolean add(final Integer integer)
Adds a single value to the setboolean remove(final Object o)
Removes a single value from the setboolean add(int fromInclusive, int toExclusive)
Adds a range of values to the set (first argument—inclusive; last argument—exclusive); returns true if range values were actually addedboolean remove(int fromInclusive, int toExclusive)
Removes a range of values from the list (first argument—inclusive; last argument—exclusive); returns true if range values were actually removedIterator<Integer> iterator()
Returns an iterator to iterate over elements of the set in natural orderint size()
Returns the number of current elements
You may not use lambdas or streams when implementing this task.
- Adding one range:
RangedOpsIntegerSetset =newRangedOpsIntegerSet();set.add(1,5);for(Integerel :set){System.out.println(el);}
Output:
1234
- Adding two ranges:
RangedOpsIntegerSetset =newRangedOpsIntegerSet();set.add(1,5);set.add(9,11);for(Integerel :set){System.out.println(el);}
1234910
- Adding and removing ranges:
RangedOpsIntegerSetset =newRangedOpsIntegerSet();set.add(1,15);set.remove(3,12);for(Integerel :set){System.out.println(el);}
12121314
Task
The purpose of this exercise is to give you some practice using collections of the Set type.
Duration:1 hour
In this task, you will determine the percentage of compliance of a certain team with project requirements. In other words, you will determine if the team is suitable for the project.
You have the following description:
- The
Position
enum defines a set of positions. - The
Skill
enum defines a set of skills. - The
Level
enum defines a set of skill levels. - The
Member
class defines a team member. Each member has a name, a level, and a set of skills (a collection of theSet<Skill>
type implemented asEnumSet<Skill>
). TThe team is described as a set of members in the form ofHashSet<Member>
. - The
Role
class defines the role of the participant in the project. Each role has a level, a position, and required skills (a collection of theSet<Skill>
type implemented as anEnumSet<Skill>
). - The
Project
class defines the project and contains a description of it and a list of roles. - The
Project.Entry
class combines a skill and its level and is used in the algorithm for calculating the team's compliance with the project.
Now, please proceed to theMember
class and implement its contents:
public Member(String name, Level level, Skill... skills)
Creates a member with the specified name, level, and skillsGetters
Return values of the appropriate fields
Now, please proceed to theRole
class and implement its contents:
public Role(Position position, Level level, Skill... skills)
Creates a role with the specified position, level, and skillsGetters
Return values of the appropriate fields
Now, please proceed to theProject
class and implement its contents:
public Project(Role... roles)
Creates a project with the specified rolespublic List<Role> getRoles()
Returns a list of rolespublic int getConformity(Set<Member> team)
Returns the percentage of team compliance with the project requirementsprivate static class Entry {}
Describes an entry containing a level/skill pair
- The
Entry
must implement the equals andhashCode
methods. Two entries are considered equal if and only if they have the same skill and level. - •To calculate the percentage of team compliance with project requirements, you must use the following algorithm:
- Generate a list of pairs
<Level, Skill>
for the project's roles (e.g., named projectEntries). - Save the size of this list to a variable (e.g., originalSize).
- Generate a list of pairs
<Level, Skill>
for the team members (e.g., named teamEntries). - Remove common elements from both lists.
- Calculate the compliance percentage as follows:
- Subtract the current size of the list of entries for the project roles from the originalSize variable
- Multiply the difference by 100
- Divide by the original size of the list of entries for the project roles
- Generate a list of pairs
You may not:
•Add extra fields to classes
•Add extra methods to classes
•Use lambdas or streams when implementing this task
- Suppose the project has the following roles:
•DEVELOPER which has the A1 level and the JAVA, DATABASE skills •KEY_DEVELOPER which has the A3 level and the JAVA, DATABASE, SPRING skills •TESTER which has the A2 level and the JAVA, SPRING, TESTING_TOOLS skills
Then the list of pairs will be:
projectEntries → [<A1, JAVA>, <A1, DATABASE>, <A3, JAVA>, <A3, DATABASE>, <A3, SPRING>, <A2, JAVA>, <A2, SPRING>, <A2, TESTING_TOOLS>]
And the list size is 8.
- Suppose the team has the following members:
•Member1 which has the A1 level and the JAVA, SPRING skills •Member2 which has the A2 and the JAVA, DATABASE, SPRING skills
Then the list of pairs will be:
teamEntries → [<A1, JAVA>, <A1, SPRING>, <A2, JAVA>, <A2, DATABASE>, <A2, SPRING>]
- Removing the common elements in both lists yields the following result:
projectEntries → [<A1, DATABASE>, <A3, JAVA>, <A3, DATABASE>, <A3, SPRING>, <A2, TESTING_TOOLS>]teamEntries → [<A1, SPRING>, <A2, DATABASE>]
The new size of the projectEntries list is 5.
- The compliance percentage is 37.5%.
Task
The purpose of this exercise is to learn how to useMap
collections.
Duration:1 hour 30 minutes
In this task, you will simulate work with a book catalog. The catalog can be represented as theTreeMap
collection, where the author is the key and the list of published books is the value. You have the following description:
- The
Author
class, which consists of the first and last name - The
Book
class, which consists of the title, genre, and cost
Since the book catalog is an ordered map, theAuthor
andBook
classes must implement theComparable
interface.TheBooksCatalog
class must have two constructors: a default one and one with a parameter that creates a map based on an existing map.
Please proceed to theAuthor
andBook
classes and provide implementations of thecompareTo()
method.
Please, proceed to theBooksCatalog
class and provide implementations of the following methods:
List<Book> findByAuthor(Author author)
Returns a list of books by the specified author ornull
if there is no such author in the catalogList<Author> findAuthorsByBook(Book book)
Returns a list of the authors of the specified book ornull
if there is no such book in the catalogString getAllAuthors()
Returns a list of all the authors as a StringSet<Book> findBooksByGenre(String pattern)
Returns a set of books of the specified genre ornull
if there are no books of this genreMap<Book, List<Author>> findAuthorsByBookTitle(String pattern)
Returns the book/author pair map. The search is carried out based on the words in the book's title
- To order the map by author, apply alphabetical order by first name and, if the names match, alphabetical order by last name.
- To order the map by book title, apply alphabetical order by title and, if the titles match, by ascending cost.
- The
findAuthorsByBookTitle
method searches for books based on a word pattern; it is case-insensitive. - The
findBooksByGenre
method searches for books of a certain genre specified as a search pattern; the matching pattern and name of the genre are case-insensitive; all the books found are sorted using natural ordering. - You can use a regular expression to match occurrences of a pattern in a book title or genre in the
findBooksByGenre
andfindAuthorsByBookTitle
methods. - The
getAllAuthors
method returns an alphabetical list of authors as a String, where the authors' names are separated by '\n'. - No methods of the
BooksCatalog
class acceptnull
, and they must throw aNullPointerException
if they do. - You can use the
getData()
method in the Util class to create the initial map. - You can add any private methods to the
BooksCatalog
class.
You may not use lambdas or streams when implementing this task.
Task
The purpose of this exercise is to work with Comparator implementations on the TreeMap maps.
Duration:1 hour
In this task, you will simulate the work of the student's gradebook. The internal structure of the gradebook is a collection of theTreeMap
type where a key is an object of theStudent
type, the value is aHashMap
whose key is the name of a discipline (an object of theString
type), and the value is the grade (an object of theBigDecimal
type).
TheStudent
class describes a student with the following characteristics:first/last
name andgroup
. All characteristics are passed to the constructor to create an object.You must not change this class.
Now, please proceed to theStudentsGradebookImpl
class, which implements theStudentsGradebook
interface, and provide implementations of the following methods:
public GradeBookImpl()
Creates the gradebook object in which aComparator
is described to compare studentsboolean addEntryOfStudent(Student student, String discipline, BigDecimal grade)
Adds a student entry to the gradebook; returns true if the addition was successful, and false if not.int size()
Returns the number of students in the gradebookComparator<Student> getComparator()
Returns theComparator
, which is used to compare studentsList<String> getStudentsByDiscipline(String discipline)
Gets a list of strings with students' names and their grades for the specified disciplines in the format"first_last name : grade"
Map<Student, Map<String, BigDecimal>> removeStudentsByGrade(BigDecimal grade)
Finds, removes, and returns from the gradebook students who have a grade below the specified one in any discipline
If no such students are found, an empty map will be returnedMap<BigDecimal, List<Student>> getAndSortAllStudents()
Gets the gradebook as an ordered map where the key is the average grade and the value is a list of theStudent
type
- Since the
Student
objects are the keys to the gradebook, when you create the gradebook, you will need to declare theComparator
to compare objects of theStudent
type and pass it to theTreeMap<Student, Map<String, BigDecimal>>
constructor. - The grading scale for any discipline is in the range
[0 .. 5]
. The minimum passing grade is3
points. - The
removeStudentsByGrade
method returns a map ordered by theStudent
type. To create the resulting map, you must use theComparator
applied in the gradebook constructor. - The
getAndSortAllStudents
method generates a gradebook based on the student's average grade. The average grade is indicated in increments of one tenth—for example, 3.1, 3.2, 3.3, etc. - It is guaranteed that the parameters passed to all methods are correct.
- You can add any private methods to the
StudentsGradebookImpl
class.
You may not use lambdas or streams to complete this task.
Task
The purpose of this exercise is to apply various algorithms to collections using the methods of theCollections
class.
Duration:1 hour
In this task, you will simulate the work of a weekly maternity hospital journal. The internal structure of the journal is a collection of theMap
type, where the key is the weekday (an enum of theWeekDay
type) and the value is a list of babies born during the week (objects of theBaby
type).
TheBaby
class describes a baby with the following characteristics:name
,weight
,height
,gender
, andbirth time
. All characteristics are passed to the constructor to create an object.You must not change this class.
Please note that once a birth journal has been created and filled in, it cannot be changed. This needs to be guaranteed.
Now, please proceed to theBirthJournalManagementImpl
class, which implements theBirthJournalManagement
interface, and provide implementations of the following methods:
boolean addEntryOfBaby(WeekDay day, Baby baby)
Adds an entry for the specified baby to the journal; returns true if the addition was successful and false if notvoid commit()
Makes the journal immutableint amountBabies()
Returns the number of babies born in a given weekList<Baby> findBabyWithHighestWeight(String gender)
Finds the baby of the specified gender with the highest weight
If there are multiple babies, it sorts them alphabetically by name.List<Baby> findBabyWithSmallestHeight(String gender)
Finds the baby of the specified gender with the smallest height
If there are multiple babies, it sorts them in order of increasing weightSet<Baby> findBabiesByBirthTime(String from, String to)
Finds babies born in the specified time period
- Time of birth is given as a
String
in the form"hour:minute"
. - For implementations of all methods, the parameters passed to them are guaranteed to be correct.
- You can add any private methods to the
BirthJournalManagementImpl
class.
You may not use lambdas or streams to complete this task.
Task
The purpose of this task is to practice with reading, processing and writing to a file using Java *Reader/*Writerclasses and their buffered variants, and usingtry-with-resources
.
Duration:1.5 hours
In this task you will implementLicenseReader#collectLicenses(File, File)
method. It must read all license filesfromroot
, format these licenses to a specific format and write all of them intooutputFile
.root
might be a directory or just a regular file. Please note that you need to collect files not only from theroot directory, but also from its subdirectories and their subdirectories, etc. All non-license files must be ignored.Be aware, that this method must not throw any checked exception.
Take a look at the license header format:
---License: <license name>Issued by: <issuer>Issued on: <date>Expires on: <date>---
The order of these properties is not restricted, so you may expect thatExpires on
might occur earlier thanLicense
. All of them are mandatory except forExpires on
. The date format is ISO date (yyyy-mm-dd
). The licenseis wrapped between lines containing 3 dashes (---
). The file always starts with license header, otherwise it's justa regular file.
If license header is invalid, thenIllegalArgumentException
must be thrown. If eitherroot
oroutputFile
is null,thenIllegalArgumentException
must be thrown. Ifroot
does not exist, or it's not readable, then the sameexception must be thrown. And ifroot
is a directory, but is not executable (means that it could not be entered),thenIllegalArgumentException
must be thrown.
The output format for just one license looks like:
License for <file name> is <license name> issued by <issuer> [<issuedOn date> - <expiresOn date>]
Each line must contain the information about license in this format. If license does not have an expiration date,then instead of<expiresOn date>
-unlimited
must be used.
IfoutputFile
exists, then it must be cleared. So no appending is allowed.
collectLicenses
method must verify thatroot
is:- not null
- exists
- readable
- if it's a directory, then that it's executable
collectLicenses
method must verify thatoutputFile
is not null- if
outputFile
is not empty, then it must be cleared before writing to it - all files and directories of
root
must be processed - non-license files must be ignored
- license files must be processed and info about it must be stored in
outputFile
(see formats inDescription
section) - if license format is invalid, or any verification is failed, then
IllegalArgumentException
must be thrown - all license properties are mandatory, except for
Expires on
(it's optional) - the order of license properties are undefined
- the order in the resulting file does not matter
- if
Expires on
is omitted, then inunlimited
must be used collectLicenses
does not throw any checked exceptionBufferedWriter
/BufferedReader
must be used for IO operations- All IO buffered streams must be defined using
try-with-resources
syntax
libA/libraryA.lic
---License: GNUIssued by: GNU CommitetIssued on: 2020-01-01Expires on: 2025-01-01---Library description...
libraryB.lic
---License: CustomIssued by: GovermentIssued on: 1984-04-13---Top secret info...
output
License for libA/libraryA.lic is GNU issued by GNU Commitet [2020-01-01 - 2025-01-01]License for libraryB.lic is Custom issued by Goverment [1984-04-13 - unlimited]
Task
The purpose of this exercise is to give you some practice managing I/O streams.
It should take you about30 minutes to complete this task.
You will implement an input stream to process data from the file. Please also implement a util class to check a file andreturn a ciphered text.
Please implement methods in theCipherCreator
class.
public static StringBuilder cipherText(File input)
- takes a file as an input and returns a ciphered text.
Please override methods in theTransformerInputStream
class.
public int read()
- reads the next data byte and returns a ciphered byte.public void close()
- closes the stream and prints a message about it to the console.
Cipher key points:
- The text can only contain letters, and each word is written on a new line.
- Each letter of the ciphered text is shifted by two characters from the original one, case-sensitive. A -> C, f ->h.
- The alphabet is looped. It means Z -> B, y -> a.
- All other characters are ignored.
TestcipherForFundamentalsOfProgrammingXYZzyxCamelCaseDiScOcipherText(file);// Vguv// ekrjgt// Hqt// Hwpfcogpvcnu// Qh// Rtqitcookpi// ZAB// baz// EcognEcug// FkUeQ
"Hi"10101 !--!cipherText(file);// Jk////
Task
The purpose of this exercise is to practice the usage of JavaScanner
andFormatter
classes.
Estimated workload of this exercise is60 minutes.
The Car class represents a car with some attributes:
- brand
- model
- cylinder capacity
- performance
- acceleration
The first part of the exercise is to read cars from a CSV (comma-separated values) file.The CSV file contains the car attributes in the same order as listed above.
Implement theCarCsvReader
class'sreadCars(File file)
method to do the job.
- Read the file content line-by-line with
BufferedReader
. Then create aScanner
and configure it to use comma (,) as delimiter.
Input file example:
Toyota,Corolla,1599,75,6.8Kia,Rio,1225,68,10.3
Once the cars are in memory, print them to the console in the following way
- brand: 10 characters width
- model: 10 characters width
- cylinder capacity: 5 digits, add measurement unit: ccm
- performance: 3 digits, add measurement unit: kw
- acceleration: 5 digits, add measurement unit: sec
Implement theFormattedCarPrinter
class'sprint(List<Car> cars)
method.
Output example, given the above list of cars:
Toyota Corolla 1599 ccm 75 kw 6.80 sec Kia Rio 1250 ccm 68 kw 10.30 sec
TheApplication
class is already implemented, which delegatesthe reading task toCarCsvReader
class, and the formatting task toFormattedCarPrinter
class.
The starter project includes a samplecars.csv
file indata
directory. The application has to read that file.
Task
The purpose of this exercise is to train you to manage files and directories using Java NIO.
Duration:1.5 hour
You must implement a method to build a directory representation. You can also create other methods for convenience that will be called from the 'tree' method.
Please implement methods in theFileTree
class.
public Optional<String> tree(final Path path)
- takes a path to a file/directory as an input parameter and builds a String representation of its hierarchy.
If a given pathdoes not exist, return an empty Optional.
If a given pathrefers to a file, return a String with its name and size like this:
some-file.txt 128 bytes
If a given pathrefers to a directory, return a String with its name, total size and full hierarchy:
`
some-dir 100 bytes├─ some-inner-dir 50 bytes│ ├─ some-file.txt 20 bytes │ └─ some-other-file.txt 30 bytes└─ some-one-more-file.txt 50 bytes
`
- Use pseudo-graphic characters to format the output.
- Compute the size of a directory as a sum of all its contents.
- Sort the contents in the following way:
- Directories should go first.
- Directories and files are sorted in lexicographic order (case-insensitive).
Task
The purpose of this exercise is to familiarize you with the mechanism of complex object serialization/deserialization.
Duration:1 hour
In this exercise, you need to implement the serialization of complex objects of theOrder
type. Below is a hierarchy of classes that describe orders.

TheOrder
class represents an order:
id
A unique identifier of the ordertotal
The cost of the order, which is automatically calculated and can only be readitems
A map that stores products (a ke y is an object of theItem
type) and the number of units to be purchased (a value is a variable of theint
type)
TheItem
class represents a product:
id
A unique identifier of the productname
The name of the productdescription
A short description of the productcharacteristics
A list of product features (objects of theItemCharacteristic
type)
The abstract classItemCharacteristic
represents one characteristic of a product and is the supertype for different types of product characteristics:
id
A unique identifier of the characteristicname
The name of the characteristictype
A data type of the characteristic (It can beString
,Integer
,Double
, etc.)
TheIntItemCharacteristic
class represents an integer characteristic and inherits theItemCharacteristic
class:
value
Keeps a value of the characteristic
TheDoubleItemCharacteristic
class represents a numeric characteristic and inherits theItemCharacteristic
class:
value
Keeps a value of the characteristic
TheOrderSerializer
class serializes and deserializes objects of theOrder
class:
public static void serializeOrder(Order order, OutputStream out) throws IOException
Serializes a specified object of the Order class into the given data output streampublic static Order deserializeOrder(InputStream in) throws IOException, ClassNotFoundException
Deserializes a specified object of theOrder
class from the given data input stream
•Each entity class must contain a constructor that accepts values for all fields and can contain any other constructors if necessary.
•All entity classes must have getters and setters for all fields.
•All entity classes must contain an overridden
equals()
method by all fields.•The
ItemCharacteristic
class must beabstract
and must not implement theSerializable
interface.•When calculating the cost of an order in the
Order
class, set thetotal
field value using the following algorithm:- If the
total
field isnull
and theitems
field is notnull
, then a call of thegetTotal()
method must calculate thetotal
value. - If the
items
field isnull
, thetotal
must be zero. - It is guaranteed that the internal state of the
items
field will not change after being installed in the object.
- If the
•The custom serialization mechanism must be implemented in all descendants of the
ItemCharacteristic
class because it is not serializable.
- You may not use the serialization mechanism with the
Externalizable
interface.
Task
The purpose of this task is to train you to declare your functional interface,practice a little more with generics, and see an example of why you might want todeclare your interface when we have plenty of predefined ones.
Duration:15 minutes
In this task, you'll implement the so-calledThrowingFunction
.It's a variant of ajava.util.function.Function
, except for it may throwan exception. It might be really helpful when you want to pass a functionto some method, but the underlying code throws some checked exception(it happens pretty often, when you work with Java IO, for example).
But what exception it might throw?IOException
, orClassNotFoundException
,or justException
, or evenThrowable
? Well, let's try to use generics here.We want to declare a function that would throw an exception, which we can specify.
There is also a pretty common practice to define "companion" methods for suchfunctions. Usually, they called something likesilent
,wrap
,quiet
, etc.The main idea of such companions is to wrap the throwing function and returnthe non-throwing function. It's useful when you need to pass your throwing functionto some API that accepts only non-throwing ones (e.g. Stream API).
Let's go through the requirements of this task:
ThrowingFunction
interface must be declared underedu.epam.fop.lambdas
package- It must be a generic type with generalized:
- Argument type
- Return type
- Exception type
- It must have an abstract
apply
method, which accepts one argument,of one generic type and returns an instance of another generic type apply
method must be able to throw any exception up toThrowable
- It must have a static method for wrapping
ThrowingFunction
intoFunction
,namedquiet
quiet
method must be generic tooquiet
method must returnnull
whennull
is passedquiet
method must not throw any exception- The returned by
quiet
methodFunction
must wrap any occurredinThrowingFunction
exception intoRuntimeException
without hiding the cause - The returned by
quiet
methodFunction
must workjust asThrowingFunction
, when no error has occurred - generic types of
ThrowingFunction
andFunction
must correspond to each other - Generic types must not have any boundaries if possible
ThrowingFunction
must be annotated with@FunctionalInterface
ThrowingFunction<String,Integer,IOException>ioFunc =newThrowingFunction<>() {@OverrideIntegerapply(StringfileName)throwsIOException {returnIOUtils.getSize(fileName); }}
try {returnioFunc.apply("big-file.csv");}catch (IOExceptione) {e.printStackTrace();}
Function<String,Integer>func =ThrowingFunction.quiet(ioFunc);func.apply("big-file.csv");
Task
The purpose of this task is to practice writing simple and concise Java lambda expressions.
Duration:30 minutes
Your task is to provide a Java lambda expression that implementsDoubleFunction<String>
.
As the name of the functional interface indicates it accepts adouble
value,which we want to format to the correspondingString
value in the format:
[-]\d+[.\d] %
Where[...]
means optional,\d
means digit, and+
means at least one symbol.Please note, the space between the number and percent sign. This lambda must never returnnull
.
The passed value can be anything, even more than1 or less than0.The value1 we consider100 %, so-0.5 would be-50 %.
- Convert the
double
value to the correspondingString
value, representing the double value as a percent string. - Never return
null
. - A
-
sign before the number in a string of negative values. - A space between the resulting number and the percent sign.
- A maximum of one digit in the fraction part.
- You must round the fraction part mathematically, i.e. anything less than0.5 is rounded down (floor),and anything greater than or equal to0.5 is rounded up (ceil). For example:
- 1.4 =>1
- 2.45 =>2
- 3.5 =>4
- 17.7000001 =>18
- (Optional) Make the lambdaone line (i.e., without using curly brackets)
The lambda can be tested using the following call, which returns aString
value for testing:
PercentageFormatter.INSTANCE.apply(<doublevalue>);
And here are some expected input/output pairs:
- 0.42 =>
42 %
- 0.427 =>
42.7 %
- 0.4273 =>
42.7 %
- 0.4275 =>
42.8 %
- -0.4275 =>
-42.8 %
Task
The purpose of this task is to practice with Optional, and its main methods -map
,filter
,flatMap
, etc.
Duration:3 hours
In this task, you are provided with some classes that are used for insurance calculations.In theinsurance
package you have:
Subject
- the main sealed interface, which must be implemented by insurance subjects.Car
,Accommodation
,Person
- the subject's insurance is calculated for (which implement theSubject
interface).Currency
- just anenum
of the currencies provided.RepeatablePayment
- represent, for example, rent, salary, or a loan.Injury
,Family
- not subject classes; used to describe a certain part of the subject classes.
These classes a mostly plain data objects without any logic. The only things to highlight are:
- Some getters return
Optional
instead of the target type. - Some of these classes implement
Comparable
interface to make it easier to retrieve the required instancefromSortedSet
.
Also, you havecalculator
package. Here you have two main classes:
InsuranceCoefficient
- a wrapper forint
value in range[0; 100],which represents the percentage of trustworthy clients.InsuranceCalculator<S extends Subject>
- a functional interface,which determinesInsuranceCoefficient
based on the passedS
instance.
Also, here you can find several*InsurancePolicies
classes, which provide methods that must be implemented.Take a closer look at them and define the requirements.
No implementations must throw an exception, and all of them must benull
-safe. Objects can benull
or returnnull
.Getters that returnOptional
never returnnull
.
All arguments cannot benull
.
AcceptsBigInteger divider
which is used to adjust the insurance coefficient.
It must return an insurance coefficient when an accommodation is rented; monthly payment should be inUSD.As a result, for the insurance coefficient, you must divide the rent amount by the divider provided.If the resulting insurance coefficient is more than100, thenInsuranceCoefficient.MAX
is returned.If a condition is not met, then return emptyOptional
.
- The accommodation must include
rent
. - The rent period must be in months.
- The rent currency must beUSD.
- The rent amount must be greater than0.
- The coefficient is equal to rent divided by the divider provided in percent (
rent / divider * 100%
). - If the relation is more than100%,100% should be returned.
- The default value is
Optional.empty
AcceptsBigInteger priceThreshold
, which must be met or exceeded by the accommodation price,int roomsThreshold
, which must be met or exceeded by the room counts,andareaThreshold
are the same but for the accommodation area.
Accommodations price, room count, and the area must be greater or equal to their corresponding thresholds.If all the conditions are met,InsuranceCoefficient.MAX
must be returned;if notInsuranceCoefficient.MIN
must be returned.
- Accommodation price >=
priceThreshold
- Accommodation rooms >=
roomsThreshold
- Accommodation area >=
areaThreshold
- Return
InsuranceCoefficient.MAX
if all conditions are met - Return
InsuranceCoefficient.MIN
if one or more conditions are not met
AcceptsLocalDate baseDate
, which is used as a pivot point for calculations. All calculations must use it.Date-math precision is1 day.
The calculator must return:
InsuranceCoefficient.MAX
if the manufactured date is less than1 year frombaseDate
- A coefficient of70 if less than5 years
- A coefficient of30 if less than10 years
InsuranceCoefficient.MIN
if a car is older than10 years.- If the manufactured date is unknown,
Optional.empty
must be returned
AcceptsLocalDate baseDate
as a base for the date-math calculations,BigInteger priceThreshold
which must be met or exceeded by car price,andPeriod owningThreshold
- the minimum period of ownership.
The idea is to calculate the insurance coefficient only for cars which are still owned by a person (soldDate
is not set),price is greater or equal topriceThreshold
, the period frompurchaseDate
tobaseDate
is greater or equal toowningThreshold
.
The resulting coefficient must be based on car price andpriceThreshold
.If the price of the car is greater than or equal to three times thepriceThreshold
,InsuranceCoefficient.MAX
must be returned. If it exceeds two times but is less than three times greater,a coefficient of50 must be returned.InsuranceCoefficient.MIN
must be returnedif the price is less than or equal to twice the threshold.If any of the conditions are not met,Optional.empty
must be returned.
soldDate
must not be set.price
must be >= thanpriceThreshold
.purchaseDate
+owningThreshold
must be >=baseDate
.InsuranceCoefficient.MAX
must be returned ifprice
>=3 *priceThreshold
.- A coefficient of50 must be returned if3 *
priceThreshold
>price
>=2 *priceThreshold
. InsuranceCoefficient.MIN
must be returned ifprice
<2 *priceThreshold
.Optional.empty
must be returned if any of the conditions are not met.
Acceptsint childrenCountThreshold
. The coefficient must be calculated based on the number of childrena person has relative to the threshold provided.
- A person must have a
family
. - A person must have
children
. - The resulting coefficient equals to
max(100, childrenCount / threshold)
. InsuranceCoefficient.MIN
must return if any of the conditions are not met.
AcceptsBigInteger salaryThreshold
andSet<Currency> currencies
,which together define the salary threshold based on the amount and the currency allowed.
- Person must have an employment history of at least four records.
- They must have multi-currency account.
- They must not have any recorded injuries.
- They must have at least one accommodation (either owned or rented).
- They must be currently employed (i.e., the last employment record does not have
endDate
). salary
for this job must be in one of thecurrencies
provided.salary.amount
must be greater than or equal tosalaryThreshold
.- If all conditions are met, a coefficient of 50 must be returned.
- If any of the conditions are not met,
Optional.empty
must be returned.
AcceptsSet<EmergencyStatus> statuses
, which defines the allowed emergency statusesof an accommodation owned or rented by a person.
- A person must have an accommodation.
- The calculator must pick the accommodation that is the smallest in area.
- Check to make sure its
emergencyStatus
is listed in thestatuses
parameter. - The coefficient is calculated as
100 * (1 - status.ordinal() / totalStatuses)
. - If any of the conditions are not met,
Optional.empty
must be returned.
AcceptsBigInteger rentThreshold
.
- A person must have an injury.
- The injury must have been caused by someone else.
- The largest accommodation (by area) must be rented.
- The rent must be inGBP.
- The coefficient is calculated as
max(100, 100 * rent / threshold)
. - If any of the conditions are not met,
Optional.empty
must be returned.
Task
The purpose of this exercise is to train you in usage of Java Stream API in basic level.
Estimated workload of this exercise is30 minutes.
MovieQueries class is responsible to perform different queries on a list of movie titles.Please implementMovieQueries
constructor and methods according to the following method definitions.Please do not change method names, arguments, or return type of the methods:
Method name | Description |
---|---|
getNumberOfMovies | Count the elements in the movie list. |
getNumberOfMoviesThatStartsWith | Count the elements that start with given parameter. |
getNumberOfMoviesThatStartsWithAndEndsWith | Count the elements that start and end with the given parameters. |
getLengthOfTitleOfMovies | Count the length of all movie titles. |
getNumberOfLettersInShortestTitle | Return the length of the shortest movie title. Throw IllegalArgumentException if the list is empty. |
getFirstTitleThatContainsThreeWords | Return the first movie title that contains three words. |
getFirstFourTitlesThatContainAtLeastTwoWords | Return the first four (and only four) movie title that contains at least 2 words. |
printAllTitleToConsole | Print all movie titles to the console. |
MovieQueries
constructor must throwIllegalArgumentException
if the parameter is null.
In this exercise use Stream API, do not implementfor
loop,while
loop or any other imperative approach.
Having the following test data:
"Terminator", "Blade Runner", "Star Wars", "Indiana Jones", "Friends","The Magnificent Seven", "The Dark Knight", "The Lord of the Rings: The Return of the King","Pulp Fiction"
getNumberOfMoviesThatStartsWith
called with parameter"The"
, returns 3.getFirstTitleThatContainsThreeWords
returns"The Magnificent Seven"
TheApplication
class is already implemented, which delegatesthe querying task toMovieQueries
class.
Task
The purpose of this exercise is to practice Java Stream API at intermediate level.The data model is similar to the previous exercise, movie. In this exercise the model is based on movies, but more complex.
Estimated workload of this exercise is90 minutes.
The stream operations are defined on movie data. There are two domain model classes:Movie
andPerson
.Person
can be the director, writer or cast of the movie..
Person example:
name: Arnold Schwarzeneggerdate of birth: July 30, 1947biography: With an almost unpronounceable surname and a thick Austrian accent
Movie example:
title: The Terminatordescription: A human soldier is sent from 2029 to 1984 to stop an almost indestructible cyborg killing machine.genres: ACTION, SCI_FIlength: 107 (minutes)release year: 1984directors: James Cameronwriters: James Cameron, Gale Anne Hurd, William Wishercasts: Arnold Schwarzenegger, Linda Hamilton, Michael Biehn
Note: directors, writers and casts fields are collections that hold Person reference.
MovieQueries
class is responsible to perform different queries on a list of movies.Please implementMovieQueries
constructor and methods according to the following method definitions.Please do not change method names, arguments, or return type of the methods:
Method name | Description |
---|---|
checkGenreOfAllMovies | Check that all the movies in the list belongs to the given genre. |
checkGenreOfAnyMovies | Check that at least one movie in the list belongs to the given genre. |
checkMovieIsDirectedBy | Check that at least one movie in the list is directed by the given person. |
calculateTotalLength | Calculate the total length of all the movies in the list. |
moviesLongerThan | Count the movies that are longer then the given parameter. |
listOfWriters | Return the writers of all movies. One writer appear only once in the list. |
movieTitlesWrittenBy | Return the titles of movies that are written by the given person. |
listOfLength | Return a list of the length of movies. |
longestMovie | Find the longest movie. Throws IllegalArgumentException if the movies list is empty. |
oldestMovie | Find the oldest movie. Throws IllegalArgumentException if the movies list is empty. |
sortedListOfMoviesBasedOnReleaseYear | Return a sorted list of movies based on their release year. |
sortedListOfMoviesBasedOnTheDateOfBirthOfOldestDirectorsOfMovies | Return a sorted list of movies based on the date of birth of the oldest director of each movie. |
moviesReleasedEarlierThan | Return a list of all the movies which are released earlier than the given year (inclusively). |
MovieQueries
constructor must throwIllegalArgumentException
if the passed parameter is null.
InMovieQueries
implementation you can expect that theMovie
and relatedPerson
objects passed as arguments are all valid,each field is populated with non-null values. No need to validate them.
Use only Java Stream API.
Having the following movies:
The Terminatorgenres: ACTION, SCI_FIBlade Runnergenres: ACTION, SCI_FI, DRAMAIndiana Jonesgenres: ACTION, ADVENTURE
checkGenreOfAllMovies(Genre.SCI_FI)
returns falsecheckGenreOfAnyMovies(Genre.SCI_FI)
returns true
TheApplication
class is already implemented, which delegates the querying task toMovieQuery
class.You can find the models inmodel
package.MovieDataStore
builds test data and provide them to the application.Classes inbuilder
package helps to create models.