четвъртък, 3 септември 2020 г.

JetBrains September coding challenge

I love JetBrains IDE's. They are really cool. I am also currently participating in JetBrains academy and I am trying to improve my Java skills. JetBrains academy is a perfect service where you can study Java, Python and Web development. I love the possibility to solve tasks directly in your IDE. I am creating this post because I am participating in JetBrains September codding challenge. The challenge is to solve at least one problem of a day in the academy.

The first one was OOP task.

Here is the description of the task:
"Write a class named User. It must have three string fields: login, firstName, lastName and a constructor with three parameters to initialize these fields. The order of parameters in the constructor must be the same as presented bellow. Do not make the fields and the constructor private."

The idea is the participant to train OOP a little bit. How to create a class in Java and how to create a constructor. Here is a short video which demonstrates the task:



Here is how the code looks:

The second task was:

"You want to create a program that models the behavior of cars. For this purpose, you've created a class named Car containing three fields: the int field yearModel, the string field make, and the int field speed. You want to add functionality to your cars, so you need methods. Add the following instance methods to your class: void accelerate() that adds 5 to the speed each time it's called; void brake() that subtracts 5 from the speed field each time it's called, the speed cannot be less than zero. Do not make the fields and methods private."
The idea is the participant to train OOP more to creating methods. Here the tricky part was that when the car speed cannot be less than 5 the car must stop. :) Here is a short video which demonstrates the task:

Here is how the code looks:



The same day I've implemented a task about multidimensional arrays. You must draw an asterisk in console using a matrix - two dimensional array. The task was a bit tricky but very funny:
The star figure
Given an odd number n, not exceeding 15. Create a two-dimensional array 
(matrix) from n×n elements,
 by filling it with "." symbols (each element of the matrix is a string
 containing a single symbol). 
Then fill the middle row of the matrix, the middle column, and the main 
and the secondary diagonals 
with the "*" symbols. As a result, all "*"s in the array must form the 
star figure. 
Output this matrix; elements of the array should be space separated.


Sample Input:
5

Sample Output:
* . * . *
. * * * .
* * * * *
. * * * .
* . * . *"

This is how my implementation looks: I also implemented Angular version for that task which can be viewed here. This Angular application displays how the shape looks with different matrix sizes.
After I finished the whole challenge I started to write the bellow part of the post.

The third thing which I did was that task:

Given the sequence of integer numbers (which ends 
with the number 0). Find the largest element of the sequence.

The number 0 itself is not included in the sequence 
but serves only as a sign of the sequence’s end.

Sample Input 1:

1
7
9
0

Sample Output 1:

9
And this is my code.

The fourth:

Declare an enum Currency.

It should include the following 
currency codes (according to ISO 4217):

    USD — United States dollar
    EUR — Euro
    GBP — Pound sterling
    RUB — Russian ruble
    UAH — Ukrainian hryvnia
    KZT — Kazakhstani tenge
    CAD — Canadian dollar
    JPY — Japanese yen
    CNY — Chinese yuan

You must include all of the codes presented above and nothing else. 
The constants in the enum can be declared in any order.
This is my code:

The fifth:

It was a sipmple question: 
What name should the class containing the main method have?
Of course it can have any name.


The sixth:

It was finishing of Stage 1/5 of the Tic-Tac-Toe project. You can check 
the whole finished project here 
in Github. 
Description

Tic-tac-toe is a game played by two players 
on a 3x3 field.

One of the players plays as 'X', and the other player is 
'O'. 'X' plays first, then the 'O' side plays, and so on.

The players write 'X' and 'O' on a 3x3 field.

The first player that writes 3 'X' or 3 'O' in a 
straight line (including diagonals) wins.

Your first task in this project is to print any state 
of the field in the console output.
Example

The example below shows how your output might look.

X O X
O X O
X X O 
Bellow you can check the code of that step:

The seventh:

It was finishing of Stage 2/5 of the Tic-Tac-Toe project: 
The user is the gamemaster 
Description

