text:
I reverse the source code, you negate the input!
Blatant rip-off of a rip-off. Go upvote those!
Your task, if you wish to accept it, is to write a program/function that outputs/returns its integer input/argument. The tricky part is that if I reverse your source code, the output must be the original integer negated.
Examples
Let's say your source code is ABC and its input is 4. If I write CBA instead and run it, the output must be -4.
Let's say your source code is ABC and its input is -2. If I write CBA instead and run it, the output must be 2.
An input of 0 may give 0 or -0, however, if you do support signed zero, -0 should give 0.

Why do we need a copy of the same question?

@Christian That one outputs a constant number (and its negation) whereas this one has to take input and return/negate it. A very different job in a lot of languages.

A yes, now I see the difference. One needs to read VERY carefully

If using a structured language like C#, are you just reversing lines?

@PerpetualJ No, look at the source like list of characters, some of which are line breaks.

J, 3 bytes
-&0

Try it online!
-&0 is "argument minus 0"
0&- is "0 minus argument"

this is really quite nice :)

Clever, I didn't think of that one, but rather ][- etc.

PowerShell, 18 14 bytes
$args#"sgra$"-

Try it online! !enilno ti yrT
First of the trivial comment-abuse answers

Oh, God. Not this again.

"First of the trivial comment-abuse answers" Redeemed by the TIO links!

x86 machine code, 3 bytes
C3 D8 F7

The above bytes of code define a function that is a no-op: it simply returns control to the caller. That function is followed by two garbage bytes that will not be executed, since they come after a return—they are in "no man's land". In assembler mnemonics:
ret                     ; C3
fdiv  st(0), st(7)      ; D8 F7

Okay, so now some troll comes by and reverses the order of the bytes:
F7 D8 C3

These bytes now define a function that takes an integer argument in the EAX register, negates it, and returns control to the caller. In assembler mnemonics:
neg  eax     ; F7 D8
ret          ; C3

So…that was simple. :-)
Note that we can make the "negation" instruction be anything we want, since it is never executed in the "forward" orientation and only executed in the "reversed" orientation. Therefore, we can follow the same pattern to do arbitrarily more complicated stuff. For example, here we take an integer argument in a different register (say, EDI, to follow the System V calling convention commonly used on *nix systems), negate it, and return it in the conventional EAX register:
C3      ret
D8 F7   fdiv  st(0), st(7)      ;  \ garbage bytes that
F8      clc                     ;  | never get executed,
89      .byte 0x89              ;  / so nobody cares

  ↓ ↓
89 F8   mov  eax, edi
F7 D8   neg  eax
C3      ret

JavaScript, 11 bytes
n=>n//n->=n

Try it Online! | Reversed

Jelly, 2 bytes
oN

Try it online! and its reverse.
oN - (input) OR ((input) negated)

No - ((input) negated) OR (input)

Heh, you can also do ḷN, no need for the OR logic. :D

Na, words give aN aesthetic effect :)

Haskell, 8 bytes
Anonymous identity function, turning into subtraction from 0 when reversed.
id--)-0(

Try it online!
Reversed:
(0-)--di

Try it online!

You’ve managed to break the code highlighting with your reversed version!

@Tim Curious. Testing suggests it fails when a comment starts right after a right parenthesis.

Whitespace, 48 bytes
S S S N
S N
S T N
T   T   T   T   T   T   N
S T N
N
N
T   S N
T   N
S S T   N
T   T   S S T   T   T   T   T   N
T   S N
S N
S S S

Letters S (space), T (tab), and N (new-line) added as highlighting only.
Minor modification of my Whitespace answer for the I reverse the source code, you negate the output! challenge.
Try it online or try it online reversed (with raw spaces, tabs and new-lines only).
Explanation:
Utilizing the Exit Program builtin being a short palindrome NNN.
The regular program will:
SSSN   # Push 0 to the stack
SNS    # Duplicate it
TNTT   # Read STDIN as integer, and store it at heap address 0
TTT    # Retrieve the input from heap address 0, and push it to the stack
TNST   # Pop and print the top of the stack as number
NNN    # Exit the program, making everything after it no-ops

The reverse program will:
SSSN   # Push 0 to the stack
SNS    # Duplicate it
TNTT   # Read STDIN as integer, and store it at heap address 0
TTT    # Retrieve the input from heap address 0, and push it to the stack
SSTTN  # Push -1 to the stack
TSSN   # Multiply the top two values on the stack together
TNST   # Pop and print the top of the stack as number
NNN    # Exit the program, making everything after it no-ops

Small additional explanation of pushing a number:

First S: Enable Stack Manipulation
Second S: Push a number to the stack
S or T: Positive/negative respectively
Some S/T followed by a trailing N: number in binary, where S=0 and T=1

I.e. SSTTSTSN pushes -10. For the 0 we don't need an explicit S=0, so simply SSSN or SSTN is enough.

R, 23 bytes
I decided to give it a go without the comment trick.
Forward
`+`=scan;""+-0;nacs=`+`

Try it online!
Reverse
`+`=scan;0-+"";nacs=`+`

Try it online!
In the forward version + is acting a binary operator, and - is a unary operator.
In the reverse the + becomes unary and the - is binary. So scan function takes the arguments: file="" which means stdin and what=0, which are also defaults. So when the + is unary the first argument is on the right, when it is binary the first argument is on the left.
The
;nacs=`+`

part of the code does nothing really useful, so in a sense my code is not really very much more valid than using the comment trick.

This is very smart (+1). We often redefine the R operators to golf bytes, but I think this is the first time I have seen + redefined to be used as both unary and binary. It took me a minute to understand how this was parsed… No other operator name would have done the job.

C (clang), 23 bytes
f(*x){}//};x*-=x*{)x*(g

Try it online!

Labyrinth / Hexagony, 6 bytes
Labyrinth:
?!@!`?

Try it online! and its reverse.
Hexagony:
?!@!~?

Try it online! and its reverse.
How?
?       - take a signed integer
(` / ~) - negate
!       - output top-of-stack / current-memory-edge
@       - exit

Perl 6 / Raku, 3 bytes
*-0

Try it online!
Creates a Whatever code block.  Read in normally its standard block equivalent is -> \x {x - 0}, but in reverse it becomes -> \x {0 - x}.

Python 3, 22 bytes
lambda x:x#x-:x adbmal

Try it online!
A lambda which implements the identity function (or negation)

Gaia, 2 bytes
_@

Try it online!
_	| implicit push input and negate
 @	| push next input OR push last input (when all inputs have been pushed)
	| implicit print TOS

Reversed:
@	| push input
 _	| negate
	| implicit print TOS

Brain-Flak, 7 bytes
#)]}{[(

Try it online!
Reversed:
([{}])#

Try it online!
Note: Only works in interpreters that support comments (e.g. works in Rain-Flak, but not in BrainHack)

If we also swap opening/closing brackets instead of just reversing the bytes we can do this in 8 bytes without using comments:
({}[{}])

Try it online!
Try it reversed!

Is this undefined behaviour abuse? I don't think Brain-Flak specification allows such parenthesis.

@TwilightSparkle The # starts a comment, so the parenthesis in the original version are ignored.

