text:
Reverse odd runs
Inspiration.
Task
Reverse runs of odd numbers in a given list of 2 to 215 non-negative integers.
Examples
0 1 → 0 1
1 3 → 3 1
1 2 3 → 1 2 3
1 3 2 → 3 1 2
10 7 9 6 8 9 → 10 9 7 6 8 9
23 12 32 23 25 27 → 23 12 32 27 25 23
123 123 345 0 1 9 → 345 123 123 0 9 1

I only understood the challenge after looking at the examples. I think runs of odd integers would be clearer than sequences. 2. I don't think setting an explicit upper limit is a good thing. If a language has only 8-bit integers, participating will be a lot harder.

Also, I'm not sure what further numeric computation refers to. Does it mean that I cannot return an immutable tuple or simply print the numbers?

@Dennis Updated as you suggested. It is to prevent input/output as string. Any suggestion for better wording?

Why do you want to prevent string output?

@Dennis Good point taken.

Related. Maybe dupe?

@xnor This one requires much more processing to find the parts that should be reversed.

Yes, looking at the other challenge, most of the answers rely on splitting on zeroes, whereas here you'd have to split on a condition, which most languages don't have a built-in for.

@LuisMendo Yes.

Python 2, 75 68 63 bytes
5 bytes thanks to Dennis.
And I have outgolfed Dennis.
Credits to Byeonggon Lee for the core of the algorithm.
o=t=[]
for i in input():o+=~i%2*(t+[i]);t=i%2*([i]+t)
print o+t

Ideone it!
Old version: 75 bytes

Tied, really. Also, I'm counting 81, not 75. I'm guessing you counted it with tabs, but the SE editor filled in spaces.

@DrGreenEggsandIronMan Your guess is correct. Tabs for readability. Either count the source or count the ideone one.

print doesn't need parens. Also, you only use a once, so there's no need for a variable.

APL, 21 20 bytes
{∊⌽¨⍵⊂⍨e⍲¯1↓0,e←2|⍵}

Try it || All test cases
Explanation:
                  2|⍵ Select all the odd numbers
                e←    Save that to e
              0,      Append a 0
           ¯1↓        Delete the last element
         e⍲           NAND it with the original list of odd numbers
     ⍵⊂⍨             Partition the list: (even)(even)(odd odd odd)(even)
  ⌽¨                 Reverse each partition
 ∊                    Flatten the list

Edit: Saved a ~ thanks to De Morgan's laws

Hello, and welcome to PPCG! This is a good post.

Haskell, 46 44 bytes
h%p|(l,r)<-span(odd.(h*))p=l++h:r
foldr(%)[]

Thanks to @xnor for recognizing a fold and saving two bytes.

Nice method, especially the (h*)! You can save a byte on the base case by writing f x=x second to match the empty list, though it looks like a foldr is yet shorter: h%p|(l,r)<-span(odd.(h*))p=l++h:r;foldr(%)[]:

I knew it was just a foldr after all! Thank you.

Python 2, 79 75 73 bytes
def f(x):
 i=j=0
 for n in x+[0]:
    if~n%2:x[i:j]=x[i:j][::-1];i=j+1
    j+=1

This is a function that modifies its argument in place. Second indentation level is a tabulator.
Test it on Ideone.

Where's the meta for this?

http://meta.codegolf.stackexchange.com/a/4942/12012

Cant you use x[j:i:-1]?

Jelly, 10 bytes
Ḃ¬ðœpUżx@F

Try it online! or verify all test cases.
How it works
Ḃ¬ðœpUżx@F  Main link. Argument: A (array)

Ḃ           Bit; return the parity bit of each integer in A.
 ¬          Logical NOT; turn even integers into 1's, odds into 0's.
  ð         Begin a new, dyadic link.
            Left argument: B (array of Booleans). Right argument: A
   œp       Partition; split A at 1's in B.
     U      Upend; reverse each resulting chunk of odd numbers.
       x@   Repeat (swapped); keep only numbers in A that correspond to a 1 in B.
      ż     Zipwith; interleave the reversed runs of odd integers (result to the
            left) and the flat array of even integers (result to the right).
         F  Flatten the resulting array of pairs.

Python3, 96 bytes
Saved a lot of bytes thanks to Leaky Nun!
o=l=[]
for c in input().split():
 if int(c)%2:l=[c]+l
 else:o+=l+[c];l=[]
print(" ".join(o+l))

93 bytes

Python 2, 78 75 bytes
def r(l):
 def k(n):o=~n%2<<99;k.i+=o*2-1;return k.i-o
 k.i=0;l.sort(key=k)

Super hacky :)

what is k.i ?

@LeakyNun k.i=0 on the last line. It's just a variable.

I don't get it. Are k and k.i related?

@LeakyNun No. k.i is a persistent variable between calls of k. See it as a makeshift global without having to use the global keyword.

C, 107 bytes
i;b[65536];f(){for(;i;)printf("%d ",b[--i]);}main(n){for(;~scanf("%d",&n);)n%2||f(),b[i++]=n,n%2||f();f();}

I know this is an old answer but you can move the last statement in the loop into the for(;;) for -1 byte. As suggested in this tip

MATL, 20 bytes
TiodgvYsG8XQ!"@gto?P

Input is a column array, using ; as separator.
Try it online!
Explanation
Consider as an example the input array [1;2;3;5;7;4;6;7;9]. The first part of the code, Tiodgv, converts this array into [1;1;1;0;0;1;0;1;0], where 1 indicates a change of parity. (Specifically, the code obtains the parity of each entry of the input array, computes consecutive differences, converts nonzero values to 1, and prepends a 1.)
Then Ys computes the cumulative sum, giving [1;2;3;3;3;4;4;5;5]. Each of these numbers will be used as a label, based on which the elements of the input will be grouped. This is done by G8XQ!, which splits the input array into a cell array containing the groups. In this case it gives {[1] [2] [3;5;7] [4;6] [7;9]}.
The rest of the code iterates (") on the cell array. Each constituent numeric array is pushed with @g. to makes a copy and computes its parity. If (?) the result is truthy, i.e. the array contents are odd, the array is flipped (P).
The stack is implicitly displayed at the end. Each numeric vertical array is displayed, giving a list of numbers separated by newlines.

Pyth, 14 bytes
s_McQshMBx0%R2

           %R2Q   Take all elements of the input list modulo 2
         x0       Get the indices of all 0s
      hMB         Make a list of these indices and a list of these indices plus 1
     s            Concatenate them
   cQ             Chop the input list at all those positions
 _M               Reverse all resulting sublists
s                 Concatenate them

Test cases

Desmos, 167 bytes
k=mod(l,2)
K=l.length
a=[K...1]
L=a[k[a]=1]
g(q)=∑_{n=1}^{[1...q.length]}q[n]
A=g(join(1,sign(L-L[2...]-1)))
f(l)=l[\{k>0:\sort(L,A.\max+1-A)[g(k)],k\}+[1...K](1-k)]

Hooooly crap, this was pretty challenging to do in Desmos given its limited list functionalities, but after lots of puzzling and scratched ideas, I finally managed to pull together something that actually works.
Try It On Desmos!
Try It On Desmos! - Prettified

Desmos, 94 93 bytes
g(M,j)=j-max([1...j]0^{mod(M,2)})
f(L)=L[[i+g(L[n...1],n+1-i)-g(L,i)fori=[1...n]]]
n=L.length

Try it on Desmos!
*-1 byte thanks to @AidenChow (remove space after for)
How it works
g(M,j) gives the difference between j and the greatest index less than (or equal to) j of an even entry in M. For example, g([0,2,4,1,3,5,7,6,8],6) = 3 because the 6th element in the list is 5, and the last even entry before it is 4, which is 3 elements earlier.
f(L) is the solution to the challenge. It's of the form L[[h(i)for i=[1...n]]], which is a list indexing: h(i) gives the index of the value in L that should be at index i in the result list.
The main difficulty lies in h(i), defined as h(i) = i+g(L[n...1],n+1-i)-g(L,i). Note that g(M,j) = 0 whenever M[j] is even, so h(i)=i if L[i] is even (this corresponds to even entries not moving) since L[n...1][n+1-i]=L[i]=even
If L[i] is odd then we have a more complicated story: g(L,i) gives the distance to the element before the start of the odd run, and g(L[n...1],n+1-i) gives the distance to the element after the end of the odd run. Then g(L[n...1],n+1-i)-g(L,i) says how much closer the element is to the end of the run than the start of the run. For example, for L=[0,2,4,1,3,5,7,6,8] and i=6, this difference is -1, so L[6] has to move 1 element to the left, to where the 3 is currently.
In general regarding the difference g(L[n...1],n+1-i)-g(L,i):

if the difference is positive, then the element is closer to the left than the right, and it needs to move right by the value of the difference
if the difference is negative, then the element is closer to the right than the left, and it needs to move left by the negative of the difference
if the difference is zero, then the element is at the center of an odd-length run, so it doesn't need to move at all.

Wow, brilliant solution! You forgot to put {...} around mod(M,2) btw. Also I'm pretty sure you don't need a space between for and i.

@AidenChow Pastes in fine for me without the curly braces

Weird... it pastes like this for me.

Ah, I accidentally left wolfram2desmos enabled. Thanks for catching it

J, 33 31 30 bytes
[:;]<@(A.~2-@|{.);.1~1,2|2-/\]

Usage
   f =: [:;]<@(A.~2-@|{.);.1~1,2|2-/\]
   f 0 1
0 1
   f 1 3
3 1
   f 1 2 3
1 2 3
   f 1 3 2
3 1 2
   f 10 7 9 6 8 9
10 9 7 6 8 9
   f 23 12 32 23 25 27
23 12 32 27 25 23
   f 123 123 345 0 1 9
345 123 123 0 9 1

JavaScript (ES6) 70 66 bytes
Edit 4 bytes saved thx @Neil
a=>[...a,[]].map(x=>x&1?o=[x,...o]:r=r.concat(o,x,o=[]),r=o=[])&&r

:r=r.concat(o,x,o=[]), saves you a couple of bytes. I think you can then go on to save another two like this: a=>[...a,[]].map(x=>x&1?o=[x,...o]:r=r.concat(o,x,o=[]),r=o=[])&&r.

What is the meaning of ...o?

@aloisdg http://codegolf.stackexchange.com/a/37723/21348

@Neil the empty array used as the added element is a master stroke

C#, 179 178 177 bytes
s=>{var o=new List<int>();var l=new Stack<int>();foreach(var n in s.Split(' ').Select(int.Parse)){if(n%2>0)l.Push(n);else{o.AddRange(l);o.Add(n);l.Clear();}}return o.Concat(l);}

I use a C# lambda. You can try it on .NETFiddle.
The code less minify:
s => {
    var o=new List<int>();var l=new Stack<int>();
    foreach (var n in s.Split(' ').Select(int.Parse)) {
        if (n%2>0)
            l.Push(n);
        else {
            o.AddRange(l);
            o.Add(n);
            l.Clear();
        }
    }
    return o.Concat(l);
};

Kudos to Byeonggon Lee for the original algorithm.

You can drop the space at the foreach(var and change if(n%2==1) to if(n%2>0) to save 2 bytes (or actually 1, because your current answer is 179 bytes instead of 178).

@KevinCruijssen It was changed in the less minify section but not in the minify one. Also thank you for the foreach space!

Clojure, 86 bytes
#(flatten(reduce(fn[a b](if(odd? b)(conj(pop a)(conj[b](last a)))(conj a b[])))[[]]%))

Here is the ungolfed version
#(flatten ; removes all empty vectors and flattens odd sequences
    (reduce
        (fn[a b]
            (if(odd? b) ; if we encounter odd number in the seq
                (conj(pop a)(conj[b](last a))) ; return all elements but last and the element we encountered plus the last element of current result
                (conj a b[])) ; else just add the even number and the empty vector
            )
        [[]] ; starting vector, we need to have vector inside of vector if the sequence starts with odd number
        %    ; anonymous function arg
    )
)

Basically it goes through the input sequence and if it encounters even number it adds the number and the empty vector otherwise if it's an odd number it replaces the last element with this number plus what was in the last element.
For example for this seq 2 4 6 1 3 7 2 it goes like this:

[]<=2
[2 []]<=4
[2 [] 4 []]<=6
[2 [] 4 [] 6 []]<=1
[2 [] 4 [] 6 [1 []]]<=3
[2 [] 4 [] 6 [3 [1 []]]]<=7
[2 [] 4 [] 6 [7 [3 [1 []]]]]<=2
[2 [] 4 [] 6 [7 [3 [1 []]]] 2 []]

And then flattening this vector gives the correct output. You can see it online here: https://ideone.com/d2LLEC

Husk, 7 bytes
ṁ↔ġ¤&%2

Try it online!
Explanation
ṁ↔ġ¤&%2  Implicit input, a list of integers.
  ġ      Group by equality predicate:
   ¤ %2   Arguments modulo 2
    &     are both truthy.
ṁ        Map and concatenate
 ↔       reversing.

Ruby, 51 bytes
->l{l.chunk(&:odd?).flat_map{|i,j|i ?j.reverse: j}}

Try it online!
Some slight variations:
->l{l.chunk(&:odd?).flat_map{|i,j|i&&j.reverse||j}}
->l{l.chunk(&:odd?).flat_map{|i,j|!i ?j:j.reverse}}
->l{l.chunk(&:even?).flat_map{|i,j|i ?j:j.reverse}}

Ruby 2.7, 48 bytes
->l{l.chunk{_1%2}.flat_map{_1>0?_2.reverse: _2}}

Unsupported by TIO :(

Pyth, 29 28 bytes
JYVQ=+J*%hN2+YN=Y*%N2+NY;+JY

Test suite.
Direct translation of my python answer (when has translating from python to pyth become a good idea?)

TSQL 118 bytes
DECLARE @ TABLE(i int identity, v int)
INSERT @ values(123),(123),(345),(0),(1),(9)

SELECT v FROM(SELECT sum((v+1)%2)over(order by i)x,*FROM @)z
ORDER BY x,IIF(v%2=1,max(i)over(partition by x),i),i desc

Fiddle

Perl 5 with -p, 42 bytes
map{$_%2?$\=$_.$\:print$\.$_,$\=""}$_,<>}{

Try it online!

Stax, 15 10 bytesCP437
Çⁿ╜"}☻≥º╚(

Try it online!
Tied Jelly!
So sad that packing only saved one byte.
Unpacked version with 11 bytes:
{|e_^*}/Frm

Explanation
{|e_^*} is a block that maps all even numbers n to n+1, and all odd numbers n to 0.
{|e_^*}/Frm
{     }/       Group array by same value from block
 |e            1 if the element is even, 0 if odd.
   _^          Get another copy of the current element and increment by 1
     *         Multiply them
        F      For each group execute the rest of the program
         r     Reverse the group
          m    Print elements from the group, one element per line.

JavaScript (Node.js), 53 bytes
a=>a.map((c,k)=>o.splice(n=c&1?+n:k+1,0,c),o=n=[])&&o

Try it online!
JavaScript (Node.js), 54 bytes
a=>a.map((c,k)=>o.splice(n=c&1?n:k+1,0,c),o=[],n=0)&&o

Try it online!

R, 69 bytes
v=scan();ifelse(o<-v%%2,v[rep(2*cumsum(r<-rle(o)$l)-r+1,r)-seq(v)],v)

Try it online!
Ungolfed, commented version:
o=v%%2              # get the odd numbers in the list
r=rle(o)$l          # find the run lengths of odd/even numbers

# reverse the indices of all the runs:
e=cumsum(r)         # the indices of the ends of each run
ie=rep(e,r)         # for each index in v, the index of the end of its run
is=rep(e-r+1,r)     # for each index in v, the index of the start of its run
irev=is+(ie-seq(v)) # reverses all runs

# the above 4 steps can be combined as:
irev=rep(2*cumsum(r)-r+1,r)-seq(v)

# so: use the reversed indices for odd numbers, and leave the even numbers unchanged
ifelse(o,v[irev],v)

Clojure, 66 bytes
#(mapcat(fn[x](if(some odd? x)(reverse x)x))(partition-by odd? %))

Try it online!

05AB1E, 11 9 bytes
.γÈN>*}í˜

Try it online or verify all test cases.
Explanation:
.γ    }    # Adjacent group the (implicit) input-list by:
  È        #  Check if the value is even (1 if even; 0 if odd)
   N>*     #  Multiply it by the 1-based index
           # (adjacent odd values will be grouped together, and every even
           # value is in its own separated group)
       í   # After the adjacent group-by: reverse each inner list
        ˜  # Flatten the list of lists
           # (after which the result is output implicitly)