In this stage, you should write a program that 
reads 9 symbols from the input 
and writes an appropriate 3x3 field. Elements of 
the field can contain only 'X', 'O' and '_' symbols.

Note, that field has a specific format and should start 
and end with ---------, all lines in between should start 
and end with '|' symbol and everything in the middle 
should be separated with a single space.
Examples

Examples below show how your output should look.

Example 1:

Enter cells: O_OXXO_XX
---------
| O _ O |
| X X O |
| _ X X |
---------

Example 2:

Enter cells: OXO__X_OX
---------
| O X O |
| _ _ X |
| _ O X |
---------

Example 3:

Enter cells: _XO__X___
---------
| _ X O |
| _ _ X |
| _ _ _ |
---------
Bellow you can check the code of that step:

The eight:

It was finishing of Stage 3/5 of the Tic-Tac-Toe project: 
What's up on the field?  
Description

In this stage, you should analyze a Tic-Tac-Toe field.

Note. In this stage either 'X' or 'O' can start the game.

After printing the field, you need to find the state
in which the game is at the moment. Possible states:

    "Game not finished" - when no side has a 
    three in a row but the field has empty cells;
    "Draw" - when no side has a three in a row 
    and the field has no empty cells;
    "X wins" - when the field has three X in a
    row;
    "O wins" - when the field has three O in a 
    row;
    "Impossible" - when the field has three X 
    in a row as well as three O in a row. Or 
    the field has a lot more X's than O's or
    vice versa (if the difference is 2 or 
    more, should be 1 or 0).

Also, you can use ' ' or '_' to print empty 
cells - it's up to you.
Examples

The examples below show outputs for some 
predefined states. Your program should 
work in the same way.

Example 1:

Enter cells: XXXOO__O_
---------
| X X X |
| O O _ |
| _ O _ |
---------
X wins

Example 2:

Enter cells: XOXOXOXXO
---------
| X O X |
| O X O |
| X X O |
---------
X wins

Example 3:

Enter cells: XOOOXOXXO
---------
| X O O |
| O X O |
| X X O |
---------
O wins

Example 4:

Enter cells: XOXOOXXXO
---------
| X O X |
| O O X |
| X X O |
---------
Draw

Example 5:

Enter cells: XO_OOX_X_
---------
| X O   |
| O O X |
|   X   |
---------
Game not finished

Example 6:

Enter cells: XO_XO_XOX
---------
| X O _ |
| X O _ |
| X O X |
---------
Impossible

Example 7:

Enter cells: _O_X__X_X
---------
|   O   |
| X     |
| X   X |
---------
Impossible

Example 8:

Enter cells: _OOOO_X_X
---------
|   O O |
| O O   |
| X   X |
---------
Impossible
Bellow you can check the code of that step:

The ninth was the project of the day.

Write a program that reads an array of 
lowercase strings and checks whether the array is in alphabetical 
order or not.

There are some rules to compare a pair of strings
a and b:

    First chars of strings are compared: a[0] and b[0]. 
    If a[0] comes earlier than b[0] in the alphabet, 
    then a comes before b in terms of alphabetical order. 
    If the first chars are the same, then the second 
    chars are compared, and so on.
    If a position is reached where one string has no 
    more chars to compare while the other does, 
    then the shorter string is deemed to come first 
    in alphabetical order.
    Finally, identical strings are always in 
    alphabetical order.

You can use compareTo method of the String class to 
compare 2 strings. If this String object 
alphabetically precedes the argument string, 
then the result is a negative integer. The result 
is a positive integer if this String object alphabetically 
follows the argument string. The result is zero if the 
strings are identical. This is exactly what you need 
to compare 2 strings in terms of alphabetical order!

For example

System.out.println("abc".compareTo("acd")); // -1 "abc" < "acd"
System.out.println("abc".compareTo("aac")); //  1 "abc" > "aac"
System.out.println("abc".compareTo("abc")); //  0 "abc" = "abc"

Input data format

The single input line contains lowercase strings separated by spaces.

