📜 ⬆️ ⬇️

Programming without using conditional constructions

One friend told me that any program can be written without using if / else. Of course, I was immediately indignant and formulated to him (and at the same time to himself) the simplest task: to write a program that would be happy if it were given, for example, the word “cookie” to the input, and grieved otherwise; but you cannot use any constructions that change the direction of the program - that is, it must be strictly linear. Solution under the cut.

Pseudo-correct solutions

Java. , , . , , , . , String "cake"? Java .

, if' , - , . Hashtable.

:
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    String input = in.readLine();
    HashMap<Boolean,String> map = new HashMap<Boolean,String>();
    map.put(true, "Yummy!!!");
    map.put(false, "The cake is a lie :(");
    System.out.println(map.get(input.equals("cake")));

. , equals(), ? if/else ! , . . HashMap :
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    String input = in.readLine();
    Object yeah = new Object();
    HashMap map = new HashMap();
    map.put("cake", yeah);
    map.put(yeah, "Yummy, thanks!!!");
    map.put(null, "You are still lying to me!");
    System.out.println(map.get(map.get(input)));

, - , . ? , - . - . ?


, , , , — . ? ! if x then a else b x*a+(1-x)*b (, , 1, — 0). , 1 «cake» ( «cookie», «candy»), 0 . :
    int x = isCake(input);
    System.out.print((char)(x*'Y'+(1-x)*'N'));
    System.out.print((char)(x*'e'+(1-x)*'o'));
    System.out.print((char)(x*'s'));

, , . : (, ) , "cake\0". :
import java.io.*;

class CakeEater {
    static public void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        String input = in.readLine().concat("\0\0\0\0\0");
        int x = input.charAt(0)^'c';
        x |= input.charAt(1)^'a';
        x |= input.charAt(2)^'k';
        x |= input.charAt(3)^'e';
        x |= input.charAt(4);
        //   ,      1
        x = x | (x>>1) | (x>>2) | (x>>3) | (x>>4) | (x>>5) | (x>>6) | (x>>7) | (x>>8)
          | (x>>9) | (x>>10) | (x>>11) | (x>>12) | (x>>13) | (x>>14) | (x>>15);
        x = 1 - (x&1);
        System.out.print((char)(x*'Y'+(1-x)*'N'));
        System.out.print((char)(x*'e'+(1-x)*'o'));
        System.out.println((char)(x*'s'));
    }
}

: if/else , . , , , !

')

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


All Articles