J, 27 bytes
[:;]<@(|.^:{.);.1~1,2|2-/\]

Try it online!
A minor improvement over miles' J answer.
How it works
[:;]<@(|.^:{.);.1~1,2|2-/\]  NB. Input: an integer vector V
                  1,2|2-/\]  NB. Pairwise difference modulo 2 and prepend 1
                             NB. giving starting positions for same-parity runs
   ]          ;.1~  NB. Cut V at ones of ^ as the starting point and
      (|.^:{.)      NB. reverse each chunk (head of the chunk) times
                    NB.   (effectively, reverse odd chunks only)
    <@              NB. and enclose it
[:;                 NB. Finally, flatten the result

Factor + grouping.extras, 62 bytes
[ [ odd? ] group-by [ last2 swap [ reverse ] when ] map-flat ]

Attempt This Online!

Vyxal, 10 bytes
λ&›₂¥*;ḊRf

Try it Online!
Port of 05AB1E.
Another 10-byter that I produced independently: ⁽₂Ḋƛh∷ßṘ;f


text:
Convert to and from signed octal
Write some code to do the following:

Take as its input a signed integer in either signed decimal or signed octal
(explained below)
If the number is decimal convert it to octal. If it's octal, convert it to decimal
Output the number!

Instead of starting with a 0, negative octal numbers will start with a Z (capital zed).
In the same way that -1 is commonly encoded in binary as all 1s, in signed octal it is encoded as all 7s. -2 is all 7s except for the final digit which is 6, and so on.
Your code must accept leading 0s, or 7s (after the initial Z in octal) but must not output leading 0s for decimal or non-negative octal, with the exception of a single 0 to indicate octal format, and must not output leading 7s in the case of negative octal. 0 is valid as an entire number in both decimal and octal and is the only number to have an identical representation in both. Decimal numbers must not have any leading zeros and must be interpreted as octal if they do (i.e. 08 should be interpreted as neither decimal nor octal). Note that 0s immediately after the Z are significant and must not be truncated. Z is shorthand for an infinite number of 7s. You may assume that the input will always be valid and not check for it in your code.
 Input : Output
-1 : Z
-10: Z66
-5: Z3
10: 012
-30000: Z05320
-10000: Z54360
0  : 0
01234: 668
Z1234: -3428
Z77777: -1
00777: 511
Z6000: -1024

A table of the first few positive and negative signed octal numbers:
+ve -ve
  0   0
 01  Z
 02  Z6
 03  Z5
 04  Z4
 05  Z3
 06  Z2
 07  Z1
010  Z0
011 Z67
012 Z66

Make it small!

Doesn't octal zero have to be 00?

Could you remove the second part of the challenge (overflow) as it is not very related?

"Decimal numbers must not have any leading digits and must be interpreted as octal if they do." What does this mean? It seems to contradict itself. 2. How many bits are required to represent a negative number? 3. It took me some careful thinking to realise that Z is shorthand for an infinite string of ..777. But then the natural representation for -1 seems to be Z rather than Z7. Can answers give either in output? Can they choose to accept only one in input?

@PeterTaylor - Replace "digits" with "zeroes", I think.

@PeterTaylor I did mean "digits" but I've changed it to "0"s and "7"s.

The contradiction I see is that a number is either decimal or octal. I think the confusion could be avoided by explicitly stating that if it starts with 0 or Z it's octal: otherwise it's decimal; and 0 is a special case for which the output is 0.

source: Stack Exchange

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

sort: votes


text:
Sequence avoiding near collision
Task
Find a sequence of all numbers between min and max where every number differs from every other number in the sequence by at least "d" digits.
Example of sub-sequence
For min = 0, max = 1000 and d = 2, the following is part of one possible solution sequence:

123 ← Good
132 ← Good
145 ← Good
146 ← Bad

Notes
This is a bit practical. I was thinking about this as a problem that has kept cropping up over the years. Basically it's a pattern in URL shorteners / prize codes / conference room codes / etc...
I'd like to be able to hand out codes from a list, and have each code be:
A - Simple to type, and B - Be somewhat unlikely to accidentally conflict with another code because of a typing mistake.
There's no reason to work in base ten. I've expressed the problem that way for clarity, but in real cases we'd take advantage of letters as well.
Sub-Note
This is not that practical. If you use just six "digits" (allowing numbers and capital letters), then you have over two billion choices. That seems like plenty for most cases except for the URL shortener. Still I was thinking it would be nice to be able to generate a random number from that space and be able to quickly check that it was at least "d" different from all others that had been handed out up to that point. Generating a solution sequence is not quite the same problem, but it seemed interesting and I'm hoping that someone comes up with a clever way to structure the data in order to make it efficient to search for these near collisions.

Why is a minimun number needed, why not just 0 to max?

how is 145 good?

Also its not clear what the input and output of this challenge are. Moreover, please explain more regarding fastest code part as you have marked this question as fastest code but not provided any info around that in the question.

Oh, I didn't realise it wasn't a code-golf - fastest algorithm should be the first tag btw

@muddyfish - You could always start with zero. Starting with a different min gives a convenient way to generate a different sequence. I've reordered the tags as you suggested.

@Optimizer - Can you explain the confusion with the example? 145 differs by at least two digits from each previously given value. 146 has 1 and 4 in common in the same position as 145, though so it would fail the test.
I marked question as "fastest-algorithm" hoping to avoid the typical "fastest-code" issues. I want to avoid bench-marking in a half dozen different languages. I'm looking for an innovative search method or a way to generate a good sequence without having to search. I may post a naive example to try to clarify any confusion with the examples.

oh. I was thinking more in terms of each digit of 146 having a max diff of d. There are already 2 close votes on the question, proving that more clarity is needed.

As this is currently written, nothing stops the program that always outputs the empty sequence from being a valid answer.

What is the scope of "all" in "a sequence of all numbers between min and max"? The obvious reading is that you're looking for a permutation, but further reading strongly suggests that you're actually after a subset. Do you want a largest possible subset which meets the criterion? But then [tag:fastest-algorithm] is unlikely to be a good discriminator, because the size of the output is probably exponential in the size of the input. And although I'm not a coding theorist, I suspect that the only known approach is brute force.

Here's a terrible, brute force way of generating a sequence. I haven't attempted to do much to make it fast, though there are probably several simple gains to be had here. I'm trying to think of a way to make this at least a couple of orders of magnitude faster rather than finding improvements of a few percent.
public static IEnumerable<int> GetDifferentCodes(int min, int digits, int minDifference)
{
    var max = Math.Pow(10, digits) - 1;
    var goodCodes = new List<int>();
    var goodCodeDigits = new List<short[]>();

    for (var i = min; i < max; i++)
    {
        var newDigits = GetDigits(i, digits);

        if (!goodCodeDigits.All(goodCode => HasMinDiff(goodCode, newDigits, digits, minDifference)))
            continue;
        goodCodes.Add(i);
        goodCodeDigits.Add(newDigits);
    }
    return goodCodes;
}

private static readonly int[] Powers = {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000};

private static short[] GetDigits(int num, int digits)
{
    var ret = new short[digits];
    for (var i = 0; i < digits; i++)
    {
        ret[i] = (short) ((num/Powers[i]) % 10);
    }
    return ret;
}

private static bool HasMinDiff(short[] goodDigits, short[] digitsToCheck, int digits, int minDiff)
{
    var difference = 0;
    for (var i = 0; i < digits; i++)
    {
        if (goodDigits[i] == digitsToCheck[i]) continue;
        if (++difference >= minDiff) return true;
    }
    return false;
}

This questions is now closed over a rule that doesn't actually exist so far as I can see. This is pretty disappointing. In any case I found a not-quite-so-brute-force method if anyone else is thinking about this issue in the future: It's possible to calculate all collisions for the code you're checking, and search only for those collisions. This makes the algorithmic complexity linear. It seems obvious after I though of it, and I don't know why it gave me so much trouble earlier.

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


text:
Help me figure out what TeX I can use!
On TeX.SE the Help Centre says that the following is on topic:
Formats like LaTeX, ConTeXt and plain TeX
Engines like pdfTeX, LuaTeX and XeTeX
Distributions like TeX Live, MiKTeX, and MacTeX
Related software and tools, BibTeX, MakeIndex, Lyx, etc.

I wanted you to write a program to tell me whether my TeX is in the on-topic types of TeX.
An explicit list of the valid TeX-s is as follows:

MetaPost
PostScript
MetaFUN
TeX
LaTeX
LuaLaTeX
LuaTeX
ConTeXt
BibTeX
pdfTeX
Lyx
MakeIndex
TeX Live
XeLaTeX
XeTeX
MacTeX
MiKTeX

Rules

You may use any language.
This is code-golf, to the shortest answer wins.
If you use Regex, you can just match correct ones.
You only need to match one at a time: no
Lyx
BibTeX
You must check with capitalization listed here.

Tests
TeX -> True/1/<match>
pTeX -> False/0/<not-match>
ConTeXt -> True/1/<match>
context -> False/0/<not-match>
MetaFun -> False/0/<not-match>
MetaFUN -> True/1/<match>

P.S. Bonus points for an on-topic TeX answer!

@closevoter This is a [tag:tips] question, which is explicitly on-topic.

Your regex looks broken. The ^ is only applied to the first alternative and none of the alternatives have a $.

You also seem to be missing MiKTeX in your full list.

Why not make this a challenge?

@DrGreenEggsandIronMan, it's tagged [tag:tips], but it looks far too specific to be a [tag:tips] question. I agree with Mego that it's really a challenge, but as a challenge it seems to be a moral duplicate of existing "write a regex to match everything in this list" questions.

@PeterTaylor There are lots of specific tips questions. 1 2 3 And a bunch of others than I don't have enough space to link to. Also, I don't agree with closing a tips question as a duplicate of a challenge. Sure, it could be a challenge, but it's not. (yet)

Also, if it was a challenge, I would downvote it for being language-specific.

@DrGreenEggsandIronMan, surely if an existing question's answers answer a new question, that new question is a duplicate, regardless of the tags? The purpose of tags is to help people find similar questions, not to be magical talismen.

@PeterTaylor There's a fairly big difference between this question and the challenge you closed it as a dupe of: the other one is "regular" regex golf where you have a match list and a fail list. Here, the fail list is every possible string that isn't in the match list. This question requires the regex to match only the given list and nothing else, so I don't really think the tricks from the other answers are applicable. (Although I'm not sure any tricks are applicable at all in this case.)

@MartinEnder: That is why I used the JS-specific m flag.

@NoOneIsHere I think you're misunderstanding how the m flag works. I'm not sure what you think it does, but it doesn't fix your regex. (It simply makes ^ and $ match at the beginning and end of a line, respectively, as opposed to just the beginning and end of the string.)

@MartinEnder: http://regexr.com/3doat

@NoOneIsHere The issue is this: http://regexr.com/3dob0 ... if you're not concerned about that, you can ditch the ^ and m altogether.

I don't think removing your own attempt improves the question. Since this is not a challenge but a question, SE's standard mantra of "what have you tried" still applies, and giving people a solution to improve on is definitely a good start for tips questions.

@MartinEnder: I'm working on it

Let us continue this discussion in chat.

Did this just turn from a how-can-I-golf-this to an actual challenge?

@dorukayhan Yes, it did. It was VTC-ed and everybody downvoted so I converted it to a challenge.

Do we need a [tag:tex] tag?

JavaScript Regex, 99 101 99 97 + 1 for g flag = 98 bytes
^(((Xe|Lua)?(La)?|Bib|MiK|pdf|Mac)TeX|ConTeXt|TeX Live|Meta(FUN|Post)|PostScript|MakeIndex|Lyx)$

Test it here. Type into the Text box. Alternatively, test it here.

var j = $("#dos");
var text;
function abc(){
  text = $('#uno').val();
  j.val(text.match(/^(((Xe|Lua)?(La)?|Bib|MiK|pdf|Mac)TeX|ConTeXt|TeX Live|Meta(FUN|Post)|PostScript|MakeIndex|Lyx)$/g) == text ? "Matches!" : "No match!");
};

<input id='uno' />

<button id='tres' onclick="javascript:abc()">Test!</button>

<input id='dos' />

Test all cases:

var j = $("#dos");
var tests = ["TeX", "pTeX", "ConTeXt", "context", "MetaFun", "MetaFUN", "TeX Live"];
function abc(e){
  j.val(j.val() + e + ": " + (e.match(/^(((Xe|Lua)?(La)?|Bib|MiK|pdf|Mac)TeX|ConTeXt|TeX Live|Meta(FUN|Post)|PostScript|MakeIndex|Lyx)$/g) == e ? "Matches!" : "No match!") + "\n");
};

function def(){
  tests.forEach(abc);
}

<button id='tres' onclick="javascript:def()">Test!</button>

<textarea rows=50 cols=200 id='dos'>
</textarea>

As a code-golf challenge answer, this seems to be invalid as it is not a program or function.

@feersum Except my challenge allows regex.

Is the ^ in the starting and $ at the end of the regular expression really necessary?

@R.Kap Yes. Otherwise pTeX will match.

Ah, I nearly forgot the regex.

@MatthewRoh what do you mean?

It looks like You're using regular expressions.

Perl 5, 103 bytes
102 bytes, plus 1 for -pe instead of e. Stdin→stdout.
$_=/^(Meta(Post|FUN)|TeX Live|PostScript|((Xe|Lua)?(La)?|Bib|pdf|M(ac|iK))TeX|ConTeXt|Lyx|MakeIndex)$/

How do you output without say/print?

@NoOneIsHere, -p handles reading from stdin and printing to stdout. See http://perldoc.perl.org/perlrun.html#Command-Switches

Python 3.5, 149 147 137 136 bytes
import re;lambda f:re.fullmatch('TeX Live|(La|LuaLa|Lua|Bib|pdf|XeLa|Xe|Mac|MiK)?TeX|Lyx|MakeIndex|Meta(Post|FUN)|PostScript|ConTeXt',f)

An anonymous function that uses a regular expression to return a re match object (such as <_sre.SRE_Match object; span=(0, 5), match='LaTeX'>) as a truthy value and None as a falsy value. The actual regular expression is currently 102 100 99 bytes in length.
Try It Online! (Ideone)

Why if/else? It will still work without the if/else-s because return x == return (1 if x else 0) logically.

@NoOneIsHere I was not sure if I had to, but I was making it so that it returns a truthy/falsy value based on whether a match was found or not. However, if you are fine with a re match object being returned, I'll change it. I just was not sure what kind of output you wanted, so I did this.

According to the Defaults for I/O, if bool(x) == True, then it is allowed.

@NoOneIsHere So it's okay if something like <_sre.SRE_Match object; span=(0, 5), match='LaTeX'> is returned when a match is found?

Yes, as long as bool(x) is True.

@NoOneIsHere All right. I'll change it then.

Let us continue this discussion in chat.

By the way, your answer doesn't work for MetaFUN, which it should match, and Meta FUN, which it shouldn't match.

@NoOneIsHere Oh, sorry. I thought it was supposed to be Meta FUN but I guess it was supposed to be MetaFUN instead. My bad.

@NoOneIsHere It's fixed now.

Thunno, \$ 122 \log_{256}(96) \approx 100.42 \$ bytes
"MetaPost|PostScript|MetaFUN|?|La?|LuaLa?|Lua?|ConTeXt|Bib?|pdf?|Lyx|MakeIndex|? Live|XeLa?|Xe?|Mac?|MiK?"'?"TeX"AR'|ZisAq

Attempt This Online!
"..."'?"TeX"AR'|ZisAq  # Implicit input
"..."                  # Push the string
            AR         # Replace...
     '?                # ...the character '?'...
       "TeX"           # ...with the string "TeX"
                Zi     # Split the resulting string...
              '|       # By the character '|'
                  sAq  # Is the input in this list?
                       # Implicit output

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


text:
Where should I put my mirror?
This is a mirror: |. I just found out that you can stick a mirror in the middle of a string if the string can be mirrored on itself! For example, the string abccba. If you cut it in half the two halves are mirror images of each other:
abc  <-->  cba

So, we can stick a mirror in the middle of the string, and our new string is abc|cba. Sometimes, only part of the string can be mirrored on itself. For example, the string "mirror". The two r's are mirrored, but the rest of the string isn't. That's OK, we'll just remove the parts of the string that don't mirror each other, and we get the following string:
r|r

Some strings could be mirrored in multiple places. For example, "Hello World, xyzzyx". I like having a lot of text reflected in my mirror, so you need to find the best place to put my mirror. In this case, you should output the longer mirrored string and just like our last example, remove everything else. This string becomes:
xyz|zyx

Some strings look like they can be mirrored, but actually can not. If a string cannot be mirrored anywhere, you should output nothing.
The challenge:
Given a string containing only printable-ascii, find the best place to put my mirror. In other words,

Find the largest even-length palindromic substring, then output it with a pipe character '|' in the middle of it.

The input will be 1-50 characters long.
You can assume that the input will not contain mirrors | or newlines. Beyond that, all printable-ascii characters are fair game. If the longest mirrored substring is tied between two substrings, you can choose which one to output. For example, for the string "abba ollo", you must output "ab|ba" or "ol|lo", but it doesn't matter which one you output. Strings are case-sensitive, e.g. "ABba" should not output "AB|ba", it should output the empty string.
Sample IO:
"Hello World"     --> "l|l"
"Programming Puzzles and Code-Golf"     --> Either "m|m" or "z|z"
"abcba"           --> ""
"Hulluh"          --> "ul|lu"
"abcdefggfedcba"  --> "abcdefg|gfedcba"
"abcdefggfabc"    --> "fg|gf"
"AbbA"            --> "Ab|bA"
"This input is a lot like the last one, but with more characters that don't change the output. AbbA" --> "Ab|bA"

As usual, this is code-golf, so standard loopholes apply, and the shortest answer in bytes wins!

Is there a limit on the length of the input?

@Mego As long as your algorithm theoretically works on any input, I don't care how long it takes/how much memory it takes.

I asked because vanilla regex engines are only capable of matching palindromes of length up to a specified, finite value (as opposed to arbitrarily-long palindromes), and the possibility of a regex-based solution would depend on whether or not there is an upper bound on the length of the input.

@Mego Ah, that makes sense. Let's say the input can be up to 50 characters long. How does that sound?

Pyth - 19 17 15 13 bytes
Thanks to @FryAmTheEggman for saving me two bytes.
ARRGH the special case for no answer. Solved that!
e_I#jL\|cL2.:

Test Suite.
e                Last element in list, this works out to longest one
  _I             Invariance under reverse, this detect palindrome
   #             Filter
   jL            Map join
    \|           By "|"
    cL2          Map chop in two pieces
     .:Q)        Substrings. Implicit Q). ) makes it do all substrings.

