text:
Numbers Manipulation challenge
Use any programming language to generate two random digits between 1 and 9 (including both). Then your program should display:

in the first line: the first random digit,
in the second line: the second random digit,
in the third line: a number whose tens and units digits are the first and second random digits respectively,
in the fourth line: the number from the third line raised to the power of 2.

For example, if digits "9" and "2" were generated, your program should display exactly:
9
2
92
8464

Can we output an array?

Can we sample without replacement, ie exclude 1,1 2,2 3,3... from the pairs?

(i.e., what's the distribution of the random numbers?)

You should probably specify that the digits are pairwise independent and uniformly random. Otherwise, one can go with a degenerate distribution and write "cat (10 Bytes): 1[newline]1[newline]11[newline]121"

@YonatanN The standard assumption on PPCGcfor the term random is that all possibilities have a non-zero chance of occuring.

Why did you accept my answer just yet, when there are two 9-byte solutions that are shorter? For code-golf challenges you should accept the shortest one (and sometimes the earliest edit/post if there are more than one shortest), or don't accept an answer at all.

05AB1E, 14 11 bytes
2F9LΩ=}J=n,

-3 bytes thanks to @Emigna.
Try it online.
Explanation:
2F    }        # Loop 2 times:
  9LΩ          #  Create a list in the range [1,9], and pick a random element from it
     =         #  Output it (without popping it from the stack)
       J       # Join them together
        =      # Output it (without popping it from the stack)
         n     # Take it to the power of 2
          ,    # And output it as well

11 bytes alternative:
9LãΩ©`®JDn»

Try it online.
Explanation:
9L             # List in the range [1,9]
  ã            # Cartesian product with itself: [[1,1],[1,2],[1,3],...,[9,7],[9,8],[9,9]]
   Ω           # Take a random element from it
    ©          # Store it in the register (without popping)
     `         # Pop and push both items as separated items onto the stack
      ®        # Retrieve the list of digits from the register again
       J       # Join them together to a single 2-digit number
        Dn     # Duplicate it, and take the power of 2 of the copy
          »    # Merge all values on the stack by newlines (and output implicitly)

Shorter in a looP: 2F9LΩ=}J=n,

@Emigna I was about to look for shorter alternatives, but smart use of the =!

R, 48 47 bytes
cat(x<-sample(9,2,T),y<-x%*%c(10,1),y^2,fill=1)

Try it online!
Thanks to J.Doe for golfing down a byte.

Tweak to cat args. 47 bytes

@J.Doe thanks! Probably there are other submissions where fill would be handy...

Japt, 14 13 bytes
-1 Byte from @Oliver
2ÆÒ9ö
pU¬Uì ²

2ÆÒ9ö
pU¬Uì ²     Full program
-----------------------------------------
2Æ            Range [0,2) and map
   9ö         Random number in range [0, 9)
  Ò           increased by 1
              This result is assigned to U

p            Push into U
 U¬          Elements in U joined
   Uì ²      and elements joined squared
             Implicit output each element
             separated with new line -R

Try it online!

You can use 2ÆÒ9ö to save a byte on the first line.

Vim, 43 bytes
:%!$RANDOM

:s/0//g
2f:y2hVpo<C-r>=<C-r>0*<C-r>0
<Esc>kYPa

Try it online!
Not the right tool for the job. This produces most likely the desired output
Step by step:

:%!$RANDOM Enter Enter
Produces a string like /bin/bash: 25266: command not found
:s/0//g
removes all zeroes
2f:y2hVp
moves the cursor to the colon after the number, copy the last two digits and replace the entire string with those
o Ctrl+R = Ctrl+R 0* Ctrl+R 0 Enter
add a new line and evaluate an expression. In this case, I'll multiply the number in register 0 (the one that was just copied) with itself.
Esc kYPa Enter
Copy the upper line and paste it above. The cursor ends up in the first line, on the first character. Now we just have to append a line break to it

Limitations: If the result of $RANDOM is a number with less than two non-zero digits, this will not produce the desired output

C (gcc), 68 67 bytes
-1 byte thanks to cleblanc
f(r){r=rand()%81*10/9+11;printf("%d\n%d\n%d\n%d",r/10,r%10,r,r*r);}

Try it online!

save one byte using r;f() --> f(r)

K (oK), 28 bytes
t:2?10;t,:10/t;$t,:t[2]*t[2]

Explanation
t:2?10                       //define t as two random numbers from 1-10
       t,:10/t               //join the base 10 joining of the elements of t to t
                 t,:t[2]*t[2]//join the square of the index 2 element to t
               $            //String each element of the result (to output on newlines)

Try it online!
Cleaner Output, 32 bytes
t:2?10;t,:10/t;`0:$t,:t[2]*t[2];

               `0:               //Cleanly prints the strings

Try it online!

If we're allow to return an array then a,b,b*b:10/a:1+2?9 for 18 chars Try it online!

+1 Much neater, its only the extra $ character to match the output of my first answer, with -9 bytes. I hadn't tried to fit it into one expression

2?10 could generate a 0. the challenge requires 1-9.

``0:$a,*\2#10/a:1+2?9;` (works in ngn/k too)

That works great in ok, the issue with it in ngn/k is that it seems to generate the same output on every run

@Thaufeki the random seed in ngn/k predetermined, like in the original k

oh ok cool, thanks for the response!

