text:
GET your dubs together
On 4chan, a popular game is get. Every post on the site gets a sequential post ID. Since you can't influence or determine them, people try to guess (at least a part of) their own post number, usually the first few digits. Another version of the game is called dubs, and it's goal is to get repeating digits at the end of the number (i.e 1234555).
Your task, if you wish to accept it, is to write a program that takes a post id as input (standard integer, you can assume below 2^32), and returns how many repeating digits are on the end.
Rules

Standard loopholes are disallowed.
The program can be a function, full program, REPL command, whatever works, really, as long as no external uncounted code/arguments are needed to run it.
Input can come from STDIN, function arguments, command line argument, file, whatever suits you.

Test Cases
Input: 14892093
Output: 1

Input: 12344444
Output: 5

Input: 112311
Output: 2

Input: 888888
Output: 6

Input: 135866667 //Post number I got on /pol/ few days ago, rip
Output: 1

Are we allowed to take input as string?

@DeadPossum I would assume that's allowed, since you get a string anyway if you read the input from STDIN, command-line argument or file (which are all admissible input methods).

Can we assume that the input will be greater than 0?

@MartinEnder Yes

Upvote for the dubs game! Check'em!

@sagiksp That goes against our default. Is that really your intent?

@Mego Nevermind you can use it all

Could someone make a solution that actually uses 4chan and some URL-related feature?

@ckjbgames What would it be, the user gets a url and has to regex the number out first? I'm thinking maybe a comment finder by ID would work (Looks through all threads with sequential id to find a specific id comment, because you can't index by comment in the 4chan api), but for this challeange it just won't work.

Disappointed: The question ID on SE does not have dubs.

@NumLock That would have been so perfect :D

