title: Sort a list and write some English!

text:
# Question
Title: Sort a list and write some English!
Your boss managed to read the secret hidden message. He didn't end up firing you, though, he just made you a secretary and forbade you from writing code.

But you're a programmer. You need to write code. You *must* code.

Therefore, your code needs to look as similar to English as possible, make sense, and look as little like code as possible. Your code should take a list of integers (either in a function, or STDIN), and return that list sorted (returning it, or STDOUT).

Any language can be used, but I'm looking for the most creative solution, (kudos if your code looks like a business letter).

This is a popularity contest!

# Answer
> 178 votes
# GolfScript

> Dear Boss Man.
>
> It came to my attention that my keyboard needs replacement; the keys required to write the
> symbols ~ $ \` . and } are not functioning properly.
>
> It's very difficult to work like this! Please instruct the IT department to exchange the faulty
> keyboard as soon as possible.
>
> Sincerely,
>
> Dennis

Try it online!

### How it works

* > Undefined tokens (e.g., most English words) are noops in GolfScript.
* > `. ;` duplicates the input string and discards the copy.
* > `~ $` evaluates the input string and sorts the resulting array.
* > ``` inspects the array (for pretty printing).
* > `. and` duplicates the output string and discards the copy.
* > `}` is a "super comment" since it is unmatched; everything following it is ignored.

# Answer
> 124 votes
# PHP

Defines a function called `item` that will sort an array that you pass it.

```
Dear Boss,
I have successfully discovered all brackets.
The ones marked with question marks are the ones which I am not sure about.
The ones marked with asterisks can be used both as an opening and closing delimiter.
(
)
{
}
[
]
>?
<?
/*
'*
"*

Thank you for reading my memo. In other news, the */ function item (#12 in the list of things that have an asterisk before them) was discovered recently, which I read on a local news site.
#12 is my favorite function item! Just thought you'd be interested. Sorry if this is too off-topic; here's some business stuff. Imagine that you had some (let's say you have a combination of $10
& $money) # of dollars (i.e. you have $10 + $money). Now, here's the important part. It's so important, I'll separate it from the rest of this message with the brackets I discovered:

{
#10 in my personal list of things to remember about money management is that you have to be careful. I still haven't been able to
sort #9 out yet (I bought the manual from someone else), but #9 also seems to be about being careful. You also have to guard the dollars
($money); #13 says that if you don't protect them by putting them in a bank or something, they might be stolen.
}

   //-----------------------\\
  //   Signed,               \\
  //   Your great employee   \\
   //-----------------------\\

```

It looks much better if you paste it into a text editor and resize the window so that you can see the entire thing on your screen at once.

# Answer
> 77 votes
# Python 2

```
'''''''''''''''''''''''''''''''''''''''''''''
One of the phones in the office seems to be broken, so it needs to be fixed.

''''''''''''''''''''
This memo was made while testing the functionality of its buttons since
some of them didn't seem to work.
''''''''
1 (no alphabets) working with no problem
''''''''
abc working with no problem
'''''''''
def working (partially):
 please                                              =( 'o" :\
 at least I figured out that this was a problem!     :')
 # list (phone number list) was missing as well, so I need to:

 #1
 print (please, sorted (partially)) [1] # list, and [2] the memo
 #2
 return
 #3
 check (making-sure, ghi-jkl-etc. works)

''''''''''''''''''

```

# Answer
> 72 votes
## Python 2

```
'''
                        5th of September 2014

Dear Boss,

I  am writing    this Mail because     i want to discuss
 the recent   incident.
I am Thankful    that you did not fire   me, and gave me a secretary position instead.
I dont have any    experience in being a     sec retary and I am not very. good at   writing mail,
so please   excuse any spelling,   grammar or   formating   errors  in     this mail.

I will       certainly     try to improve  and do   my best in my new job      and will'''
'from now on strictly ';exec'''ute your orders.   =
Firstly      i want to    sincerly        apologize my   dumb behaviour,it was  idiotic ( and childish ).
I   really  ;apologize  to you. it  wont  .happen again, sir. If   i   could
 only   reverse   the  timeline       (to undo it all). Then i would;
I   really   promise to never  write  code in any form

Can i talk about that   in   a   meeting with  you?
  Maybe    today at'''[4::15]#in the afternoon?

```

Finding the right words was a real pain.

Input: \[1,7,4,3\]
Output: \[1,3,4,7\]

# Answer
> 66 votes
# NetLogo

```
To Manager [IT]

Let Sue sort it; then
show Sue the end to the end

```

With indentation and capitalization changes, the code becomes clear(er). This defines a function called `manager` which takes a list as input and prints the list sorted.

```
to manager [IT]
  let sue sort IT; then (semicolons introduce a comment)
  show sue
  the
end

to the
end

```

# Answer
> 63 votes
# C

Input as space-separated list through STDIN, output as space-separated list through STDOUT.

```
Dear Boss,

I have made for you a decision about my employment a t your company. At about noon
a letter explaining this shall be presented to you, as I am a lazy person. As you
are a fool, I will say no more. And I look forward to never seeing you again.

Insincerely,
Steward Pitt

```

This should be compiled with:

```
gcc bossletter.c -o bossletter -Dam='+++' -Dwill='---' -Dthis='{' -Dhave=';'
-Ddecision=',' -Dquit='*' -Dfor='(' -Dmy=')' -Dbrain='}' -Dlie=']' -Dnoon='-quit'
-DD='' -Dto='D' -Dyou='D' -Dfool='you' -Das='to' -Dday='D' -Dno='fool' -Dcake='Pitt'
-Dlook='you' -DPitt='the' -Dthe='as' -DBoss='a[9999 lie' -DAs='a have' -Dlazy='my'
-Dperson='lazy have company' -Dyour='this' -DInsincerely='a' -Dcompany='b'
-Demployment='int quit' -DDear='struct this employment a have brain b have'
-Dbe='scanf for' -Dis='I[' -Dnever='for presented " " decision' -Dthat='4 decision'
-Dagain="my have b" -Dt='decision quit about have' -Dshall='while for'
-Dpresented='"%" to "d"' -Dletter='have brain' -DAt='a have return quit'
-Dmore='have b' -DAnd='a have shall' -Dare='qsort for' -Dforward='--my printf'
-Dexplaining='main for my'
-Dsay='1 decision that made my day'
-DSteward='Boss have no brain'
-Dseeing='the cake is a lie'

```

The code expands to:

```
struct{ int *a; } b;
a[9999], I;
made(a, about) int *a, *about; {
    b.a;
    return *about - *a;
}
main(){
    while(scanf("%d", I++ + a));
    b.a;
    qsort(a, I-- - 1, 4, made);
    b.a;
    while(I--) printf("%d ", I[a]);
    b.a, a[9999];
}

```

# Answer
> 25 votes
# Python 2 & 3

### Unfortunately, the employees of today just can't stop using hashtags all over the place...

```
#WritingALetter #Business    Dear Boss,
#SecondLine    I found this scrap of paper on the floor. It said "

def sortl(l):        # define a function
    return sorted(l) # returns the list, sorted "

#ScrapOfPaper    Just thought I should let you know.
#Honesty    From Laurence

```

\[Worth a try, I guess?\]

# Answer
> 23 votes
# Dogescript

It's basically English, right?

```
shh oooot! my  keyybr oad is brokn. i ne ed neew 1.
such fixs much keys
keys dose sort
wow keys

```

translates to:

```
// oooot! my keyybr oad is brokn. i ne ed neew 1.
function fixs(keys) {
    keys.sort();
    return keys;
}

```

# Answer
> 22 votes
# Detour

```
Dear Boss Man
I thought I had put your recovered files on drive z.
In reality it was downloaded to the main drive, C://users/boss/recovery. Sorry for the confusion!

```

Interpreter Permalink

How it works:

> The only important part is `://`, and the line above it, `z.`. `:` means "put input here", the first `/` reflects it up to `z`, which is sort; it then goes up, wraps across the top, keeps going up from the bottom, then hits `/` from below, which bounces it left to the other `/`, which does the same thing, except this time wrapping around to `.`, or output.

Simplified version:

# Detour

```
Dear Boss Man
             z.
            ://

```

Try it online!

# Answer
> 20 votes
# Brainfuck

```
Hey boss! This is the public key that you asked!

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

Pretty cool huh?

```

Copyright note:

> Note: I copy pasted it from here. As far as I know, that codes from site are has copyright cc by-sa 3.0 with attribution. If this method is illegal, let me know and I will try to delete this.

# Answer
> 18 votes
## JavaScript

I'm not sure if I can outsmart him, but I can throw him off my trail!

```
/*Hello Bossman
I feel the need to alert you to a pressing matter.
Nothing Dan from Marketing's head seems to be */function/*ing anymore.
I have a lot of evidence, but not enough time to */sort/* through it.
Should I just send it to you directly */(/*although I'm sure you have about a thou*/s/*and other things to do*/)/*?
Nah, here's it in a summary:

Dan seems to be overly facinated by the */{/* key on his keyboard, and presses it many times a minute.
He */return/*ed his new Galaxy */s/*4, after trying to eat it, multiple times.*/.

/*When Dan was tasked to */sort/* through the Haberson account, he attempted to stab his computer multiple times with a ruler */(/*he was eventually deterred by Jenny)
Everyone backed off for a few days, but we all remembered.
Later, we approached him about the incident, he claimed hostile working conditions and that he was unable to */function(/*.
I think he m*/a/*y need to see a psychatrist.

None of us feel safe to approach him on the topic again*/, b/*rining up conflict is something most of us like to avoid. (except Jenny*/)
{/*Dan was then moved to a different spot in the building, in an attempt to give him a new environment.
Despite the move he */return/*ed to his old desk every day, and wrote */a - b/* on the walls of the new spot.
We all just sort of accepted that and the layout planner gave up after a week or two.

One week we got a new employee in the office. When she went to say Hi to Dan, he screamed a - b over and over.
Not sure what his fascination is there. b-c is a much superior algorithm.

We're not really sure what caused this, but one day he switched from the { key to the */}
/*key. Dan switched back the next day.

There is an ongoing betting pool on what will happen next (general categories mostly*/)
/*Currently the betting for him stabbing an actual person is at almost $20,000.

Please do something about Dan. If anything start a reality TV show from the security tapes.

On a completely unrelated note, I love this new */}/* key, it's really neat looking. Did my keyboard always have this?
Sincerely,
Zeke*/

```

> `function sort(s) { return s.sort(function(a,b) { return a-b }); }`

# Answer
> 16 votes
# Vyxal

```
Dear Boss,

Quite worryingly, the printer has stopped working. Please bring a hammer, a battleaxe and a potentiometer.

Sincerely,
Joe

```

Try it Online!

By some miracle, `Dear Bo` leaves the original input on top. `ss` sorts it twice, `,` outputs, `Q`, halts the program, then the rest is unexecuted.

# Answer
> 12 votes
# LiveScript

Try figuring this one out...Been sending him emails like this the whole time to allow for easy, more versatile copy-paste.

```
# Mr. Boss,
#
#     So, I'm done with this job. It is driving
#     me crazy. We aren't allowed to have *any*
      fun =#(. I am planning on leaving this
#     company while you all poorly attempt to
#     sort all this out. Also, I would like to
#     mention that a specific single bit in the
       sort # for your in-house algorithm gets
#     inverted. Happy hunting while I have fun
#     programming for another company far more
#     grateful than yours.
#
# Best regards,
# Your handy little programmer-turned-secretary.

```

> 1. Its standard library, Prelude.ls, has a native sort function.
> 2. Note the two missing hashes (comments). The first is far more obvious than the second.
> It parses as this: "fun = sort", and compiles to this: "var fun; fun = sort;"

# Answer
> 8 votes
# JavaScript (ES6)

```
      (a) => /*----------*\ <= (a)
       |      Announcement      |
  .   (a)    \*----------*/    (a)   .

 sort (/* YOUR DOCUMENTS BEFORE 2/5 )*/

     ($,_) => /*--------*\ <= (_,$)
      |         Warnings         |
 //  (_-$)    \*--------*/    ($-_)  //

      /*( NO SMOKING IN OFFICE */)

```

Try it online!

Yes, I know the boss likes fancy decorations in his notices so I capitalized the texts and surrounded the texts with fancy symbols :)

**PS. Why is the office still using TELNET?**

> Actually, removing comments and redundant blanks makes the stuff into `(a)=>(a).sort(($,_)=>($-_))`, and that's what the stuff intends ;P

# Answer
> 8 votes
# 05AB1E

```
Dear Boss‚

I hope I{qualify for this new function. I once again want to sincerely apologize for my earlier secret message.
Thank you for giving me the opportunity to work at this department instead.
I must admit it's hard to resist the urge to write code, but I'll do my best.

Thank you.

Kind regards from your new secretary,
Kevin Cruijssen

```

Try it online. (TIO uses the legacy version which is a bit faster. Works the same as the new 05AB1E version, though.)

**Explanation:**