Python 3, 83 76 bytes
-5 bytes thanks to nwellnhof.
from random import*
k=randint(9,89)*10//9+1
[*map(print,[k//10,k%10,k,k*k])]

Try it online!

82 bytes.

Perl 6, 39 bytes
{.comb,$_,$_²}([~] roll 1..9: 2)>>.put

Try it online!

JavaScript (ES6), 67 bytes
f=_=>(n=Math.random()*90+10|0)%10?(n/10|0)+`
${n%10}
${n}
`+n*n:f()

Try it online!

PowerShell, 48 45 bytes
($a,$b=1..9*2|Random -c 2)
($x="$a$b")
+$x*$x

Try it online!
Concatenates two ranges 1..9 together, pipes that to Get-Random with a -count of 2 to pull out two elements, stores them into $a and $b, and encapsulates that in parens to place a copy of them on the pipeline.
Next we string concatenate $a$b and store it into $x, again placing in parens to put a copy on the pipeline. Finally we take $x squared and leave it on the pipeline.
All the results are gathered from the pipeline and an implicit Write-Output gives us newlines between elements for free.
Saved 3 bytes thanks to mazzy.

Smart get-random

I think 1..9|Random -c 2 completely satisfies the condition two random digits between 1 and 9 (including both)

...if not, then 1..9*2 is shorter

@mazzy Other answers seem to pick the two digits with replacement, so I did so as well. Thanks for the 1..9*2 golf!

Jelly, 10 9 bytes
9ṗ2XṄ€ḌṄ²

Try it online!
How it works
9ṗ2XṄ€ḌṄ²  Main link. No arguments.

9          Set the return value to 9.
 ṗ2        Promote 9 to [1, ..., 9] and take the second Cartesian power, yielding
           [[1, 1], [1, 2], ..., [9, 8], [9, 9]].
   X       Pseudo-randomly select one of the pairs.
    Ṅ€     Print each integer in the pair, followed by a newline.
      Ḍ    Undecimal; convert the integer pair from base 10 to an integer.
       Ṅ   Print the integer, followed by a newline.
        ²  Take the square.
           (implicit) Print the last return value.

Pyth, 14 bytes
^
i,
hO9
hO9T2

Note that the newlines are significant. Try it online here.
Explanation, with newlines replaced with ¶ character:
^¶i,¶hO9¶hO9T2   Implicit: T=10

      O9         Choose a random number in [0-9)
     h           Increment
    ¶            Output with newline - value printed is yielded as expression result
        ¶hO9     Do the above again
   ,             Wrap the two previous results in a two-element array
  i         T    Convert to decimal from base 10
 ¶               Output with newline
^            2   Square the previous result, implicit print

@Downvoter - any particular reason why?

Ruby, 41 bytes
puts [(a=11+10*rand(81)/9)/10,a%10,a,a*a]

Try it online!

T-SQL, 142 105 115 114 96 78 bytes
DECLARE @ int=RAND()*9+1,@a int=RAND()*9+1SELECT @,@a,10*@+@a,POWER(10*@+@a,2)

-37 bytes: Realized I could just use two different random numbers and use the first digits from each!
+10 bytes: Edited to meet requirements of range from 1-9, instead of 0-9
-1 byte: Changed RIGHT() to LEFT() in @b
-18 bytes: Various changes suggested by BradC
-18 bytes: More changes suggested by BradC
Ungolfed:
-- Setting RAND() separately in these produces different numbers.
-- [RAND() * b + a] sets the range for a random number, from a to b inclusive.
-- Declaring as an int removes the numbers after the decimal.
DECLARE @ int = RAND() * 9 + 1,
        @a int = RAND() * 9 + 1

SELECT @,                       -- first random digit
       @a,                      -- second random digit
       10 * @ + @a,             -- multiply first digit by ten, and add second
       POWER(10 * @ + @a, 2)    -- third digit squared

The stuff in the first comment definitely works, I'll edit that in. Problem with making the variables ints is that I would need to cast each individually as chars in the SELECT where necessary. With that, since each variable would need to be converted twice (in @+@a and POWER(@+@a,2)), it'd add more characters than it would save.

Good calls, thanks. Don't know why I didn't think of multiplying the first number by ten...

No problem, I'll delete my comments since you've incorporated them.

Python 2, 84 75 bytes
from random import*
k=randint(9,89)*10/9+1
for x in k/10,k%10,k,k*k:print x

Try it online!

Saved

-1 bytes, thanks to Erik the Outgolfer
-8 bytes, thanks to nwellnhof

Moderate golf: 83 bytes.

Java 8, 99 98 90 81 80 bytes
v->{int i=81;i*=Math.random();return(i=i*10/9+11)/10+"\n"+i%10+"\n"+i+"\n"+i*i;}

-8 bytes after being inspired by @Arnauld's JavaScript answer.
-9 bytes thanks to @nwellnhof.
Try it online.
Explanation:
v->{                        // Method with empty unused parameter and no return-type
  int i=81;i*=Math.random();//  Create a random integer `i` in the range [0,81)
  return(i=i*10/9+11)       //  Set `i` to 10 times `i`, integer-divided by 9, and 11 added
        /10+"\n"            //  Return the first digit of `i`, a newline,
        +i%10+"\n"          //         the last digit of `i`, a newline,
        +i+"\n"             //         `i` itself, a newline,
        +i*i;}              //         and `i` multiplied by itself
                            //         All concatted to each other

Charcoal, 16 bytes
≔⭆²⊕‽⁹θ↓θθ⸿ＩＸＩθ²

Try it online! Link is to verbose version of code. Explanation:
≔⭆²⊕‽⁹θ

Generate two random characters in the range 1 to 9.
↓θ

Output them downwards i.e. on separate lines.
θ⸿

Output them horizontally on their own line.
ＩＸＩθ²

Cast to integer, square, cast back to string for implicit print.

C# (.NET Core), 130 129 109 98 bytes
var r=new Random();int a=r.Next(1,10),b=r.Next(1,10),c=a*10+b;Console.Write($"{a} {b} {c} {c*c}");

Try it online!
-1 byte: edited console output to use wildcards (thanks to Logern)
-20 bytes: changed r to var from Random, changed format of c; fixed r.Next() operators (thanks to LiefdeWen)
-11 bytes: changed format of c (thanks to user51497)
Ungolfed:
var r = new Random();                   // initializes random number generator
int a = r.Next(1, 10),                  // gets random number between 1 and 9 inclusive
    b = r.Next(1, 10),                  // gets random number between 1 and 9 inclusive
    c = a * 10 + b;                     // concatenates a and b into one two-digit number
Console.Write($"{a} {b} {c} {c*c}");    // writes a, b, c, and c^2 to the console

129 bytes-Try it online!

109 bytes Also your .Next needs to include 10 so it can random 9

@LiefdeWen Thanks. Didn't realize the max value of Random.Next() was exclusive. The min value is inclusive, though, so that needs to stay at 1 to fit the requirement of being between 1-9 inclusive.

-11 bytes c = a*10 + b;

This looks to be a snippet rather than a full function or program. Here is the guide to C# that should be able to help you turn your snippet into an acceptable answer.

@AdmBorkBork In reality, we're golfing against the language, and not against others, as C# cannot compete. There is a minimum number of required characters to create a C# program. See this comment.

@Meerkat The entire program is not required, but you do need it to be in a function. That actually saves bytes then, because you can return rather than Console.Write ing

94 bytes and a valid lambda function answer. (x is an unused input to save 1 byte, which is allowed as per PPCG standard rules)

If you use the Visual C# Interactive Compiler (csi), you don't need the boilerplate. You'll have to replace the spaces in the output with newlines though. The challenge is rather specific about that.

Also by using Console.Write in the program I believe you also need to include the byte count of using System;, in which case it'd be shorter to specify System.Console.Write

97 bytes with newlines

Btw, csi lets you use Write instead of System.Console.Write and you don't need the trailing semicolon. 92 bytes

TI-BASIC, 27 bytes
11+int(89rand
Disp iPart(.1Ans),10fPart(.1Ans),Ans,Ans²

(can generate a 0 in the 2nd random number)
Uses kamoroso94's Disp layout, but makes use of TI-BASIC integer compression.  Generating the 2 random integers as a single compressed integer and extracting them via iPart and fPart allows for shaving several bytes.  It's possible to generate the random integers seperately in the same number of bytes by creating them simultaneously in a list:
1+int(9rand(2

But the repeated calls to the list via Ans(1) and Ans(2) end up taking many more bytes than the integer compression technique.  It's also important to note that rand is generally advisable over randInt( for random integer generation as they either use equivalent bytes, or rand will be shorter when the lower bound is 0, and rand has the added flexibility of list generation.

This doesn't work; sometimes it generates 0 for the second digit.

Yeah I see what I missed now, I don't think it's possible to improve from the 31 bytes and avoid the zeros then without messing with the output formatting.  You can get 33 bytes by adding 2 randInt() and extracting them as shown here or 33 bytes again via the random list.

Batch, 95 bytes
@set/at=%random%%%9+1,u=%random%%%9+1,n=t*10+u,p=n*n
@for %%a in (%t% %u% %n% %p%)do @echo %%a

%random% isn't a real variable, it's interpolated at parse time, so you need the %s even inside set/a. (Also don't try using it in a loop!)

PHP, 64 bytes
<?$d=($c=(10*($a=rand(1,9))+$b=rand(1,9)))*$c;echo"$a
$b
$c
$d";

Try it online!

Retina, 43 bytes

100*
L$`
$.`
A`0
G?`..
\*\L`.
..
$.($&*$&*

Try it online! Explanation:

100*
L$`
$.`

Count from 0 to 99.
A`0

Delete multiples of 10.
G?`..

Pick a random 2-digit number.
*\L`.

Output the digits separately.
\

Output the number.
..
$.($&*$&*

Square and implicitly output the number.

MBASIC, 100 86 bytes
1 DEF FNR(X)=INT(RND*X)+1:A=FNR(9):B=FNR(9):PRINT A:PRINT B:C=A*10+B:PRINT C:PRINT C^2

Output
5
8
58
3364

TI-BASIC, 31 bytes
randInt(1,9→A
randInt(1,9→B
10A+B
Disp A,B,Ans,Ans²

sfk, 99 bytes
rand 1 9 +setvar a +rand 1 9 +setvar b +tell -var "#(a)
#(b)
#(a)#(b)" +calc -var #(a)#(b)*#(a)#(b)

Try it online!

perl -E, 45 bytes
$_=10+int rand 90;y/0/1/;say for/./g,$_,$_**2

This exploits the lack of a requirement that all random numbers should be picked with equal probability (it will pick numbers ending in 1 twice as often as ending in any other digit).

Visual C#, 102 Bytes; 101 bytes
+2 Upper bound of Random.Next() exclusive, 10 instead of 9
-3 Thanks to LiefdeWen (var instead of Random)
var r=new Random();int x=r.Next(1,10),y=r.Next(1,10),z=x*10+y;Console.Write($"{x}\n{y}\n{z}\n{z*z}");

normal form:
var r = new Random();
int x = r.Next(1, 10),
    y = r.Next(1, 10),
    z = x * 10 + y;
Console.Write($"{x}\n{y}\n{z}\n{z * z}");

Try it online!
Visual C#, 85 bytes 89 bytes 91 Bytes
+4 bytes: fixed problem with 0 as second digits, borrowing the *10/9+1 from other answers
+2 bytes: preventing numbers <11

Even shorter solution
var r=new Random();int x=r.Next(9,89)*10/9+1;Console.Write($"{x/10}\n{x%10}\n{x}\n{x*x}");

normal form:
var r = new Random();
int x = r.Next(9, 89)*10/9+1;
Console.Write($"{x/10}\n{x%10}\n{x}\n{x*x}");

Try it online!

98 bytes. You also had to include 10 in .Next to make 9 possible

Red, 69 bytes
prin reduce[x: random 9 n:"^/"y: random 9 n z: do rejoin[x y]n z * z]

Try it online!

MathGolf, 9 bytes
2æ8w)o§o²

Try it online!
Explanation
For the example, the first random integer is 4, the second is 7.
2æ         Start for-loop of length two, with the next 3 chars as the body
  8w       Random non-negative integer less than or equal to 8
    )      Increment by 1
     o     Output without popping (stack is unchanged)
           For loop ends, stack is now [4, 7], the first two lines have been printed
     §     Concatenate the two numbers on the stack (stack is [47])
      o    Output without popping (stack is unchanged)
       ²   Square number and output implicitly


text:
My array should equal this, but it doesn't!
Given an array of integers a which contains n integers, and a single  integer x; remove the fewest amount of elements from a to make the sum of a equal to x. If no combinations of a can form x, return a falsy value.
As pointed out in a comment this is the maximum set with a sum of x, excuse my lesser math brain. I forgot a lot of terms since college.

Examples (Truthy):
f([1,2,3,4,5,6,7,8,9,10], 10) = [1,2,3,4]
f([2,2,2,2,2,2,2,2,2], 10) = [2,2,2,2,2]
f([2,2,2,2,-2,-2,-2,-4,-2], -8) = [2,2,-2,-2,-2,-4,-2]
f([-2,-4,-2], -6) = [-4,-2] OR [-2,-4]
f([2,2,2,4,2,-2,-2,-2,-4,-2], 0) = [2,2,2,4,2,-2,-2,-2,-4,-2] (Unchanged)
f([], 0) = [] (Unchanged Zero-sum Case)

Examples (Falsy, any consistent non-array value):
Impossible to Make Case: f([-2,4,6,-8], 3) = falsy (E.G. -1)
Zero Sum Case: f([], non-zero number) = falsy (E.G. -1)

Note: any value like [-1] cannot be valid for falsy, as it is a potential truthy output.

Rules:

Input may be taken in array form, or as a list of arguments, the last or first being x.
Output may be any delimited list of integers. E.G. 1\n2\n3\n or [1,2,3].
Any value can be used as a falsy indicator, other than an array of integers.
Your code must maximize the size of the end array, order does not matter.

E.G. For f([3,2,3],5) both [2,3] and [3,2] are equally valid.
E.G. For f([1,1,2],2) you can only return [1,1] as [2] is shorter.

Both the sum of a and the value of x will be less than 2^32-1 and greater than -2^32-1.
This is code-golf, lowest byte-count wins.
If there are multiple subarrays of the same size that are valid, it is not acceptable to output all of them. You must choose a single one and output that one.

Let me know if this has been posted, I couldn't find it.
Posts I found like this: Related but closed, ...

I suppose "Falsy, any consistent non-array value" includes raising an error?

"Any value can be used as a falsy indicator, other than an array of integers." Does that include an empty array?

@shaggy [] is indicative of a potential truthy value, right? Is allowing that meta rule more important than distinct truthy and falsy?

@JohnathanAllan if that error cannot be raised in a Truthy scenario- I'd suppose. But I feel this is intentionally attempting to stretch the spec. If i change the wording from indicator to return value is it fine then?

I do believe consistent exit values do count as a return value though per meta?

Something like a maybe or option type is pretty important to allow for typed languages that only allow total functions. The general assumption that every type has a falsey value is just bogus.

@dfeuer falsy and true mean any two distinct values you define. You could output "banana" for true and 293559019 for false if you desire.

Brachylog, 8 bytes
h⊇.+~t?∧

Try it online!
Monthly Brachylog answer. Returns false. if it is not possible.
Explanation
h⊇.           The output is a subset of the head of the input
  .+~t?       The sum of the elements of the output must equal the tail of the input
       ∧      (Avoid implicit unification between the output and the input)

Python 2, 108 104 bytes
lambda a,n:[x for l in range(len(a)+1)for x in combinations(a,l)if sum(x)==n][-1]
from itertools import*

Try it online!
-4 bytes, thanks to Jonathan Allan

Python 2, 108 106 bytes
def f(a,n):
 q=[a]
 while q:
  x=q.pop(0);q+=[x[:i]+x[i+1:]for i in range(len(x))]
  if sum(x)==n:return x

Try it online!
-2 bytes, thanks to Janathan Frech

You could use range(-len(a),1) and -l to save 2, but lambda a,n:[x for l in range(len(a)+1)for x in combinations(a,l)if sum(x)==n][-1] saves 4.

Possible 106 bytes.

@JonathanFrech Thanks, I must have been tired yesterday ;)

05AB1E, 9 bytes
æʒOQ}0ªéθ

Try it online!

Japt -h, 11 bytes
à f_x ¥VÃñl

Try it online!

Pyth, 8 bytes

8-byter (Try it!) – Outputs only one possible solution. For unsolvable inputs, it doesn't print anything to STDOUT, which is an empty string, which is technically speaking falsey in Pyth, but writes to STDERR. Thanks to FryAmTheEggman for suggesting this (ignoring STDERR and focusing on the STDOUT output only), thus saving 1 byte.
efqz`sTy

9-byter (Try it!) – Outputs only one possible solution, wrapped in a singleton list as allowed by default (e.g. ([1...10], 10) -> [[1,2,3,4]]; ([], 0) -> [[]]). For unsolvable inputs, it returns [], which is falsey in Pyth.
>1fqz`sTy

10-byter (Try it!) – For a clearer output, without using the singleton-list rule and using 0 rather than [] as a falsy value.
e+0fqz`sTy

Explanation
First, the code computes the powerset of the input list (all possible ordered sub-collections thereof). Then, it only keeps those collections whose sum is equal to the input number. It should be noted that the collections are generated from the shortest to the longest, so we focus on the last one. To obtain it:

The 8-byter simply uses the end built-in, which throws an error, but STDERR can be ignored as per our site rules, the output to STDOUT being an empty string, which is falsy.
The 9-byter takes the last element, but using the equivalent Python code lst[-1:] in place of lst[-1] to avoid errors from being thrown for unsolvable inputs.
The 10-byter prepends a 0 to the list of filtered sub-collections, then takes the end of that collection (last element). If the inputs aren't solvable, then 0 is naturally used instead.

[] is falsy? Neat. Why does Pyth do that []?

@MagicOctopusUrn Pyth inherits that from Python actually: Try it online.

@FryAmTheEggman wouldn't an empty list be a truthy output in the test case f([], 0) = []?

@FryAmTheEggman Thanks for your suggestion! I've made the necessary changes :)

Jelly, 7 bytes
ŒPS⁼¥ƇṪ

Try it online!
Output clarified over TIO.

Perl 6, 38 37 bytes
{*.combinations.grep(*.sum==$_).tail}

Try it online!
Curried function.

Wait, is the ; even necessary?

@JoKing It was necessary in an earlier iteration to avoid a "malformed double closure" error. But for some reason it can be omitted now. (I think after I replaced $^x with $_.)

Brachylog, 4 bytes
⟨⊇+⟩

Try it online!
Just about equivalent to Fatalize's h⊇.+~t?∧, except a lot shorter, thanks to the predicate composition feature which according to the edit history of the reference was a work in progress until January 8, postdating the answer by over two months. ⟨⊇+⟩ is a sandwich, expanding to {[I,J]∧I⊇.+J∧}, where the braces are in this case irrelevant as the sandwich is on its own line anyhow.
                The input
[I,J]           is a list of two elements I and J.
        .       The output,
         +J     which sums to J
           ∧    (which we don't unify with the output),
      I⊇        is a sublist of I
     ∧          (which we don't unify with [I,J]).

A far less dramatic transformation of Fatalize's answer, which uses the same predicates with the same variables but comes out a byte shorter from being organized differently:
Brachylog, 7 bytes
h⊇.&t~+

Try it online!
           The input
h          's first element
 ⊇         is a superlist of
  .        the output,
   &       and the input
    t      's last item
     ~+    is the sum of the elements of
           the output.

(Also, if anyone wants to see something odd, change any of the underscores in the test cases into hyphens.)

Sandwiches were implemented by @ais523 in November 2018 but were only pulled in Brachylog in early January 2019.

Of course, none of this history-digging matters, since languages that postdate the challenge have been allowed for years.

R, 100 80 bytes
function(a,x){i[sum(a|1):0,j[combn(a,i,,F),if(sum(j)==x)return(j)]]
F}
`[`=`for`

Try it online!
20 bytes saved thanks to digEmAll
Returns FALSE for impossible criteria.

And [80 abusing '' operator :D

@digEmAll I'm certainly glad I didn't get a chance to edit in your 98 byte answer :-)

eheh forgot to delete it :D

Pyth, 14 bytes
A.Q|>1fqsTHyG0

Try it online!

This started out cool and small, but edge cases got me. Whatever happens, I'm proud of the work I put into this.
Python 3, 169 161 154 bytes
from itertools import*
def f(a,x):
	if sum(a)==x:return a
	try:return[c for i in range(len(a))for c in combinations(a,i)if sum(c)==x][-1]
	except:return 0

Try it online!

Remember that this is [code-golf] so you should try to make your byte count as small as possible! You have a leading newline and some other trivial whitespace golfs, and I bet someone else who knows python can golf this down further.

@Giuseppe Thanks for reminding me of the leading whitespace. I spent some time trying to consolidate some parts of this, but decided to post it in the meantime in case any others can suggest edits.

Not a problem! It's been like 5 years since I did any Python, but doesn't range(x) generate (0...x-1)? So your range(len(a)) isn't giving you the possibility of leaving the array unchanged?

@Giuseppe Eureka, that did it. I may have been focusing too much on the new material I was working with.

Instead of if a==[] and x==0 use if sum(a)==x. Then you can also remove +1 from range.

@VedantKandoi That handles the zero-sum and whole-length cases at once, thanks!

You could have false be returned as the presence of an error, the if else can be a list, and then you can turn it into a lambda. 117 bytes

@JoKing Is the implementation supposed to crash on a falsey case?

Yes? This is confirmed by the asker, but I'm pretty sure presence of an error is valid output from default IO

Clean, 89 bytes
import StdEnv,Data.List,Data.Func
$n=find((==)n o sum)o sortBy(on(>)length)o subsequences

Try it online!
Defines the function $ :: Int -> [Int] -> (Maybe [Int]) returning Nothing if there is no appropriate combination of elements, and (Just [elements...]) otherwise.

JavaScript (ES6), 108 bytes
Takes input as (array)(n). Returns either an array or false.
a=>n=>a.reduce((a,x)=>[...a,...a.map(y=>1/r[(y=[...y]).push(x)]||eval(y.join`+`)-n?y:r=y)],[[]],r=!n&&[])&&r

Try it online!

Attache, 28 bytes
${(y&`=@Sum\Radiations@x)@0}

Try it online!
Alternatives
34 bytes: f[x,y]:=({y=Sum@_}\Radiations@x)@0
30 bytes: First@${y&`=@Sum\Radiations@x}
29 bytes: {(_&`=@Sum\_2)@0}#/Radiations
29 bytes: ${({y=Sum@_}\Radiations@x)@0}
29 bytes: `@&0@${y&`=@Sum\Radiations@x}
29 bytes: {_}@@${y&`=@Sum\Radiations@x}
Explanation
${(y&`=@Sum\Radiations@x)@0}
${                         }    function receiving two arguments, x and y
            Radiations@x        calculate the radiations of x
                                (simulates removing all possible subslices of x)
           \                    keep those radiations
        Sum                     ...whose sum...
     `=@                        ...equals...
   y&                           ...y
  (                     )@0     select the first one (always the longest)

APL(NARS), 65 chars, 130 bytes
{m←⍺=+/¨v←1↓{0=⍴⍵:⊂⍬⋄s,(⊂1⌷⍵),¨s←∇1↓⍵}⍵⋄0=↑⍴b←m/v:⍬⋄b⊃⍨n⍳⌈/n←⍴¨b}

↓ is used because the first element of the set of sets would be one void set (here ⍬ Zilde),
that one want eliminate because it seems +/⍬ is zero...
For not find, or error it would return ⍬ or in print text:
  o←⎕fmt
  o ⍬
┌0─┐
│ 0│
└~─┘

test:
  z←{m←⍺=+/¨v←1↓{0=⍴⍵:⊂⍬⋄s,(⊂1⌷⍵),¨s←∇1↓⍵}⍵⋄0=↑⍴b←m/v:⍬⋄b⊃⍨n⍳⌈/n←⍴¨b}

  o 1 z ,1
┌1─┐
│ 1│
└~─┘
  o 2 z ,1
┌0─┐
│ 0│
└~─┘
  o 10 z 1 2 3 4 5 6 7 8 9 10
┌4───────┐
│ 1 2 3 4│
└~───────┘
  o 10 z 2,2,2,2,2,2,2,2,2
┌5─────────┐
│ 2 2 2 2 2│
└~─────────┘
  o ¯8 z 2,2,2,2,¯2,¯2,¯2,¯4,¯2
┌7──────────────────┐
│ 2 2 ¯2 ¯2 ¯2 ¯4 ¯2│
└~──────────────────┘
  o ¯6 z ¯2,¯4,¯2
┌2─────┐
│ ¯4 ¯2│
└~─────┘
  o 0 z 2,2,2,4,2,¯2,¯2,¯2,¯4,¯2
┌10───────────────────────┐
│ 2 2 2 4 2 ¯2 ¯2 ¯2 ¯4 ¯2│
└~────────────────────────┘
  o 10 z 1 2 3 4
┌4───────┐
│ 1 2 3 4│
└~───────┘
  o 10 z 1 2 3
┌0─┐
│ 0│
└~─┘
  o 0 z ⍬
┌0─┐
│ 0│
└~─┘
  o +/⍬
0
~

Husk, 8 bytes
▲fo=⁰ΣQ²

Try it online!
Brachylog is insane.

Haskell, 68 bytes
import Data.List
f x=find((==x).sum).sortOn(sum.(-1<$)).subsequences

Try it online!
Defines f x a to return Just a subset or Nothing.
The only trick here is that sum.(-1<$) is one  byte shorter than (0-).length.

source: Stack Exchange

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

sort: votes


text:
Repeat this GCD operation
Problem A3 from the 2008 Putnam competition says:

Start with a finite sequence \$a_1, a_2, \dots, a_n\$ of positive integers. If possible, choose two indices \$j < k\$ such that \$a_j\$ does not divide \$a_k\$, and replace \$a_j\$ and \$a_k\$ by \$\gcd(a_j, a_k)\$ and \$\text{lcm}(a_j, a_k)\$, respectively. Prove that if this process is repeated, it must eventually stop and the final sequence does not depend on the choices made.

Your goal in this challenge is to take a finite sequence of positive integers as input, and output the result of repeating this process until no further progress is possible. (That is, until every number in the resulting sequence divides all the numbers that come after it.) You don't need to solve the Putnam problem.
This is code-golf: the shortest solution in every programming language wins.
Test cases
[1, 2, 4, 8, 16, 32] => [1, 2, 4, 8, 16, 32]
[120, 24, 6, 2, 1, 1] => [1, 1, 2, 6, 24, 120]
[97, 41, 48, 12, 98, 68] => [1, 1, 2, 4, 12, 159016368]
[225, 36, 30, 1125, 36, 18, 180] => [3, 9, 18, 90, 180, 900, 4500]
[17, 17, 17, 17] => [17, 17, 17, 17]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] => [1, 1, 1, 1, 1, 2, 2, 6, 60, 2520]

What a neat problem! Write each integer $a_i$ as $\displaystyle 2^{\alpha_i} 3^{\beta_i} 5^{\gamma_i} \cdots$ and note that the process simply bubble-sorts the lists $\alpha, \beta, \gamma, \dots$ in parallel :)

Jelly, 9 bytes
ÆEz0Ṣ€ZÆẸ

Try it online!
How it works
ÆEz0Ṣ€ZÆẸ  Main link. Argument: A (array)

ÆE         For each n in A, compute the exponents of n's prime factorization.
           E.g., 2000000 = 2⁷3⁰5⁶ gets mapped to [7, 0, 6].
  z0       Zip 0; append 0's to shorter exponent arrays to pad them to the same
           length, then read the resulting matrix by columns.
    Ṣ€     Sort the resulting arrays (exponents that correspond to the same prime).
      Z    Zip; read the resulting matrix by columns, re-grouping the exponents by
           the integers they represent.
       ÆẸ  Unexponents; map the exponent arrays back to integers.

Pari/GP, 33 bytes
Calculate the elementary divisors of the diagonal matrix.
a->Vecrev(matsnf(matdiagonal(a)))

Try it online!

J, 17 bytes
/:~"1&.|:&.(_&q:)

Try it online!
Probably the first J answer on PPCG to use &. twice. After this and that, I'm starting to feel like a weird J hacker.
Basically a translation from Dennis' Jelly answer.
How it works
/:~"1&.|:&.(_&q:)  Single monadic verb.
           (_&q:)  Convert each number to prime exponents
                   (automatically zero-filled to the right)
       |:&.        Transpose
/:~"1&.            Sort each row in increasing order
       |:&.        Transpose again (inverse of transpose == transpose)
           (_&q:)  Apply inverse of prime exponents; convert back to integers

An earlier one is here

Wolfram Language (Mathematica), 44 bytes
Table[GCD@@LCM@@@#~Subsets~{i},{i,Tr[1^#]}]&

The \$k\$-th element of the result is the GCD of the LCM's of the subsets with \$k\$ elements.
\$b_k = \gcd(\{\operatorname{lcm}(a_{i_1}, \cdots, a_{i_k}) | 1 \le i_1 < \cdots < i_k \le n\})\$
Try it online!

Very nice! You're two for two on weird approaches I didn't see coming :)

Python 3, 103 bytes
import math
def f(a,i=0,j=-1):d=math.gcd(a[i],a[j]);a[j]*=a[i]//d;a[i]=d;a[i:j]and f(a,i,j-1)==f(a,i+1)

Try it online!
Explanation
This problem is essentially a parallel sort on the prime factors, and (gcd(a,b), lcm(a,b)) is analogous to (min(a,b), max(a,b)). So let's talk in terms of sorting.
We will prove by induction that after f(i,j), a[i] becomes the smallest value in (the old value of) L, where L is the range between a[i] and a[j], including both ends. And if j = -1, f(i,j) will sort the range L.
The case when L contains one element is trivial. For the first claim, notice that the smallest of L can't stay in a[j] after the swap, so f(i,j-1) will put it in a[i], and f(i+1,-1) will not affect it.
For the second claim, note that a[i] is the smallest value, and f(i+1,-1) will sort the remaining values, so L becomes sorted after f(i,j).

Retina, 65 bytes
\d+
*
+`\b((_+)(\2)+)\b(.*)\b(?!\1+\b)(\2+)\b
$2$4$5$#3*$5
_+
$.&

Try it online! Link includes the faster test cases. Explanation:
\d+
*

Convert to unary.
+`\b((_+)(\2)+)\b(.*)\b(?!\1+\b)(\2+)\b

Repeatedly match: any number with a factor, then a later number that is not divisible by the first number but is divisible by the factor.
$2$4$5$#3*$5

$1 is the first number. $2 is the factor. Because regex is greedy this is the largest factor i.e the gcd. $4 is the part of the match between the original numbers. $5 is the second number. $#3 (in decimal rather than unary) is one less than $1 divided by $2, since it doesn't include the original $2. This means that to calculate the lcm we need to multiply $5 by one more than $#3 which is most succintly written as the sum of $5 and the product of $#3 and $5.
_+
$.&

Convert to decimal.

Unary is allowed by default for Retina, so you can count this as 52 bytes.

@Dennis Only three of my Retina answers take input in unary; I've got used to doing I/O in decimal.

JavaScript (SpiderMonkey), 69 bytes
a=>a.map((q,i)=>a.map(l=(p,j)=>a[j]=j>i&&(t=p%q)?p/t*l(q,j,q=t):p)|q)

Try it online!

Function l assign lcm(p,q) to a[j], and assign gcd(p, q) to q if j > i, otherwise keeps everything unchanged.

lcm(p,q) = if p%q=0 then p else p*lcm(q,p%q)/(p%q)

Old answer:
JavaScript (SpiderMonkey), 73 bytes
a=>a.map((u,i)=>a.map((v,j)=>i<j?a[j]*=u/(g=p=>p%u?g(u,u=p%u):u)(v):0)|u)

Try it online!

Function g calculate gcd(u, v) and assign return value to u.

05AB1E, 10 bytes
Credit for the approach goes to alephalpha.
εIæN>ù€.¿¿

Try it online!
εIæN>ù€.¿¿     Full program. Takes a list from STDIN, outputs another one to STDOUT.
ε              Execute for each element of the input, with N as the index variable.
 Iæ            Powerset of the input.
   N>ù         Only keep the elements of length N+1.
      €.¿      LCM each.
         ¿     Take the GCD of LCMs.

Perl 6, 53 bytes
{map {[gcd] map {[lcm] $_},.combinations: $^i},1..$_}

Try it online!
Port of alephalpha's Mathematica answer.

05AB1E, 15 14 13 bytes
Ó¾ζ€{øεgÅpymP

Port of @Dennis♦' Jelly answer, but unfortunately 05AB1E doesn't have an Unexponents-builtin, so that takes more than halve the program.. :(
-1 byte thanks to @Mr.Xcoder.
-1 byte thanks to @Emigna.
Try it online or verify all test cases.
Explanation:
Ó          # Prime exponents of the (implicit) input-list
 ¾ζ        # Zip, swapping rows and columns, with integer 0 as filler
   €{      # Sort each inner list
     ø     # Zip, swapping rows and columns again
ε          # Map each inner list:
 gÅp       #  Get the first `l` primes, where `l` is the size of the inner list
    ym     #  Take the power of the prime-list and inner list
      P    #  And then take the product of that result
           # (And output implicitly)

Oh, I hadn't seen your answer prior to posting my own, lol. 14 bytes by using ¾ and removing 0ï, +1. (I've tried this before because I tried to port Dennis' answer as well lol)

Using εgÅpymP would save another byte over the one Mr. Xcoder metioned

@Mr.Xcoder Oh, didn't knew there was a difference between the filler with 0 and ¾. Need to remember that! In fact, I will add it to my small 05AB1E tips right now. :)

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


text:
Count cyclically self-describing lists
Cyclically self-describing lists
A list \$L\$ of positive integers is cyclically self-describing, if the following conditions hold.

\$L\$ is nonempty.
The first and last elements of \$L\$ are different.
If you split \$L\$ into runs of equal elements, the element of each run equals the length of the next run, and the element of the last run equals the length of the first run.

For example, consider \$L = [1,1,1,2,3,3,1,1,1,3]\$.
It is nonempty, and the first and last elements are different.
When we break it into runs, we get \$[[1,1,1],[2],[3,3],[1,1,1],[3]]\$.

The first run is a run of \$1\$s, and the length of the next run, \$[2]\$, is \$1\$.
The second run is a run of \$2\$s, and the length of the next run, \$[3,3]\$, is \$2\$.
The third run is a run of \$3\$s, and the length of the next run, \$[1,1,1]\$, is \$3\$.
The fourth run is a run of \$1\$s, and the length of the next run, \$[3]\$, is \$1\$.
Finally, the last run is a run of \$3\$s, and the length of the first run, \$[1,1,1]\$, is \$3\$.

This means that \$L\$ is a cyclically self-describing list.
For a non-example, the list \$[3,2,2,2,1,4,1,1,1]\$ is not cyclically self-describing, since a run of \$2\$s is followed by a run of length \$1\$.
The list \$[2,2,4,4,3,3,3,3]\$ is also not cyclically self-describing, since the last run is a run of \$3\$s, but the first run has length \$2\$.
The Task
In this challenge, your input is an integer \$n \geq 1\$.
Your output shall be the number of cyclically self-describing lists whose sum equals \$n\$.
For example, \$n = 8\$ should result in \$4\$, since the cyclically self-describing lists whose sum is \$8\$ are \$[1,1,1,1,4]\$, \$[1,1,2,1,1,2]\$, \$[2,1,1,2,1,1]\$ and \$[4,1,1,1,1]\$.
The lowest byte count wins, and other standard code-golf rules apply.
Here are the correct output values for inputs from \$1\$ to \$50\$:
1 -> 0
2 -> 0
3 -> 0
4 -> 2
5 -> 0
6 -> 2
7 -> 0
8 -> 4
9 -> 0
10 -> 6
11 -> 6
12 -> 12
13 -> 0
14 -> 22
15 -> 10
16 -> 32
17 -> 16
18 -> 56
19 -> 30
20 -> 96
21 -> 56
22 -> 158
23 -> 112
24 -> 282
25 -> 198
26 -> 464
27 -> 364
28 -> 814
29 -> 644
30 -> 1382
31 -> 1192
32 -> 2368
33 -> 2080
34 -> 4078
35 -> 3844
36 -> 7036
37 -> 6694
38 -> 12136
39 -> 12070
40 -> 20940
41 -> 21362
42 -> 36278
43 -> 37892
44 -> 62634
45 -> 67154
46 -> 108678
47 -> 118866
48 -> 188280
49 -> 209784
50 -> 326878

An unexpected twist! Halfway through the description I was expecting the less-interesting task of just determining if a list was CSD. Kudos.

I am a little sad that the definition doesn't include lists where the first and last element are the same, and count as the same group, as they would if the list were actually a cycle without a distinct start/end.

This is code-golf, so I think determining if a list is cyclically self-describing is more interesting (solutions faster to execute) -- if there is no short way other than generating all lists and count.

There is a polynomial time algorithm, but it is quite difficult to program and definitely not as golfy as a solution that generates and verifies all possible lists.

13 is the largest impossible sum of a cyclically self-describing list? Unlucky!

@Neil prove it ;)

Every even number except 2 can be obtained as n,1,...,1, and every odd number greater than 13 can be obtained by concatenating 3,2,2,2,1,1 to an even number. The proof that 13 is impossible is left as an exercise for the reader.

Very loosely related... (Nowhere near a dupe, but is a challenge involving cyclical self-referencing)

This does not currently have an oeis entry. Consider submitting it?

Haskell, 75 bytes
Thanks Ørjan for saving one byte!
g n=sum[x#n|x<-[1..n],let a#n=sum$[b#(n-a*b)|b<-[1..n],a/=b]++[0^n^2|a==x]]

Try it online!
The problem is equivalent to:
How many ways can \$n\$ be written as \$\sum_{i=0}^ka_ia_{i+1}\$ with \$a_i\in\mathbb N,a_i\neq a_{i+1},a_0=a_k\$

76

Jelly, 18 bytes
ṗⱮ¹Ẏ;ḷ/$€IẠ$Ƈ×Ɲ€§ċ

Try it online!
Idea: Each cyclically self-describing list can be described as a list of values for each block, and we can deduce the lengths from the values. Note that two adjacent values must be different. Of course there can be at most n blocks and the length of each block is at most n.

Haskell, 118 105 103 bytes
Edit: -13 bytes thanks to @Ørjan Johansen, -2 bytes thanks to @H.PWiz
g s=sum[b#a$s|b<-[1..s],a<-[1..s],let(d#l)s|d==a,d/=b,l*d==s=1|n<-s-d*l=sum[i#d$n|i<-[1..s],d/=i,n>=0]]

Try it online!

Factor out with the same trick I showed H.PWiz.

You missed (i#d)n -> i#d$n

05AB1E, 25 bytes
Åœεœʒ¬sθÊ}ÙεγĆü‚ε`gå}P]˜O