Mathematica, 29 bytes
How about an arithmetic solution?
IntegerExponent[9#+#~Mod~10]&

I'm very pleased to see that this beats the straight-forward Mathematica approach.
Explanation
The code itself computes 9*n + n%10 and then finds the largest power of 10 that divides the input, or in other words, counts the trailing zeros. We need to show if n ends in k repeated digits, that 9*n + n%10 has k trailing zeros.
Rep-digits are most easily expressed mathematically by dividing a number like 99999 (which is 105-1) by 9 and then multiplying by the repeated digit. So we can write n = m*10k + d*(10k-1)/9, where m ≢ d (mod 10), to ensure that n doesn't end in more than k repeated digits. Note that d = n%10.
Let's plug that into our formula 9*n + n%10. We get 9*m*10k + d*(10k-1) + d. The d at the end is cancelled, so we're left with: 9*m*10k + d*10k = (9*m + d)*10k. But 9 ≡ -1 (mod 10), so 9*m + d ≡ d - m (mod 10). But we've asserted that m ≢ d (mod 10) and hence d - m ≢ 0 (mod 10).
In other words, we've shown that 9*m + d is not divisible by 10 and therefore, the largest power of 10 that divides 9*n + n%10 = (9*m + d)*10k is k, the number of trailing repeated digits.
As a bonus, this solution prints the correct result, ∞, for input 0.

It's times like this that I wish this site supported MathJax; bold formulae are not as nice as typeset ones. It's nice that you took the time to write the exponents superscript though.

@wizzwizz4 I used to use code formatting, but I've found that bold (which is usually used by Dennis) is a bit more readable than that. But agreed, it's not as nice as MathJax.

Retina, 9 bytes
&`(.)\1*$

Try it online!
Counts the number of overlapping matches of (.)\1*$ which is a regex that matches a suffix of identical characters.

This must be a meme: you and your regex

I need to learn all of these modifiers - I would have just gone for (.)(?=\1*$).

@DownChristopher he literally made a regex-based language, this goes beyond meme material c:

@Neil If it's any consolation, my first attempt was (?=(.)\1*$) (so basically the same as yours).

Yes it is, thanks!

Brachylog, 4 bytes
ẹḅtl

Try it online!
Explanation
ẹ       Elements: split to a list of digits
 ḅ      Blocks: group consecutive equal digits into lists
  t     Tail: take the last list
   l    Length: Output is the length of that last list

If ḅ worked directly on integers (and I'm not sure why I didn't implement it so that it does), this would only be 3 bytes as the ẹ would not be needed.

Python 2, 47 41 bytes
lambda s:len(`s`)-len(`s`.rstrip(`s%10`))

Try it online!
36 bytes - For a more flexible input
lambda s:len(s)-len(s.rstrip(s[-1]))

Try it online!

Wow. I gotta learn builtins more attentively. +1

@DeadPossum dir(object) is our friend c:

BTW we are not allowed to take string as input. "If your method of input automatically returns strings then sure, but you cannot assume that the input will be provided as strings." :C

@DeadPossum I think that the author changed his mind about that. The comment seems to have been deleted.

Javascript (ES6), 55 52 32 30 bytes
a=>a.match`(.)\\1*$`[0].length

Saved 19 bytes thanks to @MartinEnder by replacing the regex
Saved 2 bytes thanks to @user81655 using tagged templates literals

Using a regex to match the last group of the last digit
Note: First time posting. Do not hesitate to make remarks.
f=a=>a.match`(.)\\1*$`[0].length

console.log(f("14892093"));//1
console.log(f("12344444"));//5
console.log(f("112311"));//2
console.log(f("888888"));//6
console.log(f("135866667 "));//1

Welcome to PPCG! You can save a lot of bytes by using a backreference instead of filling in the repeated character manually: /(.)\1*$/

Also, unnamed functions are completely fine (unless you need the name for recursive calls for example), so you can save two bytes on the f=.

Good job! This for sure passes review but this could be golfed

@MartinEnder Thanks ! I still have to learn how to golf

@DownChristopher Thanks ! I will try to do better next time

@Weedoze Yeah golfing is really hard but good job

Anonymous functions are allowed, so you can remove the f= from your byte count. :) Also, another trick you could use is tagged template literals. match passes its first argument into RegExp(arg), so you can pass a string and it will turn into a RegExp object. Knowing this, you could call it like match\(.)\1*$`` for one less byte.

@user81655 Thanks ! I am still learning the tricks of golfing

@Weedoze Make sure to explicitly say if it's Javascript ES6 or not (for clarity).

C, 62 56 48 47 bytes
Saved a byte thanks to @Steadybox!
j,k;f(n){for(k=j=n%10;j==n%10;n/=10,k++);k-=j;}

Try it online!

46 bytes

Perl 5, 22 bytes
21 bytes of code + -p flag.
/(.)\1*$/;$_=length$&

Try it online!
/(.)\1*$/ gets the last identical numbers, and then $_=length$& assigns its length to $_, which is implicitly printed thanks to -p flag.

PHP, 47 45 40 bytes
while($argn[-++$i]==$argn[-1]);echo$i-1;

Run with echo <n> | php -nR '<code>
seems a loop is still smaller than my first answer. simply count the chars that are equal to the last. This uses negative string offsets of PHP 7.1.
-5 bytes by Titus. Thanks !

Old answer:
<?=strlen($a=$argv[1])-strlen(chop($a,$a[-1]));

removes from the right every character matching the rightmost character and calculates the difference in the length.

-R and $argn could save 5 bytes.

Python 2, 38 32 bytes
f=lambda n:0<n%100%11or-~f(n/10)

Thanks to @xnor for saving 6 bytes!
Try it online!

05AB1E, 4 bytes
.¡¤g

Try it online!
or as a Test suite
Explanation
.¡    # group consecutive equal elements in input
  ¤   # get the last group
   g  # push its length

CJam, 7 bytes
re`W=0=

Try it online!
Explanation
r   e# Read input.
e`  e# Run-length encode.
W=  e# Get last run.
0=  e# Get length.

Jelly, 5 bytes
DŒgṪL

Try it online!
Explanation
D      # convert from integer to decimal
 Œg    # group runs of equal elements
   Ṫ   # tail
    L  # length

Cubix, 24 19 bytes
)uO)ABq-!wpUp)W.@;;

Note

Actually counts how many of the same characters are at the end of the input, so this works for really big integers and really long strings as well (as long as the amount of same characters at the end is smaller than the maximum precision of JavaScript (around 15 digits in base-10).
Input goes in the input field, output is printed to the output field

Try it here
Explanation
First, let's expand the cube
    ) u
    O )
A B q - ! w p U
p ) W . @ ; ; .
    . .
    . .

The steps in the execution can be split up in three phases:

Parse input
Compare characters
Print result

Phase 1: Input
The first two characters that are executed are A and B. A reads all input and pushes it as character codes to the stack. Note that this is done in reverse, the first character ends up on top of the stack, the last character almost at the bottom. At the very bottom, -1 (EOF) is placed, which will be used as a counter for the amount of consecutive characters at the end of the string. Since we need the top of the stack to contain the last two characters, we reverse the stack, before entering the loop. Note that the top part of the stack now looks like: ..., C[n-1], C[n], -1.
The IP's place on the cube is where the E is, and it's pointing right. All instructions that have not yet been executed, were replaced by no-ops (full stops).
    . .
    . .
A B E . . . . .
. . . . . . . .
    . .
    . .

Phase 2: Character comparison
The stack is ..., C[a-1], C[a], counter, where counter is the counter to increment when the two characters to check (C[a] and C[a-1]) are equal. The IP first enters this loop at the S character, moving right. The E character is the position where the IP will end up (pointing right) when C[a] and C[a-1] do not have the same value, which means that subtracting C[a] from C[a-1] does not yield 0, in which case the instruction following the ! will be skipped (which is a w).
    . .
    . .
. S q - ! w E .
p ) W . . ; ; .
    . .
    . .

Here are the instructions that are executed during a full loop:
q-!;;p) # Explanation
q       # Push counter to the bottom of the stack
        #     Stack (counter, ..., C[a-1], C[a])
 -      # Subtract C[a] from C[a-1], which is 0 if both are equal
        #     Stack (counter, ..., C[a-1], C[a], C[a-1]-C[a])
  !     # Leave the loop if C[a-1]-C[a] does not equal 0
   ;;   # Remove result of subtraction and C[a] from stack
        #     Stack (counter, ..., C[a-1])
     p  # Move the bottom of the stack to the top
        #     Stack (..., C[a-1], counter)
      ) # Increment the counter
        #     Stack (..., C[a-1], counter + 1)

And then it loops around.
Phase 3: Print result
Since we left the loop early, the stack looks like this: counter, ..., C[a-1]-C[a]. It's easy to print the counter, but we have to increment the counter once because we didn't do it in the last iteration of the loop, and once more because we started counting at -1 instead of 0. The path on the cube looks like this, starting at S, pointing right. The two no-ops that are executed by the IP are replaced by arrows that point in the direction of the IP.
    ) u
    O )
. B . . . S p U
. ) . . @ . . .
    > >
    . .

The instructions are executed in the following order. Note that the B) instructions at the end change the stack, but don't affect the program, since we are about to terminate it, and we do not use the stack anymore.
p))OB)@ # Explanation
p       # Pull the counter to the top
        #     Stack: (..., counter)
 ))     # Add two
        #     Stack: (..., counter + 2)
   O    # Output as number
    B)  # Reverse the stack and increment the top
      @ # End the program

C (gcc), 32 29 bytes
f(x){x=x%100%11?1:-~f(x/10);}

This is a port of my Python answer.
This work with gcc, but the lack of a return statement is undefined behavior.
Try it online!

I'm confused, how come you neither pass a pointer, and change the value at the location, or just return the value. This looks like it just changes the local copy, which would make the function unusable, but this works on TIO. You also add 1 to n in the footer, rather then sizeof(int), wouldn't that move it 1 byte forwards, rather than the full width of an int? Clearly there are some tricks I could learn here, and I could probably use the first one in my own answer.

All the return statement does is storing the return value in EAX. With gcc, assigning it to a variable happens to do the same thing. As for the pointer arithmetic, when you add 1 to an int pointer, it moves to the next int, not the next byte.

Are there cases (when using ints) when it would be better to return, it seems like in the worst case you would make a new int, and assign that.

@Bijan C compilers always align direct memory access to the size of an atom of the primitive in question -- i don't remember if it's in the standard, though

Python 2, 51 bytes
Takes integer as input. Try it online
lambda S:[x==`S`[-1]for x in`S`[::-1]+'~'].index(0)

48 bytes for string as input. Try it online
lambda S:[x==S[-1]for x in S[::-1]+'~'].index(0)

C#, 63 62 bytes

Golfed
i=>{int a=i.Length-1,b=a;while(a-->0&&i[a]==i[b]);return b-a;}

Ungolfed
i => {
    int a = i.Length - 1,
        b = a;

    while( a-- > 0 && i[ a ] == i[ b ] );

    return b - a;
}

Ungolfed readable
i => {
    int a = i.Length - 1, // Store the length of the input
        b = a ;           // Get the position of the last char

    // Cycle through the string from the right to the left
    //   while the current char is equal to the last char
    while( a-- > 0 && i[ a ] == i[ b ] );

    // Return the difference between the last position
    //   and the last occurrence of the same char
    return b - a;
}

Full code
using System;

namespace Namespace {
   class Program {
      static void Main( String[] args ) {
         Func<String, Int32> f = i => {
            int a = i.Length - 1, b = a;
            while( a-- > 0 && i[ a ] == i[ b ] );
            return b - a;
         };

         List<String>
            testCases = new List<String>() {
               "14892093",
               "12344444",
               "112311",
               "888888",
               "135866667"
            };

         foreach( String testCase in testCases ) {
            Console.WriteLine( $" Input: {testCase}\nOutput: {f( testCase )}\n" );
         }

         Console.ReadLine();
      }
   }
}

Releases

v1.1 - - 1 byte  - Thanks to Kevin's comment.
v1.0 -  63 bytes - Initial solution.

Notes
Nothing to add

+1 You can golf it by 1 byte, though. Like this: i=>{int a=i.Length-1,b=a;while(a-->0&&i[a]==i[b]);return b-a;}

MATL, 6 5 bytes
1 byte saved thanks to @Luis
&Y'O)

Try it at MATL Online
Explanation
        % Implicitly grab input as a string
&Y'     % Perform run-length encoding on the string but keep only the second output
        % Which is the number of successive times an element appeared
O)      % Grab the last element from this array
        % Implicitly display

I had forgotten that & did that to Y':-D Why not take input as a string enclosed in quotes and get rid of j?

@LuisMendo I wasn't sure if I could do that since the challenge explicitly said that input was an "integer"

I assumed so from Martin's comment and from the default rules, which allow that. But I'm not really sure

@LuisMendo Ah ok didn't see his comment. Will update!

Batch, 91 bytes
@set s=-%1
@set n=1
:l
@if %s:~-2,1%==%s:~-1% set s=%s:~,-1%&set/an+=1&goto l
@echo %n%

The - prevents the test from running off the start of the string.

Powershell, 41 Bytes
for($n="$args";$n[-1]-eq$n[-++$a]){};$a-1

straightforward loop backwards until a char doesn't match the last char in the string, return the index of that char -1.
-3 thanks to @AdmBorkBork - using a for loop instead of a while.

JavaScript (ES6), 34 bytes
f=(n,p)=>n%10-p?0:1+f(n/10|0,n%10)

Not shorter than the regex solution.
Recursive function which evaluates the digits from right-to-left, stopping when a different digit is encountered. The result is the number of iterations. p is undefined on the first iteration, which means n%10-p returns NaN (falsy). After that, p equals the previous digit with n%10. When the current digit (n%10) and the previous (p) are different, the loop ends.

Röda, 12 bytes
{count|tail}

Try it online!
This is an anonymous function that expects that each character of the input string is pushed to the stream (I think this is valid in spirit of a recent meta question).
It uses two builtins: count and tail:

count reads values from the stream and pushes the number of consecutive elements to the stream.
tail returns the last value in the stream.

T-SQL, 238 214 Bytes
declare @ varchar(max) = '' declare @i int=0, @e int=0, @n int=right(@,1), @m int while (@i<=len(@)) begin set @m=(substring(@,len(@)-@i,1)) if (@n=@m) set @e=@e+1 else if (@i=0) set @e=1 set @i=@i+1 end select @e

Or:
declare @ varchar(max) = '12345678999999'
declare
    @i int = 0,
    @e int = 0,
    @n int = right(@,1),
    @m int

while (@i <= len(@))
begin
    set @m = (substring(@,len(@)-@i,1))
    if (@n = @m) set @e = @e + 1
    else
    if (@i) = 0 set @e = 1
    set @i = @i + 1
end
select @e

Mathematica, 33 30 bytes
Thanks to Greg Martin for saving 3 bytes.
Tr[1^Last@Split@Characters@#]&

Takes input as a string.
Gets the decimal digits (in the form of characters), splits them into runs of identical elements, gets the last run and computes the length with the standard trick of taking the sum of the vector 1^list.

Characters instead of IntegerDigits?

@GregMartin Ah yeah, I guess. Thanks.

You still don't beat that other shrewd Mathematica golfer for this question ;)

@GregMartin What a shame. :)

Java 7, 78 bytes
int c(int n){return(""+n).length()-(""+n).replaceAll("(.)\\1*$","").length();}

Try it here.
I tried some things using recursion or a loop, but both ended up above 100 bytes..

JavaScript (ES6), 39 38 37 27 bytes
f=n=>n%100%11?1:1+f(n/10|0)

Maybe not shorter than the regex-based solution, but I couldn't resist writing a solution entirely based on arithmetic. The technique is to repeatedly take n % 100 % 11 and divide by 10 until the result is non-zero, then count the iterations. This works because if the last two digits are the same, n % 100 % 11 will be 0.

Ah, you finished just before me haha! I'm not sure whether to post another answer, since they will most likely converge after golfing, but here's my solution using 34 bytes: f=(n,p)=>n%10-p?0:1+f(n/10|0,n%10)

@user81655 That's great, feel free to post it. I don't think mine will converge down to that without a complete makeover, and of course now that I've seen yours that won't happen ;-)

Python 3 - 50 44 bytes
Full program (in Python 3, input() returns a string, no matter the input):
g=input();print(len(g)-len(g.rstrip(g[-1])))

Bash + Unix utilities, 34 bytes
sed s/.*[^${1: -1}].//<<<x$1|wc -c

Try it online!

C (clang), 41 bytes
f(x){return x&&x%10-x/10%10?1:f(x/10)+1;}

There are already 2 other C solutions, but they both depend on loops. This uses recursion. If the last 2 digits are different then it's 1, otherwise you do 1+ the number of consecutive digits of the number with the last digit removed.
Try it online!

Haskell, 33 bytes
f(h:t)=sum[1|all(==h)t]+f t
f _=0

Try it online!
Takes string input. Repeatedly cuts off the first character, and adds 1 if all characters in the suffix are equal to the first one.

R, 35 bytes
rle(rev(charToRaw(scan(,''))))$l[1]

Brief explanation
                  scan(,'')         # get input as a string
        charToRaw(         )        # convert to a vector of raws (splits the string)
    rev(                    )       # reverse the vector
rle(                         )$l[1] # the first length from run length encoding

Befunge-98, 19 bytes
01g3j@.$~:01p-!j$1+

Try it online!
This could be made shorter if I managed to only use the stack.
How it works:
01g3j@.$~:01p-!j$1+
01g                 ; Get the stored value (default: 32)                 ;
   3j               ; Skip to the ~                                      ;
        ~           ; Get the next character of input                    ;
         :01p       ; Overwrite the stored value with the new char       ;
             -!     ; Compare the old value and the new                  ;
               j$   ; Skip the $ when equal, else pop the counter        ;
                 1+ ; Increment the counter                              ;

; When the input runs out, ~ reflects the IP and we run: ;
   @.$
     $              ; Pop the extraneous value (the stored value) ;
   @.               ; Print the number and exit                   ;

Jelly, 4 bytes
ŒrṪṪ

Takes input as a string, returns a number.
Try it online!
Relatively simply, Œr Run-length encodes the input, Ṫ pushes the last pair, then Ṫ pushes its second item. Which thus gives us the length of consecutive digits at the end of the string.

Clojure, 48 bytes
#(-> (partition-by identity (str %)) last count)
Usage: (#(-> (partition-by identity (str %)) last count) 123455)
=> 2
Ungolfed:
(defn count-digits [n]
                  (-> (partition-by identity (str n))
                      last
                      count))

Common Lisp, 82 bytes
(defun c (n) (if (eq (mod n 10) (floor (mod n 100) 10)) (+ 1 (c (floor n 10))) 1))
Ungolfed:
(defun c (n)
  (if (eq (mod n 10)
          (floor (mod n 100) 10))
      (+ 1 (c (floor n 10))) 1))

Welcome To PPCG! Wonderful first post, It looks like you have the basics of formatting down, just note that in the future you an make multiple answers if you use multiple languages (good for getting more rep :) )

Vyxal, l, 2 bytes
Ġt

Try it Online!

need to get this to 2 bytes somehow – Razetime

Explained
Ġt
Ġ    # Group the integer into consecutive chunks
 t   # Take the tail of that list
     # The `-l` flag prints the length of TOS

need to get this to 2 bytes somehow

ARM Thumb-2 (no divide instruction/libgcc), 38 bytes
Raw machine code:
b530 2400 250a 3401 2200 280a d302 3201
380a e7fa 0001 0010 2d0a bf08 460d 428d
d0f1 1e60 bd30

Uncommented asm:
        .text
        .arch armv6t2
        .globl dubs
        .thumb
        .thumb_func
dubs:
        push    {r4, r5, lr}
        movs    r4, #0
        movs    r5, #10
.Lloop:
        adds    r4, #1
        movs    r2, #0
.Ldivloop:
        cmp     r0, #10
        blo     .Ldivloop_end
        adds    r2, #1
        subs    r0, #10
        b       .Ldivloop
.Ldivloop_end:
        movs    r1, r0
        movs    r0, r2
        cmp     r5, #10
        it      eq
        moveq   r5, r1
        cmp     r5, r1
        beq     .Lloop
        subs    r0, r4, #1
        pop     {r4, r5, pc}

Explanation
C function signature:
// Assume: post_id != 0
uint32_t dubs(uint32_t post_id);

First, push registers and set up our dubs counter in r4:
dubs:
        push    {r4, r5, lr}
        movs    r4, #0

Now, in order to reuse the loop, we use a "magic" value of 10 for the last digit in r5, and set it at the end of the loop.
        movs    r5, #10

Begin the count by incrementing the dubs counter:
.Lloop:
        adds    r4, #1

Now, we start our divmod loop to divide the ID by 10 and get the remainder.
The divided ID will be in r2 and the remainder will be in r0.
        movs    r2, #0
.Ldivloop:
        cmp     r0, #10
        blo     .Ldivloop_end
        adds    r2, #1
        subs    r0, #10
        b       .Ldivloop

That is basically this in C:
uint32_t quotient = 0;
while (dividend >= 10) {
    ++quotient;
    dividend -= 10;
}
uint32_t remainder = dividend;

This could probably be optimized. We ended up with the registers in the wrong spot, so we have to move things around. Specifically, we want the remainder in r1 and the divided ID in r0.
The biggest problem is dealing with movs either clobbering the flags or requiring hi registers. If it didn't do that, I would put it after the cmp.
.Ldivloop_end:
        movs    r1, r0
        movs    r0, r2

Now, we check for that magic number and set the lowest digit to that.
        cmp     r5, #10
        it      eq
        moveq   r5, r1

Now, check if the new remainder in r1 and loop if it is the same as the last digit.
        cmp     r5, r1
        beq     .Lloop

Move the dubs count into the return register and return. We are actually one too high so we have to correct it.
        subs    r0, r4, #1
        pop     {r4, r5, pc}

C, 62 55 bytes
i,j;f(n){for(i=0,j=n%10;++i;n/=10)if(j-n%10)return--i;}

Try it online!

REXX, 50 bytes
arg ''-1 # 1 n
say length(n)-length(strip(n,T,#))

Parse argument with empty string, causing parsing cursor to move to end of argument, then left one step, put remainder (one character) of argument in # variable, move to first character and put first word of argument in n variable.
Strip trailing characters equivalent to # from n and compare length to n.

Ruby, 28 22 bytes
->s{s[/(.)\1*$/].size}

Anonymous function that takes the number as a string.

I believe you can get the match of a regex in Ruby like s[/(.)\1*$/].

Octave, 30 bytes
@(s)find(flip(diff([0 +s])),1)

Try it online!

JavaScript (ES6), 53 bytes
f=(n,i=1)=>(a=[...n]).pop()==a[a.length-1]?f(a,i+1):i

Japt, 23 bytes
¬â l ¥1?Ul :Uw ¬b@X¦UgJ

Try it online!
Explanation:
¬â l ¥1?Ul :Uw ¬b@X¦UgJ
¬                         // Split the input into an array of chars
 â                        // Return all unique permutations
   l ¥1                   // Check if the length is equal to 1
       ?                  // If yes, return:
        Ul                //   The length of the input
            :             // Else, return:
             Uw           //   The input, reversed
                ¬         //   Split into an array of chars
                  @       //   Iterate through, where X is the iterative item
                 b        //   Return the first index where:
                   X¦     //     X !=
                     UgJ  //     The last char in the input

Haskell, 36 bytes
Without import solution (39 bytes)
f n=length.takeWhile(==last n)$reverse n

Note that a pointfree solution is longer (and less understandable): EDIT: since anonymous functions are allowed, let's shave off two bytes which brings us to 39 (still longer than 36):
(length.).takeWhile.(==).last<*>reverse

With import solution (36 bytes, 19 without import)
import Data.List
f=length.last.group

Run like f "2394398222222" either way

Befunge-93, 45 bytes
<_v#`0:~
pv>$00p110
p>00g-#v_10g1+10
  @.g01<

Try it online!

05AB1E, 3 bytes
Åγθ

Try it online or verify all test cases.
Or alternatively:
γθg

Try it online or verify all test cases.
Explanation:
Åγ   # Run-length decode the (implicit) input-integer
     #  i.e. 1333822 → [1,3,1,2]
  θ  # Pop and push the last item
     #  → 2
     # (which is output implicitly as result)

γ    # Split the (implicit) input-integer into parts of subsequent equal digits
     #  i.e. 1333822 → [1,333,8,22]
 θ   # Pop and push the last item
     #  → 22
  g  # Pop and push its length
     #  → 2
     # (which is output implicitly as result)

Pyth, 4 bytes
her9

Kinda surprised this hasn't been posted yet.
Try it online!

Ruby -nl, 16 bytes
Input is STDIN. Subtracts the position of the start of the dubs sequence from the length of the string (technically, the position of the end of the string).
p~/$/-~/(.)\1*$/

Try it online!

Japt, 6 bytes
ì òÎÌÊ

Try it or run all test cases
ì òÎÌÊ     :Implicit input of integer
ì          :To digit array
  ò        :Partition between truthy pairs
   Î       :   Sign of difference
    Ì      :Last element
     Ê     :Length

APL (Dyalog Extended), 9 bytes
⊃⍸⌽1,2≠/⍞

⍞ input as a string
1,2≠/ 1 concatenated with n-wise reduction with ≠, boolean mask of the starts of sections
⌽ reverse
⊃⍸ index of the first 1
Try it online!

@Razetime true, edited

K (oK), 15 12 bytes
{+/&\|x=*|x}

Try it online!
Takes input as a string.

x=*|x compare each digit to the last digit of the input
&\| "turn off" 1bs occurring after first 0b, e.g. &\|110011b => 110000b
+/ take sum

Stax, 4 bytes
E:GH

Run and debug it

x86_64 machine code, 24 bytes
Could probably be golfed a bit further.
Input and output is through rax as integers.
00000000  6a 0a 5d 31 f6 31 d2 f7  f5 89 d3 ff c6 31 d2 f7  |j.]1.1.......1..|
00000010  f5 39 d3 74 f6 89 f0 c3                           |.9.t....|