Nooooo! Ninja'd to the pyth answer ;_;

Explanation please? :3

@Downgoat he took all substrings and chop into two, join each pair with |, filter by symmetry, append that to [k] and get the last element (which is the longest)

@Downgoat done.

:Q) = Bignose

I don't think you need the +k, as the error message goes to stderr, and then the program prints nothing. This and this are relevant meta posts.

@FryAmTheEggman oh, did not know this.

05AB1E, 19 17 14 bytes
Code:
Œévy2ä'|ý©ÂQi®

Explanation:
Œ                # Get all substrings of the input
 é               # Sort by length (shortest first)
  vy             # For each element...
    2ä           # Split into two pieces
      '|ý        # Join by "|"
         ©       # Copy this into the register
          Â      # Bifurcate, pushing a and reversed a
           Q     # Check if it's a palindrome
            i®   # If so, push that string again
                 # Implicit, the top element is outputted

Uses the CP-1252 encoding. Try it online!.

Python 2, 102 97 bytes
def f(s):h=len(s)/2;r=s[:h]+'|'+s[h:];return s and max(r*(r==r[::-1]),f(s[1:]),f(s[:-1]),key=len)

Rather slow and inefficient... Verify the smaller test cases on Ideone.

JavaScript, 100 99 bytes
s=>eval('for(O=i=0;s[i++];O=O[j+j]?O:o)for(o="|",j=0;(S=s[i-1-j])&&S==s[i+j++];o=S+o+S);O[1]?O:""')