Try it online or verify the first 9 test cases (times out for \$n\geq10\$).
Explanation:
Åœ              # Get all lists of positive integers that sum to the (implicit) input
  ε             # Map over each inner list:
   œ            #  Get all its permutations
    ʒ           #  Filter this list of permutation-lists by:
     ¬          #   Get the first element (without popping the list itself)
      sθ        #   Swap to get the list, and pop and push its last element
        Ê       #   Check that they are NOT equal
    }Ù          #  After the inner filter: uniquify all remaining permutations
      ε         #  Map each permutation to:
       γ        #   Split the list into groups of equal adjacent elements
        Ć       #   Enclose it: add the first group as trailing item
         ü‚     #   Create overlapping pairs of groups
           ε    #   Map over each pair:
            `   #    Pop and push both lists separated to the stack
             g  #    Pop and get the length of the second list
              å #    And check that it's in the first list
           }P   #   After this inner-most map: verify all pairs were truthy (product)
  ]             # Close the two still open nested maps
   ˜            # Flatten the list of lists
    O           # And take the sum
                # (after which this is output implicitly as result)

Try it online with a step-by-step output.

Husk, 27 bytes
#§=oṙ1mLm←fo¬εumgfo=¹ΣṖṁḣ´R

Try it online!
A direct bruteforce. Struggles for n above 4.


text:
Find the minimal initial values
Consider a sequence F of positive integers where F(n) = F(n-1) + F(n-2) for n >= 2.  The Fibonacci sequence is almost one example of this type of sequence for F(0) = 0, F(1) = 1, but it's excluded because of the positive integer requirement.  Any two initial values will yield a different sequence.  For example F(0) = 3, F(1) = 1 produces these terms.
3, 1, 4, 5, 9, 14, 23, 37, 60, 97, ...

Challenge
The task is to find F(0) and F(1) that minimize F(0) + F(1) given some term of a sequence F(n).  Write a function or complete program to complete the task.
Input
Input is a single positive integer, F(n).  It may be accepted as a parameter or from standard input.  Any reasonable representation is allowed, including direct integer or string representations.
Invalid inputs need not be considered.
Output
The output will be two positive integers, F(0) and F(1).  Any reasonable format is acceptable.  Here are some examples of reasonable formats.

Written on separate lines to standard output
Formatted on standard output as a delimited 2-element list
Returned as a tuple or 2-element array of integers from a function

Examples
60  -> [3, 1]
37  -> [3, 1]
13  -> [1, 1]
26  -> [2, 2]
4   -> [2, 1]
5   -> [1, 1]
6   -> [2, 2]
7   -> [2, 1]
12  -> [3, 2]
1   -> [1, 1]

Scoring
This is code golf.  The score is calculated by bytes of source code.
Sandbox

does 12 -> [4, 0] count?

F is a sequence of positive integers, and 0 isn't positive, so that's not valid.

Nitpick: the Fibonacci sequence may be defined by $F[0] = 0, F[1] = 1$ or $F[1] = F[2] = 1$. Many of the sequence's well-known properties rely on this indexing.

@Dennis:  Technical correctness being the best kind, I've tweaked that part.

This feels familiar but, at the same time, I think the challenge I might be thinking of is the reverse of this - given F(0), F(1) and n as input, output F(n-1)+F(n-2).

This looks like a duplicate of The lowest initial numbers in a Fibonacci-like sequence

@xnor: Yes, I suppose it is.  Being the author isn't enough to close it though, but I voted for it.

I knew this challenge looked familiar but I couldn't find it. I've closed it, although I forgot that my vote was a hammer.

Jelly, 13 bytes
pWạ\Ṛ$</¿€SÞḢ

Try it online!
How it works
pWạ\Ṛ$</¿€SÞḢ  Main link. Argument: n

 W             Wrap; yield [n].
p              Cartesian product; promote the left argument n to [1, ..., n] and take
               the product of [1, ..., n] and n, yielding [[1, n], ..., [n, n]].
         €     Map the link to the left over the pairs [k, n].
        ¿          While...
      </               reducing the pair by less-than yields 1:
  ạ\                       Cumulatively reduce the pair by absolute difference.
    Ṛ                      Reverse the result.
                   In essence, starting with [a, b] := [k, n], we keep executing
                   [a, b] := [b, |a - b|], until the pair is no longer increasing.
          SÞ   Sort the resulting pairs by their sums.
            Ḣ  Head; extract the first pair.

Japt, 34 bytes

_Ì<U?[ZÌZx]gV:ZÌ
õ ïUõ)ñx æ_gV ¥U

Try it online!
The empty first line is important.
Explanation:
_                     Declare a function V:
 Ì<U?        :ZÌ        If the second number is >= n, return it
     [ZÌZx]gV           Otherwise call V again with the second number and the sum

õ ïUõ)                Get all pairs of positive integers where both are less than n
      ñx              Sort them by their sum
         æ_gV ¥U      Return the first (lowest sum) one where V returns n

Perl 6, 52 bytes
->\n{(1..n X 1..n).max:{(n∈(|$_,*+*...*>n))/.sum}}

Try it online!
Brute-force solution.

Haskell, 81 80 bytes

-1 byte thanks to Laikoni

f x=[(a,s-a)|s<-[2..],a<-[1..s-1],let u=s-a:zipWith(+)u(a:u),x`elem`take x u]!!0

Try it online!

head[...] can be [...]!!0.

JavaScript, 216 bytes
function f(r){for(var n=1;;){var f=p(n);for(var u in f)if(s(f[u][0],f[u][1],r))return f[u];n++}}function p(r){for(var n=[],f=1;0<r;)n.push([r,f]),r--,f++;return n}function s(r,n,f){return n==f||(f<n?null:s(n,r+n,f))}

https://jsfiddle.net/twkz2gyb/
(Ungolfed code):
// For a given input n, return all combinations of positive integers that sum to n.
function findPairs(n) {
    var arr = [];
    var b = 1;
    while(n > 0) {
        arr.push([n, b]);
        n--;
        b++;
    }
    return arr;
}

// Run a sequence for a and b, and continue fibonacci'ing until r is found(or quit if past r).
function sequence(a, b, r) {
    if(b === r) {
        return true;
    } else if(b > r) {
        return null;
    }
    var nextFibo = a + b;
    return sequence(b, nextFibo, r);
}

// For a given n, find the first 2 numbers of the fibonacci sequence with the smallest sum that result in n.
function find(n) {
    var i = 1;
    while(i < 10) {
        var pairs = findPairs(i);
        for(var p in pairs) {
            var result = sequence(pairs[p][0], pairs[p][1], n);
            if(result) {
                return pairs[p];
            }
        }
        i++;
    }
}


text:
How fast am I vrooooming?
Introduction
My car speedometer was hacked! Instead of showing me how fast i'm driving, it just shows: "Vroooom!" Please help me know how fast i'm going.
Challenge
Take a string as input, and check if it matches the regex /^[Vv]ro*m!$/m. In English that means any line of the string must start with a capital or lowercase v, then a lowercase r, then any amount (including zero) of the lowercase letter o, then the exact string m!. There may be other lines, but the Vroom string must be on it's own line.
If you find a match, then you must count the amount of o's in the Vroom string and output it. If you don't find a match however, you should output any default value that can't be outputted otherwise (like -1 or an empty string)
Reminders

I/O is in any reasonable format
Standard loopholes are banned
Submission may be a full program or function
Input is guaranteed to only have 1 Vroom string

Scoring
This is code-golf, so the shortest code in bytes wins. However, I will not mark any answer as accepted.
Test cases
Input
Vrom!

Output 1
Input
vrooooooom!

Output 7
Input
Hello, Vroom!

Output (none)
Input
Foo bar boo baz
Vrooom!
hi

Output 3
Input
Vrm!ooo

Output (none)
Input
PPCG puzzlers pie

Output (none)
Input
hallo
vROOOm!

Output (none)

sed 4.2.2, 20 bytes
-nr options required at the command-line.
s/^[Vv]r(o*)m!$/\1/p

This outputs the speed in unary as the number of os.
Try it online!

Can't tell Vrm! from Vram!

Python 2, 56 53 bytes
lambda x:len(re.search('^[Vv]r(o*)m!$',x,8).group(1))

Try it online!
Basic regex and grouping, uses re.MULTILINE flag (which has a value of 8) and re.search to ensure it works for multiline inputs. Raises an exception when no match is found. Thanks to @ovs for the -3 bytes from (re.M == 8) tip.

Welcome to PPCG! I reformatted your answer to make it appear a bit nicer, if you're unhappy with my edit you can always roll back. Btw. I suggest to link to something like tio.run such that people can easily test your answer.

re.M has the value 8, so can just use re.search(regex,x,8)

R, 62 60 58 44 bytes
nchar(grep("^[Vv]ro*m!$",readLines(),v=T))-4

Try it online!
@Giuseppe with 14 bytes golfed.
Original approach with explanation:
function(x)attr(el(regexec("(?m)[Vv]r(o*)m!$",x,,T)),"m")[2]

Try it online!
R has seven pattern matching functions. The more commonly used ones are grep, grepl, and sub, but here's a nice use for regexec.
regexec gives you a bunch of things, one of which is the length of any captured substring, in this case the (o*) part of the multiline regex.
The attr(el .... "m")[2] stuff is a golfy way to get the desired number.
Returns NA if there is no match.

58 bytes with a different approach

I have a 44 byte approach... Not gonna post it unless you want me to.

@Giuseppe not sure why not? Especially if it's fundamentally different.

Powershell, 62 58 53 48 bytes bytes
"$($args|sls '(?m-i)^[Vv]ro*m!$'|% M*)".Length-4

returns numbers of o in a first Vroom!, or -4 if Vroom! not found.
Notes:

sls is alias for Select-String;
(?m-i) inside regexp means:

Use multiline mode. ^ and $ match the beginning and end of a line, instead of the beginning and end of a string.
Use case-sensitive matching

|% M* is shortcut for the property Matches, which gives a first match because we don't use -AllMatches parameter.

Test script:
$f = {

"$($args|sls '(?m-i)^[Vv]ro*m!$'|% M*)".Length-4

}

@(
,('Vrom!',1)
,('vrooooooom!',7)
,('Hello, Vroom!',-4)
,('Foo bar boo baz
Vrooom!
hi',3)
,('Vrm!ooo',-4)
,('PPCG puzzlers pie',-4)
,('hallo
vROOOm!',-4)
,('
Vrooom!
Vrooooom!
',3)        # undefined behavior.
,('vrm!',0) # :)
) | % {
    $n,$expected = $_
    $result = &$f $n
    "$($result-eq$expected): $result"
}

Output:
True: 1
True: 7
True: -4
True: 3
True: -4
True: -4
True: -4
True: 3
True: 0

JavaScript (Node.js), 41 bytes
a=>(l=/[Vv]r(o*)m!/.exec(a))&&l[1].length

Try it online!

This fails for vroooooooooooom!x\nvrom!

Seeing as we're allowed exit with an error if no match is found, you could do this for -3 bytes, fixing the problem @BMO mentioned above in the process.

Uncrossed-out 41 is definitely still 41

@Shaggy What's the space in [1]. length for?

@l4m2, a typo! I didn't spot it on my phone 'cause length was breaking to a newline anyway.

Retina, 21 bytes
L$m`^[Vv]r(o*)m!$
$.1

