Blog do projektu Open Source JavaHotel

niedziela, 18 marca 2018

Circus tower

Introduction
There is an exercise in "Cracking the coding interview", Circus Tower.

Circus Tower: A circus is designing a tower routine consisting of people standing atop one anoth­er's shoulders. For practical and aesthetic reasons, each person must be both shorter and lighter than the person below him or her. Given the heights and weights of each person in the circus, write a method to compute the largest possible number of people in such a tower.
EXAMPLE
lnput(ht,wt): (65, 100) (70, 150) (56, 90) (75, 190) (60, 95) (68, 110)
Output: The longest tower is length 6 and includes from top to bottom:
(56, 90) (60,95) (65,100) (68,110) (70,150) (75,190)
The solution is based on finding the longest subsequence.
Alternative solution
But I developed a very similar solution in term of the directed graph and the solution is to find the longest possible path in the graph. Usually, we want to find the shortest path but this time it is different.  Athletes in the circus are graph nodes and if an athlete can stand atop the weightier athlete then there is an edge from the second to the first.
The C++ code as Eclipse CDC project is available here.
The class Athlete describes a single person and class AthleteGraph describes the connection. The graph is represented as a two-dimensional adjacency matrix. If there is a connection from i to j, then graph[i][j] is true.
The algorithm is recursive.
Assume that we are at the node i, and there are several adjacent nodes to i :  i1,i2 ... i(n). We calculated recursively the longest paths for i1, i2 .. i(n). The longest path starting from i is i itself concatenated with the longest among paths for i1,i2 ... i(n).
Complexity
The most complex is the graph creation because we have to compare a person with every other person to detect edges. So the complexity is O(n squared). Having the graph built, the complexity is O(m), where m is the number of edges, every edge is visited only once.


niedziela, 25 lutego 2018

Civilization The Board Game, next version

Introduction
I deployed a new version of my computer implementation of  Civilization The Board Game. The implementation consists of three parts:
New features
  • Buildings
  • Improvements
Buildings
The player can buy building after researching appropriate technology.

Of course, the city should provide enough production.

Buying building is very simple. Click "Buy Building" button and city you want to enrich.


Last, but not least, point the square you want to industrialize and skyscraper is ready.

Replacement
But building new tower requires sometimes pulling down the old one. In order to avoid mistakes, a different button is displayed if a new building is supposed to be placed over the previous.
If new "star" building is ready to be set up, not only building on the same square could be removed but also another "star" construction.


Next step 
Wonders of the world.

sobota, 24 lutego 2018

Byliśmy na operze