or
s=>eval('for(O="",i=0;s[i++];O=O[j+j]||j<2?O:o)for(o="|",j=0;(S=s[i-1-j])&&S==s[i+j++];o=S+o+S);O')

Just curious, what's the eval for?

@gcampbell eval to avoid return

Can't you use the comma operator to avoid return?

@SpeedyNinja nope. for is not an expression, so it would normally require braces and a return

Lua, 133 bytes
s=...for i=#s,1,-1 do for j=1,#s-i do m=j+i/2-i%2/2t=s:sub(j,m).."|"..s:sub(m+1,i+j)if t==t.reverse(t)then print(t)return end end end

Verify all testcases on Ideone.com.

Use t==t:reverse() to save a byte :)

Python 2, 91 bytes
f=lambda s,p='':s and max((''<p<=s<p+'\x7f')*(p[::-1]+'|'+p),f(s[1:]),f(s[1:],s[0]+p),key=len)

Replace \x7f with the actual character DEL, which is ASCII 127 (credit to Dennis).
This follows a similar strategy to Dennis's answer of using max and recursively branching to find the longest palindrome interval. But, instead, it finds the left half, checking that the corresponding mirrored right half comes right after it with a self-made startswith.
The function guesses whether the first character is in the mirrored left half. If not, it just drops it and recurses on the remainder. If it is, it's added to to the stack p of reversed characters. If the string ever starts with the stack, the mirror string is generated and considered as a possible longest mirror. To avoid | as an output, only non-empty stacks are considered.

Retina, 66 bytes
Byte count assumes ISO 8859-1 encoding.
M!&`(.)+(?<-1>\1)+(?(1)¶)
O$#`.+
$.&
A-2`
^(.)+?(?=(?<-1>.)+$)
$&|

Try it online! (The first line enables testing of several linefeed-separated test cases at once.)
Hmmm, much longer than I would like...

JavaScript (ES6), 91
s=>[...s].map((d,i)=>{for(a='|',j=0;d=s[i-j],d&&d==s[i-~j];r=r[j+++j]?r:a)a=d+a+d},r='')&&r

Less golfed
f=s=>
  [...s].map(
    (d,i) => {
    for(a='|', j=0; d=s[i-j], d&&d==s[i-~j]; r = r[j++ +j]? r : a)
      a = d+a+d
    }, r=''
  ) && r

Test

F=
s=>[...s].map((d,i)=>{for(a='|',j=0;d=s[i-j],d&&d==s[i-~j];r=r[j+++j]?r:a)a=d+a+d},r='')&&r

;[["Hello World", "l|l"]
,["Programming Puzzles and Code-Golf", "m|m"]
,["abcba", ""]
,["Hulluh", "ul|lu"]
,["abcdefggfedcba", "abcdefg|gfedcba"]
,["abcdefggfabc", "fg|gf"]
,["AbbA", "Ab|bA"]
,["This input is a lot like the last one, but with more characters that don't change the output. AbbA", "Ab|bA"]]
.forEach(t=>{
  var i=t[0],k=t[1],r=F(i)
  console.log(k==r?'OK ':'KO ',i+' -> '+r,k!=r?'(check '+k+')':'')
})

Perl 5, 105 100 98 + 1 = 106 101 99 bytes
/(?=((.)(?1)?\2)(?{[push@_,$1})(?!))/;($_)=sort{length$b<=>length$a}@_;substr($_,length>>1,0)='|'if$_

I just wanted to give recursive regexes a go. Needs the -p option. Edit: Saved (crossed out 4) 7 bytes thanks to @msh210. (The missing byte is due to a saving that was superseded by @msh210's latest saving.)

I haven't tested any of these, but probably this can be abbreviated various ways, including: (1) @_=(@_,$1) can be push@_,$1. (2) Omit the newlines and the final ;. (3) I suspect there's a shorter sort condition you can use (if nothing else then at least --- perhaps --- substitute - for <=>)

@msh210 Thanks for the first two points but I already tried - and it didn't work (probably needs parens for precedence which defeats the saving).

Try y...c>>1 or y...c/2 instead of length>>1. (Untested.)

@msh210 I obviously should have read the tips for golfing in Perl first...

I'm guessing your last pair of parens can go, also.

And test (1) whether you really need the if$_ at the end (maybe it works even for empty $_). I suspect you do,  but it's worth checking. Also (2) whether this works when the palindromic part is 00: the if$_ should fail there and you'll wind up with no pipe. I think.

@msh210 You need the if$_ otherwise it outputs a | when there's nothing to mirror. There's no problem with 00 though, it's truthy.

@msh210 I get an error if I try to remove any more parens.

TSQL 227 223 bytes
I hardcoded the length to max 99 bytes, this saved bytes but made it slower. It still have a decent performance though.
Golfed:
DECLARE @t varchar(99)='AbccbA'

,@z char(99)='',@a INT=0,@ INT=0WHILE @a<LEN(@t)SELECT
@z=IIF(LEN(x)>LEN(@z)/2and @t LIKE'%'+x+REVERSE(x)+'%'COLLATE
Thai_bin,x+'|'+REVERSE(x),@z),@=IIF(@=50,1,@+1),@a+=IIF(@=1,1,0)FROM(SELECT
SUBSTRING(@t,@a,@)x)x PRINT @z

Ungolfed:
DECLARE @t varchar(99)='AbccbA'

,@z char(99)='',
@a INT=0,
@ INT=0
WHILE @a<LEN(@t)
  SELECT
    @z=IIF(LEN(x)>LEN(@z)/2and @t LIKE'%'+x+REVERSE(x)+'%'COLLATE Thai_bin,x+'|'
       +REVERSE(x),@z),
    @=IIF(@=99,1,@+1),
    @a+=IIF(@=1,1,0)
  FROM
    (SELECT SUBSTRING(@t,@a,@)x)x

PRINT @z

Fiddle

You can shave off 2 byte if you limit to 99 as the last example is only 99 chars long

@VisualBean thankyou, changed the script to only allow 99 characters, also changed the collation from Thai_CS_AS to thai_bin

Haskell, 126 111 bytes
(!)=drop
f s|n<-length s=last$"":[a++'|':b|k<-[1..n],t<-map(!s)[1..n-k],let[a,b]=take k<$>[t,k!t],a==reverse b]

Husk, 12 bytes
►S=↔ΘmoJ'|½Q

Try it online!
-1 from Leo.

Save 1 byte. I feel like more should be possible but couldn't find anything else

Huh. I thought Q didn't order by length and it'd fail for some testcase. Nice.

Python 2, 149 bytes
R,L,s=range,len,input()
t=max([s[i:j/2+i/2]for i in R(L(s))for j in R(L(s)+1)if s[i:j]==s[i:j][::-1]and(j-i)%2<1],key=L)
print t+'|'*(L(t)>0)+t[::-1]

Try it online
This program finds the first half of the largest palindromic substring of even length, and prints that string, followed by a |, followed by that string reversed. If there is no suitable string, t will be the empty string, and '|'*(L(t)>0) will evaluate to the empty string.

Java 8, 294 283 232 bytes
s->{int l=s.length(),i=0,j,z,y=0;String a,b="";for(;i<l;i++)for(j=0;j<=l-i;)if((a=s.substring(i,i+j++)).equals(new StringBuffer(a).reverse()+"")&(z=a.length())%2<1&z>y){y=z;b=a;}return y>0?b.substring(0,y/=2)+"|"+b.substring(y):"";}

Explanation:
Try it here.
s->{                               // Method with String as both parameter and return-type
  int l=s.length(),                //  Length of the input-String
      i=0,j,                       //  Index-integers
      z,y=0;                       //  Temp-integers
  String a,b="";                   //  Temp-Strings
  for(;i<l;i++)                    //  Loop (1) from 0 to `l` (exclusive)
    for(j=0;j<=l-i;                //   Inner loop (2) from 0 to `l-i` (inclusive)
      if((a=s.substring(i,i+j++))  //    Set the current substring to `a`
          .equals(new StringBuffer(a).reverse()+"")
                                   //    If `a` is a palindrome
         &(z=a.length())%2<1       //    And the length of `a` is even
         &z>y){                    //    And the length of `a` is larger than `y`
        y=z;                       //     Change `y` to `z`
        b=a;}                      //     Change `b` to `a`
                                   //   End of inner loop (2) (implicit / single-line body)
                                   //  End of loop (1) (implicit / single-line body)
  return y>0?                      //  If the result-length is not 0:
    b.substring(0,y/=2)+"|"+b.substring(y)
                                   //   Return the result
   :                               //  Else:
    "";                            //   Return an empty String
}                                  // End of method


text:
Compute the runs of a string
Consider the following definitions taken from The number of runs in a string by W. Rytter.  Note that word, string and substring are all roughly synonyms.

A run in a string is a nonextendable (with the same minimal period)
  periodic segment in a string.
A period p of a word w is any positive integer p such that w[i]=w[i+p]
  whenever both sides of this equation are defined. Let per(w) denote
  the size of the smallest period of w . We say that a word w is
  periodic iff per(w) <= |w|/2.

For, example consider the string x = abcab. per(abcab) = 3 as x[1] = x[1+3] = a, x[2]=x[2+3] = b and there is no smaller period. The string abcab is therefore not periodic.  However, the string abab is periodic as per(abab) = 2.
A run (or maximal periodicity) in a string w is an interval [i...j] with j>=i, such that

w[i...j] is a periodic word with the period p = per(w[i...j])
It is maximal. Formally, neither w[i-1] = w[i-1+p] nor w[j+1] = w[j+1-p].  Informally, the run cannot be contained in a larger run with the same period.

Denote by RUNS(w) the set of runs of w.
Examples
The four runs of atattatt are [4,5] = tt, [7,8] = tt, [1,4] = atat, [2,8] = tattatt.
The string aabaabaaaacaacac contains the following 7 runs:
[1,2] = aa, [4,5] = aa, [7,10] = aaaa, [12,13] = aa, [13,16] = acac, [1,8] = aabaabaa, [9,15] = aacaaca.
Your output should be a list of runs. Each run should specify the interval it represents but does not need to output the substring itself. The exact formatting can be whatever is convenient for you.
The examples use 1-indexing but you are free to use 0-indexing instead if it is more convenient.
TASK
Write code that given a string w, output RUNS(w).
Languages and input
You can use any language you like and take the input string in whatever form is most convenient.  You must give a full program however and you should show an example of your code running on the example input.

Nice challenge, but is there a good reason to overrule the default and disallow functions?

@MartinEnder It's just my preference. It makes it easier for people to just copy and paste code and try it out themselves which in turn makes the answers more interesting for more people.

But that also causes a lot of overhead code, which makes the competition unfair for languages with a verbose syntax. I wouldn't be golfing in Java for example if I had to write class A{public static ...} everytime I wanted to golf code

@BassdropCumberwubwubwub I can see there are pros and cons. I happen to weigh the pros more strongly. I think it's most interesting to compare the length of golf'ed answers in similar languages in any case rather than comparing APL to Python for example.

"a run is maximal if it is not fully contained within any larger run" but in your first example, [7,8] is fully contained within [2,8]. Or are you strictly talking about runs that repeat the same substring?

@aditsu Argh. So much for trying to add informality. The formal definition is the correct one. Edited and thanks.

Can the end indices in the output be exclusive?

@Pietu1998 Sure, why not.

in your second example, isn't 1,2 and 4,5 contained in 1,8

@t-clausen.dk The (minimal) period p is different. In the first it is a (p=1) and in the second it is aab (p=3).

Pyth, 38 bytes
{smm,hk+ekdfgaFTdcx1xM.ttB+0qVQ>QdZ2Sl

  m                                 SlQ   map for d in [1, …, len(input)]:
                            qVQ>Qd          pairwise equality of input[:-d] and input[d:]
                        tB+0                duplicate this list, prepending 0 to one copy
                      .t          Z         transpose, padding with 0
                    xM                      pairwise xor
                  x1                        find all occurrences of 1
                 c                 2        chop into groups of 2
           f                                filter for groups T such that:
             aFT                              the absolute difference between its elements
            g   d                             is greater than or equal to d
   m                                        map for groups k:
     hk                                       first element
    ,  +ekd                                   pair with the last element plus d
 s                                        concatenate
}                                         deduplicate

Test suite

I get "[[3, 5], [6, 8], [0, 4], [1, 8]]" from "atattatt".  Does [3,5] represent "tt"?  It would be great if you could explain the algorithm you have used as well at a high level.

@Lembik Yes, [i, j] represents the slice starting between (0-indexed) characters i-1 and i and ending between characters j-1 and j. This is the standard convention in Pyth and most sane languages, as it should be (see here and here).

Great.  Is it possible to describe your solution intuitively? I can't reverse engineer it from your code description unfortunately.

@Lembik Suppose we are looking for runs of period d. We find all the locations where character i matches character i + d. We then find runs of at least d consecutive such locations. Repeat for all d. We have to deduplicate at the end because the real period might have only been a divisor of d.

CJam, 66
q:A,2m*{~A>_@)_@<2*@@2*<=},{_2$-2>2,.+={+}&}*]{[_1=\)\0=2*)+]}%_&p

Try it online
Brief explanation:
The algorithm works in 4 steps (first 3 of them corresponding with the 3 main blocks you can observe):

Find all [length index] pairs that correspond to a duplicated substring (such as aabaabaaaacaacac); these are parts of runs.
Concatenate pairs that are part of the same run, i.e. consecutive indices and same length/period.
Construct the actual runs, by taking the minimum index and maximum index + 2 * length - 1.
At the end, remove the duplicated runs (which are the same interval obtained with a different period)

I'd like to golf it more, so this is all subject to change.

Thank you for this. Could you explain the algorithm you have used too please?

@Lembik ok, updated


text:
Groups of repeating items
Challenge description
Given a list / array of items, display all groups of consecutive repeating items.
Input / output description
Your input is a list / array of items (you can assume all of them are of the same type). You don't need to support every type your language has, but is has to support at least one (preferably int, but types like boolean, although not very interesting, are also fine). Sample outputs:
[4, 4, 2, 2, 9, 9] -> [[4, 4], [2, 2], [9, 9]]
[1, 1, 1, 2, 2, 3, 3, 3, 4, 4, 4, 4] -> [[1, 1, 1], [2, 2], [3, 3, 3], [4, 4, 4, 4]]
[1, 1, 1, 3, 3, 1, 1, 2, 2, 2, 1, 1, 3] -> [[1, 1, 1], [3, 3], [1, 1], [2, 2, 2], [1, 1], [3]]
[9, 7, 8, 6, 5] -> [[9], [7], [8], [6], [5]]
[5, 5, 5] -> [[5, 5, 5]]
['A', 'B', 'B', 'B', 'C', 'D', 'X', 'Y', 'Y', 'Z'] -> [['A'], ['B', 'B', 'B'], ['C'], ['D'], ['X'], ['Y', 'Y'], ['Z']]
[True, True, True, False, False, True, False, False, True, True, True] -> [[True, True, True], [False, False], [True], [False, False], [True, True, True]]
[0] -> [[0]]

As for empty lists, output is undefined - it can be nothing, an empty list, or an exception - whatever suits your golfing purposes the best. You don't have to create a separate list of lists either, so this is a perfectly valid output as well:
[1, 1, 1, 2, 2, 3, 3, 3, 4, 9] ->

1 1 1
2 2
3 3 3
4
9

The important thing is to keep the groups separated in some way. This is code-golf so the shortest code in bytes wins

Maybe we output a list that has some special separator value?

@xnor: Can you provide an example? An array of ints separated by, for instance, 0s  would be a bad idea since there can be 0s in the input...

For example, [4, 4, '', 2, 2, '', 9, 9] or [4, 4, [], 2, 2, [], 9, 9].

Actually, what types do we have to support. Can the elements themselves to be lists? I imagine some languages have built-in types that can't be printed or have weird equality-checking.

@xnor: Yeah, that's what my concern was - if your input has lists inside it, then using empty list as a separator might be confusing. That's why I included "you can assume all the items are of the same type", so that can use a different type as a separator.

Does our code really have to work for every type that exists in the language? I think this introduces too many corner-case with languages that support objects that change when accessed, that are not equal to themselves, that cannot be printed, etc. It's recommended to stick to just integers or simplier for challenges like these.

No, of course not. Using only one specified type is fine. I'll include this in the description.

Oh, I was misunderstanding. So you're saying we get to choose what type of elements our code works for, and it only has to work for that type? I presume using a type that has only a single value is not OK (though you should say so).

My point is you don't have to go out of your way to support every single edge case if your language of choice is not suitable for such operations. I'd say that supporting one specified type (like int) is an absolute minimum for your program to be considered valid.

Let us continue this discussion in chat.

Is an I/O format like abbcccddd → a bb ccc ddd acceptable?

Sure. A lot of languages treat strings as a list/array of chars, which is fine.

Mathematica, 5 bytes
Split

... there's a built-in for that.

…what a surprise!

@Fatalize The real surprise is how short it is.

Jelly, 5 bytes
I0;œṗ

Works for all numeric types. Try it online! or verify all numeric test cases.
How it works
I0;œṗ  Main link. Argument: A (array)

I      Increments; compute the differences of consecutive elements.
 0;    Prepend a zero.
   œṗ  Partition; split A at truthy values in the result to the left.

Retina, 15 8 bytes
Thanks to Lynn for suggesting a simpler I/O format.
!`(.)\1*