Try it online! Explanation: L lists matches, so if the regex fails to match then output is empty. $ causes the result to be the substitution rather than the match. m makes it a multiline match (the equivalent to the trailing m in the question). The . in the substitution makes it output the length of the capture in decimal.

Perl 6, 26 bytes
{-!/^^[V|v]r(o)*m\!$$/+$0}

Try it online!

C (gcc), 188 183 bytes
Why use regexes when you can use a state machine instead? :-)
a,b;f(char*s){for(a=b=0;a<5;s++){!a&*s==86|*s=='v'?a++:a==1&*s=='r'?a++:a==2?*s-'o'?*s-'m'?0:a++:b++:a==3&*s==33?a++:!*s&a==4?a++:*s-10?(a=-1):a-4?(a=0):a++;if(!*s)break;}s=a<5?-1:b;}

Try it online!

147

SNOBOL4 (CSNOBOL4), 99 82 bytes
I	INPUT POS(0) ('V' | 'v') 'r' ARBNO('o') @X 'm!' RPOS(0)	:F(I)
	OUTPUT =X - 2
END

Try it online!
Pretty direct SNOBOL translation of the spec, reads each line until it finds one that matches ^[Vv]ro*m!$, then outputs the length of the o* bit.
Enters an infinite loop if no Vroom! can be found.

