问:
Golf all the 16 logic gates with 2 inputs and 1 output!
For example, the gate A and B is a logic gate with 2 inputs and 1 output.

There are exactly 16 of them, because:

each logic gate takes two inputs, which can be truthy or falsey, giving us 4 possible inputs

of the 4 possible inputs, each can have an output of truthy and falsey

therefore, there are 2^4 possible logic gates, which is 16.

Your task is to write 16 programs/functions which implement all of them separately.

Your functions/programs must be independent.

They are valid as long as they output truthy/falsey values, meaning that you can implement A or B in Python as lambda a,b:a+b, even if 2 is produced for A=True and B=True.

Score is total bytes used for each function/program.

List of logic gates

0,0,0,0 (false)

0,0,0,1 (and)

0,0,1,0 (A and not B)

0,0,1,1 (A)

0,1,0,0 (not A and B)

0,1,0,1 (B)

0,1,1,0 (xor)

0,1,1,1 (or)

1,0,0,0 (nor)

1,0,0,1 (xnor)

1,0,1,0 (not B)

1,0,1,1 (B implies A)

1,1,0,0 (not A)

1,1,0,1 (A implies B)

1,1,1,0 (nand)

1,1,1,1 (true)

Where the first number is the output for A=false, B=false,
the second number is the output for A=false, B=true,
the third number is the output for A=true, B=false,
the fourth number is the output for A=true, B=true.

Leaderboard