Treats the input as a list of characters (and uses linefeeds to separate groups).
Try it online!
This simply works by matching groups and printing them all (which uses linefeed separation automatically).

I asked about abbcccddd → a bb ccc ddd being an acceptable I/O format, and the OP approved of it, so I guess !`(.)\1* is fine?

@Lynn Oh, that's indeed much simpler, thanks.

MATL, 9 bytes
Y'v"@Z}Y"

Y'     % Take input. Run-length encoding. Gives two row arrays: values and run lengths
v      % Concatenate vertically
"      % For each column
  @Z}  %   Push column and split into its two elements
  Y"   %   Run-length decoding
       % End for. Implicitly display

Input is a row array of numbers, with spaces or commas as separators.
Try it online! Test with non-integer numbers.

MATL, 11 bytes
lidgvYsG7XQ

Input is a column array of either numbers or characters, using ; as separator.
Try it online! Test with arbitrary numbers. Test with characters.
l     % Push 1
i     % Take input, say [4;4;2;2;9;9]
d     % Consecutive differences of input: [0;-2;0;7;0]
g     % Convert to logical: gives 1 if consecutive entries were different: [0;1;0;1;0]
v     % Concatenate vertically with the initial 1: [1;0;1;0;1;0]
Ys    % Cumulative sum. Each value is a group label: [1;1;2;2;3;3]
G     % Push input again
7XQ   % Split into horizontal arrays as indicated by group labels: {[4 4];[2 2];[9 9]}
      % Implicitly display

JavaScript (ES6), 39 37 bytes

f=
s=>s.replace(/(\w+) (?!\1\b)/g,`$1
`)
;
<input oninput=o.textContent=f(this.value);><pre id=o>

Works on any space-separated word-like tokens. Saved 2 bytes thanks to @MartinEnder♦. Best I could do for array input and return is 68:
a=>a.reduce((l,r)=>(l==r?c.push(r):b.push(c=[r]),r),b=[c=[a[0]]])&&b

I added an array answer at 56

gs2, 2 bytes
c-

Try it online!
c is a grouping built-in that does exactly this, so we call it on STDIN (which is a string, i.e., a list of chars) and get a list of strings. Sadly, the result is indistinguishable from the input, so we need to add separators! - (join by spaces) does the trick.
An alternative answer is cα (2 bytes of CP437), which simply wraps c into an anonymous function.

J, 13 bytes
<;.1~1,2~:/\]

Since J does not support ragged arrays, each run of equal elements is boxed. The input is an array of values and the output is array of boxed arrays.
Usage
   f =: <;.1~1,2~:/\]
   f 4 4 2 2 9 9
┌───┬───┬───┐
│4 4│2 2│9 9│
└───┴───┴───┘
   f 1 1 1 3 3 1 1 2 2 2 1 1 3
┌─────┬───┬───┬─────┬───┬─┐
│1 1 1│3 3│1 1│2 2 2│1 1│3│
└─────┴───┴───┴─────┴───┴─┘
   f 'ABBBCDXYYZ'
┌─┬───┬─┬─┬─┬──┬─┐
│A│BBB│C│D│X│YY│Z│
└─┴───┴─┴─┴─┴──┴─┘
   f 0
┌─┐
│0│
└─┘

Explanation
<;.1~1,2~:/\]  Input: s
            ]  Identify function to get s
       2       The constant 2
           \   Operate on each overlapping sublist of size 2
        ~:/      Are the two values unequal, 1 if true else 0
     1,        Prepend a 1 to it
<;.1~          Using the list just made, chop s at each index equal to 1 and box it
               Return this as the result

Dyalog APL, 9 bytes
⊢⊂⍨1,2≠/⊢

⊢ the argument
⊂⍨ partitioned at
1 at the first element
, and then
2≠/ where subsequent pairs differ
⊢ in the argument

MATL, 8 7 bytes
Removed 1 byte thanks to @Suever
ly&Y'Y{

Works with integers/floats/chars/booleans/unicorn points/other imaginary inputs.
For booleans, inputs are T/F, outputs are 1/0.
Try it online!

Grouped and Repeated
ly&Y'Y{
l          % push 1 onto the stack
 y         % duplicate the input
  &Y'      % run-length encoding (secondary output only)
     Y{    % break up array into cell array of subarrays

Brachylog, 13 bytes
:{s.dl1}fs.c?

Warning: this is extremely inefficient, and you will understand why in the explanation.
This expects a list (e.g [1:1:2:2:2]) as input. The elements inside the list can be pretty much anything.
Explanation
:{     }f       Find all ordered subsets of the Input with a unique element in them
  s.                Output is a subset of the input
    dl1             Output minus all duplicates has a length of 1 (i.e. one unique value)
         s.     Output is an ordered subset of those subsets
           c?   The concatenation of those subsets is the Input

This works only because of the way s - Subset unifies: the smallest sets are at the end. Therefore the first thing it finds that concatenates to the Input are the longest runs, e.g. [[1:1]:[2:2:2]] and not for example [[1:1]:[2:2]:[2]].

Python 2, 43 bytes
p=-1
for x in input():print"|"[:x^p],x,;p=x

Works on lists of booleans. Example:
>> [True,True,False,False,False,True,False,True,False]
 True  True | False  False  False | True | False | True | False

Iterates through the input list, storing the last seen element. A separator bar is printed before each element that is different than the previous, checked as having bitwise xor ^ of 0. Initializing p=-1 avoids a separator before the first element.

Too bad groupby is such a pain...

CJam, 9 bytes
Two solutions:
{e`:a:e~}
{e`{(*}%}

Test it here.
Explanation
e`   e# Run-length encode (gives a list of pairs [run-length value]).
:a   e# Wrap each pair in a singleton list.
:e~  e# Run-length decode each list.

Or
e`   e# Run-length encode.
{    e# Map this block over each pair...
  (  e#   Pull out the run length.
  *  e#   Repeat the list containing only the value that many times.
}%

Haskell, 22 bytes
import Data.List
group

There's a built-in. Works on any type that supports equality.

Any reason why this is community wiki?

@Fatalize Anyone who knows Haskell could have posted it.

That's noble but since no one else is doing it, why don't you ask about that on meta?

Zsh, 28 bytes
>$1;for i {mv * $i&&echo;ls}

Try it online!

>$1: create the file named the first argument
for i {}: for each argument:

mv * $i: attempt to move all files in the current directory to the current item
If these are the same (i.e. this item is the same as the last), this will fail with mv: 'X' and 'X' are the same file.
&&: if this doesn't fail (i.e. this item is not the same as the last)

echo: print a blank line to separate the runs

ls: then list all the files in the current directory. In effect, this just prints $i.

K (ngn/k), 12 bytes
{(&~~':x)_x}

Try it online!
A relatively straightforward "idiom". A (verbose) q version is:
{(where differ x)cut x}

Husk, 1 byte
g

Try it online for all the integer test-cases, or here for the "True/False" one
From the Husk Wiki:
g group  Group equal adjacent values

Husk, 10 bytes
CẊ-Θ:W≠¹L¹

Try it online!
Without g...
From the Husk wiki:
C            Cut off sublists of input, in lengths given by:
 Ẋ             Map over pairs of adjacent values:
  -              Subtract first argument from second
                 (so Ẋ- = differences)
   Θ           Prepends a falsy value (here = zero) to
    :   L¹     Append the length of the input to
     W≠¹       Indices of input that are not equal to their successor

JavaScript (Node.js), 32 bytes
s=>s.replace(/(.)(?!\1)/g,'$1 ')

Try it online!
Support char

Ruby, 24 bytes
In ruby Array instances have built-in method group_by
So solution will be:
a.group_by{|x| x}.values

ListSharp, 134 bytes
STRG l = READ[<here>+"\\l.txt"]
[FOREACH NUMB IN 1 TO l LENGTH-1 AS i]
{
[IF l[i] ISNOT l[i-1]]
STRG o=o+"\n"
STRG o=o+l[i]
}
SHOW = o

ListSharp doesnt support functions so the array is saved in a local file called l.txt

C#, 117 bytes
void f(List<String>m){Console.Write(m[0]+String.Join("",m.GetRange(1,m.Count()-1).Select((i,j)=>i==m[j]?i:"\n"+i)));}

ungolfed (not really)
    public static void f(List<String>m)
    {
        Console.Write(m[0]+String.Join("",m.GetRange(1,m.Count()-1).Select((i,j)=>i==m[j]?i:"\n"+i)));
    }

Pyth, 36 35 bytes
VQIqNk=hZ).?=+Y]*]kZ=Z1=kN;t+Y]*]kZ

Test link
Edit: explanation:
                                      standard variables: Y=[], Z=0, k='', Q=input
VQ                                    iterate over input
  IqNk                                if the current entity is equal to k:
      =hZ)                            increase Z.
          .?                          else:
               ]*]kZ                  list of length Z filled with k
            =+Y                       add it to Y
                    =Z1               set Z to 1
                       =kN            set k to the current entity
                          ;           end loop
                              ]*]kZ   list of length Z filled with k
                            +Y        add it to Y
                           t          implicitly print the tail of Y (removing the first element)

Pyth, 9 7 bytes
mr9]dr8

Credit to @LeakyNun for 2 byte!
Explanation:
             input
     r8      run-length decode
m            for each...
   ]d        ...treat each run as standalone encoded form...
 r9          ...decode
             print

Old answer, 12 bytes
hf.Am!t{dT./

Forgot about run length built-in, but I think this is an okay approach, so I kept it.
Explanation:
                input
          ./    all possible partitions
 f       T      filter by...
  .A            ...whether all groups of integers...
    m!t{d       ...have length one after deduplication
h               get the first element (first one has no adjacent [1,1] and [1])
                print

This is 7 bytes

@LeakyNun Oh right! That's cool.

I believe this works for 6.

@FryAmTheEggman Nice abuse of m.

@FryAmTheEggman Wow, I don't understand o.O

It's a trick to rld slightly more efficiently. When you rle you get a list with elements like [repetitions, value]. Reversing that and then splatting it over the map function results in: m<value><repetitions> which returns the list we want.

@FryAmTheEggman Wow, so that's how a higher-order function interacts with a function suffix! I've always wanted to figure that out.

Retina, 24 22 bytes
2 bytes thanks to Martin Ender.
A 15-byte answer already exists, so this is just another approach which costs more bytes.
S-`(?<=(\d+)) (?!\1\b)

Try it online!
It splits on spaces whose preceding number differ from the proceeding.
This is a demonstration of lookarounds.

C, 88 77 bytes
Moved the strmcmp inside the printf saving 11 bytes
f(char**a){*a++;char*x;for(;*a;x=*a++)printf(strcmp(*a,x)?"\n%s ":"%s ",*a);}

Usage:
f(char**a){*a++;char*x;for(;*a;x=*a++)printf(strcmp(*a,x)?"\n%s ":"%s ",*a);}
main(c,v)char**v;{f(v);}

Sample Input:
(command line parameters)
1 1 1 1 2 2 2 2 3 3 3 3 4 5 6 7777

Sample Output:
1 1 1 1
2 2 2 2
3 3 3 3
4
5
6
7777

Tested on:
gcc 4.4.7 (Red Hat 4.4.7-16)  - OK
gcc 5.3.0 (Cygwin)            - Segmetation Fault
gcc 4.8.1 (Windows)           - OK

I'm trying to fix the 5.3.0 Segmetation Fault.
88 Version
f(char**a){*a++;char*x;for(;*a;x=*a++)strcmp(*a,x)?printf("\n%s ",*a):printf("%s ",*a);}

Java 134 bytes
void a(String[]a){int i=0,l=a.length;for(;i<l-1;i++)System.out.print(a[i]+((a[i].equals(a[i+1]))?" ":"\n"));System.out.print(a[l-1]);}

iterates through, and decides whether to separate with a new line or a space.

for starter you could remove public and static keywords. also you could remove curly brackets in for loop

Done @user902383

05AB1E, 13 bytes
¬svyÊi¶}yðJ?y