Output data format

Only a single word: true or false.
Report a typo

Sample Input 1:

a b c

Sample Output 1:

true

Sample Input 2:

a aa az aza

Sample Output 2:

true
Bellow you can check the code of that step:

The tenth was the daily step:

Here is the method named getNumberOfMaxParam that 
takes three integer numbers and returns the 
position of the first maximum in the order of the method parameters.

The method should return number 1, 2 or 3 respectively.

Write just a body of the method.
Report a typo

Sample Input 1:

12 3 12

Sample Output 1:

1
Here you can see my code:

The eleventh was the daily step:

Shape Switch statement
Write a program, which reads the 
number of the shape (1 – square, 
2 – circle, 3 – triangle, 4 – rhombus) 
and prints the text "You have chosen 
a square" (or circle, or triangle, 
or rhombus, depending on the number). 
If it is a number that doesn't correspond 
to any of the listed shapes, 
the program should output: 
"There is no such shape!".

Note: output text should exactly match 
the sample, including letters' 
case and location of spaces.
Report a typo

Sample Input 1:

1

Sample Output 1:

You have chosen a square 
Here you can see my code:

The twelfth was a daily step:

Given a sequence of natural numbers, 
not exceeding 30000. Find the maximum 
element divisible by 4. As input, the 
program gets the number of elements 
in the sequence, and then the elements 
themselves. In the sequence, there is 
always an element divisible by 4. The 
number of elements does not exceed 1000. 
The program should print a single number: 
the maximum element of the sequence divisible by 4.

Try to solve this problem by using a while-loop.
Report a typo

Sample Input 1:

10
76
18
69
63
36
18
49
16
12
50

Sample Output 1:

76
Here you can see my code:

The thirteenth was a daily step:



The cinema has n rows, each row consists of m seats (n and 
m do not exceed 20). 
The two-dimensional matrix stores the information on the
sold tickets, number 
1 means that the ticket for this place is already sold, 
the number 0 means 
that the place is available. You want to buy k tickets 
to the neighboring 
seats in the same row. Find whether it can be done.

Input data format

On the input, the program gets the number of n rows and m seats. 
Then, there are n lines, each containing m numbers (0 or 1) 
separated by spaces. The last line contains a number k.

Output data format

The program should output the number of the row with k 
consecutive available seats. If there are several rows 
with k available seats, output the first row with these 
seats. If there is no such a row, output the number 0.
Report a typo

Sample Input 1:

3 4
0 1 0 1
1 1 0 1
1 0 0 1
2

Sample Output 1:

3

Sample Input 2:

3 3
0 1 0
1 0 0
1 1 1
3

Sample Output 2:

0
You can see my code here:

The fourteenth was a daily step:

Write a program that reads a sequence of integer numbers in a 
loop and adds up all numbers. If a new number is equal to 0, 
the program must stop the loop and output the accumulated sum. 
When the sum is equal or exceeded 1000 (the barrier), 
the program should also stop and output the value equal to sum – 1000.

Note, the input can contain extra numbers. Just ignore them.
Report a typo

Sample Input 1:

800
101
102
300
0

Sample Output 1:

3

Sample Input 2:

103
105
109
0
1000

Sample Output 2:

317
Here you can check my implementation:

The fifteenth was completing of a stage for the Tic-Tac-Toe project.

Stage 4/5: First move!
Description

Now you need to implement player's moves.

Suppose the bottom left cell has the coordinates (1, 1) and the top 
right cell has the coordinates (3, 3) like in this table:

(1, 3) (2, 3) (3, 3)
(1, 2) (2, 2) (3, 2)
(1, 1) (2, 1) (3, 1)

The program should work in the following way:

    Get the 3x3 field from the input as in the previous stages,
    Output this 3x3 field with cells before the user's move,
    Then ask the user about his next move,
    Then the user should input 2 numbers that represent the cell
    on which user wants to make his X or O. (9 symbols representing 
    the field would be on the first line and these 
    2 numbers would be on the second line 
    of the user input),
    Then output the table including the user's most recent move.

