Ternary-if Converter

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP











up vote
5
down vote

favorite
1














In Java/.NET/C/JavaScript/etc. you can use ternary-ifs to shorten if-statements.



For example (in Java):



// there is a String `s` and an int `i`
if(i<0)s="Neg";else if(i>0)s="Pos";else s="Neut";


Can be shortened with a ternary-if to:



s=i<0?"Neg":i>0?"Pos":"Neut";


Challenge:



Input: A regular if-else (possible with nesting) that sets a single variable.



Output: The converted ternary-if.



Challenge rules:



  • You can assume all if-else cases are possible without brackets (so each if/else-if/else block has a single body).

  • You can assume there won't be any spaces, tabs, or new-lines, except for a single space after each else (including at else if).

  • You can assume the variable names used are always a single lowercase letter ([a-z]).

  • The values given to the variables can be one of:

    • Strings (without spaces/tabs/new-lines), which will be surrounded by double-quotes (i.e. "Test", "SomeString", "Example_string", etc.). You can assume the strings will never contain the substrings if or else, nor will it contain spaces, tabs, newlines, (escaped) double-quotes, or the character =. It can contain the characters ><();?:!&|, but will be in the printable ASCII range only (['!' (33), '~' (126)]).

    • Integers (i.e. 0, 123, -55, etc.)

    • Decimals (i.e. 0.0, 0.123, -55.55, etc.)


  • The values won't ever be mixed. So all variables assigned are integers, and not some are integers and some are strings.

  • The conditions within parenthesis can contain the following characters =<>!+-/*%&|, a-z, 0-9. You can assume there won't be any inner parenthesis, and you can also assume there won't be any (confusing) fields of more than one character used (like if(if<0)).

  • You can assume there won't be any short-cuts like i*=10 instead of i=i*10.

  • You won't have to handle dangling else cases, so all if can be paired up with an else. I.e. if(a)if(b)r=0;else r=1; isn't a possible input-case. if(a)if(b)r=0;else r=1;else r=2; or if(a&&b)r=0;else if(a&&!b)r=1;else r=-1; are however.

  • I/O is flexible. Input and Output can be a string, list of characters, read from STDIN, output to STDOUT, etc. Your call.

  • All ternaries will have a right associativity, as is the standard in most languages (but not in for example PHP).

General rules:



  • This is code-golf, so shortest answer in bytes wins.

    Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.


  • Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.


  • Default Loopholes are forbidden.

  • If possible, please add a link with a test for your code.

  • Also, please add an explanation if possible.

Test cases:



Input: if(i<0)s="Neg";else if(i>0)s="Pos";else s="Neut";
Output: s=i<0?"Neg":i>0?"Pos":"Neut";

Input: if(i%2<1)r=10;else r=20;
Output: r=i%2<1?10:20;

Input: if(n<10)if(m<0)i=0;else i=10;else if(m<0)i=-1;else i=1;
Output: i=n<10?m<0?0:10:m<0?-1:1;

Input: if(i==1)i=0.0;else i=0.25;
Output: i=i==1?0.0:0.25;

Input: if(!a)if(b)r=0;else r=1;else r=2;
Output: r=!a?b?0:1:2;

Input: if(a)if(b)r=0;else r=1;else if(c)r=2;else r=3;
Output: r=a?b?0:1:c?2:3;

Input: if(a&&b)r=0;else if(a&&!b)r=1;else r=-1;
Output: r=a&&b?0:a&&!b?1:-1;

Input: if(i[0]>0)if(j>0)if(q>0)r="q";else r="j";else r="i";else r="other";
Output: r=i[0]>0?j>0?q>0?"q":"j":"i":"other";

Input: if(i>0)r="i";else if(j>0)r="j";else if(q>0)r="q";else r="other";
Output: r=i>0?"i":j>0?"j":q>0?"q":"other";

Input: if(a>0)if(a<2)x="one";else if(a<3)x="two";else if(a<4)x="three";else x="other";else x="other";
Output: x=a>0?a<2?"one":a<3?"two":a<4?"three":"other":"other";









share|improve this question



























    up vote
    5
    down vote

    favorite
    1














    In Java/.NET/C/JavaScript/etc. you can use ternary-ifs to shorten if-statements.



    For example (in Java):



    // there is a String `s` and an int `i`
    if(i<0)s="Neg";else if(i>0)s="Pos";else s="Neut";


    Can be shortened with a ternary-if to:



    s=i<0?"Neg":i>0?"Pos":"Neut";


    Challenge:



    Input: A regular if-else (possible with nesting) that sets a single variable.



    Output: The converted ternary-if.



    Challenge rules:



    • You can assume all if-else cases are possible without brackets (so each if/else-if/else block has a single body).

    • You can assume there won't be any spaces, tabs, or new-lines, except for a single space after each else (including at else if).

    • You can assume the variable names used are always a single lowercase letter ([a-z]).

    • The values given to the variables can be one of:

      • Strings (without spaces/tabs/new-lines), which will be surrounded by double-quotes (i.e. "Test", "SomeString", "Example_string", etc.). You can assume the strings will never contain the substrings if or else, nor will it contain spaces, tabs, newlines, (escaped) double-quotes, or the character =. It can contain the characters ><();?:!&|, but will be in the printable ASCII range only (['!' (33), '~' (126)]).

      • Integers (i.e. 0, 123, -55, etc.)

      • Decimals (i.e. 0.0, 0.123, -55.55, etc.)


    • The values won't ever be mixed. So all variables assigned are integers, and not some are integers and some are strings.

    • The conditions within parenthesis can contain the following characters =<>!+-/*%&|, a-z, 0-9. You can assume there won't be any inner parenthesis, and you can also assume there won't be any (confusing) fields of more than one character used (like if(if<0)).

    • You can assume there won't be any short-cuts like i*=10 instead of i=i*10.

    • You won't have to handle dangling else cases, so all if can be paired up with an else. I.e. if(a)if(b)r=0;else r=1; isn't a possible input-case. if(a)if(b)r=0;else r=1;else r=2; or if(a&&b)r=0;else if(a&&!b)r=1;else r=-1; are however.

    • I/O is flexible. Input and Output can be a string, list of characters, read from STDIN, output to STDOUT, etc. Your call.

    • All ternaries will have a right associativity, as is the standard in most languages (but not in for example PHP).

    General rules:



    • This is code-golf, so shortest answer in bytes wins.

      Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.


    • Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.


    • Default Loopholes are forbidden.

    • If possible, please add a link with a test for your code.

    • Also, please add an explanation if possible.

    Test cases:



    Input: if(i<0)s="Neg";else if(i>0)s="Pos";else s="Neut";
    Output: s=i<0?"Neg":i>0?"Pos":"Neut";

    Input: if(i%2<1)r=10;else r=20;
    Output: r=i%2<1?10:20;

    Input: if(n<10)if(m<0)i=0;else i=10;else if(m<0)i=-1;else i=1;
    Output: i=n<10?m<0?0:10:m<0?-1:1;

    Input: if(i==1)i=0.0;else i=0.25;
    Output: i=i==1?0.0:0.25;

    Input: if(!a)if(b)r=0;else r=1;else r=2;
    Output: r=!a?b?0:1:2;

    Input: if(a)if(b)r=0;else r=1;else if(c)r=2;else r=3;
    Output: r=a?b?0:1:c?2:3;

    Input: if(a&&b)r=0;else if(a&&!b)r=1;else r=-1;
    Output: r=a&&b?0:a&&!b?1:-1;

    Input: if(i[0]>0)if(j>0)if(q>0)r="q";else r="j";else r="i";else r="other";
    Output: r=i[0]>0?j>0?q>0?"q":"j":"i":"other";

    Input: if(i>0)r="i";else if(j>0)r="j";else if(q>0)r="q";else r="other";
    Output: r=i>0?"i":j>0?"j":q>0?"q":"other";

    Input: if(a>0)if(a<2)x="one";else if(a<3)x="two";else if(a<4)x="three";else x="other";else x="other";
    Output: x=a>0?a<2?"one":a<3?"two":a<4?"three":"other":"other";









    share|improve this question

























      up vote
      5
      down vote

      favorite
      1









      up vote
      5
      down vote

      favorite
      1






      1







      In Java/.NET/C/JavaScript/etc. you can use ternary-ifs to shorten if-statements.



      For example (in Java):



      // there is a String `s` and an int `i`
      if(i<0)s="Neg";else if(i>0)s="Pos";else s="Neut";


      Can be shortened with a ternary-if to:



      s=i<0?"Neg":i>0?"Pos":"Neut";


      Challenge:



      Input: A regular if-else (possible with nesting) that sets a single variable.



      Output: The converted ternary-if.



      Challenge rules:



      • You can assume all if-else cases are possible without brackets (so each if/else-if/else block has a single body).

      • You can assume there won't be any spaces, tabs, or new-lines, except for a single space after each else (including at else if).

      • You can assume the variable names used are always a single lowercase letter ([a-z]).

      • The values given to the variables can be one of:

        • Strings (without spaces/tabs/new-lines), which will be surrounded by double-quotes (i.e. "Test", "SomeString", "Example_string", etc.). You can assume the strings will never contain the substrings if or else, nor will it contain spaces, tabs, newlines, (escaped) double-quotes, or the character =. It can contain the characters ><();?:!&|, but will be in the printable ASCII range only (['!' (33), '~' (126)]).

        • Integers (i.e. 0, 123, -55, etc.)

        • Decimals (i.e. 0.0, 0.123, -55.55, etc.)


      • The values won't ever be mixed. So all variables assigned are integers, and not some are integers and some are strings.

      • The conditions within parenthesis can contain the following characters =<>!+-/*%&|, a-z, 0-9. You can assume there won't be any inner parenthesis, and you can also assume there won't be any (confusing) fields of more than one character used (like if(if<0)).

      • You can assume there won't be any short-cuts like i*=10 instead of i=i*10.

      • You won't have to handle dangling else cases, so all if can be paired up with an else. I.e. if(a)if(b)r=0;else r=1; isn't a possible input-case. if(a)if(b)r=0;else r=1;else r=2; or if(a&&b)r=0;else if(a&&!b)r=1;else r=-1; are however.

      • I/O is flexible. Input and Output can be a string, list of characters, read from STDIN, output to STDOUT, etc. Your call.

      • All ternaries will have a right associativity, as is the standard in most languages (but not in for example PHP).

      General rules:



      • This is code-golf, so shortest answer in bytes wins.

        Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.


      • Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.


      • Default Loopholes are forbidden.

      • If possible, please add a link with a test for your code.

      • Also, please add an explanation if possible.

      Test cases:



      Input: if(i<0)s="Neg";else if(i>0)s="Pos";else s="Neut";
      Output: s=i<0?"Neg":i>0?"Pos":"Neut";

      Input: if(i%2<1)r=10;else r=20;
      Output: r=i%2<1?10:20;

      Input: if(n<10)if(m<0)i=0;else i=10;else if(m<0)i=-1;else i=1;
      Output: i=n<10?m<0?0:10:m<0?-1:1;

      Input: if(i==1)i=0.0;else i=0.25;
      Output: i=i==1?0.0:0.25;

      Input: if(!a)if(b)r=0;else r=1;else r=2;
      Output: r=!a?b?0:1:2;

      Input: if(a)if(b)r=0;else r=1;else if(c)r=2;else r=3;
      Output: r=a?b?0:1:c?2:3;

      Input: if(a&&b)r=0;else if(a&&!b)r=1;else r=-1;
      Output: r=a&&b?0:a&&!b?1:-1;

      Input: if(i[0]>0)if(j>0)if(q>0)r="q";else r="j";else r="i";else r="other";
      Output: r=i[0]>0?j>0?q>0?"q":"j":"i":"other";

      Input: if(i>0)r="i";else if(j>0)r="j";else if(q>0)r="q";else r="other";
      Output: r=i>0?"i":j>0?"j":q>0?"q":"other";

      Input: if(a>0)if(a<2)x="one";else if(a<3)x="two";else if(a<4)x="three";else x="other";else x="other";
      Output: x=a>0?a<2?"one":a<3?"two":a<4?"three":"other":"other";









      share|improve this question

















      In Java/.NET/C/JavaScript/etc. you can use ternary-ifs to shorten if-statements.



      For example (in Java):



      // there is a String `s` and an int `i`
      if(i<0)s="Neg";else if(i>0)s="Pos";else s="Neut";


      Can be shortened with a ternary-if to:



      s=i<0?"Neg":i>0?"Pos":"Neut";


      Challenge:



      Input: A regular if-else (possible with nesting) that sets a single variable.



      Output: The converted ternary-if.



      Challenge rules:



      • You can assume all if-else cases are possible without brackets (so each if/else-if/else block has a single body).

      • You can assume there won't be any spaces, tabs, or new-lines, except for a single space after each else (including at else if).

      • You can assume the variable names used are always a single lowercase letter ([a-z]).

      • The values given to the variables can be one of:

        • Strings (without spaces/tabs/new-lines), which will be surrounded by double-quotes (i.e. "Test", "SomeString", "Example_string", etc.). You can assume the strings will never contain the substrings if or else, nor will it contain spaces, tabs, newlines, (escaped) double-quotes, or the character =. It can contain the characters ><();?:!&|, but will be in the printable ASCII range only (['!' (33), '~' (126)]).

        • Integers (i.e. 0, 123, -55, etc.)

        • Decimals (i.e. 0.0, 0.123, -55.55, etc.)


      • The values won't ever be mixed. So all variables assigned are integers, and not some are integers and some are strings.

      • The conditions within parenthesis can contain the following characters =<>!+-/*%&|, a-z, 0-9. You can assume there won't be any inner parenthesis, and you can also assume there won't be any (confusing) fields of more than one character used (like if(if<0)).

      • You can assume there won't be any short-cuts like i*=10 instead of i=i*10.

      • You won't have to handle dangling else cases, so all if can be paired up with an else. I.e. if(a)if(b)r=0;else r=1; isn't a possible input-case. if(a)if(b)r=0;else r=1;else r=2; or if(a&&b)r=0;else if(a&&!b)r=1;else r=-1; are however.

      • I/O is flexible. Input and Output can be a string, list of characters, read from STDIN, output to STDOUT, etc. Your call.

      • All ternaries will have a right associativity, as is the standard in most languages (but not in for example PHP).

      General rules:



      • This is code-golf, so shortest answer in bytes wins.

        Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.


      • Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.


      • Default Loopholes are forbidden.

      • If possible, please add a link with a test for your code.

      • Also, please add an explanation if possible.

      Test cases:



      Input: if(i<0)s="Neg";else if(i>0)s="Pos";else s="Neut";
      Output: s=i<0?"Neg":i>0?"Pos":"Neut";

      Input: if(i%2<1)r=10;else r=20;
      Output: r=i%2<1?10:20;

      Input: if(n<10)if(m<0)i=0;else i=10;else if(m<0)i=-1;else i=1;
      Output: i=n<10?m<0?0:10:m<0?-1:1;

      Input: if(i==1)i=0.0;else i=0.25;
      Output: i=i==1?0.0:0.25;

      Input: if(!a)if(b)r=0;else r=1;else r=2;
      Output: r=!a?b?0:1:2;

      Input: if(a)if(b)r=0;else r=1;else if(c)r=2;else r=3;
      Output: r=a?b?0:1:c?2:3;

      Input: if(a&&b)r=0;else if(a&&!b)r=1;else r=-1;
      Output: r=a&&b?0:a&&!b?1:-1;

      Input: if(i[0]>0)if(j>0)if(q>0)r="q";else r="j";else r="i";else r="other";
      Output: r=i[0]>0?j>0?q>0?"q":"j":"i":"other";

      Input: if(i>0)r="i";else if(j>0)r="j";else if(q>0)r="q";else r="other";
      Output: r=i>0?"i":j>0?"j":q>0?"q":"other";

      Input: if(a>0)if(a<2)x="one";else if(a<3)x="two";else if(a<4)x="three";else x="other";else x="other";
      Output: x=a>0?a<2?"one":a<3?"two":a<4?"three":"other":"other";






      code-golf string






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited 29 mins ago

























      asked 48 mins ago









      Kevin Cruijssen

      31.4k553169




      31.4k553169




















          2 Answers
          2






          active

          oldest

          votes

















          up vote
          1
          down vote














          Python 2, 113 bytes





          def f(s):v=s[s.find('=')-1]+'=';return v+s.replace(v,'').replace('if(','').replace(')','?').replace(';else ',':')


          Try it online!






          share|improve this answer



























            up vote
            1
            down vote














            Perl 5 -p, 50 bytes





            s/;else (.=)?/:/g;s/if.(.*?))(.=)?/1?/g;$_=$2.$_


            Try it online!






            share|improve this answer




















              Your Answer




              StackExchange.ifUsing("editor", function ()
              return StackExchange.using("mathjaxEditing", function ()
              StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
              StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
              );
              );
              , "mathjax-editing");

              StackExchange.ifUsing("editor", function ()
              StackExchange.using("externalEditor", function ()
              StackExchange.using("snippets", function ()
              StackExchange.snippets.init();
              );
              );
              , "code-snippets");

              StackExchange.ready(function()
              var channelOptions =
              tags: "".split(" "),
              id: "200"
              ;
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function()
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled)
              StackExchange.using("snippets", function()
              createEditor();
              );

              else
              createEditor();

              );

              function createEditor()
              StackExchange.prepareEditor(
              heartbeatType: 'answer',
              convertImagesToLinks: false,
              noModals: false,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: null,
              bindNavPrevention: true,
              postfix: "",
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              );



              );













               

              draft saved


              draft discarded


















              StackExchange.ready(
              function ()
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodegolf.stackexchange.com%2fquestions%2f173726%2fternary-if-converter%23new-answer', 'question_page');

              );

              Post as a guest






























              2 Answers
              2






              active

              oldest

              votes








              2 Answers
              2






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes








              up vote
              1
              down vote














              Python 2, 113 bytes





              def f(s):v=s[s.find('=')-1]+'=';return v+s.replace(v,'').replace('if(','').replace(')','?').replace(';else ',':')


              Try it online!






              share|improve this answer
























                up vote
                1
                down vote














                Python 2, 113 bytes





                def f(s):v=s[s.find('=')-1]+'=';return v+s.replace(v,'').replace('if(','').replace(')','?').replace(';else ',':')


                Try it online!






                share|improve this answer






















                  up vote
                  1
                  down vote










                  up vote
                  1
                  down vote










                  Python 2, 113 bytes





                  def f(s):v=s[s.find('=')-1]+'=';return v+s.replace(v,'').replace('if(','').replace(')','?').replace(';else ',':')


                  Try it online!






                  share|improve this answer













                  Python 2, 113 bytes





                  def f(s):v=s[s.find('=')-1]+'=';return v+s.replace(v,'').replace('if(','').replace(')','?').replace(';else ',':')


                  Try it online!







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered 27 mins ago









                  TFeld

                  12.2k2834




                  12.2k2834




















                      up vote
                      1
                      down vote














                      Perl 5 -p, 50 bytes





                      s/;else (.=)?/:/g;s/if.(.*?))(.=)?/1?/g;$_=$2.$_


                      Try it online!






                      share|improve this answer
























                        up vote
                        1
                        down vote














                        Perl 5 -p, 50 bytes





                        s/;else (.=)?/:/g;s/if.(.*?))(.=)?/1?/g;$_=$2.$_


                        Try it online!






                        share|improve this answer






















                          up vote
                          1
                          down vote










                          up vote
                          1
                          down vote










                          Perl 5 -p, 50 bytes





                          s/;else (.=)?/:/g;s/if.(.*?))(.=)?/1?/g;$_=$2.$_


                          Try it online!






                          share|improve this answer













                          Perl 5 -p, 50 bytes





                          s/;else (.=)?/:/g;s/if.(.*?))(.=)?/1?/g;$_=$2.$_


                          Try it online!







                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered 22 mins ago









                          nwellnhof

                          4,113816




                          4,113816



























                               

                              draft saved


                              draft discarded















































                               


                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function ()
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodegolf.stackexchange.com%2fquestions%2f173726%2fternary-if-converter%23new-answer', 'question_page');

                              );

                              Post as a guest













































































                              Comments

                              Popular posts from this blog

                              What does second last employer means? [closed]

                              List of Gilmore Girls characters

                              Confectionery