Explained
¬s             # push first element of list to stack and swap with input
  v            # for each X in input
   yÊi¶}       # if X is different from last iteration, push a newline
        yðJ?   # push X followed by a space to stack and join stack to string
            y  # push X to stack for next iterations comparison

Should work for any list.
Tested on int and char.
Try it online

Swift, 43 bytes
var p=0;i.map{print($0==p ?"":",",$0);p=$0}

Assumes i to be an array of equatable objects; works for anything from ints to strings to custom objects. Kind of cheeky in that the output contains lots of newlines, but making that prettier would cost bytes.
Prettier, ungolfed version:
var prev = Int.max // unlikely to be the first element, but not the end of the world if it happens to be.
i.map { n in
    print(n == prev ? " " : "\n•", n, terminator: "")
    prev = n
}

This version prints every group on a new line at the expense of more code.
Ideas for Improvement
i.reduce(0){print($0==$1 ?"":"•",$1);return $1}

This version has 47 bytes, but it's a different approach, so maybe there's something to optimize away there? The biggest problem is the return statement.

Jelly, 2 bytes
Œg

Try it online!
Alternatively, a non-builtin approach:
Ik

Try it online!

"Alternatively, a non-builtin approach". Nonsense. Even if you expand every single step to the most basic of operations, Jelly will always be a builtin.

@EasyasPi Yeah, but the same applies for all languages. str.replace in Python is just as much a builtin as I in Jelly. The second answer just shows that there is a way to do the task without a single command that does what’s asked for

It was a joke, but yeah, you are right.

Vyxal, 1 byte
Ġ

Try it Online!
Ah yes, the power of triviality.

PowerShell, 49 bytes
$args|%{,$a*!($i=$_-in$a-or!$a)
$a=$a*$i+,$_}
,$a

Try it online!

Thunno 2, 1 byte
ġ

Try it online!

Befunge, 47 41 38 Bytes
&:&:.92pv.<
g29:&:-1_@|!-
92p25*,.^ >:

Input format:
number_of_values-1         values (separated by a space)

You may test the code here

Previous version with explanations :
&:&:.00pv.<
g00:&:-1_@|!-
v*52p00:  <
>,.     ^

The interpet's cursor follows the symbols > v < ^. If the cursor is at the end of a line and is going to the right, it will loop back to the beginning (same principle for other directions).
&: : Gets the first input put it to the stack and duplicates it (to the stack)
&:.00pv : Gets the second input, prints it and saves it into the code, at the coordinates (0,0) [erasing the first '&']. Then, go down
_ : Test if last value of the stack (the number of values) is equals to 0 and set the cursor's direction to the right if it is, to the left if it isn't
1-: : Removes 1 from the number of values
&:00g-!| : Compares the next input with the one stored at (0,0). Set the cursor's direction to up if they are equal, to down if they aren't
. : Displays a numeric value
:00p52*,. : Override the last saved value to the current value, then displays \n (ascii 10, 5*2) followed by the value
@ : Terminates the program

Javascript (using external library) (178 bytes)
(s)=>_.From(s).Aggregate((t,e)=>{if(0===t.Items.length)return t.Items.push([e]),t;var s=t.Items[t.Items.length-1];return s[0]===e?(s.push(e),t):(t.Items.push([e]),t)},{Items:[]})

Disclaimer: I am using a library I wrote to implement LINQ from C# into JS. It didn't exactly help me win but oh well

TSQL, 132 bytes
This is a little different from the other answers - sql doesn't have arrays, the obvious input for sql is a table.
Golfed:
DECLARE @ table(i int identity, v varchar(20))
INSERT @ values(1),(1),(1),(3),(3),(1),(1),(2),(2),(2),(1),(1),(3)

SELECT REPLICATE(v+' ',COUNT(*))FROM(SELECT i,i-row_number()over(partition
by v order by i)x,v FROM @)z GROUP BY x,v ORDER BY max(i)

Ungolfed:
DECLARE @ table(i int identity, v varchar(20))
INSERT @ values(1),(1),(1),(3),(3),(1),(1),(2),(2),(2),(1),(1),(3)

SELECT
  REPLICATE(v+' ',COUNT(*))
FROM
  (
     SELECT
       i,
       i-row_number()over(partition by v order by i)x,
       v
     FROM @
  )z
GROUP BY
  x,v
ORDER BY
  max(i)

Fiddle

Perl 5 - 39 Bytes
print$_.($/)[$_ eq@a[++$-]]for@a=sort@a

sed, 33 23+1=24 bytes
s/([^ ]+)( \1)* */&\n/g

It needs the -r option.
Usage example:
$ echo '1 1 1 2 2 3 3 3 4 9 9' | sed -r 's/([^ ]+)( \1)* */&\n/g'
1 1 1
2 2
3 3 3
4
9 9

Pyke, 2 bytes (non competitive)
Only supports integers
$f

Try it here!
split_at(input, delta(input))

Added split_at node, splits input when 2nd arg is truthy

