text:
Evaluate polynomial expression string
Create a function which takes a polynomial equation, a value for x and returns the result of the operation.
Example: given 4x^2+2x-5 and x=3 output 37. This is the result of 4(3)^2+2(3)-5

Assume all polynomials are valid
Polynomial format will always be coefficient(variable)^exponent => 4x^2 except :

When exponent is 1 it will be coefficient(variable) => 4x
When coefficient is 1 it will be (variable)^exponent => x^2

Polynomials are one variable only
Use of external libraries are forbidden
The coefficient and variable input can be positive and negative numbers.

Test cases

("3x^3-5x^2+2x-10", 5)          => 250
("10x^4-5x^3-10x^2+3x+50", 3)   => 644
("10x+20", 10)                  => 120
("-20x^2+20x-50", -8)           => -1490
("9", 5)                        => 9
("8x^2+5", 0)                   => 5

Update

Polynomial format will always be coefficient(variable)^exponent => 4x^2 except :

When exponent is 1 it will be coefficient(variable) => 4x
When coefficient is 1 it will be (variable)^exponent => x^2

Removed the rule of negative exponent. My mistake. A valid polynomial does not contain negative exponent
An exponent of 0 would be just coefficient
Added test case for input 0

This is code-golf, so the shortest answer in bytes win.

How flexible is the input format? Instead of 3x^3-5x^2+2x-10 can we input 3*x^3-5*x^2+2*x-10? Or [3 -5 2 -10]. [3 2 1 0]?

Can the exponent input sign be ** instead of ^?

@sergiol no....

Can we take X in uppercase?

@Arnauld Yes...

What is an "external library" and how is it fair, compared to languages who have "eval" already implemented as a feature?

My apologies I haven't use my pc since yesterday. I have updated the challenge with the suggestions you gave me. Please take a look at it and reopen it if everything is ok.

Please merge the "Update" part.