Is all that whitespace necessary? Wow.

@FireCubez yep, that's what you get with a 50+ year-old language: weird whitespace requirements. It uses space/tab as concatenation and you must surround operators with whitespace as well.

PowerShell, 83 bytes
($args-split"`n"|%{if(($x=[regex]::Match($_,"^[Vv]ro*m!$")).success){$x}}).length-4

Try it online!
-splits the input $args on `newlines, pipes those into a for loop. Each iteration, we check whether our [regex]::Match is a .success or not. If so, we leave $x (the regex results object) on the pipeline. Outside the loop, we take the .length property -- if it's the regex results object, this is the length of the match (e.g., "Vroom!" would be 6); if it's not a regex results object, the length is zero. We then subtract 4 to remove the counts for the Vrm! and leave that on the pipeline. Output is implicit. Outputs a -4 if no match is found.

sls "^[Vv]ro*m!$"?

@mazzy How would that work for multiline input? Your only input is one string, and so sls will give back ('','Vroom!','') for example.

it's not completed solution. I mean, you can try sls instead [regex]::Match

@mazzy Maybe you should post it as a separate solution.

Japt, 18 bytes
fè`^[Vv]*m!$` ®èo

Try it online!
Saved a byte by taking input as an array of lines.
Includes an unprintable character between ] and *.
Explanation:
fè                   Get the line(s) that match
  `^[Vv]*m!$`          The provided RegEx with a little compression
              ®èo    Count the number of "o" in that line if it exists

19 bytes

Also 19 bytes

Actually, as input can be an array of lines, you can knock the first byte off my first comment above.

@Shaggy I can't find anywhere in the question that specifies that input can be an array of lines, and it doesn't seem to be listed in the default I/O methods that a multiline string can be taken as an array of lines. It seems likely to be reasonable, but I'll wait for confirmation first.

Haskell, 75 71 69 bytes
f s=[length n-2|r<-lines s,n<-scanr(:)"m!"$'o'<$r,v<-"Vv",r==v:'r':n]

Try it online!
No regex. Instead builds all valid Vrooom!-strings up to a sufficient length and compares the lines of the input against them, collecting the number of os in a list. Thus for invalid inputs an empty list is returned.

C (gcc), 138 124 bytes
Here's the boring regex way.
#include<regex.h>
f(char*s){regmatch_t m[9];regcomp(m+2,"^[Vv]r(o*)m!$",5);s=regexec(m+2,s,2,m,0)?-1:m[1].rm_eo-m[1].rm_so;}

Try it online!

C (gcc), 104 100 bytes
s;main(c,n){for(;gets(&s);sscanf(&s,"v%*[o]%nm%c%c",&n,&c,&c)-1||c-33?:printf("%d",n-2))s=s-768|32;}

Try it online!
Output the n for each valid line, exactly in the requirement(nothing if no valid line, the n if exactly one)
int s; // Use as a char[]
main(c){
  while(gets(&s)) {
    s=s-768|32; // byte 0: 'V'=>'v'; byte 1: 'r'=>'o', 'o'=>'l'
    if (sscanf(&s,"v%[o]m%c%c",&s,&c,&c)==2 && c=='!') {
    // The last '%c' get nothing if it's EndOfLine
      printf("%d",strlen(&s)-1))
    }
  }
}

It's so funny that the regex answer is longer than this

@WindmillCookies GCC need extra code to support regex

hmm. seems like names related to regexes are extremely long

Stax, 16 bytes
∞╠mQ╛3mQ->n▀÷↕┐ò

Run and debug it

Pyth, 28 bytes
IJjb.nm:rd0"^vro*m!$"1.z/J\o

Try it online!

Pyth, 20 bytes
/R\o:#"^Vro*m!$"1cQb

Outputs as a list containing only the number of 'o's, or an empty list if there's no Vroom.
Try it here
Explanation
/R\o:#"^Vro*m!$"1cQb
                 cQb  Split on newlines.
    :#"^Vro*m!$"1     Filter the ones that match the regex.
/R\o                  Count the `o`s in each remaining element.

C# (.NET Core), 134 122 bytes
for(var a="";a!=null;a=Console.ReadLine())if(new Regex(@"^[Vv]ro*m!$").Match(a).Success)Console.Write(a.Count(x=>x=='o'));

Try it online!
-12 bytes: moved null check into for loop and removed brackets
Ungolfed:
for(var a = ""; a != null; a = Console.ReadLine())  // initialize a, and while a isn't null, set to new line from console
    if(new Regex(@"^[Vv]ro*m!$")                        // set regex
                        .Match(a).Success)              // check if the line from the console matches
        Console.Write(a.Count(x => x == 'o'));              // write the number of 'o's to the console

-10 bytes with C# 6's null-coalescing and conditional operators, also unnecessary {} when using just one statement in the for loop: for(var a="";;a=Console.ReadLine())Console.WriteLine(new Regex(@"^[Vv]ro*m!$").Match(a??"").Success?a.Count(x =>x=='o'):-1);

Also, this needs using System.Linq; using System.Text.RegularExpressions;, not sure if this is important lol

The code you provided doesn't actually work, as it will not only output a -1 for every line that it doesn't work on, but it will output -1s forever as there is no check for null.

No, it won't. a = Console.ReadLine() makes the loop, so each time you're requesting input for the loop to go on, if there is no input, the loop is just waiting, not printing -1 forever

Proof of concept. Even if it did work as you said, a never-ending loop is not ideal behavior.
Regardless, I've moved the null check into the for loop, which removes the brackets (and makes the code shorter than your suggestion).

Pip, 21 bytes
a~,`^[Vv]r(o*)m!$`#$1

Try it online!
Match regex ^[Vv]r(o*)m!$ in multiline mode; output length of capture group.

C++, MSVC, 164 159 bytes
-5 bytes thanks to Zacharý
It compiles even with the regex header only
#include<regex>
using namespace std;int f(vector<string>i){smatch m;for(auto&e:i)if(regex_match(e,m,regex("^[Vv]ro*m!$")))return m[0].str().size()-4;return-1;}

Tests :
std::cout << "Vrom!" << " -> " << f({ "Vrom!" }) << '\n';
std::cout << "vrooooooom!" << " -> " << f({ "vrooooooom!" }) << '\n';
std::cout << "Hello, Vroom!" << " -> " << f({ "Hello, Vroom!" }) << '\n';
std::cout << "Foo bar boo baz \\n Vrooom! \\n hi" << " -> " << f({ "Foo bar boo baz", "Vrooom!", "hi" }) << '\n';
std::cout << "Vrm!ooo" << " -> " << f({ "Vrm!ooo" }) << '\n';
std::cout << "PPCG puzzlers pie" << " -> " << f({ "PPCG puzzlers pie" }) << '\n';
std::cout << "hallo \\n vROOOm!" << " -> " << f({ "hallo", "vROOOm!" }) << '\n';

I think using namespace std; would save a few bytes

sfk, 94 bytes
xex -i -case "_[lstart][char of Vv]r[chars of o]m![lend]_[part 4]o_" +linelen +calc "#text-1"

Try it online!
Gives -1 when you're not vrooming.

JavaScript, 90 73 61 bytes
_=>_.replace(/^[Vv]r(o*)m!$|[^\1]/mg,(m,a)=>a||'').length||-1

Try it online!
Replace characters that are not captured at (o*) with empty string, return length of string containing only "o" or -1 if resulting string is empty.

Ruby, 28 29 bytes
p$_[/^[vV]r(o*)m!$/].count ?o

Try it online!
Multi-line strings require three more bytes. I'm not sure if that's a hard requirement. If so, I'll update this.
->l{l[/^[Vv]r(o*)m!$/].count ?o}

How can you test multi-line strings?

Fail on VROM!

Red, 104 bytes
func[s][n:""if parse/case s[opt[thru"^/"]["V"|"v"]"r"copy n any"o""m!"opt["^/"to end]][print length? n]]

Try it online!
A straightforward solution. Red's parse is cool and readable, but too long compared to regex
Red []
f: func [ s ] [
    n: ""
    if parse/case s [
             opt [ thru newline ]
             [ "V" | "v" ]
             "r"
             copy n any "o"
             "m!"
             opt [ newline to end ]
    ] [ print length? n ]
]

J, 35  bytes
(]{~0<{.)(1{'^[Vv]r(o*)m!'rxmatch])

Returns negative 1 if the pattern doesn't match.

Ruby, 32 bytes
->n{n=~/^[Vv]r(o*)m!$/m;$1.size}

Matches the string to the regex, then uses Ruby's magic regex group variables to get the first group's size.
Call it like so:
x=->n{n=~/^[Vv]r(o*)m!$/m;$1.size}
x["Vrooooooooooooooooooooom!"] # returns 21

Clojure, 90 bytes
#(do(def a(clojure.string/replace % #"(?ms).*^[Vv]r(o*)m!$.*""$1"))(if(= a %)-1(count a)))

Try it online!
This anonymous function returns the number of "o"s in the vroom string, or -1 if there is no valid vroom string.
Readable version
(fn [s]
  (def a (clojure.string/replace s #"(?ms).*^[Vv]r(o*)m!$.*" "$1"))
  (if (= a s) -1 (count a)))

Explanation
#"(?ms).*^[Vv]r(o*)m!$.*" ; This regex matches any string that contains a valid vroom string. The first capturing group contains only the "o"s in the vroom string
(clojure.string/replace s #"(?ms).*^[Vv]r(o*)m!$.*" "$1") ; Replaces a match of the above regex with its first capturing group. The resulting string is stored in the variable a
(if (= a s) -1 (count a))) ; a equals s if and only if there is no valid vroom string, so if a equal s we return -1. If there is a valid vroom string, a contains only the "o"s from the vroom string, so we return the length of a

perl -nE, 35 bytes
$s=length$1if/^[Vv]r(o*)m!$/}{say$s

This uses the Eskimo greeting (}{) which abuses the a quick on how the -n option is dealt with by perl.

Java 8, 109 bytes
s->{int r=-1;for(var l:s.split("\n"))r=l.matches("[Vv]ro*m\\!")?l.replaceAll("[^o]","").length():r;return r;}

Try it online.
Explanation:
s->{                             // Method with String parameter and integer return-type
  int r=-1;                      //  Result-integer, starting at -1
  for(var l:s.split("\n"))       //  Loop over the lines:
    r=l.matches("[Vv]ro*m\\!")?  //   If the current line matches the regex:
       l.replaceAll("[^o]","").length()
                                 //    Change `r` to the amount of "o"'s in it
      :                          //   Else:
       r;                        //    Leave the result `r` unchanged
  return r;}                     //  Return the result

05AB1E, 39 37 bytes
|ʒć„VvsåsÁÁD…m!rÅ?s¦¦¦Ù'oså)P}Dgi`'o¢

