text:
Make an Emergency Corridor
In some nations there are recommendations or laws on how to form emergency corridors on streets that have multiple lanes per direction. (In the following we only consider the lanes going in the direction we are travelling.) These are the rules that hold in Germany:

If there is only one lane, everyone should drive to the right such that the rescue vehicles can pass on the left.
If there are two or more lanes, the cars on the left most lane should drive to the left, and everyone else should move to the right.

Challenge
Given the number N>0 of regular lanes, output the layout of the lanes when an emergency corridor is formed using a string of N+1 ASCII characters. You can use any two characters from ASCII code 33 up to 126, one to denote the emergency corridor, and one for denoting the cars. Trailing or leading spaces, line breaks etc are allowed.
Examples
Here we are using E for the emergency corridor, and C for the cars.
N  Output
1  EC
2  CEC
3  CECC
4  CECCC
5  CECCCC
6  CECCCCC
   etc

I won't fall for this! You're just looking for a lane of your own to slither through you sneaky snake.

A school assignment disguised as code golf? ;)

@PmanAce I really don't think flawr needs our help for this :P

I wouldn't suppose we could zero index?

@user56656 Sorry, it is too late to change that now that so many people have answered.

+1 because it actually works in Germany. Was in the situation last weekend.

I don't understand how you get E and C stuffed into one lane, or C, E, C, C, and C into four. (That's a question on the storyline of the question, not on the challenge itself.)

@msh210 Normally there are n lanes, but when an emergency corridor is formed there are n lanes C and the emergency corridor E.

@msh210 I think the pictures in the german WP page explain it best.

You know, at first this looked like a to-the-point challenge with C and E, but there are so many nice approaches possible for this challenge! Using mathematical operations for C=1/E=2 or C=2/E=3 like the top answer does; using C=0/E=1 with 10^(n-1); using C=0/E=. by decimal formatting 0.0; using C=1/E=- by utilizing -1; etc. etc. So many unique possibilities for a challenge that looked so to-the-point at first. Too bad I can only +1 once. ;)

Is there a maximum n we need to support? In Java for example, long is a 64-bit number and a decimal double/float has only 15 digits after the comma, so using an arithmetic or decimal approach only works up to n=16.. I think this applies to every programming language without an arbitrary number-size. Some languages also start using 1e# from a certain amount of digits. Besides, I highly doubt there are any highways in Germany with more than 8 lines wide in one direction..

@KevinCruijssen Using a built in integer type is sufficient.

Python 2, 29 26 bytes
lambda n:10**n*97/30-1/n*9

Example:
>>> f(1)
23
>>> f(2)
323
>>> f(3)
3233

you need to output 21 in the n=1 case

@DanielIndie :( fixed but now it's ugly.

Still a very creative solution:)

@orlp sorry :) but still a fine solution :)

Nice solution! You can shorten 9*(n<2) to 1/n*9.

10**n*97/30-1/n*9 saves another byte, giving f(5) == 323333 etc.

Python 3, 35 33 bytes
lambda N:'C'*(N>1)+'EC'+'C'*(N-2)

Edit: dropping f= to save 2 bytes, thanks to @dylnan's reminder.
Try it online!
To visualize it:
lambda N:''*(N>1)+''+''*(N-2)

Output:
1
2
3
4
5
6

Try  online!
Python 3, 40 bytes
A straightforward solution:
lambda N:str(10**N).replace('100','010')

Try it online!

I think the 'straightforward' solution has unnecessary whitespace after lambda N:

@someone I was not aware of that, thanks.

C (gcc), 32 bytes
f(n){printf(".%.*f"+1%n,n-1,0);}

Try it online!
Uses 0 and . characters:
.0
0.0
0.00
0.000
0.0000

Japt, 5 4 bytes
Uses q for cars and + for the corridor.
ç¬iÄ

Try it
Credit to Oliver who golfed 4 bytes off at the same time as I did.

Explanation
A short solution but a tricky explanation!
The straightforward stuff first: The ç method, when applied to an integer, repeats its string argument that number of times. The i method takes 2 arguments (s & n) and inserts s at index n of the string it's applied to.
Expanding the 2 unicode shortcuts used gives us çq i+1, which, when transpiled to JS becomes U.ç("q").i("+",1), where U is the input. So we're repeating q U times and then inserting a + at index 1.
The final trick is that, thanks to Japt's index wrapping, when U=1, i will insert the + at index 0, whatever value you feed it for n.

I was going to post ç0 iQ1 for 6 bytes, but it would be better if you used it.

Thanks, @Oliver. Got it down to 5 bytes in the meantime, though.

ç¬iÅ for 4 bytes ;) I've never abused Japt this much.

I was just about to do the same with Ä instead of Å :)

R, 50 bytes
-11 thanks to Giuseppe!
pryr::f(cat("if"(x<2,12,c(21,rep(2,x-1))),sep=""))

Outputs 1 for emergency corridor and 2 for normal lanes
My attempt, 61 bytes
Nothing fancy to see here, but let's get R on the scoreboard =)
q=pryr::f(`if`(x<2,cat("EC"),cat("CE",rep("C",x-1),sep="")))

Usage:
q(5)
CECCCC

Save 8 bytes using 21=12+9 and forcing TRUE/FALSE to 1/0 without an if https://tio.run/##K/r/v6CossjKKk0jObFEw1JLI8/OUFPb0EinKLVAw0gnT9dQU6c4tcBWSUlT8/9/AA

Haskell, 38 34 32 bytes
f 1="EC"
f n="CE"++("C"<*[2..n])

Try it online!

Python 2, 30 29 28 bytes
lambda n:`10/3.`[1/n:n-~1/n]

Print 3 instead of C and . instead of E.
Explanation:
Try it online.
lambda n:    # Method with integer parameter and string return-type
  `10/3.`    #  Calculate 10/3 as decimal (3.333333333) and convert it to a string
  [1/n       #   Take the substring from index 1 if `n=1`, 0 otherwise
   ,n-~      #   to index `n+1` +
       1/n]  #    1 if `n=1`, 0 otherwise

Python 2, 33 32 31 29 28 bytes
lambda n:1%n-1or'1-'+'1'*~-n

Prints 1 instead of C and - instead of E.
-2 bytes thanks to @ovs.
-1 byte thanks to @xnor.
Explanation:
Try it online.
lambda n:    # Method with integer parameter and string return-type
  1%n-1      #  If `n` is 1: Return '-1'
  or         #  Else:
    '1-'+    #   Return '1-', appended with:
    '1'*~-n  #   `n-1` amount of '1's

Your 10/3 one fails at 17

@JoKing I just clarified with OP, and he said "Using a built in integer type is sufficient.", which means up to n=16 if your integer built-in is 64-bit is enough, or in this case n=16 when the decimal value can't hold more than 15 decimal digits by default is enough. (Same applies to a lot of the other answers using languages with arbitrary number sizes, like Java, C# .NET, etc.)

Pyth, 10 9 8 bytes
Xn1Q*NQZ

Uses 0 to denote the emergency corridor and ".
Try it here
Explanation
Xn1Q*NQZ
    *NQ     Make a string of <input> "s.
 n1Q         At index 0 or 1...
X      Z    ... Insert 0.

Octave (MATLAB*), 31 30 28 27 22 bytes
@(n)'CE'(1+(n>1==0:n))

Try it online!
The program works as follows:
@(n)                   %Anonymous function to take input
            n>1==0:n   %Creates [1 0] if n is 1, or [0 1 (0 ...)] otherwise
         1+(        )  %Converts array of 0's and 1's to 1-indexed
    'CE'(            ) %Converts to ASCII by addressing in string

The trick used here is XNORing the seed array of 0:n with a check if the input is greater than 1. The result is that for n>1 the seed gets converted to a logical array of [0 1 (0 ...)] while for n==1 the seed becomes inverted to [1 0], achieving the necessary inversion.
The rest is just converting the seed into a string with sufficient appended cars.

(*) The TIO link includes in the footer comments an alternate solution for the same number of bytes that works in MATLAB as well as Octave, but it results in a sequence of '0' and '1' rather than 'E' and 'C'. For completeness, the alternate is:
@(n)['' 48+(n>1==0:n)]

Saved 1 byte by using n==1~=0:1 rather than 0:1~=(n<2). ~= has precedence over <, hence the original  brackets, but is seems that ~= and == are handled in order of appearance so by comparing with 1 we can save a byte.
Saved 2 bytes by changing where the negation of 2:n is performed. This saves a pair of brackets. We also have to change the ~= to == to account for the fact that it will be negated later.
Saved 1 byte using < again. Turns out that < has same precedence as == after all. Placing the < calculation before the == ensures correct order of execution.
Saved 5 bytes by not creating two separate arrays. Instead relying on the fact that the XNOR comparison will convert a single range into logicals anyway.

Very clever :-)

@StewieGriffin Thanks :). Managed to knock off another 5 bytes more.

brainfuck, 42 bytes
,[[>]+[<]>-]>>[<]<[<]>+>+<[<-[--->+<]>.,>]

Try it online!
Takes input as char code and outputs as V being normal lanes and W being the cleared lane. (To test easily, I recommend replacing the , with a number of +s)
How it Works:
,[[>]+[<]>-] Turn input into a unary sequence of 1s on the tape
>>[<]<[<]    Move two cells left of the tape if input is larger than 1
             Otherwise move only one space
>+>+<        Add one to the two cells right of the pointer
             This transforms:
               N=1:  0 0' 1 0  -> 0 2' 1 0
               N>1:  0' 0 1 1* -> 0 1' 2 1*
[<-[--->+<]>.,>]  Add 86 to each cell to transform to Ws and Vs and print

05AB1E, 7 bytes
Î>∍1I≠ǝ

Try it online!
0 is C and 1 is E.
Explanation
Î>          # Push 0 and input incremented            -- [0, 4]
  ∍         # Extend a to length b                    -- [0000]
   1I≠      # Push 1 and input falsified (input != 1) -- [0000, 1, 1]
      ǝ     # Insert b in a at location C             -- [0100]
            # Implicit display

Oh you sly fox. $<×TìsiR was how I was thinking.

@MagicOctopusUrn That's an interesting approach ! I lingered over the "if" construction as well but it requires at least 3 bytes, hence the need for a different approach :-)

In the new version of 05AB1E, 1I can be golfed to $.

5 bytes (also works in the legacy version).

Haskell, 35 33 32 bytes
2 bytes saved thanks to Angs, 1 byte saved thanks to Lynn
(!!)$"":"EC":iterate(++"C")"CEC"

Try it online!
Haskell, 32 30 29 bytes
This is zero indexed so it doesn't comply with the challenge
g=(!!)$"EC":iterate(++"C")"CEC"

Try it online!
Haskell, 30 bytes
This doesn't work because output needs to be a string
f 1=21
f 2=121
f n=10*f(n-1)+1

Try it online!
Here we use numbers instead of strings, 2 for the emergency corridor, 1 for the cars.  We can add a 1 to the end by multiplying by 10 and adding 1.  This is cheaper because we don't have to pay for all the bytes for concatenation and string literals.
It would be cheaper to use 0 instead of 1 but we need leading zeros, which end up getting trimmed off.

((blah)!!) can become (!!)$blah to save a byte in your first two answers.

@Lynn Thanks!  I tried to do that earlier but I must have mis-counted the bytes.

APL (Dyalog Unicode), 21 17 16 bytes
(-≠∘1)⌽'E',⍴∘'C'

Try it online!
Thanks to Erik for saving 4 bytes and Adám for one further byte.
How?
(-≠∘1)⌽'E',⍴∘'C' ⍝ Tacit function
           ⍴∘'C' ⍝ Repeat 'C', according to the input
       'E',      ⍝ Then append to 'E'
      ⌽          ⍝ And rotate
    1)           ⍝ 1
  ≠∘             ⍝ Different from the input? Returns 1 or 0
(-               ⍝ And negate. This rotates 0 times if the input is 1, and once if not.

(⍵>1) doesn't need to be in parentheses. And you can save 4 bytes with a tacit function: (⊢×1<⊢)⌽'E',⍴∘'C'.

@EriktheOutgolfer thanks! I didn’t have the time to go tacit after posting because I had a class today. I’ll edit when I get home.

(-≠∘1)⌽'E',⍴∘'C' or =∘1⌽¯1⌽'E',⍴∘'C'.

15 bytes with ⎕io=0: 'CE'[1(≠=∘⍳+)⎕]

@ngn I can't even... can you get me a TIO link with the test cases? Can't seem to make it work...

@J.Sallé TIO link

Jelly, 11 9 bytes
’0ẋ⁾0E;ṙỊ

Try it online!
Full program.
Uses 0 instead of C.

C (gcc), 39 bytes
f(n){printf("70%o"+!n,7|(1<<3*--n)-1);}

Try it online!
Borrowed and adapted the printf trick from ErikF's answer.

Welcome to the site and nice first post!

Python 3, 32 bytes
lambda n:f"{'CE'[n<2:]:C<{n+1}}"

Try it online!
Uses an f-string expression to format either'E'or'CE' padded on the right with'C'so it has width ofn+1.
f"{          :       }    a Python 3 f-string expression.
   'CE'[n<2:]             string slice based on value of n.
             :            what to format is before the ':' the format is after.
              C           padding character
               <          left align
                {n+1}     minimum field width based on n

Brain-Flak, 100 66 bytes
{({}[()]<((((()()()()){}){}){}())>)}{}(({}<>)())<>{<>{({}<>)<>}}<>

Try it online!
Uses " as the emergency lane and ! as the normal lanes.

+1 for using this language of all things. XD

@Alex, Well, Brain-Flak is the language of the month for April

Seriously or late April Fool's joke? Where do languages of the month get elected?

@Alex Nominations and voting here, and then a month-specific post is made such as this one

Oh, it's on this platform. I see, thanks! :-)

C#, 34 bytes
n=>n++<2?"EC":"CE".PadRight(n,'C')

Try it online!

Python 3, 30 29 bytes
lambda n:"CEC"[~n:]+"C"*(n-2)

Try it online!
OK, there is a lot of Python answers already, but I think this is the first sub-30 byter among those still using "E" and "C" chars rather than numbers.

JavaScript (Node.js), 28 bytes
n=>n<2?21:"12".padEnd(n+1,1)

Try it online!

Stax, 7 bytes
ü♣àj#F

Run and debug it
This uses the characters "0" and "1".  This works because when you rotate an array of size 1, it doesn't change.
Unpacked, ungolfed, and commented, it looks like this.
1]( left justify [1] with zeroes. e.g. [1, 0, 0, 0]
|)  rotate array right one place
0+  append a zero
$   convert to string

Run this one

APL+WIN, 20 16 bytes
4 bytes saved thanks to Adám
Prompts for integer n:
(-2≠⍴n)⌽n←1⎕/⍕10

1 for emergency corridor o for cars.

16: (-2≠⍴n)⌽n←1⎕/⍕10

@Adám Thanks. I see ngn's trick, 1⎕/⍕, is coming in useful. One for the idiom list?

What idiom list are you talking about?

@Adám The two idiom lists I use most frequently are the Finnapl and APL2idioms

I'm not sure what's so idiomatic here. It is just golfy. Anyway, my idiom list may interest you.

Perl 5 -p, 27 20 19 bytes
$_=1x$_;s/1?\K1/E1/

Try it online!
Saved a byte by using 1 for the cars and E for the emergency corridor.

APL (Dyalog Unicode), 16 bytes
≡∘1⌽'CE',1↓⍴∘'C'

Try it online!

JavaScript (Node.js), 19 bytes
n=>--n?"0"+10**n:10

Try it online!

Whitespace, 141 104 103 bytes
[S S S N
_Push_0][S N
S _Duplicate_0][T   N
T   T   _Read_STDIN_as_number][T    T   T   _Retrieve][S S S T  S N
_Push_2][T  S S T   _Subtract][S N
S _Duplicate_input-2][N
T   T   N
_If_negative_Jump_to_Label_-1][S S S T  N
_Push_1][S N
S _Duplicate_1][T   N
S T _Print_as_integer][S S T    T   N
_Push_-1][T N
S T _Print_as_integer][T    S S T   _Subtract][N
S S T   N
_Create_Label_LOOP][S N
S _Duplicate][N
T   T   S N
_If_negative_Jump_to_EXIT][S S S T  N
_Push_1][S N
S _Duplicate_1][T   N
S T _Print_as_integer][T    S S T   _Subtract][N
S N
T   N
_Jump_to_LOOP][N
S S N
_Create_Label_-1][T N
S T _Print_as_integer][N
S S S N
_Create_Label_EXIT]

Letters S (space), T (tab), and N (new-line) added as highlighting only.
[..._some_action] added as explanation only.
Prints 1 instead of C and - instead of E.
-1 byte thanks to @JoKing by suggesting the use of 1 and -1 instead of 0 and 1.
Explanation in pseudo-code:
Integer i = STDIN-input as integer - 2
If i is negative (-1):
  Print i (so print "-1")
Else:
  Print "1-1"
  Start LOOP:
    If i is negative:
      EXIT program
    Print "1"
    i = i-1
    Go to the next iteration of the LOOP

Example runs:
Input: 1
Command   Explanation                 Stack      Heap    STDIN   STDOUT   STDERR

SSSN      Push 0                      [0]
SNS       Duplicate top (0)           [0,0]
TNTT      Read STDIN as integer       [0]        {0:1}   1
TTT       Retrieve heap at 0          [1]        {0:1}
SSSTSN    Push 2                      [1,2]      {0:1}
TSST      Subtract top two            [-1]       {0:1}
SNS       Duplicate input-2           [-1,-1]    {0:1}
NTSN      If neg.: Jump to Label_-1   [-1]       {0:1}
NSSN      Create Label_-1             [-1]       {0:1}
TNST      Print top as integer        []         {0:1}           -1
NSSSN     Create Label_EXIT           []         {0:1}
                                                                         error

Try it online (with raw spaces, tabs and new-lines only).
Stops with error: Exit not defined.
Input: 4
Command   Explanation                   Stack      Heap    STDIN   STDOUT   STDERR

SSSN      Push 0                        [0]
SNS       Duplicate top (0)             [0,0]
TNTT      Read STDIN as integer         [0]        {0:4}   4
TTT       Retrieve heap at 0            [4]        {0:4}
SSSTSN    Push 2                        [4,2]      {0:4}
TSST      Subtract top two              [2]        {0:4}
SNS       Duplicate input-2             [2,2]      {0:4}
NTSN      If neg.: Jump to Label_-1     [2]        {0:4}
SSSTN     Push 1                        [2,1]      {0:4}
SNS       Duplicate top (1)             [2,1,1]    {0:4}
TNST      Print as integer              [2,1]      {0:4}           1
SSTTN     Push -1                       [2,1,-1]   {0:4}
TNST      Print as integer              [2,1]      {0:4}           -1
TSST      Subtract top two              [1]        {0:4}
NSSTN     Create Label_LOOP             [1]        {0:4}
 SNS      Duplicate top (1)             [1,1]      {0:4}
 NTTSN    If neg.: Jump to Label_EXIT   [1]        {0:4}
 SSSTN    Push 1                        [1,1]      {0:4}
 SNS      Duplicate top (1)             [1,1,1]    {0:4}
 TNST     Print as integer              [1,1]      {0:4}           1
 TSST     Subtract top two              [0]        {0:4}
 NSNTN    Jump to Label_LOOP            [0]        {0:4}

 SNS      Duplicate top (0)             [0,0]      {0:4}
 NTTSN    If neg.: Jump to Label_EXIT   [0]        {0:4}
 SSSTN    Push 1                        [0,1]      {0:4}
 SNS      Duplicate top (1)             [0,1,1]    {0:4}
 TNST     Print as integer              [0,1]      {0:4}           1
 TSST     Subtract top two              [-1]       {0:4}
 NSNTN    Jump to Label_LOOP            [-1]       {0:4}

 SNS      Duplicate top (-1)            [-1,-1]    {0:4}
 NTTSN    If neg.: Jump to Label_EXIT   [-1]       {0:4}
NSSSN     Create Label_EXIT             [-1]       {0:4}
                                                                            error

Try it online (with raw spaces, tabs and new-lines only).
Stops with error: Exit not defined.

Would it be easier to print the clear lane as - by abusing printing -1?

@JoKing Unfortunately it would be longer. Try it online 112 bytes. It indeed changed push_0;print_as_integer;push_1;print_as_integer to push_-1;print_as_integer, but in exchange the two push_0;print_as_integer are replaced with push_45;print_as_character, where push_0 = SSSN, and push_45 = SSSTSTTSTN. And an additional push_45 has to be added as well, because for input n=1 I now print the duplicated 0 I already had on the stack, so I didn't had to push 0 again because the 0 was already on the stack.

I meant - as replacing 1 and 1 replacing 0. Then you would avoid having to push 45, and as far as I can tell this would save on printing a number in the first half of the conditional, but slightly increase costs on pushing 1 instead of 0. Check my Gol><> answer for an example of the output I mean

@JoKing I've tried implementing it, but I ended up at 107 bytes (here is the same code with added highlighting and explanation). It indeed saves on print_-1 instead of print 0 and 1, but an additional print_-1 is necessary outside the loop. EDIT: Been able to reduce it to 103 bytes by changing subtract_1;if_0_jump_to_ONE;push_-1;print_integer to subtract_2;if_negative_jump_to_ONE;print_integer, because -1 is already on the stack then. So thanks for -1 byte. :)

Jelly, 6 bytes
⁵*ṾṙỊṙ

Displays car lanes as 0, the emergency lane as 1.
Try it online!
How it works
⁵*ṾṙỊṙ  Main link. Argument: n

⁵*      Compute 10**n.
  Ṿ     Uneval; get a string representation.
   ṙỊ   Rotate the string (n≤1) characters to the left.
     ṙ  Rotate the result n characters to the left.

AutoHotkey 32 bytes
Replaces the letter "C" with "EC" unless amount of C > 1, then it sends "CEC" and exits the app.
::C::EC
:*:CC::CEC^c
^c::ExitApp

C => EC
CC => CEC then exits the program. Any further Cs will be entered after the program exits.

J, 11 bytes
1":1&<=i.,]

Try it online!
Based on ngn’s comment.
 and :
1&<,~/@A.'',~''$~,&4

MathGolf, 7 6 bytes
ú░\┴╜╪

Try it online.
Output 1 for E and 0 for C.
Explanation:
ú         # 10 to the power of the (implicit) input
          #  i.e. 1 → 10
          #  i.e. 4 → 10000
 ░        # Convert it to a string
          #  i.e. 10 → "10"
          #  i.e. 10000 → "10000"
  \       # Swap so the (implicit) input is at the top of the stack again
   ┴╜     # If the input is NOT 1:
     ╪    #  Rotate the string once towards the right
          #   i.e. "10000" and 4 → "01000"
          # Output everything on the stack (which only contains the string) implicitly

Canvas, 11 bytes
┤C×EC×╴╷？C×

Try it here!

[GNU sed 4.2.2], 14 bytes

Score includes 1 byte for the -r sed parameter
3 bytes saved thanks to @Leo

Input integer is given in unary.  Output characters are E for emergency vehicles and 1 for regular cars.
s/(.?)1/\1E1/

Try it online!

You know already what the second group will contain, so you can avoid it Try it online!

@Leo thanks - very good!

Jelly, 14 bytes
⁵*×109:90+Ị9×Ɗ

Try it online!
Port of orlp's python answer which only uses arithmetic.

Jelly, 15 bytes
ḊṬ1;,2Ṭ¤LÐṀị⁾CE

Try it online!

C (gcc), 48 bytes
f(n){for(printf("CEC"+!--n);--n>0;putchar(67));}

Try it online!

Python 3, 39 bytes
lambda n:'C'*(n>1)+'E'+'C'*(n-1+(n==1))

Try it online!

You can replace n==1 with n<2 since n will always be >0.

'C'*(n>1) can be replaced with 1%n*'C'

C# (.NET Core), 39 bytes
n=>(n--<2?"EC":"CE")+new string('C',n);

Try it online!

The solution is wrong. You have on C to many at the end of each line for n>1.

@raznagul I missed that, thanks for pointing it out. I fixed it.

PowerShell, 49 37 35 bytes
param($n)'C'*(1%$n)+1+'C'*($n-1%$n)

Try it online!
Saved a pair of quotes by just making the E into a number.

Gol><>, 10 bytes
IR1~I{lRn;

Try it online!
One of a few 10-byte solutions I found. I like this one the most because it uses the - as the clear lane, where the - is a result of printing -1.
The other 10-byte solutions:

IR0P{lPRn;
IR`CP{`C}H

Pity Gol><> doesn't have a halt and output the stack numbers command, like it does for chars, or this could be 3 bytes smaller.

Java 10, 53 51 45 42 38 37 36 35 34 bytes
n->n+=Math.pow(10,n)*97/30-1/n*9-n

Prints 3 instead of C and 2 instead of E.
Try it online.
Port of @orlp's Python 2 answer.
n+=...-n is used instead of (long)... to save a byte.

Old 35 bytes answer:
n->(10/3f+"").substring(1/n,1/n-~n)

Prints 3 instead of C and . instead of E.
Explanation:
Try it online.
n->{               // Method with integer parameter and String return-type
  (10/3f+"")       //  Divide 10 by 3 and convert it to a String ("3.333333333")
   .substring(1/n  //  And take the substring from index 1 if `n=1`, 0 otherwise
    ,1/n           //  to index 1 if `n=1`, 0 otherwise
        -~n)       //  + `n+1`

Nice, you beat my best guess at 39 bytes: n->n--<2?"10":"".format("01%0"+n+"d",0).

@OlivierGrégoire My 42-byte answer used String#format as well, but by using 0 and . :) (n->(n--<2?".":"")+"".format("%."+n+"f",0f)). So many nice approached possible for this challenge.

@OlivierGrégoire Your answer could have been golfed to 37 bytes by returning an Object instead of a String, so "10" becomes 10. :) I'm currently at 35 however by creating a port of the top Python 2 answer. EDIT: Just realized my 38 byte answer becomes 36 using the same Object instead of String trick however.. ;p

Python 2, 30 bytes
lambda n:1%n*'0'+`10**(n-1%n)`

Try it online!
If n is larger than 1, 1%n gets 1: 1*'0'+`10**(n-1)`
If n is equal to 1, 1%n gets 0: 0*'0'+`10**(1-0)`

Python 2, 31 bytes
lambda n:1/n*'.'+'%%.%df'%~-n%0

Try it online!
1/n*'.'        # if n is 1, insert a dot ...
+              # before
'%%.%df'%~-n%0 # the decimal representation of 0 with n-1 digits after the decimal point

'%%.%df'%~-n expands to '%.<n-1>f'.

MATL, 7 bytes
Q:G2Xl=

Try it online!
Uses 1 for emergency, 0 for normal traffic.
Q:      % Range 1...n+1, implicit input n
  G2Xl  % Explicitly push input, limit to 2 (so, either 1 or 2)
      = % Element-wise equality of range and limited input.
        % Implicit display.

This answer assumes (like some other answers) that separating spaces are OK. If not, append VXz for ten bytes.

Excel, 29 bytes
=IF(A1=1,0,10&REPT(1,A1-2))&1

Uses 0 for Emergency lane. 1 for Cars:
1  01
2  101
3  1011
4  10111
5  101111

J, 20 bytes
'CECC'#~1(<,[,=,-~)]

Try it online!

Python, 53 bytes
lambda n:-1*((n+1)//n-2)*'C'+'E'+(n+((n+1)//n-2))*'C'

Try it online!

Welcome to the site! You may not assume that input is stored in a variable, so please change the method you take input. A function is completely acceptable, so prepending your code with lambda n: would be perfectly fine.

Hi, welcome to PPCG! You can make the "Python, pure math+str, 45 bytes" title-case by adding a # in front of it. With Python lambdas you'll have to include lambda n: to the code and byte-count. So your current answer should be 53 bytes. Also, you might want to add a TIO-link with test code. Here is an example of how to do that with your code. Something to golf: both (n+1) can be -~n. Tips for golfing in Python might also be interesting to read through. Enjoy your stay!

Excel, 28 bytes
=REPT(2,A1+1)-10^MAX(A1-1,1)

Uses 2 for cars, and 1 for Corridor
Makes a list of 2s n+1 long, then subtracts the larger of 10^(n-1) and 10:

n=1 : 22 - MAX(1,10) = 12
n=2 : 222 - MAX(10,10) = 212
n=3 : 2222 - MAX(100,10) = 2122
n=10 : 22222222222 - MAX(1000000000,10) = 21222222222

Haskell (interactive), 30 bytes
a 1=12;a 2=212;a n=a(n-1)*10+2

1 is a corridor, 2 is a car.
Example:
GHCi, version 8.2.2: http://www.haskell.org/ghc/  :? for help
Prelude> a 1=12;a 2=212;a n=a(n-1)*10+2
Prelude> a 1
12
Prelude> a 2
212
Prelude> a 3
2122
Prelude> a 4
21222
Prelude> a 5
212222

Welcome to the site! I wrote a similar answer earlier but commenters pointed out that answers need to output a string, whereas this outputs a number, in order to get the string you need to also use show.

The current top Python answer uses a number printing in an interactive prompt too and doesn't use print.

Huh.  I didn't see that.  I would leave a comment on the OP to make sure that this output form is permissible.

@user56656 Or just let the language be "Haskell (interactive)". Done. (or does it work? consider this is a function submission)

ghci requires let to bind a, the example would result in a parse error

Scratch that, it's new in ghci 8 it seems. Might want to add that specifier in the language header.

It's just an example of it working. It's clear it uses GHCI 8. GHCI is not a language (and neither is 'interactive Haskell'). I have gotten one vote and two nitpickers. No one has told the top Python answer they return a number or that their language is 'interactive Python' and that answer is what I looked at when writing mine. No one also has problems with lambdas/functions in Python or other languages if the question didn't say "write a full program" but I got a comment about that as well. So much for a healthy welcoming community.

Perl 5 -lp, 19 bytes
#!/usr/bin/perl -lp
$_=--$_?CE.C x$_:EC

Try it online!

Ruby, 25 bytes
->n{n>1?'CE'+?C*~-n:'EC'}

Try it online!

APL (Dyalog Classic), 11 bytes
⊃∘⍕¨1∘<=0,⍳

Try it online!
uses ⎕io←1

Prolog (SWI), 63 51 bytes
1+`EC`.
2+`CEC`.
N+X:-M is N-1,M+Y,append(Y,`C`,X).

Try it online!

Octave, 36 34 33 bytes
x((n=input(''))+1)=0;x(1+(n>1))=1

Try it online!

Windows Batch, 75 bytes
To be improved...
@if %1==1 echo EC&exit/b
@cd|set/p=CE
@for /l %%G in (2,1,%1)do @cd|set/p=C

Retina 0.8.2, 17 bytes
.+
E$&$*C
ECC
CEC

Try it online! I could save a byte by using 1 for a car.

"I could save a byte by using 1 for a car." Then why don't you do so?.. In the challenge rules it states "You can use any two characters from ASCII code 33 up to 126, one to denote the emergency corridor, and one for denoting the cars."

Python 3, 31 bytes
lambda n:'ECE'[n>1:n+1]+'C'*~-n

Try it online!
At first I tried reversing EC if n>1, but converting a boolean to (-1,+1) turned out longer than using a different string instead.
Alternative 31 byte solutions:

lambda n:'ECCE'[n>1::2]+'C'*~-n Try it online!
lambda n:bin(4**n-2-1%n)[:n:-1] Try it online!

All of these also work in Python 2.

JavaScript, 28 bytes
f=n=>n-->2?f(n)+'1':n?121:21

Swift, 74 bytes
func r(i:Int)->String{return i>1 ?"CE"+(1..<i).map{_ in"C"}.joined():"EC"}

Try it online!

PHP, 103 Bytes
Try it online!
Code, recursive function
function f($n,$i=1,$s=''){if($i<$n){$s.="CE".str_repeat("C",$i)."
";f($n,$i+1,$s);}else{echo"EC
".$s;}}

Explanation
function f($n,$i=1,$s=''){
if($i<$n){                         #condition to get out, it counts to $n
    $s.="CE".str_repeat("C",$i)."  # "C" is repeated and concatenated
    ";f($n,$i+1,$s);               #note that "\n" = "(Enter key)"
}else{
    echo"EC                        #the first line "EC"
    ".$s;
}
}

Note that "\n" = "
", you save one byte
Output
f(5);
EC
CEC
CECC
CECCC
CECCCC

f(10);
EC
CEC
CECC
CECCC
CECCCC
CECCCCC
CECCCCCC
CECCCCCCC
CECCCCCCCC
CECCCCCCCCC

I think you only have to print the result for one line.

Jelly, 8 bytes
«2=‘R$;⁷

A full program printing the output with car lanes as 0 and the emergency lanes as 1.
Try it online!

Yabasic, 54 bytes
Input""n
If n>1Then?"C";Fi
?"E";
For i=1To n:?"C";Next

Try it online!

Excel VBA, 32 bytes
An anonymous VBE immediate window function that takes input from range [A1] and outputs to the VBE immediate window.
?[If(A1-1,10,"01")&Rept(1,A1-1)]
''  or
?[If(A1-1,10,0)&Rept(1,A1-A1<1)]

Fails on A1=1 - outputs 0 instead of 01

@Chronocidal why you are right, its been corrected

><>, 26 bytes
::?v~1)?o"!">o<
00.>1-"~"}

Watch it run !
Results :
1.     !~
2.     ~!~
3.     ~!~~
4.     ~!~~~
etc.

Perl 6, 20 bytes
{1%$_*10~1 x$_-1%$_}

Try it online!
Returns
1 => 01
2 => 101
3 => 1011
4 => 10111
5 => 101111

Another 20 byte solution with -p is $_=1 x$_;s/1?<(1/E1/ which is identical to Xcali's Perl 5 solution.

><>, 16 bytes
1-:?!v1$
n<}1{<>

Try it online!
Prints 0 as the corridor and 1 as the cars.

Befunge-98 (FBBI), 14 bytes
Uses 0 for cars, and 1 for the empty lane.
12&:b0p`j\' k.

Try it online!
This uses a & to end the program, stalling it until TIO shuts it off, instead of ending when it's finished. In order to avoid waiting, you can hit the run button again soon after it starts to end it prematurely and see the result it would give if it waited. In case ending like this is too iffy, here is a 15 byte solution that doesn't use this method:
12&:b0p`j\' k.@

Try it online!
Explanation
This program uses the implicit zeroes at the bottom of the stack to print the cars at the end. This way we can avoid pushing N - 1 things, and only use the input for printing N + 1 things and determining whether N is 1 or not.
(stack terminology is bottom [a, b, c] top)
12                Push 1 and 2. The stack is [1, 2]
  &:              Take input and duplicate. [1, 2, N, N]
    b0p           Put N at (0, 11), which is after the '
       `          Pops the top 2 and pushes 1 if a>b, 0 if not. [1, 2>N]
        j\        Jumps the \ if 2>N (i.e. N = 1), otherwise switches the top 2.
                      The stack is [1] if N=1, otherwise [1, 0]
          '       Takes in N again from the put instruction earlier
            k.    Prints out N+1 characters: (01 or 10 depending on N) + (N-1 0s).
12                Wraps and adds irrelevant things to the stack.
  &               Waits for TIO to end the program.

naz, 104 bytes
2x0v1a2x1v1x1f1o1s1o0x1x2f2x2v0m1o0m1a1f2v2s2x2v3f0x1x3f2v3x0v4e1s2x2v0m1o3f0x1x4f0a0x1x5f1r3x1v1e2f0x5f

There may be some byte saves I haven't immediately seen. I'm starting to be out of practice with my own language.
This program uses 1 for the emergency corridor and 0 for the cars, and accepts its input as a character code, which is allowed by meta consensus.
Due to integer constraints, this works for all N where 0 < N < 128. Use the -u flag to remove the constraints.
Explanation (with 0x commands removed)
2x0v                         # Set variable 0 equal to 0
1a2x1v                       # Set variable 1 equal to 1
1x1f                         # Function 1
    1o1s1o                   # Output, then subtract 1 and output again
1x2f                         # Function 2
    2x2v                     # Set variable 2 equal to the current register value
        0m1o0m1a1f           # Output "010" with the help of function 1
                  2v2s2x2v   # Subtract 2 from variable 2
                          3f # Call function 3
1x3f                         # Function 3
    2v3x0v4e                 # Goto function 4 if variable 2 is equal to variable 0 (0)
            1s2x2v           # Otherwise, subtract 1 from variable 2,
                  0m1o       # output 0,
                      3f     # and jump back to the start of function 3
1x4f                         # Function 4
    0a                       # Add 0 to the register
1x5f                         # Function 5
    1r                       # Read a byte of input
      3x1v1e                 # Goto function 1 if it equals variable 1
            2f               # Otherwise, call function 2
5f                           # Call function 5

Vyxal, 6 bytes
↵S$ċ[ǔ

Try it Online!

PHP, 35 bytes
<?=str_pad(1<$argn?CE:E,C,$argn+1);

Run as pipe with -n or try it online.

C# (.NET Core), 74 bytes
Additional bytes for using System; and int L
var S="0X";for(int I=1;I<L;I++)S+='0';System.Console.Write(L<2?"X0":S);

Try it online!

@JoKing thanks for the pointing. I think that I got it right now

You're still using L as a predefined variable, which is not allowed by default

Defining L as an int is not what I meant. Either your submission is a full program (which needs the boilerplate as well as taking input from an acceptable input) or a function that can take an int.

Pyt, 18 bytes
Đ1≤?ĉ01:ŕ01↔⁻⑴;áƑǰ

Try it online!
Uses 0 for the emergency lane and 1 for the normal lanes
Explanation
                          Implicit input (N)
Đ                         Duplicate N on the stack
 1≤                       Is N≤1
   ?   :       ;          If top of stack is non-zero, continue execution until reaching
                               colon, then jump to semicolon; otherwise, jump to colon
                               and continue executing
   ?                      - Then (i.e. i≤1)
    ĉ                     Clear the stack
     01                   Push 0 followed by 1

       :                  - Else branch (i.e. N≥2)
        ŕ                 Pop the top of the stack
         01               Push 0 followed by 1
           ↔              Flip the stack
            ⁻⑴           Decrement N and then push an array of N-1 1's
               ;          - End of if statement

                á         Push contents of stack to an array
                 Ƒ        Flatten the resulting array
                  ǰ       Join the contents of the array with no delimiters

Pushy, 10 bytes
1wEs{t?};Q

Try it online!
1             \ Push 1
 w            \ 'Mirror' the stack around the central item, yielding [n, 1, n]
  E           \ Pop 1 and n, and push 1 * 10 ** n
   s          \ Split into its digits
    {         \ Get input back on top of stack
     t?       \ If input > 1:
       };     \    Cyclically shift the stack right once
         Q    \ Collect all items on stack, interpret as indicies into uppercase alphabet,
              \ and print the resulting string.

Prints A for lanes and B for corridors.

ink, 55 33 55 bytes
=l(n)
~temp i=2
{n-1:C}EC<>
-(k){i<n:
~i++
C<>->k
}->->

Try it online!
Starts by printing C if input is not 1, then EC, then prints C another n-2 times.


text:
Join up the rooms
So, here's a map of, let's say, a dungeon...
##########
#    #####
#    #####
##########
##########
##########
##########
####    ##
####    ##
##########

Let's say that the hero is in Room A (at the top left) and their goal (a prince in distress?) is in Room B (to the bottom right). Our map does not allow the hero to progress to their goal.
We need to add a passageway...
##########
#    #####
#    #####
####.#####
####.#####
####.#####
####.#####
####    ##
####    ##
##########

There, much better!

Rules

A program or function which accepts a dungeon map (made up of hashes and spaces, with rows separated by new line characters).
It will output a map with dots added to denote passages in all spaces which are on a direct path between the space characters.
It will not change the line length, or number of lines.
Passages are all in a direct line from spaces to spaces.

Passages can not turn around corners
They will not be between spaces and the edge of the map.

Use any language.
Attempt to perform the conversion in the fewest bytes.
If no passageways can be drawn, return the map, unchanged.
The map should always have hashes around all edges (You do not need to handle spaces at the edge).
Input maps are always rectangular, each row should be the same width.

Test cases
####       ####
#  #   =>  #  #
#  #       #  #
####       ####

##########        ##########
#    #####        #    #####
#    #####        #    #####
##########        ####.#####
##########    =>  ####.#####
##########        ####.#####
##########        ####.#####
####    ##        ####    ##
####    ##        ####    ##
##########        ##########

##########        ##########
#    #####        #    #####
#    #####        #    #####
##########        ##########
##########    =>  ##########
##########        ##########
##########        ##########
######  ##        ######  ##
######  ##        ######  ##
##########        ##########

##########        ##########
#    #####        #    #####
#    #####        #    #####
##########        ####.#####
##########    =>  ####.#####
####   ###        ####   ###
##########        ######.###
######  ##        ######  ##
######  ##        ######  ##
##########        ##########

##########        ##########
#    #####        #    #####
#    #####        #    #####
##########        ##..######
##########    =>  ##..######
##########        ##..######
##########        ##..######
## #######        ## .######
##  ######        ##  ######
##########        ##########

##########        ##########
#    #####        #    #####
#    #####        #    #####
##########        #.########
##########    =>  #.########
##########        #.########
#######  #        #.#####  #
#######  #        #.#####  #
# #####  #        # .....  #
##########        ##########

##########        ##########
#    #####        #    #####
#    #####        #    #####
##########        #.########
#####  ###    =>  #.###  ###
#####  ###        #.###  ###
#######  #        #.#####  #
#######  #        #.#####  #
# #####  #        # .....  #
##########        ##########

##########        ##########
##       #        ##       #
##########        ##......##
##########        ##......##
##########    =>  ##......##
##########        ##......##
##########        ##......##
##########        ##......##
#       ##        #       ##
##########        ##########

##########        ##########
####  ####        ####  ####
####### ##        ####..# ##
###### ###        ####.. ###
# ### ## #    =>  # ... .. #
# ## ### #        # .. ... #
### ######        ### ..####
## #######        ## #..####
####  ####        ####  ####
##########        ##########

Can I use different characters than # and .?

@user202729 Nope. It was in the rules from the start, and there's already been one answer with it. Probably best to leave the reqs consistent.

@user202729 The test case you suggested is similar to my penultimate case. I might add it when i next change the question, but it doesn't add much.

... I just didn't scroll down. No problem.

@l4m2 Same rules apply, wherever there's a straight line between rooms, it's a passage. So a u-shaped room would have the gap filled in with passages.

"between rooms" may mean "should connect two different room", so i ask

@l4m2 Okay, that's the answer. It doesn't matter if it's a single room, if there's a straight line between parts of it.

Are the inputs always squares?

@recursive Not necessarily (although all my test cases are). I think they should have to be rectangular. I'll edit the question.

I think there's an issue with the second to last example. I think in the output there are extra # in the second column, specifically, (1,1) just shows up. Am I missing something?

Jelly, 17 bytes
ỴḲaLḊṖƊ¦”.KƊ€Z$⁺Y

Try it online!
Tricky -1 thanks to user202729.
Explanation:
ỴḲaLḊṖƊ¦”.KƊ€Z$⁺Y Arguments: S
Ỵ                 Split S on newlines
 ḲaLḊṖƊ¦”.KƊ€Z$   Monadic link
 ḲaLḊṖƊ¦”.KƊ€      Map over left argument
 ḲaLḊṖƊ¦”.KƊ        Monadic link
 Ḳ                   Split on spaces
  aLḊṖƊ¦”.           Dyadic link with right argument '.'
  aLḊṖƊ¦              Apply at specific indices
  a                    Logical AND (vectorizes)
   LḊṖƊ                Monadic link
   L                    Length
    Ḋ                   Range [2..n]
     Ṗ                  Remove last element
          K          Join with spaces
             Z     Zip
               ⁺  Previous link
                Y Join with newlines

It always amazes me how quickly people can meet these challenges, and in so few characters.

@AJFaraday Well, then you can be a part of it too. :) Just start with stack-based golfing languages (e.g. CJam, 05AB1E) and work your way from there.

It does seem a long way beyond me, to be honest, but I love seeing how the process works.

...we can continue the discussion over TNB if you want. ;)

Wait, is TNB short for 'tea and biscuits'? Or am I just being super-British right now?

@AJFaraday Our chat room, The Nineteenth Byte.

An explanation would be cool for this answer.

Explanation

The explanation looks like some kind of ASCII art (a tree? or fire?), it's beautiful. :P

Perl 5 -p0, 56 bytes
#!/usr/bin/perl -p0
/
/;$n="(.{@+})*";s%#%/ #*\G#+ |(?= )$n\G$n /s?".":$&%eg

Try it online!

APL+WIN, 87 bytes
Prompts for character matrix:
n←(' '=m←⎕)⋄c←(∨⍀n)+⊖∨⍀⊖n⋄r←(∨\n)+⌽∨\⌽n⋄((,c>1)/,m)←'.'⋄((,r>1)/,m)←'.'⋄((,n)/,m)←' '⋄m

Haskell, 209 165 162 bytes.
import Data.List
t=transpose
k=concat
j a=(foldr1 max<$>)<$>t<$>t[a,f<$>a,t$f<$>t a]
f b|(e:g:d@(h:_:_))<-group b=k[f$e++g,'.'<$h,drop(length h)$f$k d]|1>0=' '<$b

Try it online!
Not the most efficient way of doing it in Haskell I'm sure. It's got too many parentheses for my liking but I'm not sure how to remove any more.

Welcome to the site! You can reduce some of the parentheses by using $ ((k(take 2 c)) becomes (k$take 2 c)).  You can also use !!0 instead of head in some cases.

Actually in the particular case of (k(take 2 c)) you can just remove the outer parentheses, they are not needed.  But in the case of drop(length(head d)) you can still use the $, replacing it with drop(length$head d) (and even drop(length$d!!0)).

In addition if you use k instead of ++ you can greatly reduce the last line. k[' '<$k(take 2 c),'.'<$d!!0,drop(length$d!!0)$f$k$d].

One last golf, the last line can be replaced with f b|(e:g:d@(h:_:_))<-group b=k[' '<$e++g,'.'<$h,drop(length h)$f$k d]|1>0=' '<$b, this uses a pattern match to do a lot of the heavy lifting that was being done before.

Thanks for the heavy duty golfing @user56656! Ungolfed I had f as 2 functions and just pasted them together without optimizing them as a whole. That's a good thing to keep in mind.

I think you can also replace the use of ' '<$e++g with f$e++g, because it will fail the first match and move to the second.

Python 2, 173 148 bytes
m=input().split('\n')
exec"m=zip(*[[c*(c!='#')or'#.'[(' 'in r[i:])*(' 'in r[:i])]for i,c in enumerate(r)]for r in m]);"*2
for r in m:print''.join(r)

Try it online!

Retina 0.8.2, 95 bytes
+`(?<=(.)*)#(?=.*¶(?>(?<-1>.)*)[ .])
.
+`\.(?=(.)*)(?<![ .](?>(?<-1>.)*)¶.*)
#
 (\S+)
 $.1$*.

Try it online! Explanation:
+`(?<=(.)*)#(?=.*¶(?>(?<-1>.)*)[ .])
.

This looks for # signs that are above spaces or .s and turns them into dots until there are none left. The lookbehind finds the #'s column and then the lookahead skips to the next line and atomically to the same column below so that the space or . can only match if it's exactly below the #.
+`\.(?=(.)*)(?<![ .](?>(?<-1>.)*)¶.*)
#

This looks for .s that are not below spaces or .s and turns them back into #s until there are none left. The lookahead finds the .'s column and then the lookbehind skips to the previous line and atomically to the same column above in much the same way so that the space or . can only match if it's exactly above the #. A negative lookbehind is used so that this also works for .s in the top row.
 (\S+)
 $.1$*.

(Note trailing space on both lines) This simply looks for all runs of non-whitespace characters between spaces and ensures that they are all .s.

Ruby, 104 bytes
->s{2.times{s=((0...s=~/\n/).map{|i|s.lines.map{|b|b[i]}*""}*"\n").gsub(/ [#.]+(?= )/){$&.tr(?#,?.)}};s}

Try it online!
Well, it's not great, but at least it's convoluted. I'm sure it can be improved.

JavaScript (Node.js),205 193 190 186 181 175 172 bytes
r=>r.split`
`.map(x=>[...x]).map((R,y,r)=>R.map((c,x)=>{for(D=2;c<"#"&&D--;){for(;(T=(r[y+=D]||0)[x+=!D])>" ";);for(;r[y-=D][x-=!D]>c;)T?r[y][x]=".":0}})&&R.join``).join`
`

Try it online!
Commented
f=r=>r.split`
` ->                                     //getting as string with lines
.map(x=>[...x])                          //to 2d string array
  .map((R,y,r)=>                         //r - the new 2d string array
    R.map((c,x)=>{                       //
      for(D=2;c<"#"&&D--;)              //instead of using if joining c==" " with the loop,D=1/0
        {for(;                           //
         (T=(r[y+=D]||0)[x+=!D])>" ";);  //0[num] = undefined. checking for a path - consisting of # or .(or not consisting of space or undefined), we dont need temp (X,Y) because in the next loop we will return to our original position regardless of the correctness of the path
           for(;T&&r[y-=D][x-=!D]>c;)    //again instead of if(T) combine with loop. if T is not undefined it will be a space because the array can return .#(space). and we then go back to the source(x,y)
                                         //remeber that c==" "
             r[y][x]="."                 //and just putting . where weve been
     }})&&R.join``                       //instead of return r as string at the end , we know that we cant change a row at a smaller index(due to D-0/1) so we can return R.join`` already
    ).join`
`

Stax, 19 bytes
╛XA╟φkôα`æbπ┐w↨╙j≥☺

Run and debug it

I'm afraid your debug link shows blank code.

@AJFaraday: Which browser are you using?  It's working for me on Chrome for Windows.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Several bases but not twice the same digit
Input
A non-empty array of positive integers.
Task
Convert each integer to either binary, octal, decimal or hexadecimal in such a way that each digit (0 to F) is used at most once.
Output
The list of bases that were used to solve the puzzle.
Detailed example
The expected output for [ 16, 17 ] is [ octal, decimal ].
Here is why:

We can't simply use decimal for both numbers, because they both contains a 1.
16 cannot be converted to binary, because its representation in this base (10000) contains several 0's.
17 cannot be converted to binary either, because its representation in this base (10001) contains several 0's and  several 1's.
17 cannot be converted to hexadecimal, because its representation in this base (11) consists of two 1's.
Let's consider all remaining possibilities:
               +---------+---------+--------+
               | oct(16) | dec(16) | hex(16)|
               | = 20    | = 16    | = 10   |
+--------------+---------+---------+--------+
| oct(17) = 21 | 20,21   | 16,21   | 10,21  |
| dec(17) = 17 | 20,17   | 16,17   | 10,17  |
+--------------+---------+---------+--------+

The only possible solution is to convert 16 in octal (20) and to keep 17 in decimal (17). This way, the digits 0, 1, 2 and 7 are used exactly once.

Clarifications and rules

The input is guaranteed to lead to a unique solution. Your code is not supposed to support arrays that give several solutions or no solution at all.
You may output the bases in any reasonable format, such as [ "bin","oct","dec","hex" ], [ 'b','o','d','h' ], "BODH", [ 2,8,10,16 ], [ 0,1,2,3 ] etc. But it should be clearly explained in your answer.
The order of the bases in the output must match the order of the input integers.
If that helps, you may assume that the input is sorted from lowest to highest, or from highest to lowest.
This is code-golf, so the shortest answer in bytes wins!

Test cases
You do not have to output the conversion results listed below. They are purely informational.
Input                                  | Output          | Conversion result
---------------------------------------+-----------------+------------------------
[ 119 ]                                | O               | 167
[ 170 ]                                | D               | 170
[ 64222 ]                              | H               | FADE
[ 16, 17 ]                             | O/D             | 20/17
[ 14, 64, 96 ]                         | H/H/D           | E/40/96
[ 34, 37, 94 ]                         | O/D/H           | 42/37/5E
[ 2, 68, 82 ]                          | B/D/H           | 10/68/52
[ 22, 43, 96 ]                         | O/O/O           | 26/53/140
[ 3639, 19086, 57162 ]                 | H/D/H           | E37/19086/DF4A
[ 190, 229, 771 ]                      | O/H/O           | 276/E5/1403
[ 2, 44, 69, 99 ]                      | B/H/H/H         | 10/2C/45/63
[ 75, 207, 218, 357, 385 ]             | H/H/H/D/O       | 4B/CF/DA/357/601
[ 12, 28, 46, 78, 154, 188, 222, 240 ] | D/O/O/D/H/H/H/H | 12/34/56/78/9A/BC/DE/F0

The raw input list is available here.

should we care about some aspect of efficiency? (like if the array is of length 1000 or something like that)

@DanielIndie No, you don't have to. Besides, a puzzle of 1000 entries would include a lot of duplicate digits, no matter the bases that are used, so it can't possibly be a valid one. (This is guaranteed not to happen as per the first rule.)

yes, you are right... stupid me... :)

Really looking forward to a Japt solution, because I tried it out and couldn't find a good one.

Can we output the list of bases with each as a number in its own base? For example, for [16, 17]: [10, 10] (8 in octal, 10 in decimal)?

@Scrooble Nope. :) Nice try!

JavaScript (Node.js),192,155,154,152,151,145,136,113,99,92 90 bytes

thanks to @Arnauld for reminding me that i can return [0,1,2,3] -> which is [2,8,10,16] saves 8 bytes, and for the brilliant idea (which help to reduce by 23+ bytes)
thanks to @Kevin Cruijssen for reducing by 1 bytes

f=([c,...a],t="")=>c?[1,4,5,8].find(b=>T=!/(.).*\1/.test(n=t+c.toString(b*2))&&f(a,n))+T:a

Try it online!
Explanation:
[c,...a] - @Arnauld trick for taking one item at a time
c?***:" " ->if c is undefined we managed to get to the end result- [] - if i would put "" than the find would not considered that legit. ([]+5="5" JS FTW)
[1,4,5,8].find every time we find the correct base (the output will be of this array (1,4,5,8)->(2,8,10,16) its legit.
now how the find works -> if it finds something it returns the element (1-8)
and than i add the result of the inner solution. if it doesnt find then it returns undefined + T is now false -> NaN which in the parent call will be considered false
!/(.).*\1/.test(n=t+b) determine if the string has duplicates, if so:
f(a,n)) just go the the next number(a is now array.slice(1)) with the new string(n)
we assign result to T(temp) of the result because find stops when it finds and so we know that the last result will be f() which is result B

t="",B="" to t="",B=t would save a byte.

@KevinCruijssen updates the solution, thanks :) (and you to Arnauld)

@Arnauld i took your brilliant idea and did something similiar. look at the solution now

@Arnauld pure awesomeness

@Arnauld watch the new version :) managed to get to 92. i hope trailing spaces are allowed :)

Cool! Let's shave off 2 more bytes (and no need to trim() anymore).

Perl 5 -alp, 55 bytes
Uses %x for hex, %d for decimal, %o for octal and %b for binary
#!/usr/bin/perl -alp
($_)=grep{sprintf($_,@F)!~/(.).*\1/}glob"%{d,o,b,x}"x@F

Try it online!

Ruby, 72 71 bytes
->a{a.map{%w[b o d x]}.inject(&:product).find{|c|/(.).*\1/!~[p,c]*?%%a}}

Output format is some kind of reverse S-expression monstrosity:
f[[12, 28, 46, 78, 154, 188, 222, 240]]
=> [[[[[[["d", "o"], "o"], "d"], "x"], "x"], "x"], "x"]

Slash-separating it instead would cost 3 more bytes (appending *?/).
This format comes from the loop structure, slightly shorter than the more idiomatic repeated_combination(a.size), which generates an array of arrays of characters and then reduces it over the cross-product function.
Edit: Saved 1 byte thanks to Lynn.

Jelly, 17 16 bytes
⁴⁽%ʠḃṗL³bF⁼Q$ƲÐf