Disassembly (with explanation):
dubs:
  6a 0a                 push   0xa
  5d                    pop    rbp      ; set rbp to 10 (for divison)
  31 f6                 xor    esi,esi  ; zero counter
  31 d2                 xor    edx,edx  ; zero upper dividend
  f7 f5                 div    ebp      ; initial divide (can this be golfed into the other divide?)
  89 d3                 mov    ebx,edx  ; set ebx (repeating digit)
loop:
  ff c6                 inc    esi      ; inc counter
  31 d2                 xor    edx,edx  ; zero upper dividend (gets filled with remainder)
  f7 f5                 div    ebp      ; divide
  39 d3                 cmp    ebx,edx  ; compare repeating digit with digit 'popped'
  74 f6                 jz     loop     ; if equal keep looping
  89 f0                 mov    eax,esi  ; move counter to eax for output
  c3                    ret

Full program source to run subroutine:
; nasm -felf64 -odubs.o dubs.asm
; ld -odubs dubs.o
; ./dubs; echo $?

bits 64

section .text
    global _start

_start:
    mov rax, 12344444
    call dubs

    mov rdi, rax
    mov rax, 60
    syscall ; exit with return val as exit code

dubs:
    push 10
    pop rbp
    xor esi, esi
    xor edx, edx
    div ebp ; eax quot edx rem
    mov ebx, edx
loop:
    inc esi
    xor edx, edx
    div ebp ; eax quot edx rem
    cmp ebx, edx
    jz loop
    mov eax, esi
    ret

Jelly, 3 bytes
ŒɠṪ

Try it online!
Well, there’s a 5 byte and a 4 byte Jelly answer, so might as well go for 3 bytes
How it works
ŒɠṪ - Main link. Takes l on the left as a list of digits
Œɠ  - Group adjacent equal values in l and get the lengths of each
  Ṫ - Get the last one

AWK, 44 bytes
{for(d=$1%10;$1%10~d;k++)$1=($1-d)/10;$1=k}1

This piece of code uses math, so should work only with numbers.
{
for(             # $1 is the input, but will be modified during the code.
    d=$1%10;     # before the loop, records the last digit of $1 to _d_,
    $1%10~d;     # and stops if the last digit of $1 is different from _d_.
    k++          # increments 1 to _k_ after each loop.
   )
   $1=($1-d)/10; # removes the last digit of $1 and divides by 10.
                 # this uses less bytes than int($1/10).

$1=k             # after the end of the looping, assigns the count variable _k_
                 # to $1, which will become the output.
}
1                # prints $1

Try it online!

AWK, 44 bytes
{for(i=n=split($1,a,e);a[i--]~a[n];)$1=n-i}1

This code treats the input as string. Works with all kinds of characters.
{
for(
    i=n=split($1,a,e); # splits the input to the _a_ array,
                       # using the _e_ empty variable as flag (i.e, a null character)
                       # also sets the number of elements of the array
                       # to the _i_ and _n_ variables

    a[i--]~a[n];       # loops while the _i_ and _n_ elements are equal
                       # this also decrements _i_ by 1 after the evaluation
   )
     $1=n-i            # during each loop, sets the output to n-i
}
1                      # prints $1

Try it online!

Thunno 2 tL, 1 byte
ġ

Attempt This Online!
Thunno 2, 3 bytes
ġtl

Attempt This Online!
Explanation
     # Implicit input
ġ    # Group consecutive digits together
 t   # Get the last item (also done by t flag)
  l  # And push the length (also done by L flag)
     # Implicit output

Raku, 18 bytes
{m/(.)$0*$/.chars}

Try it online!
m/(.)$0*$/ applies a regex to the input argument that matches any number of the same trailing characters.  (In Raku, applying a regex to a number implicitly matches against its string representation.)  Then .chars counts how many characters there are in the match.

Lua, 36 bytes
s=...print(#s:match(~~(s%10)..'+$'))

Try it online!

PHP 40chars
(Does not take into account php tags)
strlen(preg_match('/(.)\1*$/',$argv[1]))

I think you mean preg_match('/(.)\1*$/',$argv[1],$t);echo strlen($t[0]); or as alternative <?=strlen(preg_filter('/.*?((.)\2*)$/','\1',$argv[1]));

C#, 49 bytes
i=>i.Reverse().TakeWhile(x=>x==i.Last()).Count();

Try it here
Full code
  using System;
  using System.Linq;

  class Program
  {
      static void Main()
      {
          Func<string, int> func = i=>i.Reverse().TakeWhile(x=>x==i.Last()).Count();

          Console.WriteLine(func("14892093"));
          Console.WriteLine(func("12344444"));
          Console.WriteLine(func("112311"));
          Console.WriteLine(func("888888"));
          Console.WriteLine(func("135866667"));
          Console.ReadLine();
      }
  }

Java 7, 64 62 bytes
Golfed:
int w(int x){int r=1,d=x%10;while((x/=10)%10==d)r++;return r;}

Ungolfed:
int w(int x)
{
    int r = 1, d = x % 10;
    while ((x /= 10) % 10 == d)
        r++;
    return r;
}

Try it online

Common Lisp, 72 chars
(lambda(i)(do((n i(floor n 10))(c 1(1+ c)))((/= 0(mod(mod n 100)11))c)))

Unoglfed
(lambda (i)
  (do ((n i (floor n 10))
       (c 1 (1+ c)))
      ((/= 0 (mod (mod n 100) 11)) c)))

Explanation
(/= 0 (mod (mod n 100) 11))
This checks to see if the last two digits of n are different- if n%100 is  not divisible by 11.
(do ((n i (floor n 10))
     (c 1 (1+ c)))
    (... c))

do is a powerful generic looping construct in lisp. Its first argument  is a list describing the looping variables. Each element is a list of (variable initial-value step-form) where step-form is evaluated each time through the loop to update that variable. The second argument is a test to perform to end the loop (the test I covered above) and a list of values to return after looping (in this case just c, which has been incrementing each time though the loop).
(lambda (i) ...)
Wraps the operation in an anonymous function that takes the number as an integer.

Vim - 39
ix^[Y$d?[^^R=@@[len(@@)-2]^M]^Mcc^R=len(@2)^M

(^[, ^Ms and ^Rs are one char each)

insert non-number (for 88888 input), copy line, move to the end
delete searching backwards for a char other then the last char
replace line with length of deleted text

J, 14 bytes
>:i.&1}.~:|.":

Try it online!
It's fortunate that the challenge allows a REPL command. As a verb (function) it's 20 bytes:
3 :'>:i.&1}.~:|.":y'

For arbitrarily large integers, the literal must be suffixed by x.
Explained
Applied right to left, all monadic verbs:

": Format - Stringifies its argument
|. Reverse
~: Nub sieve - Produces a boolean array of 1's each time a new item is introduced, 0 otherwise
}. Behead - Removes first item of array
i.&1 Index of - Gets index of first 1. i. is actually a dyadic verb, but &1 ties right argument to 1.
>: Increment

x86-16 machine code, IBM PC DOS, 22 21 20 bytes
Binary:
00000000: d1ee 8a1c 8d38 8a05 fdf3 aef6 d191 052f  .....8........./
00000010: 0ecd 10c3                                ....

Build and test DUBS.COM with xxd -R.
Unassembled listing:
D1 EE       SHR  SI, 1              ; SI to command line tail (80H)
8A 1C       MOV  BL, BYTE PTR[SI]   ; BX = input string length
8D 38       LEA  DI, [BX][SI]       ; DI to end of string
8A 05       MOV  AL, BYTE PTR[DI]   ; AL = last char
FD          STD                     ; set LODS to decrement
F3 AE       REPZ SCASB              ; scan [DI] backwards until AL doesn't match
F6 D1       NOT  CL                 ; negate CL to get number of matches + 1
91          XCHG AX, CX             ; AL = CL
05 2F0E     ADD  AX, 0E2FH          ; ASCII convert and adjust, BIOS tty function
CD 10       INT  10H                ; write number to console
C3          RET                     ; return to DOS

A standalone PC DOS executable program.  Input via command line, output number to console.
Notes:
This takes advantage of a few "features" of PC DOS register startup values; specifically BH = 0, CX = 00FFH and SI = 100H.  REPZ decrements CX on every compare operation, so starting at 00FFH will yield a negative count of reps.  It is off-by-one because REPZ decrements before comparison, so the first non-match still gets counted.  That number is ones-complimented and adjusted by 1 to get the count of matched digits.
Also, since CH = 0 it's possible to combine ADD AL, '0'-1 and MOV AH, 0EH into a single instruction ADD AX, 0E2FH to save 1 byte, since AH will be 0.  Old-school SIMD for you!
I/O:

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


text:
Tips for golfing in Röda
Röda is a stream-based scripting language created by fergusq.
What general tips do you have for golfing in Röda? I'm looking for ideas that can which can be applied to code-golf problems and which are also at least somewhat specific to Röda (e.g. "remove comments" is not an answer).
Please post one tip per answer.

Are you trying to get tips to beat me in the golf? :P (I should probably look at the tips for Python page)

Wow, a question from PCG.SE that got into the Hot Network Questions and is not a programming puzzle / challenge! :)