Although 05AB1E is a golfing languages, regex-based challenges are definitely not its strong suite, since it has no regex-builtins.
Outputs [] if no match was found.
Try it online or verify all test cases.
Explanation:
|              # Get the input split by newlines
 ʒ             # Filter it by:
  ć            #  Head extracted: Pop and push the remainder and head-character
               #   i.e. "vrm!" → "rm!" and "v"
               #   i.e. "Vroaom!" → "roaom!" and "V"
   „Vvså       #  Is this head character in the string "Vv"?
               #   i.e. "v" → 1 (truthy)
               #   i.e. "V" → 1 (truthy)
  s            #  Swap so the remainder is at the top of the stack again
   ÁÁ          #  Rotate it twice to the right
               #   i.e. "rm!" → "m!r"
               #   i.e. "roaom!" → "m!roao"
     D         #  Duplicate it
      …m!rÅ?   #  Does the rotated remainder start with "m!r"?
               #   i.e. "m!r" → 1 (truthy)
               #   i.e. "m!roao" → 1 (truthy)
  s¦¦¦         #  Remove the first three characters from the duplicated rotated remainder
               #   i.e. "m!r" → ""
               #   i.e. "m!roao" → "oao"
      Ù        #  Uniquify, leaving only distinct characters
               #   i.e. "" → ""
               #   i.e. "oao" → "oa"
       'oså   '#  Is this uniquified string in the string "o"?
               #   i.e. "" → 1 (truthy)
               #   i.e. "oa" → 0 (falsey)
  )P           #  Check if all three checks above are truthy
               #   i.e. [1,1,1] → 1 (truthy)
               #   i.e. [1,1,0] → 0 (falsey)
 }             # Close the filter
  D            # After the filter, duplicate the list
   gi          # If its length is 1:
               #   i.e. ["vrm!"] → 1 (truthy)
               #   i.e. [] → 0 (falsey)
     `         #  Push the value in this list to the stack
               #   i.e. ["vrm!"] → "vrm!"
      'o¢     '#  And count the amount of "o" in it (and output implicitly)
               #   i.e. "vrm!" → 0
               # (Implicit else:)
               #  (Implicitly output the duplicated empty list)
               #   i.e. []

Kotlin, 55 bytes
{Regex("^[Vv]ro*m!\$").find(it)?.value?.count{it=='o'}}

Try it online!

16-bit x86 assembly code, 35 bytes

l1: lodsb          ;fetch a byte
    cbw            ;zero AH to allow returning 0
    cwd            ;zero counter
l2: and   al, 0dfh ;lower- to upper-case
    je    l4       ;exit if end of string
    cmp   al, 'V'
    jne   l1
    lodsb          ;fetch a byte
    cmp   al, 'r'
    jne   l2       ;if not 'r', branch to try 'v' or 'V' instead
l3: lodsb          ;fetch a byte
    test  al, al
    je    l4       ;exit if end of string
    inc   dx       ;speculatively count 'o's
    cmp   al, 'o'
    je    l3       ;loop while 'o'
    lodsw          ;fetch two bytes
    dec   si       ;align pointer as though only one byte fetched
                   ;in case of mismatch at the end
    cmp   ax, '!m' ;Intel backwards ordering
    jne   l2       ;loop while not matching complete string
    xchg  dx, ax   ;return count only if match
l4: ret
Accepts a pointer to the string in si, returns the count (or 0) in ax.

Can't tell vrm! from foo?


text:
The inverse Collatz Conjecture
I think the Collatz Conjecture is already well-known. But what if we invert the rules?
Start with an integer n >= 1.
Repeat the following steps:
If n is even, multiply it by 3 and add 1.
If n is odd, subtract 1 and divide it by 2.
Stop when it reaches 0
Print the iterated numbers.
Test cases:
 1        => 1, 0
 2        => 2, 7, 3, 1, 0
 3        => 3, 1, 0
10        => 10, 31, 15, 7, 3...
14        => 14, 43, 21, 10, ...

Rules:

This sequence does not work for a lot of numbers because it enters in an infinite loop. You do not need to handle those cases. Only printing the test cases above is enough.
I suggested to subtract 1 and divide by two to give a valid integer to continue, but it is not required to be computed that way. You may divide by 2 and cast to integer or whatever other methods that will give the expected output.
You need to print the initial input as well.
The output does not need to be formatted as the test cases. It was just a suggestion. However, the iterated order must be respected.
The smallest code wins.

As this is your third question in as many hours, I'd recommend that you check out the Sandbox, the place where we usually post question drafts for feedback, and to make sure they aren't duplicates.

Thank you @cairdcoinheringaahing. I didn't know about this page.

Do we have to print the 0 at the end?

You might want to expand the last two test cases, since they're not that long

@JoKing I compressed it because it repeats the output from the other lines. At the point you reach 3, it has the same output of when you start from it. The same applies for 10 or any other number.

@flawr it's optional.

Does it have to be in the same format as in the test cases?

@MilkyWay90: not same format, but they must be in decimal format, keep the ordering and have some kind of separator character that distinguishes the values.

Haskell, 40 39 bytes
f 0=[]
f n=n:f(cycle[3*n+1,div n 2]!!n)

Try it online!
Now without the final 0.

Perl 6, 30 bytes
{$_,{$_%2??$_+>1!!$_*3+1}...0}

Try it online!
Anonymous code block that returns a sequence.
Explanation:
{$_,{$_%2??$_+>1!!$_*3+1}...0}
{                            }   # Anonymous code block
   ,                     ...     # Define a sequence
 $_                              # That starts with the given value
    {                   }        # With each element being
     $_%2??     !!               # Is the previous element odd?
           $_+>1                 # Return the previous element bitshifted right by 1
                  $_*3+1         # Else the previous element multiplied by 3 plus 1
                            0    # Until the element is 0

Jelly, 9 bytes
:++‘ƊḂ?Ƭ2

Try it online!

Clean, 53 bytes
import StdEnv
$0=[0]
$n=[n: $if(isOdd n)(n/2)(n*3+1)]

Try it online!

Wolfram Language (Mathematica), 35 bytes
0<Echo@#&&#0[3#+1-(5#+3)/2#~Mod~2]&

Try it online!
0<Echo@# && ...& is short-circuit evaluation: it prints the input #, checks if it's positive, and if so, evaluates .... In this case, ... is #0[3#+1-(5#+3)/2#~Mod~2]; since #0 (the zeroth slot) is the function itself, this is a recursive call on 3#+1-(5#+3)/2#~Mod~2, which simplifies to 3#+1 when # is even, and (#-1)/2 when # is odd.

Rust, 65 64 bytes
|mut n|{while n>0{print!("{} ",n);n=if n&1>0{n>>1}else{n*3+1};}}

Try it online!

JAEL, 18 bytes
![ؼw>î?èÛ|õÀ

Try it online!

Your permalink doesn't seem to be working. The program just prints the input and halts.

Yes, you're right. I'll ask "them" to pull the latest version :P

I've added JAEL to the list of golfing languages. Please let me know if I got any information wrong :-)

@ETHproductions Thank you very much :D
I think I could say that the specialty is the utility package that helps the programmer to compress the code, but that's just me trying to merchandise it.

Python 2,  54 52 44 bytes
n=input()
while n:print n;n=(n*3+1,n/2)[n%2]

-2 bytes thanks to Mr. Xcoder
There must certainly be a faster way. Oddly, when I tried a lambda it was the same bytecount. I'm probably hallucinating.
Try it online!

-2 bytes

50 bytes

Though the 0 is now optional, so it's shorter to get rid of the second print

Indeed, now you can do it in 44

@Mr.Xcoder Cool, I was asleep lol

Haskell, 76 69 61 56 bytes
I feel like this is way too long. Here l produces an infinite list of the inverse-collatz sequence, and the anonymous function at the first line just cuts it off at the right place.
Thanks for -5 bytes @ØrjanJohansen!
fst.span(>0).l
l r=r:[last$3*k+1:[div k 2|odd k]|k<-l r]

Try it online!

There are no negative numbers, so (>0) should suffice. Also there's an odd function.

05AB1E, 15 14 bytes
[Ð=_#Èi3*>ë<2÷

-1 byte thanks to @MagicOctopusUrn.
Try it online.
Explanation:
[             # Start an infinite loop
 Ð            #  Duplicate the top value on the stack three times
              #  (Which will be the (implicit) input in the first iteration)
  =           #  Output it with trailing newline (without popping the value)
   _#         #  If it's exactly 0: stop the infinite loop
     Èi       #  If it's even:
       3*     #   Multiply by 3
         >    #   And add 1
      ë       #  Else:
       <      #   Subtract 1
        2÷    #   And integer-divide by 2

[Ð=_#Èi3*>ë<2÷ with = instead of D,.

@MagicOctopusUrn Ah, that was pretty bad to forgot.. Thanks! :)

Emojicode 0.5, 141 bytes
aa 10▶a 0a 2 1a➗a 2a➕✖a 3 1a 10

Try it online!

a       input integer variable 'a'
a 10       print input int
▶a 0       loop while number isn’t 0
a 2 1      if number is odd
a➗a 2        divide number by 2

       else
a➕✖a 3 1    multiply by 3 and add 1

a 10      print iteration

Thunno d, \$ 19 \log_{256}(96) \approx \$ 15.64 bytes
[zuZK!)2%?1-2,(3*1+

(No ATO link since this needs v1.2.2 and ATO is on v1.2.1)
Explanation
[zuZK!)2%?1-2,(3*1+  # Implicit input
[                    # Loop forever:
 zu                  #  Quadruplicate the value on the top of the stack
   ZK                #  Print with a trailing newline
     !)              #  If it's 0, break
       2%?           #  If it's odd:
          1-         #   Subtract one
            2,       #   And integer divide by two
              (      #  Else:
               3*    #   Multiply by three
                 1+  #   And add one
                     #  This value is on the top of the stack for the next iteration
                     # The d flag stops the implicit output at the end

Screenshot

Vyxal, 15 12 bytes
Thanks to @Steffan i learned more about Vyxal!
{…:|:∷[2ḭ|T›

Try it Online!
Naive approach for beginners:
{…:Ṡ|:₂[3*›|‹2/

12 bytes or alternative

Nibbles, 7.5 bytes
`.$?`%$~@+*3@~

Attempt This Online!
`. Iterate while unique
$   starting at input
?   if
`%   modulo (also save the quotient)
$     the number
~     2
@    then the quotient
+    else add
*3    multiply by 3
@      the number
~     1

Pyt, 15 bytes
`ĐĐ2%?ŕ₂:ŕ3*⁺;ł