23 stycznia byliśmy na operze Peleas i Melizanda w Teatrze Wielkim. Muzyka podobała się bardzo, ale samo przedstawienie mniej.
Peleas i Melizanda to jedyna opera Debussyego do libretta według dramatu Maeterlincka pod tym samym tytułem. To baśń o tajemnicy, prawdziwym uczuciu i śmierci, osadzona w bliżej nieokreślonym średniowiecznym świecie. Na początku pojawia się młoda dziewczyna która podaje tylko swoje imię, Melizanda. Jej przybycie na dwór króla Golauda wprowadza świeże powietrze do zastygłego świata królewskiej rodziny ale też uruchamia spiralę miłości i śmierci. Gdy na końcu umiera, nie wiemy o niej nic więcej poza imieniem, ale zostawia po sobie małą córkę i właśnie to imię. Jak przepowiada na końcu król Arkel, "Teraz musi żyć w jej imieniu, teraz kolej na to biedne maleństwo". Cykl tworzenia i destrukcji zatoczy kolejne koło.
Sztuka nie tworzy jakiegoś określonego ciągu wydarzeń prowadzących do finału, dialog są wieloznaczne, jest tutaj dużo pytań bez odpowiedzi i odpowiedzi do niezadanych pytań. W tle czujemy atmosferę lęku, niepewności, niewypowiedzianej tajemnicy, bohaterowie sprawiają wrażenie, że nie decyduję o swoim losie, kieruje nimi jakieś zewnętrzna siła, fatum. Sama muzyka nie jest operą do jakiej jesteśmy przyzwyczajeni, nie ma tutaj podziału na arie, recytatywy, partie solowe czy duety. Muzyka idzie za bohaterami, przechodzi płynnie z jednej sceny w drugą.
Ale dlaczego realizacja podobała się mniej? Była próbą osadzenia nieokreśloności na bardziej twardym gruncie. Sama akcja to sen Melizandy, gdzie bohaterka jest jednocześnie demiurgiem i podmiotem. Zasypia na początkui i budzi się na końcu. Pałac Golauda to burżuazyjna posiadłość i dysfunkcyjna rodzina, zaś Melisanda jest ofiarą zazdrości i namiętności rozpalonych samców. Niektóre sceny przypominają estetykę z filmów dla dorosłych. Czasami widzimy dwie Melisandy i nie jest jasne która jest prawdziwa, zaś która to alter ego. Nie jest zrozumiałe, dlaczego Melisanda czasami siada na barana na Golaudzie.
Na szczęscie od strony muzycznej i wykonawczej przedstawienie jest znakomite, muzyka się broni. Najlepiej kupić bilety, usiąść na widowni, zamknąć oczy i po prostu słuchać. Jeśli ktoś tu poniósł porażkę, to na pewno nie Debussy.

piątek, 5 stycznia 2018

Civilization The Board Game, next version

Introduction
I deployed a new version of my computer implementation of  Civilization The Board Game. The implementation consists of three parts:
New features
  • Greeting window more verbose
  • Research, building up technology tree
Greeting window

Civilizations tiles more descriptive. But that's description only, civilization capabilities, government and technologies are not implemented yet.
Technology tree
The player can spend trade and enhance technology tree.
The current technology tree can be reviewed any time by clicking technology icon. The player can also peek opponent's achievements on this field.
Unfortunately, the thumb is down. The technology abilities are not implemented.
Next steps
Producing unlocked buildings.

środa, 27 grudnia 2017

Next version of Civilization The Board Game

Introduction
I deployed a new version of my computer implementation of  Civilization The Board Game. The implementation consists of three parts:
New features
  • Player can explore huts
  • Player can attack and take over villages
  • Fight between players in two player game
  • Improvements
Exploring huts
To explore hut, go to the square adjacent to the hut and click "Explore" button.

Then hut is visible in the player resource panel on the left. Click the resource panel and discover the resource guarded by the hut.

Attacking villages
In order to take over the village, the player has to position the figure close to the village and click "Attack" button.

Next step is to start the battle.
Next step, last but not least, is to win the battle!
In training, single player game, the player has to take a role of attacker and defender. In two player game, the opponent has to fight as a barbarian.
To fight, just drag a unit from waiting list to the battle zone. The game engine will resolve the result of the battle.
This time you win. But be careful next time, you may lose as well.
Two player battle
In two player game, one of the players can attack another player. 


The only difference comparing to village battle, the victor can pick up a loot from the loser.
Improvements
I removed confirmation for all movements ("Are you sure ?"). The game runs more smoothly but there is a risk of mistake. 
Problems
The game is running slowly and awkward on Heroku in two players mode. In two players game, the client is probing constantly in 0.5 sec intervals the server to discover the change caused by other player action. The server is under the shell and is reacting slowly causing latency. Some improvements are necessary.
Next steps
  • Research implementation
  • Improvements


czwartek, 30 listopada 2017

HDP 2.6.3, Ambari, Python

