📜 ⬆️ ⬇️

Single line calculator, art or vice?

Introductory


As is often the case when you are looking for a job, you pass one interview after another. Somewhere you choose, somewhere you. And probably, in the life of each of us there were interesting interviews, which you can gladly tell the public. I want to tell about one such story, where there is a place for emotions, panic, stream of thinking and inspiration. The article will focus on the internal experiences of the applicant, his confrontation with the interviewer, an interesting and brainwashing code in java, as well as the answer to the question: "Is the unusual code an art or a vice?" . You can plunge into your past and stretch your brains. If intrigued, then let's go.

The story of one person X


Back in 2008, a guy named X was looking for a job as a programmer. He had development experience, but not the same when he was torn off with his hands and feet. Therefore, he was distracted by all vacancies and answered all calls. And so it happened, X'a was invited to a serious company, where he had to pass only 2 interviews. One, as usual, with the girls from the personnel department, which, incidentally, did not become a hindrance, and the second - technical, exciting, anxious, unknown heart. The time has come X - interview. After the accepted handshake, a young man, named Y, an interviewer, a true programmer - a haircut to the side, a jerk put up, said that he was very busy right now. Well, once you have come, so be it, I will give you a pretty laptop and a puzzle - 'Write me a calculator. A simple calculator, when the program receives an expression consisting of 2 numbers, separated by the sign '+', '-', '*', '/', which must be calculated. You have an hour and a half. ” . And at that moment, something important happened - "Surprise me!" he added haughtily and left. At this second, man X covered a barrage of negative emotions - “Aha, schA. I will reach AKS 74, 5.45 and make you dance lezginka and hum Nadezhda Babkina - 'Is it my fault?' It will be amazing, dance as much as you like ... ' .

But emotions and emotions to give way to common sense. Rudeness is not an argument. The process has begun, thoughts have begun to seethe: but calc.exe may cause, and OOP may be screwed, or an awesome expression parser may be done. But no. Just an hour and a half. Can just do the task? How to proceed? The path was chosen - I will do as I can and a semicolon. Oh, and staging, oh, and interview. After about 20 minutes, a smile appeared on X'a's face. It dawned on him! And what if to write a calculator, the code of which would contain only 1 line, i.e. only 1 semicolon, not counting packages and imports? No sooner said than done. By the end of the second hour the decision was ready. 2 hours. Tired and a little confused Y came. "Well, how?" He asked X'a. 'Done!' - answered that.

Interesting and brainwave java code


So, dear reader, the time has come and you and I will try to solve the set, human X, problem. Here is a more precise statement of the assignment: You need to write a calculator for a simple expression, which would contain exactly 1 line of code and know how to add, subtract, multiply and divide 2 numbers. 1 line - means exactly 1 semicolon, excluding the package and import declaration. Only classes from jdk can be used for the solution. Examples of the expression "7 + 4", "-12.0 * 14.12" without brackets and any tricks. The solution must be issued in 1 static method, which displays the result in the console. Do not touch the main function - it will call functions to check the results. With restrictions, perhaps all. Any tricks are welcome. Originality too.
')

Options


In java 7, this is done quite simply and there is no need to be a genius. We sacrifice a little accuracy and security. Class will lead completely. If you want to think to press the spoiler is not necessary.

Option number one
package com.calculator; import javax.script.ScriptEngineManager; import java.io.PrintStream; public class Calculator1 { /** *  ,    .   ? * @param expression    */ private static void calc(String expression) { try { System.out.println(new ScriptEngineManager().getEngineByName("JavaScript").eval(expression)); } catch (Exception ex) { try (PrintStream stream = (System.out.append("Nan"))) {} } } public static void main(String[] args) { calc("+5 + -12"); calc("+5 * -12"); calc("+5 - -12"); calc("+5 / -12"); } } 


In 2008, such a trick would not have passed, so person X solved this problem in his own way. Note: the code is still adapted for java 7, forgive.