Try it online!
`             ł        do... while top of stack is not 0; implicit print upon exiting loop
 ĐĐ                    duplicate top of stack twice (implicit input if empty)
   2%                  modulo 2
      ?ŕ₂              if top of stack is truthy, then pop from stack and divide next by 2
        :ŕ3*⁺          else: pop from stack and multiply next term by 3 and add 1
             ;         end if-then-else statement

Thunno 2, 12 bytes
(ß;DE?3×⁺:⁻½

Try it online!
Explanation
(ß;DE?3×⁺:⁻½  # implicit input
(             # while loop:
 ß            #   (condition)  print the number without popping
              #                and test if it's truthy (non-zero)
  ;D          #   (body)  duplicate the current integer
    E?        #           if it's even:
      3×      #             multiply it by 3
        ⁺     #             and then add one
         :    #           otherwise:
          ⁻   #             decrement it
           ½  #             and then halve it

JavaScript (ES6), 30 bytes
f=n=>n&&n+[,f(n&1?n>>1:n*3+1)]

Try it online!

Both order are 30

Add++, 38 35 33 bytes
D,f,@:,d3*1+$2/iA2%D
+?
O
Wx,$f>x

Try it online!
How it works
First, we begin by defining a function \$f(x)\$, that takes a single argument, performs the inverted Collatz operation on \$x\$ then outputs the result. That is,
$$f(x) = \begin{cases}
x \: \text{is even}, & 3x+1 \\
x \: \text{is odd}, & \lfloor\frac{x}{2}\rfloor
\end{cases}$$
When in function mode, Add++ uses a stack memory model, otherwise variables are used. When calculating \$f(x)\$, the stack initially looks like \$S = [x]\$.
We then duplicate this value (d), to yield \$S = [x, x]\$. We then yield the first possible option, \$3x + 1\$ (3*1+), swap the top two values, then calculate \$\lfloor\frac{x}{2}\rfloor\$, leaving \$S = [3x+1, \lfloor\frac{x}{2}\rfloor]\$.
Next, we push \$x\$ to \$S\$, and calculate the bit of \$x\$ i.e. \$x \: \% \: 2\$, where \$a \: \% \: b\$ denotes the remainder when dividing \$a\$ by \$b\$. This leaves us with \$S = [3x+1, \lfloor\frac{x}{2}\rfloor, (x \: \% \: 2)]\$. Finally, we use D to select the element at the index specified by \$(x \: \% \: 2)\$. If that's \$0\$, we return the first element i.e. \$3x+1\$, otherwise we return the second element, \$\lfloor\frac{x}{2}\rfloor\$.
That completes the definition of \$f(x)\$, however, we haven't yet put it into practice. The next three lines have switched from function mode into vanilla mode, where we operate on variables. To be more precise, in this program, we only operate on one variable, the active variable, represented by the letter x. However, x can be omitted from commands where it is obviously the other argument.
For example, +? is identical to x+?, and assigns the input to x, but as x is the active variable, it can be omitted. Next, we output x, then entire the while loop, which loops for as long as \$x \neq 0\$. The loop is very simple, consisting of a single statement: $f>x. All this does is run \$f(x)\$, then assign that to x, updating x on each iteration of the loop.

Just to understand: Is the break line part of the code? Or is it just for better explanation? I don't really know this language.

@EduardoHoefel Break line?

@cairdcoinheringaahing The newline characters, presumably.

Pyth, 12 bytes
.u?%N2/N2h*3

Try it here as a test suite!

Common Lisp, 79 bytes
(defun x(n)(cons n(if(= n 0)nil(if(=(mod n 2)0)(x(+(* n 3)1))(x(/(- n 1)2))))))

Try it online!

PowerShell, 53 52 bytes
param($i)for(;$i){$i;$i=(($i*3+1),($i-shr1))[$i%2]}0

Try it Online!
Edit:
-1 byte thanks to @mazzy

you can try for(;$i) instead while($i)

Stax, 11 bytes
₧↑╔¶┘tÇ╣;↑è

Run and debug it

R, 66 61 bytes
-5 bytes thanks to Robert S. in consolidating ifelse into if and removing brackets, and x!=0 to x>0
print(x<-scan());while(x>0)print(x<-`if`(x%%2,(x-1)/2,x*3+1))

instead of
print(x<-scan());while(x!=0){print(x<-ifelse(x%%2,(x-1)/2,x*3+1))}

Try it online!

61 bytes

MathGolf, 12 bytes
{o_¥¿½É3*)}∟

Try it online!
Explanation
{             Start block of arbitrary length
 o            Output the number
  _           Duplicate
   ¥          Modulo 2
    ¿         If-else with the next two blocks. Implicit blocks consist of 1 operator
     ½        Halve the number to integer (effectively subtracting 1 before)
      É       Start block of 3 bytes
       3*)    Multiply by 3 and add 1
          }∟  End block and make it do-while-true

I've added MathGolf to the list of golfing langs--feel free to correct me if I got anything wrong :-)

Thanks for adding it! Everything looks right to me.

x86 machine code, 39 bytes
00000000: 9150 6800 0000 00e8 fcff ffff 5958 a901  .Ph.........YX..
00000010: 0000 0074 04d1 e8eb 066a 035a f7e2 4009  ...t.....j.Z..@.
00000020: c075 dec3 2564 20                        .u..%d

Assembly (NASM syntax):
section .text
	global func
	extern printf
func:					;the function uses fastcall conventions
	xchg eax, ecx			;load function arg into eax
	loop:
		push eax
		push fmt
		call printf	;print eax
		pop ecx
		pop eax
		test eax, 1	;if even zf=1
		jz even		;if eax is even jmp to even
		odd:		;eax=eax/2
			shr eax, 1
			jmp skip
		even:		;eax=eax*3+1
			push 3
			pop edx
			mul edx
			inc eax
		skip:
		or eax, eax
		jne loop	;if eax!=0, keep looping
	ret			;return eax
section .data
	fmt db '%d '

Try it online!

Factor + math.extras, 56 bytes
[ [ .s dup odd? [ 1 - 2/ ] [ 3 * 1 + ] if ] until-zero ]

Try it online!
Explanation:

[ ... ] A quotation. An anonymous function that lives on the data stack until called or used by a combinator.
Assuming a data stack with 3 on top when this quotation is called...
[ .s dup odd? [ 1 - 2/ ] [ 3 * 1 + ] if ] Push a quotation to the data stack to be used later by until-zero. Stack: 3 [ .s dup odd? [ 1 - 2/ ] [ 3 * 1 + ] if ]
until-zero Call a quotation repeatedly until its output is 0. Stack: 3
.s Non-destructively print the data stack. Stack: 3
dup Duplicate TOS (top-of-stack). Stack: 3 3
odd? Return t if input is odd, else f. Stack: 3 t
[ 1 - 2/ ] Push a quotation to be used later by if. Stack: 3 t [ 1 - 2/ ]
[ 3 * 1 + ] Push another quotation to be used later by if. Stack: 3 t [ 1 - 2/ ] [ 3 * 1 + ]
if Takes a boolean and two quotations from the data stack. Calls the first quotation if the boolean is t, otherwise calls the second. (Now inside the first quotation...) Stack: 3
1 Push 1 to the data stack. Stack: 3 1
- Subtract TOS from NOS (next on stack). Stack: 2
2/ Integer divide by 2. Like doing x>>1 in many languages. Stack: 1
Now until-zero looks at the data stack and sees TOS is not 0, so calls its input quotation...

C (gcc), 75 bytes
#include<stdio.h>
int g(int x){printf("%d ",x);x?g(x=x%2?(x-1)/2:3*x+1):0;}

Try it online!

Building on @c-- 42 bytes

Nim, 65 50 bytes (-15 due to xigoi)
proc f(n:int)=
 echo n;if n>0:f [n*3+1,n/%2][n%%2]
Attempt This Online!
Simple recursive solution cum array-based due to xigoi.

-8 bytes: https://ato.pxeger.com/run?1=m704LzN3wYKlpSVpuhY3LQuK8pMV0jTyrDLzSjRtuRRSkzPyFfKsM9MU8uwMrNIUQAxVVSMgO09f1UghNac41SpPy1jbEGLA2rLEIoVEW0MDrjSNRE2IGMxwAA

Also, TIL about /% and %%, thanks!

Or even better, 50 bytes by using an array instead of the if expression: https://ato.pxeger.com/run?1=m704LzN3wYKlpSVpuhY3jQqK8pMV0jTyrDLzSjRtuRRSkzPyFfKsM9MU8uwMrNIUovO0jLUNdfL0VY1io_NUgSRE59qyxCKFRFtDA640jURNiBjMVAA

Nicely done! Edited to include.

K (ngn/k), 25 bytes
{x>0}{$[2!x;_x%2;1+3*x]}\

Try it online!

Pip, 29 bytes
YaWy{PyI%y{Y--y/2}EL{Yy*3+1}}

Attempt This Online!
Explanation
YaWy{PyI%y{Y--y/2}EL{Yy*3+1}}  # implicit input as a command line argument
Ya                             # store the argument in y
  Wy{                       }  # while y != 0:
     Py                        #  print y
       I%y{      }             #  if y is odd:
           Y                   #   store the following in y:
            --y/2              #    (y - 1) / 2
                  EL{      }   #  else:
                     Y         #   store the following in y:
                      y*3+1    #    y * 3 + 1

Nekomata, 11 bytes
ᶦ{Z:←½$3*→I

Attempt This Online!
ᶦ{Z:←½$3*→I
ᶦ{              Iterate until failure:
  Z                 Check if nonzero
   :                Duplicate
    ←               Decrement
     ½              Halve; fails if odd
      $             Swap
       3*           Multiply by 3
         →          Increment
          I         Choose the first value that doesn't fail

perl -Minteger -nlE, 39 bytes
{say;$_=$_%2?$_/2:3*$_+1 and redo}say 0

Retina 0.8.2, 46 bytes
.+
$*
{*M`1
^(..)+$
$&$&$&$&$&$&111
1(.*)\1
$1