05AB1E code ignores newlines and spaces outside of strings or compressed string/numbers (except when using the (if-)else-statement I just found out in an earlier attempt of making this program.. \>.\>), so let's do the same in this explanation.

```
DearBoss‚Ihope # These are all no-ops; they do execute, but won't affect the output:
D              #  Duplicates the (implicit) input-list
 e             #  Calculates the number of permutations of each item in the list
               #  (NOTE: this might time-out depending on the values in the input-list)
  a            #  Check if these numbers are letters (becomes a list of 0s / falsey values)
   r           #  Reverse the items on the stack
    B          #  Base conversion
     o         #  Raise 2 to the power of each number
      s        #  Swap the top two items on the stack
       s       #  Swap the top two items on the stack
        ‚      #  Pair the top two items
               #  (NOTE: This is not a regular comma (,), since that would print the top of
               #   the stack to STDOUT, which we of course don't want here.)
         I     #  Push the input-list again
          h    #  Convert each value to hexadecimal
           o   #  Raise 2 to the power of each integer value
            p  #  Check for each if it's a prime
             e #  Calculate the number of permutations of each item again

I{q            # Then the actual program comes:
I              #  Push the input-list
 {             #  Sort it
  q            #  Stop the program
               #   This makes everything that comes after it no-ops
               #   And will output the top of the stack implicitly as result

```

Try it online with added debugger-mode to see all this in action.

# Answer
> 5 votes
# JavaScript (Node.js)

```
Attachment => (

`Date: 2019/5/30

Dear my Majestic Boss,

Re: Business Trip to Japan

I'm writing to confirm itinerary for the next trip to Japan will be as follows:

`? (Tennoji, Osaka) => ("Shinsaibashi Tower", Osaka)

|| // Day 1

Tennoji [Osaka, "sort"]
(Hotel = (JPY$14112, Taxed) => `So I will stay here for one night, and I will be charged this price:

`? JPY$14112 + (0 - Taxed)
:`This is the total price and what I will claim afterwards.`

):0) (Attachment)

|| // Day 2

"Shinsaibashi Tower" [Conference, `NOT FOR SHOPPING`]

`I will be coming back on Day 2, so the trip will not cost too much hopefully.

Best regards,
The-former-programmer`

```

Try it online!

Okay this is an itinerary apparently. Another answer in different direction after one year.

> The really important part is `Attachment => (Tennoji => Tennoji["sort"]((JPY$14112, Taxed) => JPY$14112 - Taxed))(Attachment)`

# Answer
> 5 votes
# CJam

```
Hi; Isaq

\~O~/
 (1)
 @O@
/   \*

*~50 Times!

;;  WINNINGS  ;;
;;            ;;
;;]  $10000O  ;;

p1 is "where Kings sit', according to Shakesphere or someone. All I know is that after 4 straight years
of earning second in the national clown contest, it sure feels great to be on top for once. My clown
ASCII art could use some work, but hopefully I did a solid representation of our troupe. I can't believe
this was the one year you were sick, but we went and earned the $100k in your absence.

See you Monday,

Ethan

'I remain just one thing, and one thing only, and that is a clown." -

```

Try it online

Apparently my job is at a clown troupe that just won the grand prize, my boss's name is Isaq, and my signature didn't work and forgot to credit Charlie Chaplin.

Notes:

> This was afwul. CJam throws an error on any character that isn't a command or whitespace, or when we try to take input but there isn't any, or you try to do a command but the stack's empty, etc. This means that `knruvxylqo` is unusable for the actual code (except the one `q` at the start to load in the array), and `emth` are also notably difficult. So of the famous rstlne from Wheel of Fortune, we have left... s. English is going to be hard. I'll be explaining what happens on each character, but not really why because there's so much to go through, especially with the clown. (also I don't know why a couple of the things work shh...)

Explanation:

> I tried a few greetings to open us off (`Greetings`, `Hello`, etc.) and `Hi` was the only viable one. The others either threw errors or consumed input. `Hi` just pushes 17 and makes sure it's an int. The `;` then throws that 17 away.

> `Isaq` gives us `["18"]` by pushing 18, stringifying it, and putting it in an array. `q` then gives us our input array as a string.

> Row one of the clown: `\` swaps our two elements. `~` takes "18" out of the array. `O` pushes an empty string. `~` makes it disappear. `/` throws away "18" but puts our input string into an array.

> Row two: `(` takes our input out of the array, but leaves an empty string before it on the stack. `1` pushes 1. `)` increments that 1.

> Row three I brute-forced after writing row 5, because I knew kinda what I needed it to do. `@` rotates our array so the input is on bottom and empty string on top, `O` adds another empty string, and `@` rotates it so 2 is on top.

> Row four: `/` gets rid of the 2, `\` swaps the identical empty strings, and `*` gets rid of one of them.

> Out of the clown now. The next `*` gets rid of our other empty string, leaving just the input string. Finally, we parse it into a bunch of numbers with `~`. `50 Times!` ends up just pushing a 50 and a 0 when all is said and done.

> Now into the winnings block. `;;` gets rid of our 50 and 0. `WINNINGS` takes advantage of the fact that CJam doesn't yell at you if you scream at it because capital letters are variables. Unfortunately, that means it also pushes a bunch of junk. The next 8 `;`s take care of that.

> We're just back to our input numbers now. We'll use a not-so-sneaky `]` to turn them into an array and `$` to sort them. We just need to output with `p` now, but unfortunately for it to make sense we need some money first. We push `10000`, plus an `O` because we need two things for the upcoming semicolons to destroy.

> After a simple `p`, we've printed our sorted array! It's not much of a letter though. `1` and `is` are harmless. We start a quote with `"`, then end it with `'` to let us write in English unimpeded. We do the inverse with a quote at the end to close up, and the `-`throws what we have left on the stack away so it doesn't automatically output. This way, it looks like we intended to attribute the quote, but forgot.

# Answer
> 4 votes
# Jelly, 91 bytes

```
Gee Boss,
Go to Starbuck. Whoops, forgot the (sorry for the dot, my keyboard's messed up)
Ṣ

```

Try it online!

# Answer
> 3 votes
# Groovy

```
'Dear Bossman,
I finally found the formula to calculate the salary for the new employees.
In the salary software just enter the following:'
print "${(args.toList()*.toInteger()).sort()}"'
Sincerely,
Employee'

```

# Answer
> 3 votes
# Excel

```
=LET( me, say that I understand your decision.  I was hoping to work our issues, out, B4#,
things, got so out of control. I hope we can as Boss and, Programmer, SORT(out), our,
issues and work better together in the future,

Sincerely,
John Smith, Programmer)

```

# Answer
> 2 votes
# Zsh

I don't know whether the code or the creative writing was harder.

```
: RE: The state of the evaluation process; eval `#problems'

: While I appreciate your enthusiasm, going to `print `
: this for the world to see isn't helpful in the long run.
: Please, don't make any more enemies than you already have.
:
: > People seem to just want that `'$'`: It's a big problem
: > which needs to be resolved. People need to buy into the
: > company's team-based philosophy `'{'`: ... ''}''
:
: While I do not deny that people "just want that '$'",
: I absolutely disagree that it's a _bad_ thing. Employees
: should not be guilty for wanting to leave for greener
: pastures, so you should try and provide _some_ incentive
: to stay.
:
: > And yet everyone want's to just check "(y)" or `'(n)'`
: > without giving _any_ further feedback... You're too LAZY!
:
: I want to stop you here. Accusations like this against my
: team are _not_ to be tolerated. We do a _lot_ behind the
: scenes which you _clearly_ aren't aware of. Please refrain
: from `'@-ing'' any of my team, and think with a bit more
: empathy next time, thank you.

-- Gamma :-}'

```

Try it online!

* > Note: This will create files named "People" and "without" in the directory it is run from.
* > From the first line, you can see the `eval`, followed by backticks.
* > `# comments` continue to end-of-line, stopping quotes or backticks from being resolved, so we use `:` no-ops to indent.
* > The standard pattern we make use of throughout this is ``: lots of filler text....
> : more filler text, then an important `'X'`
> : back to the garbage`
* > At the end is one exception: Everything from `@-ing` to the last `}` is not no-op'd.
* > When the substitution has finished, it reads: `eval print $'${(n)@-ing any of my team, and think with a bit more\n: empathy next time, thank you.\n\n-- Gamma :-}'` The garbage after the `@` does nothing, so this is equivalent to `print ${(n)@}`, which is simply a numeric sort of the parameters.

# Answer
> 1 votes
# Ly

```
Dear BOss Ma&n.

    That jOb P&uts me in one of the best
    emotions that I've ever had!

    As for my recent incident, I promise that I
    will never touch code ever again. Thanks a
    lot for allowing me to be a secretary instead
    of firing me!

Your faithful secretary,
petStorm

```

Try it online!

# Answer
> 1 votes
# JavaScript

```
/*
I always start my letters with /* because it means "slashstar", a great name for a weapon.
So in case you forgot what an asterisk was, */asterisk/*is used as a sidenote in papers, and the function it serves */=/*is to get on your nerves when I write */papers/*. You made me a secretary */=>/* I really enjoy my job. Now, I need to sort the */papers/* in order because you like neat and tidy things. So I made a method */./* A guide to */sort/*ing follows: Start by finding the first paper */(/*the one on top), and then find the next one, */(/*wh*/a/*tever follows*/,/* nothing else.
Then compar*/e/* them and place the longer one on top.
Next, repeat (the process I told you before*/)/* */=>/* you should already see a clear pattern emerging. One of the best ways to compare, if you like automation, is */a-e/*, this returns the difference in characters.
In the end, (having gone through all the papers*/)/*, you should have a sorted pile of papers.

Regards,
Secretary ;(
*/
```

A secretary who seems to enjoy his job on the outside gives his boss a method of sorting his messy pile of papers in an attempt to get his coding job back.

# Answer
> 1 votes
# Pyth

Dang those bounce back emails, I've been broke ever since the boss started charging us for every mistype. And he wonders why I wanted to quit in the first place...

```
De$tination_unreachable:"Reason message:\
Couldn't find the address theboss@company.xom\
Company email servers charge for wasted electricity on bounce back emails:\
In this case, the charge was " $ 596.42; "\
Remember, this charge is employee specific, so make sure it doesn't happen again :3\
Please be more careful when typing your email addresses in the future.\

If you would like to refute this charge, your transaction ID is: " pSSQhaYk ";

```

# Answer
> 1 votes
# Javascript

```
s=/*  <k6cM   L    zE0        2]B^   cyF   #hq%  m(xg
[   ; u      e &  &   V       1   + T   H h     =
$   T }cJF* H7Yj} *&P8        n^D>  N   ;  0O+   [G{
<   s >     w   < S  8        (   Q !   2     9     2    {
Ya8u  qf]?H Z   J 6   5       sRvz   **/  x=>x  //yE    c

.sort         (   (   a         ,          be)   =>a   -be   )/*(  DM@    r   E   v ]   9 g0$wh  QBD
  0          { 1  3x EK        $ f        D   9 a   I 3   D P     @   !  > *  %6 hd I{ 9D {     *   %
  P         )Di!D N x #       h%8>f       rM;5  }2d]  @   b g  =+ hTJ}  $;yC? H z s V S 1 U{zBV ;SRV
  i         a   s G   4       Q   {       3     G  T  c   H z   l r  8  Z   | a   0 *   T C     S  9     p
+0oUy       1   I t   8       B   ^       w     h   +  O?P   #%4  {   ] l   Z D   M [   W LPTIx L   *   K

r   ]  ffv  ]3DUs         p          0u1l Q-*:a  -E{   ssD  0uLoS Aw@77   j    ^QU  V   @
sF  G 6   1   f          A J        n     n     &   * +   I m       L    n 5  y   O  % h
C x N !   j   k         =)fy9        g]Y  ;fvcN V     R;0D  (1wy+   d   QrXc7 +@c}    X
{  f+ o   W   z         |   5           } -     r   P $  %  J       t   B   1 C  z    C
>   f  cVR    l         1   K       [5Vw  mvQ2g  j[K  +   # g2G-)   -   W   L f   (   J     H

WhA|F        6fi  }   F 0T4AI jmx#I       e   D  <tG  O   z
  H         W   ( I   4   W     M         TZ  Z *   r z   e
  ]         g k W <   q   X     1         { Y r p   } t   Z
  9         M  (  a   i   G     e         >  s{ 4   ^ 2 9 n
Y9S=y        xc $  1P|  gOnp*   Q         0   b  s#P   [*/

```

Maybe he likes art? I mean, it's almost readable...

> When comments and whitespace are removed you get `s=x=>x.sort((a,be)=>a-be)` and that's all that matters.

# Answer
> 1 votes
# Jelly

```
Dear Boss,
    One of the apps on the electronic is not working. I need this to be fixed ASAP.

Thanks,
    MarṢ