Try it online!
Return a list of bases.

 == Explanation ==
⁴⁽%ʠḃṗL³bF⁼Q$ƲÐf  Main link.
 ⁽%ʠ              A number.
    ḃ             convert it to bijective base...
⁴                   16. The result is [2,8,10,16].
     ṗL           Cartesian power by the input length.
             ƲÐf  Filter, keep those that satisfies...
       ³            the input
        b           convert to that base
         F          when flatten (join all the digits of \
                      different numbers together)
          ⁼Q$       equal to itself uniquified.

Pyth, 21 20 bytes
f{Is.bjYNTQ^[8T2y8)l

Returns a list of all possible lists of bases (which always has length 1).
Try it here
Explanation
f{Is.bjYNTQ^[8T2y8)l
           ^[8T2y8)lQ  Get the tuples of bases of the same length as the input.
f                      Filter to get those...
    .bjYNTQ            ... where converting bases elementwise...
   s                   ... and joining together...
 {I                    ... has no repeats.

Wolfram Language (Mathematica), 71 bytes
Cases[2{1,4,5,8}~Tuples~Tr[1^#],b_/;UnsameQ@@Join@@IntegerDigits[#,b]]&

Return a list of bases.
Try it online!

Python 2, 128 bytes
from itertools import*
a=input()
for b in product(*['bdxo']*len(a)):
 s=''.join(map(format,a,b))
 if len(s)==len(set(s)):print b

Try it online!

05AB1E, 17 bytes
2žv8T)sgãʒIsв˜DÙQ

Try it online!

I don't know 05AB1E, so perhaps I should wait until you've added an explanation before I ask this, but why is the result for 8 the character '8', and the other three an integer? +1 though, seems to work just fine, including the longer last test cases.

@KevinCruijssen That's coming from "2žv8T". Numbers in the source code are pushed as characters in 05AB1E, whereas žv (16) and T (10) are built-ins that pushes their respective numbers on the stack. This usually goes unnoticed because 05AB1E's implicit display of the last element in the stack converts to numbers, but since in this case the displayed result is an array of elements, those elements are left untouched, hence the quotes. The command ï for example can be used after ) to cast the two char elements to ints.

@KevinCruijssen Example of my explanation: https://tio.run/##MzBNTDJM/f/fyPbQDtv//wE
The code: push 2, print, wrap into an array, print.

Python 2, 121 117 113 111 bytes
def f(a,d='',s=''):
 if a:
	for c in'bodx':t=format(a[0],c)+s;len(t)-len(set(t))or f(a[1:],d+c,t)
 else:print d

Try it online!
Tip of the hat to Lynn for format, which I had forgotten!

Husk, 19 bytes
fȯS=UΣz`B¹πmDd1458L

Try it online!
Returns lists of bases
Explanation
fȯS=UΣz`B¹πmDd1458L  Implicit input
                  L  Length of input
          π          Cartesian power of
             d1458     The digits of 1458  [1,4,5,8]
           mD          Double the digits   [2,8,10,16]
fȯ                   Filter by
      z`B¹             Zip with input by converting to its base
     Σ                 Concatenate
  S=U                  Equal to itself with unique elements

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Yet another "draw a box" Question
The following problem is a common interview question, thus dull answers are discouraged. Go short or creative, best if both:
Create the following pattern
###########
##       ##
# #     # #
#  #   #  #
#   # #   #
#    #    #
#   # #   #
#  #   #  #
# #     # #
##       ##
###########

In case you cry "dupe",
 I see your point but this is a slight variation and I hope it differs enough to be greenlit.

Related, Related

I'm pretty sure I've seen an identical question but I can't find it now.

As this is just the output for the question linked by Angs when the input is 11, it is essentially a duplicate

@Angs why did you revoke your comment?!

@mbx When the question is closed as a duplicate the proposal comment is automatically removed.

@user56656 maybe not the best design decision in the first place - that comment was referenced by 2 other comments already

Hello, how can i add my solution?

@AliISSA The question was closed so no additional answers are allowed. You can answer this open question if you want.

I think I've mentioned it before, it surprises me how often the people who vote for a question to be closed as a duplicate have already answered the question, maybe gained rep for their answer then deny anyone else the chance to compete with them. No personal attack on anyone intended. I have the utmost respect for everyone here.  As I said it just surprises me that this is seen as "community friendly".

@ElPedro I'd say that's at least partly due to the fact that people who have just answered the question are both aware of the question and active on the site at the moment, and are thus more likely than other users to notice when a dupe target is proposed.

@ElPedro In addition, this question was VTC'ed by me and Angs well after Erik posted his Charcoal solution, and he hammered the question closed because he believes it is a duplicate. There would also be no need for him to delete his answer. If he's posted an answer, then immediately hammered it closed, then it's more of an issue.

Charcoal, 9 bytes
Ｐ¬↙×⁶#‖Ｏ¬

Try it online!

Never seen Charchoal before - Short Question: The linked possible dupe by Angs contains an 8 byte Charcoal solution which apparently does not work anymore. Any Ideas why?

@mbx The deverbosifier is buggy.

@EriktheOutgolfer :| crap

Canvas, 14 bytes
６#×：＼ω↷１１╋１１╋┼

Try it here!
uses an older version of Canvas as in the latest one I undid a thing I undid with a logical reason..

So you wrote your own language for that, nice!

@mbx creating golfing languages is fun :p Shorter solutions might appear though

@dzaima and one did :P

R, 92 bytes
write(c(" ","#")[1+!!`[<-`(`[<-`(diag(11)+diag(11)[11:1,],c(1,11),,1),,c(1,11),1)],1,11,,"")

Try it online!
That is...a lot of 1s.

Serves me right for coding a closed question. Used a sligthtly different indexing based approach for 86. Just pasting here for reference. ``[<-(matrix(" ",a<-11,a),c(n<-1:a,110+n,n*10+1,n*12-a,a*n-10,a*n),"#")

C (gcc), 129 122 bytes

Saved seven bytes thanks to ceilingcat.

*s;f(j,k){for(j=puts(s="###########")-2;--j;)printf("#%*c%*c%*c\n",k-(k==5),k-5?35:32,10-k-k,35,k=j>5?10-j:j,35);puts(s);}

Try it online!

Python 2, 100 bytes
for i in range(11):s=[" "]*11 if 0<i<10 else ["#"]*11;s[0]=s[10]=s[0+i]=s[10-i]="#";print ''.join(s)

Try it online!
Explanation :
for i in range(11):
  s=[" "]*11 if 0<i<10 else ["#"]*11;    #Ternary Expression to set cap lists
  s[0]=s[10]=s[0+i]=s[10-i]="#";    #Set '#'s in the right spots
  print ''.join(s)    #Convert to string and print

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Complement of a Regex
For the purposes of this challenge, we define a postfix regex dialect with alphabet {1, 0} and the following operations:

1 and 0 match themselves literally.
_ matches the empty string.
! always fails (i.e. it does not match anything).
ab; matches a, followed by b.
ab| matches both a and b.
a+ matches one or more instances of a.

The regex should always start matching from the start of the string, and stop matching at the end of a string (in other word, it is implicitly wrapped in ^$).
As an example, the following regex matches any string with an even number of 1s:
0+_|10+_|;10+_|;;+_|;

This is equivalent to the regex 0*(10*10*)*.
The following regex matches any nonempty string of ASCII letters, expressed in binary:
110|010|10|10|10|;;;;1010|10|10|;;;10010|;10;|;;|;|;;+

This is equivalent to the regex (1.(0....|1(0...|10(0.|10))))* (where . matches any character.
You can test regexes with this program.
The Challenge
Given a regex in the format described above, return a regex in this format that matches precisely those strings that are not matched by the input.
One potential method to do this would be to convert the regex into a nondeterministic finite automaton, then convert that into a deterministic finite automaton, flip which states are designated as accept states, and then convert it back to a regex.
Test Cases
format:
input   => potential output
           equivalent infix regex

0       => _101|+_|;|
           |1.*
1       => _001|+_|;|
           |0.*
_       => 01|+
           .+
!       => 01|+_|
           .*
01|+    => _

01|+_|  => !
           [] (empty character class)
1001;;; => _01|01|01|;01|01|01|;;001|01|01|01|+_|;;;;01|101|01|01|+_|;;;;01|01|101|01|+_|;;;;01|01|01|001|+_|;;;;|||||||
           |.|..|...|0....*|.1...*|..1..*|...0.*

But /0*(10*)*/ is not an regex for matching any string with an even number.

That regex should probably have been 0*(10*10*)*.

Your first two test cases seem wrong. The outputs should also match strings which aren't of length 1.

Related

How should a regex that contains ! behave? Always fail?

@MartinEnder I think that the first test case should be 001|+_|;101|+;|_| and the second should be 101|+_|;001|+;|_|.

@MartinEnder I think it's fixed now.

@EriktheOutgolfer Force backtracking or trying the alternative to a case. It's like JavaScript's [] that always fails.

I'd like to put a bounty on this, but I don't feel the test cases are sufficient and don't know enough regex to generate nontrivial ones that are still computationally feasible. Could you add a few?

@lirtosiast The test cases aren't that useful anyway, because they were hand-written and probably don't reflect what an answer to this challenge would output given the provided inputs. I have included a program to test regexes on strings, though.

For anyone interested, someone on the internet solved this problem in Prolog, with nice explanation for each step involved: https://john-h-kastner.github.io/regex-complement-prolog/

Dyalog APL, 166 bytes
{l←!!5*≢⍵⋄z←⊂''⋄n←,∘.,⍨⋄k←{⊃,/n\l/⊂⍵}⋄f←{⊃⊃{⍺∊';|':(2↓⍵),⍨⍺{';'=⍺:n/⍵⋄,/⍵}2↑⍵⋄⍺='_':⍵,⍨⊂z⋄'+'=⍺:⊂∘k∘⊃@1,⍵⋄⍺,⍵}/⌽1,⍵}⋄w←f⍵⋄⊃q/⍨{0=≢((z,k'01')~w∪f⍵)∪w∩f⍵}¨q←k'10!_|;+'}

The solution is a function that works by brute-forcing. It cannot be run in reasonable time nor with reasonable memory on any of the inputs, so no TIO link is provided; this is due to looping over every possible regex over the factorial of the factorial of 5 to the power of the input length. Note that the numbers involved go out of Dyalog's maximum number size for an input regex of length greater than 1. To test this, take a look at the function f, which returns a value that includes all matches less than the calculated upper bound l, and test it on the complementarity check {0=≢ ... ⍵∩f⍵}. Using smaller values of l can make the function provide wrong results, so note that before reducing its value.

There is an upper bound for the minimum length of the complementary regex as a function of the length of the input regex, and an upper bound for the length of the longest string the two regexes need to be tested against to determine their complementarity. These parameters are used to brute force the complementary regex, by comparing the strings accepted by the input regex and the regex being tested for complementarity.
We start by comparing the length of a regular expression to the number of states of its respective DFA.
The non-deterministic finite automaton (NFA) for the regex 1 is the following (using (Sn) to denote accepting states)
   1
Si-->(Sf)

The regex _ representing an \$\epsilon\$-transition can be represented by an NFA that has less than 2 states, as can the regex ! representing non-acceptance.
 _

(Si)

 !

Si

Thus, a regex with only characters from 01_! with length n will have an NFA with max size n+1.
The regex ab;, where a and b are sub-regexes, denotes the concatenation of a and b and can be described as the following. (Si# denotes an initial state and (S##) denotes a final state.)
  Si1-->...-->(Sf1)   Si2-->...-->(Sf2)    ;

                     ε
NFA= Si1-->...-->Sf1-->Si2-->...-->(Sf2)

The regex a+ denotes one or more occurrences of a.
  Si1-->...-->(Sf1)   +

            ε
      +------------+
      v            |
NFA= Si1-->...-->(Sf1)

This produces an NFA with the same size as that of a. Again, a regex with only characters from 01_!; with length n will have an NFA with max size n+1.
The regex ab| denotes an alternative of either a or b.
  Si1-->...-->(Sf1)   |   Si2-->...-->(Sf2)

      Si1-->...-->(Sf1)
NFA=
      Si2-->...-->(Sf2)

Both Si1 and Si2 are starting states in the above NFA. This does not fit the traditional definition of an NFA, where an NFA has only 1 starting state, but the size of the resulting deterministic finite automaton (DFA) does not increase. If needed, the NFA for + can be changed so that there is an ε-transition from the final state to the second state, and the NFAs for _ and ! changed to have 2 states each, so that a traditional NFA can be constructed for alternation with ε-transitions between Si1 and Si2.
An NFA resulting from alternation will be as large as the sum of the two sub-regexes that make it up. A regex of length n will have an NFA with a maximum size of n+1.
By the powerset construction, an NFA with size \$n\$ will result in a DFA with size \$2^n\$. So a regex of length \$n\$ will have a minimal DFA upper-bounded by \$2^{n+1}\$. A DFA can be inverted by simply switching the final and non-final states, so its complement will have the same number of states as itself.
With this information, we need an upper limit on the size of the complementary regex as a function of the length of the number of states of the DFA. To do this, I use an algorithm to convert a DFA to a regex; the idea is to represent every possible path from Si to any other state, as well as accounting for loops by tracking every loop that starts and ends at Si, in a recursive manner. For every state that can be reached in 1 step from Si, the process is repeated and a path is constructed from this new state to every other state except the states that have already been encountered, i.e. Si in the first iteration, since loops back to Si would already be covered by tracking loops. An example of the construction can make this clearer.
0<c0>;1<c1>;|+_|
0<r0>;1<r1>;<a>||
;

This is a regex that represents a DFA that I will call the "base form". The base form for a state is a regex that traverses paths from that state to every state in the DFA except for, as we will see, states that have been explicitly excluded for a particular iteration. The accept/reject status of each path is denoted by <a>, being _ for accept or ! for reject. The second line of the regex accounts for this "breadth-first" filling, by transitioning to states that are 1 step way, and recursing the base form (as represented by <r0> and <r1>) on those states. Each time we recurse, we exclude the original "parent" state from the graph traversal to prevent the algorithm from infinitely looping. Loops in the regex are tracked in the first line, where, also, every possible path is traversed, halting when reaching the parent state, but these sub-regexes, as denoted by <c0> and <c1>, consider only the parent state to be the accepting state.
At each level of recursion, the number of excluded states increases by 1, until every possible state is covered at which point the algorithm ends.
The base form, without the recursive parts, is of length 16. Each iteration spawn 4 new sub-regexes, and there are as many iterations as states in the DFA.
If a DFA has n states, an upper bound for the regex length is \$16 + 16×4 + 16×4×4 + ... + 16×4^{n-1}\$. This is a geometric series and can also be written as
$$\frac{16}{3}\left(4^n-1\right)$$
Now given a regex with length s, the length of its complement is bounded by
$$h=\frac{16}{3}\left(4^{2^{n+1}}-1\right)$$
(I felt that this upper bound could be improved to a mere exponential instead of a double exponential, potentially saving some bytes, but I was proven wrong by this answer.)
We can check if two regexes are equivalent by brute force, but to do that we need to know the upper limit of the input length to test. If the DFAs of the two regexes are a and b, we can construct another DFA c whose states are the Cartesian product of the states of a and b, so each state of DFA c can be labeled as a 2-tuple (a_j,b_k) where a_j and b_k are states of DFA a and b respectively. The transition of DFA c's state (a_j,b_k) under input letter l is the tuple of the transition of each state a_j and b_k in DFAs a and b respectively under letter l. The final states of DFA c are all the states (a_j,b_k) where either both a_j and b_k are final states or they are both non-final states. DFA c accepts a word if both DFAs a and b accept this word, i.e. DFAs a and b do not yield complementary results on this word. DFAs a and b are complementary iff DFA c does not accept any word. By the pumping lemma, to check for this, we only need to check of input word sizes up to the number of states of DFA c, minus 1.
The size of the DFA of the complementary regex is 2^(h+1) and that of the input regex is 2^(n+1). Thus we only need to check for input lengths up to 2^(h+1)×2^(n+1)-1.
$$2^{\frac{16}{3}\left(4^{2^{n+1}}-1\right)+1+n+1}-1$$
We need to find a golfy way to write a function that is always greater than the triple exponential above for n≥1. Factorials grow faster than exponentials and are 1 byte shorter and so can be useful. However, the factorial of 1 is still 1, so we cannot simply chain 3 factorials together. The first function can instead be an exponential b*n, APL for b to the power of n, after which two factorials can be added in place of the remaining double exponential, yielding !!b*n. \$b=3\$ is too small for the base case of n=1, \$b=4\$ is slightly smaller, but \$b=5\$ goes above the function.
$$l=(5^{≢\omega}!)!$$
This gives the first statement of the APL code, l←!!5*≢⍵ assign to the variable l the factorial ! of the factorial ! of 5 to the power of * the length ≢ of ⍵ the right argument.
The submission
{l←!!5*≢⍵⋄z←⊂''⋄n←,∘.,⍨⋄k←{⊃,/n\l/⊂⍵}⋄f←{⊃⊃{⍺∊';|':(2↓⍵),⍨⍺{';'=⍺:n/⍵⋄,/⍵}2↑⍵⋄⍺='_':⍵,⍨⊂z⋄'+'=⍺:⊂∘k∘⊃@1,⍵⋄⍺,⍵}/⌽1,⍵}⋄w←f⍵⋄⊃q/⍨{0=≢((z,k'01')~w∪f⍵)∪w∩f⍵}¨q←k'10!_|;+'}

The regex is parsed and its matches returned by the function f. It works on the reversed regex, and 'fold'ing ('reducing' in APL-speak) over it. It returns all matches of a regex, with the special case of the regex a+ only returning up to the first l repetitions of sub-regex a, thus keeping the list of matches finite. By having this behaviour of +, all input matches up to a length of l are included in the result of f, i.e. nothing less than what is needed to test for complementarity. APL reduces from right to left, due to order of operations being from right to left. Each intermediate results of the reduce is formed by the matches of each sub-regex encountered thus far. For the initial case, a 1 is prepended to the regex before reversing it, after which the reduce operation is applied.
f←{⊃⊃{⍺∊';|':(2↓⍵),⍨⍺{';'=⍺:n/⍵⋄,/⍵}2↑⍵⋄⍺='_':⍵,⍨⊂z⋄'+'=⍺:⊂∘k∘⊃@1,⍵⋄⍺,⍵}/⌽1,⍵}

The right argument ⍵ contains the matches of each sub-regex encountered so far. The left argument ⍺ is the next character of the regex that is being processed. Each case of the regex character is checked using = equality or ∊ belongs-to when multiple cases can be joined into 1.
Of particular note, ! in the regex is treated the same as 0 or 1, resulting in a match of the character !. Due to how the regexes are checked for complementarity, this works fine. Its exact mechanism is ⍺,⍵, concatenate ⍺, a single character being either of 0, 1, or !, with ⍵.
_ matches the empty string, z in the APL code refers to z←⊂'' present earlier in the entire submission; ⍵,⍨⊂z the enclosed empty string, i.e. signifying that only the empty string is being matched, is prepended to ⍵.
The mechanism of + is dependent on the function k←{⊃,/n\l/⊂⍵}, which given a list of strings ⍵, performs the Cartesian concatenation (Cartesian product, but using concatenation instead of set union) of l copies of ⍵, where the Cartesian concatenation is defined earlier as n←,∘.,⍨. This is achieved using the @ operator, applying the function ⊂∘k∘⊃ on the list of matches at index 1, the ⊂ enclose and ⊃ pick functions are required due to the behaviour of @.
Concatenation and alternation are considered together. On 2↑⍵ the list of the first two elements of ⍵, n/ (reduce by n Cartesian concatenation) is applied in the case of concatenation, and ,/ (reduce by concatenation). The remaining ⍵ is concatenated at the end of this result.
After the execution of the reduce operation, its first set of matches is retrieved using ⊃.
The regex does not give errors even on incorrect regexes. The handling of + uses the @ operator which expects the argument to be indexable. When + is by itself, ⍵ is the scalar 1, so @ on 1 would not work, but the , applied on ⍵ converts it into a list, preventing an error. + then takes the Cartesian concatenation of 1 with l copies of itself.
; and | with too few arguments are implicitly handled by the functionality of the ↑ take function and the ↓ function. 2↑ takes the first 2 elements of the right argument, but if the right argument is shorter, the result is padded with sufficient prototype values, for example the prototype of a strictly numeric array is 0, while that of a character array is the space character ' '.
However, even with this treating of anomalous regexes, these regexes will not be returned by the entire complementary regex function as a complementary regex. This is due to the fact that they cannot be shorter than the respective shortest valid postfix regex, and even if these incorrect regexes are of the same length as the shortest valid regex, they are ordered lexicographically later than a valid regex, with the order being specified later while performing the complementarity check by 10!_|;+, and only the first (again, ordered lexicographically) complementary regex is picked as a result to the function submission.
Complementarity check
The checking for complementarity is done by the following part. q←k'10!_|;+' generates all possible regexes up to a length of l (k computes this function as mentioned earlier) and assigns this to q. The ordering specified by this part is what prevents incorrect regexes from being returned by the function.
For each of these strings ¨, the following function is computed, (⍵ denotes the right argument, in this case, each string for which the following function is applied on)
{0=≢((z,k'01')~w∪f⍵)∪w∩f⍵}

w is assigned earlier to the matches of the input regex. w∩f⍵ computes the intersection of w, the matches of the input, with f⍵, the matches of ⍵. For complementary regexes, this should be the empty set.
w∪f⍵ computes the union of w and f⍵. ~ performs set complement. z is ⊂'', the enclosed empty string. k'01' computes all binary strings with length up ≤ l, so z,k'01' is a list containing all these binary strings, along with the empty string.
The result of (z,k'01')~w∪f⍵ is all the binary strings that are not present in w∪f⍵, so it contains the strings that are matches by neither the input regex nor ⍵. For complementary regexes this should be the empty set.
((z,k'01')~w∪f⍵)∪w∩f⍵ is the union of the two sets above. This should be empty if the regexes are complementary. Its emptiness is checked by counting the number of elements contained within it using ≢, and comparing this result with 0. (Using ⍬ doesn't work because in Dyalog APL, empty lists can have different prototype lists.)
This function explained above returns 1 is the regexes are complementary, and 0 if they are not. The first truthy regex is picked by ⊃q/⍨, being returned by the function.
Alternative approaches
Initially, I thought that using the approach recommended in the challenge of doing the conversion regex → NFA → DFA → regex would yield a short solution in APL because of APL's strength with matrices (by storing the NFA/DFA as a 3-dimensional array, with each of its 2-dimensional arrays being adjacency matrices for transitions involving each input character and ε-transitions). I got to implement a part of this for the regex matching challenge that popped up recently, but I got a solution much longer than what I had expected at over 250 bytes. It's the handling of individual matrix entries that made the program long, for example, I had to include specific transitions between specific states, like an ε-transition from state 1 to states 2 and 3 for alternation. However the handling of the entire array or its component matrices was short, as was needed to execute the NFA on the input string. And besides, all that the >250 byte program did was only to determine if 1 string matches the input regex. Maybe storing the NFA in a "sparse" format with list of lists of numbers representing states might end up being shorter that the matrix-oriented approach.
I tried another approach to that regex matching challenge by listing all the matches of the input regex, with + repetitions bounded by the input length, and checking if the input string belongs to this list, which yielded a >140-byter, almost half the length of my previous approach. This approach ended up being adapted into function f of my submission to this challenge. Unlike the approach mentioned in the previous paragraph, this approach generates the list of all input matches, so I do not have to separately run the regex matching function on each of the possible inputs to see which ones it matches, thus saving a great deal of bytes.
Moreover, I had also tried ⎕r, Dyalog APL's PCRE replace function, for this challenge but that resulted in a postfix → PCRE converter at >110 bytes. Besides, similarly to the approach where I stored the NFA in an array, implementing the matching as well as finding all of the matches of this regex on all (bounded) input strings added too many bytes.
It was when I stumbled upon ankh-morpork's Prolog submission to the regex decomposition challenge and by the power of Prolog DCGs that I started working on this regex complement challenge in Prolog. However my Prolog skills was not good enough to make it work, and seeing how my approach ended up becoming un-Prolog-y and more APL-y I switched to APL and started this solution with the knowledge I had gathered from attempting the regex matching challenge. This brute-force approach proved to be significantly short than any other approach I could think of, so I went ahead with this. I left the calculation of the upper bound to the very end, i.e. the l← bit, and golfed the rest of my program from an initial size of >210 bytes.
The complementary check might be further golfable, perhaps there's a nice way to get rid of the parentheses, or an alternative logic. In function f, under the case when ⍺∊';|', I feel the 2↑⍵ and 2↓⍵ surrounding the code has a shorter alternative; I tried @1 2⊢⍵, but this results in an error for invalid regexes requiring me to use an error guard.

I never got around to golfing it, but here's regex complement implemented in Prolog

Python 2, 1996 1960 bytes
lambda s:L(J(I(s)))
_=set;Z=sorted;x,y,z={0},{1},{2}
A=lambda a,b,c:{e for d in b for e in a[c][d]}
def B(a,b):b=_(b);c=b|A(a,b,2);return B(a,c)if b<c else c
C=lambda a,b:any(c in a for c in b)
def D(a):
 b,c,d,e=a;f=_();g=tuple(Z(B(e,{c})));h=_();i={0:{},1:{},2:{}};j=[g]
 while j:
  l=j.pop()
  if l in f:continue
  f.add(l);C(d,l)and h.add(l)
  for k in i:i[k][l]=_()
  for k in[0,1]:m=tuple(Z(B(e,A(e,l,k))));j.append(m);i[k][l].add(m)
 return f,g,h,i
def E(b,a):c,d,e,f=b;return{(a,g)for g in c},(a,d),{(a,g)for g in e},{k:{(a,g):{(a,h)for h in f[k][g]}for g in f[k]}for k in f}
def F(a,b):c,d,e,f=E(a,0);g,h,i,j=E(b,1);l=f.copy();[l[k].update(j[k])for k in l];[l[2][m].add(h)for m in e];return c|g,d,i,l
def G(a,b):c,d,e,f=E(a,0);g,h,i,j=E(b,1);l=f.copy();[l[k].update(j[k])or l[k].update({0:_(),1:_()})for k in l];l[2][0]|={d,h};[l[2][m].add(1)for m in e|i];return c|g|x|y,0,y,l
def H(a):b,c,d,e=a;f=_(d);g={k:e[k].copy()for k in e};[g[2][h].add(c)for h in f];return _(b),c,f,g
def I(s):
 a=[]
 for c in s:
  if c in'10_!':a.append({'1':(x|y|z,0,y,{0:{0:z,1:z,2:z},1:{0:y,1:z,2:z},2:{0:_(),1:_(),2:_()}}),'0':(x|y|z,0,y,{0:{0:y,1:z,2:z},1:{0:z,1:z,2:z},2:{0:_(),1:_(),2:_()}}),'_':(x|y,0,x,{0:{0:y,1:y},1:{0:y,1:y},2:{0:_(),1:_()}}),'!':(x,0,_(),{0:{0:x},1:{0:x},2:{0:_()}})}[c])
  elif c in'|;':a[-2:]=[{'|':G,';':F}[c](a[-2],a[-1])]
  else:a[-1]=H(a[-1])
 return D(a[-1])
def J(a):b,c,d,e=a;f={};[f.update({(g,h):f.get((g,h),'!')+str(k)+'|'})for k in e for g in e[k]for h in e[k][g]];return b,c,b-d,f
def K(a,b,c,d):
 for e in a-{c,d}:
  g={f:b[(f,t)]for f,t in b if t==e!=f};h={t:b[(f,t)]for f,t in b if f==e!=t};i={(f,t):b[(f,t)]for f,t in b if f!=e!=t}
  for f in g:
   for t in h:j=i.get((f,t),'!');i[(f,t)]=g[f]+b.get((e,e),'!')+'+_|;'+h[t]+';'+j+'|'
  b=i
 l,m,n,o=[b.get(pair,'!')for pair in[(c,c),(c,d),(d,d),(d,c)]];return l+'+_|'+(m+';'+o+l+'+_|;'+m+';'+n+'|+_|;')*(c!=d)
def L(a):b,c,d,e=a;return''.join(K(b,e,c,f)for f in d)+'!'+'|'*len(d)

Try it online!
Since user41805 came up with a very short but only theoretically-working solution, here is a practical one (practical as in "you can actually observe the output for small inputs"). The TIO link also includes a kind of test-battery to check for complement-ness.
It should be theoretically possible to solve Complement of POSIX ERE by reusing large chunks of code here, but I don't think I'll tackle it anytime soon. Feel free to solve it and take the 200 bounty.
Ungolfed, and how it works
The code is mainly divided into three parts: construct an NFA from the input regex, convert it to a DFA and invert its accept states, and convert it back to a regex.
Preliminary definitions
from collections import namedtuple

NFA = namedtuple('NFA', ['nodes', 'start', 'accept', 'trans'])
DFA = namedtuple('DFA', ['nodes', 'start', 'accept', 'trans'])

The definitions for NFA and DFA are there just to help reading the code. NFA and DFA have the same field names, but the trans fields contain different data structures.
Input regex to NFA
def step_once(trans, nodes_from, step):
    return {n for x in nodes_from for n in trans[step][x]}

def e_closure(trans, nodes_from):
    nodes_from = set(nodes_from)
    nodes_to = nodes_from | step_once(trans, nodes_from, '')
    while nodes_from != nodes_to:
        nodes_from = nodes_to
        nodes_to = nodes_from | step_once(trans, nodes_from, '')
    return nodes_to

def is_accept(accept, nodes):
    return any(node in accept for node in nodes)

def to_dfa(nfa):
    new_nodes = set()
    new_start = tuple(sorted(e_closure(nfa.trans, {nfa.start})))
    new_accept = set()
    new_trans = {0:{}, 1:{}, '':{}}
    stack = [new_start]
    while stack:
        node_set = stack.pop()
        if node_set in new_nodes: continue
        new_nodes.add(node_set)
        if is_accept(nfa.accept, node_set): new_accept.add(node_set)
        for k in new_trans: new_trans[k][node_set] = set()
        for k in [0, 1]:
            node_step = e_closure(nfa.trans, step_once(nfa.trans, node_set, k))
            node_step = tuple(sorted(node_step))
            stack.append(node_step)
            new_trans[k][node_set].add(node_step)
    return NFA(new_nodes, new_start, new_accept, new_trans)

to_dfa eliminates ϵ-moves and non-deterministic moves from the given ϵ-NFA. The algorithm is pretty standard: starting from the ϵ-closure of the start state, record all the reachable state sets by traversing through 0- and 1-moves followed by ϵ-closure.
one = NFA({0,1,2}, 0, {1}, {
    0: {0:{2}, 1:{2}, 2:{2}},
    1: {0:{1}, 1:{2}, 2:{2}},
    '': {0:set(), 1:set(), 2:set()}
})

zero = NFA({0,1,2}, 0, {1}, {
    0: {0:{1}, 1:{2}, 2:{2}},
    1: {0:{2}, 1:{2}, 2:{2}},
    '': {0:set(), 1:set(), 2:set()}
})

empty = NFA({0,1}, 0, {0}, {
    0: {0:{1}, 1:{1}},
    1: {0:{1}, 1:{1}},
    '': {0:set(), 1:set()}
})

null = NFA({0}, 0, set(), {
    0: {0:{0}},
    1: {0:{0}},
    '': {0:set()}
})

The NFA definitions for the four base regexes 10_! respectively.
def prefix(nfa, a):
    new_nodes = {(a,node) for node in nfa.nodes}
    new_start = (a,nfa.start)
    new_accept = {(a,node) for node in nfa.accept}
    new_trans = {k: {(a,node): {(a,dest) for dest in nfa.trans[k][node]} for node in nfa.trans[k]} for k in nfa.trans}
    return NFA(new_nodes, new_start, new_accept, new_trans)

prefix helper function converts an NFA into an equivalent one, but with each node key n wrapped into a 2-tuple (a,n). This is used for combining two NFAs to avoid key collisions. In Python, a tuple is hashable whenever all of its elements are hashable (thus appropriate for a dict key).
def concat(a, b):
    a = prefix(a, 0)
    b = prefix(b, 1)
    new_nodes = a.nodes | b.nodes
    new_start = a.start
    new_accept = b.accept
    new_trans = a.trans.copy()
    for k in new_trans: new_trans[k].update(b.trans[k])
    for a_acc in a.accept: new_trans[''][a_acc].add(b.start)
    return NFA(new_nodes, new_start, new_accept, new_trans)

def branch(a, b):
    a = prefix(a, 0)
    b = prefix(b, 1)
    new_nodes = a.nodes | b.nodes | {0, 1}
    new_start = 0
    new_accept = {1}
    new_trans = a.trans.copy()
    for k in new_trans: new_trans[k].update(b.trans[k]); new_trans[k].update({0:set(), 1:set()})
    new_trans[''][0] |= {a.start, b.start}
    for acc in a.accept | b.accept: new_trans[''][acc].add(1)
    return NFA(new_nodes, new_start, new_accept, new_trans)

def plus(nfa):
    new_nodes = set(nfa.nodes)
    new_start = nfa.start
    new_accept = set(nfa.accept)
    new_trans = {k: nfa.trans[k].copy() for k in nfa.trans}
    for acc in new_accept: new_trans[''][acc].add(new_start)
    return NFA(new_nodes, new_start, new_accept, new_trans)

Three combiner functions corresponding to ab;, ab|, a+ respectively.
ab;: Connect the accept states of a to the start state of b through ϵ-moves.
            e
S1 ... A1 -----> S2 ... A2

ab|: Introduce the overall start and accept states, and connect them through ϵ-moves like the following.
     e                e
   -----> S1 ... A1 ----->
S {                       } A
   -----> S2 ... A2 ----->
     e                e

a+: Connect the accept states back to the start states through ϵ-moves.
S ... A
|     |
\<----/
   e

Finally, we combine all of them to convert the input regex into a deterministic NFA.
def input_to_nfa(s):
    stack = []
    for c in s:
        if c == '1': stack.append(one)
        elif c == '0': stack.append(zero)
        elif c == '_': stack.append(empty)
        elif c == '!': stack.append(null)
        elif c == '|': stack[-2:] = [branch(stack[-2], stack[-1])]
        elif c == ';': stack[-2:] = [concat(stack[-2], stack[-1])]
        elif c == '+': stack[-1] = plus(stack[-1])
    return to_dfa(stack[-1])

NFA to DFA
def nfa_to_dfa(nfa):
    nodes = nfa.nodes
    start = nfa.start
    accept = nfa.nodes - nfa.accept
    trans = {}
    for k in nfa.trans:
        for node_from in nfa.trans[k]:
            for node_to in nfa.trans[k][node_from]:
                trans[(node_from, node_to)] = trans.get((node_from, node_to), '!') + str(k) + '|'
    return DFA(nodes, start, accept, trans)

Invert the accept states by set difference, and convert the data structure of the transition table so that it is suitable for regex construction.
DFA to regex
# dfa-style trans
def path_to_regex(nodes, trans, node_from, node_to):
    for node in nodes - {node_from, node_to}:
        left_nodes = {f: trans[(f,t)] for f,t in trans if t == node != f}
        right_nodes = {t: trans[(f,t)] for f,t in trans if f == node != t}
        loop = trans.get((node, node), '!')
        new_trans = {(f, t): trans[(f,t)] for f,t in trans if f != node != t}
        for f in left_nodes:
            for t in right_nodes:
                existing = new_trans.get((f, t), '!')
                new_trans[(f,t)] = left_nodes[f] + loop + '+_|;' + right_nodes[t] + ';' + existing + '|'
        trans = new_trans
    ff, ft, tt, tf = [trans.get(pair, '!') for pair in [(node_from, node_from), (node_from, node_to), (node_to, node_to), (node_to, node_from)]]
    if node_from == node_to: return ff + '+_|'
    return ff + '+_|' + ft + ';' + tf + ff + '+_|;' + ft + ';' + tt + '|+_|;'

def dfa_to_regex(dfa):
    regexes = [path_to_regex(dfa.nodes, dfa.trans, dfa.start, acc) for acc in dfa.accept]
    if not regexes: return '!'
    return ''.join(regexes) + '|' * (len(regexes) - 1)

For each pair of start -> accept states, eliminate all the other states by regex chaining and convert the result into a single regex. If we have multiple accept states, link the resulting regexes by |. If we have zero accept states, return a single '!'.
def solution(s):
    return dfa_to_regex(nfa_to_dfa(input_to_nfa(s)))

Solves the entire task by chaining the three core functions.

Would creating another variable for {2}, and likewise for {1}, work for fewer bytes?

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/