(also don't worry too much about slow update, closed challenges can be reopened, etc.)

Your specs don't match your examples.  It should be 10x^0 under your specs, but your examples use 10.

Your test cases don't have any coefficients of 1

JavaScript (ES7), 48 bytes
Based upon a suggestion from @RickHitchcock
Expects X in uppercase. Takes input in currying syntax (p)(X).
p=>X=>eval(p.replace(/[X^]/g,c=>c<{}?'*X':'**'))

Try it online!

JavaScript (ES7), 49 bytes
Same approach as @DeadPossum. Takes input in currying syntax (p)(x).
p=>x=>eval(p.split`x`.join`*x`.split`^`.join`**`)

Try it online!

I think you can save a couple bytes by using replace:  p=>x=>eval(p.replace(/[x^]/g,a=>a>f?'*x':'**'))

@RickHitchcock I can't use a reference to f unless it's included in the byte count, at the cost of the 2 bytes that are supposed to be saved. I like this method, though. There might be a way to save a byte or two by revamping it somehow.

Oh, of course.  Hmm.

@RickHitchcock If we can take X in uppercase, then we can do a<{}?'*X':'**', saving a byte. Hence my question to the OP.

cant handle x alone

@l4m2 The challenge rules were updated. :/ It used to be 1x for x.

Python 2, 54 bytes
-2 bytes thanks to Jo King
-5 bytes thanks to Arnauld
lambda p,x:eval(p.replace('^','**').replace('x','*x'))

Try it online!

Python 3, 53 50 48 bytes
edit: -5 bytes thanks to Dennis !
lambda p,x:eval(p.translate({94:"**",120:"*x"}))

Try it online!
Used translate to avoid chaining replace calls; Python 3's version of translate is less awkward than its predecessor's.

"*(%d)"%x can become "*(x)".

Thank you, I hadn't event figured out x was in my eval scope ! I'll update.

Actually, since x is no longer a string representation, "*x" works as well.

Even better ! Thanks again.

R, 44 bytes
function(f,x)eval(parse(t=gsub("x","*x",f)))

Try it online!
Fairly straightforward with R. Replace nx with n*x and then eval the parsed string. x is used as this is how we name the second argument.
The eval function could even be used more directly with a properly formatted first argument, and other formal arguments (y, z, etc.) could be easily added:
R, 20 bytes (non-competing)
function(f,x)eval(f)

Try it online!

JavaScript (Node.js), 113 108 bytes
_=>x=>_.match(/-?(?:[x\d]+|\^?)+/g).reduce((a,b)=>b.split`x`[0]*(~b.indexOf`x`?x**(b.split`^`[1]||1):1)+a,0)

Try it online!
Thanks to @Arnauld

Since the best JS solution so far by @Arnauld (49 bytes) has already been posted and it uses eval, I decided to use Regex and reduce instead of that.
Pretty lengthy compared to his though.
Explanation :
A =>                            // lambda function accepting argument 1
    x =>                        // argument number 2 (currying syntax used)
        A.match(                // this matches all instance of what comes next
                                // and converts to array
       /[-]?(?:[x\d]+|\^?)+/g)  // regexp for -ve sign , variable number and ^ sign
            .reduce((a, b) =>   // reduce the array to single (take 2 params a,b)
                b.split `x`     // split b at instances of `x`
                        [0]     // and select the first instance
                * (b.indexOf`x` // multiply that by value of index of x in b
                    > 0 ?       // if it is greater than 0 then
                x **            // multiplication will be with x raised to power
               (l = b.split `^` // set variable split b at every `x`
                   [1]||1       // choose first index otherwise set to one
                )               // this is what x is raised to the power
                : 1)            // in the case x is not present multiply by 1
                + a,            //  add value of `a` to that value
        0)                      // in case no reduce is possible set value to 0

This currently fails on the last test case (should be 0.25). You can save a few bytes by using - instead of [-], ~b.indexOf\x` instead ofb.indexOf`x`>0and removingl=` which is not used. (But this doesn't fix the bug.)

@Arnauld: Thanks. No idea why it does that, will see what the problem

Well, the problem is that your regex splits 1x^-2 on the -.

Japt 2.0, 13 bytes
OvUd^'*²'x"*V

Try it.
Explanation:
OvUd^'*²'x"*V
              U = Implicit first input
              V = Implicit second input

Ov            Eval:
  Ud            In U, replace:
    ^             "^" with:
     '*²            "**"
        'x        "x" with:
          "*V       "*V"

Wolfram Language (Mathematica), 22 bytes
ToExpression@#/.x->#2&

Try it online!

TI-Basic, 6 bytes
Prompt X:expr(Ans

Expression is taken as argument and X is entered during runtime. Alternatively 8 bytes without expr:
Prompt X,u:u

Here both arguments are entered at runtime.

05AB1E, 16 19 bytes
„*(I')J'xs:'^„**:.E

+3 bytes as bug-fix for negative input x.
.E (Run as Batch code) has been replaced with Run as Python eval in this latest commit of @Adnan, but this version isn't on TIO yet. @Mr.Xcoder tested it on his local (latest version) 05AB1E to verify it's working.
See this version without .E to see how it converted the expression string.
Explanation:
„*I')J'xs:    # Replace all "x" with "*(n)" (where `n` is the input-integer)
              #  i.e. 5 and 3x^3-5x^2+2x-10 → 3*(5)^3-5*(5)^2-2*(5)-10
'^„**:        # Replace all "^" with "**"
              #  i.e. 3*(5)^3-5*(5)^2-2*(5)-10 → 3*(5)**3-5*(5)**2-2*(5)-10
.E            # Evaluate as Python-eval
              #  i.e. 3*(5)**3-5*(5)**2-2*(5)-10 → 250

Alternative 25 28 bytes program that works on the current version of TIO:
„*(I')J'xs:'^„**:“…¢(“s')J.e

Try it online.
Explanation:
„*(I')J'xs:'^„**:    # Same as explained above
“…¢(“                # Literal string "print("
     s               # Swap both
      ')             # Literal character ")"
        J            # Join everything together
                     #  i.e. 3*(5)**3-5*(5)**2-2*(5)-10 → print(3*(5)**3-5*(5)**2-2*(5)-10)
.e                   # Run as Python code
                     #  i.e. print(3*(5)**3-5*(5)**2-2*(5)-10) → 250

“…¢(“ is the string print(, because:

“ and “ starts and ends the compressed string
…¢ is equal to 0426 because it looks at the indices in the info.txt file, where … has index 4, and ¢ has index 26.
This index 0426 is then used in the dictionary-file, where line 427 (index 426) is the word it fetches, which is print in this case.
The ( doesn't have an index in the info.txt file, so it is interpret as is.

JavaScript (Node.js), 143 bytes
I know there are better answers but I wanted to do it without using eval
(_,x)=>_.match(/[+-]?(?:[a-z0-9.]+|\^-?)+/gi).reduce((a,b)=>~~(b.split('x')[0])*(b.indexOf('x')>0?Math.pow(x,(l=(b.split('^')[1]))?l:1):1)+a,0)

Try it online!

Your regex doesn't need [a-z0-9.] does it?  The only letter that can appear is x.  Any why .?  You don't need to handle non-integer coefficients or exponents.

Physica, 35 bytes
->e;x:Eval@Replace[e;"x";f"*({x})"]

Try it online!

Octave, 47 38 37 bytes
Saved a lot of bytes by taking the second input as a string instead of a number.
@(x,c)eval(strrep(x,'x',['*(',c,41]))

Try it online!
Explanation:
Fairly straight forward: Replace x by (c) , where c is the second input, and evaluate. The paretheses are necessary because in Octave -8^2 == -64.

Java 8, 150 149 148 bytes
n->s->new javax.script.ScriptEngineManager().getEngineByName("JS").eval(s.replace("x","*"+n).replaceAll((s="(\\-?\\d+)")+"\\^"+s,"Math.pow($1,$2)"))

Not sure if it's possible to have a currying lambda function that throws an Exception. If it is, 1 byte can be saved changing (s,n)-> to n->s->. -1 byte thanks to @OlivierGrégoire for showing me how to do this.
Try it online.
Explanation:
n->s->     // Method with integer and String parameters and Object return-type
  new javax.script.ScriptEngineManager().getEngineByName("JS")
            //  Use a JavaScript engine
   .eval(s  //  And eval the input
      .replace("x","*"+n)
            //   After all 'x' has been replaced with '*n'
            //   (where `n` is the input-integer)
      .replaceAll((s="(\\-?\\d+)")+"\\^"+s,"Math.pow($1,$2)"))
            //   And all `A^B` have have been replaced with `Math.pow(A,B)`
            //   (where both `A` and `B` are integers)

Unfortunately the JavaScript eval doesn't support **, so I have to use a longer replace to convert it to Math.pow instead..

JavaScript does support ** (ES7+), why does this not support that ?

Also is there no eval in java. That can't be right ?

@MuhammadSalman Nope, Java has no eval. And I think this builtin JavaScript-eval I can use with ScriptEngineManager hasn't been updated in the Java JDK for years, so it doesn't support ES7+..

Man, java sucks, no eval why ? Okay why hasn't it been updated ?

@MuhammadSalman I dunno.. You'll have to ask the creators of Java that question. ;)

Good idea, will go ask them (most of of your byte count is for importing the engine

Yes, there's an eval in java, since Java 9.

And here's your curried version (148 bytes) ;-)

Ruby, 43 41 bytes
->p,x{eval p.gsub('^','**').gsub'x','*x'}

Try it online!
Saved two bytes thanks to @Mr.Xcoder

Since there isn't a Ruby answer yet I added one.  Nvm there was one that used a different approach
Explanation :
->p,x{                    # lambda function that takes two arguments p and x
    eval(                 # eval
        p.gsub(           # replace all instance of
            '^' , '**'    # `^` with `**` (use for raised to power of)
        )                 # end gsub
        .gsub(            # start another replace all
            'x' , '*x'    # replace all instances of `x` with `*x`
        )                 # end the replace function
    )                     # end eval function
}                         # end lambda function

I think using gsub"x","*x" saves two bytes.

Jelly, 21 bytes
ṣ”^j⁾**ṣ”xjØ(j”*;Ʋ}ŒV

Try it online!

Due to operator precedence, this doesn't work for ("-20x^2+20x-50", -8).

@Dennis Adjusted accordingly.

Excel, 36+2 bytes,  Non-competing
Evaluating a Text field as a formula is not straight forward in Excel.  There is a hidden =EVALUATE() function, that can be called by defining a  Name.
In Excel 2007, Formulas > Define Name.  Define a Name called E, with Refers to:
=EVALUATE(SUBSTITUTE(A1,"x","*"&B1))

Then, with Formula input in A1, x value in B1, entering =E in C1 returns expected result.

Ruby, 43 bytes
->s,x{eval s.gsub /[x^]/,?x=>"*x",?^=>"**"}

Try it online!

Nice approach with hash replacement, but straight two gsubs are even shorter

Perl 5 -pl, 35 bytes
s/\^/**/g;$q=<>;s/x/*($q)/g;$_=eval

Try it online!

Wolfram Language (Mathematica), 19 bytes
(x=#;ToExpression)&

Try it online!
Take input by currying: f[x][expr].


text:
Animate Jacob's ASCII Ladder
You may have seen Jacob's Ladder in children's science museums. If you're not familiar with what they look like, there are several images and video examples on the Wikimedia Commons. The challenge today is to create an animated ASCII version of the electrical gadget. In the end, it should look something like this:

Ladder Construction
Here is the basic shape of a ladder with a height (H) of 6:
6   \            /
5    \          /
4     \        /
3      \      /
2       \    /
1        \  /
0         ¯¯

The numbers on the left simply indicate row number for this example and should not be included in the output. We'll refer to a given row by it's number (R). Row 0 is the bottom ¯¯. Each row 1 through H is comprised of four parts:

A space  (U+0020) repeated (H - R) times
A back slash \ (U+005C)
A space  (U+0020) repeated (2 * R) times
A forward slash / (U+002F)

Row 0 is identical except both the slashes are replaced with a macron ¯ (U+00AF). Trailing whitespace at the end of each line or below the ladder is OK. Leading whitespace is not.

Arc Construction
Once the ladder is constructed, you can create arcs between the left and right side. One arc is entirely within a row and replaces the spaces between the leading \ and trailing /. Therefore, row 2 will have 4 characters in its arc, row 3 will have 6, and so forth. Each arc is composed using the following rules:

The only allowable characters are _/¯\ (U+005F, U+002F, U+00AF, U+005C)
In order to ensure a smooth appearance, any ¯ or / must be followed by a ¯ or \
In order to ensure a smooth appearance, any _ or \ must be followed by a _ or /
The two rules above apply to the edges of the ladder as well
The three rules above effectively mean that the first character in the arc must be _ or / and the last character must be _ or \ (\¯\_// is invalid on both ends but \_/¯\/ is OK)
There must be a non-zero chance for each allowable character to occur at a given point
Each arc is independent from every other arc

Animation
The life of a single arc is created by starting it at row 1 and "moving" it up one row at a time until it reaches the top. I.E., first generate an arc at row 1, then set it back to spaces and generate an arc at row 2, and so forth. Given a number of arcs to show (N), show the complete life of that many arcs one at a time using the following guidelines:

Only one arc should be "alive" at any one time. The next arc cannot start until the current one reaches the top and then extinguishes.
Each row of the arc's life should be shown for exactly one frame
There should one frame of just the basic ladder (with no arcs) before a new arc starts (optional before the first arc)
The animation should show the full life of N arcs. If N=0, it should animate random arcs forever until stopped.
If N>0, you may still loop the animation forever but it must be a loop of the same arcs over and over. (The example GIF at the top of this post has H=6 and N=3 but it loops forever.)
The animation should occur in-place. That is, each frame should completely overwrite the next frame and be in the same location.
The length of each frame can be whatever you want but make it watchable by a human (I.E., use your common sense: 0.01s/frame and 30s/frame are both unacceptable.)

Input / Output

Input and Output can be in any standard format
You can export a GIF, write text to the screen, output a single file for each frame, or any other reasonable means
Standard loopholes are forbidden
The height of the ladder H will be a positive integer
The number of arcs to show N will be a non-negative integer
Both H and N are taken as inputs in any order you choose (Please include the order in your answer)

Winning Condition
This is code-golf so the shortest code wins.
Sandbox

Can arc be generated symmetrical by its center? I can't see restriction to that in rules

Can i print each frame after each other to the console?

@DeadPossum I was thinking you were right despite the fact it wouldn't look very lightning-y but it's actually disallowed by the combination of two rules: the first character in the arc must be _ or / and the last character must be _ or \  and There must be a non-zero chance for each allowable character to occur at a given point. In order to be symmetrical, both the first and last character would have to be _ every single time which means there is zero chance of either / or \\ occurring.

@TFeld So long as each frame appears in the same location on the screen, yes. That means you'll have to clear the console (or maybe scroll down, if that's possible) each time.

@EngineerToast I meant lightning like /\/\/\ is symmetrical by center. Visually, not character-wise

@DeadPossum There's nothing wrong with that segment by itself, no. You have to encapsulate it in the ladder, though, so that last forward slash can't be the last character of the arc. (Side note: formatting slashes as code in comments is tricky.)

Does the macron requirement mean that QBasic can't compete? It uses CP437, in which code point 0xAF is ».

@DLosc I hate to exclude language but, sadly, the macron is needed to make the arc appear consistent. I don't see anything in that code page that fits the bill, but I'll edit it in if you can find something that aligns with the top of the slashes.

JavaScript (ES6), 245 bytes

f=(o,h,n,i=0)=>(o.innerText=[...Array(h+1)].map((_,j)=>` `.repeat(j)+(j<h?`\\${[...Array(w--*2)].map((_,k)=>h+~j-i?` `:k>w*2|Math.random()<.5?s[s=t,1]:s[s=`¯\\`,0],s=t=`/_`).join``}/`:`¯¯`),w=h).join`
`,(++i<h||--n)&&setTimeout(f,250,o,h,n,i%h))
Height: <input type=number min=1 value=6 id=h>
Arcs: <input type=number min=0 value=3 id=n>
<input type=button value=Go! onclick=f(o,+h.value,+n.value)>

Byte count assumes ISO-8859-1 encoding.

It's possible to reduce it to 242 by defining A=x=>[...Array(x)].map; at the begining and replacing both usages.

@Bary12 You can't return map, that's just a property of Array.prototype and no use on its own. I tried working versions but they all came out longer than 245 bytes.

Python 2, 287 271 270 276 275 bytes
import time,random
r,n=input()
c=n*-~r or-r
while c:
 c-=1;L=[list(' '*i+'\\'+'  '*(r-i)+'/')for i in range(r)];x=c%-~r;time.sleep(1);y=x+1;exec"L[x][y]=random.choice('\xaf/\_'[L[x][y-1]in'\_'::2][y==2*r-x:]);y+=1;"*2*(r-x)
 for l in['']*99+L+[' '*r+'\xaf'*2]:print''.join(l)

Try it online!
Does not clear the screen on tio, but works in a console.
Gif of it running:

A bit sneaky but you could use print'\n'*99 instead of os.system('cls') and lose the os import. Still doesn't work on TIO but works in both Windows and Linux consoles.

There should [be] one frame of just the basic ladder (with no arcs) before a new arc starts (optional before the first arc)

I think you're using hyphens (U+002D) instead of macrons (U+00AF). I don't think it'll increase your byte count to fix it. Also, as @wastl pointed out, there's no empty ladder frame between arcs.

The bottom row uses macrons but the arcs do not

@EngineerToast Fixed now :)

The length of each frame can be whatever you want but make it watchable by a human allows you to choose a frame time of one second, thus not needing a byte for the decimal point.

It's 2018 and people use PowerShell unironically? You should try jQuery.

C (gcc), 406 bytes
#define p(X) printf(X),usleep(999)
#define x(X) do{s[X]=0;p(s);s[X]=' ';}while(0)
char c[2][2]={95,47,92,'¯'};R;i;j;k;a(){char s[2]={92,0};for(j=0;j<2*R-1;++j,p(s))*s=c[*s<50][rand()%2];*s=c[*s<50][0];p(s);}f(H,N){char s[99];for(i=0;i<99;++i)s[i]=' ';p("\e[s");for(i=0;;++i){i%=(N?N:i+1);srand(i^H^N);for(k=1;k<H;++k){for(R=H;--R;){x(H-R+1);p("\\");if(R==k)a();else x(2*R);p("/\n");}x(H);p(" ¯¯\n\e[u");}}}

Try it online!
Description:
#define p(X) printf(X),usleep(999)              // Define p to printf(p) + delay
#define x(X) do{s[X]=0;p(s);s[X]=' ';}while(0)  // Define x(X) to print X spaces
                                                // This uses a string s full of
                                                // spaces and adds the null
                                                // terminator where approrpiate
char c[2][2]={95,47,92,'¯'};                    // 2d array of 'next arc' options
R;i;j;k;                                        // Variables
a(){                                            // a() -> print arc for row R
    char s[2]={92,0};                           // s is a string of next char
                                                // initialize to backslash
    for(j=0;j<2*R-1;++j                         // loop over each character
            ,p(s))                              // printing s each time
        *s=c[*s<50][rand()%2];                  // set s to the next arc char
    *s=c[*s<50][0];                             // set s to the 'first' arc char
                                                // note that in definition of c
                                                // first means appropriate as
                                                // final character before /
    p(s);}                                      // print the last character
f(H,N){                                         // f(H,N) -> print jacob ladder
    char s[99];for(i=0;i<99;++i)s[i]=' ';       // this is the space string for x
    p("\e[s");                                  // ANSI terminal save position
    for(i=0;;++i){i%=(N?N:i+1);                 // loop i->N (or i->INT_MAX if N=0)
        srand(i^H^N);                           // seed random with i XOR H XOR N
        for(k=1;k<H;++k){                       // for each row (bottom to top)
            for(R=H;--R;){                      // for each row (top to bottom)
                x(H-R+1);p("\\");               // print left "    \"
                if(R==k)                        // if on the arc row
                    a();                        // print the arc
                else x(2*R);                    // otherwise print spaces
                p("/\n");}                      // finish off the row
            x(H);p(" ¯¯\n\e[u");}}}             // print bottom line and move back

Note: only really works in Xterm... many terminal emulators just don't support save/restore position.

The bottom row is row 0 and has two macrons only. It is not \--/. That's probably an easy fix. Are you able to capture and post a GIF of it working in Xterm?

Sadly I lack the tools to do that (just playing around during build times at work). I will update with correct row 0 though, it is an easy fix.

Invalid: There should [be] one frame of just the basic ladder (with no arcs) before a new arc starts (optional before the first arc)

changing k=1 to k=0 fixes that... 0 byte cost. Will update soon.

You don't need a space between the macro and the definition.

341 bytes

PowerShell, 347 319 bytes
filter c{Param($h,$n)if($n-eq0){$n=-1}for($x=0;$x++-ne$n;){($h..1)|%{$l=(($h..1)|%{"$(" "*($h-$_))\$(" "*$_*2)/"})+"$(" "*$h)¯¯"
$r="Get-Random"
$i=0
$z=-join((0..(($h-$_)*2))|%{$i=switch($i%3){0{&$r 0,1}default{&$r 2,3}}"_/¯\"[$i]})+"_\\_"[$i]
$l[$_-1]=($l[$_-1]).Substring(0,$_)+"$z/"
cls
$l
Sleep -m 250}}}

Try it online! Couldn't get $args to play nice, so the link calls the function without clearing the console.
Ungolfed
filter c{
    Param($h,$n)
    if($n -eq 0){$n=-1} # inelegant swap to allow for an infinite loop.
                        # Curse you zero-indexing!
    for($x=0;$x++-ne$n;)
    {
        ($h..1) | % {
            $l=(($h..1)|%{ # (( double paren is needed to induce each line
                           # as a new array element
                "$(" "*($h-$_))\$(" "*$_*2)/" # offset by total height.
                                              # N spaces + rung + N*2 spaces + rung
            })+"$(" "*$h)¯¯" # last line is the floor of the ladder

            $r="Get-Random" # shorter to declare once and execute with & operator

            $i=0 # initialize $i so we choose only _ or / for the first char

            $z=-join( # build an electric ZAP!
                (0..(($h-$_)*2))|%{
                    $i = switch($i%3) { # choose next char based on previous selection
                        0{&$r 0,1}
                        default{&$r 2,3}
                    }
                    "_/¯\"[$i]
                }
            )+"_\\_"[$i] # final char is \ or _ to rejoin the ladder
            $l[$_-1]=($l[$_-1]).Substring(0,$_)+"$z/" # select one rung of the ladder
                                                      # append an electric ZAP!
            cls # clear the console
            $l  # display the ladder
            Sleep -m 250
        }
    }
}

It's a small thing, but the bottom row is hyphens instead of macrons. It's a zero-byte change $l=(($h..1)|%{"$(" "*($h-$_))\$(" "*$_*2)/"})+"$(" "*$h)¯¯"

¯\(°_o)/¯ oops! swapped in macrons :p

I don't know PowerShell too well, but you can remove most of the new-lines. In addition for($x=0;$x-ne$n;$x++) can be for($x=0;$x++-ne$n;). I got it down to 324 bytes (321 chars) doing so. Tips for golfing in  and Tips for golfing in PowerShell might be interesting to read through as well.

sleep 1 saves a bit (it defaults to -seconds) but is pretty slow but still reasonable-ish, sleep -m 99 is pretty quick but also reasonable. Saves 5/1 bytes depending on what you like. Didn't check Kevin's attempt but function to filter is a free byte as well.

Ruby, 293 bytes
m={}
"   __/\\_/¯¯\\/¯\\".chars.each_slice(3){|e|u,*v=e;m[u]=v}
a=->l,c{l<1?"/":(d=m[c].sample;c+a[l-1,d])}
n=gets.to_i
h=gets.to_i
o=0
while o<n||n<1
h.times{|i|puts (0...h).map{|j|" "*j+"\\"+a[2*(h-j),i==h-j-1?["_","/"].sample: " "]}*"\n";puts" "*h+"¯¯";sleep(0.3);puts"\n"*99}
o+=1
end

Try it online!
I'm on windows so it just prints many "\n" to clear the console. Takes 2 arguments n and h as two lines on stdin.

source: Stack Exchange

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

sort: votes


text:
Which number is bigger?
Define f(a,b) := a if b=1; a^f(a,b-1) if b>1 (Tetration, where ^ means power) for positive integers a and b, given four positive integers a,b,c,d, compare f(a,b) and f(c,d).
Your program should output three constant values to mean "greater", "less" and "equal".
Samples:
a b c d f(a,b) output f(c,d)
3 2 2 3 27     >      16
4 2 2 4 256    <      65536
4 1 2 2 4      =      4

Lowest time complexity to max{a,b,c,d} win, with tie-breaker code length(the shorter the better) and then answer time(the earlier the better).
Complexity assumption

Your code should handle a,b,c,d up to 100, and your algorithm should handle all legal input
You can assume integer calculations (that your language directly support) in O((a+b+c+d)^k) cost O(1) time if can be done in O(1) for 2k bit numbers if k bit computing can be done in O(1)
For example, both plus(+) and multiply(*) can be done in O(1) for 2k bit numbers if k bit computing for both can be done in O(1), so both satisy the requirement. It's fine if multiply can't be done without plus, or even if both can't be done without each other.
Float calculations in O(log(a+b+c+d)) bit precision in ±2^O((a+b+c+d)^k), takes O(1), with same requirements like integer calculations.

[tag:code-golf] and [tag:fastest-algorithm] are conflicting with each other.

@EriktheOutgolfer Fastest-algorithm challenges often result in ties, because the number of different complexities if often rather limited for certain problems, and once an optimal solution has been found there is a good chance others will be posted. For these cases, a tie-breaker should always be specified. Common choices are earliest answer, shortest code-length of the given implementation or shortest actual runtime on a given problem set.

Do any of these rules prevent a lookup table from being used?

@user2699 and your algorithm should handle all legal input, if k bit computing can be done in O(1) (time, space & code)

Can you clarify how complexity is measured?  Your comment mentions time and space, while Big-O notation measures approximate running time, but the description also seems to include individual floating point operations.

@l4m2 I think [tag:code-challenge] is more applicable than two separate tags here, since those two tags each mean that the criterion they describe is absolutely the only one, and, if I search for [tag:code-golf] challenges, I won't expect to find a challenge with a winning criterion like this one's.

Tetration is actually defined with a if b=0 as the base case, not b=1 as in the challenge. Is this intentional?

@hakr14 The definition in wiki is 1 if b=0, but I don't require handle of zero, so it's a if b=1

@EriktheOutgolfer I see some posts put all layers of winning criticia as tag and some put only the first, but code-challenge mean the combination of bother affect the rank together, rather than one first and another as tie-breaking

Usually a primary win-condition tag is used ([fastest-algorithm] in this case), and the challenge itself states what to do on tie-breakers without an additional tag. I definitely understand why you've added the [code-golf] tag as tie-breaker. Once an efficient algorithm is found, others might copy it, or the amount of algorithms to be used is limited from the beginning maybe. But as mentioned by @EriktheOutgolfer, when I search for code-golf challenges, I wouldn't expect these kind of challenges to pop up.

@KevinCruijssen Once an efficient algorithm is found, others might copy it, and it will turn into a [tag:restricted-complexity] [tag:code-golf]

@l4m2 Tie breakers are in the criterion too, AFAIK.

Java (JDK 10), 295 bytes
int f(Long a,long b,long c,long d){return a>c?-f(c,d,a,b):a<c?b>d?d==1?(a==2&((b==2&c==4)|(b==3&c==16)))|(a==3&b==2&c==27)?0:1:b-d>1?1:f(t(a,b),1,c,d):-1:a<2?0:a.signum(b-d);}long t(long a,long b){long t=1;for(;b-->0;)t=p(a,t);return t;}long p(long a,long b){long p=1;for(;b-->0;)p*=a;return p;}

Try it online!
Codes:

1 if a^^b > c^^d
-1 if a^^b < c^^d
0 is a^^b == c^^d

fail on {1,4,2,2}?

I'll fix later today. I must have switched two conditions when golfing.

159 bytes

APL (Dyalog Unicode), 30 19 bytesSBCS
{f←*/⍴⍨⋄×(f/⍺)-f/⍵}

Try it online! Thanks to @ngn for saving 11 bytes by defining tetration in a much clever and shorter way:
f ← */⍴⍨   ⍝ Define f to be the tetration function
       ⍨   ⍝ Taking a on the right and b on the left,
      ⍴    ⍝   creating an array of b occurrences of the number a
    */     ⍝ and then building the tower of exponentials.

Now if I have a vector with two integers, f/ applies the function to those two integers, e.g. f/ 2 4 gives 65536 and f/ 4 2 gives 256. We need this in our main function:
{f←*/⍴⍨⋄×(f/⍺)-f/⍵}  ⍝ Dyadic function (g) expecting two vectors of 2 integers, e.g. 4 2 g 2 4
{f←*/⍴⍨            }  ⍝ Define the auxiliar function as above
{      ⋄           }  ⍝ and then:
{              f/⍵}   ⍝ Apply aux function to the right vector of integers
{        (f/⍺)     }  ⍝ Apply aux function to the left vector of integers
{             -    }  ⍝ Subtract the two values and finally
{       ×          }  ⍝ get the sign of that difference.

This means my function returns 1 if the left integers give a larger value, 0 if they are the same or ¯1 if the left integers give a smaller value.
My original submission had a recursive definition of tetration:
{f←{⍵=1:⍺⋄⍺*⍺∇⍵-1}⋄×(f/⍺)-f/⍵}

with tetration as:
{               }  ⍝ Dyadic function expecting 2 integers
{⍵=1:⍺         }  ⍝ If the right argument is 1, return the left argument;
{      ⋄        }  ⍝ otherwise (separate previous statement from the next one)
{       ⍺*      }  ⍝ Take the left argument to the power of
{         ⍺∇⍵-1}  ⍝ the recursive call of this function with same left argument and decremented right argument.

"Your code should handle a,b,c,d up to 100"

@ngn isn't it standard to assume I get arbitrary precision? Or what am I missing here?

maybe. other answers violate this requirement too. the challenge is unclear.

assuming arbitrary precision, tetration can be */⍴⍨

I thought the challenge was to figure out how to compare $f(a,b)$ with $f(c,d)$ for input values up to $100$, without actually computing those values (since doing the actual computations isn't feasible).  I think that's an interesting challenge!  (If we were allowed to pretend that we could compute $f(a,b)$ and $f(c,d)$ so we could then just compare them with an if statement, it wouldn't be very interesting.)

I think the challenge should state (or should have stated) that any input with values up to 100 needs to be processed by TIO within its one-minute time limit, or something comparable for languages not offered by TIO.  (I presume this is possible, but I haven't worked on a solution.)

@MitchellSpector that was not what I understood from it, partly because I can read the Haskell solution and it does more or less the same as me. I can't read the java one too well but it feels like it also computes tetration

@ngn that is a nice golf

I agree that that’s how it’s being interpreted, and it really wasn’t spelled out in the challenge. In any case, once there are answers, the challenge really shouldn’t be changed.

@MitchellSpector alright... To sum up, and to check if I got it right, you think me and nimi misinterpreted the challenge but because nimi's answer is so old we can't really make the challenge more clear?

@RGS  I don't think anybody misinterpreted it -- the challenge was just underspecified. And, actually, Olivier Grégoire's Java solution presumably wins in any case (since this challenge is fastest-algorithm with tie-breakers).

In 18.0: ×-⍥(*/¨⍴⍨/)

Haskell, 46 bytes
a#1=a
a#b=a^a#(b-1)
(a!b)c d=compare(a#b)(c#d)

Prints GT for >,  LT for < and EQfor =.
Try it online!

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


text:
Reduce using the lowest value
The challenge
Create a function which takes an array of numbers and subtract from each element the lowest element in the array that has not yet been subtracted from another.

After using the lowest value, It can not be used again.
Numbers in the array are decimal numbers, and not necessarily integers.

Example:
Input: [6, 4, 7, 8, 9, 2, 1, 4]

Next lowest value:          Output:
[6, 4, 7, 8, 9, 2, 1, 4]    [6, 4, 7, 8, 9, 2, 1, 4]
                   ^         ^
                            6-1 = 5
[6, 4, 7, 8, 9, 2, -, 4]    [5, 4, 7, 8, 9, 2, 1, 4]
                ^               ^
                            4-2 = 2
[6, 4, 7, 8, 9, -, -, 4]    [5, 2, 7, 8, 9, 2, 1, 4]
    ^                              ^
                            7-4 = 3
[6, -, 7, 8, 9, -, -, 4]    [5, 2, 3, 8, 9, 2, 1, 4]
                      ^               ^
                            8-4 = 4
[6, -, 7, 8, 9, -, -, -]    [5, 2, 3, 4, 9, 2, 1, 4]
 ^                                       ^
                            9-6 = 3
[-, -, 7, 8, 9, -, -, -]    [5, 2, 3, 4, 3, 2, 1, 4]
       ^                                    ^
                            2-7 = -5
[-, -, -, 8, 9, -, -, -]    [5, 2, 3, 4, 3,-5, 1, 4]
          ^                                    ^
                            1-8 = -7
[-, -, -, -, 9, -, -, -]    [5, 2, 3, 4, 3,-5,-7, 4]
             ^                                    ^
                            4-9 = -5

Final output: [5, 2, 3, 4, 3, -5, -7, -5]

Test Cases
Input: [6, 4, 7, 8, 9, 2, 1, 4] => Output: [5, 2, 3, 4, 3, -5, -7, -5]
Input: [4, 7, 4, 9, -10, 8, 40] => Output: [14, 3, 0, 2, -18, -1, 0]
Input: [0.25, -0.5, 8, 9, -10] => Output: [10.25, 0, 7.75, 1, -19]
Input: [3, 4, 9, 1, 1, 1, -5] => Output: [8, 3, 8, 0, -2, -3, -14]

This is code-golf, so the shortest answer in bytes win.

This could use an walk-through example. As it stands now the task needs to be inferred from the test cases.

Thanks @Arnauld for taking the time to do it. I haven't been able to use the pc since yesterday so I couldn't modify the example

Is there a specific reason to include non-integers in the arrays? It doesn't make the challenge more interesting, rules out some approaches, and poses a big problem in languages without non-integer types.

Jelly, 2 bytes
_Ṣ

Try it online!
or Try all test cases
_   # Subtract from...
 Ṣ  # The input array sorted

MATL, 3 bytes
tS-

Try it online!
(implicit input as an array)
t                              # duplicate
 S                             # sort
  -                            # element-wise subtract
(implicit output)

Prolog (SWI), 93 80 68 bytes
[H|T]/[A|B]/[X|Y]:-X is H-A,(T=[],Y=T;T/B/Y).
X*Y:-msort(X,S),X/S/Y.

Try it online!

Husk, 4 bytes
Ṡz-O

Try it online!
Explanation
      -- input, e.g. [6,4,7,8,9,2,1,4]
   O  -- sort        [1,2,4,4,6,7,8,9]
Ṡz-   -- element wise difference to input: [6-1,4-2,7-4,8-4,9-6,2-7,1-8,4-9]
      -- return result [5,2,3,4,3,-5,-7,-5]

This have to be a joke..... 4 bytes. Awesome

Java 10, 83 bytes
a->{var b=a.clone();java.util.Arrays.sort(b);for(int i=0;i<a.length;a[i]-=b[i++]);}

Modifies the input-array instead of returning a new one to save bytes.
Try it online.
Explanation:
a->{                         // Method with double-array parameter and no return-type
  var b=a.clone();           //  Create a copy of the input-array
  java.util.Arrays.sort(b);  //  Sort this copy
  for(int i=0;i<a.length;    //  Loop over the indices
    a[i]-=                   //   Subtract from the `i`'th item in the input-array:
          b[i++]);}          //    The `i`'th item of the sorted array

R, 18 bytes
(x=scan())-sort(x)

Try it online!
Does what it says :)

Haskell, 34 bytes
import Data.List
zipWith(-)<*>sort

Try it online!

JavaScript (ES6), 44 bytes
a=>[...a].map(x=>x-a.sort((a,b)=>b-a).pop())

Try it online!
Commented
a =>                 // given the input array a[]
  [...a]             // create a copy of a[]
  .map(x =>          // for each integer x in the copy:
    x -              //   update x by ...
    a.sort((a, b) => //     sorting the original array in descending order
      b - a          //     (we only need to sort it once, but it's shorter to do it here)
    ).pop()          //     taking the element at the top of a[] and subtracting it from x
  )                  // end of map()

Python 3, 42 40 bytes
 lambda a:[b-c for b,c in zip(a,sorted(a))]
lambda a:[a.pop(0)-b for b in sorted(a)]

37 bytes using map.

@ovs Your solution sort of works for Python 3. It returns a map object, instead of a list. Would that be kind of a grey area for the requirements of the contest? Maybe you could just submit it as your own answer, since it's probably different enough to qualify.

@ovs The spec also states that the input will not necessarily be ints, so I'm going to leave mine as is.

Returning a map object is valid, but the non-int requirement makes my suggestion invalid.

Japt, 8 6 4 bytes
í-Uñ

Try it here

Explanation
           :Implicit input of array U
c          :Flatten (simply creates a 2nd copy of the array because JavaScript's sort mutates the original array)
  í        :Interleave
    Un     :U sorted
   -       :Reduce each pair by subtraction

Ruby, 32 chars
->a{a.zip(a.sort).map{|x,y|x-y}}

You could just print the values: ->a{a.zip(a.sort){|x,y|p x-y}}

05AB1E, 2 bytes
{-

Try it online or verify all test cases.
Explanation:
{     # Sort the input-array
 -    # Subtract all values in this sorted array from the input-array

J, 4 bytes
-/:~

Try it online!
Explanation:
From the argument subtract - the sorted /:~ argument

Common Lisp, 46 bytes
(lambda(x)(mapcar #'- x(sort(copy-seq x)#'<)))

Try it online!

Coconut, 23 bytes
a->map((-),a,sorted(a))

Try it online!

Perl 6, 15 bytes
{@^a Z-@a.sort}

Try it online!
Anonymous function that takes one list and returns a list.

Julia 0.6, 12 bytes
A->A-sort(A)

Try it online!

K (ngn/k), 8 bytes
{x-x@<x}

Try it online!

SmileBASIC, 49 bytes
DEF R A
DIM B[0]COPY B,A
SORT B
ARYOP 1,A,A,B
END

The input array is modified in place.
ARYOP does operations on entire arrays at once. In this case it subtracts B from A and stores the result in A.

Japt, 9 bytes
íNc n
®r-

Try it online!

Stax, 5 bytes
ÿ◙┘¿N

Run and debug it
To show how it works, here's the unpacked, commented version.
m       for each element execute, then pop and print:
  xo    sort the original input
  i@    index into array using iteration index
  -     subtract

Run this one

another 5

PHP, 86 bytes
function f($a){$b=$a;sort($b);return array_map(function($x,$y){return $y-$x;},$b,$a);}

Try it online!

Tcl, 49 bytes
proc S L {lmap n $L m [lsort -r $L] {expr $n-$m}}

Try it online!

Factor, 23 bytes
[ dup natural-sort v- ]

Attempt This Online!


text:
Generate a Portmantout!
Background
Three years ago, this guy Tom Murphy got it into his head to extend the idea of a portmanteau to all words in a language and called this a portmantout (portmanteau plus tout [French for all]). Defining English as a list of 108,709 words, he managed to find a sequence of 611,820 letters with the following two properties:

Every English word is contained in the string.
Some neighborhood containing any two adjacent letters in the string is an English word.

Here's a link to a page on which this portmantout can be found (along with a video explanation).
A portmantout
The first of the two properties of a portmantout is easy to understand. The second may require some explanation.
Basically, words must overlap. "golfcode" will never appear in a portmantout of English, as there is no word there that contains the "fc". However, you might find "codegolf" in a portmantout, for "ego" bridges the gap (and all other pairs of letters are in either "code" or "golf").
Your task:
Write a program or function that takes a list of strings and returns any portmantout of the list.
This Python 3 code will verify a portmantout.
Test cases
All lists are unordered; that is,
{"code", "ego", "golf"} -> "codegolf"
{"more", "elm", "maniac"} -> "morelmaniac" or "morelmorelmaniac" or "morelmorelmorelmaniac" or...
    Would a morelmaniac be some sort of mycologist?
{"ab", "bc", "cd", "de", "ef", "fg", "gh", "hi", "ij", "jk", "kl", "lm", "mn", "no", "op", "pq", "qr", "rs", "st", "tu", "uv", "vw", "wx", "xy", "yz", "za"} -> "abcdefghijklmnopqrstuvwxyza" or "rstuvwxyzabcdefghijklmnopqrstuvwxyzabcdef" or any 27+ letters in order

And why not? The massive one on Murphy's site, if your code executes within reasonable time.
Rules

Your code must halt.
You need not return the same portmantout with each execution.
You may assume all strings consist of only lowercase letters a through z.
If no portmantout is possible, your program may do anything. Ex: {"most", "short", "lists"}
Standard rules for I/O and loopholes apply.

This is code-golf, so the shortest solution (in bytes) in each language wins! Happy golfing!

Sandbox

Maybe some test cases?

{"sic", "bar", "rabbits", "cradle"} -> "barabbitsicradle" {"mauve", "elated", "cast", "electric", "tame"} -> "mauvelectricastamelated" (more test cases)

Yeah, maybe a testcase where a word needs to be used twice

Can we return all possible portmantouts?

Will we ever get one word entirely contained in another (e.g. meow and homeowner)?

Is it okay if the program halts with probability 1, but could theoretically run forever?

Will we ever get 1-letter words?

how do you verify that it returns a different one?
https://www.random.org/analysis/dilbert.jpg

Related, not similar & old enough to be dead.

@fortran The answer poster must prove that their answer is valid, not the community.

@Mnemonic (1) I think there is a meta post about that, that says "work with probability 1 for all possible input". (2) The question doesn't specify that, so I don't see why not. Given that it's guaranteed that there is a portmantout, programs can simply filter out those 1-character ones.

@user202729 if you have to explain a joke, it's not funny anymore

Python 2, 204 202 bytes
def f(l,s=''):
 if all(w in s for w in l):return s
 for i,w in enumerate(l):
	a=next((s+w[i:]for i in range(len(w)-1,0,-1)if s[-i:]==w[:i]),0)if s else w;x=a and f(l[:i]+l[i+1:]+[l[i]],a)
	if x:return x

Try it online!

Saved

-2 bytes, thanks to recursive

You can use tabs on the last two lines to save 2 bytes.

200 bytes.

This doesn't produce the correct output for ["ab", "ba", "ca"].  My solution has the same bug.

Stax, 39 36 bytes
ä▬│•.k=╠lƒ☺╜00║¿~,▓╕╠7ÉΔB<e┼>☼Θ²└ô┴\

Run and debug it
Runs all the test cases deterministically in about a second.
This is a recursive algorithm.

Start with each word of input as a candidate
At each step, order the words by the number of times they occur as substrings of the candidate.
For each word that's compatible with the end of the current candidate, join the word to form a new candidate, and make a recursive call.

Here's the program unpacked, ungolfed, and commented.
FG              for each word in input, call target block
}               unbalanced closing brace represents call target
  x{[#o         sort input words by their number of occurrences in the current candidate
  Y             store it in register Y
  h[#{,}M       if all of the words occur at least once, pop from input stack
                input stack is empty, so this causes immediate termination,
                followed by implicitly printing the top of the main stack
  yF            for each word in register y, do the following
    [n|]_1T|[|& intersect the suffixes of the candidate with prefixes of the current word
    z]+h        get the first fragment in the intersection, or a blank array
    Y           store it in register Y
    %t+         join the candidate with the current word, eliminating the duplicate fragment
    y{G}M       if the fragment was non-blank, recursively call to the call target
    d           pop the top of stack

Run this one
Edit: This fails for a class of inputs that has a loop, like ["ab", "ba", "ca"], as do most of the other posted answers.

Pyth, 39 bytes
JQW}_1mxbdQ=+J|=b*qKOQ<=T+OP._KOJlKTY)b

Try it here
Explanation
JQW}_1mxbdQ=+J|=b*qKOQ<=T+OP._KOJlKTY)b
JQ                                        Get a copy of the input.
  W}_1mxbdQ                          )    While there are words in the input
                                          that aren't in b (initially space)...
                   KOQ    OP._KOJ         ... get a random input word, a random
                                          prefix, and a random joined word...
                       =T+                ... stick them together...
                  q   <          lKT      ... and check if joining them together
                                          is valid...
               =b*                        ... then update b accordingly...
           =+J|                     Y     ... and stick the new word into J.
                                      b   Output the final result.

JavaScript (ES6), 138 130 bytes
f=a=>a[1]?a.map((c,i)=>a.map((w,j,[...b])=>i!=j&&!/0/.test(m=(c+0+w).split(/(.+)0\1/).join``)?t=f(b,b[i]=m,b.splice(j,1)):0))&&t:a

Returns an error for lists that cannot be completely portmantouted.
Ungolfed:
f = a =>
  a[1] ?                                        //if more than one element ...
    a.map((c, i)=>                              // for each element
      a.map((w, j, [...b])=>                    //  for each element
        i != j &&                               //   if not the same element
        !/0/.test(m=(c+0+w).split(/(.+)0\1/).join``) &&  //   and the elements overlap
        (t = f(b,                               //   and f recursed is true when
               b[i] = m,    //    replacing the ith element with the 2-element portmanteau
               b.splice(j, 1)                   //    and removing the jth element
              )
        )
      )
    ) &&
    t :                                         //return the recursed function value
    a                                           //else return a

f=a=>a[1]?a.map((c,i)=>a.map((w,j,[...b])=>i!=j&&!/0/.test(m=(c+0+w).split(/(.+)0\1/).join``)?t=f(b,b[i]=m,b.splice(j,1)):0))&&t:a

console.log(f(["sic", "bar", "rabbits", "cradle"])+'')             // "barabbitsicradle"
console.log(f(["mauve", "elated", "cast", "electric", "tame"])+'') // "mauvelectricastamelated"

console.log(f(["more", "elm", "maniac"])+'')                       // "morelmaniac"
console.log(f(["elm", "more", "maniac"])+'')                       // "morelmaniac"
console.log(f(["more", "maniac", "elm"])+'')                       // "morelmaniac"

console.log(f(["ego", "code", "golf"])+'')                         // "codegolf"
console.log(f(["code", "ego", "golf"])+'')                         // "codegolf"
console.log(f(["golf", "ego", "code"])+'')                         // "codegolf"

console.log(f(['ab', 'bc', 'cd', 'de'])+'');                       // "abcde"
console.log(f(['de', 'bc', 'cd', 'ab'])+'');                       // "abcde"

console.log(f(["ab", "ba", "ca"])+'');                             // "caba"

The code is excruciatingly slow on the full alphabet example (not included for that reason in the above Snippet).
That is remedied by changing the maps to somes, for the loss of 2 bytes:
f=a=>a[1]?a.some((c,i)=>a.((w,j,[...b])=>i!=j&&!/0/.test(m=(c+0+w).split(/(.+)0\1/).join``)?t=f(b,b[i]=m,b.splice(j,1)):0))&&t:a

f=a=>a[1]?a.some((c,i)=>a.some((w,j,[...b])=>i!=j&&!/0/.test(m=(c+0+w).split(/(.+)0\1/).join``)?t=f(b,b[i]=m,b.splice(j,1)):0))&&t:a

console.log(f(["ab", "bc", "cd", "de", "ef", "fg", "gh", "hi", "ij", "jk", "kl", "lm", "mn", "no", "op", "pq", "qr", "rs", "st", "tu", "uv", "vw", "wx", "xy", "yz", "za"])+'');

console.log(f(["ab", "ba", "ca"])+'');                             // "caba"

It seems I've made a mistake.  I can't reproduce the behavior I thought I saw yesterday.  Sorry for my confusion and wasting your time.  I'll delete my comments on the subject, as they're all wrong and misleading.


text:
Find the 10-adic cube root of 3
I like to think of a 10-adic number as a number that goes infinitely to the left, or an integer modulo a very very large power of 10.
Things carry infinitely to the left and vanish. To see what I mean, note that ...6667 * 3 = 1 in the 10-adic land, since the "2" that carries to the left goes to infinity.
Addition and multiplication make sense for 10-adic numbers, since the last n digits of the sum/product only depend on the last n digits of the summands/multiplicands.

Given n, you need to print the last n digits of the 10-adic cube root of 3, i.e. x satisfiying x*x*x = 3.
It ends:
...878683312291648481630318492665160423850087895134587

Your code must terminate for n=1000 before submission.
Let's say that if the number you need to print begins with zero, then you don't need to print the leading zeroes, since it isn't actually the point to print extra zeroes.

This is code-golf. Shortest answer in bytes wins.

OEIS A225404

Do we need to print leading zeros as well? Most answers (including my Java answer) are currently failing for those. i.e. n=12 outputting 87895134587 instead of 087895134587. Personally I would make it optional, since it would invalidate almost all answers..

@KevinCruijssen done

Python 2, 33 bytes
lambda k:pow(3,10**k*2/3+1,10**k)

Try it online!
The pow function efficiently computes the modular exponent 3**(10**k*2/3+1)%10**k.
We're asked to find a solution to r**3 = 3 (mod 10**k). We want to find an exponent e for which the map x -> x**e is inverse to cubing x -> x**3 working mod 10**k, just as the decryption and encryption exponents in RSA cancel to produce the original value. This means that (x**3)**e = x (mod 10**k) for all x. (We'll assume throughout that gcd(x,10) = 1.)  Then, we can recover r by inverting the cubing to get r = 3**e (mod 10**k).
Expanding out (r**3)**e = r (mod 10**k), we get
r**(3*e-1) = 1 (mod 10**k)

We're looking for an exponent 3*e-1 that guarantees that multiplying that many copies gives us 1.
Multiplication modulo 10**k forms a group for invertible numbers, that is those with gcd(x,10) = 1. By Lagrange's Theorem, x**c = 1 where c is the count of elements in the group. For the group modulo N, that count is the Euler totient value φ(N), the number of values from 1 to N that are relatively prime to N. So, we have  r**φ(10**k) = 1 (mod 10**k). Therefore, its suffices for 3*e-1 to be a multiple of φ(10**k).
We compute
φ(10**k) = φ(5**k) φ(2**k)= 4 * 5**(k-1) * 2**(k-1) = 4 * 10**(k-1)`

So, we want 3*e-1 to be a multiple of 4 * 10**(k-1)
3*e - 1 = r * 4 * 10**(k-1)
e = (4r * 10**(k-1) + 1)/3

Many choices are possible for r, but r=5 gives the short expression
e = (2 * 10**k + 1)/3

with e a whole number. A little golfing using floor-division shortens e to 10**k*2/3+1, and expressing r = 3**e (mod 10**k) gives the desired result r.

I would like to see a more detailed explanation on how this works, very nice answer!

Should (r**3)**e = x (mod 10**k) be (r**3)**e = r (mod 10**k)? Also is it just a coincidence that (2 * 10**k + 1)/3 = 1/3 (mod 10**k)?

@H.PWiz Yes, thanks, I fixed it. I'm not sure if it being an inverse for 3 is a coincidence. It's certainly not enough, as replacing the 2 with other values doesn't work.

@xnor I think it is enough. You should be able to replace to replace 2 with any number x = 2 (mod 3)

As usual, maths win!

Python 2 (PyPy), 55 50 bytes
-5 bytes thanks to @H.P. Wiz!
n=p=1;exec"p*=10;n+=3*(3-n**3)%p;"*input();print n

Try it online!
Calculates (non-bruteforcing) digit by digit, so it's faster than brute force.
Version without exec
Explanation
(Thanks @Leaky Nun and  @user202729 for figuring this out)
First, observe that \$n^3\$ is an involution modulo 10 (i.e. if the function is called \$f\$, then \$f(f(n)) = n\$). This can be confirmed using an exhaustive search.
We can use mathematical induction to find the next digit.
Let \$d_n\$ be the \$n\$th digit of the number (from the right).
$$
\begin{align*}
d_1^3 &\equiv 3   &&\pmod{10} \\
d_1   &\equiv 3^3 &&\pmod{10} \\
  &\equiv 27  &&\pmod{10} \\
  &\equiv 7   &&\pmod{10} \\
\end{align*}
$$
Now, assume we know the number up to the \$k\$th digit, \$x\$
$$
\begin{align*}
x^3 &\equiv 3 &&\pmod{10} \\
(d_{k+1} \cdot 10^k + x)^3 &\equiv 3 &&\pmod{10} \\
m \cdot 10^{2k} + 3 \cdot d_{k+1} x^2 \cdot 10^k + x^3 &\equiv 3 &&\pmod{10^{k+1}} \;\textrm{(for some } m \textrm{)} \\
3 \cdot d_{k+1} x^2 \cdot 10^k + x^3 &\equiv 3 &&\pmod{10^{k+1}} \\
\end{align*}
$$
We know that:
$$
\begin{align*}
                 x &\equiv 7             &&\pmod{10} \\
               x^2 &\equiv 49            &&\pmod{10} \\
                   &\equiv 9             &&\pmod{10} \\
    x^2 \cdot 10^k &\equiv 9  \cdot 10^k &&\pmod{10^{k+1}} \\
3 \cdot x^2 \cdot 10^k &\equiv 27 \cdot 10^k &&\pmod{10^{k+1}} \\
                   &\equiv 7  \cdot 10^k &&\pmod{10^{k+1}} \\
\end{align*}
$$
Substituting this in:
$$
\begin{align*}
3 \cdot d_{k+1} x^2 \cdot 10^k + x^3 &\equiv 3 &&\pmod{10^{k+1}} \\
7 \cdot d_{k+1} \cdot 10k + x^3 &\equiv 3                  &&\pmod{10^{k+1}} \\
d_{k+1} &\equiv \frac{3 - x3}{7 \cdot 10^k} &&\pmod{10} \\
\therefore d_{k+1} &\equiv \frac{3 \cdot \left(3 - x^3\right)}{10^k}   &&\pmod{10} \; (7^{-1} \equiv 3 \pmod{10})
\end{align*}
$$

Actually this solution is likely to be optimal. (for most languages where the formula is less verbose than brute forcing) Explanation can be found somewhere in chat, although quite scattered.

If you aimed to golf the "non-exec" solution, this works for 62 bytes as a full program instead of a function

This only prints the last 11 digits for n=12 and n=13.

@user202729 I don't think it would be optimal. You don't need to compute the entirety of n**3 to compute n**3/p, for example.

@LeakyNun Optimal in terms of code size...

× and x look really quite similar in some fonts, and make the maths extremely hard to read. May I suggest using · (centre dot) instead of × ? (And, obviously, it would be nice to have MathJax).

save 5 bytes

@H.PWiz Another one, https://tio.run/##BcFBCoAwDATAr0hB0EghqQcPIa@Rgr3ERSrY18cZjH7dXjIGRoQbTLR@9UwgE1bf7CAn2mfkIpqoOd6@rIqneZ88Qpj5Bw

(H.PWiz later noted that my solution fails for n<3)

Wolfram Language (Mathematica), 21 bytes
PowerMod[3,1/3,10^#]&

Try it online!

05AB1E, 17 13 bytes
7IGD3mN°÷7*θì

Port of @ASCII-only's Python 2 (PyPy) answer.
-4 bytes AND bug-fixed for outputs with leading zeros thanks to @Emigna, by replacing T%N°*+ with θì.
Try it online.
Explanation:
7               # Start result-string `r` at '7'
IG              # Loop `N` in the range [1, input)
  D3m           #  `r` to the power 3
       ÷        #  Integer-divided with
     N°         #  10 to the power `N`
        7*      #  Multiplied by 7
          θì    #  Then take the last digit of this, and prepend it to the result `r`
                # Implicitly output result `r` after the loop

H.P.Wiz has golfed my approach, and the challenge no longer requires leading zeroes so you may be able to golf it more?

@ASCII-only Perhaps, but not sure how. @Emigna has already golfed T%N°*+ to θì for me, and the leading zero 'fix' was just a nice bonus with this approach.

Java (JDK 10), 106 bytes
n->n.valueOf(3).modPow(n.valueOf(2).multiply(n=n.TEN.pow(n.intValue())).divide(n.valueOf(3)).add(n.ONE),n)

Try it online!
Credits

Port of xnor's Python 2 answer.
-6 bytes thanks to Kevin Cruijssen

166 bytes by changing the loop to for(int l=0,d;++l<=n; and changing BigInteger I=null; to var I=new BigInteger("3"); which we can re-use.

1 more byte to save by changing the loop to for(int l=0,d;l++<n;).

Java 8, 158 156 141 136 135 bytes
n->{var t=n.valueOf(3);var r=n.ONE;for(int i=0;i++<n.intValue();)r=r.add(t.subtract(r.pow(3)).multiply(t).mod(n.TEN.pow(i)));return r;}

Port of @ASCII-only's Python 2 (PyPy) answer.
-2 bytes thanks to @Neil.
-20 bytes thanks to @ASCII-only.
NOTE: There is already a much shorter Java answer by @OlivierGrégoire using an algorithmic approach utilizing modPow.
Try it online.
Explanation:
n->{                            // Method with BigInteger as both parameter and return-type
  var t=n.valueOf(3);           //  Temp BigInteger with value 3
  var r=n.ONE;                  //  Result-BigInteger, starting at 1
  for(int i=0;i++<n.intValue();)//  Loop `i` in the range [1, n]
    r=r.add(                    //   Add to the result-BigDecimal:
       t.subtract(r.pow(3))     //    `t` subtracted with `r` to the power 3
       .multiply(t)             //    Multiplied by 3
       .mod(n.TEN.pow(i)));     //    Modulo by 10 to the power `i`
  return r;}                    //  Return the result-BigInteger

Oh, you used that algorithm too? I'll rollback my answer and add you changes ;)

java.math.BigInteger u=null,r=u.valueOf(7),t=r;?

@Neil Of course.. thanks. I had java.math.BigInteger t=null,r=u.valueOf(7);t=r; initially before I added the u to save some bytes.

I saved some bytes on ASCII-only's answer

@H.PWiz one less variable :P

144

I think some bytes could be saved by taking a BigInteger as an argument but IDK if that's acceptable

141?

@ASCII-only Thanks. Your 141 answer outputs the last n-1 digits though, instead of n. But that was an easy fix. :)

@ASCII-only taking a BigInteger is acceptable if it's a useful parameter. In this case, you may take n as a BigInteger if that's better for you. Just don't keep n an int and pass a null to the method, just to have access to BigInteger without declaring it.

In that case, 136

*modpow, not modpod :P

@ASCII-only Woops.. xD

Haskell, 37 bytes
1 byte saved thanks to ASCII-only!
(10!1!!)
n!x=x:(n*10)!mod(9-3*x^3+x)n

Try it online!
I use a similar approach to ASCII-only, but I avoid using division

37?

dc, 15
3?Ar^d2*3/1+r|p

Uses modular exponentiation, like @xnor's answer.
Try it online!
TIO calculates input=1000 in 21s.

Pyth, 12
.^3h/y^TQ3^T

Try it online!
Again, using modular exponentiation, like @xnor's answer.

Pyth, 23 bytes
Of course, this uses ASCII-only's approach.
K7em=+K*%*7/^K3J^TdTJtU

Try it here!

@DigitalTrauma Oh >_< I swear I haven't noticed your answer lol... I first had a port of ASCII's solution, then I saw xnor's and I ported it directly to golf it :P I guess I will rollback to the initial revision, though.

Charcoal, 26 22 bytes
≔⁷ηＦＮ≧⁺﹪×³⁻³Ｘη³Ｘχ⊕ιηＩη

Try it online! Link is to verbose version of code. Explanation:
≔⁷η

Initialise the result to 7. (Doesn't have to be 7, but 0 doesn't work.)
ＦＮ

Loop over the number of required digits.
        η       Current result.
       Ｘ ³     Take the cube.
     ⁻³         Subtract from 3.
   ×³           Multiply by 3.
            ⊕ι  Increment the loop index.
          Ｘχ    Get that power of 10.
  ﹪             Modulo
≧⁺            η Add to the result.

Now uses @H.P.Wiz's approach to save 4 bytes.
Ｉη

Print the result.
Here's a 28-byte brute-force version that takes cube roots of arbitrary values:
ＦＮ⊞υ⊟Φχ¬﹪⁻ＸＩ⁺κ⭆⮌υμ³ＩηＸχ⊕ι↓Ｉυ

Try it online! Link is to verbose version of code. First input is number of digits, second is value to root.

H.P.Wiz has updated (read: golfed) my approach. Also, stringmap shouldn't be needed anymore since Leaky Nun has updated the requirements. also the first link also points to the brute force version >_>

@ASCII-only Thanks, I've fixed the links and ported H.P.Wiz's approach, but I needed StringMap to concatenate k with the reversed list as a base 10 number.

Hmm. I would have thought just doing it the plain number way may have been golfier. I guess not though

@ASCII-only For the previous version I used Base(Reverse(u), 10) but prefixing k would have cost 4 bytes while doing it as a string only costs 2 bytes resulting in a 1-byte saving after taking the Cast into account.

J, 33 bytes
f=:3 :'((10x^y)|]+3*3-^&3)^:y 1x'

TIO
port of @ASCII-only's answer but using fixed modulo 10^n throughout

Jelly, 23 18 17 bytes
*3:×7DṪ×+⁸
R⁵*çƒ7

Try it online!
I know ƒ will be useful.


text:
Math Operations with Strings
Challenge :
Inspired by Alphabet Position Finder
Given an string and one of two possible mathematical operator (+ or -) as input, your task is to return the operation of each alphabet position from the string.
Example :
Input: "Hello World", "+"
=> "Hello World" = [8, 5, 12, 12, 15, 23, 15, 18, 12, 4] (converted to their equivalents)
=> sum alphabet positions = [8 + 5 + 12 + 12 + 15 + 23 + 15 + 18 + 12 + 4]
Output: 124

Note :

Ignore non-alphabetical characters
You must use 1-indexing (a = 1, b = 2, ..., z = 26)
If empty string submitted return a falsy value
Operator can be taken as +/-. 1/-1, truthy/falsey, etc.

Test Cases :
"Hello World", "-"             => -108
"I Love golfing", "+"          => 133
"She doesnt love you :(", "+"  => 224
"@#t%489/*-o", "-"             => 5
"", "-"                        => 0
"a", "-"                       => 1

Comments are not for extended discussion; this conversation has been moved to chat.

Java (JDK 10), 79 bytes
s->o->{int r=0,i=0;for(int c:s)r+=(c&=95)%32*(c>64&c<91?i++<1?1:o:0);return r;}

Try it online!
Original answer before the question was clarified
Java (JDK 10), 46 bytes

s->o->s.chars().reduce(0,(a,b)->a+b%32*(44-o))

Try it online!

Seems to fail for "to", "-" (expected 5, actual -35).

@KevinCruijssen I give up on this answer. The requirements changed like the wind. This is valid with the very first version of the question, but not with the latest. Also, the test cases were not consistent. So I took the first two test cases and adapted them with the input given and made this answer.

Seems the challenge is settled now.. I wish we could somehow enforce the use of the Sandbox for ALL challenges.. Anyway, adding .replaceAll("[^A-Za-z]","") takes care of one problem. The other problem is when the operator is - (it starts at the negative index of the first letter, instead of the positive value). I know some possible solutions, but all are pretty long..

@KevinCruijssen I just updated the answer based on the new question.

Python 2, 70 66 bytes
lambda s,o:eval(o.join(`ord(c)%32`for c in s if c.isalpha())or'0')

Try it online!

Japt 2.0 -F0, 19 15 bytes
OvUf\l ®c %HÃqV

Test it online
Explanation:
 OvUf\l ®c %HÃqV
 Ov                 // Japt eval:
   U                //   First input
    f\l             //   Match [A-Za-z]
        ®    Ã      //   Map; At each item:
         c          //     Char-Code
           %H       //     %32
              qV    //   Join with Second input (operator)
-F0                 // If the first input (string) is empty, output 0

Japt v2.0a0, 12 13 bytes
+1 bytes to handle empty strings :(
r\L ¬®c uHÃrV

Try it
Original 12 byte version which would be valid if an error counts as a falsey value.
f\L ®c uHÃrV

Try it

Explanation
                  :Implicit input of string U and operator string V
r                 :Remove
 \L               : /[^a-z]/gi
    ¬             :Split
     ®            :Map
      c           :  Character code
        u         :  Modulo
         H        :   32
          Ã       :End map
           rV     :Reduce by V

JavaScript (Node.js), 92 82 67 bytes
t=>o=>t?eval(t.match(/[a-z]/gi).map(x=>parseInt(x,36)-9).join(o)):0

Try it online!

JavaScript (Node.js), 52 bytes
T=>_=>eval([...T].map(a=>a.charCodeAt()%32).join(_))

Try it online!

Explanation :
T =>                            // first input for lambda function `text` (T)
    _ =>                        // second input, the separator
        eval(                   // evaluate a string
            [...T]              // conver `T` into a comma separated array of its char
            .map(a=>            // map over them `a` is representing the char
                a.charCodeAt()  // a.charCodeAt(0)
                    % 32)       // find remainder of it when divided by 32
                .join(_)        // and join them using the separator
        )                       // end eval

Note :
This completely ignores non-alphabetic words since the challenge seems to change after every two minutes, I chose this. (Can be changed if OP wants me to)

I posted this on the other challenge, just changed .join to .join(o) :
JavaScript (Node.js), 57 bytes
t=>o=>t.match(/[a-z]/gi).map(i=>parseInt(i,36)-9).join(o)

Try it online!

05AB1E, 9 bytes
áÇ32%Iý.E

Semi-port of @JonathanAllan's 05AB1E answer for the linked challenge.
Outputs nothing as falsey values if the input doesn't contain any letters.
No TIO, because .E isn't on TIO yet. Here an alternative version that does .E manually áÇ32%Iý“…¢(“s')J.e: Try it online or verify all test cases.
Explanation:
á        # Only keep letters of the first input-string
         #  i.e. "Hello World" → "HelloWorld"
 Ç       # Get the list of the unicode values of each letter
         #  i.e. "HelloWorld" → [72,101,108,108,111,87,111,114,108,100]
  32%    # modulo-32 each
         #  i.e. [72,101,108,108,111,87,111,114,108,100] → [8,5,12,12,15,23,15,18,12,4]
Iý       # Join it with the operator input
         #  [8,5,12,12,15,23,15,18,12,4] and "-" → "8-5-12-12-15-23-15-18-12-4"
  .E     # Run it as Python-eval
         #  i.e. "8-5-12-12-15-23-15-18-12-4" → -108

More details on the commit of .E, prove it works, and the alternative version here in a similar answer of mine.

CJam, 24 bytes
q~el{'`-_0>*}%{},0+':@+~

Try it online!
Could probably be more efficient, had to add 0 to the array to handle the empty string.

Jelly, 10 bytes
ŒuØAiⱮḟ0jV

Try it online!
Explanation
ŒuØAiⱮḟ0jV  Main link
Œu          Uppercase the input
     Ɱ      For each character
    i       take its index in
  ØA        the uppercase alphabet
      ḟ0    Filter; remove 0s
        j   String-join by the right element
         V  Evaluate

-4 bytes thanks to Mr. Xcoder

9 bytes: ŒuØAiⱮjŒV or 8 bytes: ŒuØAiⱮjV if - can be taken as _ instead.

@Mr.Xcoder oh that's actually shorter? cool thanks :D

You don't need ḟ0, as this outputs 0 for empty strings, doesn't it?

@Mr.Xcoder non-alphabetical characters in the first position cause issues


text:
Golf A Parentheses Matching Algorithm
You will be given a string s. It is guaranteed that the string has equal and at least one [s and ]s. It is also guaranteed that the brackets are balanced. The string can also have other characters.
The objective is to output/return a list of tuples or a list of lists containing indices of each [ and ] pair.
note: The string is zero-indexed.
Example:
!^45sdfd[hello world[[djfut]%%357]sr[jf]s][srtdg][] should return
[(8, 41), (20, 33), (21, 27), (36, 39), (42, 48), (49, 50)] or something equivalent to this. Tuples are not necessary. Lists can also be used.
Test cases:
input:[[asdf][][td([)ty54g% ]hg[[f]u][f[[jhg][gfd]sdf]sdfs]ghd]fr43f]
output:[(0, 62),(1, 6), (7, 8), (9, 56), (13, 22), (25, 30), (26, 28), (31, 52), (33, 47), (34, 38), (39, 43)]
input:[[][][][]][[][][][[[[(]]]]]))
output:[(0, 9), (1, 2), (3, 4), (5, 6), (7, 8), (10,26),(11, 12), (13, 14), (15, 16), (17, 25), (18, 24), (19, 23), (20, 22)]
input:[][][[]]
output:[(0, 1), (2, 3), (4, 7), (5, 6)]
input:[[[[[asd]as]sd]df]fgf][][]
output:[(0, 21), (1, 17), (2, 14), (3, 11), (4, 8), (22, 23), (24, 25)]
input:[]
output:[(0,1)]
input:[[(])]
output:[(0, 5), (1, 3)]

This is code-golf, so the shortest code in bytes for each programming language wins.

Related

Does the output order matter?

no, it does not.

"note: The string is zero-indexed." - It's very common to allow implementations to choose a consistent indexing in these kind of challenges (but it is, of course, up to you)

Is there any restriction on the order of the tuple in the output? Must they be sorted in increasing open paren position?

@user202729 no there is no restriction about the order.

Can we take input as an array of characters?

Related: Telescopic Parentheses

@LuisMendo I think the challenge of garbage inbetween the parens makes this unique enough that I definitely can't reuse the 05AB1E implementation.

@ngn thanks, will edit

@ngn update: edited. now there is one extra closed bracket at index 26 and the string is valid.

Can the output format be [0, 5, 1, 3] instead of [[0, 5], [1, 3]] (for example)

@dylnan yes, but only prefer that if your language does not support nested lists.

The language I'm thinking of does support nested lists, but it is one indexed. Can one indexed languages use one indexing?

why not just subtract 1 from every index?

Costs one byte...

More in some languages.

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

Try it online!
Stores each opening [ in the right stack, and outputs whenever we hit a ].

Python 2, 74 bytes
s=[];i=0
for c in input():
 if'['==c:s+=i,
 if']'==c:print s.pop(),i
 i+=1

Try it online!

JavaScript, 69 62 bytes
A quick bit of golf on the train home. Can probably be improved on.
Takes input as an array of characters and outputs an object with the keys being the indices of the [s and their values being the indices of their corresponding ]s.
a=>a.map((x,y)=>x==`]`?o[a.pop()]=y:x==`[`&&a.push(y),o={})&&o

Try it online

It blows my mind that you can golf on mobile.  :P

@Oliver, it blows my mind that I can (just about) type on touchscreens at all - bring back keyboards!

vim, 89 bytes
:s/\(.\)/\1<C-V><C-M>/g|g/^\[/ :norm %mm%:pu! =line('.').','.line(\"'m\")<C-V><C-M><C-X>$<C-X>J
:v/\[/d|%s/\[//g

Annotated
:s/\(.\)/\1<C-V><C-M>/g            " one character per line
|g/^\[/                            " for each opening square bracket:
  :norm %mm%                       "   mark the line with the matching bracket
  :pu! =line('.').','.line(\"'m\") "   write the line numbers to preceeding line
  <C-V><C-M><C-X>$<C-X>J           "   convert to 0-based counting and join lines
:v/\[/d                            " remove all non-opening bracket lines
|%s/\[//g                          " remove brackets

<C-V> is 0x16. <C-M> is 0x0d. <C-X> is 0x18.
Try it online!

Haskell, 92 79 bytes
g(u:a)n(']':x)=(u,n):g a(n+1)x
g a n(s:x)=g([n|s=='[']++a)(n+1)x
g[]_[]=[]
g[]0

Try it online!
Explanation
We create a function g which takes 3 arguments.

a, which is the locations of all unmatched [s.
n, which is the number of characters processed
x which is the characters unprocessed.

If our first character is ] we remove u from the front our a and return (u,n) plus whatever else remains.
g(u:a)n(']':x)=(u,n):g a(n+1)x

If our first character is not ], that is either [ or something else, we increment n and add [n|s=='['] to the front of a.  [n|s=='['] will be [n] if s=='[' and [] otherwise.
g a n(s:x)=g([n|s=='[']++a)(n+1)x

If we are out of characters we return the empty list.
g[]_[]=[]

wow, thats some nice piece of recursive functions. I'm a beginner on Haskell, this impressed me:)

@gnu-nobody Thanks! This answer is probably not optimal, so I would encourage you to try and beat it, or wait until the serious Haskell golfers arrive.

I'd better wait until the serious Haskell golfers arrive

QBasic (QB64), 137 127 112 bytes
INPUT a$
for i=0to len(a$)
c$=mid$(a$,i+1,1)
if"["=c$then
b(n)=i
n=n+1
elseif"]"=c$then
n=n-1
?b(n),i
endif
next

We need four two bytes because the challenge requires 0-indexing. My first QBasic post, feedback is appreciated.

10 bytes thanks to steenbergh
3 bytes thanks to Erik the Outgolfer
12 bytes by saving in unix file format (\r\n -> \n)

Looks like this when executed:

Nice one. Couple of pointers: use ? instead of print (the compiler auto-expands this to print), you don't need the spaces between the quoted strings and THEN in the IFs, and you can drop the i after NEXT.

@steenbergh Huh, seems I forgot to remove whitespace ... but I removed the one between 0 and to? I'm confused ...

Not sure about QB64, but I think if c$="[" can become if"["=c$, elseif c$="]" can become elseif"]"=c$, end if can become endif, and, with a slight change in the output, ?b(n),i can become ?b(n)i (QBasic 1.1 is what I use, your case might be different).

@EriktheOutgolfer all but ?b(n)i worked

Java 10, 95 bytes
A void lambda taking the input string as an int[] of Unicode code points.
s->{int r=0,w=0;for(var c:s){if(c==91)s[w++]=r;if(c==93)System.out.println(s[--w]+","+r);r++;}}

Try It Online
Ungolfed
s -> {
    int r = 0, w = 0;
    for (var c : s) {
        if (c == 91)
            s[w++] = r;
        if (c == 93)
            System.out.println(s[--w] + "," + r);
        r++;
    }
}

Acknowledgments

thanks to Jonathan Frech for the idea of using the input string as a stack (here)

You must define r and w as part of the code, not as parameters: s->{int r=0,w=0;...}.

@OlivierGrégoire Kind of ambiguous, but this looks like it was intended to cover multiple empty inputs.

The answer you quote explicitly answers the question "Are we allowed to take an empty parameter instead we won't use anywhere?". You're using these inputs. I see no ambiguity at all here.

The edit part of the question makes it absolutely unambiguous about the "no-use" the variable.

Right, but then why does the top answer (1) not state that inputs are unused, (2) specify what the values of extra inputs are, and (3) mention the possibility of abusing extra inputs? Regardless, I'll move the variables.

Because 1. the context of the answer is clearly the question which unequivocally says "unused parameters", 2. to make sure we can identify unused parameters from the method call (also, Nathan Merill always wanted to make things very defined, even when unneeded, which is the case here), 3. if it's shorter to declare an extra input but not using it, you may define it. That's basically what Nathan Merill said in his answer.

R, 141 133 115 112 108 bytes
function(y,x=utf8ToInt(y)){for(i in seq(x)){if(x[i]==91)F=c(i,F);if(x[i]==93){T=c(T,F[1],i);F=F[-1]}};T[-1]}

Try it online!
Nothing special. 1-indexed, because I said so. R doesn't really have stacks, so I originally used c, head, and tail to get the same literal effect. Ungolfed original version (updates using utf8ToInt to remove some bytes, using the start of the vector as the top of the stack, and abusing T and F builtins to avoid initializing the stacks.):
f <- function(y, x=el(strsplit(y,""))) {
  p <- l <- NULL
  for(i in seq_along(x)) {
    if(x[[i]]=='[') {
      p <- c(p, i)
    }
    if(x[[i]]==']') {
      l <- c(l, tail(p, 1), i)
      p <- head(p, -1)
    }
  }
  l # Because I said so. Change to l-1 if you want to check the test cases.
}

Save some bytes by abusing built-ins `T`` and `F`

and 1:nchar(y) is shorter than seq_along(x). Very nice solution btw :)

I wonder if gregexpr is the way to go.

I had originally tried to leverage this approach but I am not sure if this is the right way here.

JayCe solution is flawed (check the result, it returns 22 28 22 instead of 22 28 21) probably the (ab)use of T/F is not really safe :D. This is shorter and seems to work --> Try it online!

@digEmAll better and shorter than my nonsense!

you can use seq(x) instead of 1:nchar(y) since y is guaranteed to have at least 2 characters.

-1 byte

Jelly, 20 18 bytes
Saved 1 byte thanks to @user202729 informing me that µ€ is )
ẹⱮØ[µ³ḣċþØ[_/Ụị)Z’

Try it online!
After wrestling with this for several hours just to get it working... I'm honestly surprised that it's gotten this short :-)
Explanation
ẹⱮØ[µ³ḣċþØ[_/Ụị)Z’   Main link. Argument: s (string)  '[a[b]c[]][d]'
  Ø[                 Shortcut for the string "[]".
 Ɱ                   For each char in the "[]":
ẹ                      Find the indices of each occurrence in the input.
                     For our example, this gives the array [[1, 3, 7, 10], [5, 8, 9, 12]].

    µ                Begin a new monadic chain, with said array as its argument.
               )     For each of the two sub-arrays q within the array:
                         [[1, 3, 7, 10], [5, 8, 9, 12]]
     ³ḣ                For each item n in q, take the first n chars of the input.
                         [['[',     '[a[',      '[a[b]c[',   '[a[b]c[]]['],
                          ['[a[b]', '[a[b]c[]', '[a[b]c[]]', '[a[b]c[]][d]']]
        þØ[            For each string s in this, and each char c in "[]":
       ċ                 Count the occurrences of c in s.
                         [[[1, 0],  [2, 0],     [3, 1],      [4, 3]],
                          [[2, 1],  [3, 2],     [3, 3],      [4, 4]]]
           _/          Reduce each pair by subtraction. This is the number of open brackets
                         at each position.
                         [[1, 2, 2, 1], [1, 1, 0, 0]]
             U         Sort the indices by their values, using position as a tiebreaker.
                         [[1, 4, 2, 3], [3, 4, 1, 2]]
              ị        Index these values back into q.
                         [[1, 10, 3, 7], [9, 12, 5, 8]]

               )     Start a new monadic chain with the result as its argument.
                Z    Zip; transpose rows and columns.
                         [[1, 9], [10, 12], [3, 5], [7, 8]]
                 ’   Decrement; switch to 0-indexing.
                         [[0, 8], [9, 11], [2, 4], [6, 7]]

Pyth, 26 bytes
VQIqN\[=+YZ)IqN\],.)YZ)=hZ

Try it here
Explanation
VQIqN\[=+YZ)IqN\],.)YZ)=hZ
VQ                     =hZ   For each character in the input (indexed by Z)...
  IqN\[=+YZ)                 ... if the character is [, add the index to Y...
            IqN\],.)YZ)      ... if the character is ], output the previous index
                             and current index.

Nice! My naïve approach was 36 bytes, C,x"[" MQ #.e*qb\[t+lhfSI/LT"[]"._>Q. Edit: I succeeded golfing mine quite a bit too, I'm now below 30.

SWI-Prolog 254 bytes
d([']'|T],I,[S|Z],M,R):-J is I+1,d(T,J,Z,[',','(',S,',',I,')'|M],R).
d(['['|T],I,S,M,R):-J is I+1,d(T,J,[I|S],M,R).
d([_|T],I,S,M,R):-J is I+1,d(T,J,S,M,R).
d(_,_,_,R,R).
m(X):-atom_chars(X,A),d(A,0,[],[']'],[_|R]),atomic_list_concat(['['|R],S),print(S).

Example:
?- m('!^45sdfd[hello world[[djfut]%%357]sr[jf]s][srtdg][]').
'[(49,50),(42,48),(8,41),(36,39),(20,33),(21,27)]'
true

Jelly,  22 21 20  19 bytes
No doubt it is possible in Jelly in half this byte count :p ...
n€Ø[ḅ-µMịÄÐƤi€0ĖƊ’Ä

A monadic link accepting a list of characters which returns a list of lists of integers.
As a full program it accepts a string and prints a representation of said list.
Try it online!
How?
n€Ø[ḅ-µMịÄÐƤi€0ĖƊ’Ä - Link: list of characters    e.g. "[f[o]o!]"
  Ø[                - list of characters = ['[', ']']
n€                  - not equal? for €ach              [[0,1],[1,1],[0,1],[1,1],[1,0],[1,1],[1,1],[1,0]]
                    -     ...relating to the characters:  [     f     [     o     ]     o     !     ]
    ḅ-              - convert from base -1             [1,0,1,0,-1,0,0,-1]
                    -     ...i.e.: 1 where '['; -1 where ']'; and 0 elsewhere
      µ             - start a new monadic chain with that as the argument, say V
                Ɗ   - last 3 links as a monad (function of V):
          ÐƤ        -   for post-fixes:
         Ä          -     cumulative sum               [[1,1,2,2,1,1,1,0],[0,1,1,0,0,0,-1],[1,1,0,0,0,-1],[0,-1,-1,-1,-2],[-1,-1,-1,-2],[0,0,-1],[0,-1],-1]
            i€0     -   1st index of 0 in €ach (or 0)  [8,1,3,1,0,1,1,0]
               Ė    -   enumerate                      [[1,8],[2,1],[3,3],[4,1],[5,0],[6,1],[7,1],[8,0]]
       M            - maximal indices of V             [1,3]
        ị           - index into                       [[1,8],[3,3]]
                 ’  - decrement                        [[0,7],[2,2]]
                  Ä - cumulative sum (vectorises)      [[0,7],[2,4]]

I was trying to use œ¿ and it's relatives but couldn't find a solution. This was closest I got.

Yes, it can be shorter, but I only managed one measly byte, not half the bytes. It still feels too long. :(

@EriktheOutgolfer there was an easy 1-byte save here too

Forth (gforth), 75 bytes
: f 0 do dup i + c@ dup 91 = if i s>f then 93 = if f>s . i . cr then loop ;

Try it online!
Abuses the floating-point stack, but allows using a do loop since the code doesn't (manually) touch the return stack.
Explanation

Loop through characters in string
Check each character

If equal to [, put on floating point stack
if equal to ] pop from floating point stack and output with current position

Code Explanation
0 do                 \ start a loop from 0 to string-length
  dup                \ duplicate the starting address to avoid losing it
  i + c@             \ get the address of the current position and retrieve the character
  dup                \ duplicate the character, to allow checking twice
  91 = if            \ if char = [
    i s>f            \ store the current address on the floating point stack
  then               \ end the if-statement
  93 = if            \ if char = ]
    f>s .            \ pop the starting position from the float-stack and print
    i .              \ print the current position
    cr               \ output a newline
  then               \ end the if-statement
loop                 \ end the loop

Retina, 36 bytes
L$v`\[((\[)|(?<-2>])|[^]])*
$.`,$.>`

Try it online! Explanation:
L

Generate a list from the match results.
$

Use the following substitution to generate the list instead of the matches.
v`

Allow matches to overlap.
\[((\[)|(?<-2>])|[^]])*

This is an application of .NET's balancing groups. The [ is matched literally, then as many characters as possible are consumed. As each subsequent [ is matched, the match is added to the $2 stack. If that stack isn't empty, we can then match a ], removing the match from the stack. Otherwise, we can match anything that's not a ] (the [ was already matched earlier). The match stops when it meets the matching ] for the [, since the $2 stack is (now) empty at that point.
$.`,$.>`

The substiution consists of two variables separated by a comma. The . indicates that the length of the variable, rather than its value, be used. The > indicates that the variable should be evaluated in terms of the right-hand separator rather than the match. The $` variable refers to the prefix of the match, which means $.` gives the position of the [; the > modifier alters this to the prefix of the match's right separator, which gives the position of the matching ].

Japt v1.4.5, 23 bytes
;Ë¥']?ApENo):D¥'[©NpE
A

Try it online!
Unpacked & How it works
;UmDE{D==']?ApENo):D=='[&&NpE
A

;                              Use alternative set of initial variables
                               A = [] is used here
 UmDE{                         Map over each char of input string...
      D==']?                     If the char is closing bracket...
            ApENo)                 Push the current index and N.pop() to A
                  :D=='[&&       Otherwise, if the char is opening bracket...
                          NpE      Push the current index to N

A     Output A

The output is a flattened array of [closing index, opening index]. If the reversed order is not desired, adding w at the end does the job (+1 bytes).

Common Lisp, 95 bytes
(lambda(u &aux s)(dotimes(p(length u))(case(elt u p)(#\[(push p s))(#\](print`(,(pop s),p))))))

Long version

(defun par (string &aux stack)
  (dotimes (pos (length string))
    (case (char string pos)
      (#\[ (push pos stack))
      (#\] (print (list (pop stack) pos))))))

Tests

((lambda(u &aux s)(dotimes(p(length u))(case(elt u p)(#\[(push p s))(#\](print`(,(pop s),p))))))
 "!^45sdfd[hello world[[djfut]%%357]sr[jf]s][srtdg][] ")

prints:
(21 27)
(20 33)
(36 39)
(8 41)
(42 48)
(49 50)

CJam, 25 bytes
0q{"[]"#"_ \p_p "S/=~)}/;

Surprisingly competitive - loses only to Japt and Jelly [Edit: and Charcoal and Stax :(]
Try it online!
Explanation
0                          Push 0.
 q                         Push the input.
  {                   }/   For each character in the input:
   "[]"#                     Find index of this character in the string "[]" (or -1 if not found).
                   =         Use this index to choose
        "       "S/            one of the following snippets
                    ~          and execute it:
         _                       If it was 0 ('['), duplicate the number on the stack.
           \p_p                  If it was 1 (']'), print the current number and the one under it.
                                 If it was -1, do nothing.
                     )       Increment the number on top of the stack.
                        ;  Delete the number.

Charcoal, 20 bytes
ＦＬθ≡§θι[⊞υι]«Ｉ⊟υ,Ｉι⸿

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

Loop over the implicit range of the length of the input string.
≡§θι

Switch on the current character.
[⊞υι

If it's a [ then push the current index to the predefined array variable.
]«Ｉ⊟υ,Ｉι⸿

If it's a ] then pop the latest index from the array variable and print it and the current index separated by a comma and start a new line. Alternate output formats, if acceptable, would save some bytes: ]Ｉ⟦⊟υιω saves 2 bytes but prints each index on a separate line, double-spacing the pairs of indexes; ]Ｉ⟦⊟υι simply prints the indexes on separate lines, making it hard to distinguish them.

K (ngn/k), 38 37 bytes
{b@0N 2#,/=(|':+\-/a)b:&|/a:"[]"=\:x}

Try it online!
{ } function with argument x
"[]"=\:x two boolean lists for the occurrences of "[" and "]"
a: assign to a
|/ boolean "or" of the two lists
& where (at which indices) are the brackets?
b: assign to b
-/ a list with 1 for "[", -1 for "]", and 0 everywhere else
+\ partial sums
|': pairwise maxima (each element max'ed with the previous one, the initial element remains the same)
This represents bracket depth for each character.
We index it with b (juxtaposition is indexing) and get bracket depth only for the brackets.
= "group by" - a dictionary mapping depths to the indices at which they occur
,/ concatenate the values in the dictionary, ignoring the keys
0N 2# reshape to a 2-column matrix (list of lists)
b@ index b with each element of the matrix

C (gcc), 87 bytes
f(char*Z){for(char*z=Z,*q=z;*z;*z++-93||printf("%d,%d;",*--q,z-1-Z))*z-91||(*q++=z-Z);}

Try it online!
Explanation
To keep track of opening bracket's string indices, the input string is overwritten and used as a stack.
f(char*Z){          // take mutable input string
 for(char*z=Z,*q=z; // copy pointer to current string index, current stack index
 *z;                // loop through the entire string
 *z++-93||          // if z == ']'
   printf("%d,%d;", // decrement stack pointer,
    *--q,z-1-Z))    //  write bracket pair position
  *z-91||           // if z == '['
   (*q++=z-Z);}     // write bracket position onto stack, increment stack pointer

Try it online!

Jelly, 20 bytes
=©ⱮØ[_/aÄ$+®ŻĠḊẎ_2s2

Try it online!
It has a side-effect on the register, hope it's allowed to be a function.

It's reusable, so I think it's fine. BF answers don't typically leave the tape blank

Perl 5, 53 bytes
say"$-[0] ".($+[0]-1)while s/\[[^][]*\]/1x length$&/e

Run as perl -nE '<above code snippet>'. Takes input through stdin.
As usual, the optimal Perl solution to the problem is a regular expression. We attempt to match any pair of brackets which does not contain any pairs within it using a rather silly-looking character class (s/\[[^][]*\]/.../). If the match is successful, we replace the matched text with the digit 1 over and over again so that we don't accidentally match those brackets again, and we print out the indices of the match. Rinse and repeat.

Stax, 13 bytes
é√p(l▓1½\á²ë(

Run and debug it
It uses the input stack to track open brace pairs.  Here's the program unpacked, ungolfed, and commented.
F       iterate over input characters
 .][I   get the index of the character in the string "[]", or -1
 ^|cv   skip the rest of this iteration if index was -1
 i~     push the current iteration index to the input stack
 C      skip the rest of this iteration if index was 0
 \      form a pair with the top two items from the input stack
 JP     join with space, and print

Run this one

Python 2, 109 bytes
def a(s,r=[],i=0):
 o=[]
 while i<len(s):exec["r+=[i]","o+=[(r.pop(),i)]",'']['[]'.find(s[i])];i+=1
 return o

Try it online!

This works as well!

Pyth,  28  26 bytes
{I#.e,t+lhfSI/LT`Y+._>Qk\]

Test suite.
At the moment it's longer than Mnemonic's approach, but I feel like I can golf this down a little and this fortunately also doesn't use Pythonically-imperative structures like V. The initial version was 36 bytes and also had numerous bugs.
How it works

{I#.e,t+lhfSI/LT`Y+._>Qk\] – Full program. Takes a quoted string Q from STDIN.
   .e                      – Enumerated map. k = iteration index, b = current element.
                     >Qk   – Get the elements of Q at indices greater than k.
                   ._      – Generates all the prefixes of this.
                  +     \] – And append an "]" (for handling some edge-cases).
          f                – Filter over this list, with T = current element.
              L `Y             – For each character in str([]), "[]"...
             / T               – ... Count the occurrences of it in T.
           SI                  – And check if the values are sorted increasingly.
         h                 – Head. Retrieve the first element.
       +l                  – Get the length of this + k.
      t                    – Decrement (by 1).
     ,                     – And pair this value with k. Returns [i, k] where i is
                             the index of the corresponding ] and k is that of [.
  #                        – Filter this list by:
{I                             – The pair is invariant over deduplicating.

{I#.e,t+lhfSI/LT`Y._>Q aaalmost works for 22 bytes...


text:
Equal Pair sum of 10?
Challenge :
Check :

if there are exactly n exclamation marks ! between every pair
and whether the sum of each pair equals to 10.

Input :

A string of arbitary length.
The number of exclamation marks to check for

Output :
if there are exactly n exclamation marks between each pair, return truthy value, otherwise falsy value.

Pair :
Pair is defined as two digits with at least one exclamation mark between them

Note :

The string may contain

lowercase letters
digits (1-9)
space
and obviously exclamation marks (!)

In case no digit pair is found, return a falsy value.
The exclamation will not appear at start or end of the string

Examples :
asas6!!4somevbss5!!asa5 , 2                ---> true
sasdasd3!2ssjdn3! sdf!3 , 1                ---> false
asjsj8sj!!!! 2 sjsadasd9!!!!1 , 4          ---> true
sal7!!3 , 2                                ---> true
nodtejsanhf , 2                            ---> true
2is digit no excla 5 , 8                   ---> true
a!1!9!8!2!a  , 1                           ---> true (thanks @ngn)

The last two cases were false imo but as suggested by Adam (who has more experience than me and probably knows better :) ), they were made true

Winning criteria :
this is code-golf so shortest code in bytes for each language wins.

Don't forget :
You must check whether the sum of the two numbers equals 10 or not too, along with whether each pair is separated via n exclamation marks

Credit ? :
@Laikoni found a challenge on coderbyte similar to this : Here. O_o ? I didn't know that

Some explanation :
@ngn suggested this case a!!1!2!3a45!6!!a , 1 (return false)
a!!      --> ignore this
1        --> here we go start
!        --> sum so far = 1
2        --> sum = 3, and stop

Yep the sum of each pair must be 10 and since the sum of the first pair wasn't 10, no need to go on. :)

Very closely related.

I recommend the Sandbox to iron out issues such as these before posting to Main.

@AdmBorkBork, if that challenge wasn't (currently) closed, I'd dupehammer this.

@Shaggy : We can always reopen that and close this

This has 4 down-votes ? O_o ? why

@MuhammadSalman I think the downvotes are due to lack of specification clarity at posting time. The Sandbox would have helped.

a!1!9!8!2!a - isn't 9!8 a "pair"?

@ngn : It would be if 1!9 weren't a pair

By the definition currently given ("Pair is defined as two digits with at least one exclamation mark between them") 9!8 is a pair. (Furthermore 1!9!8 is too, somewhat more debatable though).

APL (Dyalog Unicode), 62 48 bytesSBCS
Full program. Prompts stdin for string and then for n. Now handles cases like a!1!9!!8!2!a. Thanks to ngn for saving a bunch of bytes while pointing out failure of some unlisted test cases. Assumes ⎕IO (Index Origin) to be 0, which is default on many systems.
∧/(⎕=¯2+≢¨m),0=10|+/⎕D⍳↑m←'\d!+\d'⎕S'&'⊢⍞∩⎕D,'!'

Try it online!
⎕D,'!' concatenate the Digits and an exclamation point.
⍞∩ prompt for string and find the intersection with the above (removes all irrelevant chars)
⊢i← store in i (for input) and yield that
'\d!+\d'⎕S'&' PCRE Search for a digit, a "!" run, a digit
m← store in m (for matches)
↑ mix the list of strings into a character matrix, padding with spaces
⎕D⍳ find the ɩndex of each character in the Digits (i.e. "0" → 0, "1" → 1,… "!" and " " → 10)
+/ sum each row (i.e. each pair)
10| division remainder when divided by 10 (non-digits do not affect this result)
0= is it 0? (i.e. divisible by ten; max is 18 and min is 2, so no false positives)
(…), prepend the following:
 ≢¨m tally (count the length of) each match
 ¯2+ less 2 (for the two digits, i.e. length of the "!" run)
 ⎕= prompt for n; is it equal to the lengths?
∧/ are they all true? (AND reduction)

@MuhammadSalman Now it has an explanation. APL is really not very hard to understand. I'll be happy to teach you in The APL Orchard.

And I would love to learn. Will check that out

'(\d)!+(\d)'⎕S'\1\2' -> '!'~⍨¨'\d!+\d'⎕S'&'

+/¨⍎¨¨(⊂'55'), -> +/⎕d⍳↑ (⎕io←0)

⍵='!+'⎕S 1⊢i - this condition is wrong, there may be extra '!'s that are not part of pairs

10=+/⎕D⍳↑∩∘⎕D¨ -> 0=10|+/↑⎕D⍳⍪↑ this is tricky, note that there are no '0's in the input and that the sum of two digits can't be >18 (so, if the sum is a multiple of 10, it must be 10)

reuse the matches instead of the regex: ∧/(⎕=¯2+≢¨r),0=10|+/↑⎕D⍳⍪↑r←'\d!+\d'⎕S'&'⊢⍞∩⎕D,'!'

@ngn Thank you. I removed the two no-ops from your suggestions.

Python 2, 94 bytes
lambda s,c:all(sum(map(int,r))==10for r in re.findall('(\d).*?%s.*?(\d)'%('!'*c),s))
import re

Try it online!