```

Try it online!

# Answer
> -3 votes
**C#**

// Dear Boss Man,

```
/*i have a */public/*shed a*/ List /*of*/ <string>/*s
to*/ Sort /*for you on our internal website
please take a look at the */(List /*of*/ <string>/*s and*/ check){
/*them for company restrictions. please also */check /*the */.Sort();/*ing of the     list*/
/*furthermore could you please */return /*an email to me in which you state your */check/*ing state*/;}

// sincerely your slave Rob

```

---
Tags: popularity-contest, number, sorting, obfuscation
---


title: Sort numbers in a ragged list

text:
# Question
Title: Sort numbers in a ragged list
Given a ragged list, e.g.

```
[[4, 7], [5, 3, [], [6, [2]]]]

```

Your challenge is to sort only the numbers in it. For example, with the above, the result would be

```
[[2, 3], [4, 5, [], [6, [7]]]]

```

The shape of the output should remain the same, only the numeric contents should change.

This is , shortest code wins!

All numbers will be unique positive integers. You may do input / output with strings.

## Testcases

```
[2, [3, [1, []]]] -> [1, [2, [3, []]]]
[6, 5, [[9]], 7] -> [5, 6, [[7]], 9]
[12, [43, 51], [[23, 4], 9, [22, []]]] -> [4, [9, 12], [[22, 23], 43, [51, []]]]
[9, 4, 2] -> [2, 4, 9]

```

# Answer
# Jelly, 3 bytes

```
FṢṁ

```

Try it online!

## How it works

```
FṢṁ - Main link. Takes a ragged list R on the left
F   - Flatten R
 Ṣ  - Sort the flattened R
  ṁ - Mold the sorted flattened R into the same shape as R

```
> 13 votes

# Answer
# Ruby, ~~51~~ 47 bytes

```
->l{eval"#{l}".gsub(/\d+/,'%d')%l.flatten.sort}

```

Try it online!

-4 bytes thanks to Sisyphus
> 10 votes

# Answer
# , 29 bytes

```
\(l)relist(sort(unlist(l)),l)
```

Attempt This Online!
> 8 votes

# Answer
# Wolfram Language (Mathematica), 32 bytes

-2 bytes thanks to @att.

```
#/.Thread[#->Sort@#&@Flatten@#]&

```

Try it online!
> 6 votes

# Answer
# Wolfram Language (Mathematica), 34 bytes

```
0#/.(i=0):>Sort[Flatten@#][[++i]]&