I was stuck by very nasty error while installing latest HDP 2.6.3 on RedHat 7.3. Installation failed giving the following error message:
Traceback (most recent call last):
  File "/var/lib/ambari-agent/cache/custom_actions/scripts/check_host.py", line 170, in actionexecute
    installed_packages, repos = self.execute_existing_repos_and_installed_packages_check(config)
  File "/var/lib/ambari-agent/cache/custom_actions/scripts/check_host.py", line 233, in execute_existing_repos_and_installed_packages_check
    installedPackages = self.pkg_provider.all_installed_packages()
  File "/usr/lib/python2.6/site-packages/resource_management/core/providers/package/yumrpm.py", line 222, in all_installed_packages
    return self._get_installed_packages(None)
  File "/usr/lib/python2.6/site-packages/resource_management/core/providers/package/yumrpm.py", line 157, in _get_installed_packages
    packages = self._lookup_packages([AMBARI_SUDO_BINARY, "yum", "list", "installed"], "Installed Packages")
  File "/usr/lib/python2.6/site-packages/resource_management/core/providers/package/yumrpm.py", line 191, in _lookup_packages
    if items[i + 2].find('@') == 0:
IndexError: list index out of range
No handlers could be found for logger "ambari_agent.HostCheckReportFileHandler"
Traceback (most recent call last):
  File "/usr/lib/python2.6/site-packages/ambari_agent/HostCheckReportFileHandler.py", line 74, in writeHostChecksCustomActionsFile
    items.append(itemDetail['name'])
TypeError: string indices must be integers, not str
I took me some time to get to the bottom. It looked that the culprit was additional stuff attached to the end of "yum list installed".
yum-metadata-parser.x86_64        1.1.4-10.el7               @anaconda/7.3
yum-rhn-plugin.noarch             2.0.1-6.1.el7_3            @rhel-7-server-rpms
zip.x86_64                        3.0-11.el7                 @anaconda/7.3
zlib.x86_64                       1.2.7-17.el7               @anaconda/7.3
Uploading Enabled Repositories Report
Loaded plugins: product-id
Judging from the Python source code:
    for i in range(0, len(items), 3):

        if '.' in items[i]:
          items[i] = items[i][:items[i].rindex('.')]
        if items[i + 2].find('@') == 0:
          items[i + 2] = items[i + 2][1:]
        packages.append(items[i:i + 3])

    return packages
the installer is expecting a number of elements returned from "yum list" to be divided by 3 and this two lines at the end obviously break this assumption. So the solution (working) was the manual fix in /usr/lib/ambari-agent/lib/resource_management/core/providers/package/yumrpm.py. Important: in this file, not in the file specified in error stack trace:  /usr/lib/python2.6/site-packages/resource_management/core/providers/package/yumrpm.py, because the installer every time overwrites script in /usr/lib/python2.6/site-packages/resource_management/core/providers/package directory. After the fix the aforementioned piece of code looks:
     for i in range(0, len(items), 3):

        if i + 2 >= len(items) : break

        if '.' in items[i]:
          items[i] = items[i][:items[i].rindex('.')]
        if items[i + 2].find('@') == 0:
          items[i + 2] = items[i + 2][1:]
        packages.append(items[i:i + 3])

    return packages

sobota, 28 października 2017

Next version of Civilization The Board Game

Introduction
I deployed next version of my computer implementation of  Civilization The Board Game. The implementation consists of three parts:
New features
  • spend trade for production and undo spend
  • scout can send production to the city and undo sending
  • buying units
Spend trade for production

Just specify the number of production you want to get and the trade is reduced accordingly. So you can do shopping as you wish.The player can also undo the last spending unless it is used.
Send production from square to the city

Click the city and choose the scout you want to send production.
The player can also undo this action unless production is spent.
Click Undo button right to the grayed "Send Production" button.
Buying units

The player can buy units although the battle is not implemented yet. The unit panel shows only the number of units of a particular type. After clicking the panel, the detailed list of units including their strength is revealed. Of course, this option is not available for opposite player. Also, in the market panel, any player can see the detailed list of killed units but not the units still waiting to be taken.
Next steps
  • Resource harvesting including friendly villages
  • Battle