var QUESTION_ID=82938,OVERRIDE_USER=48934;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/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+(?:\.\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

```

答:
Hexagony, 89 bytes

Thanks to FryAmTheEggman for some necessary inspiration for the XOR solution.

```<code>0000 !@
0001 ?.|@!
0010 #?#!)@
0011 ?!@
0100 +?|@!?
0101 ??!@
0110 ?<@!!<_\~(
0111 ?<<@!
1000 )\!#?@{
1001 (~?/@#!
1010 ??|@!)
1011 \#??!1@
1100 ?(~!@
1101 ?.|@!)
1110 ?$@#)!<
1111 1!@
</code>```

All programs use 0 for false and 1 for true.

Try it online! This is not a test suite, you'll have to copy in the different programs and inputs yourself.

The above solution is within 2-bytes of optimality (unless we relax the truthy/falsy interpretation, I guess). I've let a brute force search run for close to two days over all programs that fit into side-length 2, i.e. up to 7 bytes (not quite all programs - I made a few assumptions on what every valid program needs and what no valid program could have). The search found solutions for 15 of the 16 possible gates - and often a lot more than just one. You can find a list of all the alternative solutions in this pastebin where I've also grouped them by equivalent behaviour. The ones I'm showing above I've selected because they are either the simplest or the most interesting solution, and I'll add explanations for them tomorrow.

As for the 16th gate: XOR is the only gate that can apparently not be implemented in 7 bytes. A brute force search over larger programs is unfortunately not feasible with the code I currently have. So XOR had to be written by hand. The shortest I've found so far is the above 10-byte program, which is based on a failed (but very close) attempt by FryAmTheEggman. It's possible that an 8-byte or 9-byte solution exists, but other than that, all the solutions should indeed be optimal.

Explanations

Warning: wall of text. On the off-chance anyone's interested how these highly compressed Hexagony programs actually work, I've included explanations for each of them below. I've tried to choose the simplest solution for each gate in cases where more than one optimal program exists, in order to keep the explanations reasonably short. However, some of them still boggle the mind, so I thought they deserve a bit more elaboration.

0000: False

I don't think we'll need a diagram for this one:

```<code> ! @
. . .
 . .
</code>```

Since the entire memory grid is initialised to zeros, ! simply prints a zero and @ terminates the program.

This is also the only 2-byte solution.

0001: And

```<code> ? .
| @ !
 . .
</code>```

This basically implements short-circuiting. The grey diagram below shows the beginning of the program, where the first input is read with ? and the instruction pointer (IP) wraps around to the the left corner where the | mirror reflects it. Now the corner acts as a conditional, such there are two different execution paths depending on the value of the first input. The red diagram shows the control flow for A = 0 and the green diagram for A = 1:

As you can see, when the A is 0, then we simply print it and terminate (remember that all . are no-ops). But when A is 1, then the IP traverses the first row again, reading B and printing that instead.

In total there are sixteen 5-byte solutions for this gate. Fourteen of those are essentially the same as the above, either using > instead of | or replacing the . with a command that's effectively a no-op, or putting ? in the second position:

```<code>?.|@!    .?|@!    ?=|@!    =?|@!    ?_|@!    _?|@!    ?0|@!
?.>@!    .?>@!    ?=>@!    =?>@!    ?_>@!    _?>@!    ?0>@!
</code>```

And then there are two other solutions (which are equivalent to each other). These also implement the same short-circuiting logic, but the execution paths are a bit crazier (and left as an exercise to the reader):

```<code>?<!@|
?<!@<
</code>```

0010: A and not B

```<code> # ?
# ! )
 @ .
</code>```

This also implements a form of short-circuiting, but due to the use of # the control flow is much trickier. # is a conditional IP switch. Hexagony actually comes with six IPs labelled 0 to 5, which start in the six corners of the grid, pointing along their clockwise edge (and the program always begins with IP 0). When a # is encountered, the current value is taken modulo 6, and control flow continues with the corresponding IP. I'm not sure what fit of madness made me add this feature, but it certainly allows for some surprising programs (like this one).

We will distinguish three cases. When A = 0, the program is fairly simple, because the value is always 0 when # is encountered such that no IP-switching takes place:

# does nothing, ? reads A (i.e. also does nothing), # still does nothing, ! prints the 0, ) increments it (this is important, otherwise the IP would not jump to the third line), @ terminates the program. Simple enough. Now let's consider the case (A, B) = (1, 0):

The red path still corresponds to IP 0, and I've added the green path for IP 1. We see that after ? reads A (1 this time), the # switches to the IP that starts in the top right corner. That means ? can read B (0). Now ) increments that to 1, such that the # in the top left corner does nothing and we remain with IP 1. The ! prints the 1 and the IP wraps around the left diagonal. # still does nothing and @ terminates the program.

Finally, the really weird case where both inputs are 1:

This time, the second input is also 1 and ) increments it to 2. That means the # in the top left corner causes another IP switch to IP 2, indicate in blue. On that path, we first increment it further to 3 (although that's irrelevant) and then pass the ? a third time. Since we've now hit EOF (i.e. the input is exhausted), ? returns 0, ! prints that, and @ terminates the program.

Notably, this is the only 6-byte solution for this gate.

0011: A

```<code> ? !
@ . .
 . .
</code>```

This is simple enough that we won't need a diagram: ? reads A, ! prints it, @ terminates.

This is the only 3-byte solution for this gate. (In principle, it would also be possible to do ,;@, but the search didn't include ;, because I don't think it can ever save bytes over ! for this task.)

0100: B and not A

```<code> + ?
| @ !
 ? .
</code>```

This one is a lot simpler than its "brother" 0010. The control flow is actually the same as we've seen above for 0001 (And). If A = 0, then the IP traverses the lower line, reading B and printing that before terminating. If A = 1 then the IP traverses the first line again, also reading B, but the + adds two unused memory edges so all it does is reset the current value to 0, so that ! always prints 0.

There are quite a lot of 6-byte alternatives to this (42 in total). First, there's a ton of solutions equivalent to the above. We can again choose freely between | and >, and + can be replaced with any other command that gives us an empty edge:

```<code>"?|@!?    &?|@!?    '?|@!?    *?|@!?    +?|@!?    -?|@!?    ^?|@!?    {?|@!?    }?|@!?
"?>@!?    &?>@!?    '?>@!?    *?>@!?    +?>@!?    -?>@!?    ^?>@!?    {?>@!?    }?>@!?
</code>```

In addition, we can also use ] instead of ?. ] moves to the next IP (i.e. selects IP 1), so that this branch instead reuses the ? in the top right corner. That gives another 18 solutions:

```<code>"?|@!]    &?|@!]    '?|@!]    *?|@!]    +?|@!]    -?|@!]    ^?|@!]    {?|@!]    }?|@!]
"?>@!]    &?>@!]    '?>@!]    *?>@!]    +?>@!]    -?>@!]    ^?>@!]    {?>@!]    }?>@!]
</code>```

And then there's six other solutions that all work differently with varying levels of craziness:

```<code> ! @
. . .
 . .
</code>```0

0101: B

```<code> ! @
. . .
 . .
</code>```1

Woohoo, another simple one: read A, read B, print B, terminate. There are actually alternatives to this though. Since A is only a single character, we can also read it with ,:

```<code> ! @
. . .
 . .
</code>```2

And there's also the option of using a single ? and using a mirror to run through it twice:

```<code> ! @
. . .
 . .
</code>```3

0110: Xor

```<code> ! @
. . .
 . .
</code>```4

Like I said above, this was the only gate that wouldn't fit in side-length 2, so this a handwritten solution by FryAmTheEggman and myself, and there's a good chance that it isn't optimal. There are two cases to distinguish. If A = 0 the control flow is fairly simple (because in that case we only need to print B):

We start on the red path. ? reads A, < is a branch which deflects the zero left. The IP wraps to the bottom, then _ is another mirror, and when the IP hits the corner, it wraps to the top left corner and continues on the blue path. ? reads B, ! prints it. Now ( decrements it. This is important because it ensures that the value is non-positive (it's either 0 or -1 now). That makes IP wrap to the to right corner, where @ terminates the program.

When A = 1 things get a bit trickier. In that case we want to print not B, which in itself isn't too difficult, but the execution path is a bit trippy.

This time, the < deflects the IP right and then next < just acts as a mirror. So the IP traverses the same path in reverse, reading B when it encounters ? again. The IP wraps around to the right corner and continues on the green path. It next encounters (~ which is "decrement, multiply by -1", which swaps 0 and 1 and therefore computes not B. \ is just a mirror and ! prints the desired result. Then ? tries to return another number but returns zero. The IP now continues in the bottom left corner on the blue path. ( decrements, < reflects, ( decrements again, so that the current value is negative when the IP hits the corner. It moves across the bottom right diagonal and then finally hits @ to terminate the program.

0111: Or

```<code> ! @
. . .
 . .
</code>```5

More short-circuiting.

The A = 0 case (the red path) is a bit confusing here. The IP gets deflected left, wraps to the bottom left corner, gets immediately reflected by the < and returns to the ? to read B. It then wraps to the rigt corner, prints B with ! and terminates.

The A = 1 case (the green path) is a bit simpler. The < branch deflects the IP right, so we simply print the !, wrap back to the top left, and terminate at @.

There is only one other 5-byte solution:

```<code> ! @
. . .
 . .
</code>```6

It works essentially the same, but the actual execution paths are quite different and it uses a corner for branching instead of a <.

1000: Nor

```<code> ! @
. . .
 . .
</code>```7

This might be my favourite program found in this search. The coolest thing is that this implementation of nor actually works for up to 5 inputs. I'll have to get into the details of the memory model a bit to explain this one. So as a quick refresher, Hexagony's memory model is a separate hexagonal grid, where each edge holds an integer value (initially all zero). There's a memory pointer (MP) which indicates an edge and a direction along that edge (such that there's two neighboring edges in front of and behind the current edge, with meaningful left and right neighbours). Here is a diagram of the edges we'll be using, with the MP starting out as shown in red:

Let's first consider the case where both inputs are 0:

We start on the grey path, which simply increments edge A to 1 so that the # switches to IP 1 which is the blue path, starting in the top right corner. \ does nothing there and ? reads an input. We wrap to the top left corner where ) increments that input. Now as long as the input is zero, this will result in a 1, so that # doesn't do anything. Then { moves the MP to the left, i.e. on the first iteration from A to B. Since this edge still has its initial zero the IP wraps back to the top right corner and on a new memory edge. So this loop will continue as long as ? reads zeros, moving the MP around the hexagon from B to C to D and so on. It doesn't matter whether ? returns a zero because it was an input or because it was EOF.

After six iterations through this loop, { returns to A. This time, the edge already holds the value 1 from the very first iteration, so the IP wraps to the left corner and continues on the green path instead. ! simply prints that 1 and @ terminates the program.

Now what if any of the inputs is 1?

Then ? reads that 1 at some point and ) increments it to 2. That means # will now switch IPs again and we'll continue in the right corner on the red path. ? reads another input (if there is one), which doesn't really matter and { moves one edge further. This has to be an unused edge, hence this works for up to 5 inputs. The IP wraps to the top right where it's immediately reflected and wraps to the left corner. ! prints the 0 on the unused edge and # switches back to IP 0. That IP was still waiting around on the #, going southwest (grey path), so it immediately hits the @ and terminates the program.

In total there are seven 7-byte solutions for this gate. 5 of them work the same as this and simply use other commands to move to an unused edge (and may walk around a different hexagon or in a different direction):

```<code> ! @
. . .
 . .
</code>```8

And there is one other class of solutions which only works with two inputs, but whose execution paths are actually even messier:

```<code> ! @
. . .
 . .
</code>```9

1001: Equality

```<code> ? .
| @ !
 . .
</code>```0

This also makes very clever use of conditional IP selection. We need to distinguish again between A = 0 and A = 1. In the first case we want to print not B, in the second we want to print B. For A = 0 we also distinguish the two cases for B. Let's start with A = B = 0:

We start on the grey path. (~ can be ignored, the IP wraps to the left corner (still on the grey path) and reads A with ?. ( decrements that, so we get -1 and IP wrap to the bottom left corner. Now like I said earlier, # takes the value modulo 6 before choosing he IP, so a value of -1 actually gets out IP 5, which starts in the left corner on the red path. ? reads B, ( decrements that as well so that we remain on IP 5 when we hit # again. ~ negates the -1 so that the IP wraps to the bottom right corner, prints the 1 and terminates.

Now if B is 1 instead, the current value will be 0 when we hit # the second time, so we switch back to IP 0 (now on the green path). That hits ? a third time, yielding 0, ! prints it and @ terminates.

Finally, the case where A = 1. This time the current value is already zero when we hit # for the first time, so this never switches to IP 5 in the first place. We simply continue immediately on the green path. ? now doesn't just give a zero but returns B instead. ! prints it and @ terminates again.

In total there are three 7-byte solutions for this gate. The other two work very differently (even from each other), and make even weirder use of #. In particular they read one or more values with , (reading a character code instead of an integer) and then use that value modulo 6 to pick an IP. It's pretty nuts.

```<code> ? .
| @ !
 . .
</code>```1

1010: Not B

```<code> ? .
| @ !
 . .
</code>```2

This one is fairly simple. The execution path is the horizontal branch we already know from and earlier. ?? reads A and then immediately B. After reflecting at | and branching, for B = 0 we will execute the bottom branch, where ) increments the value to 1 which is then printed by !. On the top branch (if B = 1) the ? simply reset the edge to 0 which is then also printed by !.

There are eight 6-byte programs for this gate. Four of them are pretty much the same, using either > instead of | or 1 instead of ) (or both):

```<code>??>@!)    ??>@!1    ??|@!)    ??|@!1
</code>```

Two use a single ? which is used twice due to a mirror. The negation then happens as we did for xor with either (~ or ~).

```<code>?>!)~@    ?>!~(@
</code>```

And finally, two solutions use a conditional IP switch, because why use the simple way if the convoluted one also works:

```<code>??#)!@    ??#1!@
</code>```

1011: B implies A

```<code> \ #
? ? !
 1 @
</code>```

This uses some rather elaborate IP switching. I'll start with the A = 1 case this time, because it's simpler:

We start on the grey path, which reads A with ? and then hits the #. Since A is 1 this switches to IP 1 (green path). The ! immediately prints that, the IP wraps to the top left, reads B (unnecessarily) and terminates.

When A = 0 things get a bit more interesting. First let's consider A = B = 0:

This time, the # does nothing and we remain on IP 0 (red path from that point onward). ? reads B and 1 turns it into a 1. After wrapping to the top left corner, we hit # again, so we end up on the green path after all, and print 1 as before, before terminating.

Finally, here is (A, B) = (0, 1), the false case:

Note that I've removed the initial grey path for clarity, but the program begins the same way, and we end up on the red path as before. So this time the second ? returns 1. Now we encounter the 1. At this point it's important to understand what digits actually do in Hexagony (so far we've only used them on zeros): when a digit is encountered, the current value is multiplied by 10 and then the digit is added. This is normally used to write decimal numbers verbatim into the source code, but it means that B = 1 is actually mapped to the value 11. So when we hit #, this is taken modulo 6 to give 5 and hence we switch to IP 5 (instead of 1 as before) and continue on the blue path. Hitting ? a third time returns a zero, so ! prints that, and after another two ?, the IP wraps to the bottom right where the program terminates.

There are four 7-byte solutions to this and they all work differently:

```<code>#)/!?@$    <!?_@#1    \#??!1@    |/)#?@!
</code>```

1100: Not A

```<code> ? (
~ ! @
 . .
</code>```

Just a simple linear one: read A with ?, negate with (~, print with !, terminate with @.

There's one alternative solution, and that's negating with ~) instead:

```<code>?~)!@
</code>```

1101: A implies B

```<code>?.|@!    .?|@!    ?=|@!    =?|@!    ?_|@!    _?|@!    ?0|@!
?.>@!    .?>@!    ?=>@!    =?>@!    ?_>@!    _?>@!    ?0>@!
</code>```0

This is a lot simpler than the opposite implication we just talked about. It's again one of those horizontal branch programs, like the one for and. If A is 0, it simply gets incremented to 1 on the bottom branch and printed. Otherwise, the top branch is executed again where ? reads B and then ! prints that instead.

There's a ton of alternatives here (66 solutions in total), mostly due to free choice of effective no-ops. For a start we can vary the above solution in all the same ways we could for and and we can also choose between ) and 1:

```<code>?.|@!    .?|@!    ?=|@!    =?|@!    ?_|@!    _?|@!    ?0|@!
?.>@!    .?>@!    ?=>@!    =?>@!    ?_>@!    _?>@!    ?0>@!
</code>```1

And then there's a different version using conditional IP selection, where the first command can be chosen almost arbitrarily, and there is also a choice between ) and 1 for some of those options:

```<code>?.|@!    .?|@!    ?=|@!    =?|@!    ?_|@!    _?|@!    ?0|@!
?.>@!    .?>@!    ?=>@!    =?>@!    ?_>@!    _?>@!    ?0>@!
</code>```2

1110: Nand

```<code>?.|@!    .?|@!    ?=|@!    =?|@!    ?_|@!    _?|@!    ?0|@!
?.>@!    .?>@!    ?=>@!    =?>@!    ?_>@!    _?>@!    ?0>@!
</code>```3

The last complicated one. If you're still reading, you've almost made it. :) Let's look at A = 0 first:

? reads A and then we hit $. This is a jump command (like Befunge's #) which skips the next instruction so that we don't terminate on the @. Instead the IP continues at #. However since A is 0, this doesn't do anything. ) increments it to 1 so that the IP continues on the bottom path where the 1 is printed. The < deflects the IP to the right where it wraps to the left corner and the program terminates.

Next, when the input is (A, B) = (1, 0) we get this situation:

It's essentially the same as before except that at the # we switch to IP 1 (green path), but since B is 0 we switch back to IP 0 when we hit # a second time (now blue path), where it prints 1 as before.

Finally, the A = B = 1 case:

This time, when we # the second time, the current value is still 1 so that we don't change the IP again. The < reflects it and the third time we hit ? we get a zero. Hence the IP wraps to the bottom left where ! prints the zero and the program ends.

There are nine 7-byte solutions in total for this. The first alternative simply uses 1 instead of ):

```<code>?.|@!    .?|@!    ?=|@!    =?|@!    ?_|@!    _?|@!    ?0|@!
?.>@!    .?>@!    ?=>@!    =?>@!    ?_>@!    _?>@!    ?0>@!
</code>```4

Then there's two solutions that will do your head in with the amount of IP switching that's going on:

```<code>?.|@!    .?|@!    ?=|@!    =?|@!    ?_|@!    _?|@!    ?0|@!
?.>@!    .?>@!    ?=>@!    =?>@!    ?_>@!    _?>@!    ?0>@!
</code>```5

These actually blew my mind: the interesting part is that IP switching can be used as a deferred conditional. The language's IP-switching rules are such that the current IP makes another step before the switch happens. If that step happens to go through a corner, then the current value decides on which branch the IP will continue if we ever switch back to it. Exactly this happens when the input is A = B = 1. Although this is all consistent with how I designed the language, I was never aware of this implication of the spec, so it's nice when my language teaches me some new tricks :D.

Then there's a third solution whose amount of IP switching is even worse (although it doesn't make use of that deferred conditional effect):

```<code>?.|@!    .?|@!    ?=|@!    =?|@!    ?_|@!    _?|@!    ?0|@!
?.>@!    .?>@!    ?=>@!    =?>@!    ?_>@!    _?>@!    ?0>@!
</code>```6

And then there's another one:

```<code>?.|@!    .?|@!    ?=|@!    =?|@!    ?_|@!    _?|@!    ?0|@!
?.>@!    .?>@!    ?=>@!    =?>@!    ?_>@!    _?>@!    ?0>@!
</code>```7

And then there's these four equivalent solutions, which do use some non-conditional IP switching and instead implement all the logic via branches and corners:

```<code>?.|@!    .?|@!    ?=|@!    =?|@!    ?_|@!    _?|@!    ?0|@!
?.>@!    .?>@!    ?=>@!    =?>@!    ?_>@!    _?>@!    ?0>@!
</code>```8

1111: True

```<code>?.|@!    .?|@!    ?=|@!    =?|@!    ?_|@!    _?|@!    ?0|@!
?.>@!    .?>@!    ?=>@!    =?>@!    ?_>@!    _?>@!    ?0>@!
</code>```9

You've earned yourself something simple for the end: set edge to 1, print with !, terminate with @. :)

Of course, there's one alternative:

```<code>?<!@|
?<!@<
</code>```0

As usual, all control flow diagrams created with Timwi's HexagonyColorer and the memory diagram with his EsotericIDE.

Body:
Hexagony, 89 bytes

Thanks to FryAmTheEggman for some necessary inspiration for the XOR solution.

0000 !@
0001 ?.|@!
0010 #?#!)@
0011 ?!@
0100 +?|@!?
0101 ??!@
0110 ?<@!!<_\~(
0111 ?<<@!
1000 )\!#?@{
1001 (~?/@#!
1010 ??|@!)
1011 \#??!1@
1100 ?(~!@
1101 ?.|@!)
1110 ?$@#)!<
1111 1!@

All programs use 0 for false and 1 for true.

Try it online! This is not a test suite, you'll have to copy in the different programs and inputs yourself.

The above solution is within 2-bytes of optimality (unless we relax the truthy/falsy interpretation, I guess). I've let a brute force search run for close to two days over all programs that fit into side-length 2, i.e. up to 7 bytes (not quite all programs - I made a few assumptions on what every valid program needs and what no valid program could have). The search found solutions for 15 of the 16 possible gates - and often a lot more than just one. You can find a list of all the alternative solutions in this pastebin where I've also grouped them by equivalent behaviour. The ones I'm showing above I've selected because they are either the simplest or the most interesting solution, and I'll add explanations for them tomorrow.

As for the 16th gate: XOR is the only gate that can apparently not be implemented in 7 bytes. A brute force search over larger programs is unfortunately not feasible with the code I currently have. So XOR had to be written by hand. The shortest I've found so far is the above 10-byte program, which is based on a failed (but very close) attempt by FryAmTheEggman. It's possible that an 8-byte or 9-byte solution exists, but other than that, all the solutions should indeed be optimal.

Explanations

Warning: wall of text. On the off-chance anyone's interested how these highly compressed Hexagony programs actually work, I've included explanations for each of them below. I've tried to choose the simplest solution for each gate in cases where more than one optimal program exists, in order to keep the explanations reasonably short. However, some of them still boggle the mind, so I thought they deserve a bit more elaboration.

0000: False

I don't think we'll need a diagram for this one:

 ! @
. . .
 . .

Since the entire memory grid is initialised to zeros, ! simply prints a zero and @ terminates the program.

This is also the only 2-byte solution.

0001: And

 ? .
| @ !
 . .

This basically implements short-circuiting. The grey diagram below shows the beginning of the program, where the first input is read with ? and the instruction pointer (IP) wraps around to the the left corner where the | mirror reflects it. Now the corner acts as a conditional, such there are two different execution paths depending on the value of the first input. The red diagram shows the control flow for A = 0 and the green diagram for A = 1:

As you can see, when the A is 0, then we simply print it and terminate (remember that all . are no-ops). But when A is 1, then the IP traverses the first row again, reading B and printing that instead.

In total there are sixteen 5-byte solutions for this gate. Fourteen of those are essentially the same as the above, either using > instead of | or replacing the . with a command that's effectively a no-op, or putting ? in the second position:

?.|@!    .?|@!    ?=|@!    =?|@!    ?_|@!    _?|@!    ?0|@!
?.>@!    .?>@!    ?=>@!    =?>@!    ?_>@!    _?>@!    ?0>@!

And then there are two other solutions (which are equivalent to each other). These also implement the same short-circuiting logic, but the execution paths are a bit crazier (and left as an exercise to the reader):

?<!@|
?<!@<

0010: A and not B

 # ?
# ! )
 @ .

This also implements a form of short-circuiting, but due to the use of # the control flow is much trickier. # is a conditional IP switch. Hexagony actually comes with six IPs labelled 0 to 5, which start in the six corners of the grid, pointing along their clockwise edge (and the program always begins with IP 0). When a # is encountered, the current value is taken modulo 6, and control flow continues with the corresponding IP. I'm not sure what fit of madness made me add this feature, but it certainly allows for some surprising programs (like this one).

We will distinguish three cases. When A = 0, the program is fairly simple, because the value is always 0 when # is encountered such that no IP-switching takes place:

# does nothing, ? reads A (i.e. also does nothing), # still does nothing, ! prints the 0, ) increments it (this is important, otherwise the IP would not jump to the third line), @ terminates the program. Simple enough. Now let's consider the case (A, B) = (1, 0):

The red path still corresponds to IP 0, and I've added the green path for IP 1. We see that after ? reads A (1 this time), the # switches to the IP that starts in the top right corner. That means ? can read B (0). Now ) increments that to 1, such that the # in the top left corner does nothing and we remain with IP 1. The ! prints the 1 and the IP wraps around the left diagonal. # still does nothing and @ terminates the program.

Finally, the really weird case where both inputs are 1:

This time, the second input is also 1 and ) increments it to 2. That means the # in the top left corner causes another IP switch to IP 2, indicate in blue. On that path, we first increment it further to 3 (although that's irrelevant) and then pass the ? a third time. Since we've now hit EOF (i.e. the input is exhausted), ? returns 0, ! prints that, and @ terminates the program.

Notably, this is the only 6-byte solution for this gate.

0011: A

 ? !
@ . .
 . .

This is simple enough that we won't need a diagram: ? reads A, ! prints it, @ terminates.

This is the only 3-byte solution for this gate. (In principle, it would also be possible to do ,;@, but the search didn't include ;, because I don't think it can ever save bytes over ! for this task.)

0100: B and not A

 + ?
| @ !
 ? .

This one is a lot simpler than its "brother" 0010. The control flow is actually the same as we've seen above for 0001 (And). If A = 0, then the IP traverses the lower line, reading B and printing that before terminating. If A = 1 then the IP traverses the first line again, also reading B, but the + adds two unused memory edges so all it does is reset the current value to 0, so that ! always prints 0.

There are quite a lot of 6-byte alternatives to this (42 in total). First, there's a ton of solutions equivalent to the above. We can again choose freely between | and >, and + can be replaced with any other command that gives us an empty edge:

"?|@!?    &?|@!?    '?|@!?    *?|@!?    +?|@!?    -?|@!?    ^?|@!?    {?|@!?    }?|@!?
"?>@!?    &?>@!?    '?>@!?    *?>@!?    +?>@!?    -?>@!?    ^?>@!?    {?>@!?    }?>@!?

In addition, we can also use ] instead of ?. ] moves to the next IP (i.e. selects IP 1), so that this branch instead reuses the ? in the top right corner. That gives another 18 solutions:

"?|@!]    &?|@!]    '?|@!]    *?|@!]    +?|@!]    -?|@!]    ^?|@!]    {?|@!]    }?|@!]
"?>@!]    &?>@!]    '?>@!]    *?>@!]    +?>@!]    -?>@!]    ^?>@!]    {?>@!]    }?>@!]

And then there's six other solutions that all work differently with varying levels of craziness:

/[<@!?    ?(#!@]    ?(#>@!    ?/@#/!    [<<@!?    [@$\!?

0101: B

 ? ?
! @ .
 . .

Woohoo, another simple one: read A, read B, print B, terminate. There are actually alternatives to this though. Since A is only a single character, we can also read it with ,:

,?!@

And there's also the option of using a single ? and using a mirror to run through it twice:

?|@!    ?>@!

0110: Xor

  ? < @
 ! ! < _
\ ~ ( . .
 . . . .
  . . .

Like I said above, this was the only gate that wouldn't fit in side-length 2, so this a handwritten solution by FryAmTheEggman and myself, and there's a good chance that it isn't optimal. There are two cases to distinguish. If A = 0 the control flow is fairly simple (because in that case we only need to print B):

We start on the red path. ? reads A, < is a branch which deflects the zero left. The IP wraps to the bottom, then _ is another mirror, and when the IP hits the corner, it wraps to the top left corner and continues on the blue path. ? reads B, ! prints it. Now ( decrements it. This is important because it ensures that the value is non-positive (it's either 0 or -1 now). That makes IP wrap to the to right corner, where @ terminates the program.

When A = 1 things get a bit trickier. In that case we want to print not B, which in itself isn't too difficult, but the execution path is a bit trippy.

This time, the < deflects the IP right and then next < just acts as a mirror. So the IP traverses the same path in reverse, reading B when it encounters ? again. The IP wraps around to the right corner and continues on the green path. It next encounters (~ which is "decrement, multiply by -1", which swaps 0 and 1 and therefore computes not B. \ is just a mirror and ! prints the desired result. Then ? tries to return another number but returns zero. The IP now continues in the bottom left corner on the blue path. ( decrements, < reflects, ( decrements again, so that the current value is negative when the IP hits the corner. It moves across the bottom right diagonal and then finally hits @ to terminate the program.

0111: Or

 ? <
< @ !
 . .

More short-circuiting.

The A = 0 case (the red path) is a bit confusing here. The IP gets deflected left, wraps to the bottom left corner, gets immediately reflected by the < and returns to the ? to read B. It then wraps to the rigt corner, prints B with ! and terminates.

The A = 1 case (the green path) is a bit simpler. The < branch deflects the IP right, so we simply print the !, wrap back to the top left, and terminate at @.

There is only one other 5-byte solution:

\>?@!

It works essentially the same, but the actual execution paths are quite different and it uses a corner for branching instead of a <.

1000: Nor

 ) \
! # ?
 @ {

This might be my favourite program found in this search. The coolest thing is that this implementation of nor actually works for up to 5 inputs. I'll have to get into the details of the memory model a bit to explain this one. So as a quick refresher, Hexagony's memory model is a separate hexagonal grid, where each edge holds an integer value (initially all zero). There's a memory pointer (MP) which indicates an edge and a direction along that edge (such that there's two neighboring edges in front of and behind the current edge, with meaningful left and right neighbours). Here is a diagram of the edges we'll be using, with the MP starting out as shown in red:

Let's first consider the case where both inputs are 0:

We start on the grey path, which simply increments edge A to 1 so that the # switches to IP 1 which is the blue path, starting in the top right corner. \ does nothing there and ? reads an input. We wrap to the top left corner where ) increments that input. Now as long as the input is zero, this will result in a 1, so that # doesn't do anything. Then { moves the MP to the left, i.e. on the first iteration from A to B. Since this edge still has its initial zero the IP wraps back to the top right corner and on a new memory edge. So this loop will continue as long as ? reads zeros, moving the MP around the hexagon from B to C to D and so on. It doesn't matter whether ? returns a zero because it was an input or because it was EOF.

After six iterations through this loop, { returns to A. This time, the edge already holds the value 1 from the very first iteration, so the IP wraps to the left corner and continues on the green path instead. ! simply prints that 1 and @ terminates the program.

Now what if any of the inputs is 1?

Then ? reads that 1 at some point and ) increments it to 2. That means # will now switch IPs again and we'll continue in the right corner on the red path. ? reads another input (if there is one), which doesn't really matter and { moves one edge further. This has to be an unused edge, hence this works for up to 5 inputs. The IP wraps to the top right where it's immediately reflected and wraps to the left corner. ! prints the 0 on the unused edge and # switches back to IP 0. That IP was still waiting around on the #, going southwest (grey path), so it immediately hits the @ and terminates the program.

In total there are seven 7-byte solutions for this gate. 5 of them work the same as this and simply use other commands to move to an unused edge (and may walk around a different hexagon or in a different direction):

)\!#?@"    )\!#?@'    )\!#?@^    )\!#?@{    )\!#?@}

And there is one other class of solutions which only works with two inputs, but whose execution paths are actually even messier:

?]!|<)@    ?]!|<1@

1001: Equality

 ( ~
? / @
 # !

This also makes very clever use of conditional IP selection. We need to distinguish again between A = 0 and A = 1. In the first case we want to print not B, in the second we want to print B. For A = 0 we also distinguish the two cases for B. Let's start with A = B = 0:

We start on the grey path. (~ can be ignored, the IP wraps to the left corner (still on the grey path) and reads A with ?. ( decrements that, so we get -1 and IP wrap to the bottom left corner. Now like I said earlier, # takes the value modulo 6 before choosing he IP, so a value of -1 actually gets out IP 5, which starts in the left corner on the red path. ? reads B, ( decrements that as well so that we remain on IP 5 when we hit # again. ~ negates the -1 so that the IP wraps to the bottom right corner, prints the 1 and terminates.

Now if B is 1 instead, the current value will be 0 when we hit # the second time, so we switch back to IP 0 (now on the green path). That hits ? a third time, yielding 0, ! prints it and @ terminates.

Finally, the case where A = 1. This time the current value is already zero when we hit # for the first time, so this never switches to IP 5 in the first place. We simply continue immediately on the green path. ? now doesn't just give a zero but returns B instead. ! prints it and @ terminates again.

In total there are three 7-byte solutions for this gate. The other two work very differently (even from each other), and make even weirder use of #. In particular they read one or more values with , (reading a character code instead of an integer) and then use that value modulo 6 to pick an IP. It's pretty nuts.

),)#?@!

?~#,~!@

1010: Not B

 ? ?
| @ !
 ) .

This one is fairly simple. The execution path is the horizontal branch we already know from and earlier. ?? reads A and then immediately B. After reflecting at | and branching, for B = 0 we will execute the bottom branch, where ) increments the value to 1 which is then printed by !. On the top branch (if B = 1) the ? simply reset the edge to 0 which is then also printed by !.

There are eight 6-byte programs for this gate. Four of them are pretty much the same, using either > instead of | or 1 instead of ) (or both):

??>@!)    ??>@!1    ??|@!)    ??|@!1

Two use a single ? which is used twice due to a mirror. The negation then happens as we did for xor with either (~ or ~).

?>!)~@    ?>!~(@

And finally, two solutions use a conditional IP switch, because why use the simple way if the convoluted one also works:

??#)!@    ??#1!@

1011: B implies A

 \ #
? ? !
 1 @

This uses some rather elaborate IP switching. I'll start with the A = 1 case this time, because it's simpler:

We start on the grey path, which reads A with ? and then hits the #. Since A is 1 this switches to IP 1 (green path). The ! immediately prints that, the IP wraps to the top left, reads B (unnecessarily) and terminates.

When A = 0 things get a bit more interesting. First let's consider A = B = 0:

This time, the # does nothing and we remain on IP 0 (red path from that point onward). ? reads B and 1 turns it into a 1. After wrapping to the top left corner, we hit # again, so we end up on the green path after all, and print 1 as before, before terminating.

Finally, here is (A, B) = (0, 1), the false case:

Note that I've removed the initial grey path for clarity, but the program begins the same way, and we end up on the red path as before. So this time the second ? returns 1. Now we encounter the 1. At this point it's important to understand what digits actually do in Hexagony (so far we've only used them on zeros): when a digit is encountered, the current value is multiplied by 10 and then the digit is added. This is normally used to write decimal numbers verbatim into the source code, but it means that B = 1 is actually mapped to the value 11. So when we hit #, this is taken modulo 6 to give 5 and hence we switch to IP 5 (instead of 1 as before) and continue on the blue path. Hitting ? a third time returns a zero, so ! prints that, and after another two ?, the IP wraps to the bottom right where the program terminates.

There are four 7-byte solutions to this and they all work differently:

#)/!?@$    <!?_@#1    \#??!1@    |/)#?@!

1100: Not A

 ? (
~ ! @
 . .

Just a simple linear one: read A with ?, negate with (~, print with !, terminate with @.

There's one alternative solution, and that's negating with ~) instead:

?~)!@

1101: A implies B

 ? .
| @ !
 ) .

This is a lot simpler than the opposite implication we just talked about. It's again one of those horizontal branch programs, like the one for and. If A is 0, it simply gets incremented to 1 on the bottom branch and printed. Otherwise, the top branch is executed again where ? reads B and then ! prints that instead.

There's a ton of alternatives here (66 solutions in total), mostly due to free choice of effective no-ops. For a start we can vary the above solution in all the same ways we could for and and we can also choose between ) and 1:

?.|@!)    .?|@!)    ?=|@!)    =?|@!)    ?_|@!)    _?|@!)    ?0|@!)
?.|@!1    .?|@!1    ?=|@!1    =?|@!1    ?_|@!1    _?|@!1    ?0|@!1
?.>@!)    .?>@!)    ?=>@!)    =?>@!)    ?_>@!)    _?>@!)    ?0>@!)
?.>@!1    .?>@!1    ?=>@!1    =?>@!1    ?_>@!1    _?>@!1    ?0>@!1

And then there's a different version using conditional IP selection, where the first command can be chosen almost arbitrarily, and there is also a choice between ) and 1 for some of those options:

"?#1!@    &?#1!@    '?#1!@    )?#1!@    *?#1!@    +?#1!@    -?#1!@    .?#1!@
0?#1!@    1?#1!@    2?#1!@    3?#1!@    4?#1!@    5?#1!@    6?#1!@    7?#1!@
8?#1!@    9?#1!@    =?#1!@    ^?#1!@    _?#1!@    {?#1!@    }?#1!@

"?#)!@    &?#)!@    '?#)!@              *?#)!@    +?#)!@    -?#)!@
0?#)!@              2?#)!@              4?#)!@              6?#)!@
8?#)!@                        ^?#)!@    _?#)!@    {?#)!@    }?#)!@

1110: Nand

 ? $
@ # )
 ! <

The last complicated one. If you're still reading, you've almost made it. :) Let's look at A = 0 first:

? reads A and then we hit $. This is a jump command (like Befunge's #) which skips the next instruction so that we don't terminate on the @. Instead the IP continues at #. However since A is 0, this doesn't do anything. ) increments it to 1 so that the IP continues on the bottom path where the 1 is printed. The < deflects the IP to the right where it wraps to the left corner and the program terminates.

Next, when the input is (A, B) = (1, 0) we get this situation:

It's essentially the same as before except that at the # we switch to IP 1 (green path), but since B is 0 we switch back to IP 0 when we hit # a second time (now blue path), where it prints 1 as before.

Finally, the A = B = 1 case:

This time, when we # the second time, the current value is still 1 so that we don't change the IP again. The < reflects it and the third time we hit ? we get a zero. Hence the IP wraps to the bottom left where ! prints the zero and the program ends.

There are nine 7-byte solutions in total for this. The first alternative simply uses 1 instead of ):

?$@#1!<

Then there's two solutions that will do your head in with the amount of IP switching that's going on:

)?#_[!@    1?#_[!@

These actually blew my mind: the interesting part is that IP switching can be used as a deferred conditional. The language's IP-switching rules are such that the current IP makes another step before the switch happens. If that step happens to go through a corner, then the current value decides on which branch the IP will continue if we ever switch back to it. Exactly this happens when the input is A = B = 1. Although this is all consistent with how I designed the language, I was never aware of this implication of the spec, so it's nice when my language teaches me some new tricks :D.

Then there's a third solution whose amount of IP switching is even worse (although it doesn't make use of that deferred conditional effect):

>?1]#!@

And then there's another one:

?$@#)!<

And then there's these four equivalent solutions, which do use some non-conditional IP switching and instead implement all the logic via branches and corners:

]<?<@!)    ]<?<@!1    ]|?<@!)    ]|?<@!1

1111: True

 1 !
@ . .
 . .

You've earned yourself something simple for the end: set edge to 1, print with !, terminate with @. :)

Of course, there's one alternative:

)!@

As usual, all control flow diagrams created with Timwi's HexagonyColorer and the memory diagram with his EsotericIDE.


问:
Sum It Up with a Digital Triangle
Well, sum it down really.

Write a program or function that takes in a nonempty list of decimal integers (0-9) and outputs a downward pointing "triangle" of digits with the input list at the top where every digit after the first line is the sum of the two digits above it modulo 10.

For example, the input [7, 5, 0, 9] has output

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

because 2 is (7 + 5) mod 10, 5 is (5 + 0) mod 10, 9 is (0 + 9) mod 10, etc. all the way to 1 being (7 + 4) mod 10.

If the list has only one item, then the output matches the input; e.g. an input of [4] will yield

```<code>4
</code>```

Here are some additional examples:

```<code>[0]

0

[1, 2]

1 2
 3

[8, 7]

8 7
 5

[0, 0]

0 0
 0

[1, 4, 2]

1 4 2
 5 6
  1

[0, 1, 0]

0 1 0
 1 1
  2

[1, 0, 0, 0]

1 0 0 0
 1 0 0
  1 0
   1

[1, 2, 3, 4]

1 2 3 4
 3 5 7
  8 2
   0

[1, 2, 3, 5, 8]

1 2 3 5 8
 3 5 8 3
  8 3 1
   1 4
    5

[9, 2, 4, 5, 3, 2, 2]

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

Note that in the output:

The first line does not have leading spaces.

Each subsequent line has one more leading space than the line previous.

Digits are separated by a single space.

Each line is allowed to have up to one trailing space.

There may be a single optional trailing newline.

You must use the characters for normal decimal digits (0 through 9).

The shortest code in bytes wins. Tiebreaker is earlier answer.

答:
Python 3, 97 bytes

```<code>def f(x):print(*x);x[-1]==''or f(['']+[(x[i]+x[i+1])%10if''!=x[i]else''for i in range(len(x)-1)])
</code>```

Prints a single trailing newline.

How it works

```<code>def f(x):                            function with input of list of numbers
print(*x)                            print the old line of the triangle
x[-1]==''or...                       if no more numbers, stop...
(x[i]+x[i+1])%10if''!=x[i]else''...  ...else compute the next entry in the new line if
                                     possible...
...for i in range(len(x)-1)          ...for all relevant digit pairs...
['']+...                             ...concatenate with empty string to force new leading
                                     space...
f(...)                               ...and pass to function
</code>```

Try it on Ideone

ContentLicense: CC BY-SA 3.0

Title: Sum It Up with a Digital Triangle

Body:
Python 3, 97 bytes

def f(x):print(*x);x[-1]==''or f(['']+[(x[i]+x[i+1])%10if''!=x[i]else''for i in range(len(x)-1)])

Prints a single trailing newline.

How it works

def f(x):                            function with input of list of numbers
print(*x)                            print the old line of the triangle
x[-1]==''or...                       if no more numbers, stop...
(x[i]+x[i+1])%10if''!=x[i]else''...  ...else compute the next entry in the new line if
                                     possible...
...for i in range(len(x)-1)          ...for all relevant digit pairs...
['']+...                             ...concatenate with empty string to force new leading
                                     space...
f(...)                               ...and pass to function

Try it on Ideone


问:
Reverse the consonants
The program should take a string as input and reverse the consonants in it, while keeping the order of vowels. All the letters will be lowercase, so you don't have to worry about casing. Examples follow.

Input: a test case.

The consonants here are t,s,t,c,s. They should come in reversed order, i.e. s,c,t,s,t and inserted back into the string to the same positions where the pre-reversed characters were located: a sect sate.

Input: well-done. Output: nedl-lowe.

Input: reverse the consonants. Output: setenne sne cohtosarvr.

This is the code golf, the shortest solution wins.

Y should be considered vowel regardless of what it is and not reversed.

Anything, as well as numbers, punctuation, quotes, and other symbols (@#$%^&*(){}[]\|/<>~-_+=`), could potentially appear in the input.

答:
Java, 319 305 261 188 bytes

Credit to @Leaky Nun for helping with this :-)

char[]r(char[]s){int i=0,j=0,n=s.length;char[]o=new char[n];for(;i<n;i++){if((s[i]+"").matches("(?![eiouy])[b-z]")){o[j++]=s[i];s[i]=65;}}for(i=0;i<n;i++)if(s[i]==65)s[i]=o[--j];return s;}
```

<p>Old:</p>

<pre class="lang-java prettyprint-override"><code>s(String p){int i=0,j=0;char[]s=p.toCharArray(),o=p.toCharArray();for(;i<s.length;i++){if(((s[i]+"").matches("[aeiouy @#$%^&*(){}\\[\\]\\|/\\\\<>~\\-_+=`]")))continue;o[j++]=(s[i]);s[i]='A';}for(i=0;i<s.length;i++)if(s[i]=='A')s[i]=o[--j];return new String(s);}
</code>```

Inspiration taken from here ❤

Ungolfed

String s(String p){
    int i = 0, j = 0;
    char[]s=p.toCharArray(),o=p.toCharArray();
    for (;i<s.length;i++) {
        if (((s[i]+"").matches("[aeiouy @#$%^&*(){}\\[\\]\\|/\\\\<>~\\-_+=`]"))) continue;
        o[j++] = (s[i]); // Store the consonant into o
        s[i] = 'A'; // Put a special character in its place
    }
    for (i=0;i<s.length;i++)
        if (s[i] == 'A') // If special character
            s[i] = o[--j]; // Put back the consonant in reverse order
    return new String(s);
}
```

Title: Reverse the consonants

Body:
Java, 319 305 261 188 bytes

Credit to @Leaky Nun for helping with this :-)

char[]r(char[]s){int i=0,j=0,n=s.length;char[]o=new char[n];for(;i<n;i++){if((s[i]+"").matches("(?![eiouy])[b-z]")){o[j++]=s[i];s[i]=65;}}for(i=0;i<n;i++)if(s[i]==65)s[i]=o[--j];return s;}

Old:

s(String p){int i=0,j=0;char[]s=p.toCharArray(),o=p.toCharArray();for(;i<s.length;i++){if(((s[i]+"").matches("[aeiouy @#$%^&*(){}\\[\\]\\|/\\\\<>~\\-_+=`]")))continue;o[j++]=(s[i]);s[i]='A';}for(i=0;i<s.length;i++)if(s[i]=='A')s[i]=o[--j];return new String(s);}

