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!
- 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». - 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 % отвечавших. - What class is not
Comparable
?- java.lang.String
- java.util.TreeSet
- java.io.File
- java.lang.Enum
AnswerЭтот, казалось бы, простой вопрос поставил в тупик многих, точнее — 76 % отвечавших. Догадайтесь сами, какой из ответов тут правильный и какой ответ был самым популярным — его выбрали 61 % игроков. - 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 % игроков. - 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. Если ответили неправильно, не расстраивайтесь, и бегом читать эту книгу! - 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
this
explicitly the first parameter of the method
AnswerКогда в JDK 8 добавляли возможность ставить аннотации на параметры методов, параметрthis
не стали обделять. Именно для этой целиthis
теперь можно явно указывать в сигнатурах методов:classFoo { publicvoidtest(@Annotated Foo this) {} }
Хотя можно спорить о ее практической пользе, теперь это фича языка. До правильного ответа догадалось 32 % игроков. - In JDK 8, a parameter
concurrencyLevel
in the constructorConcurrentHashMap
affects:- 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 !