Oh yeah, I forgot! But it only works in Rain-Flak then(It's the official intepreter though). You will probably need to mention it?

@TwilightSparkle added a note for clarification. Thanks.

Fun little challenge: Can you do this without comments if you also swap opening/closing brackets instead of just reversing?

@DJMcMayhem My first idea came out to 10 bytes: ({}<>[{}])

I came up with nearly the same thing: ({}[{}])

Yep. Just realized the <> doesn't do anything

Perl 5 (-p), 7 6 bytes
-1 thanks to @primo
$_*=$#

TIO
A comment doesn't change input
#1-=*_$

Negate the input
$_*=-1#

TIO

-1: $_*=$# TIO. Note that the # must be the very last byte of the program, otherwise it will be interpreted as the variable $#, rather than the last index of the array with name .

however i don't understand how it works because trying to print $# gives either an error (if # is not the last character) or nothing

Seems to only work with -p or -n. I suspect the boilerplate has something to do with it...

@primo It works because -p/-n adds a ; after the code. Which means that $# is actually $#;: the size of the array @;. If the size of @; changes, the result isn't correct anymore (TIO). Anyway, this is super clever, well done! :)

that's the explanation could be seen with perl -MO=Deparse -p <(echo -n '$_*=$#'), because it seems perl -MO=Deparse -pe '$_*=$#' adds a newline

R, 14 bytes
scan()#)(nacs-

Try it online!
A full program that reads a number, or reads and negates a number. The reverse functionality is protected by an inline comment

Your brackets are the wrong way around in the commented part.

@AaronHayman thanks!

Backhand, 6 5 bytes
I@-Ov

Try it online! Try it doubled!
Made a little complex due to the nature of the pointer in Backhand. I don't think it's possible to get any shorter haha, turns out I was wrong. This duplicates no instruction and reuses both the input, output and terminate commands between the two programs. Now I think it is optimal, since you need all of the IO-@ commands to work, and in a 4 byte program you can only execute two of those commands.
Explanation:
The pointer in Backhand moves at three cells a tick and bounces off the boundaries of the cell, which means the general logic is overlapping. However you can manipulate this speed with the v and ^ commands.
The original program executes the instructions IO-@, which is input as number, output as number, subtract, terminate. Obviously the subtract is superfluous. In the code these are:
I@-Ov
^  ^    Reflect
  ^     Reflect again
 ^

The reversed program executes v-I-vO-@. The v reduces the pointer steps between ticks, and the - subtracts from the bottom of the stack, which is implicitly zero. The extra - commands do nothing. The program executes like
vO-@I
v       Reduce pointer speed to 2
  -     Subtract zero from zero
    I   Get input as number and reflect off boundary
  -     Subtract input from zero
v       Reduce pointer speed to 1
 O      Output as number
  -     Subtract zero from zero
   @    Terminate

MarioLANG, 22 bytes
;:
=#
:)!
--
<(
"
[>
;

Try it online!
He just inputs and outputs the number before he falls to EOF
reversed:
;
>[
"
(<
--
!):
#=
:;

Try it online!
He loops until the input value is 0 and the output value is -input, the he says the number.

Haskell, 12 bytes
f=id;x-0=x f

Try it online! Reverse:
f x=0-x;di=f

Try it online!
Not as short as Ørjan Johansen's answer, but without comments.

Python 3, 22 14 bytes
int#__bus__. 0

Try it online!
Uses the int class's constructor and a built-in pseudo-private method.

Huh. Why is the space before the attribute mandatory?

@JoKing 0. would be interpreted as a number, which is followed by a symbol

APL (Dyalog Unicode), 13 3 bytes
-∘0

Try it online!
Trivial answer. Returns arg or ¯arg.
Saved 10 bytes by not being dumb (thanks Adám).
Altered the resulting 3-byter to a more fitting function.

Whoa, this can be done trivially in three bytes!

Interestingly, you already have a 3-byte answer embedded as a substring of this.

@Adám yeah, I knew there was a simple answer in there somewhere. Thanks.

Wolfram Language (Mathematica), 9 bytes
1&0+#-0&1

Try it online!
Forward: read ((1)&*0+#-0)&*1=#&
Backward: read ((1)&*0-#+0)&*1=-#&

Excel VBA, 12
?[A1]']1A[-?

Reversed:
?-[A1]']1A[?

Input is cell A1 of the ActiveSheet.  Comments still work in the Immediate Window :)

I get what you are going for here, but I am pretty sure that you meant to answer ?[A1]']1A[-?

@TaylorScott A good catch, oops

Batch, 34 bytes
@ECHO.%1 2>MER@
@REM>2 1%=-aa/TES@

Echoes (ECHO.) the input (%1). The rest of the first line technically redirects STDERR to a file called MER@, but this isn't impactful.
Second line is commented out (REM...).
Reversed
@SET/aa-=%1 2>MER@
@REM>2 1%.OHCE@

Uses the arithmetic mode of the set command (SET /a) to subtract (-=) the input (%1) from an undefined variable (a) which is equivalent to 0 - input. Again, the rest of the first line technically redirects STDERR to a file called MER@, but this isn't impactful.
Second line is commented out (REM...).

This looks interesting. Care to explain?

@Adám Added an explanation, and also realised that I had the programs around backwards.

Triangular, 8 7 bytes
$%%.|.$

Try it online!
Ungolfed:
   $           | $: Read an Integer
  % %          | %: Output it
 . | .
$

Reversed:
$.|.%%$

Try it online!
Previous Version (8 bytes):
$.%..|.$

05AB1E, 2 bytes
(I

Try it online!
Reversed
(    negates nothing
  I  pushes input

I    pushes input
  (  negates input

It is supposed to only negate the input in one direction, leaving it as-is in the other. Clearly, 1-character solution cannot be valid.

My bad, I misunderstood

Your answer has a couple mistakes. First of all, the explanation for (I is slightly flawed: it doesn't negate nothing, it negates the (implicit) input. But pushing the input with I means the output is the input instead. Your other problem is that both links you put link to I(.

Befunge-98 (FBBI), 6 bytes
&.@.-&

Try it online! Try it reversed!

Klein, 2 bytes
Works in all 12 topologies!
@-

Try it online!
Reverse
-@

Try it online!
- negates the input and @ ends the program

Oh come on. This question seems to be made for some clever flipping on the Möbius strip or so, and you submit an answer that doesn't depend on the topology? Meh.

Ah, I hadn't seen that: https://codegolf.stackexchange.com/a/192983/2183

Turing Machine Language, 39 bytes
The Positive
1 r - _ 0
0 l * * 0
0 - _ l 0
0 _ _ r 0

The Negative
0 r _ _ 0
0 l _ - 0
0 * * l 0
0 _ - r 1

This one was a bit trickier than I thought, mostly because I had to get past my prejudices of having code that runs with 'compile' errors.

><>, 5 4 bytes
n-r0

uses stack initialisation with the -v option, put your input variable there.
Try it online!
Or try the reversal
Explanation
n       Prints whatever is on the stack as a number
 -      Subtract the top 2 elements on the stack.
        There aren't 2 elements, so it crashes.
  r0    Never gets executed

or reversed:

0       Push a 0 onto the stack
 r      reverse the stack (now 0, -v)
  -     Subtract top 2 elements and push result (0-v, ie negated)
   n    Print as number
        The code wraps around and executes again.
        It crashes on the - as there is only one
        item on the stack: 0.

Stack Cats -mn, 2 bytes
-X

Try it online!
Try the reverse!
Explanation
Turns out this is actually a lot easier than the previous challenge in Stack Cats. The full program (after applying -m) here is -X-. X is used to swap the stacks left and right of the tape head, i.e. it doesn't affect the initial stack at all, so we can ignore it. But then the program is effectively just -- (negate the top of the stack twice), which does nothing.
For the inverse program, applying -m gives X-X. Again, X does nothing, so the program is effectively just -, which negates the top of the stack.
The only other 2-byte solution is -=, but it's virtually the same. The only difference is that = swaps only the tops of the adjacent stacks, not the entire stacks.
But again, using -m feels a bit like cheating, so below is a solution that uses a fully mirrored program.

Stack Cats -n, 7 bytes
:I<->I:

Try it online!
Try the reverse!
Explanation
The considerations from the previous answer still apply: any valid solution needs to use the paired characters and I. The six possible solutions (included in the TIO link) are all virtually the same. - and _ are equivalent in this program, and : can be replaced by | or T (which do the same for non-zero inputs and coincidentally also work for zero inputs). I've just picked this one to explain because it's easiest.
So remember that the initial stack holds the input on top of a -1 (on top of infinitely many zeros) whereas all the other stacks along the tape only hold zeros. Stack Cats also has the property that any even-length program does nothing (provided it terminates, but we can't use loops for this challenge anyway). The same is then obviously true for any odd-length program whose centre character does nothing... let's see:
:    Swap the input with the -1 below.
I    Move the -1 one stack to the left and turn it into +1.
<    Move another stack left (without taking the value).
-    Negate the zero on top of that stack (i.e. do nothing).

Therefore, the second half of the program exactly undoes the first half and we end up with the input on top of a -1 again.
The inverse program is :I>-<I:. Let's see how that changes things:
:    Swap the input with the -1 below.
I    Move the -1 one stack to the left and turn it into +1.
>    Move one stack right, i.e. back onto the initial stack which still holds the input.
-    Negate the input.
<    Move back to the left where we've parked the 1.
I    Move that 1 back onto the initial stack and turn it back into a -1.
:    Swap the -1 below the negated input to act as an EOF marker.

Brachylog, 2 bytes
&ṅ

Brachylog implicitly inputs from the left and outputs from the right.
& ignores anything to the left and passes the input to the function rightwards.
ṅ constrains each side of it to be negated versions of each other.
Try it online

W, 3 2 bytes
Pretty much a port of the Keg answer. Might get around to implement an implicit return.
%_

Explanation
   % Since there is nothing on-stack, return the input.
%_ % Start a comment

noitanalpxE
_  % Negate input & return
 % % Start a comment

Vyxal, 2 bytes
#N

Try it Online!
!enilnO ti yrT
#N is a comment, so nothing happens and the input is outputted unchanged.
N# negates the input, which is then outputted implicitly.
If you’re not a fan of using comments for something like this, the # can be replaced with any of ? , ₴ ⁰, etc.

Alice, 15 bytes
/O\ /I@
@I/R\O/

Try it online!
!enilno ti yrT
Flattened
Original I O@, reads from the input, output
Reversed IRO@, reads from the input, negate, output
The mirrors switches in and out of ordinal mode, which execute the code in diagonal

Alice, 11 bytes
\ X'@
/I-O/

Try it online!
!enilno ti yrT
Operates entirely within ordinal mode. The negation is done by taking string symmetric difference X with the single-char string "-". The code path IXO is common; when reversed, '- is also stepped, pushing "-" before the input.

Japt, 3 bytes
TnU

Try it | Reversed
Same method as my earlier solution, with T being 0 and U being the input.

V (vim), 5 bytes
É-ó--

Try it online!
Hexdump:
00000000: c92d f32d 2d                             .-.--

C++ (gcc), 29 bytes
#define f(x)x//x-)x(g enifed#

Try it online!
Fixed issue brought up by @Nick Kennedy

This is shown the wrong way round; it should return the input when called without reversing the code.

Is #define f//- f enifed# (call as f x) cheating? ;)

Stax, 2 bytes
pN

Run and debug it

Retina 0.8.2, 13 12 bytes
-*$1#$
)^(|-

Try it online! It's impossible for the first line to match anything, so nothing happens. In reverse:
-|(^)
$#1$*-

Try it online! Explanation: Either a leading (implicitly) - or a leading empty string is matched. This is replaced with - repeated according to the number of empty strings that were matched.
Edit: Saved 1 byte thanks to @MartinEnder (although, cunningly, the reversed original worked with floating-point numbers in scientific notation). As he points out, Retina 1 would be a further byte shorter as its syntax for * is slightly different and does not require the adjacent $ (and it would therefore also modify illegal inputs such as -1# which this version ignores).

I don't think you need the ^ at the end. Also, Retina 1 would save a byte on $*.

Ruby -p , 7+1 = 8 bytes
#-?<<>$

Try it online!
Reverse:
Try it online!

PHP, 20 bytes
<?=$argn;#;ngra$-=?<

Try it online!

MathGolf, 4 bytes
*b╘k

Try it online or try it online reversed.
Explanation:
Regular:
*     # Multiply the (implicit) input with the (implicit) input
      #  STACK: [input**2]
 b    # Push -1
      #  STACK [input**2, -1]
  ╘   # Discard everything on the stack
      #  STACK: []
   k  # Push the input as integer
      #  STACK: [input]
      # (output the entire stack joined together as result)

Reversed:
k     # Push the input as integer
      #  STACK: [input]
 ╘    # Discard everything on the stack
      #  STACK: []
  b   # Push -1
      #  STACK: [-1]
   *  # Multiple the (implicit) input with this -1
      #  STACK: [-input]
      # (output the entire stack joined together as result)

And to answer your question: no, MathGolf does not have a 1-byte negate for integers. There is ~ for -n-1, but unfortunately nothing for -n (so *b could alternatively be )~ for the same byte-count).

Japt, 3 bytes
n U

Try it
Try it reversed
3 bytes
nÎN

Try it
Try it reversed

Cubix, 5 bytes
@IO\n

Try it online!
Try it reversed!

Scala, 6 bytes
+_//_-

Try it online!
Unfortunately a function can't just contain a _ to return the first argument, but using unary_+ will return the value unchanged.
Once flipped, the code is -_ which does a unary_- on the first argument, which flips the sign.

Shouldn't this be _//_-? However, _-0 seems like a valid solution.

@Adám It should be +_//_-. Unfortunately can't have _ as the body of the function, but doing +_ returns the value unchanged. Thanks for point it out!

Gol><>, 4 bytes
Ih-I

One byte golfed off courtesy of JoKing
Try it online!

@JoKing Thank you very much, is that a negate operation? I honestly forgot that there was one

@JoKing Ohhhhh, I didn't know that, thank you very much for enlightening me on that operation

Runic Enchantments, 4 bytes
i@Zi

Try it online! Try it reversed!
Its the answer I originally wrote on the other challenge when I misread the description.

Perl 5 - 12 Bytes
say$_#_$-yas

Reversed
say-$_#_$yas

Abides by the -0 rule.
Does require the -nE flags on execution.

BitCycle -U, 14 bytes
<  ^
v/?!
+~ +

Try it online!
And reversed
+ ~+
!?/v
^  <

Try it online!
The -U flag translates input/output to signed Unary, i.e. unary 1s with a zero in front if the number is negative. The first program just pipes input (?) to the output (!) directly right of it.
The reverse instead takes only the first bit of the number with the / command and dupnegs (~). If it is a 1 then it sends 0 left and 1 right, where the +s redirect them to join the flow to the output. If  the first bit is 0 instead, the 0 goes right and the 1 goes left, and the + redirect them away from the output. All in all, this has the behaviour of stripping a leading zero if the input has one, otherwise prepending a zero if it doesn't, which means inverting the sign of the input.

BitCycle -U, 15 bytes
First, a word about the -U flag. Internally, BitCycle only deals in 1's and 0's, so to allow working with decimal integers, it has flags to convert decimal input to unary. In particular, -U allows for signed integers by adding a 0 to the front of any nonpositive integer's unary representation: 4 is 1111, -4 is 01111, and 0 is 0. The same transformation is applied in reverse to the output, with the convenient addition that empty output is treated as 0.
Forward
^>

?!+?
 <0/

Try it online!
The leftmost ? gets the input, which goes straight into the ! to be output unchanged.
Reverse
 /0<
?+!?

 >^

Try it online!
The leftmost ? gets the input. The + sends the leading 0 bit, if any, left (north), and the 1 bits right (south).
If there is a leading 0 bit, it hits the splitter / and turns east, deactivating the splitter. The < sends it west again, through the deactivated splitter and off the playfield. The 0 bit that started on the playfield also hits the < and goes through the deactivated splitter and off the playfield. Meanwhile, the 1 bits are directed around by the > and ^ and reach the !, where they are output.
If there is no leading 0 bit, the 0 bit that starts on the playfield hits the < and goes west to the splitter /. Since the splitter has not been deactivated, it directs the bit south, and the + sends it west into the output !. Meanwhile, the 1 bits are directed to the output, with enough delay to make sure they get there after the 0 bit.
TL;DR: Nonpositive inputs have their leading 0 bit stripped and their magnitude is output. Positive inputs have a leading 0 bit added and are thus output as negative numbers of the same magnitude.

@JoKing That's clever! It's really different from mine; do you want to post it yourself?

Posted

Keg, 2 bytes
#±

Try it online!
!enilno ti yrT
Real simple. When run in normal direction, it simply prints the input. When run in reverse direction (±#), it negates the input.

TI-BASIC, 3 bytes
Ans-0

Very simple and works the same way as the top J answer.
Input is an integer in Ans.
Examples:
4:Ans-0
              4
4:0-Ans
             -4

APL (Dyalog Unicode), 3 bytes
-/⊢
-/ ⍝ Summation with alternating sign
  ⊢ ⍝ Identity function

Reversed
⊢/-
⊢/ ⍝ Reduce (fold) with the Right operator
  - ⍝ Negate

Mirrored
⊣\-
⊣ ⍝ Left
 \ ⍝ Expand
  - ⍝ Negate

Try it online!

Interestingly enough, -/⊢ -\⊢ -/⊣ -\⊣ all amount to identity functions, and ⊣- ⊣/- ⊢- ⊢/- all amount to negation functions... pretty cool :)

sed, 14 13 bytes
Thanks to Philippos for -1 byte.
##--#s;#-#^#s
The code is only comment, which means the input is outputted unchanged.
Attempt This Online!
Reversed:
s#^#-#;s#--##
The code first append - in front of the string. Then if there are two minuses they get removed.
Attempt This Online!

Why waste a byte for the comment sign, when you can do ##--#s;#-#^#s?

Lua, 23 bytes
print(...)--)...-(tnirp

Try it online!
Comment abuse all over again.

Cascade, 6 bytes
# -
&#

Try it online!
and reversed:
#&
- #

Try it online!
I think this is the optimal answer for this question. In order to negate the input, we have to use the - operator, which means the code must be at least three wide so the left and the right operands aren't the same. It must then be two tall to have not loop infinitely. That means at least one row must be three wide, and the other has to be two wide, since if it was one wide, it must be the redirect to the #, which would have to be directly under it. Feel free to prove me wrong though.
Explanation:
For the initial program, we only execute # (integer output) on & (integer input). Basically, the only instructions that matter are:
#
&

For the reversed program, the # on the second line leads to - (left minus right). This wraps around the program, with the right being the &, and the left as an empty space, which is zero. This results in 0 - input, which is the negated input.

Phooey, 3 bytes
+.-

Try it online! (Forwards)
Try it online! (Backwards)
This assumes an empty stack and an empty tape.
Explanation:
Each instruction in Phooey has a modifier:

No modifier defaults to either the stack or the tape, depending on the instruction.
A number (with a preceding _ for negative) uses an immediate value
A . applies to an integer from stdin
A : applies to a char from stdin
A ! applies to the stack (for instructions where it isn't the default)

So, when read forwards, it is this:
+.-
+.  # Add to the tape
  - # pop and subtract (does nothing because stack is empty)

And backwards, it is the same for -.

Phooey, universal, 5 bytes
;0@.&

This version works regardless of the stack and tape state, and also preserves the stack contents.
Forwards:
;0@.&
;0    # tape = 0 - tape (don't care)
  @.  # read input and push to stack
    & # pop from the stack to the tape

Try it online! (Forwards)
Backwards:
&.@0;
&.    # read int and store to tape
  @0  # push 0 to the stack
    ; # pop, tape is 0 (stack) - tape

Try it online! (Backwards)

Pxem, Filename: 30 27 bytes + Content: 0 bytes = 30 27 bytes, does not support signed zero, not clean.

Filename (escaped unprintable): ._.n.o.-a.d.n.-.-.00y.\001c._.

Reversed: ._.c\001.y00.-.-.n.d.a-.o.n._.

Content: empty

Try it online!
!enilno ti yrT
With comments
Original
XX.z
.a._.nXX.z # push getint; putint pop
.a.o.-XX.z # DOTo and DOT- works like EOF for insufficient items
.aa.dXX.z # push ascii code of a; exit
.a.n.-.-.00y.\001c._.XX.z # deadcode
  ## NOTE this is syntaxically valid
.a

Reversed
XX.z
.a._.cXX.z # push getint; dup
.a\001.yXX.z # push 1; while pop>pop; do
  .a00.-.-XX.z # (*essentially*) push abs(0-pop)
    # NOTE actually: push 48; push 48;
    #     push abs(pop-pop); push abs(pop-pop)
    # NOTE NULL char not supported for filename
  .a.n.dXX.z # putint pop; exit
.a.aXX.z # done
.a-.o.nXX.z # push hyphen; putchar pop; putint pop
.a._XX.z # this is why it aborts when only an integer is given
.a..c.sXX.z # push dot
.a

Pxem, Filename: 34 bytes + Content: 0 bytes = 34 bytes, clean.

Filename (escaped some): ._d..s.s.n.o.-a.d.n.-.-.00y.\001c._.

Reversed: ._.c\001.y00.-.-.n.d.a-.o.n.s.s..d_.

Content: empty

This version deals with exiting; reversed version exits well against non-negative input, too.
Try it online!

Rattle, 12 bytes
||1c0gI|\\&-

Try it online!
!enilno ti yrT
This takes advantage of how Rattle is parsed. As of right now, there is only support for one input section (everything before the first |) - this means that anything after any following |'s will be disregarded. This more or less splits the code into two sections:
|

This is the effective forward code, which is the cat program.
-&\\|Ig0c1

This is the reverse code, which spits out the negative of the input. There's still possibility that this could be golfed further!

MMIXAL, 35 bytes
f POP 1,0 # 0,1 POP ;0$,0,0$ UGEN f
Very simple; when reversed, is just negate-and-return.

MMIX, 12 bytes (3 instrs)
00000000: f8010000 000001f8 00000036           ẏ¢¡¡¡¡¢ẏ¡¡¡6

Disassembled:
f   POP  1,0
    TRAP 0,Fopen,248
    TRAP 0,Halt,36

Reversed and disassembled:
f   NEGU $0,0,$0
    POP  1,0
    TRAP 0,Fopen,248

This is essentially the same as my MMIXAL answer, except that that relied on comments and reversed the source code, while this just relies on early return.

SNOBOL4 (CSNOBOL4), 38 bytes
	OUTPUT =INPUT;END;DNE;TUPIN-= TUPTUO

Try it online!
Reversed
Anything after an END label is ignored. ; is an alternate newline delimiter which made this answer easier to think about.

dc, 5 bytes
dp-r0

Try it online!

Ly, 3 bytes
+0-

Try it online!
Forwards:
+    : compute "0 + STDIN"
 0   : push 0
  -  : subtract the top two stack entries
     : prints stack as a number automatically

Backwards:
-    : compute "0 - STDIN"
 0   : push 0
  +  : add the top two stack entries
     : prints stack as a number automatically

Knight, 5 bytes
O P~O

Try It Online!
Try It Online reversed!

Thunno, \$ 2 \log_{256}(96) \approx \$ 1.65 bytes
nI

Attempt This Online! or !enilnO sihT tpmettA
Outputs inside brackets, e.g. [5].
Port of jasanborn's 05AB1E answer. n = negate, I = push input.


text:
Creating a 16x16(NxN) grid
This is my first question in Code golf I found it in stack-overflow (originally in JavaScript however all languages are acceptable):
Render on screen NxN (where N in range 1-16) grid where each cell have black boundary and red number inside - cells are numerated in hex starting from left-upper corner to bottom-right. Example output (for N=16) shows how result should looks like (font can be different than in picture):

The image in text uri form (which works on major browsers) in output is also acceptable - a as example blow:

<img src="data:image/png;base64,[encoded data, 35788 characters]"/>

This is my (not optimised) attempt to this task

document.write('<style>.row { display: flex; font-size: 9.5px; text-align: center; color: red } .cell { width: 10px; height: 10px; margin: 1px; border: 1px solid black;}</style><div id="container"></div>')

let n=10, s='';

for(let i=0; i<n; i++) {
  s+= '<div class="row">'
  for(let j=0; j<n; j++) s+= `<div class="cell"> ${(i*n+j).toString(16)} </div>`;
  s+= '</div>'
}

container.innerHTML = s;

but I wonder how small code can produce similar effect?

Was starting to work on a brainfuck solution until I realised it can't output text in red :'(

@Therandomguy I'm pretty sure you can use weird ANSI escape magic (but I might be wrong)

Related

@Kamil to be fair, that allows you to either golf a font and a image encoder or compress 16 uncompressible different strings in a language that presumably cannot output colored text; doesn't really sound better than weird ANSI escape magic.

@KamilKiełczewski if "NxN (where N in range 1-16)" is no longer a requirement it should be removed from the spec, although I don't know why you're allowing a uri now.

Are we allowed to have all the blocks align without spaces in between them (see my current PowerShell screenshot)? If not I'll delete and fix it (later when I have some more time).

Why are some of your comments deleted now?.. An few hours ago you said input wasn't required, and @JonathanAllan asked to remove it from the challenge description as response. And now those comments are removed without a change to the challenge description.. So, do we take an input or not? And please edit the challenge description accordingly..

What is the motivation behind requiring that the output be colored? That seems like an arbitrary expectation that prevents many different golfing environments from competing. Is that really an integral part of the challenge?

I've VTCed this as unclear as, other than the issue of whether or not we should take input, there are a lot of things not covered by the spec including, but not limited to, border size, margins, padding and justification of text.

import matplotlib.pyplot as p;o='center';[p.subplot(16,16,1+x,yticks=[],xticks=[]).text(0.5,0.5,hex(x)[2:],color='r',va=o,ha=o) for x in range(256)]
question was closed but I wanted to do a python+matplotlib one anyway - 148 characters (requires matplotlib)

@HughNolan thank you for your answer - can you provide link where I can execute code online or at least some screenshot with result.

The question description with desired example (N=16) output image, JS snippet and tag graphical-output provide all information about task (including margin, paddings, colors etc., parameter N which is in range 1-16 e.g. in JS snippet is N=10 in screenshot is N=16... - I never say that N is fixed - question was clear). So what next - how I should change the question?

@Kamil Kiełczewski, it would be nice to edit the question and answer some of the asked questions so it can be re-opened and everyone can post their answers again.

Question was updated - everything should be clear

Could go smaller, but here's a quick one:

let n=10;container.innerHTML=(d='<div class="')+'grd" style="width:'+n*14+'px">'+[...Array(n*n)].reduce((a,b,i)=>a+d+'cell">'+i.toString(16)+(e='</div>'),'')+e;
.grd { display: inline-block; font-size: 9.5px; text-align: center; color: red;}
.cell { display:inline-block; width: 10px; height: 10px; margin: 1px; border: 1px solid black;}
<div id="container"></div>

Hello and welcome to codegolf ! I invite you to put your code on tio.run and export it here. The website has a special export for StackExchange and will show your score on your answer.

@Therandomguy, would the numbers stay red when run on TIO?

@manatwork you actually got a point here ...

I believe this needs to be changed to take the n as input since the spec states, "NxN (where N in range 1-16)".

Red, 131 bytes
n: -1 view collect[loop 16[keep 'across
loop 16[keep compose[field 20x20 font-color red(to""to-hex/size n: n + 1 2)]]keep 'return]]

If the leading zeroes need to be discarded:
Red, 154 bytes
n: -1 view collect[loop 16[keep 'across
loop 16[s: to""to-hex/size n: n + 1 2 parse s[remove"0"]keep
compose[field 20x20 font-color red(s)]]keep 'return]]

Note: The first screenshot is taken on my Win 10 PC, the second one - on my Win 8.1 laptop, hence the difference.

It is actually mostly red, yeah...

The first line shouldn't include leading 0s.

@Shaggy Ok, I'll fix it tomorrow.

On second thought, it might be worth asking whether they are allowed first.

PowerShell, 319 bytes
-1..15|%{If($_-lt0){$s="┌──";0..14|%{$s=$s+"┬──"};Write-Host "$s┐";}Else{$i=$_;0..15|%{Write-Host "│"-NoNewline;Write-Host ("{0:X2}"-f($i*16+$_))-f 12 -NoNewline;};Write-Host "│";$s=("├","└")[$_-eq15]+"──";0..14|%{$s=$s+(("┼","┴")[$i-eq15]+"──")};Write-Host("$s┤","$s┘")[$_-eq15]}}

Screenshot of the output:

Only my second PowerShell answer, so can definitely be golfed substantially.. Also, is it possible to create and use an Alias for the Write-Host?
Explanation:
TODO: Will add one later.
The X2 could be x2 to format the hexadecimal as lowercase letters.

@LuisMendo Fixed.. Can definitely be golfed some more though.. It's only my second PowerShell answer ever, so I'm not too sure what I'm doing. ;) EDIT: Hmm, comparing it to the challenge screenshot, I might need spaces between blocks.. >.>

how N could be parameterized?

@NahuelFouilleul OP said it was always 16 in the comments and as you can see at JonathanAllan's response, he asked to delete it from the challenge in that case, but now OP deleted his comments.. :S I honestly don't know anymore what the challenge is asking, since it keeps changing in the comments, without any substantial edits to the description.. >.> Three hours ago OP stated there wasn't any input required; now it sounds like there is an input required.. I'm gonna close as unclear until OP clarified AND edited the challenge description.

Japt, 51 49 bytes
Wrong tool for the job, but I got it working eventually with a little help from my solution to Little Boxes on the Hillside. The spec doesn't include any details on margins, padding & border width so this won't look exactly like the reference image.
G²ÇsG ici%Ãú òG
£OlX¬,$...$¡`Þ:so¦d #000;¬l:d

Test it (Open your browser's console)
If input is required then this should work for 50 48 bytes.

PHP, 157 bytes
<?php for(;$i++<$n=$_GET[n];)for(print'<p>';$$i++<$n;)echo'<x style="color:red;border:1px solid #000;display:inline-block;width:25px">'.dechex($x++).'</x> ';

This should be run as a webpage, not from CLI. Pass input as a URL query string named n. For example: grid.php?n=16
Sample output for n=8:

<p><x style="color:red;border:1px solid #000;display:inline-block;width:25px">0</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">1</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">2</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">3</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">4</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">5</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">6</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">7</x> <p><x style="color:red;border:1px solid #000;display:inline-block;width:25px">8</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">9</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">a</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">b</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">c</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">d</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">e</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">f</x> <p><x style="color:red;border:1px solid #000;display:inline-block;width:25px">10</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">11</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">12</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">13</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">14</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">15</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">16</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">17</x> <p><x style="color:red;border:1px solid #000;display:inline-block;width:25px">18</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">19</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">1a</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">1b</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">1c</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">1d</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">1e</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">1f</x> <p><x style="color:red;border:1px solid #000;display:inline-block;width:25px">20</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">21</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">22</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">23</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">24</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">25</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">26</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">27</x> <p><x style="color:red;border:1px solid #000;display:inline-block;width:25px">28</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">29</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">2a</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">2b</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">2c</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">2d</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">2e</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">2f</x> <p><x style="color:red;border:1px solid #000;display:inline-block;width:25px">30</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">31</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">32</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">33</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">34</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">35</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">36</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">37</x> <p><x style="color:red;border:1px solid #000;display:inline-block;width:25px">38</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">39</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">3a</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">3b</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">3c</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">3d</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">3e</x> <x style="color:red;border:1px solid #000;display:inline-block;width:25px">3f</x>

TIO link to get raw outputs (you have to save them as HTML to see the result): Try it online!

JavaScript (web browser console), 160 bytes
I think a JavaScript golfer should be able to golf this idea a lot more (I'm not one!).
function(n){for(x=i=0;i++<n;console.log(...a))for(j=0,a=[''];j++<n;a.push('float:left;border:1px solid #000;color:red'))a[0]+='%c'+(x++).toString(16).padEnd(2)}

A 155 bytes version, but it prints some noises on top and right of the grid:
function(n,a=[]){for(x=0;x<n*n;a.push('float:left;border:1px solid #000;color:red'),a[0]+='%c'+(x++).toString(16).padEnd(2))x%n?0:console.log(...a,a=[''])}

This only works in modern browsers console.
Sample usage in console: f=...code above...; and then f(16);
Or open your browser's console and then click on Run code snippet button.

f=function(n){for(x=i=0;i++<n;console.log(...a))for(j=0,a=[''];j++<n;a.push('float:left;border:1px solid #000;color:red'))a[0]+='%c'+(x++).toString(16).padEnd(2)};
f(16);

Explanation:
In a modern browser console, you can use this format to apply CSS to your values printed in the console:
console.log('%c Value', 'color: red; font-size: 10px;');

For every %c you have to add a new argument with your styles and those styles will be applied until the next %c. So to style and print two values in same line, we can use something like this:
console.log('%c Value %c Value2', 'color: red; font-size: 10px;', 'font-weight: bold;');

In the function above, I'm collecting arguments for each row in an array called a and each row gets a single console.log for itself.

It almost work in Opera, the 1st line is displayed shorter than the other ones.

@Therandomguy golfed more and this one should work in any modern browser's console.

I don't think you need the float, do you?

@Shaggy without float I lose the top border for each cell. OP says "each cell have black boundary".

source: Stack Exchange

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

sort: votes


text:
Create a uniquely solvable crossword ... without clues
Can you imagine solving the New York Times crossword puzzle without any clues?  Maybe not with all of the creativity and new words and phrases appearing in modern crosswords, but with a fixed word list there's some hope.  In this challenge, you create a crossword puzzle grid in which this is theoretically possible.
The challenge
Maximize the number of white squares in a white- and black-shaded 15x15 crossword puzzle grid, such that the white squares can be uniquely filled with letters so that every across and down word appears in the international Scrabble word list.
Grid construction clarifications
In US newspapers, crossword grids are usually constructed so that every letter is "checked", meaning it is part of both an "across" word and a "down" word.  In the UK and elsewhere (especially in cryptic crosswords), this is not necessarily the case: if an "across" or "down" word would only be one letter, it need not be an actual word (like "A" or "I").  For this challenge, follow the more relaxed rules: single-letter words need not appear in the word list.
There are various other traditions (in the US and elsewhere), none of which need to be followed in this challenge.  For example, words can be only two letters long, words are allowed to repeat, and the grid need not have (rotational) symmetry.
Is this even possible?
Yes!  One can write a short script to verify that the unique solution to the following blank grid on the left is the filled grid on the right:

One can display the filled grid in a computer-readable format as follows:
###CH##########
###YE##########
###AM##########
CYANOCOBALAMINE
HEMOCHROMATOSES
###CH##########
###OR##########
###BO##########
###AM##########
###LA##########
###AT##########
###MO##########
###IS##########
###NE##########
###ES##########

Your solution
The grid above has 56 white squares out of the 225 squares total in the 15x15 grid.  This serves as a baseline for this challenge.  Grids with fewer white squares may also be interesting for reasons other than their score, for example if they satisfy some of the aesthetic traditions mentioned above.
Please submit your solution in the same format as the computer-readable baseline above.  Please include code that verifies that there is a unique solution to your grid.
Interesting code snippets (eg for searching the space of possibilities) and discussion of how you found your grid are appreciated.
The word list
The international Scrabble word list was previously known as SOWPODS and is now called Collins Scrabble Words (CSW).  It is used in most countries (except notably the US).  We prefer to use this list because it includes British spellings and generally has significantly many words than the American word list.  There are multiple editions of this list which differ slightly.  You can find different versions of this list linked from Wikipedia, on Github, in Peter Norvig's Natural Language Corpus and elsewhere, often still called "SOWPODS".
This challenge is highly sensitive to the broad nature of the choice of word list, but less so to smaller details.  For example, the baseline example above works with any edition of CSW, but CH is not a word in the American Scrabble word list.  In the event of a discrepancy, we prefer to use CSW19, the most recent edition of CSW.  (If we use this list, which was released this year, we can expect answers to this challenge to remain valid longer).  You may query this list interactively on the official Scrabble word finder site or download it (as well as the previous edition, CSW15) from the Board & Card Games Stack Exchange or Reddit's r/scrabble.
Tldr: the authoritative word list for this challenge is available as a plain text file (279,496 words, one per line) over on the Board & Card Games Stack Exchange.
Further discussion
One issue raised in an early answer and comment is why existing crosswords (eg, in the NYT) don't answer this question.  Specifically, the record for fewest number of black squares (and thus largest number of white squares) for a published NYT crossword is already the most famous record in crosswords.  Why can't we use the record grid?  There are a few issues:

Many of the answers in NYT crosswords do not appear on our word list.  For example, the record grid includes PEPCID (a brand name), APASSAGETOINDIA (a four-word proper name for a film and novel, written without spaces), and STE (an abbreviation for "Sainte").  It appears that the record grid is not solvable with Scrabble words.

Merely expanding the word list to include more words does not necessarily help with this challenge: even if all of the words in the record grid appeared on our word list, the solution would not be unique without the clues.  It is often possible to alter some letters at the ends of answers while keeping everything a word.  (For example, the bottom-right-most letter can be changed from a D to an R.)  Indeed, this is part of the (human) construction process when writing a crossword, trying to obtain "better" words.
The reason ordinary crosswords (usually) have a unique solution is that the clues help narrow down the correct answers.  If you simply try to fill the grid with words without using clues, it's likely that there will either be no possibilities or many possibilities.  Here's an example of three different fills (using the word list for this challenge!) for the same grid (one that's relatively frequently used in the NYT):

Another issue raised in the comments is some amount of disbelief that this question is a coding challenge.  Perhaps it is not immediately clear, but it is hard to even find a single valid answer to this challenge.  Finding the baseline above involved multiple, specially-crafted search programs that were not guaranteed to find an answer.  I do not personally even know of a general way to solve an arbitrary grid, if you want the answer in reasonable time.  Existing crossword construction programs can help, but I assume (perhaps incorrectly) that they do not actually do a full search of the possibilities.  (I used such a program for the three side-by-side grids above; this worked because that particular grid allows for many solutions.)

Comments are not for extended discussion; this conversation has been moved to chat.

Meta post related to this general type of questions: https://codegolf.meta.stackexchange.com/questions/18117/questions-that-ask-for-artifacts-or-witnesses

I'm voting to reopen anyway, but I recommend the following changes to make further reopen votes more likely: (posting as separate comments so you can see if people agree with each one)

Drop the aesthetic option ("Grids with fewer white squares may also be interesting for reasons other than their score, for example if they satisfy some of the aesthetic traditions mentioned above.") - similarly to avoiding bonuses in code golf, I'd rather a code challenge be about just one thing. This means all the answers can be compared like for like. It also makes it clearly objective, which will help with reopen votes.

Choose a single word list and insist on it for all answers. The tldr mentions an authoratative word list, but the discussion beforehand may lead people to thinking they can pick any of those mentioned. It may help to keep the strict requirements near the top of the post, and to make it very clear that other details are not part of the specification of the challenge. Ideally, omit anything superfluous to the spec to keep the post short and immediately unambiguous.

Make the inclusion of the code used to find the solution a requirement for a valid answer.

Having said all that, I already like this challenge. +1 plus a reopen vote. I personally found the background and further discussion interesting, but they do not form part of the challenge specification so this might work better as a golfed down minimal spec which has a link at the end to the discussion.

This is the kind of challenge that could benefit from a chat room for people to discuss approaches. If you set up a chat room and link to it from the end of the spec, you can post discussion there as the initial posts, and mention this in the challenge for people who want to know more.

I find this kind of code challenge both interesting and really challenging to get right. I'd love to see some detailed guidelines as answers to the meta post linked above.

Could you add a link to the utility you used to make the baseline grids? Solutions will be prettier if we can use that in addition to the computer-readable format.

@RobinRyder: the program I used to create those diagrams is called "qxw". It is open-source and seems to be available for multiple operating systems. In particular, it is in the Ubuntu repositories.

180 white squares

My strategy was simply to find a smaller rectangle with no black squares, such that it can be filled in uniquely. All 2×k rectangles have multiple solutions. For 3×k rectangles, there are multiple solutions for k between 3 and 14, but there is a exactly one solution for k=15.
I then fit 4 such rectangles in the grid. This means that each word appears 4 times in the solution, which is usually frowned upon in crossword construction, but OK for this challenge. On the other hand, this solution has both left/right and top/down symmetry!
Computer-readable grid:
HETERONORMATIVE
OVEROPINIONATED
POSSESSEDNESSES
###############
HETERONORMATIVE
OVEROPINIONATED
POSSESSEDNESSES
###############
HETERONORMATIVE
OVEROPINIONATED
POSSESSEDNESSES
###############
HETERONORMATIVE
OVEROPINIONATED
POSSESSEDNESSES

Here is the R code I used to find all solutions for a given grid size. Looping over all triples of 15-letter words is too slow. Instead, I try to fill in rectangles by

setting the first two columns (two 3-letter words)
then looping through all 15-letter words starting with the first two letters which are now settled.
for each possible choice of the 15-letter words, I then verify whether all 3-letter words generated are in the dictionary.

For example, for the eventual solution, the code first put in HOP and EVO, then completed into HETERNORMATIVE, OVEROPINIONATED and POSSESSEDNESSES, and finally verified all the 3-letter words (HOP, EVO, TES, ERS, ROE, OPS, NIS, ONE, RID, MON, ANE, TAS, ITS, VEE, EDS).
R code
library(fastmatch)
f = "scrabble-wordlist.txt"
d = read.table(f, skip=2, as.is=T, na.strings=NULL)

d$l = apply(d, 2, nchar)
d3 = d[d$l==3, 1]

sp = function(s) strsplit(s, "")[[1]]
cm = function(v) paste0(v, collapse="")
d3s = sapply(d3, sp)

f3 = function(l){
  m = matrix("", 3, l)

  md = sapply(d[d$l == l, 1], sp)
  nf = 0

  a1 = seq(1, 3*l, by=3); a2 = a1 + 1; a3 = a1 + 2

  for(i in 1:ncol(d3s)){
    m[, 1] = d3s[, i]

    id1 = as.matrix(md[, md[1, ] == m[1, 1]])
    id2 = as.matrix(md[, md[1, ] == m[2, 1]])
    id3 = as.matrix(md[, md[1, ] == m[3, 1]])

    if(any(ncol(id1) == 0, ncol(id2) == 0, ncol(id3) == 0)) next

    for(j in 1:ncol(d3s)){
      m[, 2] = d3s[, j]

      jd1 = as.matrix(id1[, id1[2, ] == m[1, 2]])
      jd2 = as.matrix(id2[, id2[2, ] == m[2, 2]])
      jd3 = as.matrix(id3[, id3[2, ] == m[3, 2]])

      if(any(ncol(jd1) == 0, ncol(jd2) == 0, ncol(jd3) == 0)) next

      for(k1 in 1:ncol(jd1)){
        m[1, ] = jd1[, k1]

        for(k2 in 1:ncol(jd2)){
          m[2, ] = jd2[, k2]

          for(k3 in 1:ncol(jd3)){
            m[3, ] = jd3[, k3]

            w = paste0(m[a1], m[a2], m[a3])
            if(all(w %fin% d3)){
              nf = nf + 1
              print(m)
            }
            if(nf >= 2){
              print(c(l, nf))
              return()
            }
          }
        }
      }
    }
  }

  return(nf)
}

Called as f3(15). Took a few hours on my personal computer.

@downvoter Could you comment?

My answer was also downvoted.

182 white squares

Inspired by Robin Ryder's answer, I tried to squeeze in a couple more white squares.  I believe this solution is unique, and I will soon post verification code accordingly.
Computer-readable grid:
HETERONORMATIVE
OVEROPINIONATED
POSSESSEDNESSES
B##############
INCOMMUNICATIVE
NEUROANATOMICAL
DETERMINATENESS
###############
HETERONORMATIVE
OVEROPINIONATED
POSSESSEDNESSES
B##############
INCOMMUNICATIVE
NEUROANATOMICAL
DETERMINATENESS

184 since mon?cot can be completed uniquely with monocot

...make that "maybe..." since I have not verified it wont break uniqueness across the board!

I'd be curious to see your verification code. All my attempts to verify your grid are horrendously slow.

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


text:
Codegolf : the HEX
INTRODUCTION
I like Karma Fields : he's a music producer that creates original music tracks. His artwork also matches up really well his style.
He has a logo witch I find really interessing :

GOAL
Your goal will be to reproduce that logo, graphically or in ASCII.
Edit
@NahuelFouilleul managed to provide a readable ascii version of this :
     / \
   /|   |\
 /  |   | |\
|\ /|\ / \|/|
| | \ |     |
|/ \ / \    |
| \ | / |   |
 \|/ \|/ \ /
   \  |  /
     \|/

RULES

The logo can be any size BUT has to be recognisable (each hexagon
part has to be visible).
Colors don't matter, only the drawing counts.
Each line can be the same thickness, and you can forget about the 2 dots.
This is a codegold challenge, so the least amount of bytes wins.
The usual loopholes are forbidden.

recognisable is very subjective, I'd suggest giving a reference ASCII version that has to be matched.

@Grimy roger that, i'll work on it ASAP

OK?

@Adám Yes, this one is valid.

otherwise this is more regular and this is shorter

@NahuelFouilleul both would work

This post put me in a corner. I started a discussion about it here to know what I should do with it.

Logo, 170 168 160 bytes
make"l[4 5 2 3 1 3 1 1 3 1 5 5 1 3 1 1 2 5 2 5 5 3 5 5 3 0 5 4 5 3 5 5 3 5 5 4 0 0 5 0 0 5 0 0 5 0 0 5 0 0 5 0 0 5 4]repeat 55[rt 60*head:l
fw 20
make"l tail:l]

Try it online! Edit: Saved 2 9 bytes thanks to @Night2.

There's a language called Logo? Man, they have something for everything.

@JL2210 Well, it seemed the ideal language for the job in more ways than one!

@Night2 There are 46 segments to draw, but there are also 16 odd ends, which need 7 segments to connect, but two of which are 2 segments away from the nearest odd end, for a total of 46 + 7 + 2 = 55, and using the two distant ends as overall endpoints actually consumes more segments than it saves, due to the limitations it imposes on your route. I did find another route of the same length as yours that ended in the same place as my original route though, which is nice aesthetically.

@Night2 Ah yes, I suspected something like that. Also, you left some white space after a ] which isn't needed, so it's only 160 bytes.

Sadly the link no longer works but you can paste the code into this online interpreter.

Raw bitmap (29x35), 202 bytes
Hand drawn a small monochrome bitmap file which looks like the logo. I'm not sure if raw bitmap is accepted here, but if it is not, a HTML version is below the post too.

Please note that the image above is converted to PNG during upload, to see the original image save the hex dump as a binary file or use the HTML version.
000000  42 4d ca 00 00 00 00 00 00 00 3e 00 00 00 28 00  BM........>...(.
000010  00 00 1d 00 00 00 23 00 00 00 01 00 01 00 00 00  ......#.........
000020  00 00 8c 00 00 00 c3 0e 00 00 c3 0e 00 00 00 00  ................
000030  00 00 00 00 00 00 00 00 00 00 ff ff ff 00 ff fd  ................
000040  ff f8 ff f0 7f f8 ff ed bf f8 ff 9d cf f8 fe 7d  ...............}
000050  f3 f8 fd fd fd f8 f1 f8 fc 78 e6 e5 33 b8 97 5d  .........x..3..]
000060  cf c8 77 bd df f0 77 bd df f0 77 bd df f0 6f bc  ..w...w...w...o.
000070  df f0 5f bf 1f f0 3f 9f df f0 4e 67 3f f0 75 fa  .._...?...Ng?.u.
000080  ff f0 7b fd ff f0 7b f9 ff f0 7b e5 ff f0 7b dd  ..{...{...{...{.
000090  ff f0 7b dd ff f0 7b dd ff f0 64 dd fe 70 5f 52  ..{...{...d..p_R
0000a0  78 90 3f 8f a6 e8 bf df de d8 cf df de b8 f3 df  x.?.............
0000b0  de 78 fd df d9 f8 fe 5f d7 f8 ff 9f cf f8 ff cf  .x....._........
0000c0  bf f8 ff f2 7f f8 ff fd ff f8                    ..........

HTML, 292 bytes

<img src=data:;base64,Qk3KAAAAAAAAAD4AAAAoAAAAHQAAACMAAAABAAEAAAAAAIwAAADDDgAAww4AAAAAAAAAAAAAAAAAAP///wD//f/4//B/+P/tv/j/nc/4/n3z+P39/fjx+Px45uUzuJddz8h3vd/wd73f8He93/BvvN/wX78f8D+f3/BOZz/wdfr/8Hv9//B7+f/we+X/8Hvd//B73f/we93/8GTd/nBfUniQP4+m6L/f3tjP396489/eeP3f2fj+X9f4/5/P+P/Pv/j/8n/4//3/+A

Don't think the hex dump of the bitmap itself would be a valid entry; so the HTML version should be your score.

I wonder - does this kind of approach for graphical-output questions - make 'low resolution' picture of desired output - is no too trivial to be allowed? May be the requirement of output image size should be added

Are all the zeros needed?

@KamilKiełczewski the OP has said "The logo can be any size BUT has to be recognisable (each hexagon part has to be visible)" and I think this image follows that rule.

@JL2210 which specific zeroes do you mean?

Roughly between the third byte in line 0 and the 9th byte in line 30.

@JL2210 I'm not a bitmap expert, but I think around 60 bytes (more or less) at start of the file are bitmap file header and DIB (device independent bitmap) headers and should be there. The common variant used today seems to be BITMAPINFOHEADER which you can find more info about it here. I'm not sure if we can use other variants to cut some of those headers.

JavaScript, 420 407 bytes

document.write('<svg id="pic" height="255" width="255"></svg>')
v="0011120322210011343546413441045156516421646728696a52586758075b5104074848090a520a4248423a030a".split``.map((x,i)=>(i%2?[43,88,175,220,100,72,58,131,144,162,190,117]:[129,206,52,179,154,103,77])[+('0x'+x)])
for(i=1;i<46;i++) pic.innerHTML+=`<line x1=${v[2*i-2]} y1=${v[2*i-1]} x2=${v[2*i]} y2=${v[2*i+1]} style="stroke:red;stroke-width:2" />`

Point coordinates coding

let c=[129, 43, 206, 88, 206, 175, 129, 220, 52, 175, 52, 88,129, 43, 206, 88, 179, 100, 179, 72, 154, 58, 154, 88, 179, 100, 154, 88,129, 100, 103, 88, 103, 58,103, 88,77, 100, 52, 88,77, 100, 77, 131, 52, 144, 77, 162, 77, 190, 103, 175, 103, 144, 77,  131, 103, 144,129, 131, 103, 117, 103, 88,129, 100, 129, 131,154, 144, 154, 144,129, 162, 129, 190, 103, 175,129, 190,154, 175,154, 144,154, 175, 179, 190,129, 220,129, 190
]

a=[... new Set(c.filter((x,i)=> i%2))] // remove duplicates for X
b=[... new Set(c.filter((x,i)=> i%2-1))] // remove duplicates for Y
d=c.map((x,i)=> (i%2?a:b).indexOf(x).toString(16)).join``

console.log({a,b,d});

Logo turned out somehow really unsatisfying to look at, it's bugging me out. I like that.

PHP, 71 bytes
I have used a compressed version of the string created by Nahuel Fouilleul in the OP comments.
Uses raw output of gzdeflate and contains unprintable binary data, so the code itself and direct TIO link cannot be posted here, but here is a hex dump of it:
000000  3c 3f 3d 67 7a 69 6e 66 6c 61 74 65 28 22 15 c7  <?=gzinflate("..
000010  47 01 43 01 14 02 b0 73 97 87 38 c0 10 52 10 df  G.C....s..8..R..
000020  ff 36 01 d1 df 1b 19 76 39 0c 73 5a e5 56 97 3d  .6.....v9.sZ.V.=
000030  34 35 70 8c ba c5 51 4d 8c a3 2e b7 2a 8f 28 73  45p...QM....*.(s
000040  19 74 f9 03 22 29 3b                             .t..");

Save it as a binary file then execute it like this: php hex.php
TIO which uses bash to create and run this file: Try it online!
Base64 of deflated string for anyone who might need it:
FcdHAUMBFAKwc5eHOMAQUhDf/zYB0d8bGXY5DHNa5VaXPTQ1cIy6xVFNjKMutyqPKHMZdPkD


text:
Where are they calling from?
When making phone calls internationally, phone numbers are prefixed with a code indicating what country the number is located in. These codes are prefix codes, meaning that no code is a prefix of another.
Now, earlier today you missed a call, and you're kind of curious where that call might have come from. So you want to look up the calling code. But, being a prefix code, you're not quite sure where it ends, so you decide to write a program to separate the calling code from the rest of the number.
Input
As input, you will recieve a string consisting of the digits 0-9. The first few digits will be one of the country calling codes listed below (this means the first digit will never be 0). After the country calling code, the rest of the input will contain zero or more digits in any order - it is not guaranteed to be a valid phone number. Your program must be able to handle inputs containing at least 15 digits
Output
Your program should output the unique country calling code that is a prefix of the number. The valid outputs are as follows:
1
20
211
212
213
216
218
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
260
261
262
263
264
265
266
267
268
269
27
290
291
297
298
299
30
31
32
33
34
350
351
352
353
354
355
356
357
358
359
36
370
371
372
373
374
375
376
377
378
379
380
381
382
383
385
386
387
389
39
40
41
420
421
423
43
44
45
46
47
48
49
500
501
502
503
504
505
506
507
508
509
51
52
53
54
55
56
57
58
590
591
592
593
594
595
596
597
598
5993
5994
5997
5999
60
61
62
63
64
65
66
670
672
673
674
675
676
677
678
679
680
681
682
683
685
686
687
688
689
690
691
692
7
800
808
81
82
84
850
852
853
855
856
86
870
875
876
877
878
879
880
881
882
883
886
888
90
91
92
93
94
95
960
961
962
963
964
965
966
967
968
970
971
972
973
974
975
976
977
979
98
991
992
993
994
995
996
998

This list is based on the codes listed on Wikipedia's list of country calling codes page as of revision 915410826, with a few modifications

All codes listed as unassigned or discontinued and some codes listed as reserved for future use were omitted
If a code listed on Wikipedia is a prefix of another, the latter was omitted
If a single country or territory would have more than one code, and if those codes would have a common prefix, those codes are omitted in favour of their common prefix.

This may result in independent countries being lumped together, or disputed territories being lumped in with a particular claimant. This is not intended as a political statement, and decisions about the inclusion or omission of territories and states were made based on the codes, not any beliefs I hold regarding the ownership or sovereignty of the entities using them.
If given an input that does not begin with any of these codes, your program's behaviour is undefined.
And finally:

This is code-golf, fewer bytes of code is better
Your submission may be either a function or a full program
Any of the default I/O methods are fine
The standard loopholes are forbidden

Test cases

input
output

5292649259
52

3264296721
32

1550
1

33121394
33

7
7

2542112543
254

2005992972
20

350
350

360
36

8505234469
850

9795586334
979

148985513598795
1

222222
222

5999995
5999

Perhaps you should do input | output instead with a dash-line underneath unless you want input to be translated to output.

JavaScript (ES6),  75 73  71 bytes
Saved 1 byte thanks to @Shaggy
Saved 2 bytes thanks to @Neil
s=>/1|7|(2[^07]|3[578]|42|599?|50|6[789]|8[0578]|9[679]|.)./.exec(s)[0]

Try it online!

I think 599?|50 can replace 599|5[09].

@Neil Indeed. Thanks!

Does s=>/(2[^07]|3[578]|42|599?|50|6[789]|8[0578]|9[679]|[^17]|)./.exec(s)[0] work for 72 bytes?

@ovs It does, but the current version is actually 71 bytes -- the byte count was outdated.

05AB1E, 28 25 24 bytes
η•Aó¾«¸tEΓ∞ζ∊u½d•.¥¤ØªKн

Try it online!
η                            # prefixes of the input
 •Aó¾«¸tEΓ∞ζ∊u½d•            # compressed integer 211112166111113621489811655218129
                 .¥          # undelta: [0, 2, 3, 4, 5, 6, 8, 9, 15, 21, 22, 23, 24, 25, 26, 29, 35, 37, 38, 42, 50, 59, 67, 68, 69, 75, 80, 85, 87, 88, 96, 97, 99, 108]
                   ¤         # last element of that list: 108
                    Ø        # nth prime: 599
                     ª       # append it to the list
                      K      # remove all those values from the list of prefixes
                       н     # get the first prefix left

Retina 0.8.2, 60 bytes
!`^(2[1-69]?|3[578]?|42?|599?|50?|6[789]?|8[578]?|9[679]?)?.

Try it online!

Your input in the TIO already includes the answer ;) I know your code is not using them, but it looks a bit confusing tbh.

Bash, 328 341 410 bytes
Not very competitive for a golfing score, but each of these helps my bash skills!
Saved 13 bytes by eliminating handling 2 byte run-length values; storing only 3 bytes adds 8 bytes to T, but makes the case statement much simpler.
Saved 69 bytes by changing approach from bash expansion to storing deltas. The previous TIO link is at the bottom of my answer.
T='16D73r423112r62r72r6F1224r53-03511322rZr32r9L1611-01Fr9BrD2112V12-025r9-029r8-0202rB2r7-0308-162121E5r832-02082r72Cr52-3UR132'
A(){
V=$[V+36#$1]
S="$S $V"
}
R(){
read -n$1 d
}
while read -n1 c;do
case $c in -)R 3;A $d;;r)R 1;for((i=1;$i<=36#$d;i++)){ A 1;};;*)A $c;;esac;done<<<$T
for s in $S;do [[ $1 =~ ^$s ]]&&echo $s;done

Try it online!

Sorted the list of prefixes numerically
T is a "sort of" run-length encoded string showing the delta from the previous value. Each character is one of the following:

A base36 value showing the increase from the previous value
'r': indicates that the next character indicates the the base36 encoded number of repeated delta values of 1.
'-': indicates that the next 3 characters are the next delta value

The string T="16D73r42 [...] -3UR132" following the rules above becomes a list of deltas: "1 6 D 7 3 r4 2 [...] 4995 1 3 2"
Could save 2-3 more bytes by using a higher radix than 36 (like 62-64) but Excel only natively supports up to 36, and that's what used to do the list of deltas and their conversions.

On running, T is parsed and expanded into the string S used for the comparison of the phone number given in command line argument 1.

Expanding T, S becomes: "1 7 20 27 30 31 32 33 34 36 [...] 5993 5994 5997 5999"
Try it online!

Python 3, 120 78 bytes
f=lambda n:{n//10+3}-{*b'	 &()-5>FGHSXZ[cdf',602}and f(n//10)or n

Try it online!
Contains some unprintables:
00000000: 663d 6c61 6d62 6461 206e 3a7b 6e2f 2f31  f=lambda n:{n//1
00000010: 302b 337d 2d7b 2a62 2705 0306 0708 090b  0+3}-{*b'.......
00000020: 0c18 191a 1b1c 1d20 2628 292d 353e 4647  ....... &()-5>FG
00000030: 4853 585a 5b63 6466 272c 3630 327d 616e  HSXZ[cdf',602}an
00000040: 6420 6628 6e2f 2f31 3029 6f72 206e       d f(n//10)or n

Somewhat ungolfed (earlier) version:
f=lambda n:{n/10}-{0,2,3,4,5,6,8,9,21,22,23,24,25,26,29,35,37,38,42,50,59,599,67,68,69,80,85,87,88,96,97,99}and f(n/10)or n

Try it online!

Perl 5 (-p), 44 bytes
$\=chop until/^599$/+vec"\x7D\x03\xE0\x27\x68\x04\x04\x08\x38\x00\xA1\x01\x0B",$_,1

Try it online!
Both TIO and SO have troubles with unprintable chars, so the program is shown with escape sequences. Here's a hexdump of the actual 44 bytes:
0000000: 245c 3d63 686f 7020 756e 7469 6c2f 5e35  $\=chop until/^5
0000010: 3939 242f 2b76 6563 227d 03e0 2768 0404  99$/+vec"}..'h..
0000020: 0838 00a1 010b 222c 245f 2c31            .8....",$_,1

PHP, 219 bytes
I feel like there's a lot of room for improving the regex - golfed it as far as I can go but I'll bet it can be way shorter....
preg_match('/(1|7|2(0|1[12368]|[2346].|5[^9]|7|9[01789])|3[578]?.|42?[013]|5([1-8]|0.|99?[3479])|6([0-6]|7[^1]|8[^4]|9[012])|8(0[08]|[1246]|5[02356]|7[05-9]|8[0-368])|9([0-58]|6[^9]|7[^8]|9[1-8]))/',$argn,$r);echo$r[0];

Try it online!

Java 8, 84 bytes
s->s.replaceAll("(1|7|(2[^07]|3[578]|42|599?|50|6[789]|8[0578]|9[679]|.).).*","$1");

Port of @Arnauld's JavaScript regex, so make sure to upvote him!
Try it online.
Explanation:
s->                    // Method with String as both parameter and return-type
  s.replaceAll("(1|7|(2[^07]|3[578]|42|599?|50|6[789]|8[0578]|9[679]|.).).*",
                       //  Replace this regex-match
               "$1");  //  With this replacement

Regex explanation:
(1|7|(2[^07]|3[578]|42|599?|50|6[789]|8[0578]|9[679]|.).).*  // MATCH:
 1                                                           //  a 1
  |7                                                         //  or a 7
    |(                                                )      //  or:
      2[^07]                                                 //   a 2 not followed 0 nor 7
            |3[578]                                          //   or a 3 followed by 5, 7, or 8
                   |42                                       //   or a 42
                      |599?                                  //   or a 59 or a 599
                           |50                               //   or a 50
                              |6[789]                        //   or a 6 followed by 7, 8, or 9
                                     |8[0578]                //   or an 8 followed by 0, 5, 7, or 8
                                             |9[679]         //   or a 9 followed by 6, 7, or 9
                                                    |.       //   or any single digit
                                                       .     //  followed by any single digit
(                                                       )    //  All captured in capture group 1
                                                         .*  //  With 0 or more digits following

$1                                                           // REPLACEMENT:
$1                                                           //  The match of capture group 1,
                                                             //  (effectively removing the
                                                             //   remaining digits of `.*`)

Python 3, 96 bytes
lambda s:re.sub('(1|7|(2[^07]|3[578]|42|599?|50|6[789]|8[0578]|9[679]|.).).*',r'\1',s)
import re

Try it online!
Port of Arnauld's JavaScript answer.

Scala, 411 402 330 bytes
This is assuming that the argument only contains digits.
"(1|(2(0|(1[12368])|([2346]\\d)|(5[^9])|7|(9[^2-6])))|(3(([0-4])|([57]\\d)|6|(8[^48])|9))|(4([^2]|(2[013])))|(5((0\\d)|[^09]|(9([^9]|(9[3479])))))|(6([0-6]|(7[^1])|(8[^4])|(9[0-2])))|7|(8((0[08])|[1246]|(5[02356])|(7[05-9])|(8[^4579])))|(9([0-58]|(6[^9])|(7[^8])|(9[^079]))))(.*)".r.unapplySeq(args(0)).foreach(l=>println(l.head))

Try it online!


text:
How many spaces are there?
Your task is to input a string, and output the number of spaces in the string.
This is code-golf, so least number of bytes win. Your
Test Cases
Double quotes are not part of the test cases.
"test" => 0
"Hello, World!" => 1
"C O D E G O L F" => 7
"      " => 6

What characters can be in the string? Just printable ASCII, or can there be unicode characters, tabs, newlines etc?

What is considered a space? Only 32@ASCII or other whitespace characters too?

@JoKing Just printable ASCII if you want.

@JoKing It is probably not a duplicate since - You don't have to input the character you need to find, which allows for cool solutions for example: Retina, 1 byte  .(Not created for it though)

I don't think having one of the parameters hard-coded changes the challenge enough to not make it a dupe

@JoKing But I don't think there's a lot of challenge which have an 1-byte Retina solution. Also, space are special for a lot of languages, see APL answer, 05AB1E answer and so much more.

@JoKing I won't argue, though. This is my first closed challenge!

APL (Dyalog Extended), 3 bytesSBCS
+/=

Try it online!
+/ sum the mask where = equal to the prototypical element of that element, which is space for characters.

Cool.  Is the idea of a prototypical element Dyalog specific?

@Jonah It is typical (!) of APL, although some new hobby implementations do not implement this. E.g. in APL2, APLX, and Dyalog is ' ' '   '(0 0 ' ') the prototype of 'a' 'abc'(1 2 'c')

Interesting.  Golang has the idea of a type's "zero value", but I've never come across anything analogous in J.

@Jonah While neat, it does cause various issues, like needing to call f each once on empty arrays to determine the prototype and inability to get a prototype from certain elements (e.g. objects), so Iverson and Hui decided J would only do specific prototypes for simple arrays, while all boxes would give a:, so ' '={.0$'hello' and 0={.0$1 2 3 and a:={.0$'hello';1 2 3

ah right!  that’s where i’d seen it in J!   thanks @Adám

Whitespace, 93 bytes
[S S S N
_Push_0][N
S S N
_Create_Label_LOOP][S N
S _Duplicate_top][S N
S _Duplicate_top][T N
T   S _Read_STDIN_as_character][T   T   T   _Retrieve_input][S S S T    S T S N
_Push_10][T S S T   _Subtract][S N
S _Duplicate_top][N
T   S T N
_If_0_jump_to_label_DONE][S S S T   S T T   S N
_Push_22][T S S T   _Subtract][N
T   S S N
_If_0_jump_to_label_SPACE][N
S N
N
_Jump_to_Label_LOOP][N
S S S N
_Create_Label_SPACE][S S S T    N
_Push_1][T  S S S _Add][N
S N
N
_Jump_to_Label_LOOP][N
S S T   N
_Create_Label_DONE][S N
N
_Discard_top][T N
S T _Print_as_integer]

Letters S (space), T (tab), and N (new-line) added as highlighting only.
[..._some_action] added as explanation only.
Since Whitespace inputs one character at a time, the input should contain a trailing newline so it knows when to stop reading characters and the input is done.
Try it online (with raw spaces, tabs and new-lines only).
An appropriate language for the challenge I guess. PS: The program itself contains 44 spaces.
Explanation in pseudo-code:
Integer counter = 0
Start LOOP:
  Character c = STDIN as character
  If(c == ' '):
    Call function SPACE
  Else-if(c == '\n'):
    Call function DONE
  Go to next iteration of LOOP

function SPACE:
  counter = counter + 1
  Go to next iteration of LOOP

function DONE:
  Print counter as integer to STDOUT

The irony of using whitespaces to find whitespaces!

Using Whitespace for this challenge is like using Unreadable for Tex Quotes.

05AB1E, 3 2 bytes
ð¢

Try it online!
Simple explanation:
 ð  Pushes ' ' space character onto stack
  ¢ Counts the spaces in the input string

Found the 'ð' Command which saves 1 Byte for pushing a space.

J, 8 bytes
1#.' '=]

Try it online!

PHP, 26 bytes
<?=count_chars($argn)[32];

Try it online!

That was quick. What, there's a built-in in PHP called "count_chars"? Wow!

@TwilightSparkle Probably the simplest challenge I have ever seen :P I will be surprised if this isn't already a duplicate. substr_count can also be used to count, but it will be 27 bytes: Try it online!

I will be surprised if this isn't a duplicate... too. But I searched a bit and didn't find anything.

C# (Visual C# Interactive Compiler), 20 bytes
I really hope this is not optimal

a=>a.Count(b=>b==32)

Try it online!

K (ngn/k), 6 4 bytes
-2 byte thanks to ngn
+/^:

Try it online!

" " -> 32

in k4 monadic ^ compares with null, which is " " for chars, so the solution could be +/^:

Jelly, 2 bytes
ċ⁶

Try it online!
Literally ċ count ⁶ spaces.

Perl 5, 7 bytes
$_=y; ;

Try it online!

PowerShell, 18 bytes
($args-eq32).count

Try it online.
Expects input via splatting.

CJam (5 bytes)
q' e=

Online demo
qS/,(

Online demo

Java 8, 27 bytes
s->s.split(" ",-1).length-1

Try it online.
Explanation:
s->                         // Method with String as parameter and integer return-type
  s.split(" ",              //  Split the input on spaces
              -1)           //  While retaining empty strings as items
                 .length    //  Get the amount of items in the array
                        -1  //  And subtract 1

Using the count() builtin with a filter for spaces would be 2 bytes longer (or 1 if the input is guaranteed to not contain tabs/newlines/other characters below spaces - in which case the ==32 can be <33):
s->s.filter(c->c==32).count()

Try it online.

Brachylog, 5 bytes
{∋Ṣ}ᶜ

Try it online!
{  }ᶜ    The output is the number of ways in which
 ∋       an element of the input can be chosen
  Ṣ      such that the element is a space.

Alternatively,
Brachylog, 5 bytes
ṇ₁l-₁

Try it online!
  l      The length of
ṇ₁       the input split on spaces
   -₁    minus one is the output.

JavaScript, 24 22 bytes
-2 bytes thanks to Shaggy and template literals!
s=>s.split` `.length-1

Try it online!

Python 3, 21 bytes
lambda s:s.count(' ')

Try it online!

Japt, 2 bytes
Yawn!
èS

Try it

Ruby, 15 bytes
->s{s.count' '}

Try it online!
Uhmmm...

Wolfram Language (Mathematica), 9 bytes
Count@" "

Try it online!
Takes a list of characters as input.

MathGolf, 5 bytes
gÅ =£

Input as a list of characters.
Try it online.
Explanation:
g      # Filter the (implicit) input-list
 Å     #  Using the following two commands:
   =   #  Equals a space
    £  #  Then pop this filtered list and get its length for the amount of spaces
       # (after which the entire stack joined together is output implicitly)

Or alternatively: mÅ =Σ (Try it online), which is similar but uses a map & sum instead of filter & length.


text:
1, 2, 4, 8, 16, ... 33?
Challenge
Write a function/program that outputs either the n'th element, or the first n elements, in the well known number sequence:
         1, 2, 4, 8, 16 ...

Oh, wait... I forgot the first few numbers:
1, 1, 1, 1, 2, 4, 8, 16 ...

Heck, I'll add a few more for good measure:
1, 1, 1, 1, 2, 4, 8, 16, 33, 69, 146, 312, 673, 1463, 3202, 7050, 15605, 34705 ...

The numbers are Generalized Catalan numbers given by the (zero-indexed) formula:
$$a(n+1)= a(n) + \sum_{k=2}^{n-1} a(k)\cdot a(n-1-k)$$
where
$$a(0)= a(1)= a(2)= a(3) = 1$$
This is OEIS A004149.
You may choose if you want to have the sequence zero- or one-indexed. The sequence must of course be the same, so you must rewrite the formula if you have it one-indexed.

Correct me if I'm wrong here, but the modification for a one-indexed formula is to change a(n-1-k) to a(n-k) , correct?

This reminds me of The strong law of small numbers

Python, 51 bytes
f=lambda n,k=2:n<3or k<n and f(k)*f(n-k-2)+f(n,k+1)

Try it online!
Simplifies the formula a bit:
$$a(n) =  \sum_{k=2}^{n-1} a(k)\cdot a(n-2-k)$$
$$ a(-1) = a(0)= a(1)= a(2) = 1$$

Congrats on the 100k!!

Since I also arrived to this solution independently, I must say that the path towards it is a bit bumpy...

05AB1E, 14 13 11 bytes
$ƒˆ¯Âø¨¨¨PO

Try it online!
Outputs the nth element, 0-indexed.
$                # push 1 and the input
 ƒ               # repeat (input+1) times
  ˆ              #  add the top of the stack (initially 1) to the global array
   ¯             #  push the global array
    Â            #  and a reversed copy of it
     ø           #  zip the two together, giving a list of pairs
      ¨¨¨        #  drop the last 3 pairs
         P       #  take the product of each pair (or 1 if the list is empty)
          O      #  take the sum of those products
                 #  after the last iteration, this is implicitly output;
                 #  otherwise, it's added to the global array by the next iteration

Perl 6, 44 bytes
{1,1,1,1,{sum @_[2..*]Z*@_[@_-4...0,0]}...*}

Try it online!
Anonymous code block that returns a lazy infinite sequence of values. This pretty much implements the sequence as described, with the shortcut that it zip multiplies all the elements so far after the second element with the reverse of the list starting from the fourth element and adding an extra 1 at the end.
Explanation:
{                                          }  # Anonymous code block
                                       ...*   # Create an infinite sequence
 1,1,1,1,                                     # Starting with four 1s
         {                            }       # Where each new element is:
          sum                                   # The sum of
              @_[2..*]                          # The second element onwards
                      Z*                        # Zip multiplied with
                        @_[@_-4...0  ]          # The fourth last element backwards
                                   ,0           # And 1

JavaScript (ES6), 42 bytes
A port of xnor's solution.
0-indexed.
f=(n,k=2)=>n<3||k<n&&f(k)*f(n+~++k)+f(n,k)

Try it online!

JavaScript (ES6),  83  75 bytes
A faster, less recursive, but significantly longer solution.
0-indexed.
f=(n,i,a=[p=1])=>a[n]||f(n,-~i,[...a,p+=(h=k=>k<i&&a[k]*a[i-++k]+h(k))(2)])

Try it online!

Haskell, 49 43 39 bytes
a n=max(sum[a k*a(n-2-k)|k<-[2..n-1]])1

Try it online!
For n<3 the sum is 0, so max ... 1 raises it to 1.
Edit: -6 bytes thanks to @Jo King.

Wolfram Language (Mathematica), 36 33 bytes
Sum[#0[#-i]#0@--i,{i,4,#}]~Max~1&

Try it online!
1-indexed.
The 2-indexed sequence is 2 bytes shorter: Sum[#0@i#0[#-i],{i,#-4}]~Max~1&.
Try it online!

Impressive that this is shorter than the built in CatalanNumber !

05AB1E, 17 13 bytes
4Å1λ£₁λ¨Â¦¦s¦¦*O+

Not shorter than the existing 05AB1E answer, but I wanted to try the recursive functionality of the new 05AB1E version as practice for myself. Could perhaps be golfed by a few bytes. EDIT: And it indeed can, see the recursive version of @Grimy's 05AB1E answer below, which is 13 bytes.
Outputs the first \$n\$ items: Try it online.
Could be changed to the 0-based \$n\$'th item when replacing £ with è: Try it online;
or an infinite list by removing £: Try it online.
Explanation:
This implements the formula used in the challenge description like this:
\$a(n)= a(n-1) + \sum_{k=2}^{n-1}(a(k)\cdot a(n-1-k))\$
\$a(0)=a(1)=a(2)=a(3)=1\$
   λ               # Create a recursive environment,
    £              # to output the first (implicit) input amount of results after we're done
4Å1                # Start this recursive list with [1,1,1,1], thus a(0)=a(1)=a(2)=a(3)=1
                   # Within the recursive environment, do the following:
      λ            #  Push the list of values in the range [a(0),a(n)]
       ¨           #  Remove the last one to make the range [a(0),a(n-1)]
        Â          #  Bifurcate this list (short for Duplicate & Reverse copy)
         ¦¦        #  Remove the first two items of the reversed list,
                   #  so we'll have a list with the values in the range [a(n-3),a(0)]
           s       #  Swap to get the [a(0),a(n-1)] list again
            ¦¦     #  Remove the first two items of this list as well,
                   #  so we'll have a list with the values in the range [a(2),a(n-1)]
              *    #  Multiply the values at the same indices in both lists,
                   #  so we'll have a list with the values [a(n-3)*a(2),...,a(0)*a(n-1)]
               O   #  Take the sum of this list
     ₁          +  #  And add it to the a(n-1)'th value
                   # (afterwards the resulting list is output implicitly)

13 bytes version of @Grimy (make sure to upvote his answer if you haven't yet!):
1λ£λ1šÂ¨¨¨øPO

Outputs the first \$n\$ items: Try it online.
Can again be changed to 0-based indexing or an infinite list instead:
- (0-based) indexing 1λèλ1šÂ¨¨¨øPO: Try it online;
- Infinite list λλ1šÂ¨¨¨øPO: Try it online. (Note that 2 bytes are saved here instead of 1, because the recursive environment starts with \$a(0)=1\$ by default.)
Explanation:
This instead implements the formula found by @xnor for his Python answer like this:
\$a(n) =  \sum_{k=2}^{n-1}(a(k)\cdot a(n-2-k))\$
\$a(-1) = a(0) = a(1) = a(2) = 1\$
 λ             # Create a recursive environment,
  £            # to output the first (implicit) input amount of results after we're done
1              # Start this recursive list with 1, thus a(0)=1
               # Within the recursive environment, do the following:
   λ           #  Push the list of values in the range [a(0),a(n)]
    1š         #  Prepend 1 in front of this list
      Â        #  Bifurcate the list (short for Duplicate & Reverse copy)
       ¨¨¨     #  Remove (up to) the last three value in this reversed list
          ø    #  Create pairs with the list we bifurcated earlier
               #  (which will automatically remove any trailing items of the longer list)
           P   #  Get the product of each pair (which will result in 1 for an empty list)
            O  #  And sum the entire list
               # (afterwards the resulting list is output implicitly)

Interesting that this can solve a(1200) in 40 second on tio, while other recursive approaches time out for numbers n than 100...

I also made (but didn't publish) a recursive version. It's 13 bytes for the first n terms, or 11 bytes for an infinite list. Special-casing a(n-1) costs a lot of bytes and isn't needed (see for example xnor's formula).

@Grimy Do you mind if I add your recursive solutions to my answer (crediting you of course)? I will leave my original answer as well. But it's nice to see the differences between the original formula and xnor's byte-saving formula. :)

Sure, that's fine!

@StewieGriffin Yeah, I was also impressed by the speed of these recursive infinite functions. Maybe one of Elixir's strengths, and definitely due to the builtin lazy-loading. It calculates n=100 in 0.65 seconds, but when I disable lazy-loading, it will time out after 60 seconds instead, even for n=25.

Python 3, 59 bytes
really inefficient, a(13) doesn't finish on TIO.

a=lambda n,k=2:n<4or(n-k<2)*a(n-1)or a(k)*a(n-k-2)+a(n,k+1)

Try it online!

APL (Dyalog Extended), 34 bytesSBCS
-2 thanks to dzaima.
Anonymous prefix lambda.
{⍵≤3:1⋄+/(∇⍵-1),⍵(-×⍥∇¯2+⊢)¨4…⍵}

Try it online!

@dzaima Thanks. TFW someone knows my language better than me :-)

Jelly, 17 bytes
1WṪ;+¥×Uṫ3SƲ;@Ʋ⁸¡

Try it online!
A monadic link taking the zero-indexed \$n\$ and returning the list of generalized Catalan numbers from \$0\$ to \$n\$.

Haskell, 76 bytes
1:1:1:f[1,1,1]
f(x:z)|y<-x+sum(zipWith(*)(init$init z)$reverse z)=y:f(y:x:z)

Try it online!

Japt, 19 17 16 bytes
Outputs the nth term, 1-indexed.
@Zí*Zz2)Å¤x}g4Æ1

Try it
@Zí*Zz2)Å¤x}g4Æ1     :Implicit input of integer U
@                    :Function taking an array as an argument via parameter Z
 Zí                  :  Interleave Z with
    Zz2              :  Z rotated clockwise by 180 degrees (simply reversing would be a bye shorter but would modify the original array)
   *                 :  Reduce each pair by multiplcation
       )             :  End interleave
        Å            :  Slice off the first element
         ¤           :  Slice off the first 2 elements
          x          :  Reduce by addition
           }         :End function
            g        :Pass the following as Z, push the result back to it and repeat until it has length U
             4Æ1     :Map the range [0,4) to 1s
                     :Implicit output of the last element

Charcoal, 26 bytes
Ｆ⁵⊞υ¹ＦＮ⊞υΣ✂Ｅ⮌υ×κ§υλ³→Ｉ§υ±⁴

Try it online! Link is to verbose version of code. Prints the 0-indexed nth number, although it calculates using 1-indexing internally. Explanation:
Ｆ⁵⊞υ¹

Start with a[0] = a[1] = a[2] = a[3] = a[4] = 1. Yes, this is 1-indexed, but then with an extra zeroth value. That's code golf for you.
ＦＮ

Calculate an additional n terms. This is overkill, but it makes finding the desired term easier when n<5.
⊞υΣ✂Ｅ⮌υ×κ§υλ³

For each term, compute the next term as the sum of the terms so far termwise multiplied by the reverse of the terms so far, excluding three terms.
→

This is a no-op used to trick Charcoal into parsing the 2-argument form of Slice, otherwise I would have to use a less golfy way of removing three terms.
Ｉ§υ±⁴

Output the 4th last term.

Pyth, 30 bytes
J*4]1VQ=+J+eJsPP*M.t,PJ_PJ0;<J

Try it online!
Returns the first \$n\$ elements of the sequence.
J*4]1VQ=+J+eJsPP*M.t,PJ_PJ0;<JQ # Full program, last Q = input (implicitly added)
J*4]1                  # J = 4 * [1] (=[1,1,1,1])
VQ                     # for N in range(Q):
  =+J                  #  J +=
     +eJ               #   J[-1] +
        s              #    sum(                           )
           *M          #     map(__operator_mul,          )
             .t      0 #      transpose(          , pad=0)
               ,       #       [       ,         ]
                PJ     #         J[:-1]
                  _PJ  #                 J[1::-1]
<JQ                    # J[::Q]

Alternative: Replace < with @ to return the \$n\$-th element of the sequence, 0-indexed.

Haskell, 65 bytes
f a|a<4=1|z<-g[2..a]=sum$zipWith(*)z$reverse(1:g[0..a-4])
g=map f

Try it online!
You can use either f to get a single element of a sequence, or pass a list of values to g and get all the indexes for that list.

Ruby, 42 41 bytes
f=->n{n<4?1:(4..n).sum{|i|f[i-1]*f[n-i]}}

Try it online!
1-indexed (to save 1 byte)

Octave, 73 bytes
g=(1:4).^0;for(i=3:(n=input('')))g(i+2)=g(4:i+1)*g(i-(2:i-1))';end;g(end)

Try it online!
-2 bytes thanks to Stewie Griffin. Once more, the imperative approach wins over the functional recursive approach. That one is shown below.
Octave, 75 bytes
f(f=@(a)@(n){@()sum(arrayfun(@(k)a(a)(k)*a(a)(n-2-k),2:n-1)),1}{2-(n>3)}())

Try it online!
Captcha wanted to verify I was a human when posting this. To be honest, I'm not so sure.

I can't see any obvious ways to shorten the loop approach... It looks pretty well golfed! Also, it's not often I see zero-based indexing in Octave :)

@StewieGriffin Since the recursion has some offsets it doesn't really matter if you pick zero- or one indexing. I think maybe I could shave some bytes of if I did 2-indexing, but that seemed like cheating. Anyway, your intuition was right - somehow, this was indeed shorter in an anonymous recursive way. I think the main advantage is that it handles creating the four initial values very well because it just returns 1 for n<4.

@StewieGriffin Of course, good old matrix multiplication. Well done!

Forth (gforth), 99 81 bytes
: f recursive dup 4 > if 0 over 3 do over 1- i - f i f * + loop else 1 then nip ;

Try it online!
Output is nth term and input is 1-indexed
Edit: Saved 17 bytes by switching to xnor's formula. Saved another 1 byte by using 1-indexed
Code Explanation
: f                     \ start a new word definition
  recursive             \ mark that this word will be recursive
  dup 4 >               \ duplicate the input and check if it is greater than 4
  if                    \ if it is:
    0 over              \ create an accumulator and copy n to top of stack
    3 do                \ start counted loop from 3 to n-1
      over 1- i - f     \ recursively calculate f(n-1-i)
      i f               \ recursively calculate f(i)
      * +               \ multiply results and add to accumulator
    loop                \ end the counted loop
  else                  \ otherwise, if n < 5
    1                   \ put 1 on the stack
  then                  \ end the if block
  nip                   \ drop n from the stack
;                       \ end the word definition

C/C++, 70 69 67 bytes
-1 bytes thanks to Jonathan.
int a(int n){int k=2,s=0;while(++k<n)s+=a(k)*a(n+~k);return s?s:1;}

Try it online!

Can a(n-1-k) be a(n+~k)?

@JonathanFrech even a(++k)*a(n-k) is likely to work, and it drops further 2 bytes from for. But I smell undefined behavior.

That appears to be a sequencing issue; most definitely UB.

Suggest s?:1 instead of s?s:1

Perl 5 -MList::Util=sum, 61 bytes
sub a{my$b=-2+pop;$b<2||sum a($b+1),map{a($_)*a($b-$_)}2..$b}

Try it online!