text:
Product of digit runs
We seem to quite like digit runs lately, so here's a fairly simple challenge.
Given a positive integer, split it into it's digit runs, and return the product.
For example:
11122333 would become 111, 22, 333, the product of which is 813186
Input may be taken as an integer, string, or list/array of digits/characters. Your entry must work for any number within it's representable range. I have tested this for 32-bit integers (2^32-1 max value) and the largest possible result I have found is 1099999989 from 1199999999, which is also within the 32-bit integer range. I have yet to find a number who's output is larger than the input.
For the purposes of this challenge, runs of length 1 are not counted.
If there is only 1 run, return the run. If there are no runs, do anything (undefined behaviour)
Standard I/O rules apply, output can be given as an integer or string.
Testcases
11122333 -> 813186
1112333 -> 36963
1122855098 -> 13310
98776543 -> 77
1000000 -> 0
123456789 -> undefined
1 -> undefined
99445662 -> 287496
1199999999 -> 1099999989
999999999 -> 999999999

Scoring
This is code-golf so fewest bytes in each language wins!

"For the purposes of this challenge, runs of length 1 are not counted." This seems completely arbitrary.

can the input begin with a 0?

@Fatalize I won't argue with that, was mostly just a slight de-trivialization as otherwise I could see some languages simply doing [builtin to split into runs][builtin to get product of entire stack]

@FelipeNardiBatista No, an integer can't logically have leading zeroes.

@Mayube Adding arbitrary constraints to make a trivial challenge barely less trivial does not seem like a desirable thing to do to me.

Why are no runs undefined?  I'm not  really complaining, I don't think it matters much, but the product of the empty set is 1 in pretty much any definition of product.

@WheatWizard I prefer to leave "invalid" inputs as either undefined, or remove them completely, I like undefined behaviour for cases like this as it sometimes allows answers to have a lot more flexibility. (Although admittedly perhaps not so much in this particular case)

If the output was required to be undefined I would have had to increase my code by nearly an additional ⅔ {/(.)$0/??[*] .comb(/(.)$0+/)!!Mu} . Which would also make the code less clear.

Proof that the output never exceeds the input: it suffices to show that if two positive integers A and B are concatenated to form the integer C, then A*B<C. But if B has d digits, then B<10^d, and so C = A*10^d + B ≥ A*10^d > A*B.

@BradGilbertb2gills the output being undefined means your code can output anything you want, even exit with error

@FelipeNardiBatista Precisely. Many languages have a value which is referred to as being undefined. If there had to be a different result, it would take the place of the Mu; so a penalty of 11 bytes plus whatever it takes to encode the result.

Haskell, 63 55 bytes
Since no one has done Haskell yet here's my take on it.  Takes a string as input (of course).
import Data.List
f s=product[read x|x@(_:_:_)<-group s]

Try it online!
This code almost looks as if it is not golfed, but I cannot find anyway to make it shorter.

Your code fails on the test case f "1".  Expected output is undefined

@maple_shaft undefined does not mean they literally want undefined as the output, only that the behavior of the program is undefined.  1 is valid output for "1".

You can check the length condition in the pattern match, like this: x@(_:_:_)<-, and the numeric type of product is enough for the defaulting rule to apply, so you don't need the type annotation.

Japt, 10 8 bytes
Takes input as a string, outputs an integer or 1 for "undefined".
ò¦ fa_Ã×

Test it

2 bytes saved thanks to ETH

Does this multiply by 10 or something?

Incorrect output for 1112333, outputs 73926 when it should output 36963

@Mayube: Fixed now.

@EriktheOutgolfer; I'd missed the rule about ignoring runs of length 1.

I found a couple ways of dealing with that rule that only amount to 8 bytes: ò¦ fa_Ã× or ò¦ f>9 ×

@ETHproductions: D'oh! f>9 should have been obvious. Thanks :)

Actually, @ETHproductions, f>9 won't work as it will also remove runs of 0s.

ò¦ is such a cool trick.

05AB1E, 6 5 bytes
-1 byte thanks to Erik the Outgolfer
γ9ÝKP

Try it online!
If we don't need to ignore runs of length one, 2 bytes:
γP

Try it online!

Save a byte by using 9Ý instead of žhS.

@EriktheOutgolfer Ah! I knew there was a way to do it in 2 bytes.

JavaScript (ES6), 46 45 38 35 bytes
Takes input as a string, outputs an integer or throws an error for "undefined".
s=>eval(s.match(/(.)\1+/g).join`*`)

7 bytes saved thanks to Herman.
3 bytes saved thanks to Craig.

Try it

o.innerText=(f=
s=>eval(s.match(/(.)\1+/g).join`*`)
)(i.value="11122333");oninput=_=>o.innerText=f(i.value)
<input id=i><pre id=o>

-9 bytes: s=>s.replace(/(.)\1+/g,m=>n*=m,n=1)&&n (I haven't tested it yet)

Seems to do the job, thanks, @HermanLauenstein :) Was playing around to see if I could get it shorter using + instead of  * but hadn't got there yet.

Could you use eval to save a few bytes? s=>eval(s.match(/(.)\1+/g).join\*`)` - throws an error if no runs

Nice one, @CraigAyre. I was stupidly trying to see if I could save bytes by passing the replace through eval! Given the state of my golfing the past couple of days, it's a very good thing I have a holiday coming up tomorrow!

Jelly, 7 bytes
ŒgḊÐfḌP

Try it online!
-1 thanks to Leaky Nun.

7 bytes?

@LeakyNun Ooh clever trick...

Perl 5, 25 bytes
24 bytes + -p flag.
s/(.)\1+/$.*=$&/eg;$_=$.

Try it online!
Quite straight forward: (.)\1+ matches the runs of more than one digit, and $.*=$& uses $. as accumulator for the multiplications (because its initial value is 1 and not 0). Finally, $_ is set to $. and implicitly printed thanks to -p flag.

Perl 6, 21 bytes
{[*] .comb(/(.)$0+/)}

Test it
This returns 1 if there is no “digit runs” as that is the base case for multiplication.
The only change to allow one digit runs is to replace $0+ with $0* in the regular expression.
Expanded:
{            # bare block lambda with implicit parameter ｢$_｣

  [*]        # reduce the following using &infix:<*>

    .comb(   # pull out substrings that match the following
             # (implicit method call on ｢$_｣)

      /
        (.)  # any digit (character)
        $0+  # at least one more of that digit
      /
    )
}

Python 2, 95 79 bytes
-2 thanks to @LeakyNum
l='0'
p=1
for c in input()+' ':a=c in l;p*=int(l)**(len(l)>1>a);l=l*a+c
print p

Try it online!

[1,int(l)][len(l)>1] is equivalent to int(l)**(len(l)>1)

Would l='' instead of l='0' work?

no, the int(l) would throw an error if the string was empty

Retina, 47 bytes
(.)\1+
$*_
T`d
{`(?<=^(_+) _*)_
$1
}`^_+ _
_
_

This is slow on the larger test cases.
Try it online!
Explanation
(.)\1+
$*_

First, replace each run of 2 or more of the same digit with that many _s, followed by a space for separation.
T`d