Try it online! Explanation:
.+
$*

Convert to unary.
{

Repeat until the value stops changing.
*M`1

Print the value in decimal.
^(..)+$
$&$&$&$&$&$&111

If it is even, multiply by 6 and add 3.
1(.*)\1
$1

Subtract 1 and divide by 2.
The trailing newline can be suppressed by adding a ; before the {.

Red, 70 bytes
func[n][print n if n = 0[exit]either odd? n[f n - 1 / 2][f n * 3 + 1]]

Try it online!

Racket, 75 bytes
(define(f n)(cons n(if(= n 0)'()(if(odd? n)(f(/(- n 1)2))(f(+(* 3 n)1))))))

Try it online!
Equivalent to JRowan's Common Lisp solution.

C# (.NET Core), 62 bytes
a=>{for(;a>0;a=a%2<1?a*3+1:a/2)Console.Write(a+" ");return a;}

Try it online!
Ungolfed:
a => {
    for(; a > 0;                // until a equals 0
        a = a % 2 < 1 ?             // set a depending on if a is odd or even
                a * 3 + 1 :             // even
                a / 2                   // odd (minus one unnecessary because of int casting)
    )
        Console.Write(a + " "); // writes the current a to the console
    return a;                   // writes a to the console (always 0)
}

Dart, 49 bytes
f(n){for(;n>0;n=n%2>0?(n-1)>>1:(n*3)+1)print(n);}

Try it online!

Gambit Scheme (gsi), 74 bytes
(define(f n)(if(= 0 n)'()(cons n(f(if(even? n)(+ (* 3 n)1)(/(- n 1)2))))))

Try it online!

dc, 35 bytes
[3*1+]0:s[1-2/]1:s[pd2%;sxd0<l]dslx

Try it online!

Wolfram Language (Mathematica), 70 bytes
NestWhileList[If[EvenQ@#,3#+1,(#-1)/2]&,#,Unequal,All,\[Infinity],-1]&

Try it online!
Longer than previous WL, but with cycles detection.