Inspiration taken from here ❤

Ungolfed

String s(String p){
    int i = 0, j = 0;
    char[]s=p.toCharArray(),o=p.toCharArray();
    for (;i<s.length;i++) {
        if (((s[i]+"").matches("[aeiouy @#$%^&*(){}\\[\\]\\|/\\\\<>~\\-_+=`]"))) continue;
        o[j++] = (s[i]); // Store the consonant into o
        s[i] = 'A'; // Put a special character in its place
    }
    for (i=0;i<s.length;i++)
        if (s[i] == 'A') // If special character
            s[i] = o[--j]; // Put back the consonant in reverse order
    return new String(s);
}


答:
Julia, 53 bytes

!s=s[flipud(i)]=s[i=find(c->'}'>c∉"aeiouy"<"$c",s)]
```

This takes a character array as input and reverses its consonants in-place. Try it online!

Credit goes to @Sp3000 for the lowercase consonant check.

How it works

i=find(...,s) yields all indices of s for which the predicate ... returns true and saves them it the variable i.

c->'}'>c∉"aeiouy"<"$c" performs three tests and returns true if and only if all are positive.

'}'>c checks if the character c comes before {.

"aeiou" checks if the string c comes after a.

c∉"aeiouy" verifies that c is not a vowel.

Finally, s[i] yields all consonants and s[flipud(i)]=s[i] assigns them to positions in s that correspond to the reversed indices in in i.

Title: Reverse the consonants

Body:
The program should take a string as input and reverse the consonants in it, while keeping the order of vowels. All the letters will be lowercase, so you don't have to worry about casing. Examples follow.

Input: a test case.

The consonants here are t,s,t,c,s. They should come in reversed order, i.e. s,c,t,s,t and inserted back into the string to the same positions where the pre-reversed characters were located: a sect sate.

Input: well-done. Output: nedl-lowe.

Input: reverse the consonants. Output: setenne sne cohtosarvr.

This is the code golf, the shortest solution wins.

Y should be considered vowel regardless of what it is and not reversed.

Anything, as well as numbers, punctuation, quotes, and other symbols (@#$%^&*(){}[]\|/<>~-_+=`), could potentially appear in the input.