Then remove all remaining digits.
{`(?<=^(_+) _*)_
$1
}`^_+ _
_

Next, run these two stages in a loop. The first replaces every _ in the second run with the entire first run, effectively multiplying them. The second stage deletes the first run.
_

Finally, output the number _s.

You can get this to 42 bytes by using the multiplication stage from Retinas wiki.

C (gcc), 93 89 bytes
There must be some more golfing to be done here...
z,r;f(char*d){for(z=0;r=*d++;z=r/10?z?z*r:r:z)for(r-=48;r%10==*d-48;r=r*10+*d++-48);d=z;}

Try it online!

Mathematica, 61 bytes
Times@@FromDigits/@Select[Split@IntegerDigits@#,Length@#>1&]&

Python 2, 69 bytes
lambda n:eval('*'.join(zip(*re.findall(r'((.)\2+)',n))[0]))
import re

Try it online!

PHP, 62 bytes
prints 1 if no run is found

preg_match_all('#(.)\1+#',$argn,$t);echo array_product($t[0]);

Try it online!

CJam, 18 Bytes
qe`{0=1>},{:*i}%:*

Try it Online
q           e# read string - '1112333'
e`          e# convert string to RLE - [[3,'1'],[1,'2'],[3,'3']]
{0=1>},     e# filter out runs of length one - [[3,'1'],[3,'3']]
{:*i}%      e# convert sub-arrays to runs - [111,333]
:*          e# multiply array elements - 36963

Ruby, 41 bytes
p eval gets.scan(/(.)\1+/).map(&:join)*?*

Takes input from stdin, scans it for runs of length > 1, joins them on "*", evaluates and prints.

Factor, 151 bytes
[ { } { } ] dip
[ 48 - 2dup swap in? [ suffix ] [ [ suffix ] dip 1array ] if ] each
suffix rest [ 0 swap [ swap 10 * + ] each ] map product

Getting a better grip on this language! Still don't think I'm using enough combinators...


text:
Abbreviate list of names until they fit
Given a list (array) of names, your challenge is to join the items using some glue and abbreviate the longest items first until the joined string fits a maximum length. And output that string. Since the glue is part of the final string, the length of the glue is included too
Abbreviation is done using the … character
Examples
For example when | is the glue and 20 is the maximum length

giraffe would become giraffe (length = 7)
giraffe, Spiny lumpsucker would become giraffe|Spiny lumps… (length = 20)
giraffe, Spiny lumpsucker, rhinoceros would become giraf…|Spiny…|rhino… (length = 20)
giraffe, Spiny lumpsucker, rhinoceros, Hellbender would become any of these:

gira…|Spi…|rhi…|Hel…
gir…|Spin…|rhi…|Hel…
gir…|Spi…|rhin…|Hel…
gir…|Spi…|rhi…|Hell… (all length = 20)

Rules
The list, glue and maximum length are input parameters of the program.
When abbreviation is needed, abbreviation must be done on any of the longest items first. When the longest items are equally long, it doesn't matter which you abbreviate.
The output length is smaller than the maximum length when no abbreviation was necessary. When abbreviation needs to occur, the length of the output is exactly equal to the maximum length.
The order of the (abbreviated) items must match the order of the items in the input
You can't assume that the abbreviation character … and the glue won't occur as characters in the items in the list.
Update
I'm afraid that I overlooked the fact that the length of the glue concatenated with many items by itself may result into a string that is longer than the allowed maximum length. Without considering this, your program may run into an infinite loop. I prefer your program to throw an error in this case. I hope that's not too much of an inconvenience for the ones who already wrote an answer or that are busy writing one. To throw an error is NOT a requirement to win, but I would appreciate if you add a variant that does.
The winner
This is code-golf, so the shortest valid answer – measured in bytes – wins.

Do we choose the glue, or is one given to us in input?

@Mayube the glue-string itself is input too

This is quite an interesting, 'planning to do it

@ChristiaanWesterbeek can we abbreviate more than necessary? I mean, can we output gir…|Spi…|rhi…|Hel… in your example 4?

@V.Courtois No. "When abbreviation needs to occur, the length of the output is exactly equal to the maximum length.". In your comment the output length is 19. It has to be 20 when that's the maximum length

@ChristiaanWesterbeek Thanks for clarifying.

Can we assume that the glue will never be in any of the array strings?

Can we assume that … won't be in any string?

To be clear would gir…|Spin…|rhi…|Hel…, gir…|Spi…|rhin…|Hel…, and gir…|Spi…|rhi…|Hell… complete the list of valid outputs in your last example?

@EriktheOutgolfer You can't assume that. For any means practical your glue and abbreviation characters may occur as values in the list when that list originates from a database fed by some other program that isn't doing proper input validation.

@JonathanAllan Yes

Jelly, 25 bytes
ṖṖ;⁽÷ẓỌµ€µL€MḢµ¦µj⁴L>⁵ð¿j

Try it online!
This unfortunately does not contain the error-if-invalid feature.
Explanation
This is what I call the Jelly syndrome: the easy part is explaining the algorithm, the hard part is explaining how you found the exact order to put the code in to make it execute correctly.
ṖṖ;⁽÷ẓỌµ€µL€MḢµ¦µj⁴L>⁵ð¿j
                       ¿     While
                 j           joining the input list
                  ⁴          with the glue produces a string
                   L         whose length
                    >        is larger than
                     ⁵       the maximum,
               ¦             in the input array at the
             Ḣ               first of the positions that
            M                have maximal
          L€                 length,
ṖṖ                           remove the last two characters,
  ;                          append
   ⁽÷ẓ                       the number 8230
      Ọ                      and cast it to a character.
                        j    Finally, join again with the glue.

It's a draw with the 05AB1E answer. What now?

@ChristiaanWesterbeek Whoever got that score first wins. I apparently posted my 25 character solution 3 minutes before Erik posted his.

05AB1E, 25 bytes
[Ð³ýDg²›≠#\Déθ©k®¨¨"…"«sǝ

Try it online!

It's a draw with the Jelly answer. What now?

@ChristiaanWesterbeek Jelly was first so it wins (look at revision histories not post dates).

JavaScript (ES6), 153 152 bytes
(a,g,n)=>eval(`while(a.join('')#>n-2*a#+1+a#==1){for(i=n;x=a.findIndex(w=>w#==i),i--&&!~x;);a[x]=a[x].slice(0,-2)+'…'}a.join(g)`.split`#`.join`.length`)

f=(a,g,n)=>eval(`while(a.join('')#>n-2*a#+1+a#==1){for(i=n;x=a.findIndex(w=>w#==i),i--&&!~x;);a[x]=a[x].slice(0,-2)+'…'}a.join(g)`.split`#`.join`.length`)
console.log(
  f(['giraffe'], '|', 7),
  f('giraffe, Spiny lumpsucker'.split`, `, '|', 20),
  f('giraffe, Spiny lumpsucker, rhinoceros'.split`, `, '|', 20),
  f('giraffe, Spiny lumpsucker, rhinoceros, Hellbender'.split`, `, '|', 20)
)

Python 3, 102 bytes
def f(l,n,g):
 while len(g.join(l))>n:i=l.index(max(l,key=len));l[i]=l[i][:-2]+'…'
 return g.join(l)

Try it online!
Alternatively if you want to see the result being shortened over time:
def f(l,n,g):
 while len(g.join(l))>n:i=l.index(max(l,key=len));l[i]=l[i][:-2]+'…';yield g.join(l)

JavaScript (ES6), 91 bytes
a=>n=>g=>f=(l=n,r=a.join(g))=>r[n]?f(l-!a.some((s,i)=>s[l]&&(a[i]=s.slice(0,-2)+'…'))):r

Uses currying i.e. F(A)(N)(G)(). Explanation: No string can have a length of more than n and still fit, so without loss of generality the overlong length l starts off at n. Each recursive call then checks whether the strings fit. If not, then the first overlong string found is trimmed, otherwise the overlong length is decremented when all strings have been trimmed to that length.

Cool. This is how I used it x=a=>n=>g=>f=(l=n,r=a.join(g))=>r[n]?f(l-!a.some((s,i)=>s[l]&&(a[i]=s.slice(0,-2)+'…'))):r and than x(['giraffe', 'Spiny lumpsucker'])(20)('|')(). Works. But x(['giraffe', 'Spiny lumpsucker'])(2)('|')() gives a Maximum call stack size error (because it wouldn't all fit in a string with a length of 2). But that's something I can catch.

source: Stack Exchange

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

sort: votes


text:
Find the Serialized Integer
Task
Write a program that will take (as input) a positive integer.  It will then count up from 0, appending each integer to a String, only continuing if the length of the String is less than the value of the input.
A serialized integer is defined as the fully-formed integer with the maximum value belonging to the String.  By "fully-formed", the integer should have no missing digits (which would occur if the length constraint of the String is met).
The output of the program should be the serialized integer for its respective, positive input.

Rules

It's code golf, so the shortest answer (in bytes) wins!
Input will always be positive.
The output must be an integer in base-10 (decimal).
The program must be 0-indexed.

Example Input | Output
   5 | 4   (0 1 2 3 4              - Length of 5)
  11 | 9   (0 1 2 3 4 5 6 7 8 9 1  - Length of 11)
  12 | 10  (0 1 2 3 4 5 6 7 8 9 10 - Length of 12)
1024 | 377 (0 1 2 3 4 5 6 7 8 ...  - Length of 1024)

Note(s)

If you have any questions (or would like me to provide more examples), please comment!
Inspiration: https://stackoverflow.com/questions/45034478/how-do-i-calculate-the-maximum-serialized-integers-in-1024-length-limit

suggested test case : 11

@Rod Added it, hopefully it makes it easier to understand!

Adding quote marks to the string in the examples might make it easier to understand that it's a string.

So the first N-1 digits of the Champernowne constant, with a 0 prepended?

JavaScript (ES6), 40 37 bytes

f=(n,i=s='0')=>(s+=++i)[n]?i-1:f(n,i)
<input type=number min=1 value=1 oninput=o.textContent=f(this.value)><pre id=o>0

Edit: Saved 3 bytes with some help from @Arnauld.

05AB1E, 10 7 bytes
Idea to use prefixes from Jonathan's Jelly answer
LηJ€g›O

Try it online!
Explanation
L         # range [1 ... input]
 η        # prefixes
  J       # join each to string
   €g     # get length of each string
     ›    # input is greater than string length
      O   # sum

Japt, 13 bytes
1n@P±X l >U}a

Test it online!
Explanation
1n@ P± X l >U}a
1nX{P+=X l >U}a
                   Implicit: U = input integer, P = empty string
  X{         }a    Return the first integer X in [0, 1, 2, ...] that returns a truthy value:
    P+=X             Append X to P.
         l >U        Return P.length > U.
                   This returns the first integer that can't fit into the U-char string.
1n                 Subtract 1 from the result.
                   Implicit: output result of last expression

Jelly,  11 10 9  5 bytes
ẈÄ<⁸S

A monadic link taking a positive integer and returning a non-negative integer.
Try it online!
How?
ẈÄ<⁸S - Link: positive integer, n
Ẉ     - length of (implicit decimal digits) of each of (implicit [1..n])
 Ä    - cumulative sums
   ⁸  - n
  <   - (cumulative sum) less than (n)?
    S - sum

Python 2, 55 bytes
Recursive lambda port from @officialaimm's answer.
f=lambda k,s='',i=1:k>len(s+`i`)and f(k,s+`i`,i+1)or~-i

Try it online!

Python 2, 60 59 58 bytes

Thanks @Felipe for 2 bytes

i,j,k='',1,input()
while len(i+`j`)<k:i+=`j`;j+=1
print~-j

Try it online!

Haskell, 55 53 50 bytes
(n#x)a|l<-a++show x=last$x-1:[n#l$x+1|length l<=n]

Try it online!
Usage is (1024#"") 0

PHP, 56 bytes
for(;$argn>$l=strlen($r);)$r.=+$i++;echo$i-1-($argn<$l);

Try it online!

Pyth, 8 7 bytes
tf<Q=+d

Try it online. Test suite.

I love it! Using slicing as a comparison is brilliant.

@isaacg It's one of the nice golf features of Pyth(on). I got the idea when I saw Neil's answer (indexing instead of slicing, but same idea). < num seq was also very helpful.

Perl 6, 36 bytes
{(0...^{([~] 0..$^a).comb>$_})[*-1]}

Try it online!

0 ...^ {...} is the sequence of numbers from zero until one less than the number for which the code block in braces returns true.  (... without the caret would return the first number for which the block returned true.)
[~] 0 .. $^a is the concatenation of numbers from 0 up to the current number $^a (the parameter to the code block).
.comb is a list of all of the characters (digits) in the concatenated string.  Interpreted as a number, it evaluates to the length of the string.  .chars would be more natural to use here, since it evaluates directly to the length of the string, but the name is one character longer.
$_ is the argument to the top-level function.
[*-1] selects the last element of the generated list.

J, 26 bytes
(>i:1:)([:+/\[:>.10^.1+i.)

((>i:1:)([:+/\[:>.10^.1+i.))"0 ] 5 11 12 1024 2000 20000 100000 1000000
4 9 10 377 702 5276 22221 185184

QBIC, 34 bytes
{A=!p$~_lB+A|>:|_xp-1|\B=B+A]p=p+1

Explanation
{           DO infinitely
A=!p$       Set A$ to p cast to num
            Note that p starts out as 0.
~      >:   IF the input number is exceeded by
 _l   |     the length of
   B+A      A$ and B$ combined
_xp-1|      THEN QUIT, printing the last int successfully added to B$
            The _X operator quits, (possibly) printing something if followed by a-zA-Z
            _x is slightly different, it prints the expression between the operator _x and |
\B=B+A      ELSE add A$ to B$
]           END IF
p=p+1       Raise p, and rerun

Python 2, 44 bytes
f=lambda k,i=0:-2*(k<0)or-~f(k-len(`i`),i+1)

Try it online!

R, 43 bytes
n=scan();sum(cumsum(floor(log10(1:n))+1)<n)

Try it online!

Husk, 8 bytes
#ȯ<¹ṁLŀḣ

Try it online!
About as hard as I could condense it. Pyth is really hard to beat here.

Hard to beat, but at least possible to match...

Husk, 7 bytes
#<¹∫mLḣ

Try it online!
How?
      ḣ    # range from 1..input;
    mL     # get the lengths of string representations of each element;
   ∫       # get the cumulative sums;
#          # how many of these
 <¹        # are less than the input?

Vyxal s, 5 bytes
ʁvL¦>

Try it Online!
ʁ     # 0...n
 vL   # Get length of each
   ¦  # Cumulative sums
    > # (input) is greater than each?
      # (s flag) sum ToS at end

K (ngn/k), 13 bytes
{(+\#'$!x)'x}

Try it online!
Takes input n as x.

(...)'x run a binary search (returning the index of the largest value equal to or smaller than x) on the list generated by...
(+\#'$!)

$!x stringify each value from 0..x-1
#' count the number of characters in each stringified number
+\ take the cumulative sums

WendyScript, 42 bytes
<<f=>(x){<<n=""#i:0->x{n+=i?n.size>=x/>i}}

f(1024) // returns 377

Try it online!
Ungolfed:
let f => (x) {
  let n = ""
  for i : 0->x {
    n+=i
    if n.size >= x
    ret i
  }
  ret
}

PHP, 41 bytes
while(strlen($s.=+$i++)<=$argn);echo$i-2;

Try it online.

Ruby, 44 bytes
Inspired by Kevin Cruijssen's JAVA answer. -4 bytes thanks to G B.
->n{i,t=0,'';t+="#{i+=1}"while t.size<n;i-1}

(i+=1;t+=i.to_s) is the same as t+="#{i+=1}", only 4 bytes longer

And if you do that, you don't need the variable t anymore, you can subtract the size from n and then compare with 0.

Ruby, 39 bytes
->n{~-(0..n).find{|x|0>n-="#{x}"=~/$/}}

Try it online!

Java 8, 64 bytes
n->{int i=0;for(String t="0";;t+=++i)if(t.length()>n)return~-i;}

Or slight alternatives with the same byte-count:
n->{int i=0;for(String t="";;t+=i++)if(t.length()>n)return i-2;}
n->{int i=-1;for(String t="";;t+=++i)if(t.length()>n)return~-i;}

Explanation:
Try it here.
n->{                  // Method with integer as both parameter and return-type
  int i=0;            //  Integer `i`, starting at 0
  for(String t="0";   //  String, starting at "0"
      ;               //  Loop indefinitely
       t+=++i)        //    After every iteration: append the String with `i+1`
                      //    by first increasing `i` by 1 with `++i`
    if(t.length()>n)  //   If the length of the String is larger than the input:
      return~-i;      //    Return `i-1`
                      //  End of loop (implicit / single-line body)
}                     // End of method

Perl 5, 31 + 1 (-p) = 32 bytes
$".=++$\while$_>=length$"}{$\--

Try it online!

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

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


text:
Cyclic strings, hidden programs
Write 3 programs that do the following task:
Let A, B, C source codes of those three programs;

if A runs BC is produced as output,
if B runs CA is produced,
if C runs AB is produced;

so each program writes a string (cycled for each program) and hides itself from it.
Additional, but essential constraints:

standard loopholes are forbidden;
each program must be at least 1 byte long;
each of three programs must be written in a different language;

It would be nice if your submission had this format:
Language A (size of A) - Language B (size of B) - Language C (size of C) - Score
A B C
<extra stuff>

Winner is someone who get the minimum score, which is the sum of sizes of three programs.

It would be nicer to have the score come last (to fit with the leaderboard script)

Related. Related.

I wouldn't recommend deadlines.

Any requirement about A, B and C being different strings? For example, can the three strings be the same? If the program prints a newline after the output, can we not count that?

It is not required A, B, C being different. Newlines are counted as part of output so newlines in the string are part of the program.

Maybe someone could pick up my work. I don't have time to finish :C Fission quine with payload (this one can't have symbols "UDRL in payload)

Ruby,Perl,Python mutual quines

Is there anything to stop all three programs from just being 1 in languages that automatically evaluate and print an expression, and ignore input that isn't referenced?

I revert the question to the original state since it misleads the original question. When I say  if A runs BC is produced as output I mean BC is catenation of B and C and A, B and C are strings.

Trivial solutions like lang A inputs 0 and outputs 00 and so on cyclically are possible but that sounds like taking advantage from that specific language hack.

Related

Does outputting nothing (empty string) count? Three empty programs

"each program must be at least 1 byte long." So no empty strings.

Befunge-98, Gol><> and Wumpus 47*3 = 141 bytes
"r75*1-47*0.@o&r84#o&]=74#]=\`/KHj '!_@#,k.'g00

Try it in Befunge!
Try it in ><>!
Try it in Wumpus!
That's right, it's the same program three times over! When run in any of the above languages, it prints the source code twice, which is the other two programs concatenated.
How It Works:
Befunge code:
  "r                               j '!_@#,k.'g00

  "   Wrapping string literal over code
   r  Reflect the pointer
  "   Wrapping string literal
                                              g00   Fetch " from cell 0,0
                                          ,k.'      Print 47 characters
                                       _@#          If the next character is 0, exit
                                      !             Otherwise, set it to 0
                                   j '              And jump back to the beginning

Gol><> code:
  "r75*1-47*0.                \`/KH

  "             Wrapping string literal
   r            Reverse stack
    75*1-       Push "
         47*0.  Jump to cell 28,0
                              \  Continue right
                               `/K   Duplicate the top 47 characters on the stack
                                  H  Halt and output stack contents

Wumpus code:
  "r75*1-47*0.@o&r84#o&]=74#]=\

  "r75*1-47*0.  Exact same function as the ><> code, but with a bouncing string literal
                              \  Reflect left
                            ]=   Push a copy of the " to the bottom of the stack
                         74#     Push 47
                       ]=        Push a copy of the 47 to the bottom of the stack
                     o&          Print the top 47 characters
                  84#            Push a '0' to make up for the missing 0 at the end
               o&r               Reverse the stack and print the top 47 characters
              @                  And terminate

JScript, VBScript, Windows Batch, 345 bytes
a=new ActiveXObject("scripting.filesystemobject");b=a.opentextfile(".js");c=b.readline();d=b.readline();a.createtextfile(".bat").write("@echo "+d.substr(2)+">.vbs\n@echo '"+c+">>.vbs")
//set a=createobject("scripting.filesystemobject"):set b=a.opentextfile(".vbs"):c=b.readline:d=b.readline:a.createtextfile(".js").write(mid(d,2)+chr(10)+"//"+c)
Name the file .js, then .vbs and then .bat will be created.


text:
Let's play Rummikub!
Note: This is related to a variation of the game Rummikub

Background & Rules
Rummikub is a tile-based game. There are four colors: red, orange, blue and black. For each color there are 13 tiles (labeled from 1 to 13), and there are also 2 Jokers which are color-independent, hence there are 54 pieces in total. In this variation of Rummikub, each player receives 14 tiles and must get one more tile and drop another one each round, such that the tile count is constant. The players don't see each other's tiles. The goal is to group the tiles, such that all pieces belong to at least one group (see below). When a player has all the pieces grouped, they drop their tile board and reveal their pieces. The others then check if all the combinations are valid, and if they are, the player wins the round.
How can the tiles be grouped?
There are only two types of groups:

Multi-color groups:

They consist of 3 or 4 tiles.
They only contain tiles with the same number on them.
All the tiles are of different colors.
Example: RED 9, BLUE 9, BLACK 9.

Mono-color groups:

They consist of at least 3 tiles.
They cannot contain more than 13 tiles.
They only contain tiles with different, consecutive numbers on them, in ascending order.
All the tiles have the same color.
Tiles labeled with 1 may not be places after tiles labeled 13.
Example: RED 5, RED 6, RED 7.

Wait, what do the Jokers do?
Jokers can substitue any piece in the game. For example, our first example can become  JOKER, BLUE 9, BLACK 9, RED 9, JOKER, BLACK 9 or RED 9, BLUE 9, JOKER. The same applies to our other example. However, one may not place two Jokers in the same group, so things like JOKER, ORANGE 8, JOKER are forbidden.

Task
Given a Rummikub tile group, determine whether it is valid. You are guaranteed that no duplicate tiles will appear, except for the 2 jokers and that the tiles you receive as input are valid (eg. things like 60 will not appear).
Input / Output
You may take input and provide the output by any standard method.
Some valid input formats: list of strings, list of tuples, nested lists, strings, or anything else you find suitable. The colors can be taken as Strings (e.g: "Blue","Red", etc.), as String abbreviations (please make Blue and Black tiles distinguishable), or as integers coresponding to a color. When it comes to Jokers, you should mention the way your program receives them as input. If you choose Strings, you may have something like RED 9, JOKER, ..., if you choose tuples you can have (9,"RED"), ("JOKER") or something equivalent. If it helps, you may receive a color for that Joker (which should not affect the output of your program). For example, you may have ("JOKER","RED") or ("JOKER","BLUE"), but that should not influence the output in any way.
Regarding the output, standard rules for a decision-problem apply.
Worked examples
Let's take an example, that would hopefully make it easier to understand. Given a group as follows, where each tuple represents a tile:

[(9, "RED"), (9, "ORANGE"), ("JOKER"), (9, "BLACK")]

This should return a truthy value, because the input is valid. In this case, the Joker substitutes (9, "BLUE"), and they form a multi-color group.
If you would be given the following group:

[(9, "BLUE"), (9, "ORANGE"), (9, "RED"), (9, "BLACK"), ("JOKER")]

It would be invalid, and thus you program should return a falsy value, because there is nothing left for the joker to substitute, because the maximum number of cards in a multi-color group is 4.
Additional Test Cases
These are for an extended test suite that cover nearly all possible situations:

Input -> Output

[(1,"BLUE"),(2,"BLUE"),(3,"BLUE"),(4,"BLUE"),(5,"BLUE"), (6,"BLUE")] -> truthy

[(6,"BLUE"),(6,"RED"),(6,"BLACK)] -> truthy

[(5,"BLACK"),(6,"BLACK"),(7,"BLACK"),(8,"BLACK"),(9,"BLACK"),(10,"BLACK"),("JOKER"),(12,"BLACK")] -> truthy

[("JOKER"),(3,"BLUE"),(3,"RED")] -> truthy

[(8,"BLACK"),(2,"RED"),(13,"BLUE")] -> falsy

[(4,"RED"), (3,"RED"), (5,"RED")] -> falsy

[(5,"BLACK"), (6, "BLACK)] -> falsy

[("JOKER"),(5,"RED"),("JOKER")] -> falsy

[(4,"RED"),(5,"RED"),(6, BLUE")] -> falsy

[(4,"RED"),("JOKER"),(5,"RED")] -> falsy

[(12,"BLACK"),(13,"BLACK),(1,"BLACK")] -> falsy

This is code-golf, so the shortest code in bytes in every language wins!

Related

Stealing is the best part of rummikub. Even without that this looks like a fun challenge.

Is [] a valid input?

@V.Courtois Of course.

@Mr.Xcoder Something else : is test case 8 supposed to mean having two jokers is totally forbidden? or can we have something like 2R,3R,J,4R,5R,J,6R?

@V.Courtois one may not place two Jokers in the same group, so two an input containing 2 Jokers is falsy.

@Mr.Xcoder sorry for asking ;) I couldn't find it again. Thanks.

I take it [(4,"RED"),("JOKER"),(5,"RED")] -> falsy is falsy due to the order, but the same tiles if they were arranged [(4,"RED"),(5,"RED"),("JOKER")] would be truthy?

@Draco18s If you arrange them like that they would indeed become truthy.

What are the desired results for the following: [1R, 1B, 2R, 2B, 3R, 3B], [1R, 1B, J, 3R, 3B], [1R, 1B, J, 3R, J, 3B], [1R, 2R, J, 1B, 2B, J], [1R, 1B, 1O, J, 3O, 4O, 5O],[6R, 6B, 6O, J, 3O, 4O, 5O],[6R, 6B, 6O, 3O, 4O, 5O]?

All falsy. Please note that you will only receive valid tiles, so things like 60 will not appear

@Mr.Xcoder it's not 60 but 6O for orange ;)

@V.Curtois Oh sorry: They are all all falsy anyway

Ok, thanks, that clears up a bit of uncertainty I had (and yes, 6O for Orange; used letters for brevity to fit within a comment, which is why Black wasn't used).

APL (Dyalog), 58 bytes
Takes list of colors (1-4) as right argument and list of numbers as left argument. A Joker's number is denoted (⍳4) which is equivalent to (1 2 3 4) to indicate that it could be any of those. Likewise, its color is denoted (⍳13) to indicate that it could be any of the numbers from 1 through 13.
{(3≤≢⍺)∧((s⍵)∧⍺≡∪⍺)∨((s←{1∊≢∘∪¨⊃,¨/⍵})⍺)∧∨/∊(⊃,¨/⍵)⍷¨⊂⍳13}

Try it online!
Algorithm
There are three conditions, of which the last two have two conditions each:

The run must have length greater than or equal to 3

AND EITHER

a single number AND
unique colors

OR

a single color AND
sequential numbers

in order for the run to be valid.
Reading order
 3≤ 3 is less than or equal to the ≢⍺ number of tiles
∧ and
   s⍵ all numbers are the same
  ∧ and
   ⍺≡∪⍺ the colors are unique
 ∨ or
   1∊ 1 is among ≢∘∪¨ the number of unique ⊃,¨/ expanded ⍺ colors
  ∧ and
   ∨/ there exists at least one ∊ among all ⊃,¨/⍵ expanded number runs ⍷¨⊂ one which is found in ⍳13 1 through 13
Full code explanation
{…} anonymous function where ⍺ is left argument and ⍵ is right argument
3.2.
 ⍳13 the numbers 1 through 13
 (…)⍷¨ find the starting positions of each of the following runs:
  ,¨/⍵ join each element of the numbers (creates a run for each Joker value)
  ⊃ disclose (because / reduces rank)
  ∊ ϵnlist (flatten)
 ∨/ OR reduction (i.e. are any true?)
 (…)∧ AND:
3.1
  (…)⍺ the result of applying the following function on the list of colors:
   s←{…} s (for same) which is the following anonymous function (⍵ is its argument):
    ,¨/⍵ join each element across (creates a run for each Joker value)
    ⊃ disclose (because / reduces rank)
    ≢∘∪¨ the the number of unique elements in each list
    1∊ is one a member? (i.e. are there any all-same lists?)
 (…)∨ OR:
2.2.
  ∪⍺ the unique colors
  ⍺≡ are identical to the colors (i.e. they are unique)
  (…)∧ AND:
2.1.
   s⍵ the numbers are all the same
  (…)∧ AND
1.
   ≢⍺ the number of colors (i.e. the number of tiles)
   3≤ three is less than or equal to that

Wow, it looks like APL is a great tool for this challenge

Python 2, 371 370 362 341 329 325 bytes

@Mr.Xcoder saved 1 byte: str.split() instead of list literal
8 bytes saved: shorthand for len(x)-1
19 bytes saved: J O BK B R for Joker, Orange, Black, Blue, Red literals
@Mr.Xcoder saved yet another 12 bytes, Thanks!!
Another 4 bytes thanks to @Mr.Xcoder

def f(x):
 j=sum("J"in i for i in x);z=len(x)-1
 if j>1or z<2:return False
 if j<1:return(all(i[0]==x[0][0]for i in x)and sum(i[1]==x[0][1]for i in x)<2)or(all(i[1]==x[0][1]for i in x)and sum(int(x[m+1][0])==int(x[m][0])+1for m in range(z))==z)
 return any(f([[k,(i+1,j)]["J"in k]for k in x])for j in'RBbO'for i in range(13))

Try it online!

370 bytes

You can replace BK with b to save 1 byte (TIO with test cases updated to b.

This actually saves far more bytes than I thought: 329.

325 bytes. Sorry for the very late improvement.

Jelly, 41 40 38 36 bytes
EȧI=1ȦȯE
0,W€yµZç/ɓQ⁼⁸ȧ
L>2ȧ4p13ðç€Ṁ

Try it online! (comes with a test-suite footer)
Takes input as an array of (color, value) for regular tiles and 0 for jokers. Colors are represented as integers (although I'm not sure if that even matters for the current code).
Outputs 1 (truthy) or 0 (falsy).
Explanation
L>2ȧ4p13ðç€Ṁ    Main link, checks if a sequence is valid. Args: sequence
L                 Get the length of the sequence.
 >2               Check if it's at least 3 tiles.
   ȧ4             And: yield 4 if it is, 0 otherwise.
     p13          Cartesian product: yield all possible tiles if
                  result was 4, empty array otherwise.
        ð         Begin a new dyadic chain with args (tiles, sequence).
         ç€       Call the first helper link for each tile with args (tile, sequence).

0,W€yµZç/ɓQ⁼⁸ȧ    First helper link, checks if a sequence is valid if jokers
                  are substituted for the given tile. Args: tile, sequence
0,                  Make a pair [0, tile].
  W€                Turn that into [[0], [tile]].
    y               Map all 0's (jokers) into tile in the sequence.
     µ              Begin a new monadic chain with args (sequence).
      Z             Transpose to get list [colors, values].
       ç/           Call the second helper link with args (colors, values).
         ɓ          Begin a new dyadic chain with args (sequence, valid).
          Q         Remove duplicate tiles from the sequence.
           ⁼⁸       Check if the sequence is unchanged (i.e. there were no duplicates).
             ȧ      And with the output of the second helper.

EȧI=1ȦȯE    Second helper link, checks if a sequence is valid assuming no duplicates.
            Args: colors, values
E             Check if all the colors are the same.
 ȧ            Logical and with the values array.
              Yields the values if they were, 0 if not.
  I           Find the differences between each value.
              Yields [] if the colors differed.
   =1         See if each difference is equal to 1.
              Yields [] if the colors differed.
     Ȧ        Check if the list was nonempty and all values were truthy.
              Yields 1 for valid mono-colors, 0 otherwise.
      ȯ       Logical or with the values array.
              Yields 1 for valid mono-colors, the values otherwise.
       E      Check if all the values are the same. For valid mono-colors
              this tests if all items of [1] are equal (obviously true).
              Yields 1 for valid sequences, 0 otherwise.

I think you have to output a consistent truthy/falsy.

@Adám Edited, fortunately didn't affect byte count.

Scala, 491 477 chars, 491 477 bytes
This challenge was fun; thanks.
var c=Seq("O","B","b","R")
t match{case _ if t.length<3=>false
case _ if t.exists(x=>x._1==0)=>{var b=false
if(t.filter(q=>q._1!=0).exists(q=>q._1==0))b else{for(y<-1 to 13)for(u<-c)b=b|f(t.takeWhile(q=>q._1!=0)++:(y,u)+:t.reverse.takeWhile(q=>q._1!=0).reverse)
b}}
case _::(x,_)::_ if t.forall(_._1==x)=>true
case _ if t.forall(_._2==c(0))|t.forall(_._2==c(1))|t.forall(_._2==c(2))|t.forall(_._2==c(3))=>(t(0)._1 to t(0)._1+t.length-1).toList equals t.map(_._1)
case _=>false}

So f at line 4 is a recursive call where I try replacing "JOKER" by every other tile. See tio for a clearer view of the code.
I chose taking as input a sequence of 2-tuples (Int,String) - called t in my code, see tio - so "JOKER" is represented by a 2-tuple (0,"JOKER").
EDIT : 14 bytes saved thanks to comments, I take O B b R for ORANGE BLACK BLUE RED.
Try It Online!
EDIT : -2 bytes, deleted useless ( around conditions of the case _ ifs

Can't you use O,B,b,R instead of ORANGE,BLUE,BLACK,RED to save bytes? I have no idea how Scala works, but I think you can.

I tried; in fact it saves bytes doing this way (a seq of strings). It does var (O,B,b,R)=("ORANGE","BLACK","BLUE","RED") and calls are O B b R, for a total of 49 bytes; where var c=Seq("ORANGE","BLACK","BLUE","RED") and calls c(...) totalize 58 bytes. BUT the first case permits for(u<-c) in place of for(u<-Seq(O,B,b,R)), so the cost is not -9 but +2. Thanks for trying though.

@V.Courtois I believe what Mr. Xcoder was suggesting is using var c=Seq("O","B","b","R") and taking those characters as your inputs rather than full strings for color. As mentioned in the original post, "The colors can be taken as ... String abbreviations".

ohh~ i see what you mean, thanks @ both of you

C# (.NET Core), 198 bytes
using System.Linq;(C,N)=>{int l=C.Length,j=C.Count(x=>x<1),c=C.Distinct().Count(),n=N.Distinct().Count(),u=N.Min();foreach(var x in N)u*=0<(u&x)?2:0;return l>2&((u>0&n==l&c<2+j)|(n<2+j&c==l&l<5));};

Takes in the colors of tiles and numbers on them as separate lists of integers. The specifics of that mapping don't matter as long as each color has a different integer and Jokers are represented as 0.
The format for inputting numbers is pretty special though. The number that needs to be input for a number n is instead 2^n, while the number used to represent a joker should be (2^14)-1. This enables the bitwise and u&x to evaluate to u if the tile x has value equal to u or is a joker.
C# (.NET Core), 200 bytes
using System.Linq;(C,N)=>{int l=C.Length,j=N.Count(x=>x<1),c=C.Distinct().Count(),n=N.Distinct().Count(),u=N.Min();foreach(var x in N)u=u==x|x<1?u+1:0;return l>2&((u>0&n==l&c<2+j)|(n<2+j&c==l&l<5));};

A 2 byte longer solution which isn't eclectic about input. Turns out just using a special case for jokers in the one place they were hard to deal with wasn't much longer than the clever bitwise operation I was so proud of. Here Jokers are (0,0), other numbers are as expected, and colors are represented any 4 values which are distinct from each other by C#'s default comparison (specifically, the Linq Distinct() operation must consider values for the same color as 'not distinct' and values for different colors as 'distinct').
Something which might be of use to other languages, u*=!u++^x*x would be equivalent to u=u==x|x<1?u+1:0 in some languages; u^x is 0 iff u==x, and 0 times any int is 0, so u^x*x would be 0 for either u==x or x==0 if C# didn't make bitwise operations lower precedence than mathematical ones. C# also can't interpret ints as bools without explicit casting. A language that tries harder to make types work might convert the values 0 and not 0 to false and true before applying ! to them though, and then when going back to an int interpret !false as 1 and !true as 0. All that said, I can't guarantee another language would actually benefit from the rest of the algorithm so it might not even come up.

Javascript (ES6), 286 bytes

var testcases = [[{n:1,c:"BLUE"},{n:2,c:"BLUE"},{n:3,c:"BLUE"},{n:4,c:"BLUE"},{n:5,c:"BLUE"}, {n:6,c:"BLUE"}],[{n:6,c:"BLUE"},{n:6,c:"RED"},{n:6,c:"BLACK"}],[{n:5,c:"BLACK"},{n:6,c:"BLACK"},{n:7,c:"BLACK"},{n:8,c:"BLACK"},{n:9,c:"BLACK"},{n:10,c:"BLACK"},{n:0,c:"JOKER"},{n:12,c:"BLACK"}],[{n:0,c:"JOKER"},{n:3,c:"BLUE"},{n:3,c:"RED"}],[{n:8,c:"BLACK"},{n:2,c:"RED"},{n:13,c:"BLUE"}],[{n:4,c:"RED"}, {n:3,c:"RED"}, {n:5,c:"RED"}],[{n:5,c:"BLACK"}, {n:6,c:"BLACK"}],[{n:0,c:"JOKER"},{n:5,c:"RED"},{n:0,c:"JOKER"}],[{n:4,c:"RED"},{n:5,c:"RED"},{n:6,c:"BLUE"}],[{n:4,c:"RED"},{n:0,c:"JOKER"},{n:5,c:"RED"}],[{n:12,c:"BLACK"},{n:13,c:"BLACK"},{n:1,c:"BLACK"}],[{n:11,c:"BLACK"},{n:12,c:"BLACK"},{n:0,c:"JOKER"}],[{n:1,c:"BLACK"},{n:2,c:"BLACK"},{n:3,c:"BLACK"},{n:1,c:"BLUE"},{n:2,c:"BLUE"},{n:3,c:"BLUE"}]];

g=a=>a.length
j=a=>a.n==0
l=(x,y)=>x.c==y.c||j(x)||j(y)
a=s=>g(s)>2&&([q=[0],x=s[0],s.map(y=>q[0]+=x==y||((l(x,y)||x.n==y.n)&&!(j(x)&&j(y)))&&(([n=s.indexOf(y),n<1||([x=s[n-1],!l(x,y)||y.n>0&&x.n<y.n])[1]||(n<g(s)-1&&x.n+1<s[n+1].n)||(n==g(s)-1&&y.n==0&&x.n<13)])[1])?1:0)])[0][0]==g(s)

testcases.forEach(H=>console.log(a(H)));

(Note that the test cases above contain 2 additional test cases that are not in the Question: they are true and false respectively: see the ungolfed version for readability).
Rough process:
 Using first tile x:
   For each tile y:
     count for x: can group with y
 return: x matches n tiles, where n is the number of tiles

Jokers are indicated by having a 0 as their numerical value (a negative number would work too); this keeps the input struct consistent (has both a Color and Value) and doesn't rely on having to check if c=="JOKER", saving 7 bytes.
Its possible that some parentheses could be removed, it might be possible to not box q as an array (I tried it and the value just either stayed 0 or caused nasal demons).
Ungolfed:

var testcases = [
[{n:1,c:"BLUE"},{n:2,c:"BLUE"},{n:3,c:"BLUE"},{n:4,c:"BLUE"},{n:5,c:"BLUE"}, {n:6,c:"BLUE"}],//true
[{n:6,c:"BLUE"},{n:6,c:"RED"},{n:6,c:"BLACK"}],//true
[{n:5,c:"BLACK"},{n:6,c:"BLACK"},{n:7,c:"BLACK"},{n:8,c:"BLACK"},{n:9,c:"BLACK"},{n:10,c:"BLACK"},{n:0,c:"JOKER"},{n:12,c:"BLACK"}],//true
[{n:0,c:"JOKER"},{n:3,c:"BLUE"},{n:3,c:"RED"}],//true
[{n:8,c:"BLACK"},{n:2,c:"RED"},{n:13,c:"BLUE"}],//false
[{n:4,c:"RED"}, {n:3,c:"RED"}, {n:5,c:"RED"}],//false
[{n:5,c:"BLACK"}, {n:6,c:"BLACK"}],//false
[{n:0,c:"JOKER"},{n:5,c:"RED"},{n:0,c:"JOKER"}],//false
[{n:4,c:"RED"},{n:5,c:"RED"},{n:6,c:"BLUE"}],//false
[{n:4,c:"RED"},{n:0,c:"JOKER"},{n:5,c:"RED"}],//false
[{n:12,c:"BLACK"},{n:13,c:"BLACK"},{n:1,c:"BLACK"}],//false
[{n:11,c:"BLACK"},{n:12,c:"BLACK"},{n:0,c:"JOKER"}],//true
[{n:1,c:"BLACK"},{n:2,c:"BLACK"},{n:3,c:"BLACK"},{n:1,c:"BLUE"},{n:2,c:"BLUE"},{n:3,c:"BLUE"}]
];

g=a=>a.length
i=(a,v)=>a.indexOf(v)
j=x=>x.n==0
m=(x,y)=>
       (l(x,y)||x.n==y.n)
    &&!(j(x)&&j(y))
l=(x,y)=>x.c==y.c||j(x)||j(y)
c=(a,v)=>([n=i(a,v),
      n<1
    ||([x=a[n-1],!l(x,v)||v.n>0&&x.n<v.n])[1]
    ||(n<g(a)-1&&x.n+1<a[n+1].n)
    ||(n==g(a)-1&&v.n==0&&x.n<13)])[1]
a=s=>g(s)>2&&([q=[0],x=s[0],s.map(y=>q[0]+=x==y||m(x,y)&&c(s,y)?1:0)])[0][0]==g(s)

testcases.forEach(H=>console.log(a(H)));

Version I worked on to get the logic correct. Single-use lambdas got in-lined; here's their corresponding function:
g() -> string.length
i() -> indexof
j() -> isJoker
m() -> do tiles match
l() -> do colors match
c() -> same-color isConsecutiveOrder
a() -> main lambda


text:
Distribute a number into a list of values as equal as possible whose sum is equal to that number
Probably a simple code-golf challenge. Given 2 positive integers m and n, make a list of n values that are positive integers whose sum is equal to the number m. Either all values in the output are the same value or the difference is exactly 1.
Examples
For example

m=6 and n=3 would become 2, 2, 2
m=7 and n=3 would become 2, 2, 3 or 2, 3, 2 or  3, 2, 2
m=7 and n=2 would become 3, 4 or 4, 3
m=7 and n=1 would become 7
m=7 and n=8 would generate an error because the sum of 8 positive integers cannot be 7.
m=10 and n=4 would become 3, 3, 2, 2 or any other permutation

Rules

Both input and output is only about positive integers.
Either all values in the output are the same value or the difference is exactly 1.
The order of the values in the list is not important.
The sum of the values in the list is equal to m.
When it's not solvable, generate an error or a false value (in case of m=7 and n=8 for example).
As a result of the other rules m=8 and n=3 would generate any of the permutations of 3, 3, 2 (not 2, 2, 4)

The winner
This is code-golf, so the shortest valid answer – measured in bytes – wins.

I'm assuming zero is not positive?

Indeed it is: https://en.wikipedia.org/wiki/Integer#Order-theoretic_properties

@TheLethalCoder Strictly speaking, zero is never positive.

@aras I'm no mathematician but from what I've read up it usually depends on context. Some say it is unsigned, some both positive and negative, some positive etc.

@TheLethalCoder meanwhile, in java (and floating point in general), float a = -0f, b = 0f;         System.out.println(a == b);         System.out.println(a + "," + b);... produces true and -0.0,0.0. See, positive 0 and negative 0 are clearly two distinct number... the implementation says so!

Suggested test case: m=8, n=3, which -- I think -- should be any permutation of 3,3,2 (not 2,2,4).

@Arnauld. It is something that can be derived from the other rules, but it might help to show your test case. I updated the question. Thanks

suggested testcase 10 4

@SocraticPhoenix https://softwareengineering.stackexchange.com/q/280648/92517

Gaia, 4 bytes
…÷l¦

There's almost just a built-in for this...
Explanation
…     Get the range [0 .. m-1].
 ÷    Split into n roughly even length chunks. Throws an error if the number of chunks if
       more than the list's length.
  l¦  Get the length of each chunk.

I thought there was a 4 byte solution too with 05AB1E. Now that it's gone, it makes it easier for me to decide. Congratulations and thanks!

Python 2, 48 43 bytes
Returns 0 on error.
lambda m,n:m/n and[m/n]*(n-m%n)+m%n*[m/n+1]

Try it online!

41 bytes (with @xnor's trick)
Throws NameError on error.
lambda m,n:[m/n or _]*(n-m%n)+m%n*[m/n+1]

Try it online!

MATL, 7 bytes
:gie!Xs

When there is no solution the output is an array containing at least one zero, which is falsy in MATL.
Try it online!
Explanation
Consider inputs m = 10 and n = 4.
:      % Implicitly input m. Push [1 2 ... m]
       % STACK: [1 2 3 4 5 6 7 8 9 10]
g      % Logical: convert nonzeros to 1
       % STACK: [1 1 1 1 1 1 1 1 1 1]
i      % Input n
       % STACK: [1 1 1 1 1 1 1 1 1 1], 4
e      % Reshape into matrix with n rows, padding with zeros
       % STACK: [1 1 1;
                 1 1 1;
                 1 1 0;
                 1 1 0]
!      % Transpose
       % STACK: [1 1 1 1;
                 1 1 1 1;
                 1 1 0 0]
Xs     % Sum of each column. Implicitly display
       % STACK: [3 3 2 2]

Mathematica, 33 bytes
#>#2&&Last@IntegerPartitions@##1&

input

[63, 11]

output

{6, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5}

outputs False when it's not solvable

Haskell, 30 bytes
m%n|m>=n=map(`div`n)[m..m+n-1]

Try it online!

Charcoal, 15 bytes after applying NDD1
¿÷ＮＮＩＥＩη÷⁺ＩθιＩη

Try it online!
Outputs nothing if there is no solution. Link to the verbose version.
1NDD = Neil-Driven Development.
My previous answer:
Charcoal, 32 27 24 20 bytes
ＮμＮν¿÷μνＩＥν⁺÷μν‹ι﹪μν

Try it online!
Outputs nothing if there is no solution. Link to the verbose version.
Of course, I couldn't have golfed it down without Neil's help.

Removing the Cast operator works for some reason, but this isn't an ideal algorithm... I have a 16-byte solution.

@Neil Challenge accepted!

I like the predefined variable, but now knowing that Cast works on lists I'm down to 11 bytes...

@Neil And I'm still unable to use Map, how on Earth does it work??

Map is like the expression version of for, down to using the same loop variable. So in your example, rather than pushing an expression to a list each time, Map automatically collects them up and evaluates to the list of results.

@Neil OK, I got Map working (thank you!), but it seems I will have to completely change the algorithm if I want to achieve 11 bytes...

Another tip for you is that Python usually casts booleans to 0 or 1 for you, so you don't need a ternary this time. As for the smarter way, some of the other answers do have a better calculation.

@Neil I think I've found your 11-byte solution: ＩＥＩη÷⁺ＩθιＩη, but this does not address the case when n > m that must generate an error or a falsy value. Even so, the result with a previous if is shorter than what I have accomplished so far, so... updating!

Ah, you're right, that's how I accidentally got down to 11. With the if I'm back up to 16 like I said in the first place. Sorry for the confusion.

@Neil found a 15-byte way to do it! :-)

Very clever! (I just double-checked and my 11 byte "solution" was in fact a rediscovery of my 16-byte solution but without the if. Oops!)

R, 33 bytes
function(m,n)diff(trunc(0:n*m/n))

A port of Luis Mendo's Octave answer. Pretty sad that this is almost 50% shorter than my previous answer.
Try it online!
previous answer, 63 bytes:
function(m,n,o=rep(m%/%n,n),d=m-sum(o))o+c(rep(0,n-d),rep(1,d))

An anonymous function that takes two (mandatory) arguments m and n, and two optional ones which are for golfing purposes. Returns a vector in increasing order. For failure, the first value will be 0, which is falsey in R, since if only uses the first value of the vector (with a warning).
It is essentially equivalent to the following function:
function(m,n){o=rep(m%/%n,n)
d=m-sum(o)
o+c(rep(0,n-d),rep(1,d))}

Try it online!

pryr::f(diff(trunc(0:n*m/n))) works and is shorter!

Jelly, 7 6 bytes
:ȧœsL€

Try it online! Outputs nothing for falsy.
How it works
:ȧœsL€    Main link. Arguments: m (integer), n (integer)
:         Integer division. Yields 0 if m < n; a positive integer otherwise.
 ȧ        Logical AND. Yields 0 if m < n; m otherwise.
  œs      Split into n roughly equal groups. Since the left argument is an integer,
          this implicitly converts it to [1..m] (or [] for 0) before splitting.
    L€    Length of €ach. If the inputs were 7 and 3, the previous result would be
          [[1,2,3],[4,5],[6,7]], so this would give [3,2,2].

Octave, 24 bytes
@(m,n)diff(fix(0:m/n:m))

The code defines an anonymous function. The output is a numeric array (row vector). When there is no this array contains at least one zero, which is falsy in Octave.
Try it online!
Explanation
0:m/n:m produces an array of n+1 values from 0 to m with step m/n. fix rounds each entry towards 0, and diff computes consecutive differences.
As an example, here are all intermediate results for m = 7, n = 3:
>> 0:m/n:m
ans =
         0    2.3333    4.6667    7.0000

>> fix(0:m/n:m)
ans =
     0     2     4     7

>> diff(fix(0:m/n:m))
ans =
     2     2     3

An array containing a zero is falsy. That seems like a stretch, but I'm don't know Octave either. Coming from Javascript with its coercions, I'd say why the hell not. +1 from me.

@ChristiaanWesterbeek Thanks! It does sound strange if you come from other languages, but that's how it is in MATLAB/Octave

C# (.NET Core), 86 82 71 bytes
using System.Linq;a=>b=>new int[b].Select((x,i)=>(i<a%b?1:0/(a/b))+a/b)

throws an error for invalid inputs.
Try it online!
-4 bytes thanks to TheLethalCoder
-11 bytes thanks to OlivierGrégoire

This is only a code snippet at the moment; you just need to wrap it in an anonymous function or a=>b=> at the start.

@TheLethalCoder Hmm are you sure? Don't I need to add the using System.Collections.Generic if I return an IEnumerable<int>?

I got that wrong anyway because you're returning an array (I misread the first part of the ternary). But only if that shows in your code and seeing as the IEnumerable<int> would be in the function definition you won't need to include the using.

No, Your tip is still good since the code without .ToArray() still compiles.

I don't do much C# (not at all actually), but it looks to me that this is shorter: a=>b=>new int[b].Select((x,i)=>(i<a%b?1:0/(a/b))+a/b) (53 bytes). I reused, some ideas from my Java answer.

@OlivierGrégoire, he said if not possible you need to output 0 , false or error and without the first part which throws error it will return an array like [0,0,0,0,0] which doesn't really conform to that.

@LiefdeWen have you tried running it? I get an error, not a zero-filled array: System.DivideByZeroException: Attempted to divide by zero. Seems good enough for me, doesn't it? The error happens in the second part!

@OlivierGrégoire You are right, sorry and thank you.

Haskell, 93 89 88 87 86 71 bytes
m!n|n<=m=e$m:(0<$[2..n])
e(a:b:x)|b<a=e$a-1:e(b+1:x)
e(a:x)=a:e x
e x=x

Try it online!
Explanation
The main function here is e.  e will take a list and essentially run a rolling pin along it from left to right.  While there is an element in the list that is greater than its neighbor to the right we will move one from it to the right.
Now all we have to do is feed this function a sufficiently lopsided list and allow it to do the magic.  The list we will choose is just m followed by n-1 zeros.  Since that is easy to make.
The last thing we need to do is make sure that the error case is handled.  For this we just throw a Non-exhaustive patterns in function error as long as m>n.

I think you can get rid of error[] by failing with a non-exhaustive pattern instead: m!n|m>n=e$m:replicate(n-1)0.

Also (0<$[1..n-1]) is shorter than replicate(n-1)0.

TI-Basic, 23 bytes
:Prompt M,N
:N(M≥N
:int(Ans⁻¹randIntNoRep(M,M+N-1

Returns ERR:DIVIDE BY 0 on error

Haskell, 48 bytes
m#n|m>=n=iterate(\(a:b)->b++[a+1])(0<$[1..n])!!m

Start with a list of n zeros. Repeat m times: take the first element, add one and put it at the end of the list.
Fails with a pattern match error if n < m.
Try it online!

Javascript (ES6), 57 56 53 41 bytes
m=>n=>m>=n&&[...Array(n)].map(_=>m++/n|0)

Answer now includes smarter way of creating the values. Thanks @Neil
Usage
f=m=>n=>m>=n&&[...Array(n)].map(_=>m++/n|0)

f(6)(3) // [2, 2, 2]
f(7)(3) // [3, 2, 2]
f(7)(2) // [4, 3]
f(7)(1) // [7]
f(7)(8) // false
f(8)(3) // [3, 3, 2]

History
First mine
(m,n)=>m>=n&&Array(n).fill(~~(m/n)).map((v,i)=>v+(i<m%n))

(m,n)=>m>=n&&Array(n).fill().map((v,i)=>~~(m/n)+(i<m%n))

Then added the spread operator and currying syntax tipped by @Arnauld
m=>n=>m>=n&&[...Array(n)].map((v,i)=>~~(m/n)+(i<m%n))

_=>m++/n|0 saves a bunch of bytes.

PHP>=7.1, 62 bytes
for([,$s,$n]=$argv;$n;)$s-=$r[]=$s/$n--^0;$r[0]?print_r($r):0;

PHP Sandbox Online

Clicked your link to the Sandbox, clicked Execute code and I got a Parse error.

@ChristiaanWesterbeek The sandbox defaults to PHP 7.0.3.

With other languages like Octave and MATL a zero in an array is considered falsy, but I don't believe this to be the case with php. I suppose the output has to be falsy within the rules of the language the program is written in.

@ChristiaanWesterbeek fixed

Braingolf, 30 bytes
.M>.M/v.mR>[.]$_v%!?[R1+>v]|R=

Try it online!
Takes inputs in reverse order (n is first input, m is second)
Divides m by n, duplicates the result n times, then loops through and increments one by one m % n times

Batch, 71 bytes
@if %1 geq %2 for /l %%i in (1,1,%2)do @cmd/cset/an=(%1+%%i-1)/%2&echo(

cmd/cset/a doesn't output any separator, so I have to use echo( (( avoids printing ECHO is on.).

Python 2, 41 bytes
lambda m,n:(m%n*[m/n+1]+[m/n or _]*n)[:n]

Try it online!
NameError when impossible.

Python 2, 43 bytes
lambda m,n:[c/n for c in range(m,m+n,m>=n)]

Try it online!
ValueError when impossible.

have never thought of using NameError to exit via error

Java (OpenJDK 8), 80 73 63 61 59 bytes
n->m->{for(int i=n;i-->0/(m/n);)System.out.println(m++/n);}

Try it online!
Note, for currying purpose, m and n are reversed.

Pyth, 11 bytes
efqlTeQ./hQ

Try it online!

Husk, 15 bytes
S`?ø▼Ẋ-mo÷³*⁰Θḣ

Try it online! A port of Luis Mendo's answer. Takes n followed by m as arguments. Outputs an empty list when no solution is possible.

Pyth, 13 bytes
KE?>KQ0lMcK*d

Try it online! Output 0 on error.
Cheating, 6 bytes
lMcE*d

Try it online! The array contains a 0 on error. Sadly this isn't falsy in Pyth.
Explanation
KE?>KQ0lMcK*dQ    # Implicit input Q for m
KE                # Store n in K
           *d     # Generate a string of length Q containing only spaces
         cK       # Chop this string in K pieces of equal sizes, initial piece longer if necessary
       lM         # For each string, compute the length. Here we already have our result. However if the array contain a zero, we must output a falsy value
  ?>KQ            # If K > Q...
      0           # Then display zero, otherwise display the array

CJam, 13 12 bytes
{_2$>/,/z:,}

Try it online!
This is an anonymous block that takes the input as n m on the stack. It would have been a good answer, but the error handling requirement completely killed it.
Errors with a divide-by-zero when it's not possible to solve.
Explanation
{   e# Stack:                | 3 10
 _  e# Duplicate:            | 3 10 10
 2$ e# Copy from back:       | 3 10 10 3
 >  e# Greater than:         | 3 10 1 (true)
 /  e# Divide:               | 3 10
    e# This will cause an error on invalid input.
 ,  e# Range:                | 3 [0 1 2 3 4 5 6 7 8 9]
 /  e# Split on nth element: | [[0 1 2] [3 4 5] [6 7 8] [9]]
 z  e# Transpose array:      | [[0 3 4 9] [1 4 7] [2 5 8]]
 :, e# Length of each:       | [4 3 3]
}

If the error-handling requirement is lifted, this can be shortened to 7 bytes, which is a decrease of over 40%:
{,/z:,}


text:
Yet Unused Pairs
Let's define a sequence of positive integers.  We will define the value of the sequence at every even index to be double the previous term.  The odd indices of the sequence will be smallest positive integer not yet appearing in the sequence.
Here are the first couple terms.
1,2,3,6,4,8,5,10,7,14,9,18,11,22,12,24,13,26,15,30

You can also think of this as the list of concatenated pairs (n,2n) where n is the least unused positive integer so far.
Task
Given a number n as input calculate the nth term in this sequence.
This is code-golf so you should aim to minimize the size of your source code as measured in bytes.
OEIS A036552

May we choose to use either 0- or 1-indexing?

@notjagan Sure go ahead.

The 2-adic valuation of odd elements of the series is always even. Might be useful to someone.

Haskell, 40 bytes
l(a:r)=a:2*a:l[x|x<-r,x/=2*a]
(l[1..]!!)

Zero-based. l incrementally builds the sequence from a lazy list of remaining integers.

JavaScript (ES6), 92 82 69 67 65 bytes
n=>(F=i=>i^n?F(a[b=i&1?2*b:(g=k=>a[k]?g(k+1):k)(1)]=-~i):b)(a={})

How?
We keep track of:

The last inserted value b.
All previously encountered values in the lookup table a.

Internally, we're using a 0-based index i. Odd and even behaviors are therefore inverted:

At odd positions, the next value is simply 2 * b.
At even positions, we use the recursive function g() and the lookup table a to identify the smallest matching value:
(g = k => a[k] ? g(k + 1) : k)(1)

To save a few bytes, i is initialized to {} rather than 0. This compels us to use:

i^n to compare i with n because ({}) ^ n === n whereas ({}) - n evaluates to NaN.
-~i to increment i, because ({}) + 1 would generate a string.

Demo

let f =

n=>(F=i=>i^n?F(a[b=i&1?2*b:(g=k=>a[k]?g(k+1):k)(1)]=-~i):b)(a={})

for(n = 1; n <= 20; n++) {
  console.log('a[' + n + '] = ' + f(n));
}

60 bytes

Python 3, 80 72 69 bytes
-7 bytes thanks to Mr. Xcoder!
f=lambda n:n and[f(n-1)*2,min({*range(n+1)}-{*map(f,range(n))})][n%2]

Try it online!

You can repace set(...) with `{*...} for 78 bytes

@Zacharý Were you reffering to my comment? If so, a set in Python 3 can be {*...} instead of set(...).

I was commenting without thinking, I realized a few moments later that {...for...in...} woould be more byes.

Actually, it would save 4 bytes, because you use it twice

69 bytes.  (and it doesn't use True for 1)

Why do you have an unnecessary space? 71 bytes, as an alternative to WheatWizard's suggestion above.

Jelly, 15 bytes
Jḟ⁸ḢðḤṭṭ
0Ç¡Ḋị@

Try it online!

PHP, 64 bytes
for(;$argn-$i++;)if($i&$$e=1)for(;${$e=++$n};);else$e*=2;echo$e;

Try it online!
PHP, 77 bytes
for(;$argn-$i++;$r[]=$e)if($i&1)for(;in_array($e=++$n,$r););else$e*=2;echo$e;

Try it online!
PHP, 78 bytes
for(;$argn-$i++;)$e=$r[]=$i&1?end(array_diff(range($i,1),$r?:[])):2*$e;echo$e;

Try it online!

R, 70 69 65 bytes
function(n){for(i in 2*1:n)F[i-1:0]=which(!1:n%in%F)[1]*1:2
F[n]}

Try it online!
An anonymous function that takes one argument. F defaults to FALSE or 0 so that the algorithm correctly assesses that no positive integers are in the sequence yet.
The algorithm generates the pairs in a for loop in the following manner (where i goes from 2 to 2n by 2):
           which(!1:n%in%l)[1]     # the missing value
                              *1:2 # keep one copy the same and double the next
l[i-1:0]=                         # store into l at the indices i-1 and i

Mathics, 56 53 bytes
-3 bytes thanks JungHwan Min!
(w={};Do[w~FreeQ~k&&(w=w~Join~{k,2k}),{k,#}];w[[#]])&

Try it online!
Based on the Mathematica expression given in the OEIS link.

Also 53 bytes: Nest[k=0;If[#~FreeQ~++k,#~Join~{k,2k},#]&,{},#][[#]]&

45 bytes in Mathematica since Mathics seems to handle empty Sequences (and maybe Set too?) differently.

PHP, 56 bytes
while($$n=$i++<$argn)for($n*=2;$i&$$k&&$n=++$k;);echo$n;

PHP, 75 72 bytes
for($a=range(1,$argn);$i++<$argn;)$a[~-$n=$i&1?min($a):2*$n]=INF;echo$n;

Try it online

Python 2, 59 51 49 bytes
f=lambda n,k=2:2/n%-3*(1-k)or f(n+~(k&-k)%-3,k+1)

Try it online!
Background
Every positive n integer can be expressed uniquely as n = 2o(n)c(n), where c(n) is odd.
Let ⟨an⟩n>0 be the sequence from the challenge spec.
We claim that, for all positive integers n, o(a2n-1) is even. Since o(a2n) = o(2a2n-1) = o(a2n-1) + 1, this is equivalent to claiming that o(a2n) is always odd.
Assume the claim is false and let 2m-1 be the first odd index of the sequence such that o(a2m-1) is odd. Note that this makes 2m be the first even index of the sequence such that o(a2m-1) is even.
o(a2m-1) is odd and 0 is even, so a2m-1 is divisible by 2. By definition,
a2m-1 is the smallest positive integer not yet appearing in the sequence, meaning that a2m-1/2 must have appeared before. Let k be the (first) index of a2m-1/2 in a.
Since o(ak) = o(a2m-1/2) = o(a2m-1) - 1 is even, the minimality of n implies that k is odd. In turn, this means that ak+1 = 2ak = a2m-1, contradicting the definition of a2m-1.
How it works
yet to come

05AB1E, 16 15 14 bytes
1-indexed.
Uses the fact that the binary representation of elements at odd indices in the sequence ends in an even number of zeroes: A003159.
Lʒb1¡`gÈ}€x¹<è

Try it online!
Explanation
L                 # range [1 ... input]
 ʒ      }         # filter, keep only elements whose
  b               # ... binary representation
   1¡             # ... split at 1's
     `gÈ          # ... ends in an even length run
         €x       # push a doubled copy of each element in place
           ¹<è    # get the element at index (input-1)

Haskell, 63 bytes
g x=[2*g(x-1),[a|a<-[1..],a`notElem`map g[1..x-1]]!!0]!!mod x 2

Try it online!
This one abuses Haskell's lazy evaluation to the fullest extent.

Perl 6, 50 bytes
{(1,{@_%2??2*@_[*-1]!!first *∉@_,1..*}...*)[$_]}

Try it online!

1, { ... } ... * is a lazily-generated infinite sequence where each term after the first is provided by the brace-delimited code block.  Since the block references the @_ array, it receives the entire current sequence in that array.
If the current number of elements is odd (@_ % 2), we're generating an even-indexed element, so the next element is double the last element we have so far: 2 * @_[*-1].
Otherwise, we get the first positive integer that does not yet appear in the sequence: first * ∉ @_, 1..*.
$_ is the argument to the outer function.  It indexes into the infinite sequence, giving the function's return value.

k, 27 bytes
*|{x,*(&^x?!y;|2*x)2!y}/!2+

1-indexed. Try it online!
Using (!y)^x instead of &^x?!y works too.

In oK you could even use y^x instead to save three bytes

Mathematica, 82 bytes
(s={};a=1;f=#;While[f>0,If[s~FreeQ~a,s~AppendTo~{a,2a}];a++;f--];Flatten[s][[#]])&

Try it online!

58 bytes in Mathematica (although I should probably just post a separate answer since the idea is pretty different).

Did you copy that from OEIS link?

I modified it to fit the task and to be golfed more, but it more or less is the same as the OEIS link.

@not post a new answer if you want and credit the author

C# (Visual C# Interactive Compiler), 82 bytes
x=>{int y=1;for(var s="";x>2;x-=2)for(s+=2*y+":";s.Contains(++y+""););return x*y;}

Try it online!
-6 bytes thanks to @ASCIIOnly!

C#8 may be too new to be common on online interpreters for now, added to the fact that csi is a Mono thing so you'd have to wait for Mono to implement it and add it to a stable build (if it hasn't already)

sadly it isn't easy to check for this in C#

Use this to start? But yeah, doesn't seem like a straightforward thing. https://docs.microsoft.com/en-us/dotnet/api/system.convert.tostring?redirectedfrom=MSDN&view=netframework-4.7.2#System_Convert_ToString_System_Int32_System_Int32_

86? - don't think the :s are needed since it will be the largest number in the list

Also 2.0 => 2f

83?

Let us continue this discussion in chat.

JavaScript, 51 bytes
After golfing this down, it pretty much turned into edc65's solution.
n=>(g=x=>g[++x]?g(x):(g[y=x*2]=--n)?--n?g(x):y:x)``

Try it online!

Clojure, 102 bytes
#(nth(loop[l[0 1 2 3]i %](if(= i 0)l(recur(conj l(*(last l)2)(nth(remove(set l)(range))0))(dec i))))%)

Iterates n times to build up the sequence and returns the nth item, 1-indexed.

Ruby, 60 bytes
->n,*a{eval"v+=1while a[v];a[v]=a[2*v]=v+v*n%=2;"*(n/2+v=1)}

0-indexed. We loop n/2+1 times, generating two values each time and storing them by populating an array at their indices. v+v*n%2 gives the output, either v or v*2 depending on the parity of n.

Jelly, 13 12 10 bytes
ḤRọ2ḂĠZFị@

This uses the observation from my Python answer.
Try it online!
How it works
ḤRọ2ḂĠZFị@  Main link. Argument: n

Ḥ           Unhalve; yield 2n.
 R          Range; yield [1, ... , 2n].
  ọ2        Compute the order of 2 in the factorization of each k in [1, ..., 2n].
    Ḃ       Bit; compute the parity of each order.
     G      Group the indices [1, ..., 2n] by the corresponding values.
      Z     Zip/transpose the resulting 2D array, interleaving the indices of 0
            with the indices of 1, as a list of pairs.
       F    Flatten. This yields a prefix of the sequence.
        ị@  Take the item at index n.

Ruby, 49 bytes
->n{*s=t=0;s|[t+=1]==s||s<<t<<t*2until s[n];s[n]}

Start with [0], add pairs to the array until we have at least n+1 elements, then take the n+1th (1-based)
Try it online!

JavaScript (ES6), 60 65 bytes
An iterative solution.
n=>eval("for(s={},i=0;n;)s[++i]?0:(s[i+i]=--n)?--n?0:i+i:i")

Less golfed
n=>{
  s = {}; //hashtable for used values
  for(i=0; n; )
  {
    if ( ! s[++i] )
    {
      s[i*2] = 1; // remember i*2 is already used
      if (--n)
        if (--n)
          0;
        else
          result = i*2;
      else
        result = i;
    }
  }
  return result;
}

Test

F=
n=>eval("for(s={},i=0;n;)s[++i]?0:(s[i+i]=--n)?--n?0:i+i:i")

for (a=1; a < 50; a++)
  console.log(a,F(a))

Husk, 18 bytes
!ṁSeDfȯ¬%2öL→x1ḋḣ¹

Try it online!
Same method as the 05AB1E solution from Emigna.
Both are 1-indexed.
Husk, 19 bytes
!!¡S+ȯSeD←S-ȯḣ→▲ḣ2¹

Try it online!
Uses infinite iteration to generate the sequence.
Explanation
!!¡S+ȯSeD←S-ȯḣ→▲ḣ2¹
                ḣ2  array [1,2]
  ¡                 apply function repeatedly on array, yielding intermediate results
   S                hook: S f g x = s f x (g x)
    +               f → list addition
     ȯ              g → compose 3: ȯ f g h x = f (g (h x))
      S                 f → hook: S f g x = s f x (g x)
       e                    f → list of two elements
        D                   g → number doubled
         ←              g → decrement
          S             h → hook: S f g x = s f x (g x)
           -                f → list subtraction
            ȯ               g → compose 3: ȯ f g h x = f (g (h x))
             ḣ                  f → range 1..n
              →                 g → increment
               ▲                h → maximum
                    altogether, this appends the first element of
                    1..max+1 not in the array,
                    and it's double.
 !                  take the nth result
!                   take the nth value

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


text:
Golfing Python string literals
Background
Python 3 has many types of string literals. For example, the string this 'is' an exa\\m/ple can be represented as:
'this \'is\' an exa\\\\m/ple'
"this 'is' an exa\\\\m/ple"
r"this 'is' an exa\\m/ple"
'''this 'is' an exa\\\\m/ple'''
"""this 'is' an exa\\\\m/ple"""
r'''this 'is' an exa\\m/ple'''
r"""this 'is' an exa\\m/ple"""

As you can see, using different delimiters for strings can lengthen or shorten strings by changing the escaping needed for certain characters. Some delimiters can't be used for all strings: r' is missing above (see later for explanation). Knowing your strings is very useful in code golf.
One can also combine multiple string literals into one:
'this \'is\' an ''''exa\\\\m/ple'''
"this 'is' an "r'exa\\m/ple'

Challenge
The challenge is, given a printable ASCII string, to output its shortest literal representation in Python.
Details on string mechanics
Strings can be delimited using ', ", ''' and """. A string ends when the starting delimiter is hit again unescaped.
If a string literal starts with ''' or """ it is consumed as the delimiter. Otherwise ' or " is used.
Characters can be escaped by placing a \ before them. This inserts the character in the string and eliminates any special meaning it may have. For example, in 'a \' b' the middle ' is escaped and thus doesn't end the literal, and the resulting string is a ' b.
Optionally, one of r or R may be inserted before the starting delimiter. If this is done, the escaping \ will appear in the result. For example, r'a \' b' evaluates to a \' b. This is why a ' b cannot be delimited by r'.
To escape ''' or """, one only needs to escape one of the characters.
These literals can be concatenated together, which concatenates their contents.
Rules

The input is the string to golf. Printable ASCII only, so no newlines or other special characters.
The output is the golfed string literal. If there are multiple solutions, output one.
To simplify the challenge, in non-r strings any escapes except for \\, \' and \" are considered invalid. They must not be used in the output, even though '\m' is equal to '\\m' in Python. This removes the need to process special escape codes such as \n.
Builtins for golfing Python strings are disallowed. Python's repr is allowed, since it's crappy anyway.
Standard code-golf rules apply.

Example inputs/outputs
I tried my best to verify these, but let me know if there are mistakes. If there are multiple valid outputs to the cases, they are all listed below the input.
test
 -> 'test'
 -> "test"
te\st
 -> 'te\\st'
 -> "te\\st"
 -> r'te\st'
 -> r"te\st"
te'st
 -> "te'st"
te"st
 -> 'te"st'
t"e"s't
 -> 't"e"s\'t'
te\'st
 -> "te\\'st"
 -> r'te\'st'
 -> r"te\'st"
te\'\"st
 -> r'te\'\"st'
 -> r"te\'\"st"
t"'e"'s"'t"'s"'t"'r"'i"'n"'g
 -> """t"'e"'s"'t"'s"'t"'r"'i"'n"'g"""
 -> '''t"'e"'s"'t"'s"'t"'r"'i"'n"'g'''
t"\e"\s"\t"\s'\t"\r"\i"\n"\g
 -> r"""t"\e"\s"\t"\s'\t"\r"\i"\n"\g"""
 -> r'''t"\e"\s"\t"\s'\t"\r"\i"\n"\g'''
t"""e"""s"""'''t'''s'''"""t"""r"""'''i'''n'''g
 -> 't"""e"""s"""'"'''t'''s'''"'"""t"""r"""'"'''i'''n'''g"
t\"""e\"""s\"""'''t'''s'''\"""t\"""r\"""'''i'''n'''g
 -> r"""t\"""e\"""s\"""'''t'''s'''\"""t\"""r\"""'''i'''n'''g"""
t"e"s"t"s"t"r"i"n"g"\'\'\'\'\'\'\'\
 -> r't"e"s"t"s"t"r"i"n"g"\'\'\'\'\'\'\'''\\'
 -> r't"e"s"t"s"t"r"i"n"g"\'\'\'\'\'\'\''"\\"
"""t"'e"'s"'t"'s"'t"'r"'i"'n"'g'''
 -> """\"""t"'e"'s"'t"'s"'t"'r"'i"'n"'g'''"""
 -> '''"""t"'e"'s"'t"'s"'t"'r"'i"'n"'g''\''''

Thanks to Anders Kaseorg for these additional cases:
\\'"\\'\
 -> "\\\\'\"\\\\'\\"
''"""''"""''
 -> '''''"""''"""'\''''

What about strings that starts or ends with " or ' ->  """t"'e"'s"'t"'s"'t"'r"'i"'n"'g'''

@Rod I'll add that as a test case.

Nice example of a good challenge with a language tag.

What about u' and b'?

@cairdcoinheringaahing They don't provide any useful features for golfing, and b can't even be combined with regular strings, so I just left them out.

If a String has multiple representations that are the shortest, should we choose one of them or output them all?

@Mr.Xcoder You should choose one.

Python 2 or Python 3?

@CalculatorFeline Python 3.

Also, this might be better if scored by length on a set of cases and then code size, and allowing suboptimality.

@CalculatorFeline I wanted to require optimality so that the results could even be useful in golfing. Also, since the optimal answers are somewhat easy to find, it would ultimately just reduce to this challenge.

+1 for "Python's repr is allowed, since it's crappy anyway." lol :P but nice challenge

r'''t"\e"\s"\t"\s"\t"\r"\i"\n"\g''' can be r't"\e"\s"\t"\s"\t"\r"\i"\n"\g'.

@CalculatorFeline Thanks, fixed the test case.

Python 3, 264 262 bytes
f=lambda s,b='\\',r=str.replace:min(sum([['r'+d+s+d,d+r(r(s[:-1],b,b+b),d,d[1:]+b+d[0])+b*(s[-1:]in[b,d[0]])+s[-1:]+d][d in r(r(s+d[1:],b+b,'x'),b+d[0],b)or r(s,b+b,'')[-1:]==b:]for d in["'",'"',"'''",'"""']],[f(s[:k])+f(s[k:])for k in range(1,len(s))]),key=len)

Try it online!
This works but is very slow without memoization, which you can add with
import functools
f=functools.lru_cache(None)(f)

It found an improved solution for one of the test cases:
t"e"s"t"s"t"r"i"n"g"\'\'\'\'\'\'\'\
 -> 't"e"s"t"s"t"r"i"n"g"'r"\'\'\'\'\'\'\'"'\\'
 -> r't"e"s"t"s"t"r"i"n"g"\'\'\'\'\'\'\'''\\'

Previous versions of this answer returned incorrect results on the following, which could be added as test cases:
\\'"\\'\
 -> "\\\\'\"\\\\'\\"
''"""''"""''
 -> '''''"""''"""'\''''

Nice work! Thanks for the test case, I've corrected it in the challenge.


text:
Factorize a Gaussian integer
A Gaussian integer is a complex number whose real and imaginary parts are integers.
Gaussian integers, like ordinary integers, can be represented as a product of Gaussian primes, in a unique manner. The challenge here is to calculate the prime constituents of a given Gaussian integer.
Input: a Gaussian integer, which is not equal to 0 and is not a unit (i.e. 1, -1, i and -i can not be given as inputs). Use any sensible format, for example:

4-5i
-5*j+4
(4,-5)

Output: a list of Gaussian integers, which are prime (i.e. no one of them can be represented as a product of two non-unit Gaussian integers), and whose product is equal to the input number. All numbers in the output list must be non-trivial, i.e. not 1, -1, i or -i. Any sensible output format can be used; it should not necessarily be the same as input format.
If the output list has more than 1 element, then several correct outputs are possible. For example, for input 9 the output can be [3, 3] or [-3, -3] or [3i, -3i] or [-3i, 3i].
Test cases, (taken from this table; 2 lines per test case)
2
1+i, 1-i

3i
3i

256
1+i,1+i,1+i,1+i,1+i,1+i,1+i,1+i,1+i,1+i,1+i,1+i,1+i,1+i,1+i,1+i

7+9i
1+i,2−i,3+2i

27+15i
1+i,3,7−2i

6840+585i
-1-2i, 1+4i, 2+i, 3, 3, 6+i, 6+i

Built-in functions for factoring Gaussian integers are not allowed. Factoring ordinary integers by built-in functions is allowed though.

Should 3i return as 3,i, or 3i?

3i is the correct answer because i is not a prime. I have updated the test case to make it clearer.

is -3-2j, 2-1j, -1-1j a correct answer for factorization of 7+9j ?

@mdahmoune they multiply to the correct number, so I don't see why not. The spec mentions several correct outputs are possible.

According to Wolfram Alpha, 6840+585i has the wrong list of factors, as 5 is not a Gaussian prime. Instead, it returns -1-2i, 1+4i, 2+i, 3, 3, 6+i, 6+i. Source

FYI, 256=(1+i)**16 not (1+i)**8 because 256=2**8=(2i)**8 and 2i=(1+i)**2

Jelly, 61 55 50 bytes
ÆiḤp/-,1p`¤×€×1,ıFs2S€⁸÷ÆiḞƑ$ƇỊÐḟ1;Ṫð,÷@\ḟ1
Ç€F$ÐL

Try it online! (Header and Footer formats the output)
-6 bytes thanks to @EricTheOutgolfer
-5 bytes thanks to @caird coinheringaahing
How it Works
ÆiḤp/-,1p`¤×€×1,ıFs2S€⁸÷ÆiḞƑ$ƇỊÐḟ1;Ṫð,÷@\ḟ1 - helper: outputs a factor pair of the input
ÆiḤp/                    - creates a list of possible factors a+bi, a,b>=0
      -,1p`¤×€           - extend to the other three quadrants
              ×1,ıFs2S€  - convert to  actual complex numbers
⁸÷                       - get quotient with input complex number
  ÆiḞƑ$Ƈ                    - keep only Gaussian numbers (those unchanged when complex parts are floored)
     ỊÐḟ                 - remove units (i,-i,1,-1)
        1;               - append a 1 to deal with primes having no non-unit factors
          Ṫð,÷@\         - convert to a factor pair
                ḟ1       - remove 1s
Ç€F$ÐL
Ç€      - factor each number
   $    - and
  F     - flatten the list
    ÐL  - until factoring each number and flattening does not change the list

You can get 6 bytes down...and golf your header and footer by much too!

when this says "keep only Gaussian" does it mean "keep only Primes"?

@donbright no, it refers to keeping only those complex numbers with integer real and complex components

@fireflame241 oh i see now! thank you very much

-5 bytes with the newer version of Jelly

@cairdcoinheringaahing edited

Ruby, 258 256 249 246+8 = 264 257 254 bytes
Uses the -rprime flag.
Geez, what a mess.
Uses this algorithm from stackoverflow.
->c{m=->x,y{x-y*eval("%d+%di"%(x/y).rect)};a=c.abs2.prime_division.flat_map{|b,e|b%4<2?(1..e).map{k=(2..d=b).find{|n|n**(~-b/2)%b==b-1}**(~-b/4)%b+1i;d,k=k,m[d,k]while k!=0;c/=d=m[c,d]==0?d:d.conj;d}:(c/=b<3?(b=1+1i)**e:b**e/=2;[b]*e)};a[0]*=c;a}

Try it online!

Python 2, 250 239 223 215 bytes
e,i,w=complex,int,abs
def f(*Z):
 if Z:
	z=Z[0];q=i(w(z));Q=4*q*q
	while Q>0:
 	 a=Q/q-q;b=Q%q-q;x=e(a,b)
 	 if w(x)>1:
		y=z/x
		if w(y)>1 and y==e(i(y.real),i(y.imag)):f(x,y);z=Q=0
 	 Q-=1
	if z:print z
	f(*Z[1:])

Try it online!

-11 bytes when using Multiple Function Arguments
-2²*² bytes when using one variable to parse couples (a,b)
-2³ bytes when mixing tabs and spaces: thanks to ovs

Some explanation recursively decompose a complex to two complexes until no decomposition is possible...

Well, it times out in TIO on larger inputs, but it's shorter than my Ruby answer... for now. Also, def f(Z,s=[]) should save you a character

@ValueInk yes it's slower than your ruby solution

Interesting pattern with the indentation...

@ValueInk Multiple Function Arguments saves more bytes :)

You can probably replace and with binary and (&) here. That will be 4 bytes.

You can reduce your byte count by mixing tabs and spaces

@ovs beautiful :)

Rust - 212 bytes
use num::complex::Complex as C;fn f(a:&mut Vec<C<i64>>){for _ in 0..2{for x in -999..0{for y in 1..999{for i in 0..a.len(){let b=C::new(x,y);if(a[i]%b).norm_sqr()==0&&(a[i]/b).norm_sqr()>1{a[i]/=b;a.push(b)}}}}}}

I'm not 100% sure if this works 100% correct, but it seems to be correct for a large range of tests. This isn't smaller than Jelly, but at least it is smaller than the interpreted languages (so far). It also seems to be faster and can work through inputs of a billion magnitude in less than a second. For example 1234567890+3141592650i factors as (-9487+7990i)(-1+-1i)(-395+336i)(2+-1i)(1+1i)(3+0i)(3+0i)(4+1i)(-1+1i)(-1+2i), (click here to test on wolfram alpha)
This started out as the same idea as naive factoring of integers, to go through each number below the integer in question, see if it divides, repeat until done. Then, inspired by other answers, it morphed... it repeatedly factors items in a vector. It does this a good number of times, but not 'until' anything. The number of iterations has been chosen to cover a good chunk of reasonable inputs.
It still uses "(a mod b) == 0" to test whether one integer divides another (for Gaussians, we use builtin Rust gaussian modulo, and consider "0" as norm == 0), however the check for 'norm(a/b) != 1' prevents dividing "too much", basically allowing the resulting vector to be filled with only primes, but not taking any element of the vector down to unity (0-i,0+i,-1+0i,1+0i) (which is prohibited by the question).
The for-loop limits were found through experiment. y goes from 1 up to prevent divide-by-zero panics, and x can go from -999 to 0 thanks to the mirroring of Gaussians over the quadrants (I think?). As regarding the limitations, the original question did not indicate a valid range of input/output, so a "reasonable input size" is assumed... (Edit... however i am not exactly sure how to calculate at which number this will begin to "fail", i imagine there are Gaussian integers that are not divisible by anything below 999 but are still surprisingly small to me)
Try the somewhat ungolfed version on play.rust-lang.org

Perl 6, 141 124 bytes
Thanks to Jo King for -17 bytes
sub f($_){{$!=0+|sqrt .abs²-$^a²;{($!=$_/my \w=$^b+$a*i)==$!.floor&&.abs>w.abs>1>return f w&$!}for -$!..$!}for ^.abs;.say}

Try it online!

how does this work? is the floor a custom built modulo?

@donbright The floor part is checking if $_/w (i.e. the current factor divided by a number) is a whole number

Pyth, 54 51 45 42 36 bytes
 .W>H1cZ
h+.aDf!%cZT1>#1.jM^s_BM.aZ2

Try it online!
Accepts input in the form 1+2j - purely real or imaginary numbers can omit the other component (e.g. 9, 2j). Output is a newline-separated list of complex numbers, in the form (1+2j), with purely imaginary numbers omitting the real part.
This uses simple trail division, generating all gaussian integers with magnitude greater than 1 and less than the current value, plus the value itself. These are filtered to keep those that are a factor of the value, and the smallest by magnitude is chosen as the next prime factor. This is output, and the value is divided by it to produce the value for the next iteration.
Also, Pyth beating Jelly  (I don't expect it to last though)
 .W>H1cZ¶h+.aDf!%cZT1>#1.jM^s_BM.aZ2ZQ   Implicit: Q=eval(input())
                                         Newline replaced with ¶, trailing ZQ inferred
 .W                                  Q   While <condition>, execute <inner>, with starting value Q
   >H1                                   Condition function, input H
   >H1                                     Is magnitude of H > 1?
                                           This ensures loop continues until H is a unit, i.e. 1, -1, j, or -j)
      cZ¶h+.aDf!%cZT1>#1.jM^s_BM.aZ2Z    Inner function, input Z
                                .aZ        Take magnitude of Z

                             _BM           Pair each number in 0-indexed range with its negation
                            s              Flatten
                           ^       2       Cartesian product of the above with itself
                        .jM                Convert each pair to a complex number
                      #                    Filter the above to keep those element where...
                     > 1                   ... the magnitude is greater than 1 (removes units)
              f                            Filter the above, as T, to keep where:
                 cZT                         Divide Z by T
                %   1                        Mod real and imaginary parts by 1 separately
                                             If result of division is a gaussian integer, the mod will give (0+0j)
               !                             Logical NOT - maps (0+0j) to true, all else to false
                                           Result of filter are those gaussian integers which evenly divide Z
           .aD                             Sort the above by their magnitudes
          +                         Z      Append Z - if Z is ±1±1j, the filtered list will be empty
         h                                 Take first element, i.e. smallest factor
        ¶                                  Print with a newline
      cZ                                   Divide Z by that factor - this is new input for next iteration
                                         Output of the while loop is always 1 (or -1, j, or -j) - leading space suppesses output

this is very interesting but it appears to timeout on 6840+585j

@donbright It does on TIO, as it has a processing limit of 60s. It will work with more time, so if you are running it locally it should work without issue.


text:
Cap the highest values in a list so that the sum equals a given number
A slightly more challenging one compared to my previous challenge. Given a list of positive integers (>0) and the positive integer m, output a list of positive integers that are capped values of the input values so that the sum of the capped values equals m. Cap the highest values first. And keep the same order.
Cases
(Given 'list' and 'sum' output 'list')

Given 4, 2 and 6 output 4, 2 no capping needed (ncn), keep order (ko)
Given 2, 4 and 6 output 2, 4 ncn, ko
Given 3, 3 and 6 output 3, 3 ncn
Given 3, 3 and 7 output 3, 3 ncn

Then this:

Given 4, 2 and 5 output 3, 2 cap the highest (cth), ko
Given 2, 4 and 5 output 2, 3 cth, ko
Given 3, 3 and 5 output 3, 2 or 2, 3 cap any of the highest (cath)

Then this:

Given 5, 4, 2 and 10 output 4, 4, 2 cth, ko
Given 2, 4, 5 and 10 output 2, 4, 4 cth, ko
Given 4, 4, 2 and 7 output 3, 2, 2 or 2, 3, 2 cth, cath, ko
Given 4, 2, 4 and 7 output 3, 2, 2 or 2, 2, 3 cth, cath, ko

Then this:

Given 4, 4, 2 and 5 output 2, 2, 1 or any permutation (oap)
Given 2, 4, 4 and 5 output 1, 2, 2 oap
Given 4, 4, 2 and 4 output 1, 2, 1 oap
Given 2, 4, 4 and 4 output 1, 1, 2 oap
Given 70, 80, 90 and 10 output 3, 3, 4 oap

Then this:

Given 4, 2, 4 and 2 output an error or a falsy value, because the sum of 3 positive integers cannot be 2.

Rules

Both input and output are all about positive integers (>0)
The number of values in the input and output list are equal.
The sum of the output values is exactly equal to m or less than m only if the sum of the input values was already lower.
If the sum of the values in the input list is already lower then or equal to m, no capping is needed. (ncn)
Cap the highest values first (cth)
When multiple values are the highest value and equally high, it doesn't matter which you cap. (cath)
The capped values in the output list have to be in the same order as their original values in the input list. (ko)
When at some point (thinking iteratively) all values are equally high, it stops being important which you cap.
If there's no solution output an error or a falsy value.

The winner
The shortest valid answer - measured in bytes - wins.
Apart form the rules, I'm interested to see a program that keeps a value intact as long as possible. Consider the input values a plant each with the heights 10,2,10 and the maximum m=5, it would be a waste to cap the baby plant in the middle.

-1 for "no recursion". It makes this difficult if not impossible for many languages (not just esolangs), it's an ambiguous and unobservable requirement and I don't think it adds anything to the challenge.

What are the allowable answers to 3, 2 and 3?

Could you add a test case for when m is greater than the total?

Could you also explain the rules more clearly? I cant quite understand the ko rule - in the 4,4,2 and 5 case are you capping the 2 to 1 or are you capping one of the 4s to a 1 and then rearranging the items to match the input in some way? (note that if it is done iteratively we reach 2,2,2 at which point we can cath and yield 1,2,2 following all the other rules).

@JonathanAllan Your right. When at some point (thinking iteratively) all are an even height,
it stops being important which you cap.

@ØrjanJohansen 1, 2 and 2, 1. If many can be capped it doesn't matter which you cap.

The "no recursion" requirement has been removed after it was commented on right after I published the question.

Jelly, 17 bytes
œṡṀ‘jṀ’µS>⁴µ¿¹0Ạ?

Try it online!
Uses iterative approach: repetitively subtract 1 from the highest element.
œṡṀ‘jṀ’µS>⁴µ¿¹0Ạ? - Main link. First input list, second input integer.
           µ¿       - While:
        S             - Sum of the list
         >            - greater than
          ⁴           - second input
       µ            - Do:
œṡ                    - split list by first occurrence of
  Ṁ                   - the maximum element
   ‘                  - increment all
    j                 - join by
     Ṁ                - maximum element
      ’               - increment
                ?   - If:
               Ạ      - no elements are non-zero
             ¹        - Then: output the list
              0       - Else: return 0.

Python 3, 70 77 56 bytes
-21 bytes thanks to Jonathan Allan!
def f(l,n):
 while n/all(l)<sum(l):l[l.index(max(l))]-=1

Try it online!

@JonathanAllan I added a fix for the latter case that didn't change the byte count. I also am unsure about the first issue seeing as it doesn't line up with an iterative approach to reducing values. I will await further clarification prior to making a fix.

This answer is fine now. Check the update of my question

Save 11 bytes with while n/all(l)<sum(l):l[l.index(max(l))]-=1

...in fact meta consensus is that return values may be modified inputs passed by reference, like l here, so this saves another 10 bytes

@JonathanAllan Nice! I don't know why this didn't occur to me earlier.

PHP>=7.1, 94 bytes
<?for([$a,$s]=$_GET;array_sum($a)>$s;)$a[array_flip($a)[max($a)]]--;print_r(min($a)?$a:0);

replace array_flip($a)[max($a)] with array_search(max($a),$a) to cap the last/first item with the maximum value
PHP Sandbox Online

Haskell, 53 bytes
c takes an integer and a list of integers, returning a list of integers. Use as c 6 [4,2].
c n=until((<=n).sum)f
f(x:y)|any(>x)y=x:f y|x>1=x-1:y

Try it online!
How it works

c n applies f to its (implicit) list argument until its sum is <= n.
f takes and returns a list of integers. It finds the first maximum value in the list by recursing, and then reduces it by 1, unless the maximum is <=1, in which case a non-exhaustive patterns error is raised.

R, 61 56 bytes
-5 bytes thanks to Leaky Nun
function(l,s){while(sum(l)>s)l[which.max(l)]=max(l)-1;l}

Anonymous function. Returns a vector with first entry zero (falsey in R) for invalid input.
Try it online!

56 bytes

Mathematica, 79 bytes
(u:=Plus@@a;For[a=#2,u>#,a[[#&@@a~Position~Max@a]]--];Min@a>0&&u==#||Quit[];a)&

Takes sum and List of integers

Jelly, 17 bytes
Note: this solution was ready just as the question was put on hold 33 hours ago.
_MḢ$¦S>¥
ç⁹$ÐLẠȧ$

A dyadic link returning the list of positive integers or 0
(an error rather than 0 is also possible by moving Ạȧ$ from the end of the second line to the end of the first line).
Try it online! or see a test suite.
How?
_MḢ$¦S>¥ - Link 1, single conditional decrement: list a; number m
         -     ...subtracts 1 from the first maximal element of a if sum(a)>m
         -   else subtracts 0 from the first maximal element of a
       ¥ - last two links as a dyad (left=a; right=m)
     S   -   sum(a)
      >  -   greater than m? (1 if it is, 0 otherwise) - call this x
    ¦    - sparse application of:
_        -   body:       subtraction (left=a; right=x)
   $     -   at indexes: last two links as a monad:
 M       -     indexes of maximal elements
  Ḣ      -     head

ç⁹$ÐLẠȧ$ - Link: list a; number m
   ÐL    - loop until the result does not change:
  $      - last two links as a monad:
 ⁹       -   chain's right argument, m
ç        -   call the last link as a dyad (left=current_a; right=m)
       $ - last two links as a monad:
     Ạ   -   all truthy? (0 if any of the final a's elements are 0)
      ȧ  -   logical and (if all were truthy yield the final a, otherwise 0)

CJam, 30 bytes
{_2$:+<{\__:e>_@#\(t\F}{;}?}:F

This is essentially of a named function, F, that expects a list and a number on the stack and returns a list on the stack.
Try it online! or run a test suite
Explanation
I'll refer to the list as l and the number as n.
_      e# Copy n.
2$     e# Copy l.
:+     e# Sum l.
<      e# Check if n < sum(l).
{      e# If it is:
 \__   e#  Bring l to the top of stack and make 2 copies of it.
 :e>_  e#  Get the maximum number in l and copy it.
 @#    e#  Bring l back to the top and find the index of max(l) in l.
 \(    e#  Decrement max(l).
 t     e#  Set the element of l at the position of max(l) to max(l)-1.
 \     e#  Swap, so now the top of the stack has the new l just under n.
 F     e#  Call F again on the new l and n.
}{     e# Else:
 ;     e#  Delete n.
}?     e# (end if)