JavaScript (ES6), 56
Input: array of numbers or strings
Output: array of arrays
First time ever using exact comparisong in golfed code
a=>a.map(x=>x!==p?o.push(g=[p=x]):g.push(x),p=o=g=[])&&o

Clojure, 19 bytes
#(partition-by + %)

It's a built-in, but it takes a mapping function.  In this case, + serves as an identity function.

05AB1E, 1 byte
γ

Builtins ftw ¯\_(ツ)_/¯
Try it online or verify all test cases.
Here an alternative without builtins (6 bytes):
üÊ0šÅ¡

Try it online or verify all test cases.
Explanation:
γ       # Split the (implicit) input-list into chunks of equal adjacent values
        # (after which the resulting list of lists is output implicitly)

ü       # For each overlapping pair of values in the (implicit) input-list:
 Ê      #  Check that they are NOT equal (0 if equal; 1 if not)
  0š    # Prepend a 0 to this list
    Å¡  # Split the (implicit) input-list at the truthy indices
        # (after which the resulting list of lists is output implicitly)

C (gcc), 54 bytes
f(char*s){printf("%c%c",*s,*s-s[1]?10:32),*++s&&f(s);}

Try it online!
or 55 bytes iteratively
f(char*s){while(printf("%c%c",*s,*s-s[1]?10:32),*++s);}

Try it online!

Charcoal, 35 bytes
≔⁰ξ≔⁺θ θＦ⊖Ｌθ«¿¬⁼§θι§θ⊕ι«Ｐ✂θξ⊕ι↓≔⊕ιξ

Try it online! Link is to verbose version of code.
Input as a list of characters.

Brachylog v2, 1 byte
ḅ

Try it online!
Less built-in and far, far slower:
Brachylog v2, 4 bytes
~c=ᵐ

Try it online!
~c      The output is a partitioning of the input (with as few partitions as possible)
   ᵐ    such that each partition
  =     contains only one unique element.

Factor, 23 bytes
[ [ ] group-by values ]

Try it online!
[                        ! begin quotation (anonymous function)
  [ ]                    ! A quotation that returns its input
      group-by           ! group adjacent elements with a ( key -- value ) quotation
               values    ! obtain the values of an associative array
                      ]  ! end quotation

Factor actually has a combinator called monotonic-split that can do this more directly, but it's more bytes.

Arturo, 16 bytes
$=>[chunk&=>[&]]

Try it

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

Attempt This Online!
Built-in solution.

Japt, 2 bytes
Can handle all data types.
òÀ

Try it
òÀ     :Implicit input of array
ò      :Partition between elements
 À     :That are not strictly equal

Java 8, 83 bytes
s->{char a=0;for(char b:s.toCharArray())System.out.print((a<1|a==b?"":" ")+(a=b));}

Try it online!

Alternative solution using Streams (85 bytes) :
s->s.chars().reduce(0,(a,b)->{System.out.print((a<1|a==b?"":" ")+(char)b);return b;})

Don't hesitate to ask if this needs any explanation!

F#, 196 bytes
let g x=Seq.foldBack(fun n c->Seq.tryHead c|>function|None->[n,1];|Some i when fst i<>n->(n,1)::c;|_->Seq.head c|>fun h->(fst h,(snd h)+1)::(List.tail c))x []|>Seq.map(fun(i,c)->Seq.replicate c i)

Try it online! (includes character and boolean tests cases in the footer, but others must be commented out first).
Essentially, it counts the number of sequential items in the collection, then creates a new collection of each item replicated for their respective counts.

TypeScript (Type System) 4.9.5 - 156 121 Bytes

35 Bytes thanks to ASCII-only

type F<X,Y=[],Z=any>=X extends[infer A,...infer B]?[Z]extends[A]?Y extends[...infer C,infer D]?F<B,[...C,[...D, A]],A>:F<B,[...Y,[A]],A>:F<B,[...Y,[A]],A>:Y

Un-golfed version
type DistinctGroups<
  Input extends number[],
  Output extends number[][] = [],
  LastElement extends any = never
>=
  Input extends [infer First, ...infer Rest] ?
    [LastElement] extends [First] ?
      Output extends [...infer Head, infer Tail] ?
        DistinctGroups<Rest, [...Head, [...Tail, First]], First> :
        DistinctGroups<Rest, [...Output, [First]], First>
    : DistinctGroups<Rest, [...Output, [First]], First>
  : Output

Try it on the TypeScript playground!

121?

@ASCII-only just updated!

missing byte count?! (you might've also forgotten to update the code in the snippet, and the explanation)

J-uby, 15 bytes
Returns an Enumerator.
:slice_when+:!=

Attempt This Online!

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


text:
Output the happy primes
Input: n
Output: A list of length n, with each element being the nth happy prime.
Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number either equals 1, or it loops endlessly in a cycle which does not include 1. A happy number is a number for which this process ends in 1.
A happy prime is a number that is both happy and prime.
For example, if the input is 5, the output should be the list
[7, 13, 19, 23, 31]
Shortest answer wins!

Welcome to PPCG! The challenge should include a definition of "happy prime" in the text, and optionally a link

Happy number/prime: https://en.wikipedia.org/wiki/Happy_number#Happy_prime. I think the challenge should include that information.

I have edited appropriately :)

This just combines a primality test with testing for happy numbers. I won't cast a supervote, but IMO it is a duplicate of the second question, since primality testing is standard and often offered as a builtin.

I voted to close as a dupe of the happy number challenges. Besides the dupe issue, challenges to check for the AND of two unrelated conditions usually split into checking each condition separately, which feels like two separate challenges.

