Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Do While False

At work today one of my colleagues was describing the use-case for do while(false). The person he was talking to thought that this was silly and that simple if statements would be much better. We then proceeded to waste half of our day discussing the best manner to write something equivalent to:

do
{
   //some code that should always execute...

   if ( condition )
   {
      //do some stuff
      break;
   }

   //some code that should execute if condition is not true

   if ( condition2 )
   {
       //do some more stuff
       break;
   }

   //further code that should not execute if condition or condition2 are true

}
while(false);

This is an idiom which is found in c quite often. Your program should produce the same output as the below pseudo-code depending on the conditions.

do
{
   result += "A";

   if ( C1)
   {
      result += "B";
      break;
   }

   result += "C"

   if ( C2 )
   {
       result += "D";
       break;
   }

   result += "E";

}
while(false);

print(result);

Therefore the input could be:

1. C1 = true, C2 = true
2. C1 = true, C2 = false
3. C1 = false, C2 = true
4. C1 = false, C2 = false

and the output should be:

1. "AB"
2. "AB"
3. "ACD"
4. "ACE"

This is code-golf so answers will be judged on bytes. Standard loopholes are banned.

Yes this is a simple one, but hopefully we will see some creative answers, I'm hoping the simplicity will encourage people to use languages they are less confident with.

share|improve this question
    
Does the output have to be uppercase, or is lowercase also permitted? – Adnan Feb 18 at 19:56
    
Are the " marks required? Also, is a trailing space ok? – Tom Carpenter Feb 20 at 3:35
5  
As an aside for the debate with your coworker, it seems to me you could accomplish the same thing using a method with return result in place of break. Then you get the bonuses of re-usability and simplifying the calling code, too. But perhaps I'm missing something. – jpmc26 Feb 21 at 7:18
2  
I didn't know this was an idiom in C... – Mehrdad Feb 21 at 10:45
3  
@Mehrdad some folks do this instead of goto because using goto is bad form :) – Seth Feb 21 at 22:53

50 Answers 50

Python 3, 31

Saved 1 byte thanks to xnor.

Only one byte away from ES6. :/ Stupid Python and its long anonymous function syntax.

Hooray for one liners!

lambda x,y:x*"AB"or"AC"+"ED"[y]

Test cases:

assert f(1, 1) == "AB"
assert f(1, 0) == "AB"
assert f(0, 1) == "ACD"
assert f(0, 0) == "ACE"
share|improve this answer
7  
If you re-order x*"AB", you can save the space after. – xnor Feb 18 at 22:26
2  
Sorry, your long, anonymous function syntax will be the death of python :P – Cᴏɴᴏʀ O'Bʀɪᴇɴ Feb 19 at 17:36
5  
@CᴏɴᴏʀO'Bʀɪᴇɴ I knew something had to be holding Python back. I'll submit a PEP ASAP. – Morgan Thrapp Feb 19 at 17:36
2  
You do that, and I'll order snake traps – Cᴏɴᴏʀ O'Bʀɪᴇɴ Feb 19 at 17:38
7  
A PEP to make λ a synonym of lambda would be great :) – Robert Grant Feb 19 at 19:26

JavaScript ES6, 30 26 25 bytes

A simple anonymous function taking two inputs. Assign to a variable to call. Update: Let's jump on the index bandwagon. It saves 4 bytes. I have secured my lead over Python. Saved a byte by currying the function; call like (...)(a)(b). Thanks Patrick Roberts!

a=>b=>a?"AB":"AC"+"ED"[b]

Old, original version, 30 bytes (included to not melt into the python answer (;):

(a,b)=>"A"+(a?"B":b?"CD":"CE")
share|improve this answer
    
This isn't that clever... – theonlygusti Feb 18 at 21:39
13  
@theonlygusti This a code-golf, not a popularity contest. Also, why waste bytes being clever if there is a more concise solution? – Cᴏɴᴏʀ O'Bʀɪᴇɴ Feb 18 at 21:41
    
I like your choice of nose :b? – J Atkin Feb 19 at 15:48
    
@JAtkin Indeed! – Cᴏɴᴏʀ O'Bʀɪᴇɴ Feb 19 at 17:05
4  
You can save a byte with currying – Patrick Roberts Feb 19 at 21:56

C preprocessor macro, 35

#define f(a,b) a?"AB":b?"ACD":"ACE"

Ideone.

share|improve this answer

Haskell, 28 bytes

x#y|x="AB"|y="ACD"|1<2="ACE"

Usage example: False # True -> "ACD".

Using the input values directly as guards.

share|improve this answer

MATL, 15 17 bytes

?'AB'}'AC'69i-h