Option number two
 package com.calculator; import java.io.PrintStream; import java.math.BigDecimal; import java.math.MathContext; import java.math.RoundingMode; import java.util.Arrays; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Calculator2 { /** * ,          * @param expression    * @param args ,     */ private static void calc(String expression, Object ... args) { try { // 1.   System.out.println( // 2.      BigDecimal.class.getMethod( Arrays.asList("multiply", "add", "subtract", "divide").get( ((args = new Matcher[] { Pattern.compile( // 3.    . ,     <b>  </b>,      . "[+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eE][+-]?\\d+)?\\s*([+-\\\\*/])\\s*[+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eE][+-]?\\d+)?$") .matcher(expression)})) != null && ((Matcher) args[0]).find() ? // 4.     42: '*', 43: '+', 45: '-', 47: '/' -     0, 1, 2, 3 ((int) ((Matcher) args[0]).group(1).charAt(0) - 41) / 2 : -1), // 5.   BigDecimal.class, MathContext.class).invoke( // 6.    new BigDecimal(((args = new Matcher[] { Pattern.compile("([+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eE][+-]?\\d+)?)").matcher(expression)})) != null && ((Matcher) args[0]).find() ? ((Matcher) args[0]).group(0) : ""), // 7.    new BigDecimal(((args = new Matcher[] { Pattern.compile("[+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eE][+-]?\\d+)?\\s*[+-\\\\*/]\\s*([+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eE][+-]?\\d+)?)$") .matcher(expression)})) != null && ((Matcher) args[0]) .find() ? ((Matcher) args[0]).group(1) : ""), new MathContext(10, RoundingMode.HALF_EVEN))); } catch (Exception ex) { /**        */ try (PrintStream stream = (System.out.append("Nan"))) {} } } public static void main(String[] args) { calc("+5 + -12"); calc("+5 * -12"); calc("+5 - -12"); calc("+5 / -12"); } } 


As in the well-known song: Well, what to say, what to say, is arranged so java, they want to know, they want to know, they want to know what will happen ...

But we admit to ourselves that this code is too bulky and has repetitions. And what if we strengthen the restriction and demand not to use the ternary operator at all? Not immediately, but the solution was found.

Option number three
 package com.calculator; import java.io.PrintStream; import java.math.BigDecimal; import java.math.MathContext; import java.math.RoundingMode; import java.util.Arrays; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Calculator3 { /** * ,   ,    . * @param expression    * @param args ,     */ private static void calc(String expression, Object ... args) { try { // 1.   System.out.println( // 2.      BigDecimal.class.getMethod( Arrays.asList("multiply", "add", "subtract", "divide").get( // 3.      args     (Integer) (args = new Object[] {args = new Object[] { Pattern.compile("([+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eE][+-]?\\d+)?)\\s*([+-\\\\*/])\\s*([+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eE][+-]?\\d+)?)$"). matcher(expression)}, args[0], ((Matcher) args[0]).find(), ((Matcher) args[0]).group(1), ((int) ((Matcher) args[0]).group(2).charAt(0) -41) / 2, ((Matcher) args[0]).group(3)})[4]), // 4.   BigDecimal.class, MathContext.class).invoke( // 5.    new BigDecimal(args[3].toString()), // 6.    new BigDecimal(args[5].toString()), new MathContext(10, RoundingMode.HALF_EVEN))); } catch (Exception ex) { /**        */ try (PrintStream stream = (System.out.append("Nan"))) {} } } public static void main(String[] args) { calc("+5 + -12"); calc("+5 * -12"); calc("+5 - -12"); calc("+5 / -12"); } } 


So much shorter and without repetitions, but the brain will explode. I think there are a couple more solutions.

Interestingly, how do the guys think that they put their thoughts on scala or kotlin or c # or ... if these restrictions, albeit with assumptions, are appropriate?

Conclusion


Thank you, dear reader, for your attention and patience. As promised, I give my answer to the question: "Is an unusual code an art or a vice?" . I would say this: "Through the eyes of the experimenter - art, through the eyes of production - a vice ." But no matter how this code is called, remember, you can try. Separately, I want to apologize to the residents of habrahabr for the chosen presentation style, if something goes wrong. This is an experimental approach on my part, thanks for understanding.

Source: https://habr.com/ru/post/320830/


All Articles