Welcome to PPCG! I agree with the close vote for the reasons xnor stated (but won't use the mod hammer either). But please don't be disheartened by that. Writing good challenges is hard and knowing what has already been done by the community also is. You can post challenge ideas in the sandbox where you can get feedback from experienced users and iron out the details before the challenge goes live. I hope you'll stick around! :)

Don't we close questions as subset? But this case is a superset..

@LeakyNun I think it's more of a case of whether the subset or the superset makes more sense

Thanks for the feedback! I'll try not to be too brokenhearted over this one :P. The sandbox sounds very useful, I'll use that in the future.


text:
Find the nth decimal of pi
There are already 30 challenges dedicated to pi but not a single one asks you to find the nth decimal, so...
Challenge
For any integer in the range of 0 <= n <= 10000 display the nth decimal of pi.
Rules

Decimals are every number after 3.
Your program may be a function, or a full program
You must output the result in base 10
You may get n from any suitable input method (stdin, input(), function parameters, ...), but not hardcoded
You may use 1-based indexing if that's native to your language of choice
You don't have to deal with invalid input (n == -1, n == 'a' or n == 1.5)
Builtins are allowed, if they support up to at least 10k decimals
Runtime doesn't matter, since this is about the shortest code and not the fastest code
This is code-golf, shortest code in bytes wins

Test cases
f(0)     == 1
f(1)     == 4 // for 1-indexed languages f(1) == 1
f(2)     == 1 // for 1-indexed languages f(2) == 4
f(3)     == 5
f(10)    == 8
f(100)   == 8
f(599)   == 2
f(760)   == 4
f(1000)  == 3
f(10000) == 5

For reference, here are the first 100k digits of pi.

Built-ins? e.g. str(pi())[n+2]

What about this?

@primo Allowed. This is to find the shortest code in each language

@primo how it is possible to generate an infinite array with codes like pi() and then get the n+2th digit is beyond me.

@LeakyNun Related, but not a dupe imo.

@LeakyNun that's very nearly a valid answer in Sage.

The closest dupe targets IMO are Computing truncated digit sums powers of pi (overloads the parameter, or it would just be a finite difference applied to this challenge), Transmit pi precisely (adds an index and suppresses some printing), and Pi window encryption.

May we use base 16?

@Adám no, the result must be output in base 10

@Suever ofcourse! That rule is just to point out that 10k is the minimum that your program should be able to handle

I suggest adding f(599) to the test cases, as it can be easy to get it wrong (you need about 3 decimals extra precision).

Also f(760) = 4, which begins the sequence 49999998, is easy to round incorrectly.

@aditsu & Anders, edited them in, thanks!

Can we use external files?

@OldBunny2800 No, sorry.

05AB1E, 3 bytes
žs¤

Explained
žs   # push pi to N digits
  ¤  # get last digit

Try it online
Uses 1-based indexing.
Supports up to 100k digits.

Pi to n digits doesn't round?

@busukxuan No. It used a predefined constant of pi to 100k digits and retrieves N of them.

@Emigna That is very handy. Good solution.

Short and Sharp, PCG at its best

Python 2, 66 bytes
n=input()+9
x=p=5L**7
while~-p:x=p/2*x/p+10**n;p-=2
print`x/5`[-9]

Input is taken from stdin.

Sample Usage
$ echo 10 | python pi-nth.py
8

$ echo 100 | python pi-nth.py
8

$ echo 1000 | python pi-nth.py
3

$ echo 10000 | python pi-nth.py
5

Be careful about using n in the algorithm... output for 599 should be 2, not 1. Also you may want to specify that you're using python 2.

@aditsu updated. Confirmed for all n ≤ 1000.

If you take n to be the input plus 9, you can avoid parens.

The first few digits generated by this algorithm are ‘3.141596535897932…’ which is missing a ‘2’ between places 5 and 6. Why? Because that’s when Python 2’s `` operator starts appending an L to the string.

@AndersKaseorg The L is present in the very first iteration - demo. True for both 32 and 64-bit versions of CPython.

@primo That is not what I get on 64-bit CPython (I tried 2.3.7, 2.4.6, 2.5.6, 2.6.9, 2.7.6, and 2.7.12), but I’ll accept that it works on 32-bit CPython.

@AndersKaseorg you're right, 64-bit on Linux did have an issue. Should now be correct.

Bash + coreutils, 60 49 bytes
echo "scale=10100;4*a(1)"|bc -l|tr -d '\\\n'|cut -c$(($1+2))
bc -l<<<"scale=$1+9;4*a(1)-3"|tr -dc 0-9|cut -c$1

Improved by Dennis. Thanks!
The index is one-based.

Python 2, 73 71 73 bytes
thanks to @aditsu for increasing my score by 2 bytes
Finally an algorithm that can complete under 2 seconds.
n=10**10010
a=p=2*n
i=1
while a:a=a*i/(2*i+1);p+=a;i+=1
lambda n:`p`[n+1]

Ideone it!
Uses the formula pi = 4*arctan(1) while computing arctan(1) using its taylor series.

Quite speedy. 1-indexing is not native to python, though. Last I recall (admittedly I've been inactive for a while), consensus was that functions need to be defined, e.g. f=lambda n:....

Almost every lambda here are anonymous (you can search answers in Python in this site)

Relevant meta post. Seems to be in violation of Rule 1 and 3 (after running your code, there is no way to capture the function reference; the function definition would need to be typed out for each input ((lambda n:`p`[n+1])(1), (lambda n:`p`[n+1])(2), ...).

You can't run the code directly. It is akin to placing import statements beforehand, just that this makes some global variables beforehand.

i=3 while a:a=i/2*a/i;p+=a;i+=2 for 4.

@primo that looks like your answer xd

Same alg: Leibniz Series (derived from arctan(1)), Euler Transform (Appendix A). Counting backwards is self-correcting, and slightly shorter.

MATL, 11 10 bytes
1 byte saved thanks to @Luis
YPiEY$GH+)

This solution utilizes 1-based indexing
Try it Online
All test cases
Explanation
YP  % Pre-defined literal for pi
iE  % Grab the input and multiply by 2 (to ensure we have enough digits to work with)
Y$  % Compute the first (iE) digits of pi and return as a string
G   % Grab the input again
H+  % Add 2 (to account for '3.') in the string
)   % And get the digit at that location
    % Implicitly display the result

@LuisMendo Oh yea I guess the output is already a string. Doh!

@LuisMendo Oh I never actually thought of that. I always use YP in my testing of the symbolic toolbox

Is YP actually allowed? The question says it's allowed if it supports <=10k digits

@Suever OP stated "up to" rather than "at least". To my understanding that means supporting >10k is forbidden.

@Suever Yeah, I think I may be, tho I can't resist doing it lol. I deleted my Sage answer just because of that.

@Suever Oh nice! I'll un-delete it :-)

Mathematica 30 bytes
RealDigits[Pi,10,1,-#][[1,1]]&

f=%

f@0
f@1
f@2
f@3
f@10
f@100
f@599
f@760
f@1000
f@10000

1
4
1
5
8
8
2
4
3
5

CJam, 32
7e4,-2%{2+_2/@*\/2e10005+}*sq~)=

Try it online (it's a bit slow)

Sage, 32 25 bytes
lambda d:`n(pi,9^5)`[d+2]

My first answer in a language of this kind.
n rounds pi to 17775 digits.

You need the print call, or else this is a snippet which only works in the REPL.

This works for (theoretically) any input: `lambda d:`n(pi,digits=d+5)`[-4]`

@Mego there aren't "99999" runs?

@Mego busukxuan is right, that fails as early as 760, 761, 762, 763.

Then bump up the extra digits: `lambda d:`n(pi,digits=d+9)`[-8]`

@Mego but then there will be even longer "9" runs. I'm not sure if doubling the length can make it universal, but I think not even that can do it, due to the Infinite Monkey Theorem: https://en.wikipedia.org/wiki/Infinite_monkey_theorem

@busukxuan If you model the uncomputed digits of π as random, you certainly expect arbitrarily long runs of 9s (and we have no reason to expect the real π to be any different, though we have not proven this), but you only expect a run of 9s as long as its position with vanishingly small probability (though again, we haven’t proven that the real π doesn’t behave unexpectedly). We have found runs of at least nine 9s, which I think is enough to break the [-8] proposal.

J, 19 15 bytes
10([|<.@o.@^)>:

Takes an integer n and outputs the nth digit of pi. Uses zero-based indexing. To get the nth digit, compute pi times 10n+1, take the floor of that value, and then take it modulo 10.
Usage
The input is an extended integer.
   f =: 10([|<.@o.@^)>:
   (,.f"0) x: 0 1 2 3 10 100 599 760 1000
   0 1
   1 4
   2 1
   3 5
  10 8
 100 8
 599 2
 760 4
1000 3
   timex 'r =: f 10000x'
1100.73
   r
5

On my machine, it takes about 18 minutes to compute the 10000th digit.
Explanation
10([|<.@o.@^)>:  Input: n
             >:  Increment n
10               The constant n
           ^     Compute 10^(n+1)
        o.@      Multiply by pi
     <.@         Floor it
   [             Get 10
    |            Take the floor modulo 10 and return

Mathematica, 23 21 bytes
⌊10^# Pi⌋~Mod~10&

SageMath, 24 bytes
lambda n:int(10^n*pi)%10

@LLlAMnYP I tried that, but Mathematica seems to require a space between Pi and ⌋ (or between # and ⌋ if the multiplication is flipped), so the saving disappears.

Actually it works in the Mathematica Online (I had been using the console version), so I’ll take it, I guess.

These should be separate answers. Though they use the same strategy, they are nowhere near the same language.

@Mego The policy I found does not say answers in different languages cannot count as very similar. (The answer suggesting that was not accepted.) Are you referring to another policy or just a preference?

Clojure, 312 bytes
(fn[n](let[b bigdec d #(.divide(b %)%2(+ n 4)BigDecimal/ROUND_HALF_UP)m #(.multiply(b %)%2)a #(.add(b %)%2)s #(.subtract % %2)](-(int(nth(str(reduce(fn[z k](a z(m(d 1(.pow(b 16)k))(s(s(s(d 4(a 1(m 8 k)))(d 2(a 4(m 8 k))))(d 1(a 5(m 8 k))))(d 1(a 6(m 8 k)))))))(bigdec 0)(map bigdec(range(inc n)))))(+ n 2)))48)))48)))

So, as you can probably tell, I have no idea what I'm doing. This ended up being more comical than anything. I Google'd "pi to n digits", and ended up on the Wikipedia page for the Bailey–Borwein–Plouffe formula. Knowing just barely enough Calculus(?) to read the formula, I managed to translate it into Clojure.
The translation itself wasn't that difficult. The difficulty came from handling precision up to n-digits, since the formula requires (Math/pow 16 precision); which gets huge really fast. I needed to use BigDecimal everywhere for this to work, which really bloated things up.
Ungolfed:
(defn nth-pi-digit [n]
  ; Create some aliases to make it more compact
  (let [b bigdec
        d #(.divide (b %) %2 (+ n 4) BigDecimal/ROUND_HALF_UP)
        m #(.multiply (b %) %2)
        a #(.add (b %) %2)
        s #(.subtract % %2)]
    (- ; Convert the character representation to a number...
      (int ; by casting it using `int` and subtracting 48
         (nth ; Grab the nth character, which is the answer
           (str ; Convert the BigDecimal to a string
             (reduce ; Sum using a reduction
               (fn [sum k]
                 (a sum ; The rest is just the formula
                       (m
                         (d 1 (.pow (b 16) k))
                         (s
                           (s
                             (s
                               (d 4 (a 1 (m 8 k)))
                               (d 2 (a 4 (m 8 k))))
                             (d 1 (a 5 (m 8 k))))
                           (d 1 (a 6 (m 8 k)))))))
               (bigdec 0)
               (map bigdec (range (inc n))))) ; Create an list of BigDecimals to act as k
           (+ n 2)))
      48)))

Needless to say, I'm sure there's an easier way to go about this if you know any math.
(for [t [0 1 2 3 10 100 599 760 1000 10000]]
  [t (nth-pi-digit t)])

([0 1] [1 4] [2 1] [3 5] [10 8] [100 8] [599 2] [760 4] [1000 3] [10000 5])

I realized later that the standard operators actually work on big decimals, so the shortcuts at the top are unnecessary. I mount fix this at some point. That'll probably knock off ~50 bytes.

Clojure, 253 bytes
(defmacro q[& a] `(with-precision ~@a))(defn h[n](nth(str(reduce +(map #(let[p(+(* n 2)1)a(q p(/ 1M(.pow 16M %)))b(q p(/ 4M(+(* 8 %)1)))c(q p(/ 2M(+(* 8 %)4)))d(q p(/ 1M(+(* 8 %)5)))e(q p(/ 1M(+(* 8 %)6)))](* a(-(-(- b c)d)e)))(range(+ n 9)))))(+ n 2)))

Calculate number pi using this formula. Have to redefine macro with-precision as it's used too frequently.
You can see the output here: https://ideone.com/AzumC3
1000 and 10000 takes exceeds time limit used on ideone, shrugs

Smalltalk – 270 bytes
Relies on the identity tan⁻¹(x) = x − x³/3 + x⁵/5 − x⁷/7 ..., and that π = 16⋅tan⁻¹(1/5) − 4⋅tan⁻¹(1/239). SmallTalk uses unlimited precision integer arithmetic so it will work for large inputs, if you're willing to wait!
|l a b c d e f g h p t|l:=stdin nextLine asInteger+1. a:=1/5. b:=1/239. c:=a. d:=b. e:=a. f:=b. g:=3. h:=-1. l timesRepeat:[c:=c*a*a. d:=d*b*b. e:=h*c/g+e. f:=h*d/g+f. g:=g+2. h:=0-h]. p:=4*e-f*4. l timesRepeat:[t:=p floor. p:=(p-t)*10]. Transcript show:t printString;cr

Save as pi.st and run as in the following test cases. Indexing is one based.
$ gst -q pi.st <<< 1
1
$ gst -q pi.st <<< 2
4
$ gst -q pi.st <<< 3
1
$ gst -q pi.st <<< 4
5
$ gst -q pi.st <<< 11
8
$ gst -q pi.st <<< 101
8
$ gst -q pi.st <<< 600
2
$ gst -q pi.st <<< 761
4
$ gst -q pi.st <<< 1001
3
$ gst -q pi.st <<< 10001 -- wait a long time!
5

Python 3, 338 bytes
This implementation is based on the Chudnovsky algorithm, one of the fastest algorithms to estimate pi. For each iteration, roughly 14 digits are estimated (take a look here for further details).
f=lambda n,k=6,m=1,l=13591409,x=1,i=0:not i and(exec('global d;import decimal as d;d.getcontext().prec=%d'%(n+7))or str(426880*d.Decimal(10005).sqrt()/f(n//14+1,k,m,l,x,1))[n+2])or i<n and d.Decimal(((k**3-16*k)*m//i**3)*(l+545140134))/(x*-262537412640768000)+f(n,k+12,(k**3-16*k)*m

Try it online!

JavaScript (Node.js) (Chrome 67+), 75 73 67 63 bytes
n=>`${eval(`for(a=c=100n**++n*20n,d=1n;a*=d;)c+=a/=d+++d`)}`[n]

Try it online!
Using \$\pi/2=\sum_{k=0}^{\infty}k!/(2k+1)!!\$ (same logic used by Leaky Nun's Python answer, but thanks to the syntax of JS that makes this shorter). Input is passed to the function as a BigInt. 2 bytes can be removed if 1-based indexing is used:
n=>`${eval(`for(a=c=100n**n*20n,d=1n;a*=d;)c+=a/=d+++d`)}`[n]

JavaScript (Node.js) (Chrome 67+), 90 89 bytes
n=>`${eval(`for(a=100n**++n*2n,b=a-a/3n,c=0n,d=1n;w=a+b;a/=-4n,b/=-9n,d+=2n)c+=w/d`)}`[n]

Try it online!
Using \$\pi/4=\arctan(1/2)+\arctan(1/3)\$. Input is passed to the function as a BigInt. 2 bytes can be removed if 1-based indexing is used:
n=>`${eval(`for(a=100n**n*2n,b=a-a/3n,c=0n,d=1n;w=a+b;a/=-4n,b/=-9n,d+=2n)c+=w/d`)}`[n]

Java 7, 262 260 bytes
import java.math.*;int c(int n){BigInteger p,a=p=BigInteger.TEN.pow(10010).multiply(new BigInteger("2"));for(int i=1;a.compareTo(BigInteger.ZERO)>0;p=p.add(a))a=a.multiply(new BigInteger(i+"")).divide(new BigInteger((2*i+++1)+""));return(p+"").charAt(n+1)-48;}

Used @LeakyNun's Python 2 algorithm.
Ungolfed & test code:
Try it here.
import java.math.*;
class M{
  static int c(int n){
    BigInteger p, a = p = BigInteger.TEN.pow(10010).multiply(new BigInteger("2"));
    for(int i = 1; a.compareTo(BigInteger.ZERO) > 0; p = p.add(a)){
      a = a.multiply(new BigInteger(i+"")).divide(new BigInteger((2 * i++ + 1)+""));
    }
    return (p+"").charAt(n+1) - 48;
  }

  public static void main(String[] a){
    System.out.print(c(0)+", ");
    System.out.print(c(1)+", ");
    System.out.print(c(2)+", ");
    System.out.print(c(3)+", ");
    System.out.print(c(10)+", ");
    System.out.print(c(100)+", ");
    System.out.print(c(599)+", ");
    System.out.print(c(760)+", ");
    System.out.print(c(1000)+", ");
    System.out.print(c(10000));
  }
}

Output:
1, 4, 1, 5, 8, 8, 2, 4, 3, 5

Maple, 24 bytes
 trunc(10^(n+1)*Pi)mod 10

Test cases:
> f:=n->trunc(10^(n+1)*Pi)mod 10;
> f(0);
  1
> f(1);
  4
> f(2);
  1
> f(3);
  5
> f(10);
  8
> f(100);
  8
> f(599);
  2
> f(760);
  4
> f(1000);
  3
> f(10000);
  5