@HyperNeutrino Shhh.... :)

Use underscores
This is probably the most important tip. Nearly every golfed Röda program uses underscores.
The underscore syntax is syntactic sugar for for loops. The following lines of code are equivalent:
ls""|fileLength x for x|sort|pull
ls""|fileLength _|sort|pull

Each underscore adds a new variable to an invisible for loop that is around the statement. The loop pulls one value from the stream for each variable/underscore and then repeats, until no values are left.
Underscores can be used anywhere in statements:
a[x:y+1]=[1]*(1+y-x) /* Sets range x..y (inclusive) */
seq x,y|a[_]=1       /* 6 bytes less */

If you must refer to the same underscore value more than once, or use the values in reverse order, you can put a number after the underscore:
a|[_^_1]  /* maps x to x^x */
a|[_2-_1] /* maps each pair (x,y) to y-x, eg. [1,2,4,8] -> [1, 4] */

Some semicolons/newlines are optional
When writing Röda code, it is generally recommended to use newlines or semicolons to separate all statements. However, when golfing, it is worth to know that not all semicolons are really required.
Here's an incomplete list of places where semicolons/newlines are optional. Most of them do not apply when the following statement begins with an operator ((, [, +, etc.).

After assignments
After function calls, when there's at least one argument (eg. f x) or when parentheses are used (eg. f())
Everywhere, if the next line/statement would begin with |, ), ] or }

If the next statement begins with an operator, the semicolon/newline is optional if

The statement is a function call and parentheses are used, eg {f(x)[y]} is same as {f(x);[y]}. This works only in statement context, not when the function call is an expression.
The statement is an assignment and parentheses are used, eg x=(y)[z] is same as x=(y);[z] (that is not same as x=((y)[z])).

And here are some places where the newlines are unfortunately required:

After ++ and --.
After [...].

It is often possible to save bytes by reorganizing assignments. For example:
a=0;b=""c=[""]
b=""c=[b]a=0

x=f()y=i;z=a[0]
x=f()z=a[0]y=i

Use suffix control structures
It is almost never optimal not to use suffix statements, as you can use {...} in place of do...end.
Some examples:
x|unless[not(_ in y)]do[0]else[1]done
x|[0]unless[not(_ in y)]else[1]

if[p<0]do c+=p;a-=p done
{c+=p;a-=p}if[p<0]

Can you do if[_ in y] instead?

@KritixiLithos No, because I want the condition to be OR, not AND. Currently it checks if there is at least one value in x that is also in y, but your condition would check if all values in x are also in y. (The example was copied from here).

Use the stream for input
In cases where the input is a list of elements, it can be beneficial to pull the values from the stream instead of getting them as an array.
In most of the cases the array elements are iterated by pushing them to the stream and then iterating it using a for loop (or an underscore). As the elements are iterated from the stream anyway, why not define that they should be there from the beginning?
For example, to calculate the sum of the squares of the numbers in input:
{|a|a|[_^2]|sum} /* Removing a redundant argument */
{[_^2]|sum}      /* saves 5 bytes */

Using `` strings
In "" strings, you will have to escape certain characters in order to use them. For example, to print the backslash, you would have to have a string like "\\". There is one added byte for escaping the backslash. However, if you use ``, you do not have to escape this character and can save one byte.
print"\\"     /* 9 bytes */
print`\`      /* 8 bytes */

Not just that, you can encode variables and expressions inside of `` strings using $variableName or ${expression}, a feature not present in "" strings.
We are outputting the string "a" concatenated with the value of the variable b with a trailing newline in these examples.
["a",b,"      /* 11
"]               bytes   */
[`a$b         /* 8
`]               bytes; encodes b in the string using $b */

Use , instead of and
Conditions in Röda are streams, and can consist of multiple values. These values are reduced to one boolean value with and.
This means that you can replace and with , in conditions to push multiple values to the stream:
x if[a and b]
x if[a,b]

Empty condition is truthy
It is also possible to have a condition that contains no values, which is truthy.
x while true
x while[]

The parentheses are optional in the statement context. This applies even if the argument begins with an operator. For example, [a()|sqrt-_] is shorter than [a()|sqrt(-_)]. The parentheses after a are mandatory, as a is in the expression context, not in the statement context.
However, writing [a()|sqrt(_+1)*2] is not possible, and extra parentheses are needed to help the parser: [a()|sqrt((_+1)*2)]. Often it is possible to rewrite such expression so that it doesn't begin with a parenthesis: [a()|sqrt 2*(_+1)]

Is it also possible to pass multiple parameters to functions without requiring parentheses?

@KritixiLithos Yes. Eg. [a()|atan2 _,_] would be allowed.

Use , instead of .. in []/push statements

Related: Use , instead of and

The push function (as well as the print function) can take any number of arguments, and outputs each one of them with no delimiter.
So that means something like this
["a"..b]        /*8 bytes (string "a" concatenated with variable b)*/

can be shortened into just
["a",b]         /*7 bytes*/

saving 1 byte.