Do not delete code that checks for table state; it will be useful 
in the future.

Note that in this stage user moves as X, not O. Keep in mind that the first 
coordinate goes from left to right and the second coordinate goes 
from bottom to top. 
Also, notice that coordinates start with 1 and can be 1, 2 or 3.

But what if the user enters incorrect coordinates? The user could 
enter symbols instead
of numbers or enter coordinates representing occupied cells. 
You need to prevent 
all of that by checking user's input and catching possible 
exceptions.

The program should also check user input. If the user input 
is unsuitable, 
the program should ask him to enter coordinates again.

So, you need to output a field from the first line of the 
input and then ask the
user to enter a move. Keep asking until the user enters 
coordinates that represent
an empty cell on the field and after that output the 
field with that move. 
You should output the field only 2 times: before the 
move and after a legal move.
Examples

The examples below show how your program should work.

Example 1:

Enter cells: X_X_O____
---------
| X   X |
|   O   |
|       |
---------
Enter the coordinates: 1 1
---------
| X   X |
|   O   |
| X     |
---------

Example 2:

Enter cells: _XXOO_OX_
---------
|   X X |
| O O   |
| O X   |
---------
Enter the coordinates: 1 3
---------
| X X X |
| O O   |
| O X   |
---------

Example 3:

Enter cells: _XXOO_OX_
---------
|   X X |
| O O   |
| O X   |
---------
Enter the coordinates: 3 1
---------
|   X X |
| O O   |
| O X X |
---------

Example 4:

Enter cells: _XXOO_OX_
---------
|   X X |
| O O   |
| O X   |
---------
Enter the coordinates: 3 2
---------
|   X X |
| O O X |
| O X   |
---------

Example 5:

Enter cells: _XXOO_OX_
---------
|   X X |
| O O   |
| O X   |
---------
Enter the coordinates: 1 1
This cell is occupied! Choose another one!
Enter the coordinates: 1 3
---------
| X X X |
| O O   |
| O X   |
---------

Example 6:

Enter cells: _XXOO_OX_
---------
|   X X |
| O O   |
| O X   |
---------
Enter the coordinates: one
You should enter numbers!
Enter the coordinates: one three
You should enter numbers!
Enter the coordinates: 1 3
---------
| X X X |
| O O   |
| O X   |
---------

Example 7:

Enter cells: _XXOO_OX_
---------
|   X X |
| O O   |
| O X   |
---------
Enter the coordinates: 4 1
Coordinates should be from 1 to 3!
Enter the coordinates: 1 4
Coordinates should be from 1 to 3!
Enter the coordinates: 1 3
---------
| X X X |
| O O   |
| O X   |
---------
You can check my code below:

The sixteenth was completing the last stage of Tic-Tac-Toe project:

Description

Now it is time to make a working game!

In the last stage, make it so you can 
play a full game with a friend. First 
one of you moves as X, and then the other 
one moves as O.

You need to create a game loop. The game 
starts with empty cells and ends when 
someone wins or there is a draw. You 
need to output the final result 
after the end of the game.

Good luck gaming!
Example

The example below shows how your program should work.

---------
|       |
|       |
|       |
---------
Enter the coordinates: 2 2
---------
|       |
|   X   |
|       |
---------
Enter the coordinates: 2 2
This cell is occupied! Choose another one!
Enter the coordinates: two two
You should enter numbers!
Enter the coordinates: 1 4
Coordinates should be from 1 to 3!
Enter the coordinates: 1 3
---------
| O     |
|   X   |
|       |
---------
Enter the coordinates: 3 1
---------
| O     |
|   X   |
|     X |
---------
Enter the coordinates: 1 2
---------
| O     |
| O X   |
|     X |
---------
Enter the coordinates: 1 1
---------
| O     |
| O X   |
| X   X |
---------
Enter the coordinates: 3 2
---------
| O     |
| O X O |
| X   X |
---------
Enter the coordinates: 2 1
---------
| O     |
| O X O |
| X X X |
---------
X wins
You can see my implementation below:

The seventeenth was completing the Tic-Tac-Toe project and publishing it to Github.



Тhe eighteenth was completing a daily step:

You are creating a calculator that manipulates complex numbers. 
Write a class named Complex. It must have two double 
fields named real and imaginary.
Below you can check my code:

сряда, 11 декември 2019 г.

Lesson learnt about Hiper-V under Windows 10

I am not a Devop. I use VirtualBox sometimes when I need Nix* compatible system on my business PC. I use Ubuntu on my desktop PC at home. For a project I used to do it on regular basis. Some time ago I needed to install Docker and enabled Hiper-V on host PC. As a result my VirtualBox with Ubuntu stopped work and I was not able to start it even when I disabled Hiper-V completely from Windows interface and switched it off. Every time my VirtualBox was showing the following error:

Result Code:E_FAIL (0x80004005)Component:ConsoleWrap Interface:IConsole {872da645-4a9b-1727-bee2-5585105b9eed}


I researched the problem in Google but nothing helped. The box was not mandatory at that moment and I gave up to fix the issue because I already was working on another project which doesn’t required Nix* architecture. For that project I need Nix* only If I want to tests some bash script. Eventually I found a solution. If nothing helps you can try to fully remove Hyper-V feature with it's files and programs:

Disable-WindowsOptionalFeature -Online -FeatureName Microsoft-Hyper-V-All


You need to do this in the PowerShell console which needs to be run as an administrator. This is the only thing which helped me. I am writing this post for someone with a similar problem in the future. Thanks to this Stackoverflow answer:

https://stackoverflow.com/a/37143600/907047

Just bear in the mind. Use this only if something other didn't helps.

понеделник, 15 август 2016 г.

Presentation about Babel

I will lead a presentation about Babel in Questers.
Babel is a in fact coverter from ECMAScript 6 to ECMAScript 5. If you want to use ES6 features you can use it into your code and after this you can transpile
it for production. Everione who is interested is welcome. The presentation will be conducted in the Bulgarian language. You can register here.

събота, 16 юли 2016 г.

How to have value like baseDirectory into singleton object in Sbt?


I am currently a lamer in sbt technology. Sbt stands for Simple build tool. This is a build system that is highly developed, modern and is the de facto standard build tool in the Scala world. Currently I'm using sbt for several job tasks and last week I came across a rather unpleasant problem that probably is very easy to solve for experienced Scala and sbt developer. I am writing this article to help people with a similar problem in the future. Sbt has several global settings. One of this global settings is
baseDirectory. Depending on the scope, this is the base directory for the build, the project, the configuration, or the task. You can easy get value of project base directory from sbt console. Just type
baseDirectory and you will get the value of this setting.
You can also use inspect baseDirectory and you will get additional information.
In sbt is a good practice to isolate long tasks into singleton object and keep build.sbt much shorter. This is very cool but in order to have some global settings into this singleton object there are several tricky things that you must to do. The same thing is true if you want to have streams available to the singleton object. My job task involved to process a certain way all the files that meet certain criteria. For this purpose, I had to have baseDirectory for project. When I tried to pass baseDirectory as a method argument in this way:
And this:
Every time I got error like this:
I tried several things. For example to pass baseDirectory.value in this way:
But I got errors that .value cannot be used in this way. In the end, I managed to solve the problem with using ".." into the singleton object, that means "the parent directory". But this solution is not good at all. What will happen if the location of .scala file is changed? I love stackoverflow. Sometimes you can ask and get valuable help and explanations. Also you can answer questions and thereby helping others. I asked the question and received a helpful guidance. So If you want to have baseDirectory or similar value into singleton object, you must define the object like this.
And into build.sbt this:
Or this:
I like second solution because looks much clearer.
You can also check example repository into github here. If you want you can check the stackoverflow question.

понеделник, 4 юли 2016 г.

Install latest maven 3 under Ubuntu.

