Analysis of the game from classmates on Joker 2018


    Hello! A few days ago we laid out a post about puzzles that were given at the Joker 2018 conference. But this is not all! This year, especially for Joker, we made a whole game with equally interesting Java tasks (and not only), about which we’ll tell you today.

    We have done similar games at conferences before, for example, at the JPoint past this spring. To make a game, we had to: 1) invent a game mechanic, 2) come up with questions, 3) implement all this.

    Game mechanics should be very simple, intuitive, but at the same time not too banal, so as not to deprive of excitement. As a result of long discussions, they came up with such a game:


    It is necessary, answering questions, to try to lead Duke (in the upper left corner) to one of the doors in the other corners. One session of the game takes 3 minutes. To open a cell, you need to correctly answer the question, which is chosen randomly each time in accordance with the category. For the correct answers points are awarded, for incorrect ones - a penalty, the cell with the question is blocked and it will have to be bypassed. As a result, the path can be quite long or even blocked. Players can choose different strategies: reach the exit as quickly as possible and get an extra bonus; answer as many questions as possible in the allotted time; go a long way on simple issues, or directly on more complex and get more points.


    With the mechanics figured out, now we need to come up with questions. They should be of three categories of complexity, from the simplest to hardcore. The wording of the questions should be extremely short, there will be no time to read the sheets of the text. Answers should be such as not to give too many clues. Well, the questions themselves should be interesting and practical. At the same time there should have been a lot of them so that they would not repeat too quickly. As a result of the joint efforts, we managed to come up with 130 questions about data structures, algorithms, “java-passers”, hardcore questions about the internals of the JVM, and even a few questions about Docker.


    There is a problem: the game is displayed on the big screen, and those who stand side by side will remember most of the answers for several games. At first it seemed that we would need hundreds of questions in order to keep the possibility of remembering to a minimum. But, on reflection, they realized that there are easier options. For a start, they removed the mouse control, leaving only the keyboard. Now those who are near see the question, but do not see what answer the player has chosen. Added mixing options for answers, making it difficult to remember. For each question, we added several similar, but slightly different wording. Of course, it is still possible to remember the answers, and this was evident from the noticeably improved results on the second day of the conference. Many users spent dozens of minutes playing to try to break the record of others. But everything is like in life - diligence is rewarded.

    Two weeks have passed from the emergence of the idea to the invention of questions and implementation Of course, everything is in Java. Used spring boot and gradle. WEB-interface is made on Angular. The built-in database H2, which is out of the box, comes with a web-interface, which is very convenient. The stand configuration is two MacBooks, the picture of which is duplicated on two TVs. For convenience, the application settings were remotely deployed in our cloud ( https://habr.com/company/odnoklassniki/blog/346868/ ).


    We learned a long time ago: no feature should be developed without collecting statistics. Of course, for the game we screwed up detailed statistics that we can share.

    In total, the game in two days was played 811 times. Statistics of answers depending on the complexity of the question:

    DIFFICULTY
    COUNT
    CORRECT_PERCENT
    one
    3552
    61
    2
    2031
    49
    3
    912
    46

    Which cells of the field and how often the players reached:


    The percentage of correct answers on each cell of the field:


    But the most interesting is, of course, the statistics of questions. It was not so easy to assess their complexity in view of their categorization, evaluation is always subjective, and a simple question for one user is difficult for another. Oleg offered to throw out one of the questions with the words “even the cleaners know this,” but it turned out that not all cleaners know the correct answers to many “simple” questions, and the programmers too. We offer you some questions from our game - the leaders with the wrong answers, try to evaluate your strength!

    1. The result of calling this code?

      System.out.println(1/0d)

      • Throw ArithmeticException
      • Will print "Infinity"
      • Will print "NaN"
      • Will print 0

      Answer
      Это кажется очень простым вопросом. Тут простая арифметика, какой может быть подвох, почему же правильный ответ дали только 28 % игроков? Деление целого числа на 0 приводит в Java к ArithmeticException. Но целые ли тут числа? Посмотрим внимательно. Что там за «d» после 0? Эта буква означает, что перед нами не целочисленная константа 0, а значение типа double. И получается, что выражение идентично 1.0/0.0. А это уже деление с плавающей точкой на ноль, результат которого равен Double.POSITIVE_INFINITY. Значит, правильный ответ — «b».
    2. The result of calling this code?

      System.out.println(
          Long.MAX_VALUE==(long)Float.MAX_VALUE
      );
      

      • prints true
      • prints false
      • throw away ArithmeticException

      Answer
      Для начала, нужно понять, что больше: Float.MAX_VALUE или Long.MAX_VALUE? Хотя float имеет меньший диапазон значений, чем double, всё равно его максимальное значение примерно на 20 порядков выходит за диапазон возможных значений long. Но как в данном случае сработает приведение типов? Можно гадать, но лучше запустить код. А еще лучше — открыть Java Language Specification, раздел про Narrowing Primitive Conversion, и прочитать, что если значение числа с плавающей точкой слишком велико и выходит за диапазон доступных значений целочисленного типа, то результат конверсии равен максимальному значению, которое можно представить с помощью целочисленного типа. Т.е. результат конверсии равен Long.MAX_VALUE. Правильный ответ дали 27 % отвечавших.
    3. What class is not Comparable?

      • java.lang.String
      • java.util.TreeSet
      • java.io.File
      • java.lang.Enum

      Answer
      Этот, казалось бы, простой вопрос поставил в тупик многих, точнее — 76 % отвечавших. Догадайтесь сами, какой из ответов тут правильный и какой ответ был самым популярным — его выбрали 61 % игроков.
    4. What is the identical code?

      Object o = Math.min(-1, Double.MIN_VALUE)

      • Object o = -1
      • Object o = Double.MIN_VALUE
      • Object o = -1.0

      Answer
      Минимальное значение double уж точно меньше -1, что тут опять может быть не так? Разумеется, всё не так просто, иначе мы не спрашивали бы. Оказывается, Double.MIN_VALUE содержит не совсем то, что ожидается, а именно «constant holding the smallest positive nonzero value», согласно документации. Правильнее его было бы назвать Double.MIN_POSITIVE_VALUE. Double опять обвел вокруг пальца! Правильный ответ: Object o = -1.0, и так ответили всего 22 % игроков.
    5. What line is the result of calling this code?

      Long.toHexString(0x1_0000_0000L + 0xcafe_babe)

      • 1cafebabe
      • cafebabe
      • ffffffffcafebabe

      Answer
      Если вы выбрали второй ответ, то вы среди 22 % ответивших правильно. Этот вопрос взят из книги «Java Puzzlers: Traps, Pitfalls, and Corner Cases» за авторством Joshua Bloch и Neal Gafter. Если ответили неправильно, не расстраивайтесь, и бегом читать эту книгу!
    6. JDK 8 introduced support for annotations on method parameters. Is it possible to add annotation to the method parameter this?

      • It is impossible
      • Possible, but only in bytecode
      • Perhaps, by defining thisexplicitly the first parameter of the method

      Answer
      Когда в JDK 8 добавляли возможность ставить аннотации на параметры методов, параметр this не стали обделять. Именно для этой цели this теперь можно явно указывать в сигнатурах методов:

      classFoo {
          publicvoidtest(@Annotated Foo this) {}
      }

      Хотя можно спорить о ее практической пользе, теперь это фича языка. До правильного ответа догадалось 32 % игроков.
    7. In JDK 8, a parameter concurrencyLevelin the constructor ConcurrentHashMapaffects:

      • Available read / write concurrency
      • Initial table size
      • On both parameters

      Answer
      Если вы выбрали вариант 2, то вы среди 15 %, кто дал правильный ответ на этот самый сложный вопрос игры. Всё дело в том, что в JDK 8 отказались от сегментов в ConcurrentHashMap, поэтому concurrencyLevel потерял свой прежний смысл. Он влияет только на начальный размер таблицы, да и то лишь ограничивает снизу значение initialCapacity.

    Due to numerous requests, we have posted the game on our website, where you can play right now !

    Also popular now: