text:
Multiplicity Test
Use any programming language to display numbers between 1 and 99 (including both) in such a way, so that:

the numbers are separated by single space,
if a number is divisible by 3, it should be in parentheses,
if a number is divisible by 4, it should be in square brackets,
if a number is divisible by both 3 and 4, it should be in both parentheses and square brackets (with square brackets closer to the number).

Your program should display exactly:
1 2 (3) [4] 5 (6) 7 [8] (9) 10 11 ([12]) 13 14 (15) [16] 17 (18) 19 [20] (21) 22 23 ([24]) 25 26 (27) [28] 29 (30) 31 [32] (33) 34 35 ([36]) 37 38 (39) [40] 41 (42) 43 [44] (45) 46 47 ([48]) 49 50 (51) [52] 53 (54) 55 [56] (57) 58 59 ([60]) 61 62 (63) [64] 65 (66) 67 [68] (69) 70 71 ([72]) 73 74 (75) [76] 77 (78) 79 [80] (81) 82 83 ([84]) 85 86 (87) [88] 89 (90) 91 [92] (93) 94 95 ([96]) 97 98 (99)

Related

Can we output each entry on a new line, or must the output be all on one line?

Can the output end with a space. A few answers seem to assume so.

05AB1E, 23 bytes
-1 byte thanks to Kevin Cruijssen
тGND4Öi…[ÿ]}N3Öi…(ÿ)]ðý

Try it online!

-1 byte by changing }?ð? to ]ðý (close both the if and loop, and join the entire stack by spaces)

@KevinCruijssen Thanks, that was exactly what I was looking for!

-1 by using Å€

Python 2, 68 65 60 bytes
i=0
exec"i+=1;print'('[i%3:]+`[i][i%4:]or i`+')'[i%3:],;"*99

Try it online!

I was right :) +1

R, 61 bytes
"+"=c
r=""+""
cat(paste0(r+"(",r+""+"[",1:99,r+""+"]",r+")"))

Try it online!

brilliant aliasing!

How does this even work? That's amazing! +1 to you my friend

Jelly, 21 20 bytes
³Ṗµ3,4ṚƬḍ×“([“])”j)K

Try it online!
How it works
³Ṗµ3,4ṚƬḍ×“([“])”j)K  Main link. No arguments.

³                     Set the return value to 100.
 Ṗ                    Pop; yield [1, ..., 99].
  µ               )   Map the chain in between over [1, ..., 9]; for each integer k:
   3,4                    Set the return value to [3, 4].
      ṚƬ                  Reverse until a loop is reached. Yields [[3, 4], [4, 3]].
        ḍ                 Test k for divisibility by [[3, 4], [4, 3]], yielding a
                          matrix of Booleans.
         ×“([“])”         Repeat the characters of [['(', '['], [']', ')']] as many
                          times as the Booleans indicate.
                 j        Join the resulting pair of strings, separated by k.
                   K  Join the resulting array of strings, separated by spaces.

C, C++, 136 133 131 129 128 124 bytes
-5 bytes thanks to Zacharý and inspired by write() function in D language ( see Zacharý answer )
-2 bytes thanks to mriklojn
-12 bytes for the C version thanks to mriklojn
-4 bytes thanks to ceilingcat
#include<cstdio>
void f(){for(int i=0;i++<99;)printf("(%s%d%s%s%s"+!!(i%3),i%4?"":"[",i,i%4?"":"]",i%3?"":")",i%99?" ":"");}

C Specific Optimization : 115 bytes
#include<stdio.h>
i;f(){for(;i++<99;)printf("(%s%d%s%s%s"+!!(i%3),i%4?"":"[",i,i%4?"":"]",i%3?"":")",i%99?" ":"");}

Does MSVC let you do the inf f() thing?  Sorry 'bout deleting my comments, thought I had something shorter (I didn't)

@Zacharý No, i think the function is too simple and it generates a "f must return an int". BTW, your solution was 3 bytes shorter ( include compression paired with moving the incrementation of i )

I know, I thought that I had something better than what I suggested in the comments.

Dang, dotally forgot printf wasa thing. Couldn't you use the C stdio then?

Another thing you could use/exploit is the fact that, at least with gcc 5.3.1, you don't need the #include, and you can also remove the function return type.
Additionally, if you declare the int i outside the function (in global scope) then its value defaults to 0 and data type defaults to int. This would result in your loop starting at 0, and to fix this you could move the increment into the condition expression in your for loop, making it look like i;f(){for(;++i<=99;)

@mriklojn Good tricks ( with i++<99 ), but not declaring types makes it invalid in C++ ( at least not with MSVC )

Yeah, not declaring types always makes it invalid in C++.

-1 C++ optimization: #include<cstdio> (I think that works, not sure about std and the like)

@Logern No, i get a "undefined reference to printf" linker error

Suggest ")\0"+i%3 instead of i%3?"":")". Also, I think you need to add i=0 at the beginning of the loop.

@ceilingcat i=0 is not necessary as long as the program is executed only once. the i; declares a global variable (“static storage duration” in C standard parlance) which is initialized to 0 by default. https://port70.net/~nsz/c/c11/n1570.html#6.7.9p10

D, 110 bytes
import std.stdio;void f(){for(int i;i<99;)write(++i%3?"":"(",i%4?"":"[",i,i%4?"":"]",i%3?"":")",i%99?" ":"");}

Try it online!
Ported from  @HatsuPointerKun's C++ answer.

Charcoal, 30 bytes
⪫ＥＥＥ⁹⁹Ｉ⊕ι⎇﹪⊕κ⁴ι⪫[]ι⎇﹪⊕κ³ι⪫()ι

Try it online! Link is to verbose version of code. Explanation:
    ⁹⁹                          Literal 99
   Ｅ                            Map over implicit range
        ι                       Current value
       ⊕                        Incrementd
      Ｉ                         Cast to string
  Ｅ                             Map over list of strings
            κ                   Current index
           ⊕                    Incremented
             ⁴                  Literal 4
          ﹪                     Modulo
              ι                 Current value
                []              Literal string `[]`
                  ι             Current value
               ⪫                Join i.e wrap value in `[]`
         ⎇                      Ternary
 Ｅ                              Map over list of strings
                      κ         Current index
                     ⊕          Incremented
                       ³        Literal 3
                    ﹪           Modulo
                        ι       Current value
                          ()    Literal string `()`
                            ι   Current value
                         ⪫      Join i.e wrap value in `()`
                   ⎇            Ternary
                                Literal space
⪫                               Join list
                                Implicitly print

J, 54 53 bytes
1 byte less thanks to @Jonah
(*stdout(3|.0=4 3 1 3 4&|,1=":)#3|.']) ([',":)@>i.100

Try it online!

Thanks for doing this one.  Also, why do you have to do stdout here... I've never seen that before.  @FrownyFrog

@Jonah I can’t output it as a complete string, it gets cut off (. . .) stdout doesn’t do that, and it doesn’t print a newline either, so I can also print each number separately. For some reason though it makes trailing spaces appear (there are 4, and only 1 is intentionally there)

This approach is really clever, both the rotation and the choice to use #.  I had introduced an auxiliary verb to surround with () and []: g=. {.@[ , ":@] , {:@[.  ugh the verboseness!

one more question: any reason you used LF instead of _.  the latter seems to work too.

MathGolf, 41 40 34 29 bytes
♀({îû)(î+╫îa_'(\')ßyΓî34α÷ä§

NOTE: It has a trailing space
Only my second MathGolf answer..
-5 bytes thanks to @JoKing.
Try it online.
Explanation:
♀(             # Push 99 (100 decreased by 1)
  {            # Start a loop, which implicitly loops down to (and excluding) 0
   û)(         #  Push string ")("
      î+       #  Append the 1-indexed index
        ╫      #  Rotate the string once towards the right
   îa          #  Push the 1-indexed index of the loop, wrap in a list
   _           #  Duplicate it
    '(        '#  Push string "("
      \        #  Swap the top two items of the stack
       ')     '#  Push string ")"
         ßy    #  Wrap all three into a list, and join them
   Γ           #  Wrap all four into a list
               #  (We now have a list [N, "(N)", "[N]", "([N])"], where N is the index)
   î           #  Push the 1-indexed index of the loop
    34         #  Push 3 and 4 to the stack
      α        #  Wrap all three into a list
       ÷       #  Check for each if the index is divisible by it
               #  (resulting in either [0,0], [0,1], [1,0], or [1,1]
        ä      #  Convert from binary to integer
               #  (resulting in either 0, 1, 2, or 3
         §     #  Push the string at that index from the array
               #  Push a space
               # (After the loop, output the entire stack joined together implicitly)

@JoKing Thanks! Didn't knew the q could be omitted and it's done implicitly in loops. Also, didn't knew there was a 2/3/4-string builtin. Too bad that rotate trick doesn't work with the wrapped array.

Well, it's more that I've traded the explicit output each iteration for implicit output at the end of the program instead

@JoKing Yeah, but I didn't knew it would output the entire stack joined together, instead of just the top. :)

My solution was approaching 40 bytes, though I misread and thought that curly brackets should be used instead of square brackets. Good job on the solution!

Powershell, 60 bytes
"$(1..99|%{($_,"($_)","[$_]","([$_])")[!($_%3)+2*!($_%4)]})"

Explanation:

the array with 4 elements: $_, "($_)", "[$_]", "([$_])"
and the index: [!($_%3)+2*!($_%4)]
repeat for each number
convert the result to a string

Less golfed Test script:
$f = {

$r = 1..99|%{
    ($_, "($_)", "[$_]", "([$_])") [!($_%3)+2*!($_%4)]
}
"$($r)"

}

$expected = '1 2 (3) [4] 5 (6) 7 [8] (9) 10 11 ([12]) 13 14 (15) [16] 17 (18) 19 [20] (21) 22 23 ([24]) 25 26 (27) [28] 29 (30) 31 [32] (33) 34 35 ([36]) 37 38 (39) [40] 41 (42) 43 [44] (45) 46 47 ([48]) 49 50 (51) [52] 53 (54) 55 [56] (57) 58 59 ([60]) 61 62 (63) [64] 65 (66) 67 [68] (69) 70 71 ([72]) 73 74 (75) [76] 77 (78) 79 [80] (81) 82 83 ([84]) 85 86 (87) [88] 89 (90) 91 [92] (93) 94 95 ([96]) 97 98 (99)'
$result = &$f
$result-eq$expected
$result

Output:
True
1 2 (3) [4] 5 (6) 7 [8] (9) 10 11 ([12]) 13 14 (15) [16] 17 (18) 19 [20] (21) 22 23 ([24]) 25 26 (27) [28] 29 (30) 31 [32] (33) 34 35 ([36]) 37 38 (39) [40] 41 (42) 43 [44] (45) 46 47 ([48]) 49 50 (51) [52] 53 (54) 55 [56] (57) 58 59 ([60]) 61 62 (63) [64] 65 (66) 67 [68] (69) 70 71 ([72]) 73 74 (75) [76] 77 (78) 79 [80] (81) 82 83 ([84]) 85 86 (87) [88] 89 (90) 91 [92] (93) 94 95 ([96]) 97 98 (99)

Haskell, 77 bytes
unwords[f"()"3$f"[]"4$show n|n<-[1..99],let f(x:r)m s|mod n m<1=x:s++r|1<3=s]

Try it online!
I wonder if show[n] can be used to shorten things up, so far to no avail.

Python 2, 105 97 88 86 85 84 bytes
x=1
while x<100:print((('%s','(%s)')[x%3<1],'[%s]')[x%4<1],'([%s])')[x%12<1]%x,;x+=1

Try it online!

Red, 99 97 bytes
repeat n 99[a: b: c: d:""if n% 3 = 0[a:"("c:")"]if n% 4 = 0[b:"["d:"]"]prin rejoin[a b n d c" "]]

Try it online!

C#, 124 117 123 bytes
-5 bytes thanks to Kevin Cruijssen
x=>{for(int i=0;i++<99;)System.Console.Write((i%3<1?"(":"")+(i%4<1?"[":"")+i+(i%4<1?"]":"")+(i%3<1?")":"")+(i>98?"":" "));}

Test with :
Action<int> t = x=>{for(int i=0;i++<99;)System.Console.Write((i%3<1?"(":"")+(i%4<1?"[":"")+i+(i%4<1?"]":"")+(i%3<1?")":"")+(i>98?"":" "));}
t.Invoke(0);
Console.ReadKey();

Into the foray of C#, I see. Does C# allow integers as the left argument to a ternary operator, or does it have  to be a boolean?

I don't know much about C#, but could you use x instead of i,thus not having to worry about the int ? (You'd still have to set it, of course).

@Zacharý No, it generates a CS0029 error "Can't convert implicitly int to boolean". And yes, i could use i and the fact that i can initialize it at 0 when i Invoke. But wouldn't that mean that i would have to include the declaration of t ( Action<int> ) and the call ( t.Invoke(0) ) in the bytecount ?

I'm asking if something like  x=>{for(x=0;x++<99;)Console.Write((x%3==0?"(":"")+(x%4==0?"[":"")+x+(x%4==0?"]":"")+(x%3==0?")":"")+(x%99==0?"":" "));}; would work.

@Zacharý Yes, under one condition, that t is declared as Action<int>, and not Action<Whatever_other_type_but_int>. My answer works whatever generic specialization

All five ==0 can be <1.

Ah, the <int> ... okay, that makes more sense. And nice one @KevinCruijssen, totally forgot we weren't dealing with negative integers.

Does (i%4<1?"[":"")+i+(i%4<1?"]":"") => (i%4<1?"["+i+"]":""+i) work?

Don't you either have to include using System; or qualify it like System.Console.Write?

(That System.  adds to the byte count, by the way)

@Zacharý I forgot to complete the edit before saving x)

Lua, 161 123 bytes
b=""for i=1,99 do;c,d=i%3==0,i%4==0;b=b..(c and"("or"")..(d and"["or"")..i..(d and"]"or"")..(c and")"or"").." "end;print(b)

Try it online!
Ungolfed:
b = ""
for i = 1, 99 do
    c = 1 % 3 == 0
    d = 1 % 4 == 0
    a = ""
    if c then
        a = a .. "("
    end
    if d then
        a = a .. "["
    end
    a = a .. i
    if d then
        a = a .. "]"
    end
    if c then
        a = a .. ")"
    end
    b = b .. a .. " "
end
print(b)

C (gcc), 84 bytes
main(i){while(99/i++)printf("%s%s%d%s%s ","("+i%3,"["+i%4,i-1,"]"+i%4,")"+i%3);}

There's a null byte at the beginning of each "bracket string".
Try it online!

And in "("+i%3 how do you know that address for i=2 point to a zero char value? The same for "["+i%4 for i in {2,3}?

It works with gcc, which is good enough, as PPCG defines languages by their implementations.

I think you can not say that code it is ok compiled in every implementation of gcc compiler, perhaps only the one run in your pc (but possible not too)

@RosLuP gcc does work the same way on most computers though, at least on anything with the same architecture

@ASCII-only possible if is compiled optimized for space or for speed the result is different... I don't know if it is out the standard...

@RosLuP makes sense, but pretty sure they're normally compiled without flags unless otherwise specified

@RosLuP For code golfing purposes, gcc with flags is a different language.

This program absolutely does not “work with GCC”. It happens to fly only tiny demons out of the author's nose when he tries it out on his machine so that he does not notice. GCC has never guaranteed that "("+2 is in a valid page. The language description should be “GCC on my machine”.

PowerShell, 98 82 74 67 63 62 bytes
A whopping -31 bytes thanks to @Veskah
-5 bytes thanks to @ASCII-only
(1..99|%{(($a=($_,"[$_]")[!($_%4)]),"($a)")[!($_%3)]})-join' '

Try it online!
I'm still not quite sure what I've done here.

Just some quick golfing for 70 bytes. You don't have to cast $a as a string and "$a" will still substitute in the value. (Note: Single-quotes do not replace $foo, only double-quotes). Another trick is ifs only care about 0 or 1 so you can use boolean logic to save a byte

67 bytes if you use list indexing as well.

also 67

63?

62?

PowerShell, 67 62 bytes
"$(1..99|%{'('*!($x=$_%3)+'['*!($y=$_%4)+$_+']'*!$y+')'*!$x})"

Try it online!
Basically a FizzBuzz using string multiplication times Boolean variables (implicitly cast to 1 or 0). Those strings are left on the pipeline and gathered within a script block inside quotes. Since the default $OutputFieldSeparator for an array is spaces, this implicitly gives us space-delimited array elements.

Ruby, 72 66 bytes
p [*1..99].map{|x|a=x
a="[#{x}]"if x%4<1
a="(#{a})"if x%3<1
a}*' '

Thanks to @jonathan-frech and @conor-obrien for additional trimming.

Hello and welcome to PPCG! 70 bytes.

Welcome to PPCG! Here's another 4 bytes off of @JonathanFrench 's suggestion, for 66 bytes, since a.join b for an array a and string b is equivalent to a*b

Perl 5, 51 bytes
say map{$o=$_%4?$_:"[$_]";($_%3?$o:"($o)").$"}1..99

Try it online!

Clojure, 104 bytes
(apply print(map #(do(def s(if(=(rem % 4)0)(str"["%"]")%))(if(=(rem % 3)0)(str"("s")")s))(range 1 100)))

Try it online!

JavaScript (Node.js), 57 bytes
f=(n=99)=>n&&f(n-1)+(s=n%4?n:`[${n}]`,n%3?s:`(${s})`)+' '

Try it online!
Changed to community cuz the optimize rely too much on it

You could shorten significantly by doing ${n%4?n:`[${n}]`}

66 bytes (with ETH's suggestion)

59 bytes

57 bytes

perl -E, 60 bytes
$,=$";say map$_%12?$_%3?$_%4?$_:"[$_]":"($_)":"([$_])",1..99

Some bytes can be saved if we can use newlines between the numbers: in that
case, we can remove the $,=$";, change the map into a for loop, while moving the say into the loop.

Are you the Abigail? Inventor of /^1$|^(11+?)\1+$/?

Wow. What an honor to have you here!

Perl 6, 51 48 bytes
put {$_%3??$^a!!"($a)"}(++$_%4??$_!!"[$_]")xx 99

Try it online!

I was going to abuse the difference between lists and array representations, like this, but I'm not sure how to get rid of the enclosing brackets around the whole list...

@JoKing I thought about that, too, but I only came up with this 51-byter.

Batch, 145 bytes
@set s=
@for /l %%i in (1,1,99)do @set/an=%%i,b=n%%4,p=n%%3&call:c
@echo%s%
:c
@if %b%==0 set n=[%n%]
@if %p%==0 set n=(%n%)
@set s=%s% %n%

The code falls through into the subroutine but the string has already been printed by this point so the code executes harmlessly.

PHP 103
for(;$i<1e2;$i++)$a.=$i%12==0?"([$i]) ":($i%3==0?"($i) ":($i%4==0?"[$i] ":"$i "));echo substr($a,5,-1);
https://www.ideone.com/SBAuWp

Clean, 100 bytes
import StdEnv,Text

join" "[if(n/3*3<n)m("("+m+")")\\n<-[1..99],m<-[if(n/4*4<n)(""<+n)("["<+n<+"]")]]

Try it online!

sfk, 225 bytes
for n from 1 to 99 +calc -var #(n)/3+1/3 -dig=0 +calc -var #text*3-#(n) +setvar t +calc -var #(n)/4 -dig=0 +calc -var #text*4-#(n) +xed -var _0_#(t)\[#(n)\]_ _*_#(t)#(n)_ +xed _0*_([part2])_ _?*_[part2]_ +xed "_\n_ _" +endfor

Try it online!

Java 8, 92 91 bytes
-1 byte thanks to @Dana

i->{for(;i++<99;)out.printf((i>1?" ":"")+(i%12<1?"([%d])":i%3<1?"(%d)":i%4<1?"[%d]":i),i);}
Try it online!
Alternative solution, 82 bytes (with trailing space in the output - not sure if that's allowed):
i->{for(;i++<99;)out.printf((i%12<1?"([%d])":i%3<1?"(%d)":i%4<1?"[%d]":i)+" ",i);}
Explanation:
for(;i++<99;) - a for loop that goes from the value of i (reused as input, taken to be 0 in this case) to 99
out.printf(<part1>+<part2>,i); - formats the string before immediately printing it to stdout with the value of i
where <part1> is (i>1?" ":"") - prints the space before printing the number unless that number is 1, in which case it omits the space
and <part2> is (i%12<1?"([%d])":i%3<1?"(%d)":i%4<1?"[%d]":i) - if i is divisible by both 3 and 4, i has both square and round brackets around it; else if i is divisible by 3, i has round brackets; else if i is divisible by 4, i has square brackets; else, i has no brackets.

Save a byte by moving the space to the beginning of each loop iteration (i>1:" ":"")

That would only work if I printed the result in reverse (see this) but would actually save 2 bytes instead of 1.

Unfortunately that's not the same as the expected output as per the question, but thank you for the suggestion nevertheless!

The "try it online" links seem to be broken. I was thinking i->{for(;i++<99;)out.printf((i>1?" ":"")+(i%12<1?"([%d])":i%3<1?"(%d)":i%4<1?"[%d]":i),i);} ?

Ohhhh you're right that does work! Thanks for that!

Bash, 61 bytes
-14 bytes, thanks to Dennis
seq 99|awk '{ORS=" ";x=$1%4?$1:"["$1"]";print$1%3?x:"("x")"}'

explanation
Pretty straightforward:

seq produces 1..99
we pipe that into awk with the output record separator (ORS) set to space so the output is a single line.
the main awk body just adds "[]" when the number is divisible by 4, and then adds, on top of that, "()" when divisible by 3.

Try it online!

PHP, 65 bytes
while($i++<99)echo$i%4?$i%3?$i:"($i)":($i%3?"[$i]":"([$i])")," ";

or
while($i++<99)echo"("[$i%3],"["[$i%4],$i,"]"[$i%4],")"[$i%3]," ";

(requires PHP 5.5 or later)
Run with -nr or try them online.

Python 2, 78 bytes
i=0
exec"i+=1;u=i%3/-2*(i%4/-3-1);print'([%0d])'[u:7-u:1+(i%3<1<=i%4)]%i,;"*99

Try it online!
I envisioned this cool approach slicing '([%0d])' but I can't get the expressions any shorter.

APL(NARS), 46 chars, 92 bytes
{{0=3∣w:1⌽')(',⍵⋄⍵}{0=4∣w:1⌽'][',⍵⋄⍵}⍕w←⍵}¨⍳99

litte test:
  {{0=3∣w:1⌽')(',⍵⋄⍵}{0=4∣w:1⌽'][',⍵⋄⍵}⍕w←⍵}¨⍳14
1 2 (3) [4] 5 (6) 7 [8] (9) 10 11 ([12]) 13 14

Python 2, 68 bytes
i=0
exec"i+=1;t,f=i%3<1,i%4<1;print'('*t+'['*f+`i`+']'*f+')'*t,;"*99

Try it online!

Pyth, 25 bytes
jdmj]W!%d4dc2*"()"!%d3S99

Try it online here.
jdmj]W!%d4dc2*"()"!%d3S99
  m                   S99   Map [1-99], as d, using:
                   %d3        d mod 3
                  !           Logical not, effectively maps 0 to 1, all else to 0
             *"()"            Repeat "()" the above number of times
           c2                 Chop into two equal parts - maps "()" to ["(",")"] , and "" to ["",""]
                                The above is result {1}
       %d4                    d mod 4
      !                       Logical not the above
    ]W    d                   If the above is truthy, [d], else d
                                The above is result {2}
   j                          Join {1} on string representation of {2}
jd                          Join the result of the map on spaces, implicit print

Python 3, 95 bytes
print(*[(i if i%4else f"[{i}]")if i%3else(f"({i})"if i%4else f"([{i}])")for i in range(1,100)])

Try it online!

Python 2, 68 bytes
for i in range(1,100):print("(%s)","%s")[i%3>0]%("[%s]"%i,i)[i%4>0],

Try it online!
Ends with a trailing space.

Stax, 19 17 bytes
ä┐r►U^îⁿ_╤▌,│☻£╡▬

Run and debug it

C (gcc), 76 bytes
Surprisingly, this straight-forward solution was shorter than the "clever" ones I could come up with.
f(i){for(i=0;i++<99;)printf(i%3?i%4?"%d ":"[%d] ":i%4?"(%d) ":"([%d]) ",i);}

Try it online!

CJam, 70 bytes

99,:){X4%0={'[Xs']++}{X}?}fX]{Xs'[/_,(=']/0=i3%0={'(Xs')++}{X}?}fX]S*

Try it out online! (Permalink)

Explanation

99                                                                    Push 99 to stack
  ,                                                                   Make a 0..98 array
   :)                                                                 Increment every value in array
     {                   }fX                                          For X in array at top of stack
                        ?                                             If...
      X4%0=                                                           Condition: X mod 4 = 0
           {        }                                                 Is true, then:
            '[                                                        Push "["
              Xs                                                      Push X as a string
                ']                                                    Push "]"
                  ++                                                  Concatenate to "[X]"
                     { }                                              Is false, then:
                      X                                               Push X
                            ]                                         Capture all in an array
                             {                                 }fX    For X in array at top of stack
                                                              ?       If...
                              Xs                                      X as a string
                                '[/                                   Split by "["
                                   _,(=                               Take last element after split
                                       ']/                            Split by "]"
                                          0=                          Take first element after split
                                            i                         Top element as an integer
                              Xs'[/_,(=']/0=i                         The number X minus any brackets
                                             3%0=                     Condition: X mod 3 = 0
                                                 {        }           Is true, then:
                                                  '(                  Push "("
                                                    Xs                Push the original X as a string
                                                      ')              Push ")"
                                                        ++            Concatenate to "(X)"
                                                           { }        If false, then:
                                                            X         Push X
                                                                  ]   Capture all in an array
                                                                   S* Separate by a space

This does not output a trailing space.

C# (Visual C# Interactive Compiler), 71 bytes
int i;for(;i<99;)Write("{0:;;(}{1:;;[}{2}{1:;;]}{0:;;)} ",++i%3,i%4,i);

Try it online!
-9 bytes thanks to @ASCIIOnly!
Leveraging the semicolon (The ";" section separator) to create a custom format string.

:( close, also I think it'd be fine just adding a space after every term like most answers are doing

Good call on adding a space after every number. Sometimes I take things too literally :) I'll update later.

Japt, 30 bytes
Lo1@=X%4?X:"[{X}]"X%3?U:"({U})

Try it online!

PHP, 59 bytes
for(;$i<100;$s=++$i%4?$i:"[$i]")echo$i%3|!$s?$s:"($s)"," ";

Try it online!

Attache, 56 bytes
Echo@@({~Join^^S@_'Mask[4'3|_,["["'"]","("'")"]]}=>1:99)

Try it online!
Explanation
Echo@@({~Join^^S@_'Mask[4'3|_,["["'"]","("'")"]]}=>1:99)
       {                                        }=>1:99  over each number _, 1 to 99:
                        4'3|_                                check if 4 or 3 divide _
                   Mask[     ,["["'"]","("'")"]]             keep the respective brackets
             ^^S@_'                                          fold over this list (seed = S[_]):
        ~Join                                                joining elements by the iterator
Echo@@(                                                ) print strings separated by spaces

Alternatives
58 bytes: Echo@@({~Join^^S@_'Mask[[4,3]|_,["["'"]","("'")"]]}=>1:99)
59 bytes: Print@@({~Join^^S@_'Mask[[4,3]|_,["["'"]","("'")"]]}=>1:99)
76 bytes: Print@@(&/S@{Mask[1'3'4'12|_,Split@$"${_} (${_}) [${_}] ([${_}])"] }=>1:99)

Javascript, 114 96 bytes
[...Array(99)].map(_=>['[4]','(3)'].reduce((a,r)=>n%r[1]<1?r.replace(r[1],a):a,++n),n=0).join` `

Try it Online!
Thanks to Conor O'Brien for helping me improve it :-)

If you haven't heard it yet, welcome to PPCG! You can squeeze out a few more bytes: n%r[1]==0 can become n%r[1]<1 (-1 bytes); .join(' ') to .join` `  (-2 bytes); you can use [...Array(99)].map(_=>...,n=0) to make the iteration section a bit more compact. You can overall golf around 20 bytes from this answer. Try it online!.

Some good tips, thanks @ConorO'Brien! Will add the improvements

Damn, both .join\ `and adding,n=0to themap` parameters are tricks I've never seen. Love learning new things :-)

Anytime! Glad I could help! :D

ink, 61 bytes
VAR j=0
-(i)~j="{i%4:{i}|[{i}]}"
{i%3:{j}|({j})} <>{i<99:->i}

Try it online!
Explanation
VAR j=0                       // Declare a variable called j.
-(i)~j="{i%4:{i}|[{i}]}"      // The i label keeps track of how many times it's been visited. Set j to that value, or that value surrounded by brackets, depending o nwhat it is.
{i%3:{j}|({j})} <>{i<99:->i}  // Print j or (j), depending on i. Use glue (<>) to not print a newline. Go back to the i label if it's been visited fewer than 99 times.

Vyxal HS, 103 bitsv2, 12.875 bytes
ɽƛ4ḊßøB;ƛ⌊₃ßøb

Try it Online!

Go, 173 bytes
import(."strings";."fmt")
func f(){S,F:=[]string{},Sprintf
for i:=1;i<100;i++{s:=F("%d",i)
if i%4<1{s=F("[%s]",s)}
if i%3<1{s=F("(%s)",s)}
S=append(S,s)}
Print(Join(S," "))}

Attempt This Online!
Prints the output to STDOUT.


text:
Iterated Prisoner's Trilemma
CHALLENGE STATUS: OPEN
Comment, open a PR, or otherwise yell at me if I'm missing your bot.

Prisoner's dilemma ... with three choices. Crazy, huh?
Here's our payoff matrix. Player A on the left, B on the top
A,B| C | N | D
---|---|---|---
 C |3,3|4,1|0,5
 N |1,4|2,2|3,2
 D |5,0|2,3|1,1

The payoff matrix is engineered so that it's best for both players to always cooperate, but you can gain (usually) by choosing Neutral or Defection.
Here's some (competing) example bots.
# turns out if you don't actually have to implement __init__(). TIL!

class AllC:
    def round(self, _): return "C"
class AllN:
    def round(self, _): return "N"
class AllD:
    def round(self, _): return "D"
class RandomBot:
    def round(self, _): return random.choice(["C", "N", "D"])

# Actually using an identically-behaving "FastGrudger".
class Grudger:
    def __init__(self):
        self.history = []
    def round(self, last):
        if(last):
            self.history.append(last)
            if(self.history.count("D") > 0):
                return "D"
        return "C"

class TitForTat:
    def round(self, last):
        if(last == "D"):
            return "D"
        return "C"

Your bot is a Python3 class. A new instance is created for every game, and round() is called each round, with your opponent's choice from last round (or None, if it's the first round)
There's a 50 rep bounty for the winner in like a month.
Specifics

Every bot plays every other bot (1v1), including itself, in [REDACTED] rounds.
Standard loopholes disallowed.
No messing with anything outside your class or other underhanded shenanigains.
You may submit up to five bots.
Yes, you can implement handshake.
Any response other than C, N, or D will be silently taken as N.
Each bot's points from every game they play will be totaled up and compared.

Controller
Check!
Other Languages
I'll throw together an API if anyone needs it.
Scores: 2018-11-27
27 bots, 729 games.

name            | avg. score/round
----------------|-------------------
PatternFinder   | 3.152
DirichletDice2  | 3.019
EvaluaterBot    | 2.971
Ensemble        | 2.800
DirichletDice   | 2.763
Shifting        | 2.737
FastGrudger     | 2.632
Nash2           | 2.574
HistoricAverage | 2.552
LastOptimalBot  | 2.532
Number6         | 2.531
HandshakeBot    | 2.458
OldTitForTat    | 2.411
WeightedAverage | 2.403
TitForTat       | 2.328
AllD            | 2.272
Tetragram       | 2.256
Nash            | 2.193
Jade            | 2.186
Useless         | 2.140
RandomBot       | 2.018
CopyCat         | 1.902
TatForTit       | 1.891
NeverCOOP       | 1.710
AllC            | 1.565
AllN            | 1.446
Kevin           | 1.322

How are bots put against each other? I get from the Grudger that there are always two bots against/with each other and the enemy's last choice is passed to the bot. How many rounds are played? And for a game: Does only the result count (i.e. who won) or also the points?

You would get more entries if you made this language-agnostic, or at least broader. You could have a wrapper python class that spawns a process and sends it text commands to get back text responses.

Done. This was on the sandbox for like a month!

proposal: normalize scores so that adding more bots or more rounds doesn't inflate the numbers

Depending on how popular this gets, you might want to throw in a "Must run under x ms" to fend off some of the nuttier sim bots. Probably not needed considering this isn't grid-scanning, though.

@Veskah i had to limit the O(n^2) piece of PatternFinder to n=100 to avoid exploding runtime for longer matches

@Black Owl Kai: Knowing how many rounds breaks the game. You just don't know it yet.

We can just do trial and error at home to match the leaderboard and figure out the number of rounds being run. Normalized scores would help, but still not solve the problem.

The game is symmetric, why run every match twice with swapped bots? Seems like a waste of time.

If you wrap most of main.py in while len(botlist) > 1: with botlist.remove(lowest_scoring_bot) at the bottom of the loop, you get an elimination tournament with interesting results.

Another version of this someday might pass the entire interaction history rather than just the last move.  It doesn't change much although it simplifies user code slightly.  But it would allow for extensions, such as noisy communication channels that clarify over time:  "Really, a D, even though I've said C four times in a row?  No, I didn't say D; what do you take me for?  Oh, sorry, can we just forget that round?"

@ScottSauyet Have fun; I was going for simplicity in the API.

@Sparr too lazy.

Should we give a second submission in an edit or new post? Would you find the new one in an edit?

@Bridgeburners if it's fundamentally different and you want both versions to compete separately, you need to submit a second answer.

I had no idea I was [still] in the lead for this challenge.

EvaluaterBot
class EvaluaterBot:
    def __init__(self):
        self.c2i = {"C":0, "N":1, "D":2}
        self.i2c = {0:"C", 1:"N", 2:"D"}
        self.history = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
        self.last = [None, None]

    def round(self, last):
        if self.last[0] == None:
            ret = 2
        else:
            # Input the latest enemy action (the reaction to my action 2 rounds ago)
            # into the history
            self.history[self.last[0]][self.c2i[last]] += 1
            # The enemy will react to the last action I did
            prediction,_ = max(enumerate(self.history[self.last[1]]), key=lambda l:l[1])
            ret = (prediction - 1) % 3
        self.last = [self.last[1], ret]
        return self.i2c[ret]

Wins against all previously submitted bots except (maybe) the random bot (but it could have an advantage, because it picks D in a draw and D should optimal) and plays a constant draw against themself.

Yep, beats everything.

Scratch that, PatternFinder beats it by a bit.

TatForTit
class TatForTit:
    def round(self, last):
        if(last == "C"):
            return "N"
        return "D"

This bot will alternate picking D N D N while TitForTat alternates C D C D, for an average net gain of 3 points per round if I have read the payout matrix correctly. I think this might be optimal against TitForTat. Obviously it could be improved to detect a non-TFT opponent and adopt other strategies, but I was just aiming for the original bounty.

NashEquilibrium
This bot has taken a game theory class in college but was lazy and didn't go to the class where they covered iterated games. So he only plays single game mixed nash equilibrium. Turns out 1/5 2/5 2/5 is the mixed NE for the payoffs.
class NashEquilibrium:
    def round(self, _):
        a = random.random()
        if a <= 0.2:
            return "C"
        elif a <= 0.6:
            return "N"
        else:
            return "D"

Constant Abusing Nash Equilibrium
This bot picked up a lesson or two from his lazy brother. His lazy brother's problem was that he didn't take advantage of fixed strategies. This version checks if the opponent is a constant player or titfortat and plays accordingly, else it plays the regular nash equilibrium.
It's only downside is that it averages 2.2 points per turn playing against itself.
class NashEquilibrium2:

    def __init__(self):
        self.opphistory = [None, None, None]
        self.titfortatcounter = 0
        self.titfortatflag = 0
        self.mylast = "C"
        self.constantflag = 0
        self.myret = "C"

    def round(self, last):
        self.opphistory.pop(0)
        self.opphistory.append(last)

        # check if its a constant bot, if so exploit
        if self.opphistory.count(self.opphistory[0]) == 3:
            self.constantflag = 1
            if last == "C":
                 self.myret = "D"
            elif last == "N":
                 self.myret = "C"
            elif last == "D":
                 self.myret = "N"

        # check if its a titfortat bot, if so exploit
        # give it 2 chances to see if its titfortat as it might happen randomly
        if self.mylast == "D" and last == "D":
            self.titfortatcounter = self.titfortatcounter + 1

        if self.mylast == "D" and last!= "D":
            self.titfortatcounter = 0

        if self.titfortatcounter >= 3:
            self.titfortatflag = 1

        if self.titfortatflag == 1:
            if last == "C":
                 self.myret = "D"
            elif last == "D":
                 self.myret = "N"
            elif last == "N":
                # tit for tat doesn't return N, we made a mistake somewhere
                 self.titfortatflag = 0
                 self.titfortatcounter = 0

        # else play the single game nash equilibrium
        if self.constantflag == 0 and self.titfortatflag == 0:
            a = random.random()
            if a <= 0.2:
                self.myret = "C"
            elif a <= 0.6:
                self.myret = "N"
            else:
                self.myret = "D"

        self.mylast = self.myret
        return self.myret

NashEquilibrium.round needs to take arguments even if it doesn't use them, so as to fit the expected function prototype.

Little shorter: class NashEquilibrium:     def round(self, _):         a = random.random()         for k, v in [(0.2, "C"), (0.6, "N"), (1, "D")]:             if a <= k:                 return v

PatternFinder
class PatternFinder:
    def __init__(self):
        import collections
        self.size = 10
        self.moves = [None]
        self.other = []
        self.patterns = collections.defaultdict(list)
        self.counter_moves = {"C":"D", "N":"C", "D":"N"}
        self.initial_move = "D"
        self.pattern_length_exponent = 1
        self.pattern_age_exponent = 1
        self.debug = False
    def round(self, last):
        self.other.append(last)
        best_pattern_match = None
        best_pattern_score = None
        best_pattern_response = None
        self.debug and print("match so far:",tuple(zip(self.moves,self.other)))
        for turn in range(max(0,len(self.moves)-self.size),len(self.moves)):
            # record patterns ending with the move that just happened
            pattern_full = tuple(zip(self.moves[turn:],self.other[turn:]))
            if len(pattern_full) > 1:
                pattern_trunc = pattern_full[:-1]
                pattern_trunc_result = pattern_full[-1][1]
                self.patterns[pattern_trunc].append([pattern_trunc_result,len(self.moves)-1])
            if pattern_full in self.patterns:
                # we've seen this pattern at least once before
                self.debug and print("I've seen",pattern_full,"before:",self.patterns[pattern_full])
                for [response,turn_num] in self.patterns[pattern_full]:
                    score = len(pattern_full) ** self.pattern_length_exponent / (len(self.moves) - turn_num) ** self.pattern_age_exponent
                    if best_pattern_score == None or score > best_pattern_score:
                        best_pattern_match = pattern_full
                        best_pattern_score = score
                        best_pattern_response = response
                    # this could be much smarter about aggregating previous responses
        if best_pattern_response:
            move = self.counter_moves[best_pattern_response]
        else:
            # fall back to playing nice
            move = "C"
        self.moves.append(move)
        self.debug and print("I choose",move)
        return move

This bot looks for previous occurrences of the recent game state to see how the opponent responded to those occurrences, with a preference for longer pattern matches and more recent matches, then plays the move that will "beat" the opponent's predicted move. There's a lot of room for it to be smarter with all the data it keeps track of, but I ran out of time to work on it.

When you get the time, mind giving her an optimization pass? It's easily the largest time-sink.

@Blacksilver I just reduced the maximum pattern length from 100 to 10. It should run almost instantly now if you're running <200 rounds

Maybe using a highly composite number (i.e., 12) would score better?

Jade
class Jade:
    def __init__(self):
        self.dRate = 0.001
        self.nRate = 0.003

    def round(self, last):
        if last == 'D':
            self.dRate *= 1.1
            self.nRate *= 1.2
        elif last == 'N':
            self.dRate *= 1.03
            self.nRate *= 1.05
        self.dRate = min(self.dRate, 1)
        self.nRate = min(self.nRate, 1)

        x = random.random()
        if x > (1 - self.dRate):
            return 'D'
        elif x > (1 - self.nRate):
            return 'N'
        else:
            return 'C'

Starts out optimistic, but gets progressively more bitter as the opponent refuses to cooperate.  Lots of magic constants that could probably be tweaked, but this probably isn't going to do well enough to justify the time.

Ensemble
This runs an ensemble of related models.  The individual models consider different amounts of history, and have the option of either always choosing the move that will optimize the expected payout difference, or will randomly select a move in proportion to expected payout difference.
Each member of the ensemble then votes on their preferred move.  They get a number of votes equal to how much more they've won than the opponent (which means that terrible models will get negative votes).  Whichever move wins the vote is then selected.
(They should probably split their votes among the moves in proportion to how much they favor each, but I don't care enough to do that right now.)
It beats everything posted so far except EvaluaterBot and PatternFinder. (One-on-one, it beats EvaluaterBot and loses to PatternFinder).
from collections import defaultdict
import random
class Number6:
    class Choices:
        def __init__(self, C = 0, N = 0, D = 0):
            self.C = C
            self.N = N
            self.D = D

    def __init__(self, strategy = "maxExpected", markov_order = 3):
        self.MARKOV_ORDER = markov_order;
        self.my_choices = ""
        self.opponent = defaultdict(lambda: self.Choices())
        self.choice = None # previous choice
        self.payoff = {
            "C": { "C": 3-3, "N": 4-1, "D": 0-5 },
            "N": { "C": 1-4, "N": 2-2, "D": 3-2 },
            "D": { "C": 5-0, "N": 2-3, "D": 1-1 },
        }
        self.total_payoff = 0

        # if random, will choose in proportion to payoff.
        # otherwise, will always choose argmax
        self.strategy = strategy
        # maxExpected: maximize expected relative payoff
        # random: like maxExpected, but it chooses in proportion to E[payoff]
        # argmax: always choose the option that is optimal for expected opponent choice

    def update_opponent_model(self, last):
        for i in range(0, self.MARKOV_ORDER):
            hist = self.my_choices[i:]
            self.opponent[hist].C += ("C" == last)
            self.opponent[hist].N += ("N" == last)
            self.opponent[hist].D += ("D" == last)

    def normalize(self, counts):
        sum = float(counts.C + counts.N + counts.D)
        if 0 == sum:
            return self.Choices(1.0 / 3.0, 1.0 / 3.0, 1.0 / 3.0)
        return self.Choices(
            counts.C / sum, counts.N / sum, counts.D / sum)

    def get_distribution(self):
        for i in range(0, self.MARKOV_ORDER):
            hist = self.my_choices[i:]
            #print "check hist = " + hist
            if hist in self.opponent:
                return self.normalize(self.opponent[hist])

        return self.Choices(1.0 / 3.0, 1.0 / 3.0, 1.0 / 3.0)

    def choose(self, dist):
        payoff = self.Choices()
        # We're interested in *beating the opponent*, not
        # maximizing our score, so we optimize the difference
        payoff.C = (3-3) * dist.C + (4-1) * dist.N + (0-5) * dist.D
        payoff.N = (1-4) * dist.C + (2-2) * dist.N + (3-2) * dist.D
        payoff.D = (5-0) * dist.C + (2-3) * dist.N + (1-1) * dist.D

        # D has slightly better payoff on uniform opponent,
        # so we select it on ties
        if self.strategy == "maxExpected":
            if payoff.C > payoff.N:
                return "C" if payoff.C > payoff.D else "D"
            return "N" if payoff.N > payoff.D else "D"
        elif self.strategy == "randomize":
            payoff = self.normalize(payoff)
            r = random.uniform(0.0, 1.0)
            if (r < payoff.C): return "C"
            return "N" if (r < payoff.N) else "D"
        elif self.strategy == "argMax":
            if dist.C > dist.N:
                return "D" if dist.C > dist.D else "N"
            return "C" if dist.N > dist.D else "N"

        assert(0) #, "I am not a number! I am a free man!")

    def update_history(self):
        self.my_choices += self.choice
        if len(self.my_choices) > self.MARKOV_ORDER:
            assert(len(self.my_choices) == self.MARKOV_ORDER + 1)
            self.my_choices = self.my_choices[1:]

    def round(self, last):
        if last: self.update_opponent_model(last)

        dist = self.get_distribution()
        self.choice = self.choose(dist)
        self.update_history()
        return self.choice

class Ensemble:
    def __init__(self):
        self.models = []
        self.votes = []
        self.prev_choice = []
        for order in range(0, 6):
            self.models.append(Number6("maxExpected", order))
            self.models.append(Number6("randomize", order))
            #self.models.append(Number6("argMax", order))
        for i in range(0, len(self.models)):
            self.votes.append(0)
            self.prev_choice.append("D")

        self.payoff = {
            "C": { "C": 3-3, "N": 4-1, "D": 0-5 },
            "N": { "C": 1-4, "N": 2-2, "D": 3-2 },
            "D": { "C": 5-0, "N": 2-3, "D": 1-1 },
        }

    def round(self, last):
        if last:
            for i in range(0, len(self.models)):
                self.votes[i] += self.payoff[self.prev_choice[i]][last]

        # vote. Sufficiently terrible models get negative votes
        C = 0
        N = 0
        D = 0
        for i in range(0, len(self.models)):
            choice = self.models[i].round(last)
            if "C" == choice: C += self.votes[i]
            if "N" == choice: N += self.votes[i]
            if "D" == choice: D += self.votes[i]
            self.prev_choice[i] = choice

        if C > D and C > N: return "C"
        elif N > D: return "N"
        else: return "D"

Test Framework
In case anyone else finds it useful, here's a test framework for looking at individual matchups. Python2.  Just put all the opponents you're interested in in opponents.py, and change the references to Ensemble to your own.
import sys, inspect
import opponents
from ensemble import Ensemble

def count_payoff(label, them):
    if None == them: return
    me = choices[label]
    payoff = {
        "C": { "C": 3-3, "N": 4-1, "D": 0-5 },
        "N": { "C": 1-4, "N": 2-2, "D": 3-2 },
        "D": { "C": 5-0, "N": 2-3, "D": 1-1 },
    }
    if label not in total_payoff: total_payoff[label] = 0
    total_payoff[label] += payoff[me][them]

def update_hist(label, choice):
    choices[label] = choice

opponents = [ x[1] for x
    in inspect.getmembers(sys.modules['opponents'], inspect.isclass)]

for k in opponents:
    total_payoff = {}

    for j in range(0, 100):
        A = Ensemble()
        B = k()
        choices = {}

        aChoice = None
        bChoice = None
        for i in range(0, 100):
            count_payoff(A.__class__.__name__, bChoice)
            a = A.round(bChoice)
            update_hist(A.__class__.__name__, a)

            count_payoff(B.__class__.__name__, aChoice)
            b = B.round(aChoice)
            update_hist(B.__class__.__name__, b)

            aChoice = a
            bChoice = b
    print total_payoff

The controller is ready, you didn't have to do all that...

@Blacksilver I realized that just as I was about to submit.  But this one works in versions before 3.6, and gives information about individual matchups that can help identify weak spots, so it wasn't a complete waste of time.

Fair enough; running now. I'll probably add options to my controller to do similar things.

"It beats everything posted so far except Ensemble and PatternFinder"
I'm honored :)

@Sparr Oops. That was supposed to say EvaluaterBot and PatternFinder.  But that's when comparing total score against the entire field. PatternFinder remains the only one that beats this in a direct match up.

OldTitForTat
Old school player is too lazy to update for the new rules.
class OldTitForTat:
    def round(self, last):
        if(last == None)
            return "C"
        if(last == "C"):
            return "C"
        return "D"

LastOptimalBot
class LastOptimalBot:
    def round(self, last):
        return "N" if last == "D" else ("D" if last == "C" else "C")

Assumes that the opposing bot will always play the same move again, and chooses the one that has the best payoff against it.
Averages:
Me   Opp
2.6  2    vs TitForTat
5    0    vs AllC
4    1    vs AllN
3    2    vs AllD
3.5  3.5  vs Random
3    2    vs Grudger
2    2    vs LastOptimalBot
1    3.5  vs TatForTit
4    1    vs NeverCOOP
1    4    vs EvaluaterBot
2.28 2.24 vs NashEquilibrium

2.91 average overall

oof. Maybe T4T would do better as return last.

I'd like that!  If TitForTat were return last, LOB would go 18-9 over 6 rounds rather than the 13-10 over 5 rounds it's currently getting.  I think it's fine as is - don't worry about optimizing the example bots.

return last would be a better T4T for this challenge, I think

Just tried -- the if(last): return last; else: return "C" is worse.

Right, but as @Sparr was saying, it might be more appropriate.  Up to you, I suppose.

NeverCOOP
class NeverCOOP:
    def round(self, last):
        try:
            if last in "ND":
                return "D"
            else:
                return "N"
        except:
            return "N"

If the opposing bot defects or is neutral, choose defect. Otherwise if this is the first turn or the opposing bot cooperates, choose neutral. I'm not sure how good this will work...

What's the try/except for?

@Blacksilver I'd assume it serves the same purpose as the if(last): in your Grudger bot, detecting whether there was a previous round.

ahh, I see. None in "ND" errors.

Because if last and last in "ND": was too complicated?

CopyCat
class CopyCat:
    def round(self, last):
        if last:
            return last
        return "C"

Copies the opponent's last move.
I don't expect this to do well, but no one had implemented this classic yet.

Handshake
class HandshakeBot:
  def __init__(self):
    self.handshake_length = 4
    self.handshake = ["N","N","C","D"]
    while len(self.handshake) < self.handshake_length:
      self.handshake *= 2
    self.handshake = self.handshake[:self.handshake_length]
    self.opp_hand = []
    self.friendly = None
  def round(self, last):
    if last:
      if self.friendly == None:
        # still trying to handshake
        self.opp_hand.append(last)
        if self.opp_hand[-1] != self.handshake[len(self.opp_hand)-1]:
          self.friendly = False
          return "D"
        if len(self.opp_hand) == len(self.handshake):
          self.friendly = True
          return "C"
        return self.handshake[len(self.opp_hand)]
      elif self.friendly == True:
        # successful handshake and continued cooperation
        if last == "C":
          return "C"
        self.friendly = False
        return "D"
      else:
        # failed handshake or abandoned cooperation
        return "N" if last == "D" else ("D" if last == "C" else "C")
    return self.handshake[0]

Recognizes when it's playing against itself, then cooperates. Otherwise mimics LastOptimalBot which seems like the best one-line strategy. Performs worse than LastOptimalBot, by an amount inversely proportional to the number of rounds. Obviously would do better if there were more copies of it in the field *cough**wink*.

Just submit a few clones that have different non-handshake behavior.

That seems exploit-y. I could submit one such clone for every simple behavior represented here.

I've added an extra clause saying that you can only submit max five bots.

Kevin
class Kevin:
    def round(self, last):
        return {"C":"N","N":"D","D":"C",None:"N"} [last]

Picks the worst choice. The worst bot made.
Useless
import random

class Useless:
    def __init__(self):
        self.lastLast = None

    def round(self, last):
        tempLastLast = self.lastLast
        self.lastLast = last

        if(last == "D" and tempLastLast == "N"):
            return "C"
        if(last == "D" and tempLastLast == "C"):
            return "N"

        if(last == "N" and tempLastLast == "D"):
            return "C"
        if(last == "N" and tempLastLast == "C"):
            return "D"

        if(last == "C" and tempLastLast == "D"):
            return "N"
        if(last == "C" and tempLastLast == "N"):
            return "D"

        return random.choice("CND")

It looks at the last two moves done by the opponent and picks the most not done else it picks something random. There is probably a better way of doing this.

Historic Average
class HistoricAverage:
    PAYOFFS = {
        "C":{"C":3,"N":1,"D":5},
        "N":{"C":4,"N":2,"D":2},
        "D":{"C":0,"N":3,"D":1}}
    def __init__(self):
        self.payoffsum = {"C":0, "N":0, "D":0}
    def round(this, last):
        if(last != None):
            for x in this.payoffsum:
               this.payoffsum[x] += HistoricAverage.PAYOFFS[last][x]
        return max(this.payoffsum, key=this.payoffsum.get)

Looks at history and finds the action that would have been best on average. Starts cooperative.

This could run faster if it didn't re-calculate the averages every round.

@Sparr true. I edited it so it does now.

Improved Dirichlet Dice
import random

class DirichletDice2:
    def __init__(self):

        self.alpha = dict(
                C = {'C' : 1, 'N' : 1, 'D' : 1},
                N = {'C' : 1, 'N' : 1, 'D' : 1},
                D = {'C' : 1, 'N' : 1, 'D' : 1}
        )
        self.myLast = [None, None]
        self.payoff = dict(
                C = { "C": 0, "N": 3, "D": -5 },
                N = { "C": -3, "N": 0, "D": 1 },
                D = { "C": 5, "N": -1, "D": 0 }
        )

    def DirichletDraw(self, key):
        alpha = self.alpha[key].values()
        mu = [random.gammavariate(a,1) for a in alpha]
        mu = [m / sum(mu) for m in mu]
        return mu

    def ExpectedPayoff(self, probs):
        expectedPayoff = {}
        for val in ['C','N','D']:
            payoff = sum([p * v for p,v in zip(probs, self.payoff[val].values())])
            expectedPayoff[val] = payoff
        return expectedPayoff

    def round(self, last):
        if last is None:
            self.myLast[0] = 'D'
            return 'D'

        #update dice corresponding to opponent's last response to my
        #outcome two turns ago
        if self.myLast[1] is not None:
            self.alpha[self.myLast[1]][last] += 1

        #draw probs for my opponent's roll from Dirichlet distribution and then return the optimal response
        mu = self.DirichletDraw(self.myLast[0])
        expectedPayoff = self.ExpectedPayoff(mu)
        res = max(expectedPayoff, key=expectedPayoff.get)

        #update myLast
        self.myLast[1] = self.myLast[0]
        self.myLast[0] = res

        return res

This is an improved version of Dirichlet Dice. Instead of taking the expected multinomial distribution from the Dirichlet distribution, it draws a Multinomial distribution randomly from the Dirichlet distribution. Then, instead of drawing from the Multinomial and giving the optimal response to that, it gives the optimal expected response to the given Multinomial using the points. So the randomness has essentially been shifted from the Multinomial draw to the Dirichlet draw. Also, the priors are more flat now, to encourage exploration.
It's "improved" because it now accounts for the points system by giving the best expected value against the probabilities, while maintaining its randomness by drawing the probabilities themselves. Before, I tried simply doing the best expected payoff from the expected probabilities, but that did badly because it just got stuck, and didn't explore enough to update its dice. Also it was more predictable and exploitable.

Original submission:
Dirichlet Dice
import random

class DirichletDice:
    def __init__(self):

        self.alpha = dict(
                C = {'C' : 2, 'N' : 3, 'D' : 1},
                N = {'C' : 1, 'N' : 2, 'D' : 3},
                D = {'C' : 3, 'N' : 1, 'D' : 2}
        )

        self.Response = {'C' : 'D', 'N' : 'C', 'D' : 'N'}
        self.myLast = [None, None]

    #expected value of the dirichlet distribution given by Alpha
    def MultinomialDraw(self, key):
        alpha = list(self.alpha[key].values())
        probs = [x / sum(alpha) for x in alpha]
        outcome = random.choices(['C','N','D'], weights=probs)[0]
        return outcome

    def round(self, last):
        if last is None:
            self.myLast[0] = 'D'
            return 'D'

        #update dice corresponding to opponent's last response to my
        #outcome two turns ago
        if self.myLast[1] is not None:
            self.alpha[self.myLast[1]][last] += 1

        #predict opponent's move based on my last move
        predict = self.MultinomialDraw(self.myLast[0])
        res = self.Response[predict]

        #update myLast
        self.myLast[1] = self.myLast[0]
        self.myLast[0] = res

        return res

Basically I'm assuming that the opponent's response to my last output is a multinomial variable (weighted dice), one for each of my outputs, so there's a dice for "C", one for "N", and one for "D". So if my last roll was, for example, a "N" then I roll the "N-dice" to guess what their response would be to my "N". I begin with a Dirichlet prior that assumes that my opponent is somewhat "smart" (more likely to play the one with the best payoff against my last roll, least likely to play the one with the worst payoff). I generate the "expected" Multinomial distribution from the appropriate Dirichlet prior (this is the expected value of the probability distribution over their dice weights). I roll the weighted dice of my last output, and respond with the one with the best payoff against that dice outcome.
Starting in the third round, I do a Bayesian update of the appropriate Dirichlet prior of my opponent's last response to the thing I played two rounds ago. I'm trying to iteratively learn their dice weightings.
I could have also simply picked the response with the best "expected" outcome once generating the dice, instead of simply rolling the dice and responding to the outcome. However, I wanted to keep the randomness in, so that my bot is less vulnerable to the ones that try to predict a pattern.

ShiftingOptimalBot
class ShiftingOptimalBot:
    def __init__(self):
        # wins, draws, losses
        self.history = [0,0,0]
        self.lastMove = None
        self.state = 0
    def round(self, last):
        if last == None:
            self.lastMove = "C"
            return self.lastMove
        if last == self.lastMove:
            self.history[1] += 1
        elif (last == "C" and self.lastMove == "D") or (last == "D" and self.lastMove == "N") or (last == "N" and self.lastMove == "C"):
            self.history[0] += 1
        else:
            self.history[2] += 1

        if self.history[0] + 1 < self.history[2] or self.history[2] > 5:
            self.state = (self.state + 1) % 3
            self.history = [0,0,0]
        if self.history[1] > self.history[0] + self.history[2] + 2:
            self.state = (self.state + 2) % 3
            self.history = [0,0,0]

        if self.state == 0:
            self.lastMove = "N" if last == "D" else ("D" if last == "C" else "C")
        elif self.state == 1:
            self.lastMove = last
        else:
            self.lastMove = "C" if last == "D" else ("N" if last == "C" else "D")
        return self.lastMove

This bot uses LastOptimalBot's algorithm as long as it's winning.  If the other bot starts predicting it, however, it will start playing whichever move its opponent played last (which is the move that beats the move that would beat LastOptimalBot).  It cycles through simple transpositions of those algorithms as long as it continues to lose (or when it gets bored by drawing a lot).
Honestly, I'm surprised that LastOptimalBot is sitting in 5th as I post this.  I'm fairly certain this will do better, assuming that I wrote this python correctly.

Weighted Average
class WeightedAverageBot:
  def __init__(self):
    self.C_bias = 1/4
    self.N = self.C_bias
    self.D = self.C_bias
    self.prev_weight = 1/2
  def round(self, last):
    if last:
      if last == "C" or last == "N":
        self.D *= self.prev_weight
      if last == "C" or last == "D":
        self.N *= self.prev_weight
      if last == "N":
        self.N = 1 - ((1 - self.N) * self.prev_weight)
      if last == "D":
        self.D = 1 - ((1 - self.D) * self.prev_weight)
    if self.N <= self.C_bias and self.D <= self.C_bias:
      return "D"
    if self.N > self.D:
      return "C"
    return "N"

The opponent's behavior is modeled as a right triangle with corners for C N D at 0,0 0,1 1,0 respectively. Each opponent move shifts the point within that triangle toward that corner, and we play to beat the move indicated by the point (with C being given an adjustably small slice of the triangle). In theory I wanted this to have a longer memory with more weight to previous moves, but in practice the current meta favors bots that change quickly, so this devolves into an approximation of LastOptimalBot against most enemies. Posting for posterity; maybe someone will be inspired.

Tetragram
import itertools

class Tetragram:
    def __init__(self):
        self.history = {x: ['C'] for x in itertools.product('CND', repeat=4)}
        self.theirs = []
        self.previous = None

    def round(self, last):
        if self.previous is not None and len(self.previous) == 4:
            self.history[self.previous].append(last)
        if last is not None:
            self.theirs = (self.theirs + [last])[-3:]

        if self.previous is not None and len(self.previous) == 4:
            expected = random.choice(self.history[self.previous])
            if expected == 'C':
                choice = 'C'
            elif expected == 'N':
                choice = 'C'
            else:
                choice = 'N'
        else:
            choice = 'C'

        self.previous = tuple(self.theirs + [choice])
        return choice

Try to find a pattern in the opponent's moves, assuming they're also watching our last move.

HandshakePatternMatch
from .patternfinder import PatternFinder
import collections

class HandshakePatternMatch:
    def __init__(self):
        self.moves = [None]
        self.other = []
        self.handshake = [None,"N","C","C","D","N"]
        self.friendly = None
        self.pattern = PatternFinder()
    def round(self, last):
        self.other.append(last)
        if last:
            if len(self.other) < len(self.handshake):
                # still trying to handshake
                if self.friendly == False or self.other[-1] != self.handshake[-1]:
                    self.friendly = False
                else:
                    self.friendly = True
                move = self.handshake[len(self.other)]
                self.pattern.round(last)
            elif self.friendly == True:
                # successful handshake and continued cooperation
                move = self.pattern.round(last)
                if last == "C":
                    move = "C"
                elif last == self.handshake[-1] and self.moves[-1] == self.handshake[-1]:
                    move = "C"
                else:
                    self.friendly = False
            else:
                # failed handshake or abandoned cooperation
                move = self.pattern.round(last)
        else:
            move = self.handshake[1]
            self.pattern.round(last)
        self.moves.append(move)
        return move

Why pattern match yourself? Handshake and cooperate away.

import PatternFinder is cheating in my books.

@Blacksilver It gets done all the time in KOTH. It's no different than copying the code in an existing answer and using it. Robot Roulette: High stakes robot gambling had it happening all over the place to the point that bots would detect if their code was being called by an opponent and sabotage the return.

Alright then. TIL.

I'll do the crunching tomorrow.

Here's a perfect example of using other bots' code. Usually it comes down to "that guy worked out some tricky math, I want his results under these conditions." (My own entry did that to pretty good effect; UpYours was more scatter-shot in its approach).

@Blacksilver Still crunching? ;)

Hardcoded
class Hardcoded:
    sequence = "DNCNNDDCNDDDCCDNNNNDDCNNDDCDCNNNDNDDCNNDDNDDCDNCCNNDNNDDCNNDDCDCNNNDNCDNDNDDNCNDDCDNNDCNNDDCDCNNDNNDDCDNDDCCNNNDNNDDCNNDDNDCDNCNDDCDNNDDCCNDNNDDCNNNDCDNDDCNNNNDNDDCDNCDCNNDNNDDCDNDDCCNNNDNDDCNNNDNDCDCDNNDCNNDNDDCDNCNNDDCNDNNDDCDNNDCDNDNCDDCNNNDNDNCNDDCDNDDCCNNNNDNDDCNNDDCNNDDCDCNNDNNDDCDNDDCCNDNNDDCNNNDCDNNDNDDCCNNNDNDDNCDCDNNDCNNDNDDCNNDDCDNCNNDDCDNNDCDNDNCDDCNDNNDDCNNNDDCDNCNNDNNDDCNNDDNNDCDNCNDDCNNDCDNNDDCNNDDNCDCNNDNDNDDCDNCDCNNNDNDDCDCNNDNNDDCDNDDCCNNNDNNDDCNDNDNCDDCDCNNNNDNDDCDNCNDDCDNNDDCNNNDNDDCDNCNNDCNNDNDDNCDCDNNNDDCNNDDCNNDDNNDCDNCNDDCNNDDNDCDNNDNDDCCNCDNNDCNNDDNDDCNCDNNDCDNNNDDCNNDDCDCDNNDDCNDNCNNDNNDNDNDDCDNCDCNNNDNDDCDNCNNDDCDNNDCNNDDCNNDDCDCDNNDDCNDNCNNNDDCDNNDCDNDNCNNDNDDNNDNDCDDCCNNNDDCNDNDNCDDCDCNNNDNNDDCNDCDNDDCNNNNDNDDCCNDNNDDCDCNNNDNDDNDDCDNCCNNDNNDDCNNDDCDCNNDNNDDCNNDDNCNDDNNDCDNCNDDCNNDDNDCDNNDNDDCCNCDNNDCNNDNDDCNNDDNCDCDNNDCNNDNDDCDCDNNNNDDCNNDDNDCCNNDDNDDCNCDNNDCNNDDNDDCDNCNDDCNNNNDCDNNDDCNDNDDCDNCNNDCDNNDCNNDNDDNCDCNNDNDDCDNDDCCNNNNDNDDCNNDDCDCNNDNNDDCDCDNNDDC"
    def __init__(self):
        self.round_num = -1
    def round(self,_):
        self.round_num += 1
        return Hardcoded.sequence[self.round_num % 1000]

Just plays a hardcoded sequence of moves optimized to beat some of the top deterministic bots.

source: Stack Exchange

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

sort: votes


text:
Reciprocal copycats
Let \$A\$ be a positive integer consisting of \$n\$ decimal digits \$d_1,d_2,...,d_n\$. Let \$B\$ be another positive integer.
For the purpose of this challenge, we call \$A\$ a copycat of \$B\$ if there exists at least one list of positive integers \$p_1,p_2,...,p_n\$ such that:
$$\sum_{i=1}^{n}{{d_i}^{p_i}}=B$$
\$A\$ and \$B\$ are called reciprocal copycats if \$A\$ is a copycat of \$B\$ and \$B\$ is a copycat of \$A\$.
Example
\$526\$ and \$853\$ are reciprocal copycats because:
$$5^3 + 2^9 + 6^3 = 853$$
and:
$$8^3 + 5^1 + 3^2 = 526$$
The challenge
Given two positive integers \$A\$ and \$B\$, your task is to print or return a truthy value if \$A\$ and \$B\$ are reciprocal copycats or a falsy value otherwise.
Clarifications and rules

You may take \$A\$ and \$B\$ in any reasonable, unambiguous format (e.g. integers, strings, lists of digits, ...)
\$A\$ and \$B\$ may be equal. If a number is a reciprocal copycat of itself, it belongs to A007532.
Instead of truthy/falsy values, you may return two distinct consistent values.
For \$1\le A<1000\$ and \$1\le B<1000\$, your code must complete in less than one minute. If it's taking too much time for higher values, it must however be able to solve them in theory.
This is code-golf.

Test cases
Truthy:
1 1
12 33
22 64
8 512
23 737
89 89
222 592
526 853
946 961
7 2401
24 4224
3263 9734
86 79424
68995 59227
32028 695345

Falsy:
1 2
3 27
9 24
24 42
33 715
33 732
222 542
935 994
17 2401
8245 4153

Suggested case: 17 2401 -> false. I'm almost tripped on this.

Brachylog, 19 bytes
ẹ{∧ℕ₁;?↔^}ᵐ².+ᵐ↔?∧≜

Try it online!
Outputs true. or false.
Explanation
ẹ                     Split the numbers into lists of digits
 {       }ᵐ²          For each digit
  ∧ℕ₁                 Let I be a strictly positive integer
     ;?↔^                Compute the digit to the power I (which is unknown currently)
            .         Call . the list of those new numbers
            .+ᵐ       Their mapped sum results…
               ↔?     …in the reverse of the input
                 ∧≜   Find if there effectively are values for the numbers in . to satisfy
                        these relationships

@Arnauld Fixed at the cost of 1 byte. It failed because 2401 contained a 0 which didn't work with the way I checked that I was strictly positive (because I mapped it on both I and the digit to save bytes)

Husk, 17 bytes
Λλ€⁰mΣΠTṪ^ḣ√⁰d)De

Try it online!
Finishes all test cases under 1000 in about 11 seconds.
Explanation
Λλ€⁰mΣΠTṪ^ḣ√⁰d)De  Implicit inputs, say 12 and 33.
                e  Put into a list: [12,33]
               D   Duplicate: [12,33,12,33]
Λ                  Does this hold for all adjacent pairs:
                    (12,33 is checked twice but it doesn't matter)
                    For example, arguments are 33 and 12.
 λ            )     Anonymous function with arguments 33 (explicit) and 12 (implicit).
             d      Base-10 digits of implicit argument: [1,2]
          ḣ√⁰       Range to square root of explicit argument: [1,2,3,4]
        Ṫ^          Outer product with power: [[1,2],[1,4],[1,8],[1,16],[1,32]]
       T            Transpose: [[1,1,1,1,1],[2,4,8,16,32]]
      Π             Cartesian product: [[1,2],[1,4],...,[1,32]]
    mΣ              Map sum: [3,5,...,33]
  €⁰                Is the explicit argument in this list? Yes.

Why it works
If we have \$B = d_1^{p_1} + \cdots + d_n^{p_n}\$ where the \$d_i\$ are digits and \$p_i\$ are positive integers, then \$d_i^{p_i} \leq B\$ for all \$i\$, or equivalently \$p_i \leq \log_{d_i} B\$.
We can ignore the case \$d_i \leq 1\$, since exponentiating \$0\$ or \$1\$ does not change it.
In my program the search space is \$1 \leq p_i \leq \sqrt{B}\$ (to comply with the time restriction; I would use \$1 \leq p_i \leq B\$ otherwise), so if we have \$\lfloor \log_{d_i} B \rfloor \leq \lfloor \sqrt{B} \rfloor\$, then everything is fine.
If \$d_i \geq 3\$, this holds for all natural numbers \$B\$, so the only dangerous case is \$d_i = 2\$.
We have \$\lfloor \log_2 B \rfloor > \lfloor \sqrt{B} \rfloor\$ only for \$B = 8\$.
In this case \$2^3 = 8\$, but the search only considers exponents \$1\$ and \$2\$.
If the other number number \$A\$ contains the digit \$2\$, either it has other nonzero digits as well (so the exponent of \$2\$ cannot be \$3\$ in the sum), or \$A = 2 \cdot 10^k\$ for some \$k\$.
In the latter case, \$A\$ is not a power of \$8\$, so it cannot be a copycat of \$B\$ anyway, and the program correctly returns a falsy value regardless of the other computation.

Great answer which makes me want to learn Husk.  Two questions: 1. the implicit argument is mentioned again after you introduce it.  When is it used? 2. Could you elaborate on why this algorithm is equivalent to the one posed in the OP?

@Jonah 1. The digit function d takes the implicit argument. I clarified this in the explanation. 2. I added an argument for the program's correctness.

Thank you... btw, the part that had confused me was "where does the list of all ones come from?".... rereading i now realize this is merely because all the powers of 1 are just one....

Perl 6, 87 84 69 bytes
-15 bytes thanks to nwellnhof!
{!grep {!grep $^b,[X+] 0,|map (*X**1..$b.msb+1),$^a.comb},.[0,1,1,0]}

Try it online!
Anonymous code block that returns True or False.
Explanation:
{!grep {!grep $^b,[X+] 0,|map (*X**1..$b.msb+1),$^a.comb},.[0,1,1,0]}

{                                                                   }  # Anonymous code block
 !grep    # None of:
                                                          .[0,1,1,0]   # The input and the input reverse
       {!grep       # None of
                  [X+]       # All possible sums of
                       0,|   # 0 (this is to prevent single digit numbers being crossed with themself)
                          map                  ,$^a.comb   # Each digit mapped to
                              (*X**           )  # The power of
                                   1..$b.msb+1   # All of 1 to the most significant bit of b plus 1
                                                 # This could just be b+1, but time constraints...
              $^b,  # Is equal to b

@Arnauld, A Junction is Truthy/Falsey, as I've shown by using the boolify operator before outputting. I golfed it to something else anyway, though I could save a byte if I could output a truthy value for false and vice-versa...?

Thanks for the clarification. About the truthy/falsy inversion: I'd rather say no.

JavaScript (Node.js), 116 92 89 86 83 77 bytes
a=>b=>(G=(c,g,f=h=g%10)=>g?c>f&f>1&&G(c,g,h*f)||G(c-f,g/10|0):!c)(a,b)&G(b,a)

Try it online!
Expect input as (A)(B).

Strings are fine. (I've clarified the input format in the challenge.)

@Arnauld Oh I've just found a method not using string but also 108 bytes.

05AB1E, 26 22 bytes
εVтLIàgãεYSym}OIyKå}˜P

Takes the input as a list (i.e. [526,853]).
Try it online or verify most test cases in the range [1,999].
Similar as my old answer below, except that the [1,n] list is hardcoded to [1,100], and it creates the cartesian list twice, once for each input-mapping, which is the main bottleneck in terms of performance.

Old 26 bytes answer that's better for performance:
Z©bgL®gãUεVXεYSym}OsN>èå}P

In this version I traded in some bytes to make the performance a lot better so it can run [1,1000] with ease. Test cases containing numbers in the range [1,9999] are done in about a second on TIO. Test cases in the range [10000,99999] in about 10-15 seconds on TIO. Above that it will timeout.
Try it online or verify all test cases with numbers in the range [1,9999].
Explanation:
Z                 # Push the max of the (implicit) input-list (without popping)
                  #  i.e. [526,853] → 853
 ©                # Store it in the register (without popping)
  b               # Convert to binary
                  #  i.e. 853 → 1101010101
   g              # Take its length
                  #  i.e. 1101010101 → 10
    L             # Pop and push a list [1, n]
                  #  i.e. 10 → [1,2,3,4,5,6,7,8,9,10]
     ®            # Push the max from the register
      g           # Take its length
                  #  i.e. 853 → 3
       ã          # Cartesian product the list that many times
                  #  i.e. [1,2,3,4,5,6,7,8,9,10] and 3
                  #   → [[1,1,1],[1,1,2],[1,1,3],...,[10,10,8],[10,10,9],[10,10,10]]
        U         # Pop and store it in variable `X`
ε              }  # Map both values of the input list:
 V                # Store the current value in variable `Y`
  Xε    }         # Map `y` over the numbers of variable `X`
    Y             # Push variable `Y`
     S            # Convert it to a list of digits
                  #  i.e. 526 → [5,2,6]
      ym          # Take each digit to the power of the current cartesian product sublist
                  #  i.e. [5,2,6] and [3,9,3] → [125,512,216]
         O        # Take the sum of each inner list
                  #  i.e. [[5,2,6],[5,2,36],[5,2,216],...,[125,512,216],...]
                  #   → [13,43,223,...,853,...]
          s       # Swap to push the (implicit) input
           N>     # Push the index + 1
                  #  i.e. 0 → 1
             è    # Index into the input-list (with automatic wraparound)
                  #  i.e. [526,853] and 1 → 853
              å   # Check if it's in the list of sums
                  #  i.e. [13,43,223,...,853,...] and 853 → 1
                P # Check if it's truthy for both both (and output implicitly)
                  #  i.e. [1,1] → 1

Python 2, 102 bytes
lambda a,b:g(a,b)*g(b,a)
g=lambda a,b,e=1:b==a<1or(b>0<=b-e>=0<a)and(g(a/10,b-(a%10)**e)or g(a,b,e+1))

Try it online!

Haskell, 77 bytes
a#b=a!b&&b!a
a!b|a<1=b==0|b<1=b>1|1<2=or[div a 10!(b-mod a 10^e)|e<-[1..b+1]]

Try it online!

J, 56 bytes
h~*h=.4 :'x e.+/|:>,{x 4 :''<y&*^:(x&>)^:a:y''"+"."+":y'

Try it online!
Yay, nested explicit definition!
How it works
powers =. 4 :'<y&*^:(x&>)^:a:y'  Explicit aux verb. x = target, y = digit
                             y   Starting from y,
               y&*^:     ^:a:    collect all results of multiplying y
                    (x&>)        until the result is at least x
              <                  Box it.

h=.4 :'x e.+/|:>,{x powers"+"."+":y'  Explicit aux verb. x, y = two input numbers
                            "."+":y   Digits of y
                  x powers"+          Collect powers of digits of y under x
                 {            Cartesian product of each item
           +/|:>,             Format correctly and compute the sums
       x e.                   Does x appear in the list of sums?

h~*h  Tacit main verb. x, y = two input numbers
      Since h tests the condition in only one direction,
      test again the other way around (~) and take the AND.

J, 68 bytes
I thought J would perform quite well here, but it ended up being tougher than I expected and would love any suggestions for further golfing...
g=.#@#:@[
1 1-:[:(([:+./[=1#.]^"#.1+g#.inv[:i.g^#@])"."0@":)/"1],:|.

Try it online!
NOTE: we subtract 3 chars from the TIO count there since f=. on the main function doesn't count
ungolfed
1 1 -: [: (([: +./ [ = 1 #. ] ^"#. 1 + g #.inv [: i. g ^ #@]) "."0@":)/"1 ] ,: |.

Python 2, 149 147 143 139 132 118 108 107 106 105 bytes
lambda a,b:g(a,b)*g(b,a)
g=lambda a,b:any(g(a/10,b-(a%10)**-~i)for i in(a*b>0)*range(len(bin(b))))or b==0

Try it online!
-4 bytes, thanks to Vedant Kandoi

>0 can be removed. not a:a<1. b==0:b<1

@VedantKandoi Thanks, though b<0 doesn't work

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


text:
Cut-Off The Matrix
Task
Given is a square matrix of any dimension and any integer n.
Output all possible matrices(without duplicates) by removing columns and rows from the input matrix such that the determinant of these new matrices is n.
Rules
Output should include original if determinant of original is n.
Output should be all the chopped off matrices.
In case no output matrix is possible, return 0 or None or anything similar.
The input matrix will be at least of size 2x2 and all elements will be integers.
If n=1 empty matrix must also be in the output.
Test Cases
inputs:
[[1,0,5],
[1,0,5],
[1,2,4]],2

[[1, 3, 5],
[1, 3, 5],
[1, 45, 4]],0

[[1, 22, 5, 4],
[1, 3, 5, 5],
[1, 45, 4, 6],
[3, 4, 1, 4]],5

[[1, 22, 5, 4],
[1, -32, 51, 5],
[1, 45, 9, 0],
[3, 4, -1, -6]],-54

[[1, 22, 5, 4],
[1, -32, 51, 5],
[1, 45, 9, 0],
[3, 4, -1, -6]],1

outputs:
[[[2]], [[1, 0], [1, 2]]]

[[[1, 3], [1, 3]], [[1, 5], [1, 5]], [[3, 5], [3, 5]], [[1, 3, 5], [1, 3, 5], [1, 45, 4]]]

[[[5]], [[5, 4], [5, 5]]]

[[[1, 22], [1, -32]], [[9, 0], [-1, -6]]]

[[], [[1]], [[1, 4], [1, 5]]]

The shortest code wins.

+1 for making me think about why the determinant of the empty matrix really should be 1.

Jelly, 20 16 bytes
ZŒPZœcLƊ€ẎQÆḊ⁼¥Ƈ

Try it online!
Challenge finished. Unfortunately, my brain wasn't in its best mood, so Dennis pushed it until I finally managed to get here (you can see how it went). ~1 hour.

JavaScript (ES6), 246 238 196 192 bytes
Credits: the function \$D\$ is derived from this answer by edc65.
Takes input as (integer)(matrix). Prints the results to the console.
d=>g=m=>(F=(a,i)=>a.filter(_=>i--),m.map((_,i)=>m.map((_,j)=>g(F(m,i).map(r=>F(r,j))))),D=m=>m+m?m.reduce((n,[r],i)=>n+(i&1?-r:r)*D(F(m,i).map(r=>F(r,0))),0):1)(m)-d||g[m]||console.log(g[m]=m)

Try it online!
How?
Removing rows and columns
The helper function \$F\$ creates a copy of a given array \$a\$ with the \$i^\text{th}\$ item removed (0-indexed).
F = (a, i) => a.filter(_ => i--)

Computing the determinant
The recursive function \$D\$ computes the determinant of a matrix \$m\$, using Laplace expansion.
D = m =>                       // m = matrix
  m + m ?                      // if the matrix is not empty:
    m.reduce((n, [r], i) =>    //   for each value r at (0, i):
      n                        //     take the previous sum n
      + (i & 1 ? -r : r)       //     using the parity of i, either add or subtract r
      * D(                     //     multiplied by the result of a recursive call:
        F(m, i)                //       using m with the i-th row removed
        .map(r => F(r, 0))     //       and the first column removed
      ),                       //     end of recursive call
      0                        //     start with n = 0
    )                          //   end of reduce()
  :                            // else (the matrix is empty):
    1                          //   determinant = 1

Example:
$$m=\begin{bmatrix}\color{red}1&\color{red}2&\color{red}3\\\color{green}4&\color{green}5&\color{green}6\\\color{blue}7&\color{blue}8&\color{blue}9\end{bmatrix}$$
First iteration:
$$|m|=
\color{red}1\times\left|\begin{bmatrix}\color{green}5&\color{green}6\\\color{blue}8&\color{blue}9\end{bmatrix}\right|
-\color{green}4\times\left|\begin{bmatrix}\color{red}2&\color{red}3\\\color{blue}8&\color{blue}9\end{bmatrix}\right|
+\color{blue}7\times\left|\begin{bmatrix}\color{red}2&\color{red}3\\\color{green}5&\color{green}6\end{bmatrix}\right|$$
which eventually leads to:
$$1\times(5\times9-8\times6)-4\times(2\times9-8\times3)+7\times(2\times6-5\times3) = 0$$
Main function
We recursively remove rows and columns from the original matrix \$m\$ and invoke \$D\$ on all resulting matrices, printing those whose determinant is equal to the expected value \$d\$.
d =>                           // d = expected determinant value
  g = m =>                     // g = recursive function taking the matrix m,
    (                          //     also used to store valid matrices
      m.map((_, i) =>          // for each i in [0 ... m.length - 1]:
        m.map((_, j) =>        //   for each j in [0 ... m.length - 1]:
          g(                   //     do a recursive call with:
            F(m, i)            //       the i-th row of m removed
            .map(r => F(r, j)) //       the j-th column of m removed
          )                    //     end of recursive call
        )                      //   end of inner map()
      ),                       // end of outer map()
      D                        // invoke D ...
    )(m)                       // ... on m
    - d                        // provided that the result is equal to d
    || g[m]                    // and provided that this matrix was not already printed,
    || console.log(g[m] = m)   // print m and store it in the underlying object of g

R, 129 bytes
f=function(m,n,o={},z=nrow(m)){for(i in r<-1:z)for(j in r)o=c(o,if(round(det(m))==n)list(m),if(z)f(m[-i,-j,drop=F],n));unique(o)}

Try it online!
Recursive function returning a list of submatrices. Outputs NULL for no solution. It is a bit unfortunate that the determinant value has to be explicitly rounded (otherwise some tests fail due to numerical imprecision), but at least we have a built-in for calculating it.

Here's a case where the growing object o seems like it must be explicitly initialized to NULL and the built-in abuse of F or T won't work.


text:
Terms of the EKG sequence
Introduction
The EKG sequence begins with 1 and 2, then the rule is that the next term is the smallest positive integer not already in the sequence and whose common factor with the last term is greater than 1 (they are not coprimes).
The first terms are:

1, 2, 4, 6, 3, 9, 12, 8, 10, 5, 15, ...

It's called EKG because the graph of its terms is quite similar to an EKG.
It's sequence A064413 in the OEIS.
Challenge
You have to write a function which takes an integer n as input and outputs how many of the n first terms of the sequence are greater than n.
As the sequence's rule begins with the third term, the input integer has to be greater or equal to 3. For example, given input 10 the output is 1 because the 7th term is 12 and none of the other first ten terms exceed 10.
Test cases

3  ->  1
10 ->  1
100 -> 9
1000 -> 70

Rules

For integers lower than 3, the function may output 0 or an error code.
No other particular rules except: it's code golf, the shorter the better!

Can we use 0-indexing, with 1 being the 0th term of the sequence and therefor making, for example, 15 the 10th term, rather than 5?

@Shaggy I think it's fair to use this as a mathematical way, but actually it will change the result of test cases and indeed the asked function in itself. Thus I think you should'nt be allowed to do so. Sorry.

https://oeis.org/A064413/graph - OEIS can write graphs? Neat.

Jelly, 20 19 18 bytes
S‘gṪ’ɗƇḟ¹Ṃṭ
1Ç¡>¹S

This is a full program.
Try it online!
How it works
1Ç¡>¹S       Main link. Argument: n (integer)

1            Set the return value to 1.
 Ç¡          Call the helper link n times.
   >¹        Compare the elements of the result with n.
     S       Take the sum, counting elements larger than n.

S‘gṪ’ɗƇḟ¹Ṃṭ  Helper link. Argument: A (array or 1)

S            Take the sum of A.
 ‘           Increment; add 1.
     ɗƇ      Drei comb; keep only elements k of [1, ..., sum(A)+1] for which the
             three links to the left return a truthy value.
  g              Take the GCD of k and all elements of A.
   Ṫ             Tail; extract the last GCD.
    ’            Decrement the result, mapping 1 to 0.
       ḟ¹    Filterfalse; remove the elements that occur in A.
         Ṃ   Take the minimum.
          ṭ  Tack; append the minimum to A.

Note that the generated sequence is \$[1, \mathbf{0}, 2, 4, 6, 3, 9, 12, 8, 10, 5, 15, \dots]\$. Since calling the helper link \$n\$ times generates a sequence of length \$n + 1\$, the \$0\$ is practically ignored.

Perl 6, 66 63 59 58 bytes
-4 bytes thanks to Jo King
{sum (1,2,{+(1...all *gcd@_[*-1]>1,*∉@_)}...*)[^$_]X>$_}

Try it online!
Too slow on TIO for n = 1000.

@JoKing After I realised that first &f,1..* can be rewritten as +(1...&f), your junction trick helped after all.

Husk, 16 bytes
#>¹↑¡§ḟȯ←⌋→`-Nḣ2

Try it online!
Explanation
#>¹↑¡§ḟȯ←⌋→`-Nḣ2  Implicit input, say n=10
              ḣ2  Range to 2: [1,2]
    ¡             Construct an infinite list, adding new elements using this function:
                   Argument is list of numbers found so far, say L=[1,2,4]
             N     Natural numbers: [1,2,3,4,5,6,7...
           `-      Remove elements of L: K=[3,5,6,7...
      ḟ            Find first element of K that satisfies this:
                    Argument is a number in K, say 6
     §    →         Last element of L: 4
         ⌋          GCD: 2
       ȯ←           Decrement: 1
                    Implicitly: is it nonzero? Yes, so 6 is good.
                  Result is the EKG sequence: [1,2,4,6,3,9,12...
   ↑              Take the first n elements: [1,2,4,6,3,9,12,8,10,5]
#                 Count the number of those
 >¹               that are larger than n: 1

JavaScript (ES6), 107 106 105 bytes
f=(n,a=[2,1],k=3)=>a[n-1]?0:a.indexOf(k)+(C=(a,b)=>b?C(b,a%b):a>1)(k,a[0])?f(n,a,k+1):(k>n)+f(n,[k,...a])

Try it online!
How?
The helper function \$C\$ returns true if two given integers are not coprime:
C = (a, b) => b ? C(b, a % b) : a > 1

The array \$a\$ is initialized to \$[2,1]\$ and holds all values that were encountered so far in reverse order. Therefore, the last value is always \$a[0]\$.
To know if \$k\$ qualifies as the next term of the sequence, we test whether the following expression is equal to \$0\$:
a.indexOf(k) + C(k, a[0])

a.indexOf(k) is equal to either:

\$-1\$ if \$k\$ is not found in \$a\$
\$0\$ if \$k\$ is equal to the last value (in which case it's necessarily not coprime with it)
some \$i\ge 1\$ otherwise

Therefore, a.indexOf(k) + C(k, a[0]) is equal to \$0\$ if and only if \$k\$ is not found in \$a\$ and \$k\$ is not coprime with the last value (\$-1+true=0\$).

Haskell, 89 82 bytes
Edit: -7 bytes thanks to @H.PWiz
f l=[n|n<-[3..],all(/=n)l,gcd(l!!0)n>1]!!0:l
g n=sum[1|x<-iterate f[2]!!(n-2),x>n]

Try it online!

82 bytes

@H.PWiz: ah, that's clever. Thanks!

APL (Dyalog Unicode), 39 bytesSBCS
-2 bytes thanks to ngn, -1 byte by using proper conditional checking.

{+/⍵<⍵⍴3{(1=⍺∨⊃⌽⍵)∨⍺∊⍵:⍵∇⍨⍺+1⋄⍵,⍺}⍣⍵⍳2}

Try it online!

⍣ passes its own left argument to the operand function, so there's no need for ∘. also, ⍵ won't bind with the thing on the right as it starts with a function (⍳), so there's no need for ⊢.

MATL, 29 bytes
qq:2:w"GE:yX-y0)yZdqg)1)h]G>z

Try it online!
Explanation:
	#implicit input, n, say 10
qq:	#push 1:8
2:	#push [1 2]. Stack: {[1 .. 8], [1 2]}
w	#swap top two elements on stack
"	#begin for loop (do the following n-2 times):
 GE:	#push 1...20. Stack: {[1 2], [1..20]}
 y	#copy from below. Stack:{[1 2], [1..20], [1 2]}
 X-	#set difference. Stack: {[1 2], [3..20]}
 y0)	#copy last element from below. Stack:{[1 2], [3..20], 2}
 yZd	#copy from below and elementwise GCD. Stack:{[1 2], [3..20],[1,2,etc.]}
 qg)	#select those with gcd greater than 1. Stack:{[1 2], [4,6,etc.]}
 1)	#take first. Stack:{[1 2], 4}
 h	#horizontally concatenate. Stack:{[1 2 4]}
 ]	#end of for loop
G>z	#count those greater than input
	#implicit output of result

please can you explain why do you double the input (with GE:)?

@david I think empirically I noticed that $a(n)\leq 2n$ but I don't have a proof, so I originally used $a(n)\leq n^2$, which timed out on the $n=1000$ test case, so I switched it back to test that, and left it in. I'm still not sure about either bound, but it seems to work, so I may try to come up with a proof. A while loop would be much messier in MATL so I was trying to avoid it.

JavaScript, 93 91 87 bytes
Throws an overflow error for 0 or 1, outputs 0 for 2.
n=>(g=x=>n-i?g[++x]|(h=(y,z)=>z?h(z,y%z):y)(x,c)<2?g(x):(g[c=x]=++i,x>n)+g(2):0)(i=c=2)

Try it online

APL(NARS), chars 121, bytes 242
∇r←a w;i;j;v
r←w⋄→0×⍳w≤2⋄i←2⋄r←⍳2⋄v←1,1,(2×w)⍴0
j←¯1+v⍳0
j+←1⋄→3×⍳1=j⊃v⋄→3×⍳∼1<j∨i⊃r⋄r←r,j⋄i+←1⋄v[j]←1⋄→2×⍳w>i
r←+/w<r
∇

test in less one minute here in running time:
  a¨3 10 100 1000 2000
1 1 9 70 128

Natural there is no check for type and for range...

Japt, 23 21 bytes
@_jX ªAøZ}f}gA=ì)Aè>U

Try it
@_jX ªAøZ}f}gA=ì)Aè>U
                          :Implicit input of integer U
             A            :10
               ì          :Digit array
              =           :Reassign to A
@          }g             :While the length of A < U+1, take the last element as X,
                          :pass it through the following function & push the result to A
 _       }f               :  Find the first integer Z >= 0 that returns falsey
  jX                      :    Is Z co-prime with X?
     ª                    :    OR
      AøZ                 :    Does A contain Z?
                )         :End loop
                 Aè>U     :Count the elements in A that are greater than U

Python 3, 153 bytes
import math
def f(n):
 l=[1];c=0
 for _ in range(n-1):l+=[min(*range(2,n*4),key=lambda x:n*8if x in l or math.gcd(x,l[-1])<2else x)];c+=l[-1]>n
 return c

Try it online! (Warning: Takes ~30 seconds to evaluate)