Maven is the de facto standard build tool for Java. There is something that extremely annoys me under Ubuntu. That every time you need to install the latest maven 3 manually and never got it in the standard Personal Package Archives ('PPAs'). Of course there are external PPA, but always the question arises how much can be trusted their contributors. Today I again needed to update maven into one vagrant box so I repeat the exercise again. Maybe this bash script will be useful for the people with a similar problem in the future. The script just install the latest - 3.3.9 version of Maven. The idea is to can be modified easily in the future - just to change variables with name and path. I do not pretend that the script is good - I'm not bash programmer.

понеделник, 5 октомври 2015 г.

Jasmine Clock

Today I had to write unit tests for JavaScript time dependent code. I liked that Jasmine supported a way to make setTimeout or setInterval to behave synchronously. When we install clock with jasmine.clock().install(); into beforeEach we change behaviour of setTimeout and setInterval functions to be synchronous.
After this we can move forward in time like using time machine and check result of asynchronous process. We can go into future with jasmine.clock().tick function, which takes a number of milliseconds. This is small example code:

TimeoutSpec.js
1    describe("Jasmine Clock demo", function () { 
2     
3        // It is installed with a call to jasmine.clock().install  
4        // in a spec or suite that needs to manipulate time. 
5        beforeEach(function () { 
6            jasmine.clock().install(); 
7        }); 
8     
9        // Be sure to uninstall the clock after you are done  
10       // to restore the original functions. 
11       afterEach(function () { 
12           jasmine.clock().uninstall(); 
13       }); 
14    
15       it("setTimeout must behave synchronously", function () { 
16           var array = [1, 2, 3, 4, 5, 6]; 
17           var sum = 0; 
18           (function _handleArray() { 
19               sum += array.shift(); 
20               if (array.length != 0) { 
21                   setTimeout(_handleArray, 0); 
22               } 
23           }()); 
24    
25           // The cool part  
26           // We have something like 
27           // time machine and can  
28           // move time forward.  
29           jasmine.clock().tick(200); 
30           // 1 + 2 + 3 + 4 + 5 + 6 
31           // is equal to 21 
32           expect(sum).toEqual(21); 
33       }); 
34   }); 
35   
And here can be viewed this code: http://gonaumov.github.io/jasmineClockDemo/ running into Jasmine 2.3.4 with spec file.

четвъртък, 27 август 2015 г.

Get rid of crossdomain origin errors.

When developers work on web applications under Windows there are often crossdomain  origin errors. The old version of  Google Chrome browsers provides a  usefull feature
--disable-web-security command line argument for  chrome.exe but unfornatelly this option was deprecated.  When you try to use it under current version of Chrome
- Version 44.0.2403.157 m you will get the following error:
"You are using an unsupported command-line flag:   --disable-web-security. Stability and security will suffer.". I tried to download current Chromium build   but with no luck - this errors appear again. After a small time thinking I'm came to a solution that I want to share with other people with a similar problem. I download Opera that is based on Chrome. Under Opera this command line option
 works like a charm and you have the same tools available.  Even an emulator for mobile devices.


Here is small demo. Get response from yahoo when google is open. Executing of this small snippet
from console.

(function() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
console.log(xhr.responseText);
}
}
xhr.open('GET', '//www.yahoo.com/', true);
xhr.send();
}());

And here is the result: 


But if you want to use just a Google Chrome I write this script to make the starting of Google Chrome browser without security much easier than it was before. The script checks if there is running instances of chrome.exe and if there is a present instance, alerts the user that the running instance must be killed before Google Crome is started. If the user clicks on Yes button, the script will kill all instances of chrome.exe. After this, will open a new browser instance without security. If the user clicks on No button, the script will do nothing. If there is no present running instance of chrome.exe, the script will start Google Chrome without security. How to use it? Just clone this repository and fill correct path to chrome.exe. The script is tested on windows 8 with admin rigths. Don't hesitate to write to me with suggestions and feature requests.
https://github.com/gonaumov/chromeRunner