问:
Count to 100 in Danish
Print all the numbers from 0-100 in the right order using the Danish way of counting

How they count

Like English, they have dedicated words for 0-20, 30, 40 and 100

Instead of saying twenty-one and twenty-two, they say one and twenty and two and twenty

Starting with fifty they say multiples of 10 as n*20

```<code>50 = half third times twenty = half way to the 3rd multiple of 20
60 = three times twenty
70 = half fourth times twenty
80 = four times twenty
90 = half fifth times twenty
</code>```

So for instance, 55 would be five and half third times twenty.

Expected output

```<code>zero
one
two
three
four
five
six
seven
eight
nine
ten
eleven
twelve
thirteen
fourteen
fifteen
sixteen
seventeen
eighteen
nineteen
twenty
one and twenty
two and twenty
three and twenty
four and twenty
five and twenty
six and twenty
seven and twenty
eight and twenty
nine and twenty
thirty
one and thirty
two and thirty
three and thirty
four and thirty
five and thirty
six and thirty
seven and thirty
eight and thirty
nine and thirty
forty
one and forty
two and forty
three and forty
four and forty
five and forty
six and forty
seven and forty
eight and forty
nine and forty
half third times twenty
one and half third times twenty
two and half third times twenty
three and half third times twenty
four and half third times twenty
five and half third times twenty
six and half third times twenty
seven and half third times twenty
eight and half third times twenty
nine and half third times twenty
three times twenty
one and three times twenty
two and three times twenty
three and three times twenty
four and three times twenty
five and three times twenty
six and three times twenty
seven and three times twenty
eight and three times twenty
nine and three times twenty
half fourth times twenty
one and half fourth times twenty
two and half fourth times twenty
three and half fourth times twenty
four and half fourth times twenty
five and half fourth times twenty
six and half fourth times twenty
seven and half fourth times twenty
eight and half fourth times twenty
nine and half fourth times twenty
four times twenty
one and four times twenty
two and four times twenty
three and four times twenty
four and four times twenty
five and four times twenty
six and four times twenty
seven and four times twenty
eight and four times twenty
nine and four times twenty
half fifth times twenty
one and half fifth times twenty
two and half fifth times twenty
three and half fifth times twenty
four and half fifth times twenty
five and half fifth times twenty
six and half fifth times twenty
seven and half fifth times twenty
eight and half fifth times twenty
nine and half fifth times twenty
one hundred
</code>```

Rules

You may use any separator to separate the numbers

Due to a typo in the original specification, you may use forth instead of fourth.

You may write a function or write to std-out

Standard loopholes apply

This is codegolf; shortest code in bytes win!

答:
PHP , 318 Bytes

for($i=~0;$i++<100;)echo([0=>zero,10=>ten,eleven,twelve,thirteen,15=>fifteen,18=>eighteen,100=>"one hundred"][$i]??["",one,two,three,four,five,six,seven,eight,nine][$i%10].($i>20&&$i%10?" and ":"").["",teen,twenty,thirty,forty,"half third",three,"half fourth",four,"half fifth"][$i/10].($i>49?" times twenty":"")).",";
```

<p>first pick with the Null coalescing operator ?? the exceptions.</p>

<p>this version with 314 Bytes is without the , at the end</p>

<pre class="lang-php prettyprint-override"><code>zero<?php for($i=0;$i++<100;)echo",".([10=>ten,eleven,twelve,thirteen,15=>fifteen,18=>eighteen][$i]??["",one,two,three,four,five,six,seven,eight,nine][$i%10].($i>20&&$i%10?" and ":"").["",teen,twenty,thirty,forty,"half third",three,"half fourth",four,"half fifth"][$i/10].($i>49?" times twenty":""));?>,one hundred
</code>```

Title: Count to 100 in Danish

Body:
PHP , 318 Bytes

for($i=~0;$i++<100;)echo([0=>zero,10=>ten,eleven,twelve,thirteen,15=>fifteen,18=>eighteen,100=>"one hundred"][$i]??["",one,two,three,four,five,six,seven,eight,nine][$i%10].($i>20&&$i%10?" and ":"").["",teen,twenty,thirty,forty,"half third",three,"half fourth",four,"half fifth"][$i/10].($i>49?" times twenty":"")).",";

first pick with the Null coalescing operator ?? the exceptions.

this version with 314 Bytes is without the , at the end

zero<?php for($i=0;$i++<100;)echo",".([10=>ten,eleven,twelve,thirteen,15=>fifteen,18=>eighteen][$i]??["",one,two,three,four,five,six,seven,eight,nine][$i%10].($i>20&&$i%10?" and ":"").["",teen,twenty,thirty,forty,"half third",three,"half fourth",four,"half fifth"][$i/10].($i>49?" times twenty":""));?>,one hundred


问:
Counting Goats to Sleep
Some people count sheep to get to sleep. Others count goats.

Write a program or function that takes in a positive integer N and outputs N-1 awake goats followed by one sleeping goat, as if someone was counting N goats and at the very last one they fell asleep.

Awake goats look like this:

```<code>      \
  ___/o>
-(___)"
 '' ''
</code>```

Sleeping goats look like this:

```<code>      \
  ___/->
,(___)"
 `` ``
</code>```

They are chained together with a single space between beard and tail of adjacent goats:

```<code>      \       \       \
  ___/o>  ___/o>  ___/->
-(___)" -(___)" ,(___)"
 '' ''   '' ''   `` ``
</code>```

The output is allowed to have trailing spaces and a single trailing newline.

The shortest code in bytes wins.

Examples

N = 1:

```<code>      \
  ___/->
,(___)"
 `` ``
</code>```

N = 2:

```<code>      \       \
  ___/o>  ___/->
-(___)" ,(___)"
 '' ''   `` ``
</code>```

N = 3:

```<code>      \       \       \
  ___/o>  ___/o>  ___/->
-(___)" -(___)" ,(___)"
 '' ''   '' ''   `` ``
</code>```

N = 4:

```<code>      \       \       \       \
  ___/o>  ___/o>  ___/o>  ___/->
-(___)" -(___)" -(___)" ,(___)"
 '' ''   '' ''   '' ''   `` ``
</code>```

Larger N should work just as well.

答:
Jelly, <s>62</s> 56 bytes

```<code>⁶ẋ6;“\   ___/o>-(___)"  '' ''  ”s8
¢“-,o-'`”yÐ€
’1£ẋ€ż¢Y
</code>```

Test it at TryItOnline

How?

```<code>⁶ẋ6;“\   ___/o>-(___)"  '' ''  ”s8 - Link 1: make a goat, niladic
⁶ẋ6                                - space character, ⁶, repeated 6 times
    “\   ___/o>-(___)"  '' ''  ”   - rest of the awake goat text
   ;                               - concatenate
                                s8 - split into length 8 parts