Body:
Julia, 53 bytes

!s=s[flipud(i)]=s[i=find(c->'}'>c∉"aeiouy"<"$c",s)]

This takes a character array as input and reverses its consonants in-place. Try it online!

Credit goes to @Sp3000 for the lowercase consonant check.

How it works

i=find(...,s) yields all indices of s for which the predicate ... returns true and saves them it the variable i.

c->'}'>c∉"aeiouy"<"$c" performs three tests and returns true if and only if all are positive.

'}'>c checks if the character c comes before {.

"aeiou" checks if the string c comes after a.

c∉"aeiouy" verifies that c is not a vowel.

Finally, s[i] yields all consonants and s[flipud(i)]=s[i] assigns them to positions in s that correspond to the reversed indices in in i.


问:
The teacher is always wrong, flip his answer
Your dumb teacher is always wrong, so flip his answer.

Change these responses

```<code>True -> False
Yes -> No
0 -> 1
Yeah -> Nope
</code>```

and vice versa. Keeping punctuation and the first letter's capitalization counts. Only one condition will be passed to the program.

You only need to accept the following test cases:

```<code>True <-> False
True. <-> False.
true <-> false
true. <-> false.
Yes <-> No
Yes. <-> No.
yes <-> no
yes. <-> no.
0 <-> 1
Yeah <-> Nope
yeah <-> nope
Yeah. <-> Nope.
yeah. <-> nope.
</code>```

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

答:
Java, 332 274 205 bytes

String s(String p){String[]l={"True","true","Yes","yes","Yeah","yeah","0","1","nope","Nope","no","No","false","False"};for(int j=0;j<14;j++)if(p.matches(l[j]+".?"))return p.replace(l[j],l[13-j]);return"";}
```

Gotta love the uncreative Java golf! Credit to @Leaky Nun for helping!

Body:
Java, 332 274 205 bytes

String s(String p){String[]l={"True","true","Yes","yes","Yeah","yeah","0","1","nope","Nope","no","No","false","False"};for(int j=0;j<14;j++)if(p.matches(l[j]+".?"))return p.replace(l[j],l[13-j]);return"";}

Gotta love the uncreative Java golf! Credit to @Leaky Nun for helping!


问:
Wait a minute – in less than ten seconds

Task

Using any type of parallelisation, wait multiple periods, for a total sleep time of at least a minute (but less than a minute and a half).

The program/function must terminate within 10 seconds and return (by any means and in any format) two values: the total elapsed time, and the total executed sleep time. Both time values have to have a precision of at least 0.1 seconds.

This is similar to the concept of man-hours: a job that takes 60 hours can be completed in only 6 hours if 10 workers are splitting the job. Here we can have 60 seconds of sleep time e.g. in 10 parallel threads, thus requiring only 6 seconds for the whole job to be completed.

Example

The program MyProgram creates 14 threads, each thread sleeps for 5 seconds:

MyProgram → [5.016,70.105]

The execution time is greater than 5 seconds, and the total sleep time is greater than 70 seconds because of overhead.

答:
C90 (OpenMP), 131 Bytes (+ 17 for env variable) = 148 Bytes

#include <omp.h>
#define o omp_get_wtime()
n[4];main(t){t=o;
#pragma omp parallel
while(o-9<t);times(n);printf("%d,%f",n[0],o-t);}
```
<p>Example Output:</p>
<pre class="lang-c prettyprint-override"><code>7091,9.000014
</code>```

Try it online!

Notes:

7091 is in cycles (100/sec), so the program ran for 70 seconds

Could be much shorter if I figured a way to get a timer to work other than omp_get_wtime() because then I could remove the include statement aswell.

Run with OMP_NUM_THREADS=9

Body:
C90 (OpenMP), 131 Bytes (+ 17 for env variable) = 148 Bytes

#include <omp.h>
#define o omp_get_wtime()
n[4];main(t){t=o;
#pragma omp parallel
while(o-9<t);times(n);printf("%d,%f",n[0],o-t);}

Example Output:

7091,9.000014

Try it online!

Notes:

7091 is in cycles (100/sec), so the program ran for 70 seconds

Could be much shorter if I figured a way to get a timer to work other than omp_get_wtime() because then I could remove the include statement aswell.

Run with OMP_NUM_THREADS=9

ContentLicense: CC BY-SA 4.0


问:
Lithp Tranthlator
My friend made a lisp translator the other day, that is to say it took a string and converted s=>th and S=>Th. It was quite long and I thought that it could be golfed.

So the task is to make a program/function that takes an input string, translates it in to lisp and outputs the string

Test case

```<code>Sam and Sally like Sheep        Tham and Thally like Thheep
Sally likes sausages            Thally liketh thauthageth
Sally sells seashells           Thally thellth theathhellth
</code>```

Note that it doesn't matter that h gets repeated all the time

This is code golf so shortest answer wins

答:
C, 101 bytes

Note this is a complete C program, unlike the previous C answer.

It takes the first command line argument as input. Compile w/ gcc and run ./a.out "Sally sells seashells"

```<code>#include<stdio.h>
main(int d,char**c){for(d=**++c;d;putchar(d&223^83?d:d+(*0[c]--=104,1)),d=*++*c);}
</code>```

Title: Lithp Tranthlator

Body:
C, 101 bytes

Note this is a complete C program, unlike the previous C answer.

It takes the first command line argument as input. Compile w/ gcc and run ./a.out "Sally sells seashells"

#include<stdio.h>
main(int d,char**c){for(d=**++c;d;putchar(d&223^83?d:d+(*0[c]--=104,1)),d=*++*c);}


答:
Perl 5 (58 + 4 = 62 bytes)

```<code>$_=<>;$r=qr/(?![eiouy])[b-z]/;@a=/$r/g;s/$r/pop@a/ge;print
</code>```

+4 penalty for running with -0777 flag, which sets Perl to slurp mode to handle newlines correctly.

Accepts input through STDIN and prints to STDOUT.

Explanation

```<code>                   $_=<>;   Read the input
 $r=qr/(?![eiouy])[b-z]/;   Save the regex; we'll be using it twice
                @a=/$r/g;   Store all the consonants in an array
           s/$r/pop@a/ge;   Replace each consonant with the final value in the array and pop
                   print    Output the result
</code>```

Title: Reverse the consonants

Body:
Perl 5 (58 + 4 = 62 bytes)

$_=<>;$r=qr/(?![eiouy])[b-z]/;@a=/$r/g;s/$r/pop@a/ge;print

+4 penalty for running with -0777 flag, which sets Perl to slurp mode to handle newlines correctly.

Accepts input through STDIN and prints to STDOUT.

Explanation

                   $_=<>;   Read the input
 $r=qr/(?![eiouy])[b-z]/;   Save the regex; we'll be using it twice
                @a=/$r/g;   Store all the consonants in an array
           s/$r/pop@a/ge;   Replace each consonant with the final value in the array and pop
                   print    Output the result


答:
Perl 5, <s>92</s> <s>68</s> 55 bytes

Saved 37 bytes thanks to @manatwork's help. ;-)

$_=<>;@b=@a=/[^\Waeiou]/g;print$_~~@b?pop@a:$_ for/./g
```

A translation of @Lynn Python solution to Perl.

Title: Reverse the consonants

Body:
Perl 5, <s>92</s> <s>68</s> 55 bytes

Saved 37 bytes thanks to @manatwork's help. ;-)

$_=<>;@b=@a=/[^\Waeiou]/g;print$_~~@b?pop@a:$_ for/./g

A translation of @Lynn Python solution to Perl.


答:
Python 3, 227 bytes

def f(x):l=["True","False","True.","False.","true","false","true.","false.","Yes","No","yes","no","Yes.","No.","yes.","no.","0","1","Yeah","Nope","Yeah.","Nope.","yeah","nope","yeah.","nope."];r=l.index(x);return l[r+1-2*(r%2)]
```

<p>Ungolfed form:</p>

<pre class="lang-python prettyprint-override"><code>def f(x):
    l=["True","False","True.","False.","true","false","true.","false.","Yes","No","yes","no","Yes.","No.","yes.","no.","0","1","Yeah","Nope","Yeah.","Nope.","yeah","nope","yeah.","nope."]
    r=l.index(x)
    return l[r + 1 -2*(r % 2)]
</code>```

Title: The teacher is always wrong, flip his answer

Body:
Your dumb teacher is always wrong, so flip his answer.

Change these responses

```<code>True -> False
Yes -> No
0 -> 1
Yeah -> Nope
</code>```

and vice versa. Keeping punctuation and the first letter's capitalization counts. Only one condition will be passed to the program.

You only need to accept the following test cases:

```<code>True <-> False
True. <-> False.
true <-> false
true. <-> false.
Yes <-> No
Yes. <-> No.
yes <-> no
yes. <-> no.
0 <-> 1
Yeah <-> Nope
yeah <-> nope
Yeah. <-> Nope.
yeah. <-> nope.
</code>```

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

Body:
Python 3, 227 bytes

def f(x):l=["True","False","True.","False.","true","false","true.","false.","Yes","No","yes","no","Yes.","No.","yes.","no.","0","1","Yeah","Nope","Yeah.","Nope.","yeah","nope","yeah.","nope."];r=l.index(x);return l[r+1-2*(r%2)]

Ungolfed form:

def f(x):
    l=["True","False","True.","False.","true","false","true.","false.","Yes","No","yes","no","Yes.","No.","yes.","no.","0","1","Yeah","Nope","Yeah.","Nope.","yeah","nope","yeah.","nope."]
    r=l.index(x)
    return l[r + 1 -2*(r % 2)]


答:
Haskell, 139 bytes

```<code>f=mapM(\(r,s)->putStrLn$r++(s>>=(++" ").show)).zip(iterate(' ':)"").takeWhile(/=[]).iterate g where g(_:[])=[];g(y:p:ys)=mod(y+p)10:g(p:ys)
</code>```

Takes input as an argument, outputs to STDOUT.

Ungolfed version:

```<code>f = mapM (\(r, s) -> putStrLn $ r ++ (s >>= (++ " ") . show))
    . zip (iterate (' ' :) "")
    . takeWhile (/= [])
    . iterate sumTerms
    where sumTerms (_:[]) = []
          sumTerms (y:p:ys) = mod (y+p) 10 : sumTerms (p:ys)
</code>```

Title: Sum It Up with a Digital Triangle

Body:
Well, sum it down really.

Write a program or function that takes in a nonempty list of decimal integers (0-9) and outputs a downward pointing "triangle" of digits with the input list at the top where every digit after the first line is the sum of the two digits above it modulo 10.

For example, the input [7, 5, 0, 9] has output

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

because 2 is (7 + 5) mod 10, 5 is (5 + 0) mod 10, 9 is (0 + 9) mod 10, etc. all the way to 1 being (7 + 4) mod 10.

If the list has only one item, then the output matches the input; e.g. an input of [4] will yield

```<code>4
</code>```

Here are some additional examples:

```<code>[0]

0

[1, 2]

1 2
 3

[8, 7]

8 7
 5

[0, 0]

0 0
 0

[1, 4, 2]

1 4 2
 5 6
  1

[0, 1, 0]

0 1 0
 1 1
  2

[1, 0, 0, 0]

1 0 0 0
 1 0 0
  1 0
   1

[1, 2, 3, 4]

1 2 3 4
 3 5 7
  8 2
   0

[1, 2, 3, 5, 8]

1 2 3 5 8
 3 5 8 3
  8 3 1
   1 4
    5

[9, 2, 4, 5, 3, 2, 2]

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

Note that in the output:

The first line does not have leading spaces.

Each subsequent line has one more leading space than the line previous.

Digits are separated by a single space.

Each line is allowed to have up to one trailing space.

There may be a single optional trailing newline.

You must use the characters for normal decimal digits (0 through 9).

The shortest code in bytes wins. Tiebreaker is earlier answer.

Body:
Haskell, 139 bytes

f=mapM(\(r,s)->putStrLn$r++(s>>=(++" ").show)).zip(iterate(' ':)"").takeWhile(/=[]).iterate g where g(_:[])=[];g(y:p:ys)=mod(y+p)10:g(p:ys)

Takes input as an argument, outputs to STDOUT.

Ungolfed version:

f = mapM (\(r, s) -> putStrLn $ r ++ (s >>= (++ " ") . show))
    . zip (iterate (' ' :) "")
    . takeWhile (/= [])
    . iterate sumTerms
    where sumTerms (_:[]) = []
          sumTerms (y:p:ys) = mod (y+p) 10 : sumTerms (p:ys)


问:
Parity of Nth Term in Fibonacci Integer Sequences
If you look at the Fibonacci Numbers, you will notice a pattern in their parity: 0, 1 , 1 , 2 , 3 , 5 , 8 , 13 , 21 , 34 , 55 , 89 , 144. Every third number is even, and all the others are odd. This makes sense because an even plus an odd is odd, but an odd plus an odd is even and the sum for a term will always include at least one even number unless the last two terms were odd, which happens every three terms.

In this challenge you will have to look at a generalization of this problem.

Specs

You will be given as input two positive integers describing the Fibonacci integer sequence you will have to look at.

For example, 0, 1 describes the original Fibonacci numbers, and 2, 1 would be the Lucas numbers. The sequence is calculated with the recurrence relation: x(n+2)=x(n+1)+x(n).

You will also take a positive integer n.

Your code has to output the parity of the nth term of the described Fibonacci integer sequence (0 indexed).

The output format can be any two sane, consistent outputs (e.g. 0 for even and 1 for odd).

Test Cases

```<code>(Fibonacci numbers) [0, 1], 4  ->  odd
(Lucas numbers) [2, 1], 9  ->  even
[14, 17], 24  ->  even
[3, 9], 15  ->  odd
[2, 4], 10  ->  even
</code>```

答:
Jelly, 4 bytes

```<code>^¡^Ḃ
</code>```

Prints 0 for even, 1 for odd. Try it online!

How it works

The quick ¡ takes a link it applies repeated to the previous output, and optionally a second link that specifies the number of iterations. If that second link is absent (which is the case here), the number of iterations is taken from the last command-line argument.

When the first link is dyadic (which is the case with ^), ¡ applies that link to the previous return value (which is initialized as the left argument) and the right argument, then updates the return value with the result and the right argument with the previous return value. After doing so as many times as specified in the number of iterations, it returns the last return value.

The quicklink ^¡ is called with the left argument (first command-line argument) and the result of ^ (bitwise XOR of the left and right argument, i.e., the first and second command-line argument). XORing is necessary since the right argument is not among the return values, meaning that the right argument has to be the x(-1) in order to return x(n) with x(0) ^ n ¡ x(1).

To actually calculate x(n), we'd use the code +¡_@ (+¡ instead of ^¡ and _@ – left argument subtracted from right argument – instead of ^), but since we're only interested in the parities, any combination of +, _ and ^ will do.

Finally, Ḃ (bit) computes and returns the parity of x(n).

Body:
Jelly, 4 bytes

^¡^Ḃ

Prints 0 for even, 1 for odd. Try it online!

How it works

The quick ¡ takes a link it applies repeated to the previous output, and optionally a second link that specifies the number of iterations. If that second link is absent (which is the case here), the number of iterations is taken from the last command-line argument.

When the first link is dyadic (which is the case with ^), ¡ applies that link to the previous return value (which is initialized as the left argument) and the right argument, then updates the return value with the result and the right argument with the previous return value. After doing so as many times as specified in the number of iterations, it returns the last return value.

The quicklink ^¡ is called with the left argument (first command-line argument) and the result of ^ (bitwise XOR of the left and right argument, i.e., the first and second command-line argument). XORing is necessary since the right argument is not among the return values, meaning that the right argument has to be the x(-1) in order to return x(n) with x(0) ^ n ¡ x(1).

To actually calculate x(n), we'd use the code +¡_@ (+¡ instead of ^¡ and _@ – left argument subtracted from right argument – instead of ^), but since we're only interested in the parities, any combination of +, _ and ^ will do.

Finally, Ḃ (bit) computes and returns the parity of x(n).


Title: Parity of Nth Term in Fibonacci Integer Sequences

Body:
If you look at the Fibonacci Numbers, you will notice a pattern in their parity: 0, 1 , 1 , 2 , 3 , 5 , 8 , 13 , 21 , 34 , 55 , 89 , 144. Every third number is even, and all the others are odd. This makes sense because an even plus an odd is odd, but an odd plus an odd is even and the sum for a term will always include at least one even number unless the last two terms were odd, which happens every three terms.

In this challenge you will have to look at a generalization of this problem.

Specs

You will be given as input two positive integers describing the Fibonacci integer sequence you will have to look at.

For example, 0, 1 describes the original Fibonacci numbers, and 2, 1 would be the Lucas numbers. The sequence is calculated with the recurrence relation: x(n+2)=x(n+1)+x(n).

You will also take a positive integer n.

Your code has to output the parity of the nth term of the described Fibonacci integer sequence (0 indexed).

The output format can be any two sane, consistent outputs (e.g. 0 for even and 1 for odd).

Test Cases

```<code>(Fibonacci numbers) [0, 1], 4  ->  odd
(Lucas numbers) [2, 1], 9  ->  even
[14, 17], 24  ->  even
[3, 9], 15  ->  odd
[2, 4], 10  ->  even
</code>```

Body:
Python, 38 bytes

lambda a,b,n:(b*(n%3>0)+a*(~-n%3>0))%2


答:
Python, 29 bytes

lambda a,b,n:[a,b,a+b][n%3]%2
```
<p>The generalized Fibonacci sequence modulo 2 has cycle length of 3. So, we reduce <code>n</code> mod 3 and take that element of the first three.</p>
<hr />
<p><strong>31 bytes:</strong></p>
<pre class="lang-python prettyprint-override"><code>lambda a,b,n:0<a%2*2+b%2!=n%3+1
</code>```

True for odd, False for even

Body:
Python, 29 bytes

lambda a,b,n:[a,b,a+b][n%3]%2

The generalized Fibonacci sequence modulo 2 has cycle length of 3. So, we reduce n mod 3 and take that element of the first three.

31 bytes:

lambda a,b,n:0<a%2*2+b%2!=n%3+1

True for odd, False for even


答:
J, 15 bytes

```<code>2|0{(]{:,+/)^:[
</code>```

Simple method. Computes the nth term, and takes it modulo 2 to find its parity. Even parity is represented by 0 and odd parity by 1.

Usage

```<code>   f =: 2|0{(]{:,+/)^:[
   4 f 0 1
1
   9 f 2 1
0
   24 f 14 17
0
   15 f 3 9
1
</code>```

Explanation

```<code>2|0{(]{:,+/)^:[  Input: n on LHS, and initial values [a, b] on RHS
    ( .... )^:[  Repeat the function n times
         +/      Find the sum of a+b
      {:         Get the value b from the tail of [a, b]
        ,        Join the values to get [b, a+b]
     ]           Return those values as the new [a, b]
  0{             Select the first value at index 0 from the list (after n applications)
2|               Take that value modulo 2 and return
</code>```

Body:
J, 15 bytes

2|0{(]{:,+/)^:[

Simple method. Computes the nth term, and takes it modulo 2 to find its parity. Even parity is represented by 0 and odd parity by 1.

Usage

   f =: 2|0{(]{:,+/)^:[
   4 f 0 1
1
   9 f 2 1
0
   24 f 14 17
0
   15 f 3 9
1

Explanation

2|0{(]{:,+/)^:[  Input: n on LHS, and initial values [a, b] on RHS
    ( .... )^:[  Repeat the function n times
         +/      Find the sum of a+b
      {:         Get the value b from the tail of [a, b]
        ,        Join the values to get [b, a+b]
     ]           Return those values as the new [a, b]
  0{             Select the first value at index 0 from the list (after n applications)
2|               Take that value modulo 2 and return


答:
MATL, <s>10</s> 7 bytes

```<code>tshwQ)o
</code>```

Try it online!

Explanation:

```<code>t            #Duplicate the array of numbers
 s           #Sum them
  h          #and add that to the end of the array
   w         #Swap inputs so that the *N* is on top
    Q        #Increment *N* (Since MATL uses 1-based indexing)
     )       #Get that element of the array. MATL uses modular indexing.
      o      #Return it's parity
</code>```

Body:
MATL, <s>10</s> 7 bytes

tshwQ)o

Try it online!

Explanation:

t            #Duplicate the array of numbers
 s           #Sum them
  h          #and add that to the end of the array
   w         #Swap inputs so that the *N* is on top
    Q        #Increment *N* (Since MATL uses 1-based indexing)
     )       #Get that element of the array. MATL uses modular indexing.
      o      #Return it's parity


答:
Pyke, 9 bytes

```<code>3%QDs+@2%
</code>```

Try it here!

```<code>    s+    -   input+sum(input)
      @   -  ^[V]
3%        -   line_2 % 3
       2% - ^ % 2
</code>```

Body:
Pyke, 9 bytes

3%QDs+@2%

Try it here!

    s+    -   input+sum(input)
      @   -  ^[V]
3%        -   line_2 % 3
       2% - ^ % 2


答:
JavaScript (ES6), 57 <s>70</s>

Edit Amazing 20% saving thx @Neil

Late to the party, but it seems all javascript people missed something

a=>a.replace(r=/[^\W\d_aeiouy]/g,_=>c.pop(),c=a.match(r))
```

<p><em>Test</em></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>f=a=>a.replace(r=/[^\W\d_aeiouy]/g,_=>c.pop(),c=a.match(r))

function test() {
  var i=I.value
  O.textContent=f(i)
}

test()</code>```

#I { width:90% }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id=I oninput="test()" value="reverse the consonants."><pre id=O>``````

Title: Reverse the consonants

Body:
The program should take a string as input and reverse the consonants in it, while keeping the order of vowels. All the letters will be lowercase, so you don't have to worry about casing. Examples follow.

Input: a test case.

The consonants here are t,s,t,c,s. They should come in reversed order, i.e. s,c,t,s,t and inserted back into the string to the same positions where the pre-reversed characters were located: a sect sate.

Input: well-done. Output: nedl-lowe.

Input: reverse the consonants. Output: setenne sne cohtosarvr.

This is the code golf, the shortest solution wins.

Y should be considered vowel regardless of what it is and not reversed.

Anything, as well as numbers, punctuation, quotes, and other symbols (@#$%^&*(){}[]\|/<>~-_+=`), could potentially appear in the input.

Body:
JavaScript (ES6), 57 <s>70</s>

Edit Amazing 20% saving thx @Neil

Late to the party, but it seems all javascript people missed something

a=>a.replace(r=/[^\W\d_aeiouy]/g,_=>c.pop(),c=a.match(r))

Test

f=a=>a.replace(r=/[^\W\d_aeiouy]/g,_=>c.pop(),c=a.match(r))

function test() {
  var i=I.value
  O.textContent=f(i)
}

test()

#I { width:90% }

<input id=I oninput="test()" value="reverse the consonants."><pre id=O></pre>


答:
Python 154 bytes </p>

```<code>a=['True','True.','true','Yes','Yes.','yes','Yeah','Yeah.','yeah','0','False','False.','false','No','No.','no','Nope','Nope.','nope',1]
a[a.index(i)+10]
</code>```

Body:
Python 154 bytes

a=['True','True.','true','Yes','Yes.','yes','Yeah','Yeah.','yeah','0','False','False.','false','No','No.','no','Nope','Nope.','nope',1]
a[a.index(i)+10]


答:
Python 2, 132 bytes

Uses a process pool to spawn 9 processes and let each one sleep for 7 seconds.

```<code>import time as t,multiprocessing as m
def f(x):d=s();t.sleep(x);return s()-d
s=t.time
a=s()
print sum(m.Pool(9).map(f,[7]*9)),s()-a
</code>```

Prints total accumulated sleeptime first, then the actual runtime:

```<code>$ python test.py
63.0631158352 7.04391384125
</code>```

Title: Wait a minute – in less than ten seconds

Body:
Task

Using any type of parallelisation, wait multiple periods, for a total sleep time of at least a minute (but less than a minute and a half).

The program/function must terminate within 10 seconds and return (by any means and in any format) two values: the total elapsed time, and the total executed sleep time. Both time values have to have a precision of at least 0.1 seconds.

This is similar to the concept of man-hours: a job that takes 60 hours can be completed in only 6 hours if 10 workers are splitting the job. Here we can have 60 seconds of sleep time e.g. in 10 parallel threads, thus requiring only 6 seconds for the whole job to be completed.

Example

The program MyProgram creates 14 threads, each thread sleeps for 5 seconds:

MyProgram → [5.016,70.105]

The execution time is greater than 5 seconds, and the total sleep time is greater than 70 seconds because of overhead.

Body:
Python 2, 132 bytes

Uses a process pool to spawn 9 processes and let each one sleep for 7 seconds.

import time as t,multiprocessing as m
def f(x):d=s();t.sleep(x);return s()-d
s=t.time
a=s()
print sum(m.Pool(9).map(f,[7]*9)),s()-a

Prints total accumulated sleeptime first, then the actual runtime:

$ python test.py
63.0631158352 7.04391384125


问:
Fibonacci Factorization

Fibonacci Numbers

Fibonacci Numbers start with f(1) = 1 and f(2) = 1 (some includes f(0) = 0 but this is irrelevant to this challenge. Then, for n > 2, f(n) = f(n-1) + f(n-2).

The challenge

Your task is to find and output the n-th positive number that can be expressed as products of Fibonacci numbers. You can choose to make it 0-indexed or 1-indexed, whichever suits you better, but you must specify this in your answer.

Also, your answer must compute the 100th term in a reasonable time.

Testcases

```<code>n   result corresponding product (for reference)
1   1      1
2   2      2
3   3      3
4   4      2*2
5   5      5
6   6      2*3
7   8      2*2*2 or 8
8   9      3*3
9   10     2*5
10  12     2*2*3
11  13     13
12  15     3*5
13  16     2*2*2*2 or 2*8
14  18     2*3*3
15  20     2*2*5
16  21     21
17  24     2*2*2*3 or 3*8
18  25     5*5
19  26     2*13
20  27     3*3*3
100 315    3*5*21
</code>```

References

Obligatory OEIS A065108

答:
Jelly, <s>26</s> <s>24</s> <s>23</s> 21 bytes

```<code>ÆDf÷ß€FðḊ¡
1ç#2+Ð¡1¤Ṫ
</code>```

Try it online!

How it works

```<code>1ç#2+Ð¡1¤Ṫ  Main link. Argument: n (integer)

        ¤   Combine the three links to the left into a niladic chain.
   2          Set the left argument and the return value to 2 (third positive
              Fibonacci number).
       1      Yield 1 (second positive Fibonacci number).
    +Ð¡       Compute the sum of the return value and right argument, replacing the
              return value with the sum and the right argument with the previous
              return value.
              Do this n times, collecting all return values in a list.
              This returns A, the first n Fibonacci numbers greater than 1.
1             Set the return value to 1.
 ç#           Call the helper link with left argument k = 1, 2, 3... and right
              argument A = [2, 3, 5...] until n of them return a truthy value.
              Collect the matches in a list.
           Ṫ  Tail; extract the last (n-th) match.

ÆDf÷ß€FðḊ¡    Helper link. Left argument: k. Right argument: A

        Ḋ     Dequeue; yield r := [2, ..., k].
       ð ¡    If r in non-empty, execute the chain to the left. Return k otherwise.
ÆD              Yield the positive divisors of k.
   ÷            Divide k by all Fibonacci numbers in A.
  f             Filter; keep divisors that belong to k÷A, i.e., all divisors
                d for which k÷d belongs to A.
    ß€          Recursively call the helper link for each kept divisor d, with left
                argument d and right argument A.
      F         Flatten the result, yielding a non-empty array iff any of the
                recursive calls yielded a non-empty array or a number.
                If the left argument is 1, the helper link returns 1, so the
                array will be non-empty if the consecutive divisions by Fibonacci
                numbers eventually produced a 1.
</code>```

Title: Fibonacci Factorization

Body:
Jelly, <s>26</s> <s>24</s> <s>23</s> 21 bytes

ÆDf÷ß€FðḊ¡
1ç#2+Ð¡1¤Ṫ

Try it online!

How it works

1ç#2+Ð¡1¤Ṫ  Main link. Argument: n (integer)

        ¤   Combine the three links to the left into a niladic chain.
   2          Set the left argument and the return value to 2 (third positive
              Fibonacci number).
       1      Yield 1 (second positive Fibonacci number).
    +Ð¡       Compute the sum of the return value and right argument, replacing the
              return value with the sum and the right argument with the previous
              return value.
              Do this n times, collecting all return values in a list.
              This returns A, the first n Fibonacci numbers greater than 1.
1             Set the return value to 1.
 ç#           Call the helper link with left argument k = 1, 2, 3... and right
              argument A = [2, 3, 5...] until n of them return a truthy value.
              Collect the matches in a list.
           Ṫ  Tail; extract the last (n-th) match.

ÆDf÷ß€FðḊ¡    Helper link. Left argument: k. Right argument: A

        Ḋ     Dequeue; yield r := [2, ..., k].
       ð ¡    If r in non-empty, execute the chain to the left. Return k otherwise.
ÆD              Yield the positive divisors of k.
   ÷            Divide k by all Fibonacci numbers in A.
  f             Filter; keep divisors that belong to k÷A, i.e., all divisors
                d for which k÷d belongs to A.
    ß€          Recursively call the helper link for each kept divisor d, with left
                argument d and right argument A.
      F         Flatten the result, yielding a non-empty array iff any of the
                recursive calls yielded a non-empty array or a number.
                If the left argument is 1, the helper link returns 1, so the
                array will be non-empty if the consecutive divisions by Fibonacci
                numbers eventually produced a 1.


问:
golf atan2
Sometimes it really is a struggle to convert Cartesian coordinates (x,y) to Polar coordinates (r,phi). While you can calculate r = sqrt(x^2+y^2) quite easily, you often need some distinction of cases when calculating the angle phi because arcsin,arccos and arctan and all other trigonometric functions have a co-domain that each only spans half the circle.

In many languages there are built-ins for converting rectangular to polar coordinates, or at least have an atan2 function, which - given (x,y) - calculate the angle phi.

Task

Your task is to write a program/function that takes two (floating point, not both zero) Cartesian coordinates (x,y), and outputs the corresponding polar angle phi, where phi has to be in degrees, radians or grades (with grades I mean gradians which are 1/400 of the full circle), whichever is more convenient for you.

The angle is measured in positive orientation, and we have the zero angle for (1,0).

Details

You may not use built-ins that calculate the angle phi given two coordinates, including atan2,rect2polar,argOfComplexNumber and similar functions. However you can use the usual trigonometric functions and their reverses, that only take one argument. Any unit symbols are optional.

The radius r must be non-negative, and phi must be in the range [-360°, 360°] (it does not matter whether you output 270° or -90°).

Examples

```<code>Input       Output
(1,1)       45°
(0,3)       90°
(-1,1)      135°
(-5,0)      180°
(-2,-2)     225°
(0,-1.5)    270°
(4,-5)      308.66°
</code>```

答:
Pyth, 26 bytes

```<code>AQ?|>G0Hy.tcH+@s^R2Q2G5.n0
</code>```

theta in radians.

Test suite.

Title: golf atan2

Body:
Pyth, 26 bytes

AQ?|>G0Hy.tcH+@s^R2Q2G5.n0

theta in radians.

Test suite.


答:
Javascript ES6, 54 bytes

```<code>(x,y,m=Math)=>x<0&!y?m.PI:m.atan(y/(m.hypot(x,y)+x))*2
</code>```

Uses radians.

Title: golf atan2

Body:
Sometimes it really is a struggle to convert Cartesian coordinates (x,y) to Polar coordinates (r,phi). While you can calculate r = sqrt(x^2+y^2) quite easily, you often need some distinction of cases when calculating the angle phi because arcsin,arccos and arctan and all other trigonometric functions have a co-domain that each only spans half the circle.

In many languages there are built-ins for converting rectangular to polar coordinates, or at least have an atan2 function, which - given (x,y) - calculate the angle phi.

Task

Your task is to write a program/function that takes two (floating point, not both zero) Cartesian coordinates (x,y), and outputs the corresponding polar angle phi, where phi has to be in degrees, radians or grades (with grades I mean gradians which are 1/400 of the full circle), whichever is more convenient for you.

The angle is measured in positive orientation, and we have the zero angle for (1,0).

Details

You may not use built-ins that calculate the angle phi given two coordinates, including atan2,rect2polar,argOfComplexNumber and similar functions. However you can use the usual trigonometric functions and their reverses, that only take one argument. Any unit symbols are optional.

The radius r must be non-negative, and phi must be in the range [-360°, 360°] (it does not matter whether you output 270° or -90°).

Examples

```<code>Input       Output
(1,1)       45°
(0,3)       90°
(-1,1)      135°
(-5,0)      180°
(-2,-2)     225°
(0,-1.5)    270°
(4,-5)      308.66°
</code>```

Body:
Javascript ES6, 54 bytes

(x,y,m=Math)=>x<0&!y?m.PI:m.atan(y/(m.hypot(x,y)+x))*2

Uses radians.


答:
MATL, 12 bytes

```<code>yYy/X;0G0<?_
</code>```

The result is in radians.

Try it online! Or verify all test cases.

Explanation

MATL doesn't have an atan function (it has atan2, but it can't be used for this challenge). So I resorted to acos.

```<code>y     % Take x, y implicitly. Duplicate x onto the top of the stack
Yy    % Compute hypothenuse from x, y
/     % Divide x by hypothenuse
X;    % Arccosine (inverse of cosine function)
0G    % Push y again
0<    % Is it negative?
?_    % If so, change sign. Implicitly end conditional branch. Implicitly display

</code>```

Title: golf atan2

Body:
MATL, 12 bytes

yYy/X;0G0<?_

The result is in radians.

Try it online! Or verify all test cases.

Explanation

MATL doesn't have an atan function (it has atan2, but it can't be used for this challenge). So I resorted to acos.

y     % Take x, y implicitly. Duplicate x onto the top of the stack
Yy    % Compute hypothenuse from x, y
/     % Divide x by hypothenuse
X;    % Arccosine (inverse of cosine function)
0G    % Push y again
0<    % Is it negative?
?_    % If so, change sign. Implicitly end conditional branch. Implicitly display


答:
Python 3, <s>75</s> 67 bytes

8 bytes thanks to Dennis.

from math import*
lambda x,y:pi*(x<0==y)or atan(y/(hypot(x,y)+x))*2
```

Ideone it!

Title: golf atan2

Body:
Python 3, <s>75</s> 67 bytes

8 bytes thanks to Dennis.

from math import*
lambda x,y:pi*(x<0==y)or atan(y/(hypot(x,y)+x))*2

Ideone it!


答:
MATLAB / Octave, 24 bytes

```<code>@(x,y)atan(y/x)+pi*(x<0)
</code>```

This defines an anonymous function that produces the result in radians.

Try it on ideone.

Title: golf atan2

Body:
MATLAB / Octave, 24 bytes

@(x,y)atan(y/x)+pi*(x<0)

This defines an anonymous function that produces the result in radians.

Try it on ideone.


答:
Perl 6, <s> 95 </s> 93 bytes

<s>{(1..*).grep({$/=$_;map {->{$/%$_||($//=$_);$/}...*!%%$_;0},reverse 2,3,&[+]...*>$_;2>$/})[$_]}</s>
{(1..*).grep({$/=$_;map {->{$/%$_||($//=$_);$/}...*%$_;0},reverse 2,3,&[+]...*>$_;2>$/})[$_]}```

<p>( 0 based index )</p>

<h3>Test:</h3>

<pre class="lang-perl6 prettyprint-override"><code>my &fib-prod = {(1..*).grep({$/=$_;map {->{$/%$_||($//=$_);$/}...*%$_;0},reverse 2,3,&[+]...*>$_;2>$/})[$_]}

say fib-prod 0 ..^ 20;
# (1 2 3 4 5 6 8 9 10 12 13 15 16 18 20 21 24 25 26 27)
say time-this { say fib-prod 100 -1; };
# 315
# 1.05135779

sub time-this (&code) {
  my $start = now;
  code();
  now - $start;
}
</code>```

Explanation:

{
  (1..*).grep(
    {
      $/ = $_; # copy the input ($_) to $/
      map { # map used just for side effect
        ->{
          $/ % $_    # if $/ is divisible by the current fib factor
        ||
          ($/ /= $_) # divide it out once
        ;
          # return the current value in $/
          $/
        }
        ... # repeat until that returns:
        * !%% $_ # something that is not divisible by the current fib factor
        ;0
      },
      # the possible fibonacci factors plus one, reversed
      # ( the extra is to save one byte )
      reverse 2,3,&[+] ... *>$_;

      # is the end result of factoring equal to 1
      # ( for the grep above )
      2 > $/
    }
  )[ $_ ] # get the value at 0-based index
}
```

Title: Fibonacci Factorization

Body:
Fibonacci Numbers

Fibonacci Numbers start with f(1) = 1 and f(2) = 1 (some includes f(0) = 0 but this is irrelevant to this challenge. Then, for n > 2, f(n) = f(n-1) + f(n-2).

The challenge

Your task is to find and output the n-th positive number that can be expressed as products of Fibonacci numbers. You can choose to make it 0-indexed or 1-indexed, whichever suits you better, but you must specify this in your answer.

Also, your answer must compute the 100th term in a reasonable time.

Testcases

```<code>n   result corresponding product (for reference)
1   1      1
2   2      2
3   3      3
4   4      2*2
5   5      5
6   6      2*3
7   8      2*2*2 or 8
8   9      3*3
9   10     2*5
10  12     2*2*3
11  13     13
12  15     3*5
13  16     2*2*2*2 or 2*8
14  18     2*3*3
15  20     2*2*5
16  21     21
17  24     2*2*2*3 or 3*8
18  25     5*5
19  26     2*13
20  27     3*3*3
100 315    3*5*21
</code>```

References

Obligatory OEIS A065108

Body:
Perl 6, <s> 95 </s> 93 bytes

<s>{(1..*).grep({$/=$_;map {->{$/%$_||($//=$_);$/}...*!%%$_;0},reverse 2,3,&[+]...*>$_;2>$/})[$_]}</s>
{(1..*).grep({$/=$_;map {->{$/%$_||($//=$_);$/}...*%$_;0},reverse 2,3,&[+]...*>$_;2>$/})[$_]}

( 0 based index )

Test:

my &fib-prod = {(1..*).grep({$/=$_;map {->{$/%$_||($//=$_);$/}...*%$_;0},reverse 2,3,&[+]...*>$_;2>$/})[$_]}

say fib-prod 0 ..^ 20;
# (1 2 3 4 5 6 8 9 10 12 13 15 16 18 20 21 24 25 26 27)
say time-this { say fib-prod 100 -1; };
# 315
# 1.05135779

sub time-this (&code) {
  my $start = now;
  code();
  now - $start;
}

Explanation:

{
  (1..*).grep(
    {
      $/ = $_; # copy the input ($_) to $/
      map { # map used just for side effect
        ->{
          $/ % $_    # if $/ is divisible by the current fib factor
        ||
          ($/ /= $_) # divide it out once
        ;
          # return the current value in $/
          $/
        }
        ... # repeat until that returns:
        * !%% $_ # something that is not divisible by the current fib factor
        ;0
      },
      # the possible fibonacci factors plus one, reversed
      # ( the extra is to save one byte )
      reverse 2,3,&[+] ... *>$_;

      # is the end result of factoring equal to 1
      # ( for the grep above )
      2 > $/
    }
  )[ $_ ] # get the value at 0-based index
}


答:
Jelly, 11 bytes

```<code><0×ØP+÷@ÆṬ¥
</code>```

Output is in radians. Jelly had a sign bug in its division atoms which was fixed.

Try it online! or verify all test cases (converted to degrees).

How it works

```<code><0×ØP+÷@ÆṬ¥  Main link. Left argument x. Right argument: y

<0           Compare x with 0.
  ×ØP        Multiply the resulting Boolean by Pi.
          ¥  Combine the two links to the left into a dyadic chain.
      ÷@     Divide y by x.
        ÆṬ   Apply arctan to the result.
     +       Add the results to both sides.
</code>```

Title: golf atan2

Body:
Jelly, 11 bytes

<0×ØP+÷@ÆṬ¥

Output is in radians. Jelly had a sign bug in its division atoms which was fixed.

Try it online! or verify all test cases (converted to degrees).

How it works

<0×ØP+÷@ÆṬ¥  Main link. Left argument x. Right argument: y

<0           Compare x with 0.
  ×ØP        Multiply the resulting Boolean by Pi.
          ¥  Combine the two links to the left into a dyadic chain.
      ÷@     Divide y by x.
        ÆṬ   Apply arctan to the result.
     +       Add the results to both sides.


答:
Perl 6, <s> 24 </s> 23 bytes

<s>{(|@^a,sum @a)[$^n%3]%2}
{(|@^a,&[+]...*)[$^n]%2}</s>
{(|@^a,*+*...*)[$^n]%2}```

<h3>Test:</h3>

<pre class="lang-perl6 prettyprint-override"><code>use v6.c;
use Test;

constant even = 0;
constant odd = 1;
my @test = (
  ([0, 1], 4)    => odd,
  ([2, 1], 9)    => even,
  ([14, 17], 24) => even,
  ([3, 9], 15)   => odd,
  ([2, 4], 10)   => even,
);

my &seq-parity = {(|@^a,*+*...*)[$^n]%2}

for @test -> ( :key($input), :value($expected) ) {
  is seq-parity(|$input), $expected, ($input => <even odd>[$expected]).gist
}
</code>```

ok 1 - ([0 1] 4) => odd
ok 2 - ([2 1] 9) => even
ok 3 - ([14 17] 24) => even
ok 4 - ([3 9] 15) => odd
ok 5 - ([2 4] 10) => even
```

<h3>Explanation:</h3>

<pre class="lang-perl6 prettyprint-override"><code>{
  (
    # generate the Fibonacci integer sequence
    # ( @^a is the first two values )
    |@^a, *+* ... *
  )[ $^n ] # get the one at the appropriate index
  % 2 # modulo 2
}
</code>```

Body:
If you look at the Fibonacci Numbers, you will notice a pattern in their parity: 0, 1 , 1 , 2 , 3 , 5 , 8 , 13 , 21 , 34 , 55 , 89 , 144. Every third number is even, and all the others are odd. This makes sense because an even plus an odd is odd, but an odd plus an odd is even and the sum for a term will always include at least one even number unless the last two terms were odd, which happens every three terms.

In this challenge you will have to look at a generalization of this problem.

Specs

You will be given as input two positive integers describing the Fibonacci integer sequence you will have to look at.

For example, 0, 1 describes the original Fibonacci numbers, and 2, 1 would be the Lucas numbers. The sequence is calculated with the recurrence relation: x(n+2)=x(n+1)+x(n).

You will also take a positive integer n.

Your code has to output the parity of the nth term of the described Fibonacci integer sequence (0 indexed).

The output format can be any two sane, consistent outputs (e.g. 0 for even and 1 for odd).

Test Cases

```<code>(Fibonacci numbers) [0, 1], 4  ->  odd
(Lucas numbers) [2, 1], 9  ->  even
[14, 17], 24  ->  even
[3, 9], 15  ->  odd
[2, 4], 10  ->  even
</code>```

Body:
Perl 6, <s> 24 </s> 23 bytes

<s>{(|@^a,sum @a)[$^n%3]%2}
{(|@^a,&[+]...*)[$^n]%2}</s>
{(|@^a,*+*...*)[$^n]%2}

Test:

use v6.c;
use Test;

constant even = 0;
constant odd = 1;
my @test = (
  ([0, 1], 4)    => odd,
  ([2, 1], 9)    => even,
  ([14, 17], 24) => even,
  ([3, 9], 15)   => odd,
  ([2, 4], 10)   => even,
);

my &seq-parity = {(|@^a,*+*...*)[$^n]%2}

for @test -> ( :key($input), :value($expected) ) {
  is seq-parity(|$input), $expected, ($input => <even odd>[$expected]).gist
}

ok 1 - ([0 1] 4) => odd
ok 2 - ([2 1] 9) => even
ok 3 - ([14 17] 24) => even
ok 4 - ([3 9] 15) => odd
ok 5 - ([2 4] 10) => even

Explanation:

{
  (
    # generate the Fibonacci integer sequence
    # ( @^a is the first two values )
    |@^a, *+* ... *
  )[ $^n ] # get the one at the appropriate index
  % 2 # modulo 2
}


答:
JavaScript (ES6), <s>50</s> 40 bytes

```<code>(x,y)=>(Math.atan(y/x)||0)+Math.PI*(x<0)
</code>```

The result is in radians. Edit: Saved 10 bytes when I noticed that it's allowed for the result to be between -90° and 270°. Previous version with -Math.PI<=result<Math.PI:

```<code>(x,y)=>(Math.atan(y/x)||0)+Math.PI*(x<0)*(y>0||-1)
</code>```

Title: golf atan2

Body:
JavaScript (ES6), <s>50</s> 40 bytes

(x,y)=>(Math.atan(y/x)||0)+Math.PI*(x<0)

The result is in radians. Edit: Saved 10 bytes when I noticed that it's allowed for the result to be between -90° and 270°. Previous version with -Math.PI<=result<Math.PI:

(x,y)=>(Math.atan(y/x)||0)+Math.PI*(x<0)*(y>0||-1)


答:
Python 2, <s>129</s> <s>128</s> <s>125</s> <s>123</s> 121 bytes

g=lambda k:1/k|any(abs(round(5**.5*i)**2-5*i*i)==4>k%i<g(k/i)for i in range(k+1))
f=lambda n,k=1:n and f(n-g(k),k+1)or~-k
```

Test it on Ideone.

Title: Fibonacci Factorization

Body:
Python 2, <s>129</s> <s>128</s> <s>125</s> <s>123</s> 121 bytes

g=lambda k:1/k|any(abs(round(5**.5*i)**2-5*i*i)==4>k%i<g(k/i)for i in range(k+1))
f=lambda n,k=1:n and f(n-g(k),k+1)or~-k

Test it on Ideone.