```

Try it online!

Also works if input numbers are not unique.

```
0#                                  numbers become 0
  /.   0 :>                         replace 0s (in order) with:
    (i= )  Sort[Flatten@#][[++i]]     the corresponding sorted value

```
> 6 votes

# Answer
# Retina, 5 bytes

```
N`\d+

```

Try it online.

**Explanation:**

Sorts all numbers of 1 or more digits in the input in numerical order, and leaves every other character unchanged (including their positions).
> 5 votes

# Answer
# JavaScript (Node.js), 62 bytes

```
n=>n.replace(r=/\d+/g,_=>n.match(r).sort((a,b)=>a-b)[i++],i=0)

```

Try it online!

Probably defeats the purpose of the challenge, but it is valid. Takes in a stringified list and outputs a stringified list. Replaces the `i`-th number (via string replacement) with the `i`-th element of the list of sorted numbers.
> 4 votes

# Answer
# 05AB1E, 19 bytes

```
"DdiI˜{¾è¼ë®δ.V"©.V

```

Unfortunately, a simple flatten and replace/transliterate doesn't work on nested lists apparently. So instead, the default recursive approach I've used in multiple other challenges have been used.

Try it online or verify all test cases.

**Explanation:**

```
"..."     # Create the recursive string explained below
     ©    # Store it in variable `®` (without popping)
      .V  # Evaluate and execute it as 05AB1E code
          # (after which the result is output implicitly)

D         # Duplicate the current item
          # (which will be the implicit input-list in the first iteration)
 di       # If it's a (non-negative) integer:
   I      #  Push the input-list
    ˜     #  Flatten it
     {    #  Sort it
      ¾è  #  Get the `¾`'th value of this sorted list
        ¼ #  Then increase `¾` by 1
  ë       # Else (it's a list instead):
    δ     #  Map over each inner list:
   ® .V   #   Do a recursive call for each

```
> 4 votes

# Answer
# Python 3.8 (pre-release), 89 bytes

```
def f(L):a=re.split('(\d+)',L);a[1::2]=sorted(a[1::2],key=int);return''.join(a)
import re

```

Try it online!

I/O are strings.

## How

This simply ignores the nesting by picking out groups of digits sorting them and putting them back into the gaps.
> 4 votes

# Answer
# Factor \+ `sorting.human`, 93 bytes

```
[ find-numbers [ string? ] partition natural-sort [ present ] map 2array round-robin ""join ]

```

Try it online!

## Explanation

```
                       ! "[6,5,[[9]],7]"
find-numbers           ! { "[" 6 "," 5 ",[[" 9 "]]," 7 "]" }
[ string? ] partition  ! { "[" "," ",[[" "]]," "]" } { 6 5 9 7 }
natural-sort           ! { "[" "," ",[[" "]]," "]" } { 5 6 7 9 }
[ present ] map        ! { "[" "," ",[[" "]]," "]" } { "5" "6" "7" "9" }
2array                 ! { { "[" "," ",[[" "]]," "]" } { "5" "6" "7" "9" } }
round-robin            ! { "[" "5" "," "6" ",[[" "7" "]]," "9" "]" }
""join                 ! "[5,6,[[7]],9]"

```

Here's a slightly longer version that works on native sequences:

```
[ [ flatten natural-sort ] keep 0 -rot [ dup real? [ drop 2dup nth [ 1 + ] 2dip ] when ] deep-map ]

```
> 3 votes

# Answer
# APL(Dyalog Unicode), 19 bytes SBCS

```
∊{a⊣(∊a)←⍺[⍋∊a←⍵]}⊢

```

Try it on APLgolf!

A tacit function which takes a ragged array.

# Explanation

```
∊{a⊣(∊a)←⍺[⍋∊a←⍵]}⊢ Pass in:
                  ⊢ The input as is on the right
∊                   The flattened input on the left.
 {a⊣(∊a)←⍺[⍋∊a←⍵]}  and do the following:
            a←⍵     assign right arg to 'a'
         ⍺[⍋∊   ]   sort the flattened input
    (∊a)←           assign this result to 'a', preserving structure
  a⊣                return modified 'a'

```
> 3 votes

# Answer
# Perl 5 `-p`, 37 bytes

```
@a=sort{$a-$b}/\d+/g;s/\d+/shift@a/ge

```

Try it online!
> 2 votes

# Answer
# Vyxal, 38 bytes

```
1N→_a`\d+`?λ←_a1+→_a`\d+`?Ẏ⌊s←_a iS;øṙ

```

Try it Online!

Thanks @lyxal for helping me a lot in chat. I've never posted any Vyxal answers before.

This is a port of my JavaScript solution. Takes a stringified list (provided with backticks around a Python-like list syntax).
> 2 votes

# Answer
# PARI/GP, 86 bytes

```
a->i=#l=[];t(b->l=setunion([b],l),a);t(b->l[i++],a)
t(g,a)=iferr([t(g,b)|b<-a],e,g(a))
```

Attempt This Online!

## Explanation

Here is a helper function to traverse a ragged-list, since we need to traverse the input twice:

```
t(g,a)=iferr([t(g,b)|b<-a],e,g(a))

```

`t(g,a)` traverses the ragged-list `a` and replaces each number in it with `g(a)`.

When `a` is a number, the list comprehension `[t(g,b)|b<-a]` will throws an error. `iferr` will catch this error and return `g(a)`.

When `a` is a list, `[t(g,b)|b<-a]` doesn't have an error. It returns a list of `t(g,b)`, where `b` runs through `a`.

Now look at the main function:

```
a->i=#l=[];t(b->l=setunion([b],l),a);t(b->l[i++],a)

```

This is an anonymous function with argument `a`.

First it initializes `l` to `[]`, `i` to `#l` (the length of `l`, which is `0`).

Now it can do the first traversal: `t(b->l=setunion([b],l),a)`. For each number `b` in the list, it set `l` to the union of `[b]` and `l`. PARI/GP doesn't have a separated type for sets. A set is just a sorted list without duplicate elements.

Then it does the second traversal: `t(b->l[i++],a)`. For each number `b` in the list, it increments `i`, and replaces `b` with the `i`'th element in `l`. This gives the final result.
> 1 votes

---
Tags: code-golf, array, sorting, ragged-list
---


title: Write a Quine in Plain English

text:
# Question
Title: Write a Quine in Plain English
Write a quine that consists of real English words separated by single spaces. A "word" is defined as a string containing only lowercase and uppercase letters (`/[a-zA-Z]+/` in regex). To be "real" your word must be recognized by the official Scrabble dictionary.

I'm using the Scrabble dictionary since it gives a definitive answer on what is and isn't valid. There are too many gray areas with a normal dictionary. Note that "A" and "I" (not to mention "quine") are not valid scrabble words.

Since writing a quine *only* using letters and spaces is close to impossible in most programming languages, you have the option to replace the single spaces between words with a character of your choice. You also have the option to append characters to the front of the first word and the end of the last word. These added characters may be anything (including newlines and non-ASCII) **except letters (a-z, A-Z)**. There is a penalty for adding them though (see Scoring.)

# Details

* As usual, the quines may not read or access their own source code. (I'd say that HQ9+'s Q command violates this.)
* Output should go to stdout or a similar alternative. There is no input.
* The words do not need to be capitalized correctly. They can have caps and lowercase anywhere. The sequence of words does not need to make any sense.
* No word may be used more than 3 times in your program. Differently capitalized words are still the same word (e.g. 'DOG', 'dog', and 'dOg' are all the same word).
* Using languages like PHP or HTML that can just cat out their contents is considered a trivial loophole and is not allowed.
* The program must contain at least one word.

# Scoring

Your score is the number of "real words" in your program plus these penalties:

* +1 for every space that was replaced with another character
* nn for every n characters you added before the first word (yes, that's n to the power n)
* nn for every n characters you added after the last word

For example, the program

```
We all LIKE PROgraMmING

```

would score 4 because it contains 4 words; no characters were added or replaced any spaces. It's output would of course be `We all LIKE PROgraMmING`.

The program

```
!We@all LIKE#PROgraMmING- =

```

would score 4 + 2 + 1 + 27 = 34; 4 for the words, 2 for the replaced spaces, 1 for the `!` at the front, and 27 for the `- =` at the end. It's output would of course be `!We@all LIKE#PROgraMmING- =`.

**The lowest score wins.** Tiebreaker goes to the answer with the fewest penalty points. If there's still a tie the highest voted answer wins.

# Answer
# golfscript, 8 words + 8 symbols = ~~20~~ 16 (3?)

```
{four"words.written~twice"four}words.written~twice

```

The words are just a filler, the core is a tiny quine core:

```
{".~"}.~

```

Duplicates and evaluates a function that just appends the instructions to duplicate and evaluate itself. When a function is printed, it is stringified automatically. This is the smallest quine that does *something*.

Or we could just use a function literal that never gets evaluated. But it feels like cheating...

```
{whatever}

```
> 29 votes

# Answer
# \>\<\>, 25 words + (22 + 11 \+ 11) extra = ~~57~~ 49

Oh god, my brain.

```
'brr3deep*clap6beep+orb5flap*leap4deep+clap5beep5flap*leap9deep9clap*beep+flap0placed apple alp0leap=clip?lob8blip*flip0clip.

```

Since the rules state "There is no input.", for this program to work you'll need to pipe in an empty file.

Oh and yes, `brr` is a valid Scrabble word, as are `tsktsk` and `pfft`.

## Explanation

First of all, the following words are no-ops:

```
deep clap beep flap leap clip blip flip

```

This is because of two reasons:

* `abcdefl` push numbers (10, 11, 12, 13, 14, 15 and the length of the stack respectively). In addition, `i` pushes -1 if EOF is met, seeing as there is no input.
* The `p` command pops three chars `v,y,x` and places `v` at the position `x,y`.

Yes, \>\<\> lets you modify the source code on the fly! We don't really make use of that though, as we only need the `p` for popping.

If we get rid of these no-ops, we get:

```
'brr3*6+orb5*4+55*99*+0placed apple alp0=?lob8*0.

```

In a similar way, the `laced app` part of `placed apple` and the `e alp` part of `apple alp` are also no-ops, and the `rr` of `brr` just reverses the stack twice, which we can also remove:

```
'b3*6+orb5*4+55*99*+0pl0=?lob8*0.

```

Finally, something that looks like a regular \>\<\> program! The idea is to make use of the standard \>\<\> quine, which works like so:

* The initial `'` starts string parsing, pushing every char met until we hit another `'`
* We keep pushing chars until the end of the line, at which point we wrap the instruction pointer back to the start (since \>\<\> is toroidal)
* We land on the initial `'` again, and *stop* string parsing. The result is that we've pushed every single char in the program (except the initial `'`) onto the stack.

Then the following happens:

```
b3*6+o                Print the initial ' quote (ASCII 39)
r                     Reverse the stack
b5*4+                 Push a ';' (ASCII 59)
55*99*+0p             Replace the 'l' of 'lob' with ';'

(print loop)
l0=?;                 If the stack is empty, terminate. Otherwise...
o                     Print the top of the stack
b8*0.                 Jump back to the beginning of the loop

```
> 67 votes

# Answer
# Chicken, 1 word

I'm not normally into esolangs, but this one seemed perfect for this. I *think* this is a true quine:

```
chicken

```

Pushes 1 chicken to the stack. The stack is then displayed.
> 28 votes

# Answer
# Python 2, 58 = 37 words + 21 punctuation marks

```
programming=puzzle=hash and'fear=coerce and"programming=puzzle=hash and%rif reload else fire;exec prog"or English;ramming=None or"ramming"if license else pirate;print fear%puzzle+ramming'if reload else fire;exec programming

```

With some newlines added:

```
programming=puzzle=hash and'fear=coerce and"programming=puzzle=hash
and%rif reload else fire;exec prog"or English;ramming=None or
"ramming"if license else pirate;print fear%puzzle+ramming'
if reload else fire;exec programming

```

The three uses per word restriction was what made this one difficult to write. I wanted to use the string with all the code more than 3 times, and every string had to be insulated with `if else and or` operators which I only had a limited supply of.
> 16 votes

# Answer
# R, 2 words + 1 replacement + 1¹ trailing = 4

Objects which aren't assigned to anything are just printed to stdout. Since an expression is an object, the following code prints itself:

```
expression(puppy)

```

---

Previous submission, 5 points:

```
function(hello)hello

```
> 13 votes

# Answer
# Vyxal, 2 words + \\$1^1 +1 = 4\\$

```
`qUEued`qUEued

```

Try it Online!

Gosh this took ages to find.

Vyxal's a SBCS language, meaning most of its characters are unicode ones that we cannot use here. But it's still fairly usable without those.

The easiest way to make Vyxal quines is using the format ``code`code`, where the code prepends a backtick and doubles the result, or similar - this is pretty much exactly what the above program does.

```
`qUEued`       # Data string
        q      # Unevaluate; enclose in backticks
         U     # Uniquify, removing the trailing backtick
          E    # Evaluate as Python; NOP
           ue  # Extend to length -1; NOP
             d # Double, creating the quine!

```
> 10 votes

# Answer
# Julia, 1 word + 1¹ preceding = 2

Julia has objects called symbols which are defined using a preceding `:`. Much like my R solution, this just prints when submitted.

```
:puppy

```
> 8 votes

# Answer
# DOS command line, 10

```
& was unexpected at this time.

```

Error quine, not banned it seems
> 7 votes

# Answer
# Runic Enchantments, Score 4+3+11+11 = 9

```
"hOt3OX4NOt+kNOt@

```

Try it online!

Words: `hot ox not knot` (4)
Replacements: `3 4 +` (3)
Before: `"` (1)
After: `@` (1)

All of the characters `GNOQWghtxz` are no-op in Runic (as well as space and period, but more spaces doesn't help scoring). Including the `X` and `k` required for functionality, this gives the following available word list:

```
5 Letter Word(s)
  thong
4 Letter Word(s)
  gong goth gowk gown hogg hong honk howk knot know nogg nowt tong town wonk wont zonk
3 Letter Word(s)
  got gox hog hon hot how nog noh not now nth own tho tog ton tow two who wok won wot
2 Letter Word(s)
  go ho no oh on ow ox to wo

```

I cherry picked based on the needs of the space it was going into and making it sound funny.

Removing all NOP characters gives the following quine:

```
"3X4+k@

```

Try it online!
> 6 votes

# Answer
# huh? \- 1 word + 1\**1/1^1=1 char after the word = 2 total score.

```
Ouch!

```

`Ouch!` is a valid quine in huh?

Run it like `pythuhn.py Ouch!`, and there cannot be a file named `Ouch!` in the current directory.
> 3 votes

# Answer
# Pip, 8 words + (6 + 11) = 15

```
HA:saY"HA:saY eyRIE:HARPy"eyRIE:HARPy

```

Includes a trailing newline. Try it online!

### Explanation

This is an expansion of the repr-based quine `Y"Y yRsRPy"yRsRPy`.

```
HA:saY"HA:saY eyRIE:HARPy"eyRIE:HARPy
HA:s                                   Assign space character to the variable HA
    a                                  No-op
     Y"HA:saY eyRIE:HARPy"             Yank that string into the y variable
                          e            No-op
                           yR          In y, replace
                                HA     HA (space)
                             IE:       (and also assign space character to IE)
                                  RPy  with the repr of y (in this case, y wrapped in quotes)
                                       Autoprint (implicit)

```

The trailing newline is necessary because autoprint outputs a trailing newline.
> 3 votes

# Answer
# Actually, 10 + 9 + 1 = 20

```
"AB9FAce+AE;Ah+AL"AB9FAce+AE;Ah+AL

```

Try it online!

Invalid instructions do nothing in Actually, and removing them gives this:

```
"9FAc+;+"9FAc+;+
"9FAc+;+"        # String literal
         9FA     # Push abs(9th fibonacci number) = 34
            c    # 34th ascii character is "
             +   # Append the " to the start of the string
              ;+ # Append the string to itself

```
> 2 votes

---
Tags: code-challenge, restricted-source, quine
---


title: Building spikes

text:
# Question
Title: Building spikes
Inspired by this building (United States Air Force Academy Cadet Chapel, Colorado)

Your task is simple, given a positive integer `n`, output the spiked building to size `n`

# Testcases

```
1
->
   ^
  /|\
 /.|.\
/..|..\
_______

2
->
   ^  ^
  /|\/|\
 /.|..|.\
/..|..|..\
__________

7
->
   ^  ^  ^  ^  ^  ^  ^
  /|\/|\/|\/|\/|\/|\/|\
 /.|..|..|..|..|..|..|.\
/..|..|..|..|..|..|..|..\
_________________________

```

Trailing spaces are allowed

You are to output the string with newlines

This is , so shortest code wins!

# Answer
> 3 votes
# Charcoal, 30 bytes

```
_/¶_./¶×“ ∧σ¿⊘=8G℅H«⊙”Ｎ_.\¶_\⟲

```

Try it online! Link is to verbose version of code. Explanation:

```
_/¶_./¶

```

Print the first two columns.

```
×“ ∧σ¿⊘=8G℅H«⊙”Ｎ

```

Print the middle columns repeated the appropriate number of times.

```
_.\¶_\

```

Print the last two columns.

Rotate to orient the output correctly.

# Answer
> 10 votes
# JavaScript (Node.js), 80 bytes

```
n=>`   ^
  /|\\
 /.|.\\
/..|..\\
___`.replace(/.[_|^]./g,'$&'.repeat(n))+'____'

```

Try it online!

# Answer
> 7 votes
# Python 3.8 (pre-release), 81 bytes

```
lambda n:f" {'  ^'*n}\n  "+'/|\\'*n+'\n /'+(d:='.|.'*n)+rf'\
/.{d}.\
_'+'_'*3*-~n

```

Try it online!

Thanks @UnrelatedString for -3 bytes, by teaching me about the `rf` string literal. Thanks @AidenChow for -1 byte, by adding another f-string. Thanks @tsh for -1 byte.

Wow, looks like this has become a bit of a community effort.

# Answer
> 5 votes
# Vyxal, 30 bytes

```
»ε¥»₄τ2?»øƒ≈»₇τẋṀf`|^/\.`τ\_+§

```

Try it Online!

Modified port of the Jelly answer.

```
»ε¥»₄τ                         # [2, 14, 19, 3]
      2         Ṁ              # Insert at position 2...
        »øƒ≈»₇τ                # [74, 125, 99]
       ?       ẋ               # Repeated <input> times
                 f             # Flatten the whole thing
                  `|^/\.`τ     # Decompress each from base with the key "|^/\."
                          \_+  # Append an underscore to each
                             § # Transpose, fill and join by newlines.

```

Old version below because I thought it was quite elegant.

# Vyxal `C`, 42 bytes

```
` ^
/|
.|
.|
__`øM↵*`

/
/.
__`øṀ↵½Zƛ÷$j

```

Try it Online!

This is quite elegant but somewhat messy approach. I'm unsatisfied with the last bit, `vj` should work but it doesn't.

The first bit produces the string

```
 ^
/|\
.|.
.|.
___

```

Then repeats each row of that by the input.

Then, it creates

```

/\
/..\
____

```

by mirroring half of each line, and inserts the previous into that. Finally, the whole thing is centered.

# Answer
> 4 votes
# Jelly, 30 bytes

```
“\ɓ^‘ẋ“£×“Œ¥‘jṃ“|/.\^””_;Ɱz⁶ṚY

```

**Try it online!**

### How?

```
“\ɓ^‘ẋ“£×“Œ¥‘jṃ“|/.\^””_;Ɱz⁶ṚY - Main Link: integer, N
“\ɓ^‘                          - Code-page indices = [92, 155, 94]
     ẋ                         - repeat N times
      “£×“Œ¥‘                  - Code-page indices = [[2, 17], [19, 4]]
             j                 - join -> [2, 17, 92, 155, 94, ..., 92, 155, 94, 19, 4]
               “|/.\^”         - list of characters = "|/.\^"
              ṃ                - convert to base 5 using "|/.\^" in place of the digits 12340
                         Ɱ     - map across these lists of characters with:
                      ”_;      -   concatenate to an '_' character
                          z⁶   - transpose with space characters as filler
                            Ṛ  - reverse
                             Y - join with newlines
                               - implicit print

```

# Answer
> 3 votes
# Python 3, <sup>~~124~~ ~~91~~ ~~90~~</sup> 88 bytes

```
lambda n:[print(('   /_  /._'+' /.._^|||_ \.._'*n+'  \._   \_')[i::5])for i in range(5)]

```

Try it online!

# Answer
> 3 votes
# 05AB1E, ~~42~~ ~~41~~ 35 bytes

```
Y17•₅œ •₅вIи19Y·)˜"^|/.\"Åв'_δšζRJ»

```

-6 bytes porting *@JonathanAllan*'s Jelly answer

Try it online or verify the first 10 test cases.

See the previous revision for the original 42 and 41 bytes approaches.

**Explanation:**

```
Y              # Push 2
17             # Push 17
•₅œ •          # Push compressed 6021919
     ₅в        # Convert it to base-255 as list: [92,155,94]
       Iи      # Repeat this list the input amount of times
19             # Push 19
Y·             # Push 4 (2 doubled)
 )             # Wrap the stack into a list
  ˜            # Flatten
   "^|/.\"Åв  "# Convert it to custom base-"^|/.\"
               # (basically base-length, and then index into the string)
  δ            # Map over each inner list:
'_ š          '#  Prepend a "_" to each
    ζ          # Zip/transpose; swapping rows/columns, with a space " " as
               # default filler
     R         # Reverse the list of lists
      J        # Join each inner list together to a string
       »       # Join by newlines
               # (after which the result is output implicitly)

```

See this 05AB1E tip of mine (section *How to compress large integers?* and *How to compress integer lists?*) to understand why `•₅œ •` is `6021919` and `•₅œ •₅в` is `[92,155,94]`.

# Answer
> 3 votes
# APL+WIN, ~~88~~ 73 bytes

Prompts for spikes.

Original

```
l←5 2⍴¯10↑'//.__'⋄c←5 3⍴' ^ /|\.|..|.___'⋄r←5 2⍴¯10↑'\ .\__'⋄⊃⊂[2]⍎'l,',((2×⎕)⍴'c,'),'r'

```

A simpler iindexing solution

```
m←5 7⍴'   ^     /|\   /.|.\ /..|..\_______'⋄m[;⍳2],m[;(3×⎕)⍴2+⍳3],m[;6 7]

```

Try it online! Thanks to Dyalog APL Classic

# Answer
> 3 votes
# Ruby, 69 bytes

```
->n{'   ^
  /|\
 /.|.\
/..|..\
_______'.lines.each{|l|l[2,3]*=n}*''}

```

Try it online!

Lambda tacking *n* that multiplies inner substring *n* times for each line of the spike.

# Answer
> 2 votes
# Retina, ~~64~~ 63 bytes

```
.+
 $&*$(  ^)¶  $&*$(/|\)¶ /$&*$(.|.)\¶/.$&*$(.|.).\¶__$&*3*___

```

Try it online! Link includes test cases. Explanation: Just an application of Retina 1's string repetition operator. Note that repetition has higher precedence than concatenation so the string to be repeated has to be grouped (except in the case of repeating three `_`s which is achieved via a second repetition).

# Answer
> 2 votes
# Regenerate, 61 bytes

```
  ( ^ ){$~1}
  (/\|\\){$~1}
 /((.\|.){$~1})\\
/.$3.\\
_{#3+4}

```

Attempt This Online!

### Explanation

`$~1` is the input number, and `{$~1}` repeats something that many times. So:

```
  ( ^ ){$~1}

```

Two spaces, followed by  `^`  N times.

```
  (/\|\\){$~1}

```

Two spaces, followed by `/|\` N times.

```
 /((.\|.){$~1})\\

```

`/`, followed by `.|.` N times (and capture that result as group 3), followed by `\`.

```
/.$3.\\

```

`/.`, followed by the contents of group 3 again, followed by `.\`.

```
_{#3+4}

```

`_` repeated len(group 3) + 4 times.

# Answer
> 1 votes
# K (ngn/k), ~~76~~ 66 bytes

```
{`0:+?[4 4#"   /  /.  \\.   \\";2;,/(x,3 4)#" /..^||| \\.."],'"_"}

```

Try it online!

* `?[a;2;b]` use `splice` to insert `b` into `a` at position `2`
    + `4 4#" / /. \\. \\"` the initial array, representing the "sides" of the spiked building
    + `,/(x,3 4)#" /..^||| \\.."` `x` copies of the spikes
* `?[;;],"_"` append a `"_"` to each slice
* ``0:+` transpose the above, and print to stdout

# Answer
> 1 votes
# Pip, 46 bytes

```
FlRsX,4.:"/\"J'|WR'.X,3PE'^AE'_X7{(l2,5)X:aPl}

```

Attempt This Online!

### Explanation

First, we generate this list

```
["   ^"
 "  /|\"
 " /.|.\"
 "/..|..\"
 "_______"]

```

as follows:

```
RsX,4.:"/\"J'|WR'.X,3PE'^AE'_X7
                   ,3            ; Range(3): [0;1;2]
                '.X              ; Repeat . that many times: ["";".";".."]
            '|WR                 ; Wrap | in each of those strings: ["|";".|.";"..|.."]
       "/\"J                     ; Insert each of those strings between / and \:
                                 ; ["/|\";"/.|.\";"/..|..\"]
                     PE'^        ; Prepend "^" to the front of that list
                         AE'_X7  ; and append "_______" to the end:
                                 ; ["^";"/|\";"/.|.\";"/..|..\";"_______"]
   ,4                            ; Range(4): [0;1;2;3]
 sX                              ; Repeat space that many times: ["";" ";"  ";"   "]
R                                ; Reverse: ["   ";"  ";" ";""]
     .:                          ; Concatenate those two lists itemwise:
                                 ; ["   ^";"  /|\";" /.|.\";"/..|..\";"_______"]

```

Then we loop over each line, repeat the center section, and print the result:

```
Fl...{(l2,5)X:aPl}
Fl   {           }  ; For each line l
  ...               ; in the above list:
      (l   )        ;   The section of l
        2,5         ;   at indices range(2,5) i.e. [2;3;4] (modular 0-based indexing)
            X:      ;   string-repeat in place
              a     ;   (program argument) times
               Pl   ;   Print (the modified version of) l with a trailing newline

```

# Answer
> 1 votes
# Lua, 92 bytes

```
print(([[   ^
  /|\
 /.|.\
/..|..\
]]):gsub(".[_|^].",("%1"):rep(...))..('_'):rep(4+3*...))

```

Attempt This Online! I feel like it can go a bit lower but don't want to play with it right now. Basically? a port of tsh's answer but with the underscores outside the initial string.

# Answer
> 0 votes
# Retina 0.8.2, 70 bytes

```
.+
 $&$*1¶  $&$*2¶ /$&$*3\¶/.$&$*3.\¶__$&$*4__
1
  ^
2
/|\
3
.|.
4
___

```

Try it online! Link includes test cases. Explanation: Since Retina 0.8.2 can only repeat characters, placeholder digits are used for the four different building parts which are then substituted in afterwards.

# Answer
> 0 votes
# CJam, 66 bytes

```
ri:R;SSSa"^  "R*NSS"/|\\"R*NS'/".|.":QR*'\N"/."QR*".\\"N'_"___"R)*

```

Try it online! I haven't golfed for a while, and longer since CJam, so this probably has significant optimizations available, but I was in the mood to try something. It basically just constructs the result line by line, with a couple minor optimizations by saving the size as a variable, saving the `".|."` construction as a variable since we re-use it, and using 3(n+1)+1 instead of 3n+4 to construct the bottom row.

---
Tags: code-golf, string, ascii-art
---


# Question
Title: Distinguish between Masculine and Feminine Nouns in French within 100 characters
You are to write a very small program within 100 characters. Your program must distinguish between masculine and feminine french nouns. The output should be `un` if it is masculine and `une` if it is feminine. Often, there are certain statistical rules you can follow (e.g. if it ends in an "e" it is more likely feminine than masculine).

**Input**:

A french word; it may consist of any lowercase letters and dashes, including lowercase letters with accents.

Example input: `ami`

**Output**:

`un` if the word is masculine and `une` if the word is feminine.

Example output: `un`

You do not have to get every word right; your goal is to be as accurate as possible.

**Scoring**: Your answer **must** be within 100 characters. Statements such as `print` or `console.log` or `alert` do *not* count as part of your total bytes. You may also write a function or method that performs this task, in which case the first few bytes (e.g. `f=x=>`) which are part of the function declaration do not count to your total. Your total score is the number of incorrect answers. Ties are broken by code size.

Nouns to test with:

```
un ami
un café
un chapeau
un concert
un crayon
un garage
un garçon
un lit
un livre
un mari
un musée
un oncle
un ordinateur
un pantalon
un piano
un pique-nique
un portable
un père
un sandwich
un saxophone
un stade
un stylo
un théâtre
un téléphone
un voisin
une botte
une boum
une chaise
une chaussette
une chemise
une clarinette
une copine
une femme
une fille
une glace
une heure
une lampe
une maison
une montagne
une personne
une piscine
une pizza
une radio
une raquette
une salade
une souris
une sœur
une table
une télé
une voiture

```

# Answer
# CJam, 0 incorrect, ~~32~~ 29 bytes

This code uses a few odd characters (some of them unprintable), but they are all well within extended ASCII range. So again, I'm counting each character as a single byte.

```
"un"'el2b"zPB:  ":i+:%2/*

```

Due to the unprintable characters, I'm sure Stack Exchange swallows some, so you might want to copy the code from the character counter (it shows bytes with UTF-8 encoding, which is suboptimal for this challenge; also, the link doesn't seem to work in Firefox, but does in Chrome).

*A hexdump is provided for reference:*

```
00000000: 2275 6e22 2765 6c32 6222 7a50 423a 1a14  "un"'el2b"zPB:
00000010: 0e09 0422 3a69 2b3a 2532 2f2a 0a            ":i+:%2/*.

```

Test it here.

After some more discussion in chat, we figured that the regex golfing wouldn't bring us much further. So following an earlier (joking) suggestion of mine we started looking into manipulating the character codes of the words with certain functions, such that all words from one group would yield a number with some property that is easy to check. And we got luckier than we expected! Here is what the code does to the words:

* Implicitly convert the characters in the word to their code points.
* Interpret those as digits in base 2 (yes, the digits will be much larger than 0 or 1, but CJam can handle that).
* Repeatedly take the result modulo... the following numbers: `[133, 122, 80, 66, 58, 26, 20, 14, 9, 4]`. This sequence of numbers is itself encoded as the code points of a string (this is where the weird and unprintable characters come in).
* As if by magic, all 25 masculine nouns yield `0` or `1`, and all 25 feminine nouns yield `2` or `3` with this procedure. So if we divide this by `2` (integer division) we get zeroes for masculine nouns and ones for feminine nouns.

To round it off, we push `"un"` on the stack, the we push a single `e`. Then we read the input word from STDIN and perform the above computation, and finally multiply the `e` by the result.

I have never folded modulo onto any list before, and I feel like I never will again...

Many thanks for xnor and Sp3000 for throwing ideas around and helping with the search for divisor chain.
> 26 votes

# Answer
# Ruby, 0 incorrect, ~~63~~ ~~56~~ ~~53~~ ~~52~~ ~~51~~ 50 bytes

All characters are in extended ASCII, specifically ISO 8859-1, so I'm counting each character as a single byte.

```
f=->s{s[/la|tt|i.e|[égdzœu]..$|^b|^f|so|^ta/]?'une':'un'}

```

It looks like your test set was a bit too short. I've generated the regex with Peter Norvig's meta regex golfer.

You can call the above function like `f["ami"]`. You can use this test harness to check all test cases:

```
puts "ami café chapeau concert crayon garage garçon lit livre mari musée
      oncle ordinateur pantalon piano pique-nique portable père sandwich
      saxophone stade stylo théâtre téléphone voisin botte boum chaise
      chaussette chemise clarinette copine femme fille glace heure lampe
      maison montagne personne piscine pizza radio raquette salade souris
      sœur table télé voiture".split.map{|s|f[s]+" "+s}

```

Test it on Coding Ground.

**Edit:** Using Peter Norvig's second script I found a different regex, that was actually *one* byte longer, but which I could shorten by *two* bytes by hand.

**Edit:** Sp3000 set the regex golfer he wrote for my recent regex challenge on it, and found a ~~36~~ ~~35~~ 34 byte regex for me to use. Thanks for that!
> 23 votes

# Answer
# CJam, 0 errors (~~36~~ ~~32~~ ~~29~~ 28 bytes)

```
{"un"oEb72^"+ÕåWïº"583b2b='e*o}:F;

```

This is a named function, so I'm only counting the inner code. Also, `o` is a print statement, so it doesn't contribute to the byte count.

Try the test cases in the CJam interpreter.

## How it works

```
"un"o       " Print 'un'.                                                  ";
Eb          " Consider the input a base 14 number.                        ";
72^         " XOR the result with 72.                                     ";
"+ÕåWïº"    " Push that string.                                           ";
583b2b      " Convert from base 583 to base 2.                            ";
=           " Retrieve the corresponding element (0 or 1) from the array. ";
'e*o        " Print 'e' that many times.                                  ";

```

Just a hash function and a table lookup.
> 13 votes

# Answer
# Lexurgy, 18 incorrect, 65 bytes

A quick check for whether the word ends with `e`.

```
a:
*=>|une/e _ $
else:
*=>|un/ _ $
b propagate:
[]=>*/_ |
c:
|=>*

```
> 0 votes

---
Tags: string, code-challenge, restricted-source, natural-language, classification
---


title: Tips for golfing in Lexurgy

text:
# Question
Title: Tips for golfing in Lexurgy
What general tips do you have for golfing in Lexurgy? I'm looking for ideas which can be applied to code-golf problems and which are also at least somewhat specific to Lexurgy (e.g. "remove comments" is not an answer).

Please post one tip per answer.

Lexurgy is a tool created by Graham Hill/`def-gthill` meant for conlangers (people who create constructed languages) to apply sound changes to their lexicon. As a result, Lexurgy is highly geared towards rule-based string operations. Its feature set includes capturing, character classes, and much more as detailed in the documentation below.

The documentation for Lexurgy is here, and a cheatsheet is here.

You can access Lexurgy here.

# Answer
### Reducing Whitespace

Lexurgy has specific rules about where whitespace can be removed. Consider the following rule (taken from my submission to Covfefify a string):

```
part-1:
 @consonant * => @consonant ; / $ @consonant* @vowel* _ // {$ _, $ @consonant _}

```

Lexurgy parses the rules as such, with `<>` separating individual elements:

```
<part-1>:
 <@consonant *> => <@consonant ;> / <$ @consonant* @vowel* _> // <{<$ _>, <$ @consonant _>}>

```

You cannot remove any whitespace within the `<>` or else it will yield a parsing error. As a result, with all extraneous whitespace removed, the rule turns into:

```
part-1:
@consonant *=>@consonant ;/$ @consonant* @vowel* _//{$ _,$ @consonant _}

```

If both sides have only 1 possible string on each side, then you can combine them:

```
# single string
a:
s t r=>o t h

b: # -1 byte per space
str=>oth

# combinable strings
c:
s t r *=>* o t h

d: # -1 byte per space
str *=>* oth

# two or more strings
e:
str ing=>oth er

f: # -1 byte per string
string=>other

```
> 3 votes

# Answer
### Caveats about Lexurgy

* Lexurgy treats whitespace in the input as word separators, so whitespace must be replaced by some other character. Individual inputs are separated by newlines, and those cannot be escaped in the input box.
* Escaping certain characters is done with `\`, i.e. `\! => !`.
* Lexurgy is designed for working on characters from a set of characters; use `[]` for matching any single character.
> 2 votes

# Answer
### Use class variables within class declarations

Lexurgy allows you to define arbitrary "classes" of characters which can be accessed by `@classname`. Classes must have at least 1 character within them. Consider the following classes:

```
# 75 bytes
Class v {a,e,i,o,u}
Class c {p,t,k,b,d,g}
Class l {a,e,i,o,u,p,t,k,b,d,g}

# 59 bytes (-16 bytes)
Class v {a,e,i,o,u}
Class c {p,t,k,b,d,g}
Class l {@v,@c}

```

A class is minimum 11 bytes long (`Class n {c}` to account for the single character needed for a class), and each additional character is +2 bytes. Consider these two minimum classes, and wanting to make a class `c` that is the union of `a` and `b`:

```
Class a {a}
Class b {b}

Class c {a,b}   # +13 bytes
Class c {@a,@b} # +15 bytes

```

For minimal classes it's better to use the explicit declaration instead of using class variables.

The break-even point is at three characters for 2 classes:

```
Class a {a,e}
Class b {b}

Class c {a,b,e} # +15 bytes
Class c {@a,@b} # +15 bytes

```

Let there be \\$c \ge 2\\$ classes. The total number of characters \\$n\\$ in classes will cause the byte count to break even (i.e. using class variables is just as good as explicitly declaring the union) at \\$2n=3c \Rightarrow n=\frac{3}{2}c\\$.

**Therefore, it is better to use variables when \\$n \ge \frac{3}{2}c\\$, and explicit declarations when \\$n \le \frac{3}{2}c\\$**.

(Desmos link to my calculations)
> 1 votes

# Answer
### Programs with no input

Programs with no input are possible in Lexurgy, with a rule like:

```
# +7 bytes
a:
*=>c

```

It takes an empty string and outputs a character for you to further mutate as needed. You can put an entire string on the right-hand side as well.

This must be the first rule for anything useful to happen.

However, if the program is given input, it will apply the rule to each input and every possible match in the input strings.
> 1 votes

# Answer
### Use classes as variables holding strings

You can place entire, arbitrary strings into class definitions, provided they are properly escaped:

```
Class s {Hello\,\ world\!}

```

Then, use it like any other class:

```
# 38 bytes
a:
[]=>Hello\,\world\!Hello\,\world\!

# 41 bytes
Class s {Hello\,\ world\!}
a:
[]=>@s @s

```

The above example gains a 3 bytes, but if you use the string multiple times you get even more savings:

```
# 53 bytes
a:
[]=>Hello\,\world\!Hello\,\world\!Hello\,\world\!

# 44 bytes
Class s {Hello\,\ world\!}
a:
[]=>@s @s @s

```
> 1 votes

# Answer
### The "Find/Marker/Delete" Pattern

A common pattern that I've found, which I've named the "Find/Marker/Delete" pattern, shows up often whenever the output is unrelated to the input except for some value that cannot be done using a simple replacement.

For example, consider this code that will output `true` or `false` if the word ends with `e`:

```
a:
*=>|true/e _ $
else:
*=>|false/_ $
b propagate:
[]=>*/_ |
c:
|=>*

```

This code has three parts:

```
# part a: find and place the marker. (here it's a |)
a:
*=>|true/e _ $
else:
*=>|false/e _ $
# part b: delete everything before/after the marker. (here it's everything before)
b propagate:
[]=>*/_ |
# part c: delete the marker
c:
|=>*

```

This pattern is the only real way you can have an output that is not some simple replacement of the input.

The minimal version for 2 outputs is as such (68 bytes):

```
a:
*=>|a/e _ $
else:
*=>|b/_ $
b propagate:
[]=>*/_ |
c:
|=>*

```
> 0 votes

---
Tags: tips
---


title: Draw a graph of \$y=(-n)^x\$

text:
# Question
Title: Draw a graph of \$y=(-n)^x\$
## Challenge

Given an input of an integer, \\$n\\$ (where \\$0\<n\<50\\$), output the graph of \\$y=\mathrm{Re}((-n)^x)\\$ from \\$x = -3\\$ to \\$x = 3\\$ inclusive.

Where \\$\mathrm{Re}(p)\\$ is the real part of the complex number \\$p\\$.

Note that \\$\mathrm{Re}((-n)^x) = n^x \cos{(\pi x)}\\$

## Output

The output may be in any form you wish (e.g. an image or a window etc.). ASCII art is disallowed.

The graph does not need to have axes (to allow languages without built-in graphing functions to compete).

If an image is output, it each side must be longer than 500 pixels. Similarly, the plot must fill the image as best it can.

The minimum interval between plots is 0.05.

Vector graphics are allowed.

## Examples

For an input of `2`:

For an input of `1`:

---

***You must put your corresponding outputs in your answer (n = 1 and n = 2).***

## Winning

The shortest code in bytes wins.

# Answer
# MATL, ~~22 18~~ 16 bytes

Thanks @LuisMendo for additional -2 bytes!

```
I_.01I3$:i_y^&XG

I_                       push 3 and negate
  .01                    push 0.01
     I                   push 3
      3$:                generate the list [-3,-2.99,-2.98,...,3]
         i_y^            calculate (-input)^(list)
             $XG         plot the first list against the real part of the second list

```

Try it on matl.io
> 12 votes

# Answer
# TI-Basic, ~~26~~ 21 bytes

```
~3→Xmin
3→Xmax
Prompt N
DrawF N^Xcos(πX

```

Output for N=2:
> 24 votes

# Answer
# Bash + Gnuplot, ~~56~~ 45 bytes

*(-11 bytes thanks to Noiralef!)*

```
gnuplot -e "se t png;p[-3:3]real((-$1)**x)">A

```

Saves the resulting graph as a `png` image named `A` in the current working directory.

### Example Outputs

For **n = 1**:

For **n = 2**:
> 15 votes

# Answer
# Python 3 with matplotlib, ~~103~~ 72 bytes

-12 bytes thanks to DSM (a module is installed alongside `matplotlib` called `pylab` with the necessary functionality "making Python in a repl more like Matlab" - odd, but true!)
-18 more as a result (pylab has many numpy functions too!)
-1 byte thanks to Ajasja (replacing `arange(-60,61)/20+0j` with `arange(121)/20-3+0j`)

```
from pylab import*
def f(n):x=arange(121)/20-3+0j;plot(x,(-n)**x);show()

```

**n=2,1**
> 14 votes

# Answer
## Mathematica, 41 bytes

```
Plot[Re[(-#)^x],{x,-3,3},PlotRange->All]&

```

Output looks exactly as shown in the challenge except for the font of the numbers (which I suspect was created with Wolfram Alpha).
> 12 votes

# Answer
## R, 29 bytes

```
curve(Re((0i-scan())^x),-3,3)

```

`n` is provided through stdin. Result for n=1:

And for n=2:
> 12 votes

# Answer
# MATLAB, ~~35~~ 30 bytes

```
x=-3:.01:3;@(n)plot(x,(-n).^x)

```

This defines an anyonmous function. The output is via a new window with a resizable vector graphic output. MATLAB's `plot` automatically ignores the imaginary part of the y-coordinates as long as your provide corresponding x-coordinates.The following output is for `n=3`.
> 11 votes

# Answer
# R, 30 bytes

```
plot(Re((0i-n)^seq(-3,3,.05)))

```

### `n` = 1

### `n` = 2
> 10 votes

# Answer
# Excel VBA, ~~168~~ ~~160~~ ~~147~~ 138 Bytes (cells as pixels at 100x scale)

Saved 8 bytes thanks to KyleKanos
Saved 22 bytes thanks to Taylor Scott

```
Sub g(n)
For i=0To 1
For x=-3To 3Step.01
y=n^x*Cos([Pi()]*x)
m=IIf(y<m,y,m)
If i Then Cells(500*(1-y/m)+1,(x+3)*100+1)="#
Next x,i
End Sub

```

Formatted, it looks like this:

```
Sub g(n)
    For i = 0 To 1
    For x = -3 To 3 Step 0.01
        y = n ^ x * Cos([Pi()] * x)
        m = IIf(y < m, y, m)
        If i Then Cells(500 * (1 - y / m) + 1, (x + 3) * 100 + 1) = "#"
    Next x, i
End Sub

```

Fun Fact: VBA does not have a built-in `pi` variable so we have to evaluate it as a worksheet function where it *does* exist.

**n=1** **n=2**

---

I started with a chart version at 193 bytes but it *did* get prettier results.

```
Sub c(n)
For x=-3To 3Step 0.05
r=r+1
Cells(r,1)=n^x*Cos(Atn(1)*4*x)
Next
With ActiveSheet.Shapes.AddChart(xlLine).Chart
.SetSourceData Range("A1:A121")
.Axes(xlCategory).Delete
End With
End Sub

```

**n=1**
**n=2**
> 10 votes

# Answer
# MATLAB, ~~35~~ 33 bytes

*Thanks fo @flawr for removing 2 bytes!*

```
@(n)ezplot(@(x)real((-n)^x),-3:3)

```

This defines an anonymous function. To call it with input `2`, use `ans(2)` (or assign the function to a variable such as `f` and then use `f(2)`).

Output is vector graphics (resizable window). The sampling interval on the *x* axis is determined automatically by the `ezplot` function, but it seems to be more than enough.

A warning is produced in STDERR because the function passed to `ezplot` (`@(x)real((-n)^x)`) is not vectorized, but the graph is generated.

Example for `n = 2`:
> 6 votes

# Answer
# Jupyter notebook and Python 3; 53 bytes

```
%pylab
def f(n):x=arange(121)/20-3+0j;plot(x,(-n)**x)

```

Three bytes saved thanks to @Jonathan Allan.
> 5 votes

# Answer
# , ~~37~~ 36 bytes

Thanks to my colleague Marshall for guidance. -2 thanks to FrownyFrog.

Anonymous tacit prefix function.

```
-(]plot@;9 o.^)i:@3j120[load@'plot'

```

```
-(]plot@;9 o.^)i:@3j120[load@'plot'
                        load@'plot'       NB. load plotting library
               i:@3j120                   NB. -3...3 in 120 steps
-                                         NB. negate argument
 (           ^)                           NB. raise the negated value to those exponents
 (       9 o. )                           NB. real part
 (]     ;     )                           NB. pair with the exponents
 ( plot@      )                           NB. plot it

```
> 4 votes

# Answer
# Julia 0.6 with Plots.jl, 46 bytes

```
using Plots
~n=plot(real((0im-n).^(-3:.05:3)))

```

This needed a Julia representation!

Not much to golf here though, except (ab)using operator overloading to save bytes on function defintion, and using `0im-n` to make the input number complex where I might usually have used `Complex(n)`. That's necessary because in Julia, for type stability reasons, the `^` operator returns Complex results only when the input is Complex itself. So here we make it a complex number by adding `0im` ie. 0i.

One cool thing about the Plots.jl package is that it automatically chooses the backend to use based on what plotting packages you have installed and where you're running the `plot` command from. The above plot was created with the GR backend, but if I didn't have that installed (or if I explicitly ran a `plotly()` command like I did for this), it would have used the more interactive Plotly backend and output this (which looks a tiny bit nicer IMO):

There's even a UnicodePlots backend, to print a plot in the terminal (or save to a text file) using Unicode characters and color codes. SE keeps messing up the plot alignment if I try to directly paste it though, so here's a terminal screenshot:

PS: The alternate formula, \\$ Re((−n)^x)=n^xcos(πx) \\$, comes out to the same length:

```
using Plots
~n=plot(n.^(x=-3:.05:3).*cospi(x))

```
> 4 votes

# Answer
# Desmos, ~~12~~ ~~10~~ 9 bytes

-2 thanks to @Steffan
-1 thanks to @LeoDog896

```
n^xcosxπ

```

How has nobody used Desmos yet?
> 4 votes

# Answer
# Encapsulated PostScript; 232 bytes

```
%!PS-Adobe-3.0 EPSF-3.0
%%BoundingBox: 0 0 500 500
%%EndComments
/n 1 def .02 setlinewidth /f{dup dup n exch exp exch 180 mul cos mul 3 div}def
250 250 translate 80 80 scale newpath -3 f moveto -3 .05 3{f lineto}for stroke
%%EOF

```

Now since this is a vector image itself...
> 3 votes

# Answer
# TikZ \+ PGFPlots, 175 bytes

```
\documentclass{standalone}\usepackage{tikz,pgfplots}\begin{document}\typein[\n]{}\tikz{\begin{axis}\addplot[domain=-3:3,samples=120]{\n^x*cos(180*x)};\end{axis}}\end{document}

```

Compile with, *e.g.*, `latexmk -cd -f -pdf in.tex` for a pdf output. During compilation, the user is prompted for `n`.

Sample outputs (converted to png) for n = 1 and n = 2:
> 3 votes

# Answer
# Math.JS Grapher, 20 Bytes

```
r(n)=f(x)=re((-n)^x)

```

By sheer fluke, this graphing utility is TC (For the most part, Infinite loops just crash it.), and by nature, it's primary output is graphs.

## How it works

`r(n)=` assigns a function `r` which takes the argument `n` to the expression `f(x)=re((-n)^x)`. `re((-n)^x)` is pretty much letter for letter the challenge description. But this assigns the function `f(x)` to this, which the grapher implicitly outputs as a line graph.

## How to test it

You can use this site, punch that function in there, then call it with `r(input)`.

## Output
> 2 votes

# Answer
# Excel VBA, 133 bytes

Immediate window script that takes input from `[A1]` and outputs a `Chart` object to the `Sheet1` object.

```
[B:B]="=ROW()/20-3.05":[C:C]="=A$1^B1*Cos(Pi()*B1)":Set c=Sheet1.Shapes.AddChart(4).Chart:c.SetSourceData[C1:C121]:c.Axes(1).Delete

```

## Ungolfed

Full `Sub`routine version. I/O is unchanged.

```
Sub b()
    [B:B] = "=ROW()/20-3.05"                ''  Define `x`-axis
    [C:C] = "=A$1^B1*Cos(Pi()*B1)"          ''  Define `y`-axis in terms of input from A1
    Set c = Sheet1.Shapes.AddChart(4).Chart ''  Add line plot to Sheet1 (xlLine)
    c.SetSourceData [C1:C121]               ''  Set `y` source to match `x` in [-3,3]
    c.Axes(1).Delete                        ''  Remove erroneous axes (xlCategory)
End Sub

```

## Output

Where input, \\$n=1\\$

Where input, \\$n=3\\$
> 2 votes

# Answer
# Dyalog APL, 41 bytes

```
⎕SE.UCMD∊'chart x(9○(-'⍞')*x←3-20÷⍨⍳121)'

```

### How it works:

```
⎕SE.UCMD∊'chart x(9○(-'⍞')*x←3-20÷⍨⍳121)' ⍝ Main function
⎕SE.UCMD∊                                 ⍝ User Command (called from the session object)
         'chart                           ⍝ Plot a chart with arguments:
                 (           3-20÷⍨⍳121)' ⍝ Yields the list [-3, -2.95, -2.9,..., 2.9, 2.95, 3]
                           x←             ⍝ Assign that list to x
                          *               ⍝ and use it as exponent
                    (-'⍞')                ⍝ with (-input) as base
                  9○                      ⍝ discard the complex part; this generates Re((-n)^x)
                x                         ⍝ And x.

```

The user command `]chart`, in this case, takes two vector arguments, `x` and `y` and plots the graphs:

For \\$n=1\\$:

For \\$n=2\\$:
> 2 votes

# Answer
# Google Sheets, 65

* Input N is in A1

Graphing:

* `=SPARKLINE(ArrayFormula(IMREAL(IMPOWER(-A1,.05*SEQUENCE(121,1,-60` or
* `=SPARKLINE(ArrayFormula(IMREAL(IMPOWER(-A1,SEQUENCE(121,1,-60)/20`

Resize row and column of graph to 500x500.

I tried to use the COS() formula, but the best I can do is 66 characters with a named range. Problems that I came across:

* X is generated by the SEQUENCE(), which is then used twice. You would naturally think to cache this, but every time you cache into a column, to use it again, you have to either name a range, or use a FILTER. Named Range is obviously better, but it does cost 1 character to make it fair.
* Attempting to scalar multiply a SEQUENCE() forces us into an ArrayFormula (or MMULT() at best), and we cannot use a non-integer step for SEQUENCE(). This means that the most optimal way to use it is to give it to the SPARKLINE formula.
* This also means that our scalar multiply/divide has to occur each time we use the range.
> 1 votes

# Answer
# SmileBASIC, 82 bytes

```
INPUT N
FOR I=0TO 399X=I/66.5-3GPSET I,120-POW(N,X-3*SGN(N-1))*COS(PI()*X)*120NEXT

```

Graph fills the entire screen, even when N is less than 1.

When N is greater than 1, you can scale Y to be between -1 and 1 by dividing it by `n^3`. I'm already doing `n^x`, and `n^x / n^3` can be simplified to `n^(x-3)`. However, when N is less than 1, I have to divide Y by `n^-3` instead. This is equivalent to `n^(x+3)`.

I can use `n^(x-3*sign(n-1))` to use `-3` if `n>1`, and `+3` if `n<1`

Images coming soon
> 0 votes

---
Tags: code-golf, math, graphical-output, complex-numbers, trigonometry
---


title: Recursively rotate a ragged list

text:
# Question
Title: Recursively rotate a ragged list
Given a ragged list of positive integers return a full cycle of recursive rotations starting with the unchanged input and ending with the state immediately before revisiting the initial state.

#### Examples:

```
[[2,3],4,5,5] -> [[2,3],4,5,5] , [4,5,5,[3,2]] , [5,5,[2,3],4] , [5,[3,2],4,5]

[1,10,[2,2,4],6,[[5,6],7],1] -> [1,10,[2,2,4],6,[[5,6],7],1] , [10,[2,4,2],6,[7,[6,5]],1,1] , [[4,2,2],6,[[5,6],7],1,1,10] , [6,[7,[6,5]],1,1,10,[2,2,4]] , [[[5,6],7],1,1,10,[2,4,2],6] , [1,1,10,[4,2,2],6,[7,[6,5]]]

[[5,6],[6,5]] -> [[5,6],[6,5]]

[1,[2,3,4,5,6],[7,8]] -> [1,[2,3,4,5,6],[7,8]] , [[3,4,5,6,2],[8,7],1] , [[7,8],1,[4,5,6,2,3]] , [1,[5,6,2,3,4],[8,7]] , [[6,2,3,4,5],[7,8],1] , [[8,7],1,[2,3,4,5,6]] , [1,[3,4,5,6,2],[7,8]] , [[4,5,6,2,3],[8,7],1] , [[7,8],1,[5,6,2,3,4]] , [1,[6,2,3,4,5],[8,7]] , [[2,3,4,5,6],[7,8],1] , [[8,7],1,[3,4,5,6,2]] , [1,[4,5,6,2,3],[7,8]] , [[5,6,2,3,4],[8,7],1] , [[7,8],1,[6,2,3,4,5]] , [1,[2,3,4,5,6],[8,7]] , [[3,4,5,6,2],[7,8],1] , [[8,7],1,[4,5,6,2,3]] , [1,[5,6,2,3,4],[7,8]] , [[6,2,3,4,5],[8,7],1] , [[7,8],1,[2,3,4,5,6]] , [1,[3,4,5,6,2],[8,7]] , [[4,5,6,2,3],[7,8],1] , [[8,7],1,[5,6,2,3,4]] , [1,[6,2,3,4,5],[7,8]] , [[2,3,4,5,6],[8,7],1] , [[7,8],1,[3,4,5,6,2]] , [1,[4,5,6,2,3],[8,7]] , [[5,6,2,3,4],[7,8],1] , [[8,7],1,[6,2,3,4,5]]

```

#### Rules:

Direction of rotation is your choice but must be consistent across layers.

You must start with the initial state and stop immediately before it reappears.

States are completely determined by their values, cf. example 3 to see what I mean by that.

Destroying the input is ok but different iterations cannot be the same object (if that makes any sense in your language - me only speak Python).

Other than the above standard code golf loopholes and I/O apply.

#### Promises:

Lists and sublists will be nonempty and finite as will be the nesting.

#### Scoring:

Code golf: shortest in bytes per language wins.

# Answer
# Wolfram Language (Mathematica), 52 bytes

```
If[#!=##2,#0[Map[RotateLeft,#,{0,-2}],##2,#],{##2}]&

```

Try it online!

Uses an approach from this answer to `RotateLeft` on every level.

---

If the initial state can be last instead, **48 bytes**:

```
If[#!=##2,Map[RotateLeft,#,{0,-2}]~#0~##,{##2}]&

```

Try it online!
> 6 votes

# Answer
# Vyxal, ~~16~~ ~~15~~ 10 bytes

```
≬Iȧ[vxǓ]İǔ

```

Try it Online!

~~All because there's a bug with `ǔ` and nested lists.~~ Gotta love bug fixes.

## Explained

```
≬Iȧ[vxǓ]İǔ
≬       İ    # Apply the following on the input while the result is unique, collecting iterations:
 Iȧ          #   Either push lambda arugment spaces or split a list into two halves. Then remove all whitespace.
   [   ]     #   If that's truthy (that is, the item is a list):
    vx       #    Apply this lambda to each item recursively
      Ǔ      #    And rotate the result of that left once
        ǔ    # Rotate the resulting list right

```
> 4 votes

# Answer
# K (ngn/k), 23 bytes

```
{(`i>@x)(o',/|0 1_)/x}\

```

Try it online!

```
{(`i>@x)(o',/|0 1_)/x}\    Iterate and collect until it returns to the input...
 (`i>@x)(         )/x        Apply once if x is not an integer atom...
         o',/|0 1_             Rotate once and apply recursively to each item

```

Not quite sure if I can circumvent the explicit type checking.
> 4 votes

# Answer
# Ruby, 69 bytes

```
r=->l{l*0==0?l:l.rotate.map(&r)}
f=->l,x=l{l!=r[x]?[x]+f[l,r[x]]:[x]}

```

Try it online!

*r* =\> rotate ragged list
*l\*0==0?l*
If input is a value return it.
Else is an array, so rotate and map by *r*.

*f* =\> recursively build an array of the steps.
> 4 votes

# Answer
# , ~~124~~ ~~115~~ ~~112~~ 101 bytes

```
r=\(l)"if"(is.list(l),Map(r,c(l[-1],l[1])),l)
`+`=list
f=\(l,a=+l,b=r(l))"if"(+b%in%a,a,f(b,c(a,+b)))
```

Attempt This Online!

-12 bytes thanks to Dominic van Essen. -11 bytes thanks to pajonk.
> 4 votes

# Answer
# 05AB1E, 25 bytes

```
[="Ð˜Êi®δ.V}DdiëÀ"©.VDIQ#

```

Outputs the states each on a separated newline.

Try it online or verify all test cases.

**Explanation:**

Yet another 05AB1E monstrosity..

```
[              # Loop indefinitely:
 =             #  Print the current list with trailing newline (without popping)
               #  (which will be the implicit input-list in the first iteration)
  "..."        #  Create the recursive-string explained below
       ©       #  Store it in variable `®` (without popping)
        .V     #  Evaluate and execute it as 05AB1E code
          DIQ  #  If it's now equal to the input:
             # #   Stop the infinite loop
               #
Ð              # Triplicate the current list/item
 ˜             # Flatten the top copy
  Êi           # If the top two lists are NOT equal (so there is an inner list):
     δ         #  Map over each inner item:
    ® .V       #   Do a recursive call
   }           # After the if-statement, whether we've executed it or not
    Ddië       # If the current item is NOT an integer (so it's a list):
               # (necessary to prevent rotation on multi-digit integers)
        À      #  Rotate this list once towards the left

```
> 3 votes

# Answer
# Charcoal, 42 bytes

```
⊞υθＦυＦΦι⁺κ⟦⟧⊞υκＷ¬⁼θω«≔∨ω×¹θω⟦⭆¹θ⟧ＦυＵＭκ§κ⊕μ

```

Try it online! Link is to verbose version of code. Would save 1 byte if the initial state could be last instead. Explanation:

```
⊞υθＦυＦΦι⁺κ⟦⟧⊞υκ

```

Collect the list and all of the sublists.

```
Ｗ¬⁼θω«

```

Repeat until the current value equals the original value.

```
≔∨ω×¹θω

```

Actually save a clone of the original value the first time through the loop, so that the above comparison fails to start with and then succeeds when the original value returns.

```
⟦⭆¹θ⟧

```

Pretty-print the list, since Charcoal's default list output format doesn't suit ragged lists.

```
ＦυＵＭκ§κ⊕μ

```

Rotate the list and all of its sublists.
> 3 votes

# Answer
# Jelly, 9 bytes

```
ṙ1ßI¡€
ÇƬ

```

A monadic Link that accepts a ragged list of numbers and yields the recursivesly rotated states in a list.

**Try it online!**

Note that this still works if ragged lists and their sublists may be empty.

### How

```
ṙ1ßI¡€ - Helper Link, one recursive rotation: ragged list of numbers A
ṙ1     - rotate A left by one
     € - for each element:
    ¡  -   repeat... (utilised as an if statement, as described below)
   I   -   ...number of times: forward differences
                               given either a number or a list containing up to one
                                 number and nothing else we get an empty list which
                                 is falsey, so we don't do the "action"
                               given any other list get a non-empty list
                                 which is truthy, so we do the "action" once
  ß    -   ...action: call this Link (with the element)

ÇƬ - Main Link: ragged list of numbers, R
 Ƭ - start with R and collect inputs up while distinct applying:
Ç  -   call the last Link (our helper) as a monad - f(current)

```
> 3 votes

# Answer
# PARI/GP, 73 bytes

```
a->b=a;until(a==b=t(b),print(b))
t(a)=if(#a',[t(a[i%#a+1])|i<-[1..#a]],a)
```

Attempt This Online!
> 2 votes

# Answer
# Javascript, 110 Bytes

# Solution

```
    j=JSON.stringify
    f=x=>-x+x?[...x.slice(1),x[0]].map(f):x
    g=(x,y=[])=>y.includes(j(x))?y+"":g(f(x),[...y,j(x)])

```

# Explanation

```
    j=JSON.stringify
    f=x=>
      -x+x                     // If x is a number, then -x+x is 0 (i.e.
                               // falsey), but if x is an array, then -x+x is
                               // a non-empty string (i.e. truthy)

        ? [...x.slice(1),x[0]].map(f) // Rotate array and recurse if x is an
                                      // array
        :x                     // return as is otherwise

    g=(x,y=[])=>
      y.includes(j(x))          // Stop when y includes current array
        ? y+""                  // Equivalent to y.join(",")
        : g(f(x),[...y,j(x)])   // Recurse

```

# Tests

```
// 110 Bytes, solution in g(x)

j=JSON.stringify
f=x=>-x+x?[...x.slice(1),x[0]].map(f):x
g=(x,y=[])=>y.includes(j(x))?y+"":g(f(x),[...y,j(x)])

// Test Cases

input1 = [[2,3],4,5,5]
input2 = [1,10,[2,2,4],6,[[5,6],7],1]
input3 = [[5,6],[6,5]]
input4 = [1,[2,3,4,5,6],[7,8]]

console.log(g(input1))
console.log(g(input2))
console.log(g(input3))
console.log(g(input4))
```
> 2 votes

# Answer
# Factor \+ `math.unicode`, 80 bytes

```
[ dup '[ dup . [ dup array? [ 1 rotate ] when ] deep-map dup _ ≠ ] loop drop ]

```

Try it online!

The key to this is the `deep-map` combinator which is like `map` except instead of acting on the surface elements of a sequence, it uses a depth-first search algorithm to perform the mapping. We need to check if the element is a list and only perform the rotation if so (since rotating an atom causes an error).
> 2 votes

# Answer
# Python3, 124 bytes:

```
f=lambda x:x if int==type(x)else(j:=[f(i)for i in x])[1:]+j[:1]
g=lambda x,c=0:[x]+([]if(y:=f(x))==(c or x)else g(y,c or x))

```

Try it online!
> 1 votes

# Answer
# Python 3, 81 bytes

*Your OP's reference implementation*

```
f=lambda L,*t:t*(L in t)or f(g(L),*t,L)
g=lambda L:L*-1*-1or[*map(g,L[1:]+L[:1])]

```

Try it online!
> 1 votes

---
Tags: code-golf, ragged-list
---


# Question
Title: Implement a very simple ALU using only NAND gates
*Note: This challenge was inspired by Joe Z's many excellent questions surrounding NAND golfing.*

## Description

Your goal in this challenge, should you choose to accept it, is to implement a very simple ALU using just NAND gates. The ALU can only perform the the following four operations:

1. 00, meaning increment (wrapping at 15).
2. 01, meaning decrement (wrapping at 0).
3. 10, meaning logical left shift.
4. 11, meaning return zero.

Your circuit should take six inputs and give four outputs. Inputs I0 and I1 denote the operation. Inputs I2 through I5 denote the value to be operated on. Outputs O0 through O3 denote the output value.

## Scoring

Your score is the number of gates you utilize to create this circuit. Lower is better.

## Test cases

| I0-I1 | I2-I5 | O0-O3 |
| --- | --- | --- |
| 00 | 0001 | 0010 |
| 01 | 0000 | 1111 |
| 10 | 0100 | 1000 |
| 10 | 0011 | 0110 |
| 11 | 1100 | 0000 |

# Answer
# ~~71~~ ~~64~~ 49 gates

First define a few additional boolean operations in terms of *NAND*:

```
NOT(x)     := NAND(x,x)                           # 1 NAND
AND(a,b)   := NOT(NAND(a,b))                      # 2 NANDs
XOR(a,b)   := NAND(NAND(t=NAND(a,b),a),NAND(t,b)) # 4 NANDs

# AND(XOR(a,b), XOR(c,b)) in 7 NANDs:
XAX(a,b,c) := NOT(NAND(NAND(NAND(NOT(a), b), NAND(c, a)), NAND(c, b)))

```

Then we can define the ALU with these operations:

```
ni0    = NOT(i0)
ni1    = NOT(i1)
double = AND(i0,ni1)
o3     = AND(ni0,NOT(i5))
o2     = NAND(NAND(double,i5), NAND(ni0,XOR(XAX(o3,i5,i1),i4)))
o1     = NAND(NAND(double,i4), NAND(ni0,XOR(XAX(o2,i4,i1),i3)))
o0     = NAND(NAND(double,i3), NAND(ni0,XOR(XAX(o1,i3,i1),i2)))

```

Try it online!

This uses 9 NANDs, 3 NOTs, 2 ANDs, 3 XORs and 3 XAXs for a total of 49 NAND gates.

There is one gate that could be saved by removing some of the abstraction (we could get `NOT(o3)` for free and use that in the first *XAX*), but until I find some larger improvement I'd like to keep it simple.

The logic for the three higher bits might seem a bit intimidating, but with some transformations it is actually not bad:
`NAND(NAND(...), NAND(...))` is equivalent to `OR(AND(...), AND(...))`. The left *AND* reads "operation is *double* and the bit to right in the input is set", and the right one flips the bit if *XAX(new value of bit to the right, old value of bit to the right, decrement)* evaluates to 1. And `XAX(a,b,c)` is equivalent to `a>b if c else a<b`.
> 11 votes

# Answer
# 42 gates

```
a, b, c, d, e, f = I

na = NOT(a)
nb = NOT(b)
nc = NOT(c)
nd = NOT(d)
ne = NOT(e)
nf = NOT(f)

xa = NAND(NAND(a, ne), NAND(na, e))
xb = NAND(NAND(b, ne), NAND(nb, e))
xc = NAND(NAND(c, ne), NAND(nc, e))

o0 = NOT(NAND(na, nf))

M = NOT(NAND(ne, f))

nxa = NOT(xa)

o1 = NAND(NAND(M, a), NAND(nf, XOR(xa, b, nxa, nb)))

nxaxb = NAND(xa,xb)
xaxb = NOT(nxaxb)

o2 = NAND(NAND(M, b), NAND(nf, XOR(xaxb, c, nxaxb, nc)))

nxaxbxc = NAND(xaxb, xc)
xaxbxc = NOT(nxaxbxc)

o3 = NAND(NAND(M, c), NAND(nf, XOR(xaxbxc, d, nxaxbxc, nd)))

```

Try it online!

11 NOT's, 22 NAND's, 3 XOR's (`XOR(a,b)` is defined as `NAND(NAND(NOT(a), b),NAND(a, NOT(b)))` except we pass in `NOT(a)` and `NOT(b)`).
> 8 votes

# Answer
# 88 NAND Gates

This is just the first thing i could think of, given the challenge specification... some obvious things might become apparent later.

Here shown decrementing 6.
> 6 votes

# Answer
# ~~59~~ ~~56~~ ~~53~~ ~~52~~ ~~51~~ 50 gates

I thought I'd create an actual ALU here, even though it ended up taking more gates than @ovs' answer. Edit: A true ALU would actually use identical lanes for all four bits of the form `Result = Input + ((Input & Mask) ^ Flip) + Carry`. This would provide for eight different operations:

```
Mask Flip Carry Result
0    0    0     Input
0    0    1     Input + 1
0    1    0     Input - 1
0    1    1     Input
1    0    0     Input * 2
1    0    1     Input * 2 + 1 (c.f. Z80 SLL "instruction")
1    1    0     -1
1    1    1     0

```

Each lane (except the last, as the carry out is not required) would use 15 gates, and then 5 gates are needed to generate the desired carry in for the four operations, making a total of 64 gates. However my first approach actually special-cased the first lane, so that I could choose between the input and `1` as the RHS of the full adder:

```
00: IIII -> IIII + 0001
01: IIII -> IIII - 0001
10: IIII -> IIII + IIII
11: IIII -> IIII - IIII

```

To get the RHS takes 8 gates:

```
R2 = NAND(NOT(I2), I0)
R3 = NOT(NAND(I3, I0))
R4 = NOT(NAND(I4, I0))
R5 = NOT(NAND(I5, I0))

```

To select between `+` and `-`, I perform 2's complement on the value. 1's complement takes 16 gates:

```
S2 = XOR(R2, I1)
S3 = XOR(R3, I1)
S4 = XOR(R4, I1)
S5 = XOR(R5, I1)

```

To achieve 2's complement we simply add `I1` as part of the `IIII + SSSS` operation:

```
C0, O0 = ADD(I2, S2, I1)
C1, O1 = ADD(I3, S3, C0)
C2, O2 = ADD(I4, S4, C1)
C3, O3 = ADD(I5, S5, C2)

```

This takes 36 gates for a grand total of 60 gates, except we don't need `C3` which saves a gate.

Notes:

* `NOT` takes 1 gate:

```
NOT(X) = NAND(X, X)

```
* `XOR` takes 4 gates:

```
XOR(X, Y) = _XOR2(X, Y, NAND(X, Y))
_XOR2(X, Y, W) = NAND(NAND(X, W), NAND(Y, W))

```
* `ADD` takes 9 gates:

```
ADD(X, Y, Z) = _ADD2(X, Y, Z, NAND(Y, Z))
_ADD2(X, Y, Z, W) = _ADD3(X, W, _XOR2(Y, Z, W))
_ADD3(X, W, V) = _ADD4(X, W, V, NAND(X, V))
_ADD4(X, W, V, U) = NAND(W, U), _XOR2(X, V, U)

```

Edit: The LSB's adder's inputs have a lot of redundancy:

```
S2 = XOR(R2, I1)
C0, O0 = ADD(I2, S2, I1)

```

But this means that `XOR(S2, I1)` is just `R2`, so we can write this as:

```
C0 = NAND(NAND(S2, I1), NAND(I2, XOR(S2, I1)))
   = NAND(NAND(S2, I1), NAND(I2, R2))
O0 = XOR(I2, XOR(S2, I1))
   = XOR(I2, R2)
   = _XOR2(I2, R2, NAND(I2, R2))

```

This saves three gates.

Edit: Even more redundancy that I overlooked:

```
C0 = NAND(NAND(S2, I1), NAND(I2, XOR(S2, I1)))
   = NAND(NAND(S2, I1), NAND(I2, R2))
   = NAND(NAND(XOR(R2, I1), I1), NAND(I2, R2))
   = NAND(NAND(NOT(R2), I1), NAND(I2, R2))

```

Although this costs a gate, it makes `S2` unnecessary which saves four gates for an overall saving of three gates.

Edit: Found another redundant gate:

```
C0 = NAND(NAND(S2, I1), NAND(I2, XOR(S2, I1)))
   = NAND(NAND(S2, I1), NAND(I2, R2))
   = NAND(NAND(XOR(R2, I1), I1), NAND(I2, R2))
   = NAND(NAND(NOT(R2), I1), NAND(I2, R2))
   = NAND(NAND(NOT(R2), I1), NAND(I2, NAND(NOT(I2), I0)))
   = NAND(NAND(NOT(R2), I1), NOT(I2))

```

Although this seems to just change a shared `NAND` to a shared `NOT`, I computed `NOT(I2)` as part of the calculation for `R2`, so that gate can be shared too, thus saving another gate.

Edit: This applies to `O2` as well, then further allowing for a further saving of one gate:

```
O0 = XOR(I2, XOR(S2, I1))
   = XOR(I2, R2)
   = _XOR2(I2, R2, NAND(I2, R2))
   = _XOR2(I2, R2, NAND(I2, NAND(NOT(I2), I0)))
   = _XOR2(I2, R2, NOT(I2))
   = NAND(NAND(I2, NOT(I2)), NAND(R2, NOT(I2)))
   = NOT(NAND(R2, NOT(I2)))

```

Edit: One final gate can be saved by eliminating `R2`.

```
C0 = NAND(NAND(NOT(R2), I1), NOT(I2))
   = NAND(NAND(NOT(NAND(NOT(I2), I0)), I1), NOT(I2))
   = NAND(NAND(AND(NOT(I2), I0), I1), NOT(I2))
   = OR(AND(AND(NOT(I2), I0), I1), I2)
   = OR(AND(I0, I1), I2)
   = NAND(NAND(I0, I1), NOT(I2))
O0 = NOT(NAND(R2, NOT(I2)))
   = NOT(NAND(NAND(NOT(I2), I0), NOT(I2)))
   = NOT(NAND(OR(I2, NOT(I0)), NOT(I2)))
   = NOT(NAND(NOT(I0), NOT(I2)))

```
> 3 votes

# Answer
# ~~46~~  44 gates

```
input a[4]
input c[2]
tmp s[4] = a + {1,c[0],c[0],c[0]} // 1+9+9+8=27
tmp !c[1] // 1
tmp t[4] = {0,c[0]<s[0],c[0]<s[1],c[0]<s[2]} // 3+2
out {s[0]&!c[1],c[1]?t[1]:s[1],c[1]?t[2]:s[2],c[1]?t[3]:s[3]} // 11

```

Maybe we need a checker

s\[0\]: t+1 = t(!t), costing 1

`c[0]>=s[0]` is found when making `s`

out: a?b:c = (a nand b) nand (!a nand c)

You can try it by running this code in console of nandgame.com and refresh
> 3 votes

---
Tags: atomic-code-golf, logic-gates
---