Inputs are 0 or 1 on separate lines. Alternatively, 0 can be replaced by F (MATL's false) and 1 by T (MATL's true).

Try it online!

?           % if C1 (implicit input)
  'AB'      %   push 'AB'
}           % else
  'AC'      %   push 'AC'
  69        %   push 69 ('E')
  i-        %   subtract input. If 1 gives 'D', if 0 leaves 'E'
  h         %   concatenate horizontally
            % end if (implicit)
share|improve this answer

Brainfuck, 65 bytes

This assumes that C1 and C2 are input as raw 0 or 1 bytes. e.g.

echo -en '\x00\x01' | bf foo.bf

Golfed:

++++++++[>++++++++<-]>+.+>+>,[<-<.>>-]<[<+.+>>,[<-<.>>-]<[<+.>-]]

Ungolfed:

                                      Tape
                                      _0
++++++++[>++++++++<-]>+.+  print A    0 _B
>+>,                       read C1    0 B 1 _0  or  0 B 1 _1
[<-<.>>-]<                 print B    0 B _0 0  or  0 B _1 0
[<+.+>>                    print C    0 D 1 _0
    ,                      read C2    0 D 1 _0  or  0 D 1 _1
    [<-<.>>-]<             print D    0 D _0 0  or  0 D _1 0
    [<+.>-]                print E    0 D _0    or  0 E _0
]

I believe it worth noting that this solution is in fact based on breaking out of while loops.

share|improve this answer

GNU Sed, 21

/^1/cAB
/1$/cACD
cACE

Ideone.

share|improve this answer

NTFJ, 110 bytes

##~~~~~#@|########@|~#~~~~~#@*(~#~~~~#~@*########@^)~#~~~~##@*##~~~~~#@|########@|(~#~~~#~~@*):~||(~#~~~#~#@*)

More readable:

##~~~~~#@|########@|~#~~~~~#@*(~#~~~~#~@*########@^)~#~~~~##@*##~~~~~#@|########@|(~#~~~#~~@*
):~||(~#~~~#~#@*)

That was certainly entertaining. Try it out here, using two characters (0 or 1) as input.

Using ETHProduction's method for converting to 0, 1 (characters) to bits, this becomes simpler.

##~~~~~#@|########@|

This is the said method. Pushing 193 (##~~~~~#@), NANDing it (|) with the top input value (in this case, the first char code, a 48 or 49). This yields 254 for 1 and 255 for 0. NANDing it with 255 (########@) yields a 0 or 1 bit according to the input.

~#~~~~~#@*

This prints an A, since all input begins with A. * pops the A when printing, so the stack is unchanged from its previous state.

(~#~~~~#~@*########@^)

Case 1: the first bit is 1, and ( activates the code inside. ~#~~~~#~@* prints B, and ########@^ pushes 255 and jumps to that position in the code. This being the end of the program, it terminates.

Case 2: the first bit is 0. ( skips to ) and the code continues.

~#~~~~##@*

This prints a C, because that's the next character.

##~~~~~#@|########@|

This converts our second input to a bit.

(~#~~~#~~@*)

If our second bit is a 1, we proceed to print an E.

:~||

This is the NAND representation of the Boolean negation of our bit: A NAND (0 NAND A) = NOT A.

(~#~~~#~#@*)

This now activates if the bit was a 0, and prints E.

share|improve this answer

Pyth, 16 bytes

+\A?Q\B+\C?E\D\E

Test suite

Ternaries!

Explanation:

+\A              Start with an A
?Q\B             If the first variable is true, add a B and break.
+\C              Otherwise, add a C and
?E\D             If the second variable is true, add a D and break.
\E               Otherwise, add a E and finish.

Input on two consecutive lines.

share|improve this answer
3  
Oh pythmaster, make known to us the ways of this program. ;) – Cᴏɴᴏʀ O'Bʀɪᴇɴ Feb 18 at 18:41

Pyth, 13 chars, 19 bytes

.HC@"૎્««"iQ2

Takes input in form [a,b]

Explanation

               - autoassign Q = eval(input())
           iQ2 -    from_base(Q, 2) - convert to an int
   @"૎્««"    -   "૎્««"[^]
  C            -  ord(^)
.H             - hex(^)

Try it here

Or use a test suite

share|improve this answer
2  
At least in UTF-8, this weighs 19 bytes. – Dennis Feb 19 at 4:50
1  
bytesizematters uses a completely made up way of counting bytes, which does not (and cannot) correspond to an actual encoding. It counts the square thingies as 2 bytes each (3 bytes in UTF-8) and « as 1 byte each (2 bytes in UTF-8). Both wc and this agree that it's 19 bytes. – Dennis Feb 19 at 15:47

CJam, 15 16 17 bytes

'Ali'B'C'Eli-+?

Try it online!

One byte off thanks to @randomra, and one byte off thanks to @Dennis

Explanation:

'A                  e# push "A"
  li                e# read first input as an integer
    'B              e# push "B" 
      'C            e# push "C"
        'E          e# push "E"
          li-       e# leave "E" or change to "D" according to second input
             +      e# concatenate "C" with "E" or "D"
              ?     e# select "B" or "C..." according to first input

Old version (16 bytes):

'Ali'B{'C'Eli-}?

Explanation:

'A                  e# push character "A"
               ?    e# if-then-else
  li                e# read first input as an integer. Condition for if
    'B              e# push character "B" if first input is true
      {       }     e# execute this if first input is false
       'C           e# push character "C"
         'E         e# push character "E"
           li       e# read second input as an integer
             -      e# subtract: transform "E" to "D" if second input is true
                    e# implicitly display stack contents
share|improve this answer
5  
Our good friends Ali and Eli! – Cᴏɴᴏʀ O'Bʀɪᴇɴ Feb 19 at 17:39

C, 76 bytes

I renamed c1 to c, c2 to C and result to r. C programmers go to extremes to avoid goto. If you ever have a problum with absurd syntax in C, it is most likely to be because you did not use goto.

char r[4]="A";if(c){r[1]=66;goto e;}r[1]=67;if(C){r[2]=68;goto e;}r[2]=69;e:

Ungolfed

char r[4] = "A";
if(c1){
    r[1] = 'B';
    goto end;
}
r[1] = 'C';
if(c2){
    r[2] = 'D';
    goto end;
}
r[2] = 'E';
end:
share|improve this answer
    
Can you start with char r[4]="A";? My C is rusty. – LarsH Feb 19 at 11:17
    
Isn't that a really ridiculous way of declaring a String literal? – Tamoghna Chowdhury Feb 20 at 11:51
    
@TamoghnaChowdhury Sort of. String literals aren't writable. It's an array which is then initialized by the string literal "A". Since "A" only sets the first two bytes, the remainder is initialized per the rules for objects of static duration (so 0 in this case). [C99 6.7.8/22] – Ray Feb 22 at 0:27
1  
You can save 22 bytes by changing the initialization list to "AC" and replacing everything from r[1]=67 to r[2]=69; with r[2]=c2?68:69; – Ray Feb 22 at 0:43

Mathematica, 35 30 bytes

If[#,"AB",If[#2,"ACD","ACE"]]&

Very simple. Anonymous function.

share|improve this answer

Retina, 22 bytes

1.+
AB
.+1
ACD
.+0
ACE

Try it Online

share|improve this answer
1  
retina.tryitonline.net/…. Prefix the ^ with m`, to make it work for multi-line input, which is not necessary for the question, but makes testing easier. – Digital Trauma Feb 18 at 20:14
    
I think you can save 3 bytes by removing the space between the two inputs. – CalculatorFeline Mar 22 at 15:12

JavaScript, 38 bytes

Use no-delimiter 0 or 1 instead of false/true

_=>"ACE ACD AB AB".split` `[+('0b'+_)]
share|improve this answer
1  
You can use split` ` instead of split(" ") – andlrc Feb 18 at 20:06
    
You can also use +('0b'+prompt()) instead of parseInt(prompt(),2) – andlrc Feb 18 at 20:08

Caché ObjectScript, 27 bytes

"A"_$s(x:"B",y:"CD",1:"CE")
share|improve this answer

C, 41 bytes

I'm not sure if the question requires a program, a function or a code snippet.
Here's a function.

f(a,b){a=a?16961:4473665|b<<16;puts(&a);}

It gets the input in two parameters, which must be 0 or 1 (well, b must), and prints to stdout.

Sets a to one of 0x4241, 0x454341 or 0x444341. When printed as a string, on a little-endian system, gives the required output.

share|improve this answer

Pyth, 21 bytes

@c"ACE ACD AB AB"diz2

Try it here!

Input is taken as 0 or 1 instead of true/false while C1 comes first.

Explanation

Just using the fact that there are only 4 possible results. Works by interpreting the input as binary, converting it to base 10 and using this to choose the right result from the lookup string.

@c"ACE ACD AB AB"diz2   # z= input

                  iz2   # Convert binary input to base 10
 c"ACE ACD AB AB"d      # Split string at spaces
@                       # Get the element at the index
share|improve this answer

Y, 20 bytes

In the event that the first input is one, only one input is taken. I assume that this behaviour is allowed. Try it here!

'B'AjhMr$'C'E@j-#rCp

Ungolfed:

'B'A jh M
   r$ 'C 'E@ j - # r
 C p

Explained:

'B'A

This pushes the characters B then A to the stack.

jh M

This takes one input, increments it, pops it and moves over that number of sections.

Case 1: j1 = 0. This is the more interesting one. r$ reverses the stack and pops a value, 'C'E pushes characters C and E. @ converts E to its numeric counterpart, subtracts the second input from it, and reconverts it to a character. r un-reverses the stack. Then, the program sees the C-link and moves to the next link p, and prints the stack.

Case 2: the program moves to the last link p, which merely prints the entire stack.

share|improve this answer

PowerShell, 40 bytes

param($x,$y)(("ACE","ACD")[$y],"AB")[$x]

Nested arrays indexed by input. In PowerShell, $true / 1 and $false / 0 are practically equivalent (thanks to very loose typecasting), so that indexes nicely into a two-element array. This is really as close to a ternary as PowerShell gets, and I've used it plenty of times in golfing.

Examples

PS C:\Tools\Scripts\golfing> .\do-while-false.ps1 1 1
AB

PS C:\Tools\Scripts\golfing> .\do-while-false.ps1 1 0
AB

PS C:\Tools\Scripts\golfing> .\do-while-false.ps1 0 1
ACD

PS C:\Tools\Scripts\golfing> .\do-while-false.ps1 0 0
ACE
share|improve this answer

K, 37 bytes

{?"ABCDE"@0,x,(1*x),(2*~x),(~x)*3+~y}
share|improve this answer

Vitsy, 26 bytes

Expects inputs as 1s or 0s through STDIN with a newline separating.

W([1m;]'DCA'W(Zr1+rZ
'BA'Z

I actually discovered a serious problem with if statements during this challenge. D: This is posted with the broken version, but it works just fine. (I'll update this after I fix the problem) Please note that I have updated Vitsy with a fix of if/ifnot. This change does not grant me any advantage, only clarification.

Explanation:

W([1m;]'DCA'W(Zr1+rZ
W                      Get one line from STDIN (evaluate it, if possible)
 ([1m;]                If not zero, go to the first index of lines of code (next line)
                       and then end execution.
       'DCA'           Push character literals "ACD" to the stack.
            W          Get another (the second) line from STDIN.
             (         If not zero, 
do the next instruction.
              Z        Output all of the stack.
               r1+r    Reverse the stack, add one (will error out on input 0, 1), reverse.
                   Z   Output everything in the stack.

'BA'Z
'BA'                   Push character literals "AB" to the stack.
    Z                  Output everything in the stack.

Try it Online!

share|improve this answer

beeswax, 26 bytes

Interpreting 0 as false, 1 as true.

E`<
D`d"`C`~<
_T~T~`A`"b`B

Output:

julia> beeswax("codegolfdowhile.bswx",0,0.0,Int(20000))
i1
i1
AB
Program finished!

julia> beeswax("codegolfdowhile.bswx",0,0.0,Int(20000))
i1
i0
AB
Program finished!

julia> beeswax("codegolfdowhile.bswx",0,0.0,Int(20000))
i0
i1
ACD
Program finished!

julia> beeswax("codegolfdowhile.bswx",0,0.0,Int(20000))
i0
i0
ACE
Program finished!

Clone my beeswax interpreter from my Github repository.

share|improve this answer
    
I'm pretty sure you don't need the quotes. – undergroundmonorail Feb 20 at 4:38
    
@undergroundmonorail: Okay, I’ll update my solution. Thanks. – M L Feb 20 at 5:49

ArnoldC, 423 bytes

IT'S SHOWTIME
HEY CHRISTMAS TREE a
YOU SET US UP 0
HEY CHRISTMAS TREE b
YOU SET US UP 0
BECAUSE I'M GOING TO SAY PLEASE a
BECAUSE I'M GOING TO SAY PLEASE b
TALK TO THE HAND "ABD"
BULLSHIT
TALK TO THE HAND "ABE"
YOU HAVE NO RESPECT FOR LOGIC
BULLSHIT
BECAUSE I'M GOING TO SAY PLEASE b
TALK TO THE HAND "ACD"
BULLSHIT
TALK TO THE HAND "ACE"
YOU HAVE NO RESPECT FOR LOGIC
YOU HAVE NO RESPECT FOR LOGIC
YOU HAVE BEEN TERMINATED

Since ArnoldC doesn't seem to have formal input, just change the first 2 YOU SET US UP values to either 0 or 1 instead.

Explanation

This is just a whole bunch of conditional statements which account for all the possible outputs. Why, you may ask? Well, ArnoldC doesn't really have string comprehension. It can't even concatenate strings! As a result, we have to resort to the more... inefficient... method.

share|improve this answer

Java, 28 bytes

Same boilerplate as a lot of the answers. type is BiFunction<Boolean,Boolean, String>.

(c,d)->c?"AB":d?"ACD":"ACE"
share|improve this answer

Perl, 23 bytes

say<>>0?AB:<>>0?ACD:ACE

Requires the -E|-M5.010 flag and takes input as 1 and 0:

$ perl -E'say<>>0?AB:<>>0?ACD:ACE' <<< $'0\n0'
ACE
$ perl -E'say<>>0?AB:<>>0?ACD:ACE' <<< $'0\n1'
ACD
$ perl -E'say<>>0?AB:<>>0?ACD:ACE' <<< $'1\n0'
AB

Alternative solution that requires -p and is 22 + 1 = 23 bytes:

$_=/^1/?AB:/1/?ACD:ACE
perl -pe'$_=/^1/?AB:/1/?ACD:ACE' <<< '0 1'
share|improve this answer
    
say-<>?AB:-<>?ACD:ACE is two bytes shorter. – nwellnhof Feb 19 at 14:45

05AB1E, 23 20 bytes

Code:

Ii"AB"?q}"AC"?69I-ç?

Try it online!

share|improve this answer

Japt, 19 bytes

"A{U?'B:'C+(V?'D:'E

Test it online!

Fun fact: This would be 16 bytes if it weren't for a bug:

"A{U?"B:C{V?"D:E
share|improve this answer
    
Bugs are the worst :| – Cᴏɴᴏʀ O'Bʀɪᴇɴ Feb 18 at 20:01
2  
@CᴏɴᴏʀO'Bʀɪᴇɴ Lemme see if I can dig out an older version that didn't have this bug. Then the 16 bytes would be legit. – ETHproductions Feb 18 at 20:02
1  
What's the bug? – CalculatorFeline Mar 22 at 15:13

Kotlin, 50 bytes

It is interesting what one can do with string templates.

{a,b->"A${if(a)"B" else "C${if(b)"D" else "E"}"}"}

Try Here

share|improve this answer
1  
Those quotations... shivers – Seeq Feb 19 at 23:55
    
Oh my god, the quotes actually match? ... – cat Feb 20 at 10:48

Mouse-2002, 23 bytes

??"A"["B"|"C"["D"|"E"]]

Switches on two inputs, which each should be either 0 for false or anything else for true.

Ungolfed, as a function:

#Y,?,?;

$Y 1% a: 2% b:
  "A"
  a [
    "B"
  |
    "C"
    b [
      "D"
    |
      "E"
    ]
  ]
$

Brackets just test if the top of the stack is true, and | is else.

This is a translation of @Cᴏɴᴏʀ O'Bʀɪᴇɴ's ES6 answer.

share|improve this answer
    
Feature-request: These mentions actual should show up in my inbox >-< – Cᴏɴᴏʀ O'Bʀɪᴇɴ Feb 19 at 17:41
    
@CᴏɴᴏʀO'Bʀɪᴇɴ I know, right? – cat Feb 19 at 17:47

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.