[]/push > print
Never use print statements. [] push statements are always golfier. The difference between print and push is that the former outputs a trailing newline while the latter doesn't. However, this can be circumvented.
print"a"              /* 8 bytes */
["a                   /* 6 bytes; uses a literal newline */
"]

print"a",b            /* 10 bytes */
[`a$b                 /* 8 bytes; uses a literal newline and `` strings */
`]

Write replacement lists in form *"...;..."/";"
The replace function takes normally a list of strings as arguments. However, if the list is very long, it is beneficial to simply store the regex/replacement pairs in a string and then split the string and use the star operator:
replace"a","b","c","d"
replace*"a;b;c;d"/";"

source: Stack Exchange

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

sort: votes


text:
Balance the Brackets
Your objective: Given a string of brackets, output the minimum Damerau-Levenshtein Distance required to turn the input string into a string where the brackets are balanced.
Input
The input string will only contain brackets and no other characters. That is, it is a combination of any of the characters in (){}[]<>. You may take input as either a string or an array of characters. You may not make any other assumptions about the input string; it may be arbitrarily long (up to the maximum size supported by your language), it may be empty, the brackets may already be balanced, etc.
Damerau-Levenshtein Distance
The Damerau-Levenshtein Distance between two strings is the minimum number of insertions, deletions, single-character substitutions, and transpositions (swapping) of two adjacent characters.
Output
The output should be the minimum Damerau-Levenshtein Distance between the input string and a string in which the brackets are matched. Output should be a number, not the resulting balanced string.
A pair of brackets is considered "matched" if the opening and closing brackets are in the right order and have no characters inside of them, such as
()
[]{}

Or if every sub-element inside of it is also matched.
[()()()()]
{<[]>}
(()())

Sub-elements can also be nested several layers deep.
[(){<><>[()]}<>()]
<[{((()))}]>

(Thanks to @DJMcMayhem for the definition)
Test Cases
Input                   Possible Balanced       Output

Empty                   Empty                   0
[](){}<>                [](){}<>                0
[(){}<>                 [(){}<>]                1
[(])                    []()                    1
[[[[[[[[                [][][][]                4
(](<>}[>(}>><(>(({}]    ()(<>)[(<><>){}]        7
>]{])<                  []{()}                  3
([)}}>[                 (){}<>                  4
{<((<<][{{}>[<)         <>(<<[]>{}>[])          5
{><({((})>}}}{(}}       {<><({()})>}{}{()}      4
(](<)>}[>(}>>{]<<(]]    (<()<><<>()>>[])<()>    9
}})(                    {}()                    2

(Thanks to @WheatWizard for solving half of the test cases)
This is code-golf, fewest bytes wins!
Your submissions should be testable, meaning it should output a result for  each test case in no more than an hour.

Balance your own brackets :P

I will be surprised if we'll even see a single correct non-bruteforce answer to this challenge.

Someone will just have to prove you wrong then :P

There are too many corner cases. For example, We do not know how we should balance things like [<>.

@SIGSEGV the answer to that is 1.  It doesn't matter whether you balance it like [<>] or []<> or <>

@NathanMerrill Oh, I see.

This is hard, and though it's only been up for 4 hours I think it's telling that there are no answers yet. Can you maybe change it to be only ()[] rather than 4 different types of brackets? I think you get all the important propreties without making it into a significantly different challenge the way using only 1 type of brackets would.

@Bijan Nah, it won't make it much easier, and besides, Brain-Flak's birthday is coming up soon!

(I think) I have somehow solved it for addition purposes(imo, deletion is same number of additions here because of the symmetry). but i just cannot wrap my head around the editing thing.
def f(a,i=lambda a,r='[{(<]})>':r[(r.find(a)+4)%8]):
 c=[]
 for b in a:c.pop()if(len(c)>0and c[-1]==i(b))else c.append(b)
 return f(c[1:-1])+1if(len(c))else 0

I suggest a limit for the input string, because the problem seems computationally expensive (maybe NP-complete?)

@qwr Why have a limit? The time limit only applies for the test cases given, for large inputs your program can take all the time in the world.

Error in the 7th test case: Consider []{()} (distance of 3)

@math_junkie thanks! I'm on mobile, can you make the edit yourself?

i also edited in the 6 down to 5!

@RomanCzyborra I don't think that actually works, can you comment a link to the steps you used?

@math_junkie 0:{<((<<][{{}>[<) 1:<((<<][{{}>[<) 2:<>(<<][{{}>[<) 3:<>(<<[]{{}>[<) 4:<>(<<[]>{}>[<) 5:<>(<<[]>{}>[])

The second-to-last can be done in 9:

(<()<><<>()>>[])<()> <- (<()<><<>()>>[])<()] <- (<()<><<>()>>[])<(]] <- (<()<><<>()>>{])<(]] <- (<()<><<>(}>>{])<(]] <- (<()<><[>(}>>{])<(]] <- (<()<><[>(}>>{]<<(]] <- (]()<><[>(}>>{]<<(]] <- (]()<>}[>(}>>{]<<(]] <- (](<)>}[>(}>>{]<<(]]

@user1502040 can you edit that in?

Would using LISP be too obvious?

Retina, 254 252 264 248 240 232 267 bytes
Thank you to @AnthonyPham, @officialaimm, and @MistahFiggins for pointing out bugs
T`[]()`:;'"
+`'-*"|:-*;|{-*}|<-*>
-
+`'(\W+)"|:(\W+);|{(\W+)}|<(\W+)>
A$1$2$3$+B
+`'(\D+)"|:(\D+);|{(\D+)}|<(\D+)>
6$1$2$3$+9
(.*)(}{|"'|;:|><)
1$1
-

A6B9|6A9B
1
A6+B9+|A6+.B9+.|A+6.B+9
11
T`':{";}`<<<>
(.*)(<\W|\W>)
1$1
+`<(.*A.*B.*)?\W|\W(.*A.*B.*)?>
1$1$2
\W|6B|1

Try it Online!
Non-brute force solution! It works for all test cases, and even found an error in one.
 -2 bytes thanks to @MartinEnder (${4} to $+)
 +12 bytes to account for additional swapping cases
 -16 bytes by making better use of character classes
 -8 bytes by removing an unnecessary restriction on swapping. This also fixed a bug :)
 -10 bytes by combining the swapping logic into a single regex
 +2 bytes to account for consecutive swaps
 +many for various bug fixes**
Explanation:
T`[]()`:;'" is used to replace special bracket types for convenience.
First, we recursively replace all matched brackets with -, AB or 69 depending on whether they are adjacent or not.
Then, useful "swapping " is performed by removing newly matched brackets and adding a 1 to the beginning of the string. We also replace - with the empty string, as it was just being used for the above swapping.
Next, we try "replacements" by removing pairs of unmatched brackets that don't overlap already-matched brackets and adding a 1 to the string.
Finally, \W|6B|1 counts any remaining single brackets plus the number of 1s.
**I'm currently working on a shorter version that uses Retina's line splitting features, though I ran into a considerable problem so it might take quite awhile.

That ${4} can be shortened to $+. I'm very curious why this is guaranteed to work though.

@MartinEnder Thanks! I'm not sure that it always works, but it works at least for the provided test cases, and a couple edge cases that I came up with

Given [{][}] [] [[][][][][][]] [][][][][][][][][][][][], you can simply swap the } inside the first pair of parentheses and have it balanced. Spacing is used to make the input a bit more readable. You outputted 3 but it really should be one.

@AnthonyPham Thanks! I think I know why that's not working, I'll try to find a clever way to fix it

Even weirder is that [{]} returns 1 but [{][]} returns 2.

Fails for: [{<><>][]}

@officialaimm Fixed! (and saved some bytes)

fails for {[(<}>)] - output should be 2, but is 3

@MistahFiggins Thanks! Fixed at the cost of two bytes

fails for (([))] - output should be 2, but is 1 (which is strange given that [((])) correctly returns 2)

@MistahFiggins Moving the [ outside works: [(())]. It should be the other way around :)

@AnthonyPham Not quite sure what you mean. I'm saying that the code as is returns the wrong value for the case (([))]. It returns 1, when it should instead return 2. I found it strange because the case [((])) correctly returns 2, and that [((])) and (([))] should be functionally equivalent (although I don't know how the code works internally).

@MistahFiggins It is supposed to be one not two as moving the [ outside is enough to balance the brackets

@AnthonyPham "...and transposition (swapping) of two adjacent characters."

Also, {[(<}>)] still returns the wrong value (3). It should return 2, because you can delete both {} to balance it.
(sorry for re-ping, accidentally deleted comment)

@MistahFiggins I'm having trouble creating a solution that fixes everything at once. I will keep trying, but I'm open to any suggestions as well!

I'm (half) working on a solution too, so if I figure anything significant out I'll tell you. Thanks for maintaining your answer!

@MistahFiggins Look at the OP's fourth example. It should still be one

@AnthonyPham In that case, 2 adjacent characters are swapped. This is distinctly different than swapping 2 letters that are not adjacent, like swapping the [ with the second ( in [((]))

Brain-Flak, 1350 bytes
{({}(())(<>))<>({(()()()())<{({}[()])<>}{}>}{}<>({<({}[()])>{()(<{}>)}}{}{}<>))<>}<>([[]]){([[]({}()<>)]<>)<>{(({}())<<>(({})<(({}(<()>))<>({}))([(())()()]){<>({}())}{}{<>{}<>({}()){(((({}<(({}<>)<{({}()<([(){}])>)}{}>)<>(({}(<>))<{({}()<([(){}])>)}{}<>>)><>({}))(<(((({}({})[()])[()()]<>({}))<>[({})({}){}]({}<>))<>[(({}<>)<>({}<>)<>)])<>>)))[()](<()>)<<>(({})<({}{}()){({}()<({}<>)<>>)}{}<>(({})<<>(({}<>))>)<>(())>){({}[()()]<(<([({[{}]<(({})()<>[({})]<>)>{()(<{}>)}}{}<(({})<>[()({}<(({}<<>({}<>)<>(({})<>)>)<>[(){}])<>>)]<>)>{()(<{}>)}{}(){[()](<{}>)}<<>{({}<>)<>}{}>)]({}{}))>)<>{({}<>)<>}>)}{}{}<>{}{}{({}<>)<>}{}{}(<>)<>{({}<>)<>}{}{(<{}>)<>{({}<>)<>}<>({}<{}>){({}<>)<>}}{}((({}<({}({})({})<{{}<>{}(<>)}{}(((({}<({}<>)>)<>)))<>>)<>>)<><({}<({}<<>(()())>)>)>)<<>({}<{}{({}<>)([()()()]){((({}()()<>))[()]<(({()(<{}>)}{})<>({}<(({}<<>({}[()()](()[({})({})]({[()](<{}>)}{}<>{}<(({})<>)>)<>))>)<>)>)<>)<>({}<({}<({}<({}<>)>)>)>)>)}{}{}<>}<>{}{}{}{}{}{}{}{}>)>)>)}{}({}<({}<{({}<(({}){({}())}{}{}<(({}){({}())}{}{}<>)>)>)<>}<>{((({}(()()){([{}](<({}(<()>)<>){({}<({}<>)>(())<>)}{}>({})<<>{{}({}<>)<>}{}>))([{}()]{})}{})))<>(({}))<>{<>({}[()])}{}({}<<>{}{}{<>}>)<>{}}<>(({}<>){[()](<{}>)}{})(<>)>)>)<>(<({}<>)>)<>}<>{}({}<(({}){({}())}{}{}){({}<({}<>)>(())<>)}{}{}>)<>{{}({}<>)<>}{}>)<>>)}{}<>([[]{}])}{}(([]){<{}{}>([])}{}<>){({}[()]<{}>)}{}({}<>)

Try it online!
With constant-speed comparisons and pointer dereferencing, this algorithm is O(n3).  Unfortunately, Brain-Flak has neither of these, so this program runs in O(n5) time instead.  The longest test case takes about 15 minutes.
Simplifying results
To see that my algorithm works, we need to show some results that reduce the search space considerably.  These results rely on the fact that the target is an entire language instead of just one specific string.

No insertions are needed.  Instead, you can just remove the bracket that the inserted character would eventually match.
You will never need to remove a bracket, then swap its two neighbors.  To see this, assume wlog that the removed bracket is (, so we are transforming a(c to ca in two steps.  By changing c and inserting a copy, we can reach ca() in two steps without a swap.  (This insertion can then be removed by the above rule.)
The same bracket will never need to be swapped twice.  This is a standard fact about the Damerau-Levenshtein distance in general.

Another simplifying result that I didn't use, because accounting for them would cost bytes:

If two brackets are swapped, and they don't match each other, the eventual match to each of those brackets will never be changed or swapped.

The algorithm
When any string is reduced to a balanced string, one of the following will be true:

The first bracket is deleted.
The first bracket stays where it is and matches the bracket at some position k (possibly after changing one or both of them).
The first bracket is swapped with the second, which in turn matches the bracket at position k.

In the second case, the bracket at position k may have swapped with one of its neighbors.  In either of the latter two cases, the string between the (possibly newly) first bracket and the bracket that started in position k must be edited to a balanced string, as does the string consisting of everything after k.
This means that a dynamic programming approach may be used.  Since a swapped bracket need not be swapped again, we only need to consider contiguous substrings, as well as subsequences formed by removing the second character and/or the penultimate character from such a substring.  Hence, there are only O(n2) subsequences we need to look at.  Each of those has O(n) possible ways to match (or delete) the first bracket, so the algorithm would be O(n3) under the conditions above.
The data structure
The right stack includes the brackets from the original string, with two bytes per bracket.  The first entry determines the entire bracket, and is chosen such that matched brackets have a difference of exactly 1.  The second entry only determines whether it is an opening bracket or a closing bracket: this determines how many changes it takes for two brackets to match each other.  No implicit zeros below this are ever made explicit, so that we can use [] to get the total length of this string.
Each substring under consideration is represented by two numbers in the range 0 to 2n: one for the beginning position, and one for the end.  The interpretation is as follows:

A substring starting at 2k will start at position k (0-indexed), and the second character is not removed.
A substring starting at 2k+1 will start at position k, and the second character is removed due to having been swapped left.
A substring ending at 2k will end just before position k (i.e., the range is left-inclusive and right-exclusive.)
A substring ending at 2k-1 will end just before position k, and the penultimate character is removed due to having been swapped right.

Some ranges (k to k+1, 2k+1 to 2k+1, 2k+1 to 2k+3, and 2k+1 to 2k+5) make no physical sense.  Some of those show up as intermediate values anyway, because it's easier than adding additional checks to avoid them.
The left stack stores the number of edits needed to convert each substring into a balanced string.  The edit distance for the interval (x,y) is stored at depth x + y(y-1)/2.
During the inner loop, entries are added above the left stack to denote which moves are possible.  These entries are 5 bytes long.  Counting from the top, the numbers are d+1, y1, x1, y2, x2, where the move costs d edit steps and divides the substring into (x1,y1) and (x2,y2).
The code
Description to come.  For now, here's my working copy of the code.  Some comments may be inconsistent with terminology.
# Determine bracket type for each byte of input
{({}(())(<>))<>({(()()()())<{({}[()])<>}{}>}{}<>({<({}[()])>{()(<{}>)}}{}{}<>))<>}

# For every possible interval length:
<>([[]]){

  # Compute actual length
  ([[]({}()<>)]<>)

  # Note: switching stacks in this loop costs only 2 bytes.
  # For each starting position:
  # Update/save position and length
  <>{(({}())<<>(({})<

    # Get endpoints
    (({}(<()>))<>({}))

    # If length more than 3:
    ([(())()()]){<>({}())}{}{

      # Clean up length-3 left over from comparison
      <>{}<>

      # Initialize counter at 2
      # This counter will be 1 in the loop if we're using a swap at the beginning, 0 otherwise
      ({}())

      # For each counter value:
      {

        # Decrement counter and put on third stack
        (((({}<

          # Do mod 2 for end position
          (({}<>)<{({}()<([(){}])>)}{}>)<>

          # Do mod 2 for start position
          (({}(<>))<{({}()<([(){}])>)}{}<>>)

        # Subtract 1 from counter if swap already happened
        ><>({}))(<

          # Compute start position of substrings to consider
          (((({}({})[()])[()()]<>({}))

            # Compute start position of matches to consider
            <>[({})({}){}]({}<>))<>

            # Compute end position of matches to consider
            [(({}<>)<>({}<>)<>)]

          # Push total distance of matches
          )

        # Push counter as base cost of moves
        # Also push additional copy to deal with length 5 intervals starting with an even number
        <>>)))[()](<()>)<

          # With match distance on stack
          <>(({})<

            # Move to location in input data
            ({}{}()){({}()<({}<>)<>>)}{}

            # Make copy of opening bracket to match
            <>(({})<<>(({}<>))>)

          # Mark as first comparison (swap allowed)
          <>(())>)

          # For each bracket to match with:
          {({}[()()]<

            (<([(

              # If swap is allowed in this position:
              {

                # Subtract 1 from cost
                [{}]

                # Add 1 back if swap doesn't perfectly match
                <(({})()<>[({})]<>)>{()(<{}>)}

              }{}

              # Shift copy of first bracket over, while computing differences
              <(({})<>[()({}<(({}<<>({}<>)<>(({})<>)>)<>[(){}])<>>)]<>)>

              # Add 1 if not perfectly matched
              {()(<{}>)}{}

              # Add 1 if neither bracket faces the other
              # Keep 0 on stack to return here
              (){[()](<{}>)}

              # Return to start of brackets
              <<>{({}<>)<>}{}>

            # Add to base cost and place under base cost
            )]({}{}))>)

            # Return to spot in brackets
            # Zero here means swap not allowed for next bracket
            <>{({}<>)<>}

          >)}

          # Cleanup and move everything to right stack
          {}{}<>{}{}{({}<>)<>}{}

          # Remove one copy of base cost, and move list of costs to right stack
          {}(<>)<>{({}<>)<>}{}

          # If swap at end of substring, remove second-last match
          {(<{}>)<>{({}<>)<>}<>({}<{}>){({}<>)<>}}{}

          # Put end of substring on third stack
          ((({}<({}({})({})<

            # If swap at beginning of substring, remove first match
            {{}<>{}(<>)}{}

            # Move start of substring to other stack for safekeeping
            (((({}<({}<>)>)<>)))

          # Create "deletion" record, excluding cost
          <>>)<>>)<>

          # Move data to left stack
          <({}<({}<<>

            # Add cost to deletion record
            (()())

          >)>)>)

          # Put start position on third stack under end position
          <<>({}<

            # For each matching bracket cost:
            {}{

              # Move cost to left stack
              ({}<>)

              # Make three configurations
              ([()()()]){

                # Increment counter
                ((({}()()<>))[()]<

                  # Increment cost in first and third configurations
                  (({()(<{}>)}{})<>({}<

                    # Keep last position constant
                    (({}<

                      # Beginning of second interval: 1, 2, 1 past end of first
                      <>({}[()()]

                        # End of first interval: -3, -1, 1 plus current position
                        (()[({})({})]

                          # Move current position in first and third configurations
                          ({[()](<{}>)}{}<>{}<

                            (({})<>)

                          >)

                        <>)

                      )

                    >)<>)

                  >)<>)

                  # Move data back to left stack
                  <>({}<({}<({}<({}<>)>)>)>)

                >)

              }{}

            {}<>}

            # Eliminate last entry
            # NOTE: This could remove the deletion record if no possible matches.  This is no loss (probably).
            <>{}{}{}{}{}{}{}{}

        # Restore loop variables
        >)>)>)

      }{}

      # With current endpoints on third stack:
      ({}<({}<

        # For all entries
        {

          # Compute locations and move to right stack
          ({}<(({}){({}())}{}{}<(({}){({}())}{}{}<>)>)>)<>

        }

        # For all entries (now on right stack):
        <>{

          # Cost of match
          ((({}

            # Do twice:
            (()()){([{}](

              # Add cost of resulting substrings
              <({}(<()>)<>){({}<({}<>)>(())<>)}{}>({})<<>{{}({}<>)<>}{}>

            # Evaluate as sum of two runs
            ))([{}()]{})}{}

          )))

          # Find smaller of cost and current minimum
          <>(({}))<>{<>({}[()])}{}

          # Push new minimum in place of old minimum
          ({}<<>{}{}{<>}>)

          <>{}

        }

        # Subtract 1 if nonzero
        <>(({}<>){[()](<{}>)}{})(<>)

      >)>)

      <>(<({}<>)>)<>

    # Otherwise (length 3 or less), use 1 from earlier as cost.
    # Note that length 0-1 is impossible here.
    }<>{}

    # With cost on third stack:
    ({}<

      # Find slot number to store cost of interval
      (({}){({}())}{}{})

      # Move to slot
      {({}<({}<>)>(())<>)}{}

    # Store new cost
    {}>)

    # Move other slots back where they should be
    <>{{}({}<>)<>}{}

  Restore length/position for next iteration
  >)<>>)}

  # Clear length/position from inner loop
  {}<>([[]{}])

}{}

(([]){<{}{}>([])}{}<>){({}[()]<{}>)}{}({}<>)

Haskell, 797 bytes
import Data.Array;import Data.Function;import Data.List;
e=length;f=fst;o=map;s=listArray;u=minimum;b p=let{m=e p;x=s(1,m)p;
v=s(1,m)(listArray('(','}')[0,0..]:[v!i//[(x!i,i)]|i<-[1..m-1]]);
d q=let{n=e q;y=s(1,n)q;t(a,b)=listArray((a,b),(m,n));
c=t(1,1)[sum[1|x!i/=y!j]|i<-[1..m],j<-[1..n]];
d=t(-1,-1)[if i<0||j<0then m+n else
if i*j<1then(i+j)else u[1+d!(i-1,j),1+d!(i,j-1),c!(i,j)+d!(i-1,j-1),
let{k=v!i!(y!j)-1;l=w!(i,j-1)-1}in-3+i+j-k-l+d!(k,l)]|i<-[-1..m],j<-[-1..n]];
w=t(1,0)[if j>0&&c!(i,j)>0then w!(i,j-1)else j|i<-[1..m],j<-[0..n]]}in d!(m,n);
a=s(0,div m 2)([(m,"")]:[(concat.take 2.groupBy(on(==)f).sort.o(\q->(d q,q)))(
[b:c++[d]|[b,d]<-words"() <> [] {}",(_,c)<-a!(l-1)]++
concat[[b++d,d++b]|k<-[1..div l 2],(_,b)<-a!k,(_,d)<-a!(l-k)])|l<-[1..div m 2]]);
}in u(o(f.head)(elems a))

Try it online!

Yesterday i read here that the bounty would not end before tomorrow therefore i wanted to contest that an implementation applying the https://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance#Distance_with_adjacent_transpositions algorithm computes more correct values than the current very much faster Retina heuristic!

No, this ain't worthy the prize after all because i wrongly extrapolated that its grokking the 18 characters distant 4 in 2400s@800MHz would also grok the 22 characters distant 9 equally close to 3600s which it sadly would not.

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

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


text:
Change text gravity like the 2048 puzzle
In the game 2048, you have a grid, and you can move the elements in four directions. They all move in that direction as far as they can. For this challenge, you will be given a padded, square 2D string (either with newlines, or a list of strings), like so:
ab cd e
 f ghij
      kl
mno p
 q r st
u      v
 w x  y
z
or
['ab cd e ', ' f ghij ', '      kl', 'mno p   ', ' q r st ', 'u      v', ' w x  y ', 'z       ']

The four operations are left, right, up, and down. The result of each on the above input:
Left:
abcde
fghij
kl
mnop
qrst
uv
wxy
z
or
['abcde   ', 'fghij   ', 'kl      ', 'mnop    ', 'qrst    ', 'uv      ', 'wxy     ', 'z       ']

Right:
   abcde
   fghij
      kl
    mnop
    qrst
      uv
     wxy
       z
or
['   abcde', '   fghij', '      kl', '    mnop', '    qrst', '      uv', '     wxy', '       z']

Up:
abocdiel
mf ghsjv
un rp k
zq x  t
 w    y

or
['abocdiel', 'mf ghsjv', 'un rp k ', 'zq x  t ', ' w    y ', '        ', '        ', '        ']

Down:

 b    e
af c  j
mn gd k
uq rhitl
zwoxpsyv
or
['        ', '        ', '        ', ' b    e ', 'af c  j ', 'mn gd k ', 'uq rhitl', 'zwoxpsyv']

Your goal is to rotate which operation is performed each iteration, performing them on the input n times. So if your order is URDL, and the input says to start with D (2, 0-indexed), and you need 5 operations, you perform D-L-U-R-D, then print.
Input:

A string in a format like above

Trailing spaces are not required (but they are probably helpful)
It will be at least 2x2
Will only contain printable ASCII and spaces (and newlines per your input format)
You should theoretically support any length, but memory constraints are okay

A non-negative integer, n, for the number of operations that will be performed
An integer 0-3 or 1-4, or a letter UDLR, describing the operation to start with.

So your program must be able to start or end with any operation
You may define them in any order for starting purposes, but it must be a consistent order, so U cannot sometimes follow R and also sometimes follow L.

Operations must be performed non-trivially

You could do operations in the order LDRU (left, down, right, up) repeatedly, but not DLRU or UDLR (because UD is the same as D, and LR is the same just as doing R.)

Output:

The string after performing the four operations n times
The output format must be the same as your input format
Trailing spaces are not required (but they are probably helpful)

Example:
This example uses the order URDL.
Input:
10  (number of times operations are applied)
0   (starts with Up)

ab cd e
 f ghij
      kl
mno p
 q r st
u      v
 w x  y
z
Outputs for n = 0-5: (just print the end result)
ab cd e
 f ghij
      kl
mno p
 q r st
u      v
 w x  y
z
---------------
abocdiel
mf ghsjv
un rp k
zq x  t
 w    y

---------------
abocdiel
 mfghsjv
   unrpk
    zqxt
      wy

---------------

      el
    dijv
   chspk
 bognrxt
amfuzqwy
---------------

el
dijv
chspk
bognrxt
amfuzqwy
---------------
eljvkxty
disprqw
chgnz
bofu
am

My pretty, ungolfed implementation

Related, but different, because that one can have letters "fall off the map".

Related

Should be only print the final result, or the intermediate steps too? Also, isn't the result just cyclic after all four operations have been performed once? (Not sure, just guessing)

Just the end result. And I confirmed that it is not cyclic.

Not cyclic after only four operations, that is. The period will be much longer.

Jelly, 23 bytes
UZ
Ç¡=⁶$Þ€Ç$⁴¡ZU$⁵+⁴¤¡Y

Try it online!
I'm a bit unsatisfied, but MATL needed some competition. :P
Uses the order URDL. Inputs:

the input array as an array of padded lines
the number of repetitions
the move to start from (1 = U, 2 = R, 3 = D, 4 = L)

Explanation
UZ       Helper link. Argument: A (the 2D array)
U        Reverse each line and...
 Z       ...transpose. Rotates 90° CCW.

Ç¡=⁶$Þ€Ç$⁴¡ZU$⁵+⁴¤¡Y    Main link. Arguments: A, n (2D array, repetitions)
Ç                       Rotate 90° CCW...
 ¡                      ...m times. (m = which move to start on)

     Þ                  Sort...
      €                 ...each line of the array...
  =⁶                    ...based on the characters' equality to " ".
       Ç                Rotate 90° CCW.
        $               Combine the sort and rotate to one action.
         ⁴¡             Do that n times. (n = repetition count)

           Z            Transpose and...
            U           ...reverse each line. Rotates 90° CW.
             $          Combine the transpose and reverse to one action.
                  ¡     Do that...
              ⁵+⁴¤      ...m + n times.

                   Y    Join the array by newlines.

JavaScript (ES6), 168 bytes
(n,d,s,t=s.replace([RegExp(`( )([^]{${l=s.search`
`}})(\\w)`),/(.)(\b)( )/,RegExp(`(\\w)([^]{${l}})( )`),/( )(\b)(.)/][d%4],`$3$2$1`))=>n?t!=s?f(n,d,t):f(n-1,d+1,s):s

Ungolfed:
function gravity(count, direction, string) {
    let width = string.indexOf('\n');
    let up = new RegExp('( )([^]{' + width + '})(\\w)');
    let down = new RegExp('(\\w)([^]{' + width + '})( )');
    while (count--) {
        let regexp = [up, /(.)(\b)( )/, down, /( )(\b)(.)/][direction++ % 4];
        while (regexp.test(string)) string = string.replace(regexp, '$3$2$1');
    }
    return string;
}

d is the initial index into the directions which are URDL.

Python 2, 226 224 204 193 bytes
-1 byte thanks to Trelzevir
x,s,n=input()
j=''.join
g=lambda x,i:[eval("j(_.split(' ')).%sjust(len(_))"%'lr'[i%2])for _ in x]
for i in([0,3,1,2]*n)[s:s+n]:x=[map(j,zip(*g(map(j,zip(*x)),i))),g(x,i)][i>1];print'\n'.join(x)

Try it online!
Function that remove all spaces of each element in the list and complete with spaces on left or right.
g=lambda x,i:[eval("''.join(_.split(' ')).%sjust(len(_))"%'lr'[i%2])for _ in x]

This to transpose (rotate 90º) when the input is 0 or 1(U or D) and apply g
x=[map(''.join,zip(*g(map(''.join,zip(*x)),i))),g(x,i)][i>1]

Extra space in for i in (...).

This is basically a golfed version of my implementation (I never bothered to golf it much).

MATL, 24 23 bytes
:+"@X!XJ_JXzJ32>S(c@_X!

Order is URDL, 1-based. So 1 is Ù,2isR` etc.
Inputs are: number of times, initial direction, char matrix (using ; as row separator).
Try it online!

I'll add an explanation later in the day


text:
Make mathematics with minimal matchsticks
Meta-background
This was set as a question on Puzzling, and the instant reaction was "well, someone will just solve that by computer". There was a debate about just how complex a program to solve this would have to be. Well, "how complex does this program have to be" is pretty much the definition of code-golf, so maybe PPCG can settle the issue?
Background
A matchstick equation is basically a normal mathematical equation, but where the digits and operators are constructed physically by placing matchsticks onto a table. (The main relevant feature of matchsticks here is that they're fairly rigid and have a constant length; sometimes people use other objects instead, such as cotton swabs.)
For this challenge, we don't need to define specific rules for how the matchsticks are arranged (like the linked challenge does); rather, we just care about how many matchsticks we'll need to represent an expression that evaluates to a given number.
The task
Here's an alphabet of digits and mathematical operators you can use, each having a cost in matchsticks:

0, costing 6 matchsticks
1, costing 2 matchsticks
2, costing 5 matchsticks
3, costing 5 matchsticks
4, costing 4 matchsticks
5, costing 5 matchsticks
6, costing 6 matchsticks
7, costing 3 matchsticks
8, costing 7 matchsticks
9, costing 6 matchsticks
+, costing 2 matchsticks
-, costing 1 matchstick
×, costing 2 matchsticks

(You may represent × as * in your program's output if you wish, in order to avoid needing to use non-ASCII characters. In most encodings, × takes up more bytes than *, and so I imagine that most programs will want to take advantage of this leeway.)
You need to write a program that takes a nonnegative integer as input (via any reasonable means), and produces an expression that evaluates to that integer as output (again via any reasonable means). Additionally, the expression must be nontrivial: it must contain at least one operator +, -, or ×. Finally, the expression you output must be the cheapest (or tied for the cheapest) in terms of total matchstick cost, among all outputs that otherwise comply with the specification.
Clarifications

You can form multiple-digit numbers via outputting multiple digits in a row (e.g. 11-1 is a valid output to produce 10). Just to be completely precise, the resulting number gets interpreted in decimal. This sort of concatenation isn't an operation that works on intermediate results; only on literal digits that appear in the original expression.
For the purpose of this challenge. +, -, and × are infix operators; they need an argument to their left and to their right. You aren't allowed to use them in prefix position like +5 or -8.
You don't have parentheses (or any other way to control precedence) available. The expression evaluates according to the typical default precedence rules (multiplications happen first, and then the additions and subtractions are evaluated left to right).
You don't have access to any mathematical operators or constants other than the ones listed above; "lateral thinking" solutions are often accepted at Puzzling, but it doesn't make sense to require a computer to come up with them itself, and over here on PPCG, we like it to be objective whether or not a solution is correct.
The usual integer overflow rules apply: your solution must be able to work for arbitrarily large integers in a hypothetical (or perhaps real) version of your language in which all integers are unbounded by default, but if your program fails in practice due to the implementation not supporting integers that large, that doesn't invalidate the solution.
If you use the same digit or operator more than once, you have to pay its matchstick cost each time you use it (because, obviously, you can't reuse the same physical matchsticks in two different locations on the table).
There's no time limit; brute-force solutions are acceptable. (Although if you have a solution that's faster than brute force, feel free to post it even if it's longer; seeing how alternative approaches compare is always interesting.)
Although writing an explanation of your code is never required, it's likely to be a good idea; code-golf solutions are often very hard to read (especially to people not familiar with the language they're written in), and it can be hard to evaluate (and thus vote on) a solution unless you understand how it works.

Victory condition
As a code-golf challenge, answers with fewer bytes are considered better. However, as usual, feel free to post answers with different approaches, or in specific languages even if they're more verbose than certain other languages; the goal of golf is really to see how far you can optimize a particular program, and doing things this way gives us lots of potential programs to optimize. So don't be discouraged if someone submits a solution using a completely different approach, or a completely different language, and gets a much shorter answer; it may well be that your answer is better-optimized and shows more skill, and voters on PPCG often appreciate that.

Jeez, whats the highest number we need to handle? My current attempt wouldn't run beyond like... maybe 20 on TIO.

@carusocomputing: Arbitrarily high in theory, but if you can't get over 20 within a reasonable time in practice, that's entirely acceptable.

Do you have any test cases?

I really wish this were a single operation, spread against multiple competitions. The multiplication is a divisor problem, but adding in addition and subtraction really complicates things. I have a solution that works, but not for the addition and subtraction; making that work perfectly will be tedious.

@carusocomputing: You might be interested in this challenge, then. I suspect the challenge with multiplication only is significantly different and would require rather different solution techniques to get a good score.

PHP, 241 Bytes
Online Version
function m($i){for(;$s<strlen($i);)$e+="6255456376"[$i[$s++]];return$e;}foreach($r=range(0,2*$a=$argv[1])as$v)foreach($r as$w)$x[$v+$w]["$v+$w"]=$x[$v*$w]["$v*$w"]=1+$x[$v-$w]["$v-$w"]=m("$v")+m("$w")+1;echo array_search(min($x[$a]),$x[$a]);

Breakdown
function m($i){
    for(;$s<strlen($i);)$e+="6255456376"[$i[$s++]];return$e; #return the count of the matchstick for an integer
}

foreach($r=range(0,2*$a=$argv[1])as$v) # limit to an input to 300 in the online version
foreach($r as$w)
       $x[$v+$w]["$v+$w"]=  #fill the 2D array in the form [result][expression] = count matchsticks
       $x[$v*$w]["$v*$w"]=
       1+$x[$v-$w]["$v-$w"]=
       m("$v")+m("$w")+1;
echo $k=array_search(min($x[$a]),$x[$a]); # Output expression with a minium of matchsticks
echo"\t".$x[$a][$k]; #optional Output of the count of the matchsticks

Way with a little better performance
function m($i){
for(;$s<strlen($i);)
$e+="6255456376"[$i[$s++]];return$e;} #return the count of the matchstick for an integer
foreach($r=range(0,2*$a=$argv[1])as$v)
foreach($r as$w){$c=m("$v")+m("$w")+1;
if($a==$v+$w)$x["$v+$w"]=1+$c; # fill array if value equal input
if($a==$v*$w)$x["$v*$w"]=1+$c;
if($a==$v-$w)$x["$v-$w"]=$c;}
echo $k=array_search(min($x),$x); # Output expression with a minium of matchsticks
    echo"\t".$x[$k]; #optional Output of the count of the matchsticks

Support of negative integers
Version with negative integers
function m($i){
    $e=$i<0?1:0; # raise count for negative integers
    for($s=0;$s<strlen($i);)$e+=[6,2,5,5,4,5,6,3,7,6][$i[$s++]];return$e; #return the count of the matchstick for an integer
}
$q=sqrt(abs($argv[1]));
$l=max(177,$q);
$j=range(-$l,$l); # for second loop for better performance
foreach($r=range(min(0,($a=$argv[1])-177),177+$a)as$v)
foreach($j as$w){$c=m("$v")+m("$w")+1;
    if($a==$v+$w)$x["$v+$w"]=1+$c; # fill array if value equal input
    if($a==$v*$w)$x["$v*$w"]=1+$c;
    if($a==$v-$w)$x["$v-$w"]=$c;
    if($a==$w-$v)$x["$w-$v"]=$c; # added for integers <0
}
echo $k=array_search(min($x),$x); # Output expression with a minium of matchsticks
echo"\t".$x[$k]; #optional Output of the count of the matchsticks

Oh snap, this works on negative numbers too!

@carusocomputing not really it could been that a solution exists with less matchsticks cause negative numbers are only added by subtraction. in this cases you should check the absolute value too and add an one

I don't think the literal 333 would be acceptable here, although you could likely fix it via making it some function of the input. (The program might well run much slower, so you could keep the hardcoded version for testing.)

@JörgHülsermann smart man... I only checked a few low numbers, but it seemed to work for a few of them.

The output for 1000 is not optimal. This gives 8*125 for 21 matchsticks, but 1000-1 is better with 19.

@mbomb007 replace 333 with 2*$argv[1] and it should be fixed but I found no online version that runs not in an error

@ais523 done 333 is replaced with 2*input

@carusocomputing after the change to 2* input it should not work with negative numbers

@mbomb007 1000 1111-111 are 15 Matchsticks. I have no idea what ist wrong with your program

@carusocomputing I have added a version for negative integers

@JörgHülsermann What program? I don't have one.

You can index strings: $e+="6255456376"[$i[$s++]];.

Python2, 1̶9̶8̶ ̶b̶y̶t̶e̶s̶  182 bytes thanks to math_junkie
def f(n,c=dict(zip('0123456789+-*',map(int,'6255456376212'))),e=[(0,'')]):
 while 1:
    v=(m,s)=min(e);e.remove(v)
    try:
     if eval(s)==n:return s
    except:0
    e+=[(m+c[x],s+x)for x in c]

This algorithm does nothing to exclude prefix versions of + and -, but they will either be worse than, or equal to and appear later in the search, their infix counterparts. Because it uses the keyword argument e mutably, it will give invalid results if called multiple times per session. To fix this, use f(n, e=[(0,'')]) instead of just f(n). Note that the four-spaced indents represent tabs, so this will only work with Python 2.
I also have an ungolfed and optimized version which runs quickly even for quite large numbers:
from heapq import heappop, heappush

def f(n):
    digits = list('0123456789')
    ops =['+','-','*','']
    costs = dict(zip(digits + ops, [6,2,5,5,4,5,6,3,7,6,2,1,2,0]))
    expressions = [(costs[d], abs(n - int(d)), int(d), d) for d in digits[1:]]
    seen = set()
    while 1:
        cost, d, k, expression = heappop(expressions)
        if d == 0:
            return expression
        for op in ops:
            if op in '+-' and k in seen:
                continue
            for digit in digits:
                if op and digit == '0':
                    continue
                expression1 = expression + op + digit
                k1 = eval(expression1)
                d1 = abs(n - k1)
                if d1 == 0:
                    return expression1
                heappush(expressions, (cost+costs[op]+costs[digit], d1, k1, expression1))
        seen.add(k)

Some minor suggested golfs: TIO (182 bytes)


text:
Indexize a number
Given a string of digits or an integer as input,  you will have to indexize it.
This is how you modify the input. We will use 30043376111 as an example:
First, find the sum of the indices of each occurrence of the respective digits:
0: 1 + 2 = 3
1: 8 + 9 + 10 = 27
3: 0 + 4 + 5 = 9
4: 3
6: 7
7: 6

Then, construct a new integer or string where the digits above go in the order of the sums of their indices. In the case that multiple digits yield the same sum, the smaller digit comes before the larger one:
047631

Finally, remove any leading zeroes, and return or print the result:
47631

You must write a program or function which returns or prints the input indexized.
This is code-golf, so shortest code in bytes wins!
More test cases can be added if requested.

For functions, is returning a string okay? How about taking a string as an argument?

@ConorO'Brien Given a string of digits or an integer

@AdmBorkBork Well, that answers the input question >_>

@ConorO'Brien Also, construct a new integer or string, which sounds like returning a string is OK, too.

May I take input as a list of characters? May I use 1-indexing instead of 0-indexing (if specified in answer)?

k, 7 bytes
.<+/'=$

online repl
  $30043376111 / convert to string($)
"30043376111"
  =$30043376111 / group(=) - return a mapping (dict) from unique chars to indices
"304761"!(0 4 5
 1 2
 ,3
 ,6
 ,7
 8 9 10)
  +/'=$30043376111 / sum(+/) each(') value in the dict
"304761"!9 3 3 6 7 27
  <+/'=$30043376111 / grade(<) ascending values - return keys from the dict
"047631"
  .<+/'=$30043376111 / execute(.) the string - convert it to a number
47631

Juxtaposition of functions is composition, so no explicit parameter or input is required.

J, 14 bytes
~.".@/:1#.I.@=

Accepts a string, returns a number.
Attempt This Online!
~.".@/:1#.I.@=
          I.@=  NB. = makes a boolean table of occurrences, each row is a unique item
            @   NB. monadic atop, f@g y => f g y
          I.    NB. returns indices of 1s in each boolean list from =
       1#.      NB. sums each resulting list
~.              NB. returns unique items from input
  ".@/:         NB. /: sorts x by y
    @           NB. dyadic atop, x f@g y => f x g y
  ".            NB. eval resulting indexized string

Haskell, 69 bytes
import Data.List
f x=0+read(nub$sortOn(\d->(sum$elemIndices d x,d))x)

Takes a string, returns a number. Usage example: f "30043376111" -> 47631. Try it online!
Pretty straight forward: sort the digits of the input string first on the sum of their indices and the by the digit itself (-> pairs of (sum ...,d)), remove duplicates and convert to a number to remove leading 0. The 0+ is needed to get the types right.

Stacked, 59 bytes
:@q uniq[:q\eq q size:>*sum,]map[-1#]sortby[0#]map''#`'^0'-

Try it online!
This takes a character string (like $'1231231') as input from the top of the stack, and leaves a string on the stack.
Explanation
:@q uniq[:q\eq q size:>*sum,]map        stack: (str)
:                                       stack: (str str)
 @q                                     stack: (str)        ; store as `q`
    uniq                                stack: (str')       ; de-duplicate
        [                   ]map        map the inner over each element
         :                              stack: (chr chr)
          q\eq                          stack: (chr q')     ; `q'` is where equality occurs
               q size:>                 stack: (chr, q', k) ; `k` is range from 0, size(q')
                       *sum             stack: (chr, k')    ; `k'` is sum of indices
                           ,            stack: ((chr, k'))

Now we are left with pairs of (chr, sum of indices).
[-1#]sortby[0#]map''#`'^0'-
[   ]sortby                    sort by the inner function
 -                             vectorized subtraction of two pairs
  1#                           use the second element as the comparison
           [0#]map             get the first element of each row
                  ''#`         join by the empty string
                      '^0'-    remove all leading zeroes

05AB1E, 29 28 bytes
-1 thanks to Riley
TFN¹SQDg<ÝsÏON‚}){vyD0å_i1è,

Try it online!
TFN            }             # Loop from 0 to 9.
   ¹SQ                       # Push 1 if index is same as `y`.
      Dg<ÝsÏ                 # Push index of the number instead of 1.
            ON‚              # Sum, combine with current `y`.
                ){           # Collect, sort 'em.
                  vyD0å_i1è, # Only print the ones with a count above 0.

Can you substitute TFN for 9Ývy

@Riley 05AB1E is a weird language... It seems the longer you use it the more you attempt to over-complicate EVERYTHING... Thanks, yes, that does seem to work fine.

JavaScript (ES6), 98 bytes
n=>+[...new Set(n)].sort().sort((a,b)=>(s=d=>[...n].reduce((S,D,i)=>S+i*(d==D),0))(a)-s(b)).join``

Takes a string n, then converts it to a Set and then to an Array of distinct digits. Sorts these digits in numerical order, then sorts again according to sums of indices. Concatenates the sorted Array to a String, and finally converts to a Number to remove leading zeros.

f=
n=>+[...new Set(n)].sort().sort((a,b)=>(s=d=>[...n].reduce((S,D,i)=>S+i*(d==D),0))(a)-s(b)).join``

console.log(f('30043376111'))

is the repeated sort necessary?

Yes, "In the case that multiple digits yield the same sum, the smaller digit comes before the larger one". Without the first .sort(), an input of 1332 yields 132 instead of 123.

Ah, okay, I see

Jelly, 10 bytes
Ġ’S$ÞịDFQḌ

Try it online!
Takes and returns an integer.
How?
Ġ’S$ÞịDFQḌ - Main link: n            e.g. 30043376111
Ġ          - group indices of n by value  [[2,3],[9,10,11],[1,5,6],[4],[8],[7]] (implicitly treats the number as a decimal list)
    Þ      - sort that by:
   $       -     last two links as a monad:
 ’         -         decrement (since Jelly is 1-indexed)
  S        -         sum                  [[2,3],[4],[7],[8],[1,5,6],[9,10,11]] (this leaves those indices of lower value to the left as required)
      D    - decimal list of n            [3,0,0,4,3,3,7,6,1,1,1]
     ị     - index into                   [[0,0],[4],[7],[6],[3,3,3],[1,1,1]]
       F   - flatten                      [0,0,4,7,6,3,3,3,1,1,1]
        Q  - unique                       [0,4,7,6,3,1]
         Ḍ - cast to a decimal number     47631

PowerShell, 88 bytes
$a=@{};[char[]]"$args"|%{$a[$_]+=$i++};+-join(($a.GetEnumerator()|Sort value,name).Name)

Try it online!
Sets an empty hashtable $a, then casts the input $args as a char array, and loops through each element |%{...}. We set the value at "the current element" of $a to be incremented by $i++, to count up our input's indices. For example, for input 300433766111, the first loop $a[3] gets +=0; the next loop, $a[0] gets +=1; etc.
Next, we need to Sort our hashtable. Unfortunately, due to an internal language quirk, this means we need to $a.GetEnumerator() before we can do the actual sorting. We sort by value, then by name, to satisfy the requirement of smaller digits get sorted first. We pull out the .Names thereof (in sorted order), -join them together into a string, and cast that string as an int + to remove leading zeros. That's left on the pipeline and output is implicit.

05AB1E, 11 bytes
ΣISQā<*O}Ùï

Try it online.
Could be 9 bytes if 1-based indexing is allowed by replacing ā<* with ƶ, in which case 4 would come before the 0 in the example, because 0: 2 + 3 = 5 and 4: 4:  try it online.
Explanation:
Σ         # Sort the digits of the (implicit) input by:
 I        #  Push the input
  S       #  Convert it to a list of digits
   Q      #  Check for each if it's equal to the current digit (resulting in 1s/0s)
    ā<*   #  Multiply each check by its 0-based index:
    ā     #   Push a list in the range [1,length] (without popping)
     <    #   Decrease each by 1 to make it the range [0,length)
      *   #   Multiply the values at the same indices in the two lists
       O  #  Sum the lists together
}Ù        # After the sort-by: uniquify the digits
  ï       # Cast it to an integer to remove potential leading 0s
          # (after which the result is output implicitly)

APL (Dyalog Unicode), 77 bytes
{⍎⊃{⍺[⍋⍵]}/{(⊂⊂⍋⊃⍵)⌷¨⍵}↓⍉{⍺(+/⍵-1)}⌸⍵}

Try it online!

Vyxal, 85 62 bits1, 10.625 7.75 bytes
µ?f=T∑;Uṅ⌊

Try it Online! (link is to bitstring)
-2.875 bytes (2 characters) thanks to @lyxal
Explanation
µ?f=T∑;Uṅ⌊  # Implicit input (as a string)
µ     ;     # Sort input string by:
 ?f         #  List of characters of input
   =        #  Equals the current character?
    T∑      #  Sum of truthy indices
       Uṅ⌊  # Uniquify and convert to integer
            # Implicit output

Old:
fDÞzµ∑;İfU₀β  # Implicit input
fD            # Convert to digit list and duplicate
  Þz          # Group by indices
    µ∑;       # Sort by sum
       İfU    # Index in, flatten, uniquify
          ₀β  # Convert from digit list
              # Implicit output

7.875 bytes

7.75 bytes - same sbcs byte count

Thunno 2, 10 bytes
Þ$d=VS;UJN

Port of my Vyxal answer (suggested by @lyxal)
Explanation
Þ$d=VS;UJN  # Implicit input
Þ     ;     # Sort the input string by:
 $d=        #  Vectorised equality with the input string's characters
    VS      #  Sum of truthy indices of that list
       UJN  # Uniquify, join, and convert to integer
            # Implicit output

PHP, 103 Bytes
for(;$i<strlen($a="$argv[1]");)$r[$a[$i]]+=$i++;ksort($r);asort($r);echo ltrim(join(array_keys($r)),0);

Python 2, 102 92 bytes
Thanks to Ben Frankel for saving 10 bytes!
a={}
for i,j in enumerate(input()):a[j]=a.get(j,0)+i
print int(''.join(sorted(a,key=a.get)))

Try it Online!
Takes input as a string and outputs an integer.
Uses a dictionary to store the sum of indexes, then sorts it by value.
Converts to an integer to strip off leading zeroes because int is shorter than .lsplit('0').

a[j]=a.get(j,0)+i saves 10 bytes.

Python 3.5, 86 85 bytes
Thanks @Ben Frankel for saving a byte:
f=lambda s:int(''.join(sorted({*s},key=lambda d:sum(i*(c==d)for i,c in enumerate(s)))))

Old code:
lambda s:int(''.join(sorted({*s},key=lambda d:sum(i for i,c in enumerate(s)if c==d))))

Anonymous function taking a string of digits and returning an integer

sum(i*(c==d)for saves 1 byte.

Pip, 18 bytes
+J:$+(a@*_)SKSNUQa

Takes the number as a command-line argument. Try it online!
Explanation
                    a is 1st cmdline arg (implicit)
               UQa  Get unique digits in a
             SN     Sort (numerically)
           SK       Then sort with this key function:
      a@*_           Find all indices of argument in a
   $+(    )          and sum them
 J:                 Join the resulting list back into a string (: is used to lower the
                    precedence of J)
+                   Convert to number (eliminates leading 0)
                    Print (implicit)

Scala, 123 104 bytes
(_:String).zipWithIndex.groupBy(_._1).toSeq.sortBy(c=>c._2.map(_._2).sum->c._1).map(_._1).mkString.toInt

Example (using Scala REPL):
scala> (_:String).zipWithIndex.groupBy(_._1).toSeq.sortBy(c=>c._2.map(_._2).sum->c._1).map(_._1).mkString.toInt
res0: String => Int = <function1>

scala> res0("30043376111")
res1: Int = 47631

Pretty straightforward, using tuple as sorting predicate for secondary sort.

Pyth, 9 bytes
sosxNcQ1{

Try it online
Takes a string of digits as input.
sosxNcQ1{
sosxNcQ1{Q    Implicit variable introduction
        {Q    Unique digits
 o            Order by
     cQ1      Chop input into list of individual characters.
   xN         Find all indexes of the digit in question in the list.
  s           Sum
s             Convert string to integer.

K (ngn/k), 16 7 bytes
.<+/'=:

Try it online!
Down 9 bytes thanks to ovs for the sum tip!
A pretty literal implementation of the challenge. Takes a string and output an integer.
Explanations:
.<+/'=:  Main function. Takes implicit input with :
     =   Group, creates a dictionary with characters as
         the keys and their occurances position as the
         values
    '    In each of the key's values...
  +/     Sum
 <       Sort by ascending order
.        Evaluate

Applying +/' to a dictionary implicitly applies +/ to each key and returns an updated dictionary.

Ruby, 96 bytes
I'm sure this can be golfed more.
->a{(0..9).map{|n|[(0...a.size).select{a[_1]==n}.sum,n]}.select{_1[0]>0}.sort.map{_2}.join.to_i}

Attempt This Online!

Japt v2.0a0 -N, 10 bytes
ñ ñ@ðX xÃâ

Try it
Input as a string
Explanation:
ñ ñ@ðX xÃâ
ñ          # Sort the digits by value
  ñ@    Ã  # Stable-sort the digits by this function:
    ðX     #  Find all indices where it appears in the input
       x   #  Sum them
         â # Remove repeated characters

-N         # Convert the string to number (removes leading 0)

10 bytes, with the -N flag.

@Shaggy Good find, I looked into -N but it didn't work on arrays of digits so I didn't find a way to use it.

Actually, do we need the first sort here?

C#, 245 bytes
using System.Linq;s=>{var a=new int[10];for(int i=0,l=0;i<10;i++){a[i]=-1;while((l=s.IndexOf(i+"",l+1))!=-1)a[i]+=l;}return string.Concat(a.Select((c,i)=>new{c,i}).OrderBy(o=>o.c).ThenBy(o=>o.i).Where(o=>o.c>-1).Select(o=>o.i)).TrimStart('0');};

Not happy with how long it ended up being and it can probably be shorter but this is what I ended up with.

Perl 6,  65 61  52 bytes
{+[~] {}.push(.comb.map:{$_=>$++}).sort({.value.sum,.key})».key}

Try it
{+[~] {}.push(.comb.antipairs).sort({.value.sum,.key})».key}

Try it
{+[~] .comb.antipairs.Bag.sort({.value,.key})».key}

Try it
Expanded
{      # bare block lambda with implicit parameter ｢$_｣

  +    # turn the following into a Numeric
  [~]  # reduce the following using &infix:<~> (join)

    .comb              # list of digits from ｢$_｣ (implicit method call)
    .antipairs         # get a list of ｢value => index｣ pairs from above list
    .Bag               # combine them together (does the sum)
    .sort(
      { .value, .key } # sort it by the sum of indexes, then by the digit
    )».key             # get the list of digits from that
}

Scala, 131 bytes
Golfed version. Try it online!
def f(x:String)=scala.collection.immutable.SortedSet(x:_*)(Ordering.by((d:Char)=>(x.indices.filter(x(_)==d).sum,d))).mkString.toInt

Ungolfed version. Try it online!
import scala.collection.immutable.SortedSet

object Main {
  def main(args: Array[String]): Unit = {
    println(f("30043376111"))
  }

  def f(x: String): Int = {
    val sortedUnique = SortedSet(x: _*)(Ordering.by((d: Char) => (x.indices.filter(x(_) == d).sum, d)))
    sortedUnique.mkString.toInt
  }
}