¢“-,o-'`”yÐ€ - Link 2: put a goat to sleep, niladic
¢            - last link (make a goat)
 “-,o-'`”    - characters to remap
         yÐ€ - map for each (change "-" into ",", "o" into "-", and "-" into "`"

’1£ẋ€ż¢Y - Main link: n
’        - decrement (nAwakeGoats)
 1£      - call link 1 as a nilad (make an awake goat)
   ẋ€    - repeat nAwakeGoats times
      ¢  - last link (make a sleeping goat)
     ż   - zip
       Y - join with line feeds
         - implicit print
</code>```

ContentLicense: CC BY-SA 3.0

Title: Counting Goats to Sleep

Body:
Jelly, <s>62</s> 56 bytes

⁶ẋ6;“\   ___/o>-(___)"  '' ''  ”s8
¢“-,o-'`”yÐ€
’1£ẋ€ż¢Y

Test it at TryItOnline

How?

⁶ẋ6;“\   ___/o>-(___)"  '' ''  ”s8 - Link 1: make a goat, niladic
⁶ẋ6                                - space character, ⁶, repeated 6 times
    “\   ___/o>-(___)"  '' ''  ”   - rest of the awake goat text
   ;                               - concatenate
                                s8 - split into length 8 parts

¢“-,o-'`”yÐ€ - Link 2: put a goat to sleep, niladic
¢            - last link (make a goat)
 “-,o-'`”    - characters to remap
         yÐ€ - map for each (change "-" into ",", "o" into "-", and "-" into "`"

’1£ẋ€ż¢Y - Main link: n
’        - decrement (nAwakeGoats)
 1£      - call link 1 as a nilad (make an awake goat)
   ẋ€    - repeat nAwakeGoats times
      ¢  - last link (make a sleeping goat)
     ż   - zip
       Y - join with line feeds
         - implicit print


问:
Print an alphabet wave
You are to print this exact text:

```<code>ABABABABABABABABABABABABAB
BCBCBCBCBCBCBCBCBCBCBCBCBC
CDCDCDCDCDCDCDCDCDCDCDCDCD
DEDEDEDEDEDEDEDEDEDEDEDEDE
EFEFEFEFEFEFEFEFEFEFEFEFEF
FGFGFGFGFGFGFGFGFGFGFGFGFG
GHGHGHGHGHGHGHGHGHGHGHGHGH
HIHIHIHIHIHIHIHIHIHIHIHIHI
IJIJIJIJIJIJIJIJIJIJIJIJIJ
JKJKJKJKJKJKJKJKJKJKJKJKJK
KLKLKLKLKLKLKLKLKLKLKLKLKL
LMLMLMLMLMLMLMLMLMLMLMLMLM
MNMNMNMNMNMNMNMNMNMNMNMNMN
NONONONONONONONONONONONONO
OPOPOPOPOPOPOPOPOPOPOPOPOP
PQPQPQPQPQPQPQPQPQPQPQPQPQ
QRQRQRQRQRQRQRQRQRQRQRQRQR
RSRSRSRSRSRSRSRSRSRSRSRSRS
STSTSTSTSTSTSTSTSTSTSTSTST
TUTUTUTUTUTUTUTUTUTUTUTUTU
UVUVUVUVUVUVUVUVUVUVUVUVUV
VWVWVWVWVWVWVWVWVWVWVWVWVW
WXWXWXWXWXWXWXWXWXWXWXWXWX
XYXYXYXYXYXYXYXYXYXYXYXYXY
YZYZYZYZYZYZYZYZYZYZYZYZYZ
ZAZAZAZAZAZAZAZAZAZAZAZAZA
</code>```

Specs

You can print all lowercase instead of all uppercase. However, case must be consistent throughout the output.

You may print one extra trailing linefeed.

Scoring

Since this is an alphabet wave that fluctuates to a small extent, your code should also be small in terms of byte-count. In fact, the smallest code in terms of byte-count wins.

答:
GNU sed, 95 bytes

s,^,@@@@@@@@@@@@@,;s,@,AB,g
:;p
y,ABCDEFGHIJKLMNOPQRSTUVWXYZ,BCDEFGHIJKLMNOPQRSTUVWXYZA,
/^Z/!b
```

I wish the 'y' command had this syntax: y,A-Z,B-ZA,.

Title: Print an alphabet wave

Body:
GNU sed, 95 bytes

s,^,@@@@@@@@@@@@@,;s,@,AB,g
:;p
y,ABCDEFGHIJKLMNOPQRSTUVWXYZ,BCDEFGHIJKLMNOPQRSTUVWXYZA,
/^Z/!b

I wish the 'y' command had this syntax: y,A-Z,B-ZA,.


问:
Sum or difference of two powers of two
Your challenge, should you choose to accept it, is, given an integer K >= 1, find non-negative integers A and B  such that at least one of the two conditions following hold:

K = 2^A + 2^B

K = 2^A - 2^B

If there does not exist such A and B, your program may behave in any fashion. (To clarify, A and B can be equal.)

Test cases

There are often multiple solutions to a number, but here are a few:

```<code>K => A, B
1 => 1, 0
15 => 4, 0                      ; 16 - 1 = 15
16 => 5, 4                      ; 32 - 16 = 16; also 3, 3: 8 + 8 = 16
40 => 5, 3                      ; 2^5 + 2^3 = 40
264 => 8, 3
17179867136 => 34, 11           ; 17179869184 - 2048 = 17179867136
</code>```

The last test case, 17179867136, must run in under 10 seconds on any relatively modern machine. This is a code golf, so the shortest program in bytes wins. You may use a full program or a function.

答:
Perl 6, 41 bytes

{.base(2).flip~~/1[1+|0*]/;$/.to,$/.from}
```

<p>( Algorithm shamelessly copied from the Perl 5 answer )</p>

<h2>Explanation:</h2>

<pre class="lang-perl6 prettyprint-override"><code># bare block lambda with implicit parameter ｢$_｣
{
  # turn into binary
  # ( implicit method call on ｢$_｣ )
  .base(2)

  # flip the binary representation
  .flip

  ~~ # smartmatch that against:

  /
    1      # a ｢1｣
    [
      | 1+ # at least one ｢1｣
      | 0* # or any number of ｢0｣
    ]
  /;

  # returns a list comprised of

  # the position of the end of the match (larger of the two)
  $/.to,
  # the position of the beginning of the match
  $/.from
}
</code>```

Usage:

# give it a lexical name for clarity
my &bin-sum-diff = {.base(2).flip~~/1[1+|0*]/;$/.to,$/.from}

say bin-sum-diff 15; # (4 0)
say bin-sum-diff 16; # (5 4)

say bin-sum-diff 20; # (4 2)
# 2**4==16, 2**2==4; 16+4 == 20

say bin-sum-diff 40; # (5 3)
say bin-sum-diff 264; # (8 3)
say bin-sum-diff 17179867136; # (34 11)
```

Title: Sum or difference of two powers of two

Body:
Perl 6, 41 bytes

{.base(2).flip~~/1[1+|0*]/;$/.to,$/.from}

( Algorithm shamelessly copied from the Perl 5 answer )

Explanation:

# bare block lambda with implicit parameter ｢$_｣
{
  # turn into binary
  # ( implicit method call on ｢$_｣ )
  .base(2)

  # flip the binary representation
  .flip

  ~~ # smartmatch that against:

  /
    1      # a ｢1｣
    [
      | 1+ # at least one ｢1｣
      | 0* # or any number of ｢0｣
    ]
  /;

  # returns a list comprised of

  # the position of the end of the match (larger of the two)
  $/.to,
  # the position of the beginning of the match
  $/.from
}

Usage:

# give it a lexical name for clarity
my &bin-sum-diff = {.base(2).flip~~/1[1+|0*]/;$/.to,$/.from}

say bin-sum-diff 15; # (4 0)
say bin-sum-diff 16; # (5 4)

say bin-sum-diff 20; # (4 2)
# 2**4==16, 2**2==4; 16+4 == 20

say bin-sum-diff 40; # (5 3)
say bin-sum-diff 264; # (8 3)
say bin-sum-diff 17179867136; # (34 11)


问:
Bitflip and negate
Given an integer, make an expression that produces it from 0 using unary negation - and bitwise complement ~ (~n = -n-1), with the operators applied right to left.

```<code>...
-3  = ~-~-~0
-2  = ~-~0
-1  = ~0
 0  = 0
 1  = -~0
 2  = -~-~0
 3  = -~-~-~0
...
</code>```

Your expression must be as short as possible, which means no redundant parts of ~~, --, -0, or 00. Output or print the expression as a string or a sequence of characters.

var QUESTION_ID=92598,OVERRIDE_USER=20260;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/92598/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="
"+e.body.replace(OVERRIDE_REG,"")+"
")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}</code>```

 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

```

答:
GolfScript, 30 24 20 bytes

Saved 6 bytes thanks to xnor.

Saved 4 bytes thanks to Dennis.

~."-~"\abs*\0<{(;}*0

Input: -5

Output: -5 = ~-~-~-~-~0

Explanation

```<code>~.     # Input to integer and duplicate
"-~"   # We shall output a repetition of this string
\abs   # Move the input onto the stack and computes abs
*      # Multiply "-~" for abs(input) times
\      # Copy onto the stack the input
0<     # Is it less than 0?
{(;}*  # Yes: remove first '-' from the output
0      # Push 0
</code>```

Try it online!

Title: Bitflip and negate

Body:
GolfScript, 30 24 20 bytes

Saved 6 bytes thanks to xnor.

Saved 4 bytes thanks to Dennis.

~."-~"\abs*\0<{(;}*0

Input: -5

Output: -5 = ~-~-~-~-~0

Explanation

~.     # Input to integer and duplicate
"-~"   # We shall output a repetition of this string
\abs   # Move the input onto the stack and computes abs
*      # Multiply "-~" for abs(input) times
\      # Copy onto the stack the input
0<     # Is it less than 0?
{(;}*  # Yes: remove first '-' from the output
0      # Push 0

Try it online!


Title: Counting Goats to Sleep

Body:
Some people count sheep to get to sleep. Others count goats.

Write a program or function that takes in a positive integer N and outputs N-1 awake goats followed by one sleeping goat, as if someone was counting N goats and at the very last one they fell asleep.

Awake goats look like this:

```<code>      \
  ___/o>
-(___)"
 '' ''
</code>```

Sleeping goats look like this:

```<code>      \
  ___/->
,(___)"
 `` ``
</code>```

They are chained together with a single space between beard and tail of adjacent goats:

```<code>      \       \       \
  ___/o>  ___/o>  ___/->
-(___)" -(___)" ,(___)"
 '' ''   '' ''   `` ``
</code>```

The output is allowed to have trailing spaces and a single trailing newline.

The shortest code in bytes wins.

Examples

N = 1:

```<code>      \
  ___/->
,(___)"
 `` ``
</code>```

N = 2:

```<code>      \       \
  ___/o>  ___/->
-(___)" ,(___)"
 '' ''   `` ``
</code>```

N = 3:

```<code>      \       \       \
  ___/o>  ___/o>  ___/->
-(___)" -(___)" ,(___)"
 '' ''   '' ''   `` ``
</code>```

N = 4:

```<code>      \       \       \       \
  ___/o>  ___/o>  ___/o>  ___/->
-(___)" -(___)" -(___)" ,(___)"
 '' ''   '' ''   '' ''   `` ``
</code>```

Larger N should work just as well.

Body:
PHP , 200 Bytes

$a=["      \ ","  ___/o>",'-(___)" '," '' ''  "," `` ``  "];$z=8*$n=$argv[1];for($i=0;$i<4;)$o.=str_repeat($a[$i],$i++==3?$n-1:$n);$o[$z*2-2]="-";$o[$z*3-8]=",";$o.=$a[4];echo chunk_split($o,$z,"\n");


问:
Esolang-Comment-Template-Generator
Lots of people on this site use esoteric languages, and since these languages are unusual and hard to understand, they will frequently write an explanation in a certain format. For example, if the code was

```<code>abcdefghijklmnop
</code>```

And this languages uses # for comments, they would write an explanation like this:

```<code>a                #Explanation of what 'a' does
 bc              #Bc
   d             #d
    e            #Explanation of e
     fgh         #foobar
        ij       #hello world
          k      #etc.
           l     #so on
            mn   #and
              op #so forth
</code>```

I frequently do this too, but every time I do this, I feel like creating the layout of text is really obnoxious and time-consuming. So I want you to create a "Esolang-Comment-Template-Generator" for me. For example, if we ignore the comments, the previous code has this template:

```<code>a                #
 bc              #
   d             #
    e            #
     fgh         #
        ij       #
          k      #
           l     #
            mn   #
              op #
</code>```

The Challenge:

You must write a program or function that takes two strings as input, and outputs this "Esolang-Comment-Template". The first input will be the code, but with bars (|) inserted where the newlines go. The second input is what we will use for comments. So our last example would have this for input:

```<code>"a|bc|d|e|fgh|ij|k|l|mn|op", "#"
</code>```

Unfortunately this excludes bars from being part of the code input, but that's OK. You can assume that the comment input will be a single character. For simplicity's sake, the comment char will not be a bar. The code input will only contain printable ASCII, and it will not contain any newlines.

Hopefully you can infer what to do from the testcases, but I'll try to clarify some things.

You must split the code input up into "code-sections" on every bar. Then, each section of code is output on its own line and left-padded with the length of all the previous code (not including the bars). Then, each line is right-padded with enough spaces so that the last two characters on every line are "One additional space" + "The comment character".

One trailing newline is allowed.

Here is another example. For the input

```<code>"Hello|World", "/"
</code>```

The first section of code is "Hello" and the second is "World". So it should give the output:

```<code>Hello      /
     World /
</code>```

Here are some more samples:

```<code>Input:
"a|b|c|d|e|f|g", ","

Output:
a       ,
 b      ,
  c     ,
   d    ,
    e   ,
     f  ,
      g ,

Input:
"abcdefg", ":"

Output:
abcdefg :

Input:
"4|8|15|16|23|42", "%"

Output:
4          %
 8         %
  15       %
    16     %
      23   %
        42 %

Input:
"E|ac|h s|ecti|on is| one c|haracte|r longer| than the| last!", "!"

Output:
E                                                   !
 ac                                                 !
   h s                                              !
      ecti                                          !
          on is                                     !
                one c                               !
                     haracte                        !
                            r longer                !
                                     than the       !
                                              last! !

Input:
"This|Code|has||empty||sections", "@"

Output:
This                     @
    Code                 @
        has              @
                         @
           empty         @
                         @
                sections @
</code>```

Rules:

You may take these inputs and outputs in any reasonable format. For example, reading/writing a file, STDIN/STOUT, function arguments/return value, etc. As usual, this is code-golf, so try to make your code as short as possible and you win if you can get the shortest solution in your language! I will also select the shortest solution as the overall winner. Standard loopholes are banned.

答:
Floroid - 94 bytes

```<code>Ah(a,b):c=a.fn("|");z(" "+b+"\n".y(' '*Z("".y(c[:j]))+l+" "*Z("".y(c[j+1:]))Kj,lIai(c))+' '+b)
</code>```

Uses an approach similar to @JonathanAllans' Python solution.

Testcases

```<code>Call: h("a|bc|d|e|fgh|ij|k|l|mn|op", "#")
Output:
a                #
 bc              #
   d             #
    e            #
     fgh         #
        ij       #
          k      #
           l     #
            mn   #
              op #
</code>```

ContentLicense: CC BY-SA 4.0

Title: Esolang-Comment-Template-Generator

Body:
Floroid - 94 bytes

Ah(a,b):c=a.fn("|");z(" "+b+"\n".y(' '*Z("".y(c[:j]))+l+" "*Z("".y(c[j+1:]))Kj,lIai(c))+' '+b)

Uses an approach similar to @JonathanAllans' Python solution.

Testcases

Call: h("a|bc|d|e|fgh|ij|k|l|mn|op", "#")
Output:
a                #
 bc              #
   d             #
    e            #
     fgh         #
        ij       #
          k      #
           l     #
            mn   #
              op #


答:
PHP, 73 bytes

I could have copied Jonathan´s Pyhton 2 solution for 54 bytes (+13 overhead),

but wanted to come up with something different.

save to file, then execute with php or php-cgi.

```<code><?=strlen($n=decbin($argv[1]))-!!strpos($n,'01')._.strpos(strrev($n),49);
</code>```

prints a and b separated by an underscore, anything for no solution.

distinctive solution, 96 bytes

```<code><?=preg_match('#^(10*1|(1+))(0*)$#',decbin($argv[1]),$m)?strlen($m[0])-!$m[2]._.strlen($m[3]):_;
</code>```

prints a and b separated by an underscore; a sole underscore for no solution.

It even tells you the operation for 11 more bytes:

Just replace the first underscore in the code with '-+'[!$m[2]].

Title: Sum or difference of two powers of two

Body:
Your challenge, should you choose to accept it, is, given an integer K >= 1, find non-negative integers A and B  such that at least one of the two conditions following hold:

K = 2^A + 2^B

K = 2^A - 2^B

If there does not exist such A and B, your program may behave in any fashion. (To clarify, A and B can be equal.)

Test cases

There are often multiple solutions to a number, but here are a few:

```<code>K => A, B
1 => 1, 0
15 => 4, 0                      ; 16 - 1 = 15
16 => 5, 4                      ; 32 - 16 = 16; also 3, 3: 8 + 8 = 16
40 => 5, 3                      ; 2^5 + 2^3 = 40
264 => 8, 3
17179867136 => 34, 11           ; 17179869184 - 2048 = 17179867136
</code>```

The last test case, 17179867136, must run in under 10 seconds on any relatively modern machine. This is a code golf, so the shortest program in bytes wins. You may use a full program or a function.

Body:
PHP, 73 bytes

I could have copied Jonathan´s Pyhton 2 solution for 54 bytes (+13 overhead),

but wanted to come up with something different.

save to file, then execute with php or php-cgi.

<?=strlen($n=decbin($argv[1]))-!!strpos($n,'01')._.strpos(strrev($n),49);

prints a and b separated by an underscore, anything for no solution.

distinctive solution, 96 bytes

<?=preg_match('#^(10*1|(1+))(0*)$#',decbin($argv[1]),$m)?strlen($m[0])-!$m[2]._.strlen($m[3]):_;

prints a and b separated by an underscore; a sole underscore for no solution.

It even tells you the operation for 11 more bytes:

Just replace the first underscore in the code with '-+'[!$m[2]].


答:
GolfScript, 85 bytes

```<code>{(;);}:r;", "%(r\(r n+:c;;.,\'|'%.,@\-)):l;0:m;{.,0>}{" "m*\(.,m+:m l\-" "\*+c@}while
</code>```

Try it online

2017 Update - GolfScript - 71 bytes

```<code>', '/~~:c;~1/.,\.{'|'=},,@\-):l;['|']/0:i;{.,i+:i l i-' '*c+\' '*"
"\}/
</code>```

Explanation

```<code>', '/~~:c;~1/        # Parses input
.,\.{'|'=},,@\-):l;  # Computes string length without '|'
['|']/               # Splits the array
0:i;                 # Counter
{.,                  # Length of the substring
i+:i                 # Counter update
l i-' '*c+\          # Adds spaces after the substring
' '*"\n"\            # Adds spaces before the next substring
}/                   # ...For each substring
</code>```

Title: Esolang-Comment-Template-Generator

Body:
Lots of people on this site use esoteric languages, and since these languages are unusual and hard to understand, they will frequently write an explanation in a certain format. For example, if the code was

```<code>abcdefghijklmnop
</code>```

And this languages uses # for comments, they would write an explanation like this:

```<code>a                #Explanation of what 'a' does
 bc              #Bc
   d             #d
    e            #Explanation of e
     fgh         #foobar
        ij       #hello world
          k      #etc.
           l     #so on
            mn   #and
              op #so forth
</code>```

I frequently do this too, but every time I do this, I feel like creating the layout of text is really obnoxious and time-consuming. So I want you to create a "Esolang-Comment-Template-Generator" for me. For example, if we ignore the comments, the previous code has this template:

```<code>a                #
 bc              #
   d             #
    e            #
     fgh         #
        ij       #
          k      #
           l     #
            mn   #
              op #
</code>```

The Challenge:

You must write a program or function that takes two strings as input, and outputs this "Esolang-Comment-Template". The first input will be the code, but with bars (|) inserted where the newlines go. The second input is what we will use for comments. So our last example would have this for input:

```<code>"a|bc|d|e|fgh|ij|k|l|mn|op", "#"
</code>```

Unfortunately this excludes bars from being part of the code input, but that's OK. You can assume that the comment input will be a single character. For simplicity's sake, the comment char will not be a bar. The code input will only contain printable ASCII, and it will not contain any newlines.

Hopefully you can infer what to do from the testcases, but I'll try to clarify some things.

You must split the code input up into "code-sections" on every bar. Then, each section of code is output on its own line and left-padded with the length of all the previous code (not including the bars). Then, each line is right-padded with enough spaces so that the last two characters on every line are "One additional space" + "The comment character".

One trailing newline is allowed.

Here is another example. For the input

```<code>"Hello|World", "/"
</code>```

The first section of code is "Hello" and the second is "World". So it should give the output:

```<code>Hello      /
     World /
</code>```

Here are some more samples:

```<code>Input:
"a|b|c|d|e|f|g", ","

Output:
a       ,
 b      ,
  c     ,
   d    ,
    e   ,
     f  ,
      g ,

Input:
"abcdefg", ":"

Output:
abcdefg :

Input:
"4|8|15|16|23|42", "%"

Output:
4          %
 8         %
  15       %
    16     %
      23   %
        42 %

Input:
"E|ac|h s|ecti|on is| one c|haracte|r longer| than the| last!", "!"

Output:
E                                                   !
 ac                                                 !
   h s                                              !
      ecti                                          !
          on is                                     !
                one c                               !
                     haracte                        !
                            r longer                !
                                     than the       !
                                              last! !

Input:
"This|Code|has||empty||sections", "@"

Output:
This                     @
    Code                 @
        has              @
                         @
           empty         @
                         @
                sections @
</code>```

Rules:

You may take these inputs and outputs in any reasonable format. For example, reading/writing a file, STDIN/STOUT, function arguments/return value, etc. As usual, this is code-golf, so try to make your code as short as possible and you win if you can get the shortest solution in your language! I will also select the shortest solution as the overall winner. Standard loopholes are banned.

Body:
GolfScript, 85 bytes

{(;);}:r;", "%(r\(r n+:c;;.,\'|'%.,@\-)):l;0:m;{.,0>}{" "m*\(.,m+:m l\-" "\*+c@}while

Try it online

2017 Update - GolfScript - 71 bytes

', '/~~:c;~1/.,\.{'|'=},,@\-):l;['|']/0:i;{.,i+:i l i-' '*c+\' '*"
"\}/

Explanation

', '/~~:c;~1/        # Parses input
.,\.{'|'=},,@\-):l;  # Computes string length without '|'
['|']/               # Splits the array
0:i;                 # Counter
{.,                  # Length of the substring
i+:i                 # Counter update
l i-' '*c+\          # Adds spaces after the substring
' '*"\n"\            # Adds spaces before the next substring
}/                   # ...For each substring


Title: Counting Goats to Sleep

Body:
PHP, <s>133</s> 131 bytes

for(;$y<32;$y+=8)for($x=$argv[1];$x--;)echo substr("      \   ___/".($x?"o>-(___)\"  '' ''  ":"->,(___)\"  `` ``  "),$y,8),"
"[$x];

I found two bytes to golf away from one of the version without curlys.


问:
RGB Gradients Generation
The Challenge

Given the two uppercase hexadecimal strings (both 6 characters long, XXXXXX and YYYYYY) representing RGB values (ranging from 000000 to FFFFFF inclusive), and a positive non-zero integer N, display a linear transition of the N+2 colors generated from XXXXXX to YYYYYY that would result in a color gradient.

Example

Input

```<code>FF3762
F08800
9
</code>```

Output

Please note in our example, I've requested 9 interim steps between the two colors, therefore 11 lines will be displayed from initial color to the final color

```<code>FF3762
FD3F58
FC474E
FA4F44
F9573A
F75F31
F66727
F46F1D
F37713
F17F09
F08800
</code>```

Caveats

While I've gone with a simple linear process of deriving the integer values for the interim colors before converting them back into hexadecimal, your methods may vary. Please consider the various ways one could round up/down your numbers accordingly.

Testing

To make this interesting, I've provided a snippet to allow testing of your code, inclusive of a button to provide you with two random colors to test your code against. Displaying your results is optional, but it's encouraged!

c1=()=>('00000'+(Math.random()*(1<<24)|0).toString(16)).slice(-6);

$("#col").click(function(){
  alert("Your two colors are: "+c1()+" and "+c1()+".");
});

$("#colors").blur(function(){
  $("#test").empty();
 var colArr = $("#colors").val().split("\n");
 for(c in colArr){
   $("#test").append('
'+colArr[c]+'
')
  }

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.tester{height: 20px;
width: 60px;padding: 4px;border: 1px solid black;}</code>```

<button id="col">Your two colors</button>

<textarea id="colors"></textarea>

```

1) You can access two random colors for your test by clicking on the "Your two colors" button.
2) The number of interim steps will be the same as the number of characters in your PPCG username inclusive of spaces, in the case of "WallyWest" it would be 9 (as per my example above).
3) Run your code with the two colors and the number and once you have your generated list, you have the option of pasting your output into the textarea and tabbing away from it to get your generated color gradient.

My example is shown here:

I must admit, that looks pretty awesome!

Please note: As I mentioned, showing your testing of your output using the snippet is optional, but it's encouraged! :)

Output

The list output must be in the form of N+2 sets of 6 digit hex numbers separated by line feeds (\n) as shown in my example above. Output can be in the form of separate lines, space/comma separated list, an array or whatever is best suited for your language... (Thanks @nimi for the heads up) Please remember, that if you plan on testing your code with the snippet, however you separate each "color" is up to you.

Rules

This is code-golf, so the shortest solution in bytes will be crowned the winner. No loopholes, naturally. Input must accept the two strings and a number (which as I said will be equivalent to the number of letters in your username on PPCG, thus your resulting output will always be a minimum of three lines long.

答:
sh + ImageMagick, 81 bytes

```<code>convert -size 1x$((2+$3)) gradient:#$1-#$2 -depth 8 txt:-|grep -o "[A-F0-9]\{6\}"
</code>```

usage:

```<code>> ./grad.sh FF3762 F08800 9
FF3762
FE3F58
FC474E
FB4F45
F9573B
F86031
F66827
F5701D
F37814
F2800A
F08800
</code>```

("-depth 8" is not necessary if your IM is compiled with 8bpp as the default)

Title: RGB Gradients Generation

Body:
sh + ImageMagick, 81 bytes

convert -size 1x$((2+$3)) gradient:#$1-#$2 -depth 8 txt:-|grep -o "[A-F0-9]\{6\}"

usage:

> ./grad.sh FF3762 F08800 9
FF3762
FE3F58
FC474E
FB4F45
F9573B
F86031
F66827
F5701D
F37814
F2800A
F08800

("-depth 8" is not necessary if your IM is compiled with 8bpp as the default)


Title: Counting Goats to Sleep

Body:
C++, 180 bytes

auto f(int n)
{
string a,b,c,d;
while(n--)
{
a+="      \\ ";
b+="  ___/";b+=n?"o>":"->\n";
c+=n?"-(___)\" ":",(___)\" \n";
d+=n?R"( '' ''  )":" `` ``  \n";
}
return a+'\n'+b+c+d;
}


问:
Distance to four
This challenge is based on this video. I recommend that you watch it before trying this challenge.

First we define a function.  This function (OEIS) takes a integer n as input and outputs the number of letters in the English representation of n (without spaces or hyphens).  For example "three" has 5 letters so 3 maps to 5.

As demonstrated in the video starting with any number repeating this process will eventually result in a four, which will map to itself forever.

Here is a crude directed graph showing the orbits of the numbers less than 16:

```<code>  12 11
    \|
15 2 6 1 10 14 13
  \ \|/ /  /  /
   7 3-/  8--/
    \|   /
 9 0 5--/
  \ \|
   \-4
</code>```

Your challenge is to determine the number of steps that a number will take (or the number of times this function must be applied to a number) before reaching four (i.e. the level on the directed graph pictured).

Forming english numbers

Here is a brief explanation of how one should form english words for this challenge:

The numbers one through nineteen are:

one, two, three, four, five, six, seven, eight, nine, ten, eleven, twelve, thirteen, fourteen, fifteen, sixteen, seventeen, eighteen, nineteen

For numbers greater than nineteen the process is as follows:

If the number has a hundreds place begin with the name of digit in the hundreds place and "hundred".

e.g.

```<code>100 -> "onehundred"
</code>```

If the remainder is less than twenty append the remainder's English representation.

e.g.

```<code>714 -> "sevenhundredfourteen"
</code>```

Otherwise if the tens digit is not zero append the proper representation:

```<code>2-> twenty
3-> thirty
4-> forty
5-> fifty
6-> sixty
7-> seventy
8-> eighty
9-> ninety
</code>```

e.g.

```<code>470 -> "fourhundredseventy"
</code>```

Finally if there is a one's digit append its representation

e.g.

```<code>681 -> "sixhundredeightyone"
</code>```

Further Stipulations

For numbers greater than one hundred you should leave out the "and" when counting the number of letters. For instance 577 is "fivehundredseventyseven" which has 23 letters.

Your program must accept all integers greater than 0 and less than 1,000 as input via standard methods.

Your program must output the number of steps required to standard output methods.

This is codegolf so the solution with the fewest bytes wins.

Test cases

```<code>1 -> 3
4 -> 0
7 -> 2
23 -> 5
577 -> 6
600 -> 4
</code>```

答:
Pyth - 54 bytes

Will try to refactor.

```<code>KjC"Y©åláóê¤"Ttl.u?<NyT@KNs+V@LKJ_jNT[Z@jC"Ckg"ThtJ7
</code>```

Test Suite.

Title: Distance to four

Body:
Pyth - 54 bytes

Will try to refactor.

KjC"Y©åláóê¤"Ttl.u?<NyT@KNs+V@LKJ_jNT[Z@jC"Ckg"ThtJ7

Test Suite.


问:
Golff y Côd - Treiglad
Read this yng Nghymraeg

Challenge

Given a word in Welsh, output all of the possible mutated forms of the word.

Mutations

A mutation is a change of the first letter of a word when following certain words or in certain grammatical contexts.

In Welsh, the following are considered "consonants":

```<code>b c ch d dd f ff g ng h l ll m n p ph r rh s t th
</code>```

Note that multiple character consonants such as ch, ng and rh are counted as one letter in Welsh, and therefore one consonant.

The other letters in the Welsh alphabet are vowels, listed below:

```<code>a e i o u w y
</code>```

See below, all of the mutations with the original letter on the left and the resulting mutated letters on the right:

```<code>Original | Mutations
---------+---------------
p        | b mh ph
t        | d nh th
c        | g ngh ch
b        | f m
d        | dd n
g        | [no letter] ng
m        | f
ll       | l
rh       | r
</code>```

Here, [no letter] means that the g is removed from the start of the word.

Note that there are some consonants which do not mutate:

```<code>ch
dd
f
ff
j
l
n
ng
ph
r
s
th
</code>```

Vowels may also be found at the start of words but do not mutate:

```<code>a
e
i
o
u
w
y
</code>```

Examples

Input: dydd

Output:

```<code>dydd
ddydd
nydd
</code>```

Input: pobl

Output:

```<code>pobl
bobl
mhobl
phobl
</code>```

Input: gwernymynydd

Output:

```<code>gwernymynydd
wernymynydd
ngwernymynydd
</code>```

Input: ffrindiau

Output:

```<code>ffrindiau
</code>```

Input: enw

Output:

```<code>enw
</code>```

Input: theatr

Output:

```<code>a e i o u w y
</code>```0

On the request of ArtOfCode ;)

Input: llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch

Output:

```<code>a e i o u w y
</code>```1

Rules

The input will only ever be one word.

There will always be more letters after the leading consonant in your input.

Winning

The shortest code in bytes wins.

答:
C#, 349 bytes

Based on @grizzly's submission, but corrected to work with the consonants that don't get transformed (ph/ch/th/dd) that it wasn't working with, plus trimmed some excess out. Hope that's alright?

I had it down to 290 until I realized that I was missing the th/ch/ph/dd cases :-(. Adding in the Regex call killed it

```<code>namespace System{class P{static void Main(string[]a){var x=a[0];if(!Text.RegularExpressions.Regex.IsMatch(x,"^[pct]h|^dd"))foreach(var r in"p.b.mh.ph-t.d.nh.th-c.g.ngh.ch-b.f.m-d.dd.n-g..ng-m.f-ll.l-rh.r".Split('-')){var b=r.Split('.');if(a[0].StartsWith(b[0]))for(int i=1;i<b.Length;)x+='\n'+b[i++]+a[0].Substring(b[0].Length);}Console.Write(x);}}}
</code>```

Interesting note, never knew that you could omit the space between var r in"string"

Formatted:

```<code>namespace System
{
    class P
    {
        static void Main(string[] a)
        {
            var x = a[0];
            if (!Text.RegularExpressions.Regex.IsMatch(x, "^[pct]h|^dd"))
                foreach (var r in"p.b.mh.ph-t.d.nh.th-c.g.ngh.ch-b.f.m-d.dd.n-g..ng-m.f-ll.l-rh.r".Split('-'))
                {
                    var b = r.Split('.');
                    if (a[0].StartsWith(b[0]))
                        for (int i = 1; i < b.Length;) x += '\n' + b[i++] + a[0].Substring(b[0].Length);
                }
            Console.Write(x);
        }
    }
}
</code>```

Title: Golff y Côd - Treiglad

Body:
C#, 349 bytes

Based on @grizzly's submission, but corrected to work with the consonants that don't get transformed (ph/ch/th/dd) that it wasn't working with, plus trimmed some excess out. Hope that's alright?

I had it down to 290 until I realized that I was missing the th/ch/ph/dd cases :-(. Adding in the Regex call killed it

namespace System{class P{static void Main(string[]a){var x=a[0];if(!Text.RegularExpressions.Regex.IsMatch(x,"^[pct]h|^dd"))foreach(var r in"p.b.mh.ph-t.d.nh.th-c.g.ngh.ch-b.f.m-d.dd.n-g..ng-m.f-ll.l-rh.r".Split('-')){var b=r.Split('.');if(a[0].StartsWith(b[0]))for(int i=1;i<b.Length;)x+='\n'+b[i++]+a[0].Substring(b[0].Length);}Console.Write(x);}}}

Interesting note, never knew that you could omit the space between var r in"string"

Formatted:

namespace System
{
    class P
    {
        static void Main(string[] a)
        {
            var x = a[0];
            if (!Text.RegularExpressions.Regex.IsMatch(x, "^[pct]h|^dd"))
                foreach (var r in"p.b.mh.ph-t.d.nh.th-c.g.ngh.ch-b.f.m-d.dd.n-g..ng-m.f-ll.l-rh.r".Split('-'))
                {
                    var b = r.Split('.');
                    if (a[0].StartsWith(b[0]))
                        for (int i = 1; i < b.Length;) x += '\n' + b[i++] + a[0].Substring(b[0].Length);
                }
            Console.Write(x);
        }
    }
}


问:
Phonemic Abugida

Characters

Let’s call these Unicode characters English IPA consonants:

```<code>bdfhjklmnprstvwzðŋɡʃʒθ
</code>```

And let’s call these Unicode characters  English IPA vowels:

```<code>aeiouæɑɔəɛɜɪʊʌː
</code>```

(Yes, ː is just the long vowel mark, but treat it as a vowel for the purpose of this challenge.)

Finally, these are primary and secondary stress marks:

```<code>ˈˌ
</code>```

Note that ɡ (U+0261) is not a lowercase g, and the primary stress marker ˈ (U+02C8) is not an apostrophe, and ː (U+02D0) is not a colon.

Your task

Given a word, stack the vowels on top of the consonants they follow, and place the stress markers beneath the consonants they precede. (As the question title hints, such a writing system, where consonant-vowel sequences are packed together as a unit, is called an abugida.) Given the input ˈbætəlʃɪp, produce the output:

```<code>æə ɪ
btlʃp
ˈ
</code>```

A word is guaranteed to be a string of consonants, vowels, and stress marks, as defined above. There will never be consecutive stress marks, and they will always be placed at the start of the word and/or before a consonant.

Test cases

There may be consecutive vowels. For example, kənˌɡrætjʊˈleɪʃən becomes

```<code>      ɪ
ə  æ ʊeə
knɡrtjlʃn
  ˌ   ˈ
</code>```

If a word starts with a vowel, print it on the “baseline” with the consonants: əˈpiːl becomes

```<code> ː
 i
əpl
 ˈ
</code>```

A test case with an initial, stressed vowel: ˈælbəˌtrɔs becomes

```<code>  ə ɔ
ælbtrs
ˈ  ˌ
</code>```

A long word: ˌsuːpərˌkaləˌfrædʒəˌlɪstɪˌkɛkspiːæləˈdoʊʃəs becomes

```<code>               æ
ː              ː ʊ
uə aə æ əɪ ɪɛ  iəoə
sprklfrdʒlstkkspldʃs
ˌ  ˌ ˌ   ˌ  ˌ    ˈ
</code>```

A nonsense example with an initial diphthong, lots of vowel stacking, and no stress markers: eɪbaeioubaabaaa becomes

```<code> u
 o
 i a
 eaa
ɪaaa
ebbb
</code>```

Reference implementation

Your program should produce the same output as this Python script:

```<code>consonants = 'bdfhjklmnprstvwzðŋɡʃʒθ'
vowels = 'aeiouæɑɔəɛɜɪʊʌː'
stress_marks = 'ˈˌ'

def abugidafy(word):
    tiles = dict()
    x = y = 0

    is_first = True
    for c in word:
        if c in stress_marks:
            tiles[x + 1, 1] = c
        elif c in consonants or is_first:
            y = 0
            x += 1
            tiles[x, y] = c
            is_first = False
        elif c in vowels:
            y -= 1
            tiles[x, y] = c
            is_first = False
        else:
            raise ValueError('Not an IPA character: ' + c)

    xs = [x for (x, y) in tiles.keys()]
    ys = [y for (x, y) in tiles.keys()]
    xmin, xmax = min(xs), max(xs)
    ymin, ymax = min(ys), max(ys)

    lines = []
    for y in range(ymin, ymax + 1):
        line = [tiles.get((x, y), ' ') for x in range(xmin, xmax + 1)]
        lines.append(''.join(line))
    return '\n'.join(lines)

print(abugidafy(input()))
</code>```

Try it on Ideone.

Rules

You may write a function or a full program.

If your program has a Unicode character/string type, you can assume inputs and outputs use those. If not, or you read/write from STDIN, use the UTF-8 encoding.

You may produce a string containing newlines, or a list of strings representing rows, or an array of Unicode characters.

Each row of output may contain any amount of trailing spaces. If you produce a string, it may have a single trailing newline.

Your program should produce the correct output for arbitrarily long words with arbitrarily long vowel chains, but may assume that the input word is always valid.

If there are no stress markers, your output may optionally include a final empty row (containing nothing, or spaces).

The shortest answer (in bytes) wins.

答:
Python, 222 bytes

(202 characters)

import re
def f(s):y=[w[0]in'ˈˌ'and w or' '+w for w in re.split('([ˈˌ]?[bdfhjklmnprstvwzðŋɡʃʒθ]?[aeiouæɑɔəɛɜɪʊʌː]*)',s)[1::2]];return[[x[i-1:i]or' 'for x in y]for i in range(max(len(w)for w in y),0,-1)]
```

Returns an array of unicode characters with an array for each row (containing single spaces for each space required)

Not sure where one can get decent output online yet (and I haven't even got the tools to test it properly here either).

I have loaded a version to ideone that just uses English consonants and vowels with , and . as stress marks, where I have fudged the test cases to conform.

Title: Phonemic Abugida

Body:
Python, 222 bytes

(202 characters)

import re
def f(s):y=[w[0]in'ˈˌ'and w or' '+w for w in re.split('([ˈˌ]?[bdfhjklmnprstvwzðŋɡʃʒθ]?[aeiouæɑɔəɛɜɪʊʌː]*)',s)[1::2]];return[[x[i-1:i]or' 'for x in y]for i in range(max(len(w)for w in y),0,-1)]

Returns an array of unicode characters with an array for each row (containing single spaces for each space required)

Not sure where one can get decent output online yet (and I haven't even got the tools to test it properly here either).

I have loaded a version to ideone that just uses English consonants and vowels with , and . as stress marks, where I have fudged the test cases to conform.


问:
Tips for golfing in Ruby
What general tips can you give for golfing in Ruby?

I'm looking for ideas that can be applied to code golf problems in general that are specific to Ruby. (For example, "Remove comments" would not be an answer.)

Please post one tip per answer.

答:
Use Goruby instead of Ruby, which is something like an abbreviated version of Ruby. You can install it with rvm via

```<code>rvm install goruby
</code>```

Goruby allows you to write most of your code as you would be writing Ruby, but has additional abbreviations built in. To find out the shortest available abbreviation for something, you can use the helper method shortest_abbreviation, for example:

```<code>shortest_abbreviation :puts
#=> "pts"

Array.new.shortest_abbreviation :map
#=> "m"

String.new.shortest_abbreviation :capitalize
#=> "cp"

Array.new.shortest_abbreviation :join
#=> "j"
</code>```

Also very handy is the alias say for puts which itself can be abbreviated with s. So instead of

```<code>puts [*?a..?z].map(&:capitalize).join
</code>```

you can now write

```<code>s [*?a..?z].m(&:cp).j
</code>```

to print the alphabet in capitals (which is not avery good example). This blog post explains more stuff and some of the inner workings if you are interested in further reading.

PS: don't miss out on the h method ;-)

Title: Tips for golfing in Ruby

Body:
Use Goruby instead of Ruby, which is something like an abbreviated version of Ruby. You can install it with rvm via

rvm install goruby

Goruby allows you to write most of your code as you would be writing Ruby, but has additional abbreviations built in. To find out the shortest available abbreviation for something, you can use the helper method shortest_abbreviation, for example:

shortest_abbreviation :puts
#=> "pts"

Array.new.shortest_abbreviation :map
#=> "m"

String.new.shortest_abbreviation :capitalize
#=> "cp"

Array.new.shortest_abbreviation :join
#=> "j"

Also very handy is the alias say for puts which itself can be abbreviated with s. So instead of

puts [*?a..?z].map(&:capitalize).join

you can now write

s [*?a..?z].m(&:cp).j

to print the alphabet in capitals (which is not avery good example). This blog post explains more stuff and some of the inner workings if you are interested in further reading.

PS: don't miss out on the h method ;-)


Title: Counting Goats to Sleep

Body:
GolfScript, 91 bytes

~:a 1-:b;"      \\ "a*n"  ___/o>"b*"  ___/->"n"-(___)\" "b*",(___)\""n" '' ''  "b*" `` ``"n

Input: 3

Output:

      \       \       \
  ___/o>  ___/o>  ___/->
-(___)" -(___)" ,(___)"
 '' ''   '' ''   `` ``

Explanation

~:a 1-:b;      # Parse and save the input
"      \\ "a*n # Repeat the first line 'a' times
"  ___/o>"b*   # Repeat the head 'b' times
"  ___/->"n    # Then add the sleeping goat's head
"-(___)\" "b*  # Idem
",(___)\""n    #
" '' ''  "b*   # Idem
" `` ``"n      #

Try it online!


问:
Hexagolf: Validagons

Challenge

Given an ASCII art shape, you must find out whether the shape is a regular hexagon or not.

Hexagons

A regular hexagon is defined using two rules:

It has six sides

Each side has equal numbers of characters

For example, the following shape is regular but it doesn't have six sides and so is not a regular hexagon:

```<code>B a a h
s a i d
y o u r
g a o t
</code>```

Similarly, the following shape has six sides but has sides of different lengths and so is not a regular hexagon:

```<code>  * *
 * * *
* * * *
 * * *
  * *
</code>```

However, the following shape has six sides and all of the sides have the same number of characters, so it is a regular hexagon:

```<code>  T h e
 h e x a
g o n s a
 r e c o
  m i n
</code>```

Rules

Output should be a truthy or a falsey value (truthy if the shape is a regular hexagon, falsey if not).

The shapes will only ever contain printable ASCII characters.

The border of the shape will never contain spaces. If it does, you can return falsey.

There can be arbitrary amounts of whitespace before and/or after the shape.

All angles in the shape may not be equal for example, the following shape is valid input:

```<code>  . . .
   . . .
. . . . .
 . . . .
  . . .
</code>```

It will return a falsey value.

All shape inputs will be on a space separated grid. Hexagonal input will be on a staggered grid (each line is offset from the next).

Examples

Truthy

The following shapes should return truthy values:

```<code> # _
+ + +
 9 :
</code>```

```<code>  5 6 7
 8 9 0 1
2 3 4 5 6
 7 8 9 0
  1 2 3
</code>```

```<code>    t h i s
   i       s
  a         h
 e           x
  a         g
   o       n
    ! ! ! !
</code>```

```<code>    5 6 7
   8 9 0 1
  2 3 4 5 6
   7 8 9 0
    1 2 3
</code>```

Falsey

The following should return falsey values

```<code>r e c t a
n g l e s
</code>```

```<code>  h e l l o
 w o r l d s
t h i s i s b
 e t a d e c
  a y n o w
</code>```

```<code>  *
 * *
* * *
</code>```

```<code>  .....
 .......
.........
 .......
  .....
</code>```

This shape is not on a space separated grid and is not staggered.

```<code>   * * * *
  ---------
 * * * * * *
-------------
 * * * * * *
  ---------
   * * * *
</code>```

```<code>5 6 7
8 9 0 1
2 3 4 5 6
7 8 9 0
1 2 3
</code>```

For single character inputs, your program may output either truthy or falsey:

```<code>&
</code>```

Winning

The shortest program in bytes wins.

答:
SnakeEx, 200 bytes

The right language for the job... sort of.

```<code>m:{v<>}{r<RF>2P}{r<R>2P}{h<RF>1P}{w<>}{l<RF>2P}{l<R>2P}{h<.>1}
w:{u<>P}{v<>}
v:{e<L>}{u<R>1}
u:.*{e<>}
e:.$
r:[^ ]+
h:([^ ] )+
l:({c<.>}[^ ])+{c<.>}
c:{b<B>}(. )+{x<>LP}{s<>}
b:.{s<>}
s:[^\!-\~]*$
x:.
</code>```

SnakeEx is a language from the 2-D Pattern Matching challenge. It ought to be really good at this task, but unfortunately all the corner cases really bloated the code. I also turned up a couple of interpreter bugs. Still, it was a fun challenge.

m is the main snake that calls all the others to do the actual work. It matches starting at the top right corner of the hexagon and going clockwise. Numbered groups are used to verify that the diagonal side lengths are all equal and that the horizontal side length matches the height of the whole figure. I could write a more detailed explanation, but I've spent the last two days dealing with corner cases, so just try it out for yourself here. :^)

Title: Hexagolf: Validagons

Body:
SnakeEx, 200 bytes

The right language for the job... sort of.

m:{v<>}{r<RF>2P}{r<R>2P}{h<RF>1P}{w<>}{l<RF>2P}{l<R>2P}{h<.>1}
w:{u<>P}{v<>}
v:{e<L>}{u<R>1}
u:.*{e<>}
e:.$
r:[^ ]+
h:([^ ] )+
l:({c<.>}[^ ])+{c<.>}
c:{b<B>}(. )+{x<>LP}{s<>}
b:.{s<>}
s:[^\!-\~]*$
x:.

SnakeEx is a language from the 2-D Pattern Matching challenge. It ought to be really good at this task, but unfortunately all the corner cases really bloated the code. I also turned up a couple of interpreter bugs. Still, it was a fun challenge.

m is the main snake that calls all the others to do the actual work. It matches starting at the top right corner of the hexagon and going clockwise. Numbered groups are used to verify that the diagonal side lengths are all equal and that the horizontal side length matches the height of the whole figure. I could write a more detailed explanation, but I've spent the last two days dealing with corner cases, so just try it out for yourself here. :^)


答:
Python, with num2words, <s>97 113 115 94 93</s> 92 bytes

+16 bytes (forgot the hyphenation that num2words applies which does not actually change the results of any of the test cases, even though 23 and 577 each have a hyphen)

+2 bytes (forgot to include f= although recursive)

-20 bytes (use re)

-8 bytes thanks to @Wheat Wizard (use ~, replace n!=4 with n-4, and ...one line import >_<)

-1 byte thanks to @Cyoce (space from 4 and)

```<code>import re,num2words as w
f=lambda n:n-4and-~f(len(re.sub('\W|and','',w.num2words(n))))
</code>```

Just counts up the number of steps; works for huge and negative integers too (\W finds the spaces, commas and hyphens in the num2words result):

```<code>>>> for test in (1,4,7,23,577,600,-1*2**96,3**96):
...     print('test: {0}  ->  {1}'.format(test, f(test)))
...
test: 1  ->  3
test: 4  ->  0
test: 7  ->  2
test: 23  ->  5
test: 577  ->  6
test: 600  ->  4
test: -79228162514264337593543950336  ->  4
test: 6362685441135942358474828762538534230890216321  ->  5
</code>```

Here is that last case, step by step:

```<code>sixquattuordecillionthreehundredsixtytwotredecillionsixhundredeightyfiveduodecillionfourhundredfortyoneundecilliononehundredthirtyfivedecillionninehundredfortytwononillionthreehundredfiftyeightoctillionfourhundredseventyfourseptillioneighthundredtwentyeightsextillionsevenhundredsixtytwoquintillionfivehundredthirtyeightquadrillionfivehundredthirtyfourtrilliontwohundredthirtybillioneighthundredninetymilliontwohundredsixteenthousthreehundredtwentyone
fourhundredfiftyone
nineteen
eight
five
</code>```

Title: Distance to four

Body:
This challenge is based on this video. I recommend that you watch it before trying this challenge.

First we define a function.  This function (OEIS) takes a integer n as input and outputs the number of letters in the English representation of n (without spaces or hyphens).  For example "three" has 5 letters so 3 maps to 5.

As demonstrated in the video starting with any number repeating this process will eventually result in a four, which will map to itself forever.

Here is a crude directed graph showing the orbits of the numbers less than 16:

```<code>  12 11
    \|
15 2 6 1 10 14 13
  \ \|/ /  /  /
   7 3-/  8--/
    \|   /
 9 0 5--/
  \ \|
   \-4
</code>```

Your challenge is to determine the number of steps that a number will take (or the number of times this function must be applied to a number) before reaching four (i.e. the level on the directed graph pictured).

Forming english numbers

Here is a brief explanation of how one should form english words for this challenge:

The numbers one through nineteen are:

one, two, three, four, five, six, seven, eight, nine, ten, eleven, twelve, thirteen, fourteen, fifteen, sixteen, seventeen, eighteen, nineteen

For numbers greater than nineteen the process is as follows:

If the number has a hundreds place begin with the name of digit in the hundreds place and "hundred".

e.g.

```<code>100 -> "onehundred"
</code>```

If the remainder is less than twenty append the remainder's English representation.

e.g.

```<code>714 -> "sevenhundredfourteen"
</code>```

Otherwise if the tens digit is not zero append the proper representation:

```<code>2-> twenty
3-> thirty
4-> forty
5-> fifty
6-> sixty
7-> seventy
8-> eighty
9-> ninety
</code>```

e.g.

```<code>470 -> "fourhundredseventy"
</code>```

Finally if there is a one's digit append its representation

e.g.

```<code>681 -> "sixhundredeightyone"
</code>```

Further Stipulations

For numbers greater than one hundred you should leave out the "and" when counting the number of letters. For instance 577 is "fivehundredseventyseven" which has 23 letters.

Your program must accept all integers greater than 0 and less than 1,000 as input via standard methods.

Your program must output the number of steps required to standard output methods.

This is codegolf so the solution with the fewest bytes wins.

Test cases

```<code>1 -> 3
4 -> 0
7 -> 2
23 -> 5
577 -> 6
600 -> 4
</code>```

Body:
Python, with num2words, <s>97 113 115 94 93</s> 92 bytes

+16 bytes (forgot the hyphenation that num2words applies which does not actually change the results of any of the test cases, even though 23 and 577 each have a hyphen)

+2 bytes (forgot to include f= although recursive)

-20 bytes (use re)

-8 bytes thanks to @Wheat Wizard (use ~, replace n!=4 with n-4, and ...one line import >_<)

-1 byte thanks to @Cyoce (space from 4 and)

import re,num2words as w
f=lambda n:n-4and-~f(len(re.sub('\W|and','',w.num2words(n))))

Just counts up the number of steps; works for huge and negative integers too (\W finds the spaces, commas and hyphens in the num2words result):

>>> for test in (1,4,7,23,577,600,-1*2**96,3**96):
...     print('test: {0}  ->  {1}'.format(test, f(test)))
...
test: 1  ->  3
test: 4  ->  0
test: 7  ->  2
test: 23  ->  5
test: 577  ->  6
test: 600  ->  4
test: -79228162514264337593543950336  ->  4
test: 6362685441135942358474828762538534230890216321  ->  5

Here is that last case, step by step:

sixquattuordecillionthreehundredsixtytwotredecillionsixhundredeightyfiveduodecillionfourhundredfortyoneundecilliononehundredthirtyfivedecillionninehundredfortytwononillionthreehundredfiftyeightoctillionfourhundredseventyfourseptillioneighthundredtwentyeightsextillionsevenhundredsixtytwoquintillionfivehundredthirtyeightquadrillionfivehundredthirtyfourtrilliontwohundredthirtybillioneighthundredninetymilliontwohundredsixteenthousthreehundredtwentyone
fourhundredfiftyone
nineteen
eight
five


答:
C# 176 167 154 bytes

```<code>string f(string s,char x){var c=s.Split('|');var d="";int i=0;foreach(var b in c)d+=b.PadLeft(i+=b.Length).PadRight(s.Length+2-c.Length)+x+"\n";return d;}
</code>```

UnGolfed

```<code>string f(string s, char x)
{
    var c = s.Split('|');
    var d = "";
    int i = 0;
    foreach (var b in c)
        d += b.PadLeft(i += b.Length).PadRight(s.Length + 2 - c.Length) + x + "\n";
    return d;
}
</code>```

A LINQ solution would have been 146 but needed using System.Linq; bringing it back up to 164:

```<code>string f(string s,char x){var c=s.Split('|');int i=0;return c.Aggregate("",(g,b)=>g+b.PadLeft(i+=b.Length).PadRight(s.Length+2-c.Length)+x+"\n");}
</code>```

Old solutions:

167 bytes:

```<code>string f(string s,char x){var c=s.Split('|');var d="";int i=0;foreach(var b in c){d+=b.PadLeft(i+b.Length).PadRight(s.Length+2-c.Length)+x+"\n";i+=b.Length;}return d;}
</code>```

176 bytes using string interpolation

```<code>string f(string s,char x){var c=s.Split('|');var d="";int i=0;foreach(var b in c){d+=string.Format($"{{1,{i}}}{{0,-{s.Length+2-c.Length-i}}}{x}\n",b,"");i+=b.Length;}return d;}
</code>```

Title: Esolang-Comment-Template-Generator

Body:
C# 176 167 154 bytes

string f(string s,char x){var c=s.Split('|');var d="";int i=0;foreach(var b in c)d+=b.PadLeft(i+=b.Length).PadRight(s.Length+2-c.Length)+x+"\n";return d;}

UnGolfed

string f(string s, char x)
{
    var c = s.Split('|');
    var d = "";
    int i = 0;
    foreach (var b in c)
        d += b.PadLeft(i += b.Length).PadRight(s.Length + 2 - c.Length) + x + "\n";
    return d;
}

A LINQ solution would have been 146 but needed using System.Linq; bringing it back up to 164:

string f(string s,char x){var c=s.Split('|');int i=0;return c.Aggregate("",(g,b)=>g+b.PadLeft(i+=b.Length).PadRight(s.Length+2-c.Length)+x+"\n");}

Old solutions:

167 bytes:

string f(string s,char x){var c=s.Split('|');var d="";int i=0;foreach(var b in c){d+=b.PadLeft(i+b.Length).PadRight(s.Length+2-c.Length)+x+"\n";i+=b.Length;}return d;}

176 bytes using string interpolation

string f(string s,char x){var c=s.Split('|');var d="";int i=0;foreach(var b in c){d+=string.Format($"{{1,{i}}}{{0,-{s.Length+2-c.Length-i}}}{x}\n",b,"");i+=b.Length;}return d;}


答:
NARS2000 APL, 138 bytes

```<code>⍉⌽⊃E,⍨¨↓∘' '¨∨/¨∊∘M¨E←(1+(W∊M←'ˌˈ')++\W∊'bdfhjklmnprstvwzðŋɡʃʒθ')⊂W←⍞
</code>```

Title: Phonemic Abugida

Body:
Characters

Let’s call these Unicode characters English IPA consonants:

```<code>bdfhjklmnprstvwzðŋɡʃʒθ
</code>```

And let’s call these Unicode characters  English IPA vowels:

```<code>aeiouæɑɔəɛɜɪʊʌː
</code>```

(Yes, ː is just the long vowel mark, but treat it as a vowel for the purpose of this challenge.)

Finally, these are primary and secondary stress marks:

```<code>ˈˌ
</code>```

Note that ɡ (U+0261) is not a lowercase g, and the primary stress marker ˈ (U+02C8) is not an apostrophe, and ː (U+02D0) is not a colon.

Your task

Given a word, stack the vowels on top of the consonants they follow, and place the stress markers beneath the consonants they precede. (As the question title hints, such a writing system, where consonant-vowel sequences are packed together as a unit, is called an abugida.) Given the input ˈbætəlʃɪp, produce the output:

```<code>æə ɪ
btlʃp
ˈ
</code>```

A word is guaranteed to be a string of consonants, vowels, and stress marks, as defined above. There will never be consecutive stress marks, and they will always be placed at the start of the word and/or before a consonant.

Test cases

There may be consecutive vowels. For example, kənˌɡrætjʊˈleɪʃən becomes

```<code>      ɪ
ə  æ ʊeə
knɡrtjlʃn
  ˌ   ˈ
</code>```

If a word starts with a vowel, print it on the “baseline” with the consonants: əˈpiːl becomes

```<code> ː
 i
əpl
 ˈ
</code>```

A test case with an initial, stressed vowel: ˈælbəˌtrɔs becomes

```<code>  ə ɔ
ælbtrs
ˈ  ˌ
</code>```

A long word: ˌsuːpərˌkaləˌfrædʒəˌlɪstɪˌkɛkspiːæləˈdoʊʃəs becomes

```<code>               æ
ː              ː ʊ
uə aə æ əɪ ɪɛ  iəoə
sprklfrdʒlstkkspldʃs
ˌ  ˌ ˌ   ˌ  ˌ    ˈ
</code>```

A nonsense example with an initial diphthong, lots of vowel stacking, and no stress markers: eɪbaeioubaabaaa becomes

```<code> u
 o
 i a
 eaa
ɪaaa
ebbb
</code>```

Reference implementation

Your program should produce the same output as this Python script:

```<code>consonants = 'bdfhjklmnprstvwzðŋɡʃʒθ'
vowels = 'aeiouæɑɔəɛɜɪʊʌː'
stress_marks = 'ˈˌ'

def abugidafy(word):
    tiles = dict()
    x = y = 0

    is_first = True
    for c in word:
        if c in stress_marks:
            tiles[x + 1, 1] = c
        elif c in consonants or is_first:
            y = 0
            x += 1
            tiles[x, y] = c
            is_first = False
        elif c in vowels:
            y -= 1
            tiles[x, y] = c
            is_first = False
        else:
            raise ValueError('Not an IPA character: ' + c)

    xs = [x for (x, y) in tiles.keys()]
    ys = [y for (x, y) in tiles.keys()]
    xmin, xmax = min(xs), max(xs)
    ymin, ymax = min(ys), max(ys)

    lines = []
    for y in range(ymin, ymax + 1):
        line = [tiles.get((x, y), ' ') for x in range(xmin, xmax + 1)]
        lines.append(''.join(line))
    return '\n'.join(lines)

print(abugidafy(input()))
</code>```

Try it on Ideone.

Rules

You may write a function or a full program.

If your program has a Unicode character/string type, you can assume inputs and outputs use those. If not, or you read/write from STDIN, use the UTF-8 encoding.

You may produce a string containing newlines, or a list of strings representing rows, or an array of Unicode characters.

Each row of output may contain any amount of trailing spaces. If you produce a string, it may have a single trailing newline.

Your program should produce the correct output for arbitrarily long words with arbitrarily long vowel chains, but may assume that the input word is always valid.

If there are no stress markers, your output may optionally include a final empty row (containing nothing, or spaces).

The shortest answer (in bytes) wins.

Body:
NARS2000 APL, 138 bytes

⍉⌽⊃E,⍨¨↓∘' '¨∨/¨∊∘M¨E←(1+(W∊M←'ˌˈ')++\W∊'bdfhjklmnprstvwzðŋɡʃʒθ')⊂W←⍞


答:
JavaScript (ES6), 181 bytes

f=
s=>(a=s.match(/[ˈˌ]?.[aeiouæɑɔəɛɜɪʊʌː]*/g).map(s=>/[ˈˌ]/.test(s)?s:` `+s)).map(s=>(l=s.length)>m&&(t=s,m=l),m=0)&&[...t].map(_=>a.map(s=>s[m]||` `,--m).join``).join`
`
;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input oninput=o.textContent=f(this.value)><pre id=o></code>```

Title: Phonemic Abugida

Body:
JavaScript (ES6), 181 bytes

f=
s=>(a=s.match(/[ˈˌ]?.[aeiouæɑɔəɛɜɪʊʌː]*/g).map(s=>/[ˈˌ]/.test(s)?s:` `+s)).map(s=>(l=s.length)>m&&(t=s,m=l),m=0)&&[...t].map(_=>a.map(s=>s[m]||` `,--m).join``).join`
`
;

<input oninput=o.textContent=f(this.value)><pre id=o>


Title: Distance to four

Body:
Java, 556 295 bytes

Thanks to @KevinCruijssen for saving 261 bytes

  void int(n) {int s[]={0,3,3,5,4,4,3,5,5,4,3,6,6,8,8,7,7,9,9,8,6,9,9,11,10,6,6,5,5,7,7,6};int c=0,t=(int)Math.pow(10,(int)Math.log10(n)),v=1;while(n>0){if(n/100>0)c+=(s[n/100]+7);else {if(n>0&n<25){c+=s[n];break;}else{c+=s[(n/10)+22];}}n=n%t;t=t/10;}while(c!=4){v++;c=s[c];}System.out.print(v);}

Ungolfed:

  void int(n) {

    int s[]={0,3,3,5,4,4,3,5,5,4,3,6,6,8,8,7,7,9,9,8,6,9,9,11,10,6,6,5,5,7,7,6};
     int c=0,t=(int)Math.pow(10,(int)Math.log10(n)),v=1;
         while(n>0){
            if(n/100>0)
                c+=(s[n/100]+7);
            else {if(n>0&n<25){
                c+=s[n];
            break;
            }
            else{
                c+=s[(n/10)+22];

            }
            }
            n=n%t;
            t=t/10;
        }

        while(c!=4)
        {
            v++;
        c=s[c];
        }
System.out.print(v);
}


答:
Pip, 60 + 1 = 61 bytes

One byte added for the n flag.

```<code>YsX6.\"\   ___/o>-(___)"  '' ''  \"<>8yXa-1.YyR^"-o'"Y^",-`"
</code>```

Constructs an awake goat as a list of lines and yanks it into y. String-multiplies to get a-1 awake goats. Replaces -o' with ,-` in y and concatenates it to the end. Prints, newline-separated.

Try it online!

(I think this is my first time using Pip's escaped-string syntax \"...\", which allows for literal double quotes in the string.)

Title: Counting Goats to Sleep

Body:
Some people count sheep to get to sleep. Others count goats.

Write a program or function that takes in a positive integer N and outputs N-1 awake goats followed by one sleeping goat, as if someone was counting N goats and at the very last one they fell asleep.

Awake goats look like this:

```<code>      \
  ___/o>
-(___)"
 '' ''
</code>```

Sleeping goats look like this:

```<code>      \
  ___/->
,(___)"
 `` ``
</code>```

They are chained together with a single space between beard and tail of adjacent goats:

```<code>      \       \       \
  ___/o>  ___/o>  ___/->
-(___)" -(___)" ,(___)"
 '' ''   '' ''   `` ``
</code>```

The output is allowed to have trailing spaces and a single trailing newline.

The shortest code in bytes wins.

Examples

N = 1:

```<code>      \
  ___/->
,(___)"
 `` ``
</code>```

N = 2:

```<code>      \       \
  ___/o>  ___/->
-(___)" ,(___)"
 '' ''   `` ``
</code>```

N = 3:

```<code>      \       \       \
  ___/o>  ___/o>  ___/->
-(___)" -(___)" ,(___)"
 '' ''   '' ''   `` ``
</code>```

N = 4:

```<code>      \       \       \       \
  ___/o>  ___/o>  ___/o>  ___/->
-(___)" -(___)" -(___)" ,(___)"
 '' ''   '' ''   '' ''   `` ``
</code>```

Larger N should work just as well.

Body:
Pip, 60 + 1 = 61 bytes

One byte added for the n flag.

YsX6.\"\   ___/o>-(___)"  '' ''  \"<>8yXa-1.YyR^"-o'"Y^",-`"

Constructs an awake goat as a list of lines and yanks it into y. String-multiplies to get a-1 awake goats. Replaces -o' with ,-` in y and concatenates it to the end. Prints, newline-separated.

Try it online!

(I think this is my first time using Pip's escaped-string syntax \"...\", which allows for literal double quotes in the string.)


问:
Crossword grid verification
Validate a proposed crossword grid.

Entries should be full programs that simply test a proposed grid
to determine if it meets a set of conditions for making crossword
solvers happy.

Input

The input will be the name of a file representing the crossword
grid. The input filename may be passed as an argument, on the
standard input, or by other conventional means other than
hardcoding.

Grid file format: The first line consists of two white-space
separated integer constants M and N. Following that line are M
lines each consisting of N characters (plus a new line) selected
from [#A-Z ]. These characters are interpreted such that '#'
indicates a blocked square, ' ' a open square in the puzzle
with no known contents and any letter an open square whose
containing that letter.

Output

The program should produce no output on valid grids and exit with
normal termination state. If the proposed grid fails, the program
should produce a diagnostic error message and exit with a
abnormal termination state (i.e. not 0 on unix) if this is
supported by your execution environment. The error message should
indicate both which condition for validity is violated and the
location of the offending square; you are free to chose the means
of conveying these facts.

Conditions for validity

Valid grids will have no answers (across or down) that are only 1
character long (extra credit for making the minimum length a
input parameter), and will exhibit the usual symmetry. The usual
symmetry means the crossword remains the same after (three
equivalent descriptions of the same operation):

reflection through it's own center

reflection both vertically and horizontally

180 degree rotation

Test input and expected output

Passes:

```<code>5   5
#  ##
#
  #
    #
##  #
</code>```

Fails on short answer:

```<code>5   5
## ##
#
  #
    #
## ##
</code>```

Fails on symmetry:

```<code>5   5
#  ##
#
  #
#   #
##  #
</code>```

Aside

This is the second of several crossword related challenges. I
plan to use a consistent set of file-formats throughout and to
build up a respectable suite of crossword related utilities in
the process. For instance a subsequent puzzle will call for
printing a ASCII version of the crossword based on the input and
output of this puzzle.

Previous challenges in this series:

Crossword numbering

答:
Ruby - <s>215</s> 207

```<code>t,*d=$<.map &:chop;n,d,e=t.size+1,(d*S=?#).gsub(/[^#]/,W=" "),->c,i{puts [c,i/n+1,i%n+1]*" ";exit 1}
0.upto(d.size-1){|i|d[i]==d[-i-1]||e[?R,i];d[i]==W&&(d[i-1]!=W&&d[i+1]!=W||d[i-n]!=W&&d[i+n]!=W)&&e[?L,i]}
</code>```

Ungolfed:

```<code>h, *g = $<.map &:chop
w = h.size+1
g = (g*?#).gsub(/[^#]/," ")
error = ->c,i{ puts [c,i/w+1,i% w+1]*" "; exit 1 }
0.upto(size-1) { |i|
        error[?R, i] if g[i] != g[-i-1]
        error[?L,i] if g[i]==" " && (g[i-1]!=" " && g[i+1]!=" " || g[i-w]!=" " && g[i+w] != " ")
}
</code>```

.

```<code>h, *g = $<.map &:chop
</code>```

This basically removes the last char (line break) of each input line by calling the chop method on them, and returning an array of the results.

h takes the first element of this array and *g takes the rest. So we end up with the first line in h and the crossword grid lines in g.

```<code>g = (g*?#).gsub(/[^#]/," ")
</code>```

g*?# joins (*) the array g with the "#" (?# is a character literal). This is the same as g.*("#"), or g.join("#"). Then every non # is replaced by a space.

For the symmetry check we just have to check if the char at every index is equals to the char at the opposite index in the string:

```<code>0.upto(g.size-1) { |i| if g[i] != g[g.size - i - 1]; error() }
</code>```

In Ruby we can index strings from the end using negative indexes (starting from -1 instead of 0), so that g[-i-1] is the opposite of g[i] in the string. This saves a few chars:

```<code>0.upto(g.size-1) { |i| if g[i] != g[-i-1]; error() }
</code>```

We can save a ; by using a conditional statement:

```<code>0.upto(g.size-1) { |i| error() if g[i] != g[-i-1] }
</code>```

In the golfed version we can save a few more chars:

```<code>0.upto(g.size-1){|i|g[i]==g[-i-1]||error()}
</code>```

In a previous version I used recursion for iterating over the string:

```<code>(f=->i{g[i]&&f[i+1]&&g[i]!=g[-i-1]&&error()})[0]
</code>```

An out of bound access to g returns nil, so once g[i] returns nil, this stops the iteration.

Output format:

```<code>{ L | R } line-number column-number
</code>```

L for length errors, and R for rotation error (so L 1 2 means length error at line 1, column 2)

ContentLicense: CC BY-SA 2.5

Title: Crossword grid verification

Body:
Ruby - <s>215</s> 207

t,*d=$<.map &:chop;n,d,e=t.size+1,(d*S=?#).gsub(/[^#]/,W=" "),->c,i{puts [c,i/n+1,i%n+1]*" ";exit 1}
0.upto(d.size-1){|i|d[i]==d[-i-1]||e[?R,i];d[i]==W&&(d[i-1]!=W&&d[i+1]!=W||d[i-n]!=W&&d[i+n]!=W)&&e[?L,i]}

Ungolfed:

h, *g = $<.map &:chop
w = h.size+1
g = (g*?#).gsub(/[^#]/," ")
error = ->c,i{ puts [c,i/w+1,i% w+1]*" "; exit 1 }
0.upto(size-1) { |i|
        error[?R, i] if g[i] != g[-i-1]
        error[?L,i] if g[i]==" " && (g[i-1]!=" " && g[i+1]!=" " || g[i-w]!=" " && g[i+w] != " ")
}

.

h, *g = $<.map &:chop

This basically removes the last char (line break) of each input line by calling the chop method on them, and returning an array of the results.

h takes the first element of this array and *g takes the rest. So we end up with the first line in h and the crossword grid lines in g.

g = (g*?#).gsub(/[^#]/," ")

g*?# joins (*) the array g with the "#" (?# is a character literal). This is the same as g.*("#"), or g.join("#"). Then every non # is replaced by a space.

For the symmetry check we just have to check if the char at every index is equals to the char at the opposite index in the string:

0.upto(g.size-1) { |i| if g[i] != g[g.size - i - 1]; error() }

In Ruby we can index strings from the end using negative indexes (starting from -1 instead of 0), so that g[-i-1] is the opposite of g[i] in the string. This saves a few chars:

0.upto(g.size-1) { |i| if g[i] != g[-i-1]; error() }

We can save a ; by using a conditional statement:

0.upto(g.size-1) { |i| error() if g[i] != g[-i-1] }

In the golfed version we can save a few more chars:

0.upto(g.size-1){|i|g[i]==g[-i-1]||error()}

In a previous version I used recursion for iterating over the string:

(f=->i{g[i]&&f[i+1]&&g[i]!=g[-i-1]&&error()})[0]

An out of bound access to g returns nil, so once g[i] returns nil, this stops the iteration.

Output format:

{ L | R } line-number column-number

L for length errors, and R for rotation error (so L 1 2 means length error at line 1, column 2)


问:
Sort a list of numbers
About Code-Bowling:

In golf, you try to get the lowest score (smallest application, most elegant, etc). In Bowling, you try to get the highest score. So if you follow, the goal of a Code-Bowling challenge is to make the biggest, most bastardized, hardest to maintain piece of code that still meets the requirements of the challenge. However, there's no point in making source longer just for the sake of it. It needs to seem like that added length was from design and not just padding.

The Challenge:

Create a program that sorts a list of numbers in ascending order.

Example:

Input: 1, 4, 7, 2, 5

Output: 1, 2, 4, 5, 7

Code: Obviously this wouldn't be a good answer, since there aren't many WTFs in there

```<code>function doSort(array $input) {
    sort($input);
    return $input;
}
</code>```

Rules:

There are no real rules.  As long as the program functions, have at it!

Remember: This is code-bowling, not golf.  The objective is to make the worst, most bastardized code that you can!  Bonus points for code that looks good, but is actually deceptively evil...

答:
Bogobogosort in Python

```<code>import random
import copy

def isSorted(list):
    newlist = copy.deepcopy(list)
    while True:
        newlist[:len(newlist)-1] = bogobogosort(newlist[:len(newlist)-1])
        if newlist[len(newlist)-2] < newlist[len(newlist)-1]:
            break
        random.shuffle(newlist)
    return newlist == list

def bogobogosort(list):
    ret = copy.deepcopy(list)
    if (len(ret) > 1):
        while not isSorted(ret):
            random.shuffle(ret)
    return ret
</code>```

Algorithm invented by David Morgan-Mar.

Warning: don't try this with any list larger than 5 elements. Even 5 is very slow.

Title: Sort a list of numbers

Body:
Bogobogosort in Python

import random
import copy

def isSorted(list):
    newlist = copy.deepcopy(list)
    while True:
        newlist[:len(newlist)-1] = bogobogosort(newlist[:len(newlist)-1])
        if newlist[len(newlist)-2] < newlist[len(newlist)-1]:
            break
        random.shuffle(newlist)
    return newlist == list

def bogobogosort(list):
    ret = copy.deepcopy(list)
    if (len(ret) > 1):
        while not isSorted(ret):
            random.shuffle(ret)
    return ret

Algorithm invented by David Morgan-Mar.

Warning: don't try this with any list larger than 5 elements. Even 5 is very slow.


答:
JavaScript (ES6), 106 bytes

```<code>f=(n,a="03354435543668877998")=>n-4&&1+f(7*(n>99)-(-a[n/100|0]-(a[n%=100]||a[n%10])-"0066555766"[n/10|0]))
</code>```

Strings seem to be the best way to encode the length, despite the numeric conversion overhead.

Title: Distance to four

Body:
JavaScript (ES6), 106 bytes

f=(n,a="03354435543668877998")=>n-4&&1+f(7*(n>99)-(-a[n/100|0]-(a[n%=100]||a[n%10])-"0066555766"[n/10|0]))

Strings seem to be the best way to encode the length, despite the numeric conversion overhead.


问:
What's your next move?
This challenge is to write a minimax function in a language of your choice, to output the next best move in an NxN game of tic-tac-toe given the current board state. The board input can be accepted as a Matrix, 2D Collection or anything else that makes sense to you, but adheres to the rules. The output being the next best move for whoever's turn it is currently, where X is considered to have started.

Quick Background on the Minimax Algorithm

The basic idea of the minimax algorithm is to enumerate all possible outcomes as a DAG then weight them by the benefit that the sequence of moves has to the player, keyed by the first move made. All possible outcomes are then 'bucketed' by the first move, and are scored based on the sum of all outcomes (-1 for a loss, 0 for a tie and a 1 for a win). In implementations that require multiple players to play, you enumerate all possible moves by the player, and all possible responses by the opponents as well. For instance, in a game of tic-tac-toe (after the first move) there are 8 possible first moves you can make, and they all may seem equal when only analyzing the next turn. But by iterating through all possible outcomes for each possible set of moves that results in a final outcome and summing them all up, we can get a score for our next move, and have a basis for our choices.

For a better, more in-depth and contextual summary of the mini-max algorithm in terms of tic-tac-toe, read more here: http://neverstopbuilding.com/minimax

XKCD (3x3 Solution Only)

The Rules

Any language can be used, but no external minimax libraries are allowed.

Output can be a coordinate (0-n,0-n) or a number (1-n*n) indicative of the best next move.

In addition to this, you must be able to identify when the best case scenario is a loss or a tie instead of a win.

The way you denote a loss or a tie is, once again, up to you.

Input must use the traditional X and O, and you must assume X moves first; blank spaces can be represented by anything.

You may assume any inputs coming into your program have n O's and n+1 X's, in other words you may assume you're getting a well-formed board.

The current state of the board must be the only input to your program, if you are using recursion, helper methods must be made to facilitate the input requirements. See https://codegolf.stackexchange.com/a/92851/59376 for clarification.

Any value of 10 >= n >= 1 must be supported; if your program "times out" for n > 10, I find this acceptable as well, as some languages have significantly lower processing power (Especially using web-facing consoles).

Judging

This is code-golf, so the lowest byte-count of the program wins and standard loopholes are universally disallowed.

In the case of a tie, the program that supports the largest 'n' will win.

Example Inputs

2x2

```<code>[[X,O]
 [-,-]]
</code>```

Output: 2 or [0,1]  (3 or [1,1] would also be arguably correct)
(Some form of indication of the location, arbitrary as long as you can easily explain the format you used)

3x3

```<code>[[X,O,X]
 [O,X,-]
 [-,-,-]]
</code>```

Output: -1 (Loss)

Once again any input format you want is allowed, but X's and O's must be used, the examples provided were not meant to constrain to that format, just to inspire.

答:
Perl, <s>101</s> 98 bytes

Includes +4 for -0p

Run with the input on STDIN

```<code>tictactoe.pl
OXO
---
--X
^D
</code>```

Output is the same diagram, but with each move updated with its status, 1 represents a win, 2 represents a draw and 3 represents a loss. For this case that would be

```<code>OXO
223
21X
</code>```

so 3 moves draw, 1 wins and 1 loses
(I'll update the solution if this output format is unacceptable, but the basic code will remain the same)

tictactoe.pl:

```<code>#!/usr/bin/perl -0p
m%@{[map"O.{$_}"x"@-"."O|",1-/.(
)(.)/,@-]}Z%sx||s%-%$_="$`X$'";y/XO/OX/;do$0%eg?/1/?3:1+/2/:2
</code>```

This is already painfully slow and uses lots of memory for the empty 3*3 board (why actually, the recursion doesn't go that deep. Must be some memory leak). Adding memoizing costs 6 bytes but is a lot saner:

```<code>#!/usr/bin/perl -0p
$$_||=m%@{[map"O.{$_}"x"@-"."O|",1-/.(\n)(.)/,@-]}Z%sx||s%-%$_="$`X$'";y/XO/OX/;do$0%eg?/1/?3:1+/2/:2
</code>```

Title: What's your next move?

Body:
Perl, <s>101</s> 98 bytes

Includes +4 for -0p

Run with the input on STDIN

tictactoe.pl
OXO
---
--X
^D

Output is the same diagram, but with each move updated with its status, 1 represents a win, 2 represents a draw and 3 represents a loss. For this case that would be

OXO
223
21X

so 3 moves draw, 1 wins and 1 loses
(I'll update the solution if this output format is unacceptable, but the basic code will remain the same)

tictactoe.pl:

#!/usr/bin/perl -0p
m%@{[map"O.{$_}"x"@-"."O|",1-/.(
)(.)/,@-]}Z%sx||s%-%$_="$`X$'";y/XO/OX/;do$0%eg?/1/?3:1+/2/:2

This is already painfully slow and uses lots of memory for the empty 3*3 board (why actually, the recursion doesn't go that deep. Must be some memory leak). Adding memoizing costs 6 bytes but is a lot saner:

#!/usr/bin/perl -0p
$$_||=m%@{[map"O.{$_}"x"@-"."O|",1-/.(\n)(.)/,@-]}Z%sx||s%-%$_="$`X$'";y/XO/OX/;do$0%eg?/1/?3:1+/2/:2


问:
Decipher Neurotic Frogs

Decipher Neurotic Frogs

Now that Puzzling.SE has finally cracked my amphibian-obsessed cipher, let's write a program or function to decrypt it!

(If you want to look at the puzzle before having it spoiled for you, click the above link now.)

How the cipher works

In Neurotic Frogs Ought To Relax In Mud Baths ("Neurotic Frogs" for short), every letter is encrypted as one or two words:

The length of a non-italicized word represents a letter.

neurotic => 8 letters => H

frogs => 5 letters => E

perpendicular => 13 letters = M

A word that contains italics modifies the following word, adding 10 if the italicized word was odd in length or 20 if the italicized word was even in length. Any or all of the word may be italicized. An italicized word is always followed by a non-italicized word.

*o*ught to => odd, 2 => 12 => L

lo*u*nging calms => even, 5 => 25 => Y

Every word of plaintext corresponds to a sentence of ciphertext, and every sentence of plaintext corresponds to a paragraph of ciphertext.

Input format

Your program or function shall input a message in Neurotic Frogs, formatted in Markdown. The input will consist only of printable ASCII and newlines.

Words are runs of characters that match the regex [A-Za-z0-9'].

Numbers and letters both count toward the length of a word. QB64 represents D.

NOTE: Apostrophes do not count toward the length of a word. Isn't represents D, not E.

Italicized letters are wrapped in a pair of asterisks (*letters*).

One or more consecutive letters may be italicized, up to an entire word (masseus*es*, *all*); multiple non-consecutive letters in a word may also be italicized (g*e*n*e*rates).

Italics never span multiple words, never include punctuation, and never include apostrophes.

Unpaired asterisks and multiple adjacent asterisks will never occur.

Punctuation is any of the following characters: .,?!:;-()".

Words within a sentence are separated by one or more punctuation characters and/or a single space. Examples: *all* welcomed, toad*s*, newts, Ever*y*one--frogs, cap... bliss, they're (I

Sentences end with one or more punctuation characters and are separated by a double space: Th*e* Montgomery A*m*phibian Salon!  Come luxuriate today!

Paragraphs are separated by a single newline. (The last sentence of a paragraph still has one or more punctuation characters at the end.)

Other characters will not appear in input and do not need to be handled.

Your code may, at your discretion, expect input to have a single trailing newline.

Output format

The result of decrypting the input will be one or more sentences. Letters of plaintext may be any combination of upper- and lowercase. Words within a sentence must be separated by single spaces. Sentences must end with a period (.) and be separated by a single space. You may output a trailing space after the last sentence. Your output will all be on one line, but you may output a trailing newline.

Miscellaneous details

Your code may use any of the standard input and output methods. It must receive input as a multiline string, not a list or other data structure, and it must output a string.

The shortest code in bytes wins!

Test cases

```<code>-->
Neurotic Frogs *O*ught To Rel*a*x In *M*ud Baths!
<--
HELLO.

-->
Business standards all*o*w only *adult* amphibians.
<--
HINT.

-->
Rejoice, *a*ll frogs an*d* toads also!  Montgomery Sal*o*n opens up!  Ha*pp*y throng fill*s* street ecstatically!
<--
GOOD JOB PPL.

-->
I like 3.1415926535897.
IM*O*, it's a *b*la*st*, yeah!
<--
ADAM. MAN.

-->
*I*, happily, *th*anks 2 u *e*ditin*g* specific wor*ding*--clarifying a *bit*--betterment :D!
<--
QUARTATA.

-->
Perpendicular l*ou*nging calms.  *A* frog, a m*u*d cap... bliss!  Wallowing g*e*n*e*rates happiness.  Amphibian sp*a* isn't expensive--seventy d*o*llars--cheap!  That'*s* not *a* large e*x*pens*e* from an*y* discerning fr*o*g's money, unlik*e* Super 8.
Ever*y*one--frogs, toad*s*, newts, *a*nd salamanders!  G*e*t a wonderful shiat*s*u, or recei*v*e an other kind.  Masseus*es* are her*e* today!  Invite a fianc*e*e, supervisor, roommate, niece: *all* welcomed!
Y*o*u simply ne*v*er believed these p*o*ssibilitie*s*; they're (I *swear*) absolute truth!  Th*e* Montgomery A*m*phibian Salon!  Come luxuriate today!
<--
MY NAME IS INIGO MONTOYA. YOU KILLED MY FATHER. PREPARE TO DIE.
</code>```

答:
JavaScript (ES6), <s>172</s> <s>169</s> <s>157</s> 150 bytes

Saved 10 bytes thanks to @Neil

```<code>x=>x.match(/[\w'*]+|\s+/g).map(y=>y[0]==" "?y[1]:y==`
`?". ":/\*/.test(y,l+=y.match(/\w/g).length)?(l=l%2*10+19,""):l.toString(36,l=9),l=9).join``+"."
</code>```

Can probably be further improved. Outputs in all lowercase.

Title: Decipher Neurotic Frogs

Body:
JavaScript (ES6), <s>172</s> <s>169</s> <s>157</s> 150 bytes

Saved 10 bytes thanks to @Neil

x=>x.match(/[\w'*]+|\s+/g).map(y=>y[0]==" "?y[1]:y==`
`?". ":/\*/.test(y,l+=y.match(/\w/g).length)?(l=l%2*10+19,""):l.toString(36,l=9),l=9).join``+"."

Can probably be further improved. Outputs in all lowercase.


答:
Python 2.7, 101 113 bytes

Edit: Added function definition

```<code>def f(n):
 m=n-1
 print "      \ "*n+"\n"+"  ___/o>"*m+"  ___/->\n"+'-(___)" '*n+"\n"+" '' ''  "*m+" ``"*2
</code>```

de-golfified:

```<code>m=n-1              # Replacement variable. Saves 6 bytes
"      \ "*n+"\n"+ # Print ears, same for all goats!
"  ___/o>"*m+      # Print eyes of n-1 awake goat
"  ___/->\n"+      # Print eye of sleeping goat
'-(___)" '*m+      # Print body of n-1 awake goat
',(___)"\n'+       # Print body of sleeping goat
+" '' ''  "*m+     # Print the legs of n-1 awake goat
" ``"*2            # Print legs of sleeping goat using *2 operator to save 1 byte
</code>```

Note Python2.7 is one byte shorter than Python3 due to that it doesn't need parentesis when printing.

Title: Counting Goats to Sleep

Body:
Python 2.7, 101 113 bytes

Edit: Added function definition

def f(n):
 m=n-1
 print "      \ "*n+"\n"+"  ___/o>"*m+"  ___/->\n"+'-(___)" '*n+"\n"+" '' ''  "*m+" ``"*2

de-golfified:

m=n-1              # Replacement variable. Saves 6 bytes
"      \ "*n+"\n"+ # Print ears, same for all goats!
"  ___/o>"*m+      # Print eyes of n-1 awake goat
"  ___/->\n"+      # Print eye of sleeping goat
'-(___)" '*m+      # Print body of n-1 awake goat
',(___)"\n'+       # Print body of sleeping goat
+" '' ''  "*m+     # Print the legs of n-1 awake goat
" ``"*2            # Print legs of sleeping goat using *2 operator to save 1 byte

Note Python2.7 is one byte shorter than Python3 due to that it doesn't need parentesis when printing.


答:
PHP ,117 Bytes

```<code>if(preg_match("#^(1+|(10*1))0*$#",$b=decbin($k=$argv[1]),$t))echo($l=strlen($b))-($t[2]?1:0).",",$l+~strrpos($b,"1");
</code>```

Extended version 4 Cases

```<code>$l=strlen($b=decbin($k=$argv[1]));
// Case 1: n=2(n-1)=n+n or n=n*(2-1)=2n-n
if(preg_match('#^100*$#',$b))echo($l-2).'a+'.($l-2).':'.$l.'a-'.($l-1);
// Case 2: n-m
elseif(preg_match('#^1+0*$#',$b)){echo $l.'b-',strpos($b,"0")?$l-strpos($b,"0"):0;}
// Case 3: n+m
elseif(preg_match('#^10*10*$#',$b))echo ($l-1).'c+',$l-strrpos($b,"1")-1;
else echo "Nothing";
</code>```

the short version union Case 1 and 3 and makes a Difference to Case 3 and in both versions Case 4 gives no output.

Title: Sum or difference of two powers of two

Body:
Your challenge, should you choose to accept it, is, given an integer K >= 1, find non-negative integers A and B  such that at least one of the two conditions following hold:

K = 2^A + 2^B

K = 2^A - 2^B

If there does not exist such A and B, your program may behave in any fashion. (To clarify, A and B can be equal.)

Test cases

There are often multiple solutions to a number, but here are a few:

```<code>K => A, B
1 => 1, 0
15 => 4, 0                      ; 16 - 1 = 15
16 => 5, 4                      ; 32 - 16 = 16; also 3, 3: 8 + 8 = 16
40 => 5, 3                      ; 2^5 + 2^3 = 40
264 => 8, 3
17179867136 => 34, 11           ; 17179869184 - 2048 = 17179867136
</code>```

The last test case, 17179867136, must run in under 10 seconds on any relatively modern machine. This is a code golf, so the shortest program in bytes wins. You may use a full program or a function.

Body:
PHP ,117 Bytes

if(preg_match("#^(1+|(10*1))0*$#",$b=decbin($k=$argv[1]),$t))echo($l=strlen($b))-($t[2]?1:0).",",$l+~strrpos($b,"1");

Extended version 4 Cases

$l=strlen($b=decbin($k=$argv[1]));
// Case 1: n=2(n-1)=n+n or n=n*(2-1)=2n-n
if(preg_match('#^100*$#',$b))echo($l-2).'a+'.($l-2).':'.$l.'a-'.($l-1);
// Case 2: n-m
elseif(preg_match('#^1+0*$#',$b)){echo $l.'b-',strpos($b,"0")?$l-strpos($b,"0"):0;}
// Case 3: n+m
elseif(preg_match('#^10*10*$#',$b))echo ($l-1).'c+',$l-strrpos($b,"1")-1;
else echo "Nothing";

the short version union Case 1 and 3 and makes a Difference to Case 3 and in both versions Case 4 gives no output.


Title: Decipher Neurotic Frogs

Body:
Decipher Neurotic Frogs

Now that Puzzling.SE has finally cracked my amphibian-obsessed cipher, let's write a program or function to decrypt it!

(If you want to look at the puzzle before having it spoiled for you, click the above link now.)

How the cipher works

In Neurotic Frogs Ought To Relax In Mud Baths ("Neurotic Frogs" for short), every letter is encrypted as one or two words:

The length of a non-italicized word represents a letter.

neurotic => 8 letters => H

frogs => 5 letters => E

perpendicular => 13 letters = M

A word that contains italics modifies the following word, adding 10 if the italicized word was odd in length or 20 if the italicized word was even in length. Any or all of the word may be italicized. An italicized word is always followed by a non-italicized word.

*o*ught to => odd, 2 => 12 => L

lo*u*nging calms => even, 5 => 25 => Y

Every word of plaintext corresponds to a sentence of ciphertext, and every sentence of plaintext corresponds to a paragraph of ciphertext.

Input format

Your program or function shall input a message in Neurotic Frogs, formatted in Markdown. The input will consist only of printable ASCII and newlines.

Words are runs of characters that match the regex [A-Za-z0-9'].

Numbers and letters both count toward the length of a word. QB64 represents D.

NOTE: Apostrophes do not count toward the length of a word. Isn't represents D, not E.

Italicized letters are wrapped in a pair of asterisks (*letters*).

One or more consecutive letters may be italicized, up to an entire word (masseus*es*, *all*); multiple non-consecutive letters in a word may also be italicized (g*e*n*e*rates).

Italics never span multiple words, never include punctuation, and never include apostrophes.

Unpaired asterisks and multiple adjacent asterisks will never occur.

Punctuation is any of the following characters: .,?!:;-()".

Words within a sentence are separated by one or more punctuation characters and/or a single space. Examples: *all* welcomed, toad*s*, newts, Ever*y*one--frogs, cap... bliss, they're (I

Sentences end with one or more punctuation characters and are separated by a double space: Th*e* Montgomery A*m*phibian Salon!  Come luxuriate today!

Paragraphs are separated by a single newline. (The last sentence of a paragraph still has one or more punctuation characters at the end.)

Other characters will not appear in input and do not need to be handled.

Your code may, at your discretion, expect input to have a single trailing newline.

Output format

The result of decrypting the input will be one or more sentences. Letters of plaintext may be any combination of upper- and lowercase. Words within a sentence must be separated by single spaces. Sentences must end with a period (.) and be separated by a single space. You may output a trailing space after the last sentence. Your output will all be on one line, but you may output a trailing newline.

Miscellaneous details

Your code may use any of the standard input and output methods. It must receive input as a multiline string, not a list or other data structure, and it must output a string.

The shortest code in bytes wins!

Test cases

```<code>-->
Neurotic Frogs *O*ught To Rel*a*x In *M*ud Baths!
<--
HELLO.

-->
Business standards all*o*w only *adult* amphibians.
<--
HINT.

-->
Rejoice, *a*ll frogs an*d* toads also!  Montgomery Sal*o*n opens up!  Ha*pp*y throng fill*s* street ecstatically!
<--
GOOD JOB PPL.

-->
I like 3.1415926535897.
IM*O*, it's a *b*la*st*, yeah!
<--
ADAM. MAN.

-->
*I*, happily, *th*anks 2 u *e*ditin*g* specific wor*ding*--clarifying a *bit*--betterment :D!
<--
QUARTATA.

-->
Perpendicular l*ou*nging calms.  *A* frog, a m*u*d cap... bliss!  Wallowing g*e*n*e*rates happiness.  Amphibian sp*a* isn't expensive--seventy d*o*llars--cheap!  That'*s* not *a* large e*x*pens*e* from an*y* discerning fr*o*g's money, unlik*e* Super 8.
Ever*y*one--frogs, toad*s*, newts, *a*nd salamanders!  G*e*t a wonderful shiat*s*u, or recei*v*e an other kind.  Masseus*es* are her*e* today!  Invite a fianc*e*e, supervisor, roommate, niece: *all* welcomed!
Y*o*u simply ne*v*er believed these p*o*ssibilitie*s*; they're (I *swear*) absolute truth!  Th*e* Montgomery A*m*phibian Salon!  Come luxuriate today!
<--
MY NAME IS INIGO MONTOYA. YOU KILLED MY FATHER. PREPARE TO DIE.
</code>```

Body:
PHP, <s>231</s> <s>226</s> 228 bytes

for a start

<?preg_match_all("#([\w\*']+)([^\w\*']*)#",$argv[1],$m,2);foreach($m as list(,$a,$b)){$e=strlen(strtr($a,["'"=>""]))+$d;if(!$d=strstr($a,'*')?$e%2*10:0)echo chr($e+64),strpos(".$b","
")?". ":(strpos(".$b","  ")?" ":"");}echo".";

Save to file, rund php <scriptpath> <text>. Escape newlines in the text to make it work in shell.