text:
Extract all keys from an object (json)
Description
Given an object (json), write code to extract all the keys from it. This is a question that I really wanted to ask everybody for a long time ago but I did not have time to write it up. It can be helpful in some cases in your daily work.
Rule:

You can use any parse function to get the JSON object, it does not cost you any bytes
Since a JSON object is a data structure that is not available in some languages, you can use any kind of data that has a similar structure in your favorite language.
To be clear, the input to your function should be a JSON object if it can.
The object can have nested keys.
The object can contain arrays and if it contains an array you will use the index of each element as a key.
Output can be a list with any format but it is preferred to be line by line.
The output keys can be arranged in any order, it does not matter.
Shortest bytes for each language will be win.
You can use any delimiter between each child key and its parent. Here I use . (please see the sample output for more detail).
The key can be a special character. For example:
The input I got from @tsh

{"":{"":4,".":5},".":2,"..":3}

But this is a special case and it is not required to handle it. You are better to avoid it.
Example
Given an object:
A = {
"name" : {
  "first": "jane",
  "last": "doe"
},
"lang" : ["html", "css"]
}

Then the output should be:
"name"
"name.first"
"name.last"
"lang"
"lang.0"
"lang.1"

The index key (0 and 1) are a little tricky here, so for some languages like Javascript, it can be [0] and [1] instead.
So the example below is also correct:
"name"
"name.first"
"name.last"
"lang"
"lang[0]"
"lang[1]"

A Sample test case:
Input:
{
    "quiz": {
        "sport": {
            "q1": {
                "question": "Which one is a correct team name in the NBA?",
                "options": [
                    "New York Bulls",
                    "Los Angeles Kings",
                    "Golden State Warriors",
                    "Houston Rockets"
                ],
                "answer": "Houston Rockets"
            }
        },
        "maths": {
            "q1": {
                "question": "5 + 7 = ?",
                "options": [
                    "10",
                    "11",
                    "12",
                    "13"
                ],
                "answer": "12"
            },
            "q2": {
                "question": "12 - 8 = ?",
                "options": [
                    "1",
                    "2",
                    "3",
                    "4"
                ],
                "answer": "4"
            }
        }
    }
}

Output:
[
  "quiz",
  "quiz.sport",
  "quiz.sport.q1",
  "quiz.sport.q1.question",
  "quiz.sport.q1.options",
  "quiz.sport.q1.options.0",
  "quiz.sport.q1.options.1",
  "quiz.sport.q1.options.2",
  "quiz.sport.q1.options.3",
  "quiz.sport.q1.answer",
  "quiz.maths",
  "quiz.maths.q1",
  "quiz.maths.q1.question",
  "quiz.maths.q1.options",
  "quiz.maths.q1.options.0",
  "quiz.maths.q1.options.1",
  "quiz.maths.q1.options.2",
  "quiz.maths.q1.options.3",
  "quiz.maths.q1.answer",
  "quiz.maths.q2",
  "quiz.maths.q2.question",
  "quiz.maths.q2.options",
  "quiz.maths.q2.options.0",
  "quiz.maths.q2.options.1",
  "quiz.maths.q2.options.2",
  "quiz.maths.q2.options.3",
  "quiz.maths.q2.answer"
]

This is my solution using jq:
jq -r '[paths|map(.|tostring)|join(".")]'

Full code:
jq -r '[paths|map(.|tostring)|join(".")]' file.json

The content of file.json is an object from input

[paths|map(tostring)|join(".")]

paths|map(@text)|join(".")

JavaScript (V8), 72 bytes
An edited version to support literal false, true and null values.
f=(o,s)=>!o|[o]==o||Object.keys(o).map(k=>f(o[k],k=s?s+[,k]:k,print(k)))

Try it online!

JavaScript (V8), 69 bytes
Takes a native JSON object as input. Prints the results, using a comma as the delimiter.
f=(o,s)=>[o]==o||Object.keys(o).map(k=>f(o[k],k=s?s+[,k]:k,print(k)))

Try it online!
How?
This is a recursive function walking through the keys at the root level and then in each sub-tree of the structure.
We need to process recursive calls on objects and arrays and to stop on strings and numbers. This is achieved with [o]==o||Object.keys(o):
 type of o | [o]==o    | Object.keys(o)  | string coercion example
-----------+-----------+-----------------+-------------------------------------
 array     | false     | 0-based indices | ['foo', 'bar'] -> 'foo,bar'
 object    | false     | native keys     | {abc: 'xyz'}   -> '[object Object]'
 string    | true      | n/a             | 'hello'        -> 'hello'
 number    | true      | n/a             | 123            -> '123'

fantastic, your answer beats @tsh, I am just curious what o.big is, could you please tell me about it?

awesome, you rock!

what does k=s mean? is that a condition test or an assignment of value..? does k=s sets k to equal s? But why is it in an if statement? or does it means if k==s? HELP

@danielassayag You should read this as k = (s ? s + [,k] : k).

@danielassayag Well, it could be written as if(s) k = s + [,k]; else k = k; but it's really just if(s) k = s + [,k]; since the else is pointless. However, you can't use a if within a function call anyway so you'd have to rewrite it entirely: .map(k=>{v=o[k];if(s)k=s+[,k];print(k);f(v,k);}).

Ruby, 108 146 115 92 bytes
+38 bytes to fix test cases for objects inside arrays.....
-31 bytes because we can take a parsed JSON object as input now.
-17 bytes by removing the duplicated flat_map usage.
f=->j,x=''{z=j==[*j]?[*0...j.size]:j.keys rescue[];z.flat_map{|k|[r=x+k.to_s]+f[j[k],r+?.]}}

Try it online!

JavaScript (Node.js), 75 bytes
f=o=>Object.keys(o+''===o||o||0).flatMap(k=>[k,...f(o[k]).map(i=>k+'.'+i)])

Try it online!

Python 2, 122 135 122 119 bytes
f=lambda d:`d`[0]in'{['and sum([[str(k)]+['%s.'%k+q for q in f(v)]for k,v in(enumerate,dict.items)['{'<`d`](d)],[])or[]

Try it online!
Now handles an even broader class of inputs, including lists of dicts.

PHP, 147 146 bytes
function f($j,$t){foreach($j as$k=>$v){if(is_array($v)){echo trim($t.="$k.",'.')."\n";f($v,$t);$t=str_replace("$k.",'',$t);}else{echo$t."$k\n";}}}

Try it online!
I'm sure that this is far from best solution in PHP, but I tried my junior talent. :D
$json = '{
    "name" : {
        "first": "jane",
        "last": "doe"
    },
    "lang" : [
        "html",
        "css"
    ]
}';

/** We need to define a text string variable. */
$text = ''; // or keysChainString

/** Assume that our json is decoded. */
$array = json_decode($json, true);

/**
 * Function that extract all multidimensional array keys.
 * The result will be as:
 * - firstKey
 * - firstKey.firstSubKey
 * - firstKey.firstSubKey.firstSubSubKey
 * - firstKey.secondSubKey
 * - secondKey
 * - etc.
 */
function extractAndFormatMultidimensionalArrayKeys($array, $text){
    /**
     * Iterate through array.
     */
    foreach($array as $key => $value) {
        /**
         * Check if key value is an array.
         * Echo key appended to previously declared $text variable.
         * Then make a recursive call to this function on that array.
         * After that, delete the key from text string.
         */
        if(is_array($value)) {
            echo trim($text .= "$key.", '.') . "\n";
            extractAndFormatMultidimensionalArrayKeys($v, $t);
            $text = str_replace("$key.",'',$text);
        /**
         * If the value is not an array, echo the text concatenated with the key.
         */
        } else {
            echo $text . "$key \n";
        }
    }
}

Welcome to Code Golf, and nice first answer! Be sure to check out our Tips for golfing in PHP page for ways you may be able to golf your program

Red, 159 bytes
func[s][r: :rejoin g: func[s m][foreach k keys-of m[print p:
r[s k]if map? t: m/:k[g r[p"."]t]if block? t[repeat n length?
t[print r[p"."n]]]]]g ""load-json s]

Doesn't work in TIO since load-json was introduced recently, but works fine in the Red console:

Wolfram Language (Mathematica), 39 27 bytes
MapIndexed[Echo@#2&,#,∞]&

Try it online! This function represents JSON arrays as Lists and objects as Associations. The function takes a JSON object as input and prints a set of part specifications to the standard output, each on their own line and preceded by >> . A part specification is a list of indices, where each index is a 1-based number or a string wrapped in Key. The index of a parent object is printed after those of its children. The output for the first example is:
>> {Key[name], Key[first]}
>> {Key[name], Key[last]}
>> {Key[name]}
>> {Key[lang], 1}
>> {Key[lang], 2}
>> {Key[lang]}

If the Key wrapper is undesirable, it can be removed using a 36-byte function:
Wolfram Language (Mathematica), 36 bytes
MapIndexed[Echo[#2/.Key->N]&,#,∞]&

The original challenge's formatting can be achieved with a 54-byte function:
Wolfram Language (Mathematica), 54 bytes
MapIndexed[Print@StringRiffle[#2/.Key->N,"."]&,#,∞]&

Julia 1.0, 57 bytes
!x=[(k->["$k";"$k.".*!x[k]]).(keys(x))...;]
!x::String=[]

Try it online!

R, 114 bytes
f=function(x){if(is.null(n<-names(x)))n<-seq(x);unlist(Map(function(y,z)c(z,if(is.list(y))paste(z,f(y))),x,n),,F)}

Try it online!
Defines a recursive function which takes an R list, possibly named, and returns the list of names using space as a separator. Here, a named list (or sub list) corresponds to an object in JSON, and an unnamed list corresponds to an array in JSON.


text:
What is my volume?
Given an input integer, output the volume corresponding to the value. The value will always be in the range \$[0,100]\$.
Examples
If the input \$=0\$:
 _/|
|  |\/
|_ |/\
  \|

If the input \$>0\$ and \$<33\$:
 _/|
|  |\
|_ |/
  \|

If the input \$\ge33\$ and \$<66\$:
 _/| \
|  |\ \
|_ |/ /
  \| /

If the input \$\ge66\$, \$\le100\$:
 _/| \ \
|  |\ \ \
|_ |/ / /
  \| / /

Rules

Input/output can be given by any convenient method.
You can print it to STDOUT or return it as a function result.
Either a full program or a function are acceptable.
Any amount of extraneous whitespace is permitted, provided the characters line up appropriately.
Standard loopholes are forbidden.
This is code-golf so all usual golfing rules apply, and the shortest code (in bytes) wins.

You should have based the volume on 0 - 10 so that someone could answer with "mine goes to 11"

JavaScript (ES6), 98 bytes
n=>` _/|2
|  |\\0
|_ |/1
  \\|3`.replace(/\d/g,k=>n?(k&1?' /':' \\').repeat(n/33^n>98):['/\\'[k]])

Try it online!
How?
We use the following template:
 _/|2
|  |\0
|_ |/1
  \|3

If \$n=0\$ (volume muted):

\$0\$ is replaced with / and \$1\$ is replaced with \
the other digits are removed

If \$n\neq 0\$:

odd digits are replaced with the string " /" repeated \$k\$ times
even digits are replaced with the string " \" repeated \$k\$ times

where \$k\$ is defined as:
$$k=\cases{\left\lfloor n/33\right\rfloor&\text{$n<99$}\\
2&\text{$n\ge 99$}
}$$

for 99 and 100, output has an unnecessary line

@NahuelFouilleul Thanks for reporting this. Now fixed.

05AB1E, 65 64 bytes
„ /SõD‚„\ Â‚D4δ∍D)T•4aÖ™é•“| 0\
1/“ÅвJrI33÷IĀ+©è‡∊'_1•uтÄ•22в®è‚ǝ

When I started I thought I would be able to make this pretty short with the approach I had in mind, but it had some annoying edge cases to fix.. Can definitely be golfed, though. Will take another look later on.
Try it online or verify some more test cases.
Explanation:
„ /              # Push string " /"
   S             # Convert it to a list of characters: [" ","/"]
õD‚              # Push an empty string "", duplicate it, and pair them together: ["",""]
„\               # Push string "\ "
   Â             # Bifurcate it (shorter for duplicate and reverse copy)
    ‚            # Pair them together: ["\ ","\ "]
D                # Duplicate it
 4δ∍             # Extend both inner strings to size 4: ["\ \ ","\ \ "]
D                # Duplicate it
)                # Wrap all lists on the stack into a list:
                 #  [[" ","/"],["",""],["\ ","\ "],["\ \ ","\ \ "],["\ \ ","\ \ "]]
T                # Push 10
•4aÖ™é•          # Push compressed integer 17523821317
“| 0\
1/“              # Push string "| 0\\n1/"
   Åв            # Convert the integer to custom base-"| 0\\n1/"
     J           # And join these characters together to a single string:
                 #  "  /| 1\n
                 #   |  |\0"
r                # Reverse the items on the stack (list, 10, string to string, 10, list)
 I33÷            # Push the input, and integer-divide it by 33
     IĀ          # Push the input again, and truthy it (0 if 0; else 1)
       +         # And add them together (0→0; 1..32→1; 33..65→2; 66..98→3; 98..100→4)
        ©        # Store it in variable `®` (without popping)
         è       # And index it into the list we created at the start
          ‡      # Then transliterate the ["1","0"] of 10 to the strings in this pair
∊                # Now vertically mirror the entire string
                 #  (i.e. "  /|  \n
                 #         |  |\/" becomes:
                 #   "  /|  \n
                 #    |  |\/\n
                 #    |  |/\\n
                 #      \|  "
    •/Tδ•        # Push compressed integer 7095187
         ₂в      # Converted to base-26 as list: [15,13,17,21,21]
           ®     # Push variable `®` again
            è    # Index it into this list
   1         ‚   # Pair it with a leading 1
 '_           ǝ '# And insert a "_" at those 0-based positions inside the string
                 # (after which the result is output implicitly)

See this 05AB1E tips of mine (section How to compress large integers? and How to compress integer lists?) to understand why •4aÖ™é• is 17523821317; •/Tδ• is 7095187,  and •/Tδ•₂в is [15,13,17,21,21].

Python 2, 111 101 90 bytes
n=input()
for s in'\ _/|','\|  |\/','/|_ |/\\','/  \|':print s[1:6+0**n],s[:n>32],s[:n/66]

Try it online!
-11 bytes, thanks to xnor

Nice method! I found a way to shorten it by encoding b in the first character of each string rather than as a zip, and extracting from there: Try it online!

@xnor Wow nice! Thanks :)

Lua, 308 259 246 242 219 180 bytes
i=io.read("*n")
print(i<1 and[[ _/|
|  |\/
|_ |/\
  \|]]or i<33 and[[ _/|
|  |\
|_ |/
  \|]]or i<66 and[[ _/| \
|  |\ \
|_ |/ /
  \| /]]or[[ _/| \ \
|  |\ \ \
|_ |/ / /
  \| / /]])

Try it online!
New to code golf and coding in general.

Thanks to all comments for their help!

Hey, quick tip: the input is guaranteed to be within $[0, 100]$ so you don't need to check that it is less than 101. Also your third line doesn't appear to be necessary.

Third line? Edited now so may be different, but all were necessary excluding the 100/0 input check..

yes my comment was made before your edit :) Anyways, you are still unnecessarily checking for $i<101$, when it is guaranteed that $i<101$.

You can replace i==0 with i<1

do p=print to shorten it

also use [[long strings like this to not escape \ and newlines]]

Use "if-expressions" in order to golf your code. (Shorter than the existing Lua solution!)

Oh, I forgot about or/and's other uses. Explanation for people uneducated: Lua's or returns the first argument if true, the second if false - the opposite is true for and.

PowerShell, 113 bytes
param($n)' _/|'+($y=' \'*($x=($n-ge33)+($n-ge66)))
'|  |\'+($y,'/')[!$n]
'|_ |/'+(($z=' /'*$x),'\')[!$n]
"  \|$z"

Try it online!

Perl 5 (-p), 86 bytes
inspired from @Arnauld's solution
$_=' _/|3
|  |\\1
|_ |/0
  \|2'=~s,\d,$_?" $&"x($_/33-$_/99):$&<2&&$&^1,ger;y;0213;//\

Try it online!

Charcoal, 40 bytes
ＮθＦ AＦ›θ℅ι \Ｃ¹¦¹⸿\Ｆ¬θ/‖Ｍ↓⸿←Ｐ↑⁴←↖¹←_↑² _/

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

Input the volume.
Ｆ AＦ›θ℅ι \

Output a space and a \ for each character ordinal in space and A that the volume is greater than. In other words, output once for inputs of 33 or more and twice for inputs of 66 or more.
Ｃ¹¦¹

Copy the \s one square diagonally.
⸿\

Output an extra \ at the start of the second line.
Ｆ¬θ/

If the volume was zero then add a /.
‖Ｍ↓

Reflect to complete the volume.
⸿←Ｐ↑⁴←↖¹←_↑² _/

Draw the speaker symbol.

PowerShell, 94 92 bytes
param($n)33,66-le$n|%{$y+=' \';$z+=' /'}
" _/|$y
|  |\$y"+'/'*!$n
"|_ |/$z"+'\'*!$n
"  \|$z"

Try it online!

Keg, -hd 167 bytes
¿:0=[` _/|\n|  |\\/\n|_ |/\\\n  \\|`|:1\!"∂[` _/|\n|  |\\\n|_ |/\n  \\|`|:\!B"∂[` _/| \\\n|  |\\ \\\n|_ |/ /\n  \\| /`|` _/| \\ \\\n|  |\\ \\ \\\n|_ |/ / /\n  \\| / /`

Try it online!
Definitely golfable by using variables and string formatting. That's what Imma go do now. Anyhow, it acts as a sort of switch statement to determine which range the volume is in and prints the corresponding string.
Nevermind. Variables only make the program longer.

Canvas, 32 27 26 bytes
┤＃Mi‾‟⁸？⁸‾｛÷ｕ２ｍ２＼×＋］ ¶/＋｝═

Try it here!

Python 3, 109 bytes
lambda n:'\n'.join(i[:5+0**n]+(n//33*(' '+j))[:4]for i,j in zip([' _/|','|  |\\/','|_ |/\\','  \|'],'\\\//'))

Try it online!

Lua, 196 bytes
i=tonumber(io.read())
t=[[ _/|%s
|  |\%s
|_ |/%s
  \|%s]]
t=(i==0 and t:format("","/","\\","")) or t
while i>=33 do t=t:format(" \\%s"," \\%s"," /%s"," /%s");i=i-34 end
t=t:gsub("%%s","")
print(t)

Try it online!
A bit shorter (below 200) than the other Lua answer.

source: Stack Exchange

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

sort: votes


text:
Print all the ways to aquire specific number using only specific numbers
Let's say we have some arbitrary number:
For example 25. We also have some "tokens" (poker chips, money, something similar) with different values.
Values of tokens are
2; 3; 4; 5.
"Tokens" are limitless
You need to achieve number 25 using exactly n tokens (for example, 8) and to output all possible ways of doing so.
Fragment of example expected output (25 with 8 tokens):
3 '5' tokens, 5 '2' tokens
2 '5' tokens, 1 '4' token, 1 '3' token, 4 '2' tokens
....
1 '4' token, 7 '3' tokens

You may output in any reasonable, non-ambiguous format. For instance, 3 '5' tokens, 5 '2' tokens can be represented as a single list [5,0,0,3] or as a list of tuples [[3,5],[5,2]]. And if there's no solution, you can provide empty output (or state no solution found or something among the lines)
Standard code golf rules apply, so winner is decided by shortest byte count (though you have to also provide "commented" version of your code, especially for languages such as Brainfuck, Jelly, Piet and so on)
Edit:
 I intended this challenge as challenge with fixed tokens, but I like universal answers more then "niche" ones even if it's not specified in challenge itself initially. As long as making tokens "third input parameter" still provides correct answer for tokens provided it's accepted for this challenge. If you are willing to rewrite your code - go on, save those precious bytes/chars.

@Arnauld, Oh, sorry. I'm very new to this community. How should I add standard LoC winning criteria and probably rewrite this challenge so that input and ouput is still readable and not to limit participants to much?

I'd suggest something along these lines: You may output in any reasonable, non-ambiguous format. For instance, 3 '5' tokens, 5 '2' tokens can be represented as a single list [5,0,0,3] or as a list of tuples [[3,5],[5,2]]. And if there's no solution, the output should just be empty.

By the way: welcome to Code Golf! I hope you'll enjoy your stay here.

Any number will be possible, correct?

Can we provide the same combination, but in a different order? e.g. [3 5s, 5 2s] and [5 2s, 3 5s]?

Can we take input arguments as a vector with an int in it?

Are 2,3,4,5 always the tokens, or is that part of the input too and that's just the example?

@JosephSible I intended this challenge as challenge with fixed tokens, but I like universal answers more then "niche" ones even if it's not specified in challenge itself. If taking tokens to "third input parameter" makes your solution shorter but still provides correct answer for tokens [2,3,4,5] - I would accept it

@stephanmg let's limit it by MAX_INT, I don't think going for some BigInteger values will make this challenge any more intersting

@JoKing [3 5s, 5 2s] and [5 2s, 3 5s] is same combination. So if you provide it in both ways In same solution I would say that you are just overdoing your work. If you are asking about order of tokens in combination, it doesn't really matter, but I would like ascending or descending order more

@gggg Input can be in any reasonable way. stdin, file, arguments of command line, string separated by some special symbols (like "," or ";")

Jelly, 10 bytes
ŒṗfƑƇL=¥Ƈ⁵

Try it online!
A full program that takes the total, token values and number of arguments as its arguments. Returns a list of lists of token values.
Explanation
Œṗ          | Integer partition (of first argument)
    Ƈ       | Keep only those which:
   Ƒ        | - are invariant when:
  f         |   - filtered to only include the (implicit) second argument.
       ¥Ƈ   | Keep only those for which:
     L      | - the length
      =  ⁵  |   - is equal to the third argument

Wow. I'll probably never understand Jelly but it always seem to provide shortest solution. Congrats. And bonus points for providing a way to input tokens.

@SheykoDmitriy The Jelly answer is the only one that takes the [2,3,4,5] as third input instead of hard-coding it, though. Which of the two is correct? Could you answer @JosephSible's comment on your challenge?

@KevinCruijssen I’d interpreted it as being part of the input, rightly or wrongly.

@NickKennedy I can understand. I also read it like that as first. But I noticed all other answers are hard-coding it instead, and I also noticed Joseph's question regarding it. If it's a third input, the 05AB1E answer for example could be 7 bytes, and I'm sure some of the other answers would be able to save some bytes as well. If it's indeed intended to be a third input as we both thought when reading the challenge.

J, 35 32 bytes
~.@((=1&#.)#])2+#&4/:~@#:[:i.4^]

Try it online!

Count in base 4 from 0 up to 4 ^ num_tokens to generate all the raw possibilities: #&4/:~@#:[:i.4^]
Add 2 to all numbers so the tokens will have 2 3 4 5 labels instead of 0 1 2 3 labels: 2+
Sort each possibility in preparation for removing dups: /:~@
Filter the raw possibilities to include only those with the correct sum: ((=1&#.)#])
Take the uniqs: ~.@

Perl 6, 64 bytes
{grep(*.sum==$_,|($/=2..5),|(+<<[\X] $/xx$_)[*;*])>>.Bag.unique}

Try it online!
Fails for inputs above 7 due to Too many arguments in flattening array.This is because we are generating a list of every possible combination with repetition of numbers up to length n (where n is the same as the input), and not just that, but every possible ordering as well. Ah well, the price of being golfy...
This takes a number and returns a Bag, which is an unordered list of numbers and the amount in the bag.

Haskell, 63 bytes
n%k=[l|l<-mapM(\_->[0..n])"xnor",sum l==k,sum(scanr(+)0l)==n-k]

Try it online!
A cute trick is used to check the list sum. We're looking for for elements l=[a,b,c,d] with a+b+c+d=k (right number of tokens) and 2*a+3*b+4*c+5*d==n (right total value). Subtracting the first equation from the second gives a+2*b+3*c+4*d==n-k. To get a+2*b+3*c+4*d, we do scanr(+)0 l to get the reversed cumulative sum [a+b+c+d,b+c+d,c+d,d,0] and take the sum of its elements.
The solution brute-forces using mapM to generate all possible quadruples of token counts.

71 bytes
n%k=filter(all(>=0))[[a,4*k-n-2*a+d,n-3*k+a-2*d,d]|a<-[0..n],d<-[0..n]]

Try it online!
A longer direct solution. We try all a and d, and for each possibility we solve for b and c and check if they are non-negative positive.

68 bytes
(%)2
6%t=[[]|t==(0,0)]
x%(v,c)=do y<-[0..c];(y:)<$>(x+1)%(v-x*y,c-y)

Try it online!
Golfing Joseph Sible's solution. Takes input uncurried like (25,8).

JavaScript (V8),  94  82 bytes
Takes input as (sum)(n). Prints the solutions, as lists of token values.
s=>(g=(n,t=0,u=[])=>n?[2,3,4,5].map(v=>v>u[0]||g(n-1,t+v,[v,...u])):t-s||print(u))

Try it online!
Commented
s => (              // s = expected sum
  g = (             // g is a recursive function taking:
    n,              //   n   = expected number of tokens
    t = 0,          //   t   = current sum, initialized to 0
    u = []          //   u[] = list of tokens
  ) =>              //
    n ?             // if n is not equal to 0:
      [2, 3, 4, 5]  //   for each allowed token value v:
      .map(v =>     //
        v > u[0] || //     abort if u[] is non-empty and v is greater than the last
                    //     token value (which is actually stored at the beginning)
        g(          //     otherwise, do a recursive call:
          n - 1,    //       decrement n
          t + v,    //       add v to t
          [v, ...u] //       prepend v to u[]
        )           //     end of recursive call
      )             //   end of map()
    :               // else:
      t - s ||      //   if t = s:
        print(u)    //     this is a solution: print it
)                   //

I like the way you format your code for explanations.  Do you do it by hand or use a program you've written?

@Jonah Every once in a while, the idea of writing a program crosses my mind. And then I say to myself: "oh well, let's do this one manually for now..."

Wow. Taking off my hat. Nice formatting and thorough comments. That's the way I like to see code!

Pyth, 21 20 bytes
{mSdfqhQsT.c*hQr2 6e

Try it online!
Saved a byte because the last Q is implicit
Returns a list of token combinations (e.g. [3, 3, 4] for 2 '3' tokens and 1 '4' token) which seems like a reasonable, non-ambiguous format, so I'll leave it unless the rules are changed. Takes input as value, n. Return an empty list if there are no valid combinations (I think)
Also hopelessly slow, so dont pick a value thats too high.
How it works
{mSdfqhQsT.c*hQr2 6e (Q)
            *hQ        - Multiply the first input by...
               r2 6    - The range 2,6 (2..5)
          .c       e(Q)- All combinations of the above that are the length of the
                        second input (Q is implicit)
    fqhQsT             - Filter to elements where the sum is equal to the first input
 mS                    - Sort all elements
{                      - Remove duplicates

05AB1E, 11 bytes
ÅœIùʒ5L¦ÃyQ

Try it online!
Outputs list of token values.
Explanation
Åœ            | Take all integer partitions of the target number
  Iù          | Only keep those of length n
    ʒ         | Filter by:
     5L¦      | Push [2,3,4,5]
        ÃyQ   | Check if partition is equal to its intersection with [2,3,4,5]
              | Filter it out if not

Wolfram Language (Mathematica), 36 bytes
Not really golfed. There is a built-in for this in Mathematica.
IntegerPartitions[#,{#2},{2,3,4,5}]&

Try it online!

Charcoal, 30 bytes
ＮθＮηΦＥＸ⊕θ⁴⭆⮌↨ι⊕θ⭆λ⁺²μ∧⁼Ｌιθ⁼Σιη

Try it online! Link is to verbose version of code. Outputs a list of strings each of n tokens sorted in ascending order (if they had been sorted in descending order then the list itself would be in ascending order). Explanation:
ＮθＮη

Input n and the target.
ΦＥＸ⊕θ⁴

Loop over the range 0..(n+1)⁴.
⭆⮌↨ι⊕θ

Convert each value to base (n+1) as an array with least significant digit first.
⭆λ⁺²μ

Convert each array to a string of tokens 2..5 and concatenate the results.
∧⁼Ｌιθ⁼Σιη

Only output those strings with a length of n and the correct digital sum.

Haskell, 75 67 bytes
f(x:l)v c=do y<-[0..c];(y:)<$>f l(v-x*y)(c-y)
f[]0 0=[[]]
f[]_ _=[]

Try it online!
-8 bytes by taking the tokens as input
The last two lines could be replaced with either f[]v c=[[]|v==0,c==0] or f n v c=[n|v==0,c==0], both keeping the same byte count. Perhaps there's a way to golf one of those variants further that I'm not seeing though.

Python 3, 97 bytes
lambda s,n:{(*sorted(i),)for i in product([2,3,4,5],repeat=n)if sum(i)==s}
from itertools import*

Try it online!

Python 3, 106 bytes
lambda s,n,r=range:{(i,j,k,n-i-j-k)for i in r(n+1)for j in r(n-i+1)for k in r(n-i-j+1)if 5*n==s+3*i+2*j+k}

Try it online!
This function iterates over 3 variables i, j and k. The fourth variable follows from the difference between the number of tokens n and ijk. A combination is valid if 2*i+3*j+4*k+5*(n-i-j-k)==s. This condition rearranges to 5*n==s+3*i+2*j+k.

Julia 1.0, 67 bytes
f(s,n,q=0:n)=[[a b c d] for a=q,b=q,c=q,d=q if[a b c d]*(2:5)==[s]]

Generates values representing how many tokens there are, then uses matrix multiplication to calculate the total. It seems like there should be a way to avoid typing [a b c d] twice, but I'm not aware of it.
Try it online!

Japt, 22 bytes
V*4 o î6o2)àV â f_x ¥U

Try it
Returns arrays of tokens.
Not really efficent though.

(V * 4).o() // create an array of 4 times every token
.î(6 .o(2)) // repeat 2 to 5 inside it
.à(V).â() // all unique combinations
.f(function(Z) { return Z.x() == U }) // remove the wrong combinatons

Flag -Q to pretty print the result

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


text:
1D Shikaku Validation
Shikaku is a 2D puzzle. The basic rundown of it is that a rectangular grid has some numbers in it, and you want to partition the grid into rectangular components such that each component contains exactly one number which is the number of grid squares in that component.
This challenge involves a 1D simplification of this: it is a line of N squares with K numbers \$\{a_1, a_2, \cdots, a_K\}\$, and a solution would be a division of the line into K partitions such that each partition contains \$a_i\$ squares. However, in this simplification, not all squares need to be used.
Challenge
Given a list of N numbers (where 0 is an empty square), determine if a valid solution to that problem exists.
Truthy Cases
(_ is a blank; it will be given as 0 in the input. you may not take the input as an index:element mapping)
 _ _ 3 _ _ 5 _ _ 3 _ _
([   ] [       ] [   ])

 2 _ _ _ _ 6 _ _ _ 4 _ _
([ ] [         ] [     ])

 _ 5 _ _ _ 3 _ _ _ _ _ 4
([       ] [   ] [     ])

 _ _ 2 _ _ _ _ 4 _ _
(  [ ]       [     ])
(    [  ]  [     ]  ) just to give 2 examples

Falsy Cases
_ _ 2 _ 4 _
_ 3 _ _ 5 _ _ 3 _
_ _ 5 _ _ _ 3
_ 2 _ 2 _ 2 _ 3

Rules and Specifications
Input can be taken as any convenient way to take a list of numbers. You can input it as a string with _ for blanks as well; etc. Any reasonable method; however, you may not change the general structure of the input as a list.
Output is a true/false value. Any truthy/falsy value is acceptable. The true/false value does not have to be consistent across cases, but your program must give the same exact answer for the same test case every run, and please specify how truthy/falsy is distinguished if it's not conventional. For example, you can output 1 for a true case and 2 for another, and 0 for false cases, but the first case must always yield 1 every time, and the second must give 2 every time.
To prevent a loophole brought up thanks to @xnor, your output must be successful / failed completion as a result, numbers, booleans, or other similar "primitive-like" datatypes (basically, you cannot submit the identity function and say that the Truthy/Falsy sets are divided by this problem's specifications).

Standard loopholes are forbidden.
This is code-golf, therefore the shortest answer in each language wins. No answer will be accepted.

I'm unclear what's allowed for to represent True/False outputs. It sounds like they still have to be Truthy/Falsey, but your suggestion to "declare that None and positive integers mean 'False' and 0 means 'True' " on Riolku's Python answer seems to mix Python's Truthy/Falsey values for the two cases. Does at least one of True/False need to correspond to a single fixed output? Presumably you don't want the loophole of just outputting the input as a solution with the claim "Only outputs that fit the problem criterion count as Truthy."

@xnor I basically mean that the output must never change between runs of the same input, and you must be able to define two disjoint sets of possible outputs, one set being truthy and one set being falsy.

Right, but what's stopping me from submitting the identity function, and saying the two disjoint subsets for true/false happen to be those defined by the challenge validation condition?

@xnor Hmm, good point. I didn't think of that. I'm going to update it so that valid outputs (other than things like nothing / failure like with your submission) only "primitive-like" datatypes can be output, like numbers or booleans, since that doesn't break any existing solutions

Can input use a character (not number) for blanks? For example _?

@Night2 Sure. I'll update the rules to make it a bit more flexible.

JavaScript (ES6),  56  52 bytes
Returns a Boolean value.
a=>![...a,1].some(x=>t>0/x?1:(t+=x-1)*x<0?t=0:0,t=0)

Try it online!
Commented
The accumulator \$t\$ is decremented whenever an empty slot is encountered. For each non-zero value \$x\$, we update \$t\$ to \$max(t+x-1,0)\$. The test fails if we reach a non-empty slot (or the end of the list) with \$t>0\$.
a =>               // a[] = input
  ![...a, 1]       // append a '1' at the end of a[] to force a last test
  .some(x =>       // for each value x in the updated array:
    t > 0 / x ?    //   if x = 0, this test is always falsy (0 / 0 -> NaN)
                   //   if x ≠ 0 and t is greater than 0:
      1            //     failed: yield 1
    :              //   else:
      (t += x - 1) //     add x - 1 to t
      * x < 0 ?    //     if t is negative and x ≠ 0:
        t = 0      //       we have accumulated more empty slots than
                   //       we can consume here: set t to 0
      :            //     else:
        0,         //       do nothing
    t = 0          //   start with t = 0
  )                // end of some(); return the opposite result

Python 3, 96 87 85 bytes
def f(a):
	c=p=0
	for x in a:
		if p*x:return
		p|=x;c+=1
		if c>=p>0:c=p=0
	return p

Try it online!
-5 bytes thanks to 79037662.
-6 bytes thanks to HyperNeutrino.
None and positive are falsy, 0 is truthy.

Welcome to Code Golf!

Can p and x be changed to p*x?

Can the c=0,p=0 in the parameters be replaced with c=p=0 in the function body? -5 bytes with these changes: https://tio.run/##XU1BDoMgEDzLK/aILQettgdb@heiEEkM3RBsbdK/U1CoSdmwOzM7A/h248M03g9SgaKi7EjRc@QVKdTDwgLagAhaoRXgYemsdLM1geOHL9f@yOu0A2EG6O8cuxTfnIC32r9GPUlax7fRauOoovIpJqoNzo6W4fiKVaxhsZ/ZD5PTimNd0mxXPbtyJu1I7HsmezetXfHfH2RngZPNmW/zBQ

I was trying to think of a better way to do p and x, thanks! Also moving it into the function body is something I had considered but not tried... thanks as well.

By abusing my output formatting, you could just return p at the end and declare that None and positive integers mean "False" and 0 means "True"

Python 2 via exit code, 52 bytes
n=0
for x in input()+[1]:x*n<0>_;n+=x<1or-max(x-1,n)

Try it online!
Successful completion for True, error for False.
-1 byte thanks to Arnauld.

PowerShell, 56 55 54 47 bytes
inspired by Arnauld's one accumulator code.
!($args+1|?{$_;$t+=$_-1}|?{$t-ge$_;$t*=$t-ge0})

Try it online!

Retina 0.8.2, 34 bytes
^
,
\d+
$*
\b
;
+1`,;1|1;,
;
^\W*$

Try it online! Explanation:
^
,

Prepend a , so that there's one , for each square.
\d+
$*

Convert the entries to unary.
\b
;

Surround each non-empty square with ;s.
+1`,;1|1;,
;

Each ; in turn starts eating away at the adjacent empty squares.
^\W*$

Check that there were no 1s left.
After adding the prefix and the unary conversion, .NET is actually able to solve the problem in a single regex, although it weighs in at a massive 58 bytes:
^
,
\d+
$*
^(,*(,)*(?<-2>1)*(?(2)^)(1)*(?<-3>,)*(?(3)^))*$

Try it online!

J, 47 bytes
[:*/2(>+.0>:[)/\[:(++(0>.0-+)*0<+-])/@|.\<:@,&1

Try it online!
Credit to Arnauld for the high-level idea.
I'll add explanation and golf more soon.

Jelly, 20 bytes
ŒṖT€ẈỊẠƲƇðẈẋ`€F⁹a⁼ðƇ

A monadic Link accepting a list of non-negative integers which yields a list. An empty list is falsey, a non-empty list is truthy. (The list is actually all ways which work).
Try it online! Or see a test-suite.
How?
ŒṖT€ẈỊẠƲƇðẈẋ`€F⁹a⁼ðƇ - Link: list, S
ŒṖ                   - all partitions (of S)
        Ƈ            - filter keep those for which:
       Ʋ             -   last four links as a monad:
   €                 -     for each:
  T                  -       truthy indices
    Ẉ                -     length of each
     Ị               -     insignificant (for our purposes: is in (0,1)?)
      Ạ              -     all truthy?
                   Ƈ - filter keep those for which:
         ð        ð  -   the dyadic link - i.e. f(partition, S)
          Ẉ          -     length of each
             €       -     for each:
            `        -       use left as both arguments of:
           ẋ         -         repeat (i.e. 5 -> [5,5,5,5,5])
              F      -     flatten
               ⁹     -     chain's right argument (S)
                a    -     logical AND (vectorises)
                 ⁼   -     is equal to (S)?

J, 28 bytes
[:*/1>1&,*([0&>.<:@+)/\.@,&0

Try it online!
Inspired by Arnauld's algorithm. 1 if a solution exists, 0 otherwise.
How it works
In order to retain intermediate values of t, I chose to use "Reduce on suffixes" /\. with the initial value appended. Given a function f, the result of f/\. looks like this:
Input array: 0 0 2 2 2 0 0 0
Index 0: 0 f 0 f 2 f 2 f 2 f 0 f 0 f 0 (right-assoc for everything)
Index 1:     0 f 2 f 2 f 2 f 0 f 0 f 0
Index 2:         2 f 2 f 2 f 0 f 0 f 0
...
Index 6:                         0 f 0
Index 7:                             0

Explanation of full code:
[:*/1>1&,*([0&>.<:@+)/\.@,&0  Right argument: 1D Shikaku grid
                              ex. 0 0 2 2 2 0 0 (expected: falsy)
                         ,&0  Append the starting value of t=0
                              ex. 0 0 2 2 2 0 0 0
                     /\.@     Reduce from right and keep intermediate values...
          (         )           (left: x, right: t, output: t')
                <:@+            Compute y = x + t - 1
           [0&>.                Compute max(0, y) x times; simply y if x = 0
                              ex. 0 1 2 1 0 -2 -1 0
      1&,*                    For each element, match the current value of x with
                              the previous value of t (including the finish),
                              counting from the right
                              ex. 0 0 0 2 0 -4 0 0
[:*/1>                        Check if all of them are zero or less

Golfing the next-t algorithm
If x is empty, decrement t; otherwise compute max(t+x-1, 0)
->
If x is empty, compute t+x-1; otherwise compute max(t+x-1, 0)
->
Compute t+x-1; if x is nonempty, apply (y => max(y, 0))
->
Compute t+x-1; apply (y => max(y, 0)) x times (assume x >= 0)


text:
Currency exchange
You are starting up a cryptocurrency exchange website which supports conversion from USD to two currencies, foo-coin and bar-coin. Write a program that takes the exchange rate for each coin to USD as arguments and outputs the maximum value of USD that cannot be completely divided into the two currencies (assuming these crypto-coins can only be purchased as full coins):
e.g.
If the two exchange rates are $23 and $18, then 41 dollars could be split into 1 foo-coin and 1 bar-coin, but there is no way to completely split 42 dollars between the two coins. The output of the program for these two values is 373, as that is the largest dollar amount that CANNOT be divided into whole values of foo-coin and bar-coin.
Winner is the program with the fewest characters.
edit:
You may assume the GCD of the two rates is 1

Can you add more test cases? I am not sure I even understand the question. What does "cannot be completely divided into the two currencies" mean in this case? How is 373 "completely divided" into foo-coin and bar-coin?

@wislaw does the updated description clarify things well enough?

This is a simpler version of this challenge.

What's the expected output if $\gcd(x,y)\neq 1$? Or is it guaranteed that it won't happen?

The title of exchange rates is confusing. It made me think the challenge would be about converting an amount in one currency to another given the exchange rate.

@xnor sorry about that, do you have a suggestion for a better title?

@Arnauld I would say that cases where gcd(x,y)≠1 can be ignored

05AB1E, 3 bytes
<P<

Try it online!
This is of course only assuming that the greatest common denominator of the inputs (exchange rates) is 1, because otherwise this number is not well-defined.
Explanation:
The number we want to compute is called the Frobenius Number and can be calculated with the formula \$\operatorname{Frob}(a,b) = (a-1)(b-1) - 1\$.
<    | Subtract 1 from each input
 P   | Take their product
  <  | Subtract 1

Pyth, 7 bytes
t*thQte

Try it online!
As @Wisław pointed out, this is simply the Frobenius Number. Also uses (a-1)(b-1)-1, as the alternate ab-a-b is a bit longer.
How it works
 *thQ   - Multiply the first number minus one
     te - By the second number (the Q is implicit) minus one
t       - Minus one

Swift, 42 bytes
func d(f:Int,b:Int)->Int{return f*b-(f+b)}

Try it online!

Wouldn't f*b-f-b be 2 bytes shorter?


text:
Am I being run backwards?
Your task is to write a program, function, or snippet that will output one value if run forward, and another if run backward. The program must run without errors.
The output can be any two distinct values, of the same data type. For example, 1 and 3, true and false, or 't' and 'f'. In languages without a concept of data types, such as brainf*** or text, any distinct values are allowed.
This is a code golf challenge, shortest answer per language wins. Note that snippets are allowed (so something like 1-2 is valid, but don't expect any upvotes).

Related but IMO not a duplicate: https://codegolf.stackexchange.com/questions/16043/mirror-quine-or-my-head-hurts

https://codegolf.stackexchange.com/questions/192979/i-reverse-the-source-code-you-negate-the-output

Is it just me, or does this seem like it would be an interesting candidate for [tag:code-bowling]?

@Xcali There'd have to be something a like a pristine program rule

Does backwards mean character by character or line by line?

@CaptainMan Character by character

Using a Bytecode, would your reverse the order of Bytes (i.e. the 2 Bytes AB CD become CD AB), or of the Nibbles (i.e. the 2 Bytes AB CD become DC BA)?

@Chronocidal The bytes

As much rep as someone wants if said person can think of a 1 byte answer.

Can the output be nondeterministic? (But they will always still be different)

@pxeger No, sorry

Python 3, no comments or string literals, 106 bytes
x=quit
y=x.__class__
y.__add__=print
y.__pos__=x
x+x++x+x
x=__sop__.y
tnirp=__dda__.y
__ssalc__.x=y
tixe=x

I've never liked how comments and string literals let you "turn off" most of your language's syntax in challenges like this, so I wanted to see how far I could golf things without using either comments or string literals. This is what I came up with.
Since I don't have any way to disable the syntactical significance of parentheses, I cannot use the function call operator. Any attempt to do so would result in the reversed code having a closing parenthesis before the first opening parenthesis, which is invalid outside a comment or string literal. I also can't use def or container literals (aside from unparenthesized tuples), and my access to language features is in general extremely restricted.
One thing I can do is take advantage of Python's operator overloading to call functions implicitly. My ability to define any classes or functions is extremely limited, but fortunately, there are enough tools lying around in the built-in namespace for me to use. Most built-ins don't let me perform the attribute assignment I need to redefine their operator overloads, but (unless Python is run with one of the flags that disables site importing) the auto-imported site module adds quit and exit objects to the built-ins. These objects are instances of non-C classes, so I can reassign their operator overloads.
Setting __add__ to print lets me use addition to print things, and setting __pos__ to quit or exit lets me use the unary + operator to abort the program before the rest of the code runs. Without setting __pos__, I would need a bunch of additional code to make sure the "backwards" part of the code can find all the variables and attributes it needs to not fail. With __pos__, I only need to make sure the "backwards" code is still syntactically valid.
Forward, the code prints
Use quit() or Ctrl-D (i.e. EOF) to exit

Backward, the code prints
Use exit() or Ctrl-D (i.e. EOF) to exit

(The messages are slightly different on Windows. For platform-independent output at the expense of 3 extra bytes, you can replace the middle line with x+1++x++2+x, printing 1 when run forwards and 2 when run backwards.)

I also tried to figure out a way to do this by defining my own class instead of messing with quit.__class__. I got as far as the following:
if.1j:adbmal=1j
class ton:adbmal
a=lambda:j1.fi
j1=a
a.__dict__=a.__globals__

class ton:adbmal is one of the very few combinations of class name and class body such that the class statement is syntactically valid backward. tressa, led, labolg, tropmi, and esiar would also have been valid class names (with a different class body, such as not fi), but ton is the only one where the reversed name can be part of an expression, giving the most flexibility.
if.1j:adbmal=1j assigns a value to adbmal to make the class body succeed, while still being syntactically valid backward.
The stuff with a and j1 lets me use j1.ton to refer to my ton class, which is still a valid expression backward.
At this point, I got stuck. I couldn't figure out how to get my class out of j1.ton and into a more useful variable. I can't assign attributes on j1.ton and still have valid syntax backward, so I can't set operator overloads. I also wanted to set builtins.__build_class__ to my class so I could abuse the class statement to construct instances without the function call operator, but trying to put j1.ton on the right side of an assignment produces invalid syntax backward.
If I had been able to name my class something like fi or tpecxe, I could have used tricks like b:j1.fi to get the class into an annotation and then a.__dict__=__annotations__ to get it into a.b, but I couldn't find any way to get the class statement and the annotation tricks to hook up. Anything that was compatible with the class statement was incompatible with the annotation tricks.
(You might wonder why I didn't abuse builtins.__build_class__ to call an existing function directly, like print. I couldn't figure out a way to do that and have the output be deterministic, and I wanted deterministic output.)

+1, this is awesome.

JavaScript, 19 bytes
Returns true because of the assignment at the end, since JS treats that as defining a global variable. The first part is an arrow function, which is ignored. When run backwards, eurt is set to NaN (not a number), and since NaN is not greater than true (or equal), it returns false.
eurt=>true;NaN=true

Try it online!
eurt=NaN;eurt>=true

Try it online!
JavaScript, 3 bytes
A snippet which outputs 1, or -1 in reverse. Very simple.
2-1

Try it online!
1-2

Try it online!
JavaScript, 7 bytes
Abuses the not equal to operator and the not operator, will output false, or true in reverse. JavaScript uses NaN as not-a-number.
5==!NaN

Try it online!
NaN!==5

Try it online!
JavaScript, 18 bytes
Another boring solution, with comments instead of subtraction. Returns 1, or 2 in reverse. I included the print statements in these.
print(1)//)2(tnirp

Try it online!
print(2)//)1(tnirp

Try it online!
JavaScript, 7 bytes
Similar to the previous answer, but with assignment instead of equal-to. Uses the atob variable, which is a builtin in browser Javascript (decodes base64). Since TIO doesn't include browser builtins, I defined it just to keep it from erroring. Works as expected in console. Return true, or false in reverse.
2!=atob

Try it online!
bota=!2

Try it online!

Why do you have to use NaN in the second snippet? That can be absolutely anything but 5, as far as I see.

@someone IDK, didn't think about it I guess. I kinda like the NaN being symmetrical trick, so I'll keep it

I was thinking of 0||1

@Bergi That would work too, there're a huge number of 3-5 character solutions possible

@Bergi I just realized, that would be 1 every time...

@RedwolfPrograms Ouch. Looks like I was not thinking. || can still be used, but as you say there's a lot of boring 3-5 character solutions.

Here's a function answer: _=>1|0<=_ and _=>0|1<=_

J, 3 bytes
1"_

Try it online!
one or infinity...

1"_ is the constant 1, turned into a verb of rank " infinity _.  Hence always returns 1.
_"1 is the constant infinity _, turned into a verb of rank 1.  Hence always returns infinity.

How does the ranking work? I've never seen anything like that in a programming language.

@RedwolfPrograms It's rank in the dimensional sense of linear algebra, rather than the colloquial sense of "a ranking."  The basic idea is simple enough, but understanding it thoroughly is a serious undertaking.

Jelly, 2 bytes
+1

Try it online!
Prints 1.
Jelly, 2 bytes
1+

Try it online!
Prints 2.
The reason for this is that Jelly's dyad-nilad structure chains differently on either side. +1 becomes a monad meaning "plus one", which is applied to the Left Argument, which defaults to zero. 1+ does not become a monadic chain here (if I remember correctly - correct me if my Jelly theory is off; I'm a bit rusty on the structural component), but rather is seen as 1 set as the Left Argument, and then + is applied as a dyad to (left, left) in the default case of no Right Argument, giving 1 + 1.
Great challenge; I almost feel like this is a cheese. I don't know if I should be happy with this solution or feel bad for having such a short and trivial solution >_<.
This uses Jelly's structure to be fancy. A more boring answer would just be 01 (prints 1) and 10 (prints 10), or any other two-digit number and its reverse (that isn't a palindrome).

Cool solution! The higher level languages might be interesting to see, as well. +1

bash, 12 bytes (no comments or string literals)
echo 0$ ohce

Prints "0$ ohce"
echo $0 ohce

Prints "bash ohce"
bash, 11 bytes (no comments or string literals)
echo ftnirp

Prints "ftnirp"
printf ohce

Prints "ohce"

brainf*** 2 bytes
+.

Try it online!
Outputs 1 forwards, 0 backwards. Really randomdude999's answer

Doesn't simply +. also work? It would output a 1 if run forwards and 0 if run backwards.

@randomdude999 Whoops, yeah it does. Man I'm bad at this so far

Wolfram Language (Mathematica), 10 bytes
Print@ohcE

Try it online!
Prints ohcE.
Echo@tnirP

Try it online!
Prints >> tnirP.

R, 2 bytes
.1

Prints 0.1.
1.

Prints 1.
Both numeric (double).
tio
Less trivial? and for an explicit true/false
2>1
# TRUE

1>2
# FALSE

tio

Shouldn't 1.<1 be 1.>1?

@Adám: Yes. Got my eyes crossed.

@AkselA That seems to happen a lot in this challenge...(-:

@RedwolfPrograms Is that a reversed sad smiley face? ;-)

@RobinRyder No, just a sideways one. I always forget which side the eyes are supposed to be on (;;;)

POSIX sh (Dash, Bash, Zsh, ...), 3 bytes
: !

Try it online!
The builtin : discards its arguments and exits 0 (true). Reversed, ! negates the exit code of : and exits 1 (false).

very cool. i was going to write a cross platform answer echo sey <=> yes ohce but this is way golfier!

7, 2 characters, 1 byte in 7's encoding
31

Try it online! (forwards)
Try it online! (reversed)
This should be the first valid 1-byte solution (because the existing 1-byte solution in BCT requires a particular value on its input to work, and isn't counting it in the byte count – that could only be assumed in a full program, and BCT full programs can't do I/O and must wipe all their working memory to be able to halt, thus have no way to halt with a value). 7's encoding packs multiple characters into a single byte: here are xxd hexdumps for the forward and reverse programs:
00000000: 67                                       g

00000000: 2f                                       /

This conceptually outputs a string: 31 for the forwards program, and an empty string for the backwards program. The output encoding is set to be the same as the input encoding; so if you encode the program in 7's encoding, you'll get a single byte of output which encodes the string 31 (and if you use ASCII instead, you'll get two bytes that encode the string 31 in ASCII).
Explanation
On the first pass through the program, the 3 appends a "print and pop" command to the stack, and the 1 appends a "push empty stack element" command to the stack. So, we end up forming a program on top of the stack. At the end of the first pass through the program, 7 will run the resulting program, but without popping it from the stack.
With the forward version of the program, the "print and pop" command will attempt to print the program consisting of a "print" command and a "pop" command. That isn't a valid literal, so the 7 interpreter will construct code that's capable of constructing that stack element and print that instead; in this case, the code it finds for for "push a stack element that generates a 'print and pop' command then a 'push empty stack element command'" is 731 (i.e. basically the program we wrote, although our program appends to an implicit empty stack element, whereas the reconstructed program makes a new one). The print routine interprets the 7 as a command to set the output encoding to the same encoding that was used for the source code, and then the 31 is interpreted as a literal and gets printed. The command in question pops two things in total (the thing it's printing and the element below), so the stack now contains no data and thus there are no more passes through the program; it just exits (even though we push an empty stack element after this point, those don't affect the end-of-program behaviour).
With the reverse program, we're pushing the empty stack element before the print attempt, rather than the other way round, so it's now an empty string that gets printed, and the remnants of the program (which are below it) get popped without printing them. Everything is now the same as in the forward program, so the reverse program also exits naturally and without error.

Keg, 2 bytes
10

Try it online!
Keg, 2 bytes
01

Try it online!
When run forwards, it prints 10. When run backwards, it prints 01.
I might try to create a non-trivial answer soon, as this seems like a really great challenge!

Also works in pretty much every language REPL.

Actually, 2 bytes
Decrement empty value & push 1.
D1

Reversed program decrements 1, outputting 0.
1D

Try it online!
05AB1E, 2 bytes
The exact same answer ported to a different language.
<1

Try it online!

Perl 5, 11 bytes
say$-,$$yas

Try it online!
Outputs 0 when run forward.  Outputs the current process number followed by 0 when run backwards.

Poetic, 15 13 bytes
tis,A NAMETAG

Try it online!
Prints ASCII character 1 (SOH).
GATEMAN A,sit

Try it online!
Prints ASCII character 0 (NUL).
The previous answer ends with an "Unexpected EOF" error forwards because the END command (any ten-letter word) is omitted, and a "Mismatched IF/EIF" error backwards because EOF is encountered before an IF/EIF loop can end. The following answer terminates properly.
Poetic, 51 bytes
the difference between I and certain ridiculous men

Try it online!
Prints a newline.
nem suolucidir niatrec dna I neewteb ecnereffid eht

Try it online!
Prints a newline and a "vertical tab" character.
(I really wanted to be able to make the programs make sense both backwards and forwards, but I'm not sure that's possible in English, and I don't know any other languages to try that out with.)

The only thing I can think of that makes sense forward and backward (actually, neither) is tacocat racecar wow.

TIS A NAMETAG -> a person getting excited about a nametag. GATEMAN A SIT A command unto Gateman A; he must sit.

@ReinstateMonica Good one!

Haskell, 52 bytes
a=0--
--b tnirp=b#a
niam=main
1#a=niam
main=print a

==> prints "1"
a tnirp=niam
main=a#1
niam=main
a#b=print b--
--0=a

==> prints "0"
Explanation:
a=0--
-- FWD: define constant "a" to be 0 / BWD: No-op                                 --

--b tnirp=b#a
-- FWD: No-op / BWD: define a function "#" in two arguments and prints the       --
-- second                                                                        --

niam=main
-- FWD & BWD: define constant "niam" to be the same as "main"                    --

1#a=niam
-- FWD: define a function "#" in two arguments that produces "main" if the first --
-- argument is 1 / BWD: define constant "main" to be the result of the function  --
-- "#" applied to the arguments "a" and 1                                        --

main=print a
-- FWD: define constant "main" to be an IO action that prints the value of "a" / --
-- BWD: define a function "a" in one argument that always produces the value     --
-- of "niam"                                                                     --

Of course, there is also the shorter item:
Haskell, 29 bytes
main=print 1--
--0 tnirp=niam

which is much less interesting.

MathGolf, 2 bytes
This one does not have any nilads or dyads inside the program. Just monads.
±(

Try it online!
Explanation
±  Find absolute value of the implicit 0
 ( Decrement 0, resulting -1.

Reversed:
(  Decrement 0, resulting -1.
 ± Find absolute value of -1, which results in 1.

Interesting, using absolute value. +1

HolyC, 12 bytes
Like the C version, except using the implicit print in HolyC
"0"; // ;"1"

Prints 0
"1"; // ;"0"

Prints 1
Spaces required by the compiler :)

MarioLANG, 3 bytes
:
+

Try it online!
Prints 0
+
:

Try it online!
Prints 1

MarioLANG, 10 bytes
 ==
:+
==

Try it online!
Prints 0
 ==
+:
==

Try it online!
Prints 1

Dyalog APL
Boring solution using comments
0⍝1   => 0
1⍝0   => 1

Even more boring numeric solution:
10    => 10
01    => 1

Basic arithmetics:
2-1    => 1
1-2    => ¯1

another: 0⊢1 and 1⊢0

@Razetime yeah, it can be done using various operators - power, division, etc... but i found it pointless to include it here

embrace the boring

Whispers v3, 31 bytes
1 tuptuO >>
> 1
>> Output 1
0 >

Try it online!, !enilnO tI yrT
Hooray for strict parsing rules!
The first and last lines are ignored, because they don't fit the right syntax. They come into action when reversed.

Fig 0.1.0, \$2\log_{256}(96)\approx\$ 1.646 bytes
,"

See the README to see how to run this
Argh. Beaten by Halfwit by more than half a byte. In the forward position, it prints a single newline. Backwards, ",, it prints a comma followed by a newline.

Make, 14 15 bytes
x:#
	#$@$#
#:y

Try it online!
Updated to add a trailing tab on the second line...
Here's another one that's not as short, but seems interesting enough to post...
Forwards it prints x and backwards it prints y.  It works by referencing the $@ symbol, which is defined as the target being made.  The "command" run is just a comment to the shell, so it's a no-op.  But by default Make echos the commands it runs.
Also, the $# reference doesn't cause an error, and evaluates to an empty string, which allows #$@$# to work both directions without having to add more characters.

Nice answer, but I think it should be 15 bytes, because the second line should end with tab. Also I think it would be nice to tell that $# is variable with empty value as it confused me a bit at first, because I am not that much familiar with Make.

Good point...  there is missing trailing tab on the second line.  I'll update the answer.  And I'll add a note about "$#" evaluating to an empty string.

Vyxal, 4 bits1, 0.5 bytes
2

Try it Online! (link is to bitstring) The bitstring form of this is 0101, which translates to 2.
Reversed - Try it Online! (outputs 0)
If we stretch the rules a bit, we can get two bits: Try it Online! !enilnO ti yrT, which respectively output an empty string and 0 - 0 and 1 in unary.

Pyth, 2 bytes
\"

Try it online!
Returns the string ' " ' (one set of double quotes)
Pyth, 2 bytes
"\

Try it online!
Returns "\"
Oops, my earlier answer missed that they had to be the same data type. This answer returns two different strings, and relies on the fact that '\' makes a one character string of the input and that Pyth closes strings implicitly

Oh, smart, using \" to escape a quote

Python 3, 17 bytes
print(1)#)2(tnirp

Try it online!
I promise this is the last trivial/cheese one I post; I'm trying to think of a more interesting solution. If I remember I'll see where I can get with this.

At this point, Python devs should add tnirp as a function just to mess with y'all.

@DonThousand haha that would be funny :P

I keep reading tnirp as turnip

Japt, 2 bytes
1g

Returns 1. Reverse returns -1.
g is the sign function when it has no arguments, and returns the sign of the argument minus the caller if called with an argument. So g1 would be the sign of zero minus one because the default input is 0
Test it

Wren, 32 bytes
Basically just a port of the Python answer.
System.write(1)//)0(etirw.metsyS

Try it online!

I think you mean System.write(1)//)0(etirw.metsyS. Remember that orientation of brackets is preserved when the code is reversed

Thank you for noting that.

05AB1E, 2 bytes
Push 1 onto the stack & negates. (This results in -1)
1(

Negate empty value & push 1. Output 1 implicitly.
(1

Try it online!

3Í would also work. Try it online!

Deadfish~, 2 bytes
oi

Try it online!
Boy, if that fruit hanged any lower, it'd be underground I tell you.

TI-BASIC Non-trivial, 4 5 bytes
Disp "Disp :

This outputs 'Disp :'
Since TI-BASIC is token based, reversing it gives
:Disp "Disp

which outputs 'Disp'
Let me explain.  'Disp ' is one token which prints the given string to the home screen.  First we are giving it a string of 'Disp :', so simple there.  When reversed, since each 'Disp ' is one byte, we get the reversed code above.  This reversed code starts with a ':', which ends the line, and means nothing here.  The remaining code is 'Disp "Disp ', which runs and outputs 'Disp ' to the home screen.
TI-BASIC Trivial, 2 bytes
If a program ends with a values, then it outputs it.  This lets us do
12

which outputs 12, and reversed is
21

which outputs 21.

I was waiting for a TI-Basic answer, +1

Java, 14 bytes
()->1;//;0>-)(

Simple function that uses comments to exclude the other part. Outputs 1, and reversed outputs 0.

Bitwise Cyclic Tag, 2 bits (0.25 bytes)
With an input of 1 this should either set the data string to a null string or a string of length 2 in its next iteration.
01

Explanation:
0  Delete the leftmost data bit.
   Halt. No more instructions executed.
 1 Not executed

Reversed:
1  If the left-most data-bit is 1,
 0 Append a 0 to the data-string.

Ruby, 6 bytes
p:stup

Output
:stup

Reversed output
p

Ceylon (Snippet), 20
The same trivial thing as in many other languages:
print(1);//;)2(tnirp

Outputs 1.
print(2);//;)1(tnirp

Outputs 2.
Given that parentheses need to be in the right order and you need print for output, I don't think this can be improved.
A full program or function needs even more braces/parentheses mirrored, so no chance of getting it better.
Ceylon (anonymous function), 17
If we don't need to output anything, but just return it from an anonymous function, then this is enough:
()=>//
1.2
//>=)(

A function which returns 1.2 (a floating point value).
()=>//
2.1
//>=)(

A function which returns 2.1 (a floating point value).
Ceylon (expression with return value), 3
If we accept just an expression (which then can be printed), then we don't even need any comments:
2.1

Gives 2.1 (a floating point value).
1.2

Gives 1.2 (a floating point value).
Try all of them online

Turing Machine Code, no comments or string literals, 19 bytes
0 * 0 * 0
0 * 1 * 0

Reversed:
0 * 1 * 0
0 * 0 * 0

Try it online!
The code runs without errors, but does loop forever. Prints '0' forward, prints '1' reversed.

Befunge-98 (PyFunge), 2 bytes
@,

Try it online!
Prints nothing by default, prints a null byte if reversed

AppleSoft Basic, 3 bytes
0?1 outputs 1 1?0 outputs 0
0?"?1 <=> 1?"?0
verified here

Halfwit, 1 byte
*k

Try It Online!
The second valid one-byte solution :P
* is multiplication, multiplying two 0s. k is a digraph character, and on its own a NOP, but k* is exponentiation.
Alternatively, anything that's a single char before > works as > delimits a compressed integer, so >x will push some number, and x> will apply x then push 0.

Ly, 2 bytes
-`

Try it online!
Forwards outputs 1 and backwards shows -1.
Why?  Forwards:
 -   : subtract top two stack entries, when empty produces "0"
  `  : increment top of stack, produces "1"

Backwards:
`   : increment top of stack, when empty produces "0"
 -  : subtract top two stack entries, produces "-1"

ok... will do.  I thought multiple entries from the same person were discouraged.  My bad...

HBL, 1 byte
+2

Run forwards, outputs 3:
+   Increment
 2  Two

Run backwards, outputs 8:
2   Double
 +  Four

In fact, any program consisting of two characters from the set 2<+-/% will work. Here are all the possible combinations together with their outputs. We could also add 0 to the set if it weren't for the "same data type" restriction.

Vyxal, 3 bytes
2-1

Try it Online!
Running it forward gives 1, running it backwards gives 2.
This because vyxal's syntax is weird:
ab- (vyxal) = a-b (py)

This can be 10 for 2 bytes

Brachylog, 2 bytes
+1

Try it online!
There are probably loads of different 2 byte answers.
Explanation
+1 states that 1 is the result of the sum of an unknown list of integers, which is obviously true. (there are infinitely such lists).
1+ states that we can sum the list 1 into some result, which is obviously false. since 1 isn’t a list.

Japt, 2 bytes
c1

Return x rounded up to nearest multiple of N => output 0
Test it
1c

x default to 1 => output 1
Test it

Whitespace, 20 bytes
S S S N
T   N
S T N
N
N
T   S N
T   N
T   T   S S

Letters S (space), T (tab), and N (new-line) added as highlighting only.
Outputs 0/-1.
Try it online or try it online reversed (with raw spaces, tabs and new-lines only).
Explanation:
Very minor modification of my answer here (outputting 0 is 1 byte shorter than 1), so I'm just gonna copy-paste the explanation:
Utilizing the Exit Program builtin being a short palindrome NNN (also note that without an exit, every Whitespace program would result in an error, making it invalid for this challenge).
The regular program will:
SSSN   # Push 0 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:
SSTTN  # Push -1 to the stack
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. Only the first three and trailing N are mandatory, so SSSN/SSTN will both push 0.

SimpleTemplate, 10 bytes
This was actually hard to optimize, without going into the trivial answer.
{@echo"1"}

Outputs the string "1".
When reversing, you get the following:
}"1"ohce@{

Outputs the string }"1"ohce@{.
As stated in the question: "The output can be any two distinct values, of the same data type.", and both solutions output a distinct string.
You can test this on http://sandbox.onlinephpfunctions.com/code/ec4bf4b3efa93c63c6c5c9f1458330da0178b6cd
(On line 960, change between the $code and $reversed variables)

SimpleTemplate, 2 bytes
This one is extremelly trivial:
<any 2 different bytes>

Reversing them will output whatever is reversed.

PHP, 2 bytes
12

Try it online!
Prints 12 ...
21

Try it online!
Prints 21 ...

Looking for non-trivial solution?
PHP, 11 bytes
<?=1;#;2=?<

Try it online!
Prints 1 ...
<?=2;#;1=?<

Try it online!
Prints 2 ...

Don't like comment abuse?
PHP, 13 bytes
;echo+1-ohce;

Try it online!
Prints 1 ...
;echo-1+ohce;

Try it online!
Prints -1 ...
Note: this one is an exact copy of my answer here: https://codegolf.stackexchange.com/a/193169

The definition of "reversed" is ambiguous in the question, and could be byte-reversed, as you have, line-reversed... or bit-reversed, which means you can get it down to one byte (eg J is binary 0100 1010, which reversed is 01010 0010, or R). I don't think you can get shorter than that, though, as I don't think sub-byte sizes are valid input to the parser.

@DewiMorgan Reversed in terms of characters

@RedwolfPrograms I get that it's what you meant, but since it was left ambiguous, it makes that aspect of the request fair game for golfing, too. All three could give interesting results, though I think the bitwise reverse would be the most trivial in many languages, and impossible in others, and the winner would likely be any language which allowed sub-byte inputs; while the command-wise reversal would for once give no advantage to golfing languages, if the number of operators is being counted, rather than number of characters.

C (gcc), 21 bytes
puts("");//;)"0"(stup

Try it online!
!enilno ti yrT

Runic Enchantments, 3 bytes
0@1

Try it online!
Prints 0 forwards and 1 backwards.
If no output is allowed, then @1 saves a byte.

Never realized you made this language...seems pretty cool!

@RedwolfPrograms Yep! Its almost the only language Igolf in because of that.

Rebol, 2 bytes
#1

Prints #1
1#

Prints ##

Ahead, 4 bytes
O@j1

Prints 0 forward and 1 backward.
Forward
O     pop stack and print number
 @    end
  j1  not reached

Backward
1     push 1
 j    jump next cell
   O  pop stack and print number
  @   end

Control flow is more interesting backward because I tried to reduce the amount of redundant characters.
Try it online!

GolfScript, 2 bytes
Simply prints 1 because the duplicate instruction duplicates the null string.
.1

Reversed
Outputs 11 because that is the value 1 duplicated.
1.

Try it online!
GolfScript, 4 bytes
Outputs 0 because 1 - 1 is 0.
1 1-

Reversed
Outputs -11 due to concatenation.
-1 1

Try it online!
GolfScript, 2 bytes (Am I allowed to use the null string?)
Outputs the null string, because the null string from the input minus 1 is still the null string.
1-

Reversed:
Pushes -1 onto the stack.
-1

Try it online!

Null string and -1 are same data type in GolfScript?

@, 2 bytes
Outputs \n1, where \n represents a literal newline.
\1

Reversed
Returns 1, the expression after 1 is ignored.
1\

Try it online!

33, 4 bytes
o1ao

Try it online!
Outputs 01 if run forwards or 00 if run backward

Actually, 2 bytes
12

Try it online!
Prints 2\n1\n forwards, and 1\n2\n backwards.

Dis, 2 bytes
{!

Try on dis.web! Outputs one NULL character.
!bew.sid no yrT Outputs nothing.

><> (Fish), 3 bytes
0n1

Try it forwards
Try it backwards 1n0

SmileBASIC, 4 bytes
?12?

prints 12\n\n forwards and 21\n\n backwards

Triangular, 3 bytes
i.%

Try it online!
Prints 1.
%.i prints 0.
If it weren't invalid to do an integer and a character, %# would've been a nice 2-byter.


text:
Making Fibonacci Cry
Introduction
The Fibonacci sequence is a mathematical sequence in which each term is the sum of the \$2\$ terms before it; the first two terms are \$0\$ and \$1\$. The first few terms are \$0, 1, 1, 2, 3, 5, 8, 13\$. However, it is possible to make variations of this sequence, where each term is the sum of the, say \$3\$ terms before it, of the sum of the previous \$4\$. That is what you must do in this challenge.
Challenge
Given two numbers, an index in the sequence \$n\$ and a number of terms \$x\$ to sum, generate the first \$n\$th terms in the messed up Fibonacci sequence. You can assume that the first \$x\$ terms are just the first \$x\$ whole numbers (\$0\$ and up).

Your program must take two numbers as input. You can assume that \$n\$, the first number, will always be greater than the second, \$x\$, and that \$x\$ will always be greater than or equal to 2. They will always be valid integers. If it is easier or if it saves bytes to read from stdin, command line arguments, or a variable, you may do one of those options.
Your program must output the first \$n\$ terms in the Fibonacci sequence in which each term is the sum of the last \$x\$ numbers. Again, if it saves bytes, your program may output through stdout, a variable, exit code, or return value.

Example I/O

n: 8, x: 2
Output: {0, 1, 1, 2, 3, 5, 8, 13}
n: 7, x: 4
Output: {0, 1, 2, 3, 6, 12, 32}
n: 4, x: 3
Output: {0, 1, 2, 3}

Rules
This is code-golf, so shortest answer in bytes wins!
`

You can assume that the first x terms are just the first x whole numbers (0 and up). But in the last test case, the first three terms are not the first three whole numbers

This looks really similar to Print the N-bonacci sequence, with just a different base case. I think dupe?