条件構造を使用しないプログラミング

ある友人は、if / elseを使用せずにプログラムを書くことができると言った。 もちろん、私はすぐに激怒し、彼(そして私自身)に最も単純なタスクを処方しました。 ただし、プログラムの方向を変更する構造は使用できません。つまり、厳密に線形でなければなりません。 解決策は未定です。

擬似正しい決定

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/J124878/


All Articles