[Question]
      [
Write a program which outputs the square root of a given number in the shortest time possible.
## Rules
It may not use any builtins or powering with non-integers.

# Input format
* as a function argument
* as a command line argument
* as a direct input on stdin or a window
Your entry hasn't to be a complete program, it may be a function or a snippet.

It doesn't need to be exact; a one percent margin of error is allowed.
The test cases will only be positive integers, but your program should output/return floats.

It may return the square root as function return value, print it to stdout or write in a consistent file, which is readable by the user..
Each program should specify the compiler/interpreter it should be run on and compiler flags. If they aren't specified, I'll use the following implementations: (just talking about mainstream langs):
* C/C++: gcc/g++ on Linux, no flags
* Java: OpenJDK on Linux, no flags
* Python: CPython
* Ruby: MRI
* Assembler: x86 Linux
* JS: Node.js
## Examples
```
Input    Output
4        2 (or something between 1.98 and 2.02)
64       8 (between 7.92 and 8.08)
10000    100 (between 99 and 101)
2        bewteen 1.40001 and 1.428
```
## Scoring
Your programs on the same computer with same conditions (Terminal and Iceweasel with this tab open).
This question has the tag "Fastest code", so the program, which calculates the square root of a (not yet given) random integer between 1 and 10^10 as fast as possible will win!

[Answer]
# C
Since input is limited to positive integers between 1 and 1010, I can use a well-known fast inverse square root [algorithm](https://en.wikipedia.org/wiki/Fast_inverse_square_root) to find the inverse square root of the reciprocal of the input.
I'm not sure what you mean by *"only Xfce and the program and a terminal running"* but since you stated that functions are acceptable, I provide a function in C that will take an integer argument (that will be casted to float automatically) and outputs a float as the result.
```
float f(float n) {
    n = 1.0f / n;
    long i;
    float x, y;
    x = n * 0.5f;
    y = n;
    i = *(long *)&y;
    i = 0x5f3759df - (i >> 1);
    y = *(float *)&i;
    y = y * (1.5f - (x * y * y));
    return y;
}
```
The following is a program that makes uses of the function above to calculate the square roots of the given test cases and compares them to the values given by the `sqrtf` function in `math.h`.
[Ideone](http://ideone.com/xhpvud)
[Answer]
# Python 3
Why am I using Python? Never mind.
```
def sqrt(n):
    # 3 iterations of newton's method, hard-coded
    # normalize
    # find highest bit
    highest = 1
    sqrt_highest = 1
    while highest < n:
        highest <<= 2
        sqrt_highest <<= 1
    n /= highest+0.0
    result = (n/4) + 1
    result = (result/2) + (n/(result*2))
    result = (result/2) + (n/(result*2))
    return result*sqrt_highest
```
[Ideone it!](http://ideone.com/fq8Do0)
[Answer]
# C
Uses unsigned integers when possible for speed.
`root.c`:
```
#include <math.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define ns(t) (1000000000 * t.tv_sec + t.tv_nsec)
struct timespec then, now;
int output(uint64_t result)
{
    clock_gettime(CLOCK_REALTIME, &now);
  printf("sqrt(x) = %10lu.%2d    real time:%9ld ns\n", result / 100, ((int) (result % 100)), ns(now) - ns(then));
  return 0;
}
//real time:    60597 ns
int main(int argc, char *argv[]) {
    clock_gettime(CLOCK_REALTIME, &then);
    uint64_t num = atol(argv[1]), root = 100, old_root = 0;
    num *= 10000; //multiply by 10k because int is faster
    //and you only need 2 d.p. precision max. (for small numbers)
    while (old_root != root) {
        old_root = root;
        root = (root + num / root) / 2;
    }
    return output(root);
}
```
`timein`:
```
#!/bin/bash
gcc -Wall $1 -lm -o $2 $2.c
./$2 $4
r=$(seq 1 $3)
for i in $r; do ./$2 $4; done > times
awk -v it=$3 '{ sum += $7 } END { print "\n" sum / (it) " ns" }' times
rm times
```
Usage: `./timein '-march=native -O3' root <iterations> <number>`
Inspired by [this answer](https://codegolf.stackexchange.com/a/74372/39244), uses [this algorithm](https://en.wikipedia.org/wiki/Newton's_method).
[Answer]
# [C (gcc)](https://gcc.gnu.org/)
demonstrates one Newton step after a linear approximation on mantissa
speed of C is fast but not really relevant unless you have to apply it several million times
then it is sensitive to overall context of SIMD vectorisation, memory access patterns & other branching causing pipeline stalls etc
```
float f(float x){int i=*(int*)&x;i=0x1fb90000+(i>>1);float y=*(float*)&i;return(y+x/y)/2;}
void main() {float y[4]={4,64,10000,2};
for(int j=0;j<4;j++)printf("f(%f)\t=\t%f\n",y[j],f(y[j]));}
```
[TIO](https://tio.run/##LY1BboMwEEX3nMJKlcoGim1qWlHHXCRkkQITjAgg41QgxNmpaTqbNxq9/6d4uxXF9qK7on2UFTqNttR9VGce9dFYVai2dviitOZijIbERL250ZjxmLKUsimB988kLSGq7b1FPt2g7a8WAX5yIovuLNLKx44@eZ2kVmzi8J0yNwHWWcaJfMqzs/4252lpKvswHZ6Dic6ExnL1fnpdovtVd5ig5T9yFhe1iPBDhHwvDONVetCb/RtqFJPNScgmCMhg3AXwAfARSG5Vbo@Qd4dwPjeXEPAOQuS6bb8 "C (gcc) – TIO")
[Answer]
>
> Adaptation of [my own answer](https://codegolf.stackexchange.com/questions/9027/fast-inverse-square-root/145914#145914) on [Fast inverse square root](https://codegolf.stackexchange.com/questions/9027/fast-inverse-square-root)
>
>
>
# [Tcl](http://tcl.tk/), 114 bytes
```
rename binary B
proc R n {B s [B f f $n] i i
B s [B f i [expr 0x5f3759df-($i>>1)]] f y
expr 1/($y*1.5-$n/2*$y**3)}
```
[Try it online!](https://tio.run/##PYm7CoMwAEV3v@IOGaJgNT5aOtTBT7CjZLA2QkDTNFpIEL89DR167nK4Zxtn741QwyLwkGowDm2kzWtEB4W9xYq@xRRGFIeEjP6XRC@sNshtPZWX@vqcUkpk07CY85Bd9Ksso8Ql7FSnRGVFEjwp48PPy6BhsVc4V2B5AMWBXX@2Ffe3ocTGt74DsfzwXw "Tcl – Try It Online")
]


[Question]
      [
## Introduction and Credit
Today without a fancy prelude: Please implement `takewhile`.
A variation of this (on a non-trivial data structure) was an assignment at my university functional programming course. This assignment is now closed and has been discussed in class and I have my professor's permission to post it here (I asked explicitly).
## Specification
### Input
The input will be a list (or your language's equivalent concept) of positive integers.
### Output
The output should be a list (or your language's equivalent concept) of positive integers.
### What to do?
Your task is to implement `takewhile` (language built-ins are allowed) with the predicate that the number under consideration is even (to focus on takewhile).
So you iterate over the list from start to end and while the condition (is even) holds, you copy to the output-list and as soon as you hit an element that doesn't make the condition true, you abort the operation and output (a step-by-step example is below). This higher-order functionality is also called takeWhile (`takewhile`).
### Potential corner cases
The order of the output list compared to the input list may not be changed, e.g. `[14,42,2]` may not become `[42,14]`.
The empty list is a valid in- and output.
### Who wins?
This is code-golf so the shortest answer in bytes wins!
Standard rules apply of course.
## Test Vectors
```
[14, 42, 2324, 97090, 4080622, 171480372] -> [14, 42, 2324, 97090, 4080622, 171480372]
[42, 14, 42, 2324] -> [42, 14, 42, 2324]
[7,14,42] -> []
[] -> []
[171480372, 13, 14, 42] -> [171480372]
[42, 14, 42, 43, 41, 4080622, 171480372] -> [42, 14, 42]
```
### Step-by-Step Example
```
Example Input: [42, 14, 42, 43, 41, 4080622, 171480372]
Consider first element: 42
42 is even (21*2)
Put 42 into output list, output list is now [42]
Consider second element: 14
14 is even (7*2)
Put 14 into output list, output list is now [42,14]
Consider third element: 42
42 is even (21*2)
Put 42 into output list, output list is now [42,14,42]
Consider fourth element: 43
43 is not even (2*21+1)
Drop 43 and return the current output list
return [42,14,42]
```

[Answer]
## Pyke, 8 bytes
```
0+2L%fhO
```
Interpreter fixed, use other links
Uses Dennis' method except my split\_at function includes the change - probably a bug
### Or with bugfix, 7 bytes
```
2L%1R@<
```
[Try it here!](http://pyke.catbus.co.uk/?code=2L%251R%40%3C&input=%5B42%2C+14%2C+43%2C+2324%5D)
```
2L%     -   map(%2, input)
   1R@  -  ^.index(1)
      < - input[:^]
```
Or after 2nd bugfix, 6 bytes
```
2L%fhO
```
[Try it here!](http://pyke.catbus.co.uk/?code=2L%25fhO&input=%5B42%2C+14%2C+42%2C+2324%5D)
Explanation:
```
2L%    -   map(%2, input)
   f   -  split_at(input, ^)
    hO - ^[0][:-1]
```
[Answer]
# JavaScript, 40 bytes
`a=>[...a,1].slice(0,a.findIndex(n=>n%2))`
### How it works
1) Take input array `a` and add a `1` to the end
2) Find the index of the first odd integer in the array
3) Return a subset of the array from index 0 (inclusive) to the odd integer's index (exclusive)
[Answer]
# GolfScript, 11 bytes
This is a full GolfScript program that reads a stringified GolfScript array literal (e.g. `[28 14 7 0]`) and prints out the same array with the first odd element and everything after it removed:
```
~1\{~&.},p;
```
[**Try it online.**](http://golfscript.tryitonline.net/#code=fjFce34mLn0scDs&input=WzQyIDE0IDQyIDQzIDQxIDQwODA2MjIgMTcxNDgwMzcyXQ)
(Also: [Extended version with test harness.](http://golfscript.tryitonline.net/#code=biV7ICAgICAgICAgICAgICMgc3BsaXQgaW5wdXQgaW50byBsaW5lcyBhbmQgbG9vcCBvdmVyIHRoZW0KICB-MVx7fiYufSxwOyAgICMgYWN0dWFsIGNvZGUKfS8gICAgICAgICAgICAgICMgZW5kIG9mIGxvb3Ag&input=WzE0IDQyIDIzMjQgOTcwOTAgNDA4MDYyMiAxNzE0ODAzNzJdCls0MiAxNCA0MiAyMzI0XQpbNyAxNCA0Ml0KW10KWzE3MTQ4MDM3MiAxMyAxNCA0Ml0KWzQyIDE0IDQyIDQzIDQxIDQwODA2MjIgMTcxNDgwMzcyXQ))
De-golfed version with comments:
```
~     # evaluate input
1\    # push the number 1 onto the stack and move it under then input array
{     # start of loop body
  ~   #  bitwise negate the input number (making odd numbers even and vice versa)
  &   #  take bitwise AND of input and the saved number (0 or 1) on stack
  .   #  duplicate result; filter loop will pop off the duplicate
},    # run loop above over input array, select elements for which it returns true
p     # stringify and print filtered array
;     # pop the number 0/1 off the stack
```
This solution is based on the GolfScript `{ },` filter operator, which runs the contents of the code block on each element of an array, and selects the elements of the array for which the code in the block returns a true (i.e. non-zero) value on top of the stack.
Thus, for example, `{1&},` would select all odd numbers in an array, and `{~1&},` would select all even numbers. The challenge, then, is to make a filter that selects even numbers *until it finds the first odd one*, and thereafter selects no numbers at all.
The solution I used is to replace the constant bit-mask `1` (used to extract the lowest bit of each input number) with a variable on the stack that stores the result (0 or 1) of the previous filter loop iteration (and is initialized to 1 before the loop). Thus, as soon as the filter returns 0 once, the bitmask also gets set to 0, preventing the filter from ever returning 1 again.
[Answer]
# Forth, 114 bytes
Forth doesn't really have lists. The parameters must be pushed onto the stack in reverse order, as is typical in Forth. The result will be left on the stack in the same order. This doesn't work on Ideone for some reason, but it works on repl. The new line is required to remove ambiguity of some sort?
```
: D DEPTH ;
: f D IF 1 D 1 DO D 1- ROLL LOOP D 0 DO I PICK 2 MOD IF D I LEAVE THEN LOOP
DO I ROLL DROP LOOP THEN ;
```
[**Try it online**](https://repl.it/C9Nz)
Ungolfed, with comments:
```
: f DEPTH IF                                ( if stack not empty )
        1 DEPTH 1 DO DEPTH 1- ROLL LOOP     ( put 1 on bottom of stack )
        DEPTH 0 DO                          ( loop over entire stack )
            I PICK 2 MOD IF                 ( if stack[i] is odd )
                DEPTH I LEAVE               ( put range and exit loop )
            THEN
        LOOP
        DO I ROLL                           ( roll eyes )
            DROP
        LOOP                                ( iterate that range and remove )
    THEN
;
```
This program (my previous attempt) prints the results until it hits an odd number. Everything remaining (not taken) will be left on the stack.
```
: f DEPTH IF BEGIN DUP 2 MOD DUP 1- IF SWAP . THEN UNTIL THEN ;
```
*Fails if only even integers*
[Answer]
# Befunge, 35 Bytes
This code handles numbers between 0 and 65535
```
1&:v
v-1_@#:@#<
>\:&:2%|
 \+1p4\< ^
```
Input format :
```
number_of_values    values(separated by a space)
```
Here is a version that displays the values at the end of the process :
```
1&:v>::   v                >00g1+:4g.v
v-1_^#:>#<>$$\$1-:10p000p0-| -g01p00:<
>\:&:2%|                   @
 \+1p4\< ^
```
You may test the code [here](http://www.quirkster.com/iano/js/befunge.html), but you will have to add a trailing line with trailing spaces, as this interpret specifies :
>
> « The code torus is only as large as the initial program. Insert more
> lines or trailing space if data will be put beyond the end of code.»
>
>
>
I don't know if this is acceptable, as I didn't count this trailing in the byte count

nb: it seems that because I'm storing number in the code, the interpreter won't let this program run twice in the correct way. You'll have to reload it.
---
How does this work:
![how](https://i.stack.imgur.com/DZvfr.png)
The interpreter follows the arrows and skip an instruction when crossing '#'
Grey dots are test, and the red line removes unneeded variables from the stack
Using the here in the above interpreter, the saved values are displayed in the code using their representations (I don't know the format).
Yes, Befunge is a quite reflective language
[Answer]
# 32-bit x86 machine code, 14 bytes
In hex:
```
31C9FCADD1E87203E0F941F7D9C3
```
The list of integers in machine code is something like C's "int a[]". Since the list contains positive integers let's assume the list is zero-terminated, i.e. the value zero marks the end of the array. It's also makes no sense to copy values to another buffer inside this function, that's what strncpy() is for.
The pointer to an array is passed via ESI register. Returns the number of elements comprising the resulting list in ECX.
## Disassembly:
```
31 c9     xor    ecx,ecx  ;ECX=0
fc        cld
_loop:
ad        lodsd           ;Fetch a number to EAX
d1 e8     shr    eax,1    ;EAX=>>1
72 03     jc _end         ;If CF is set then the number is odd, break
e0 f9     loopne _loop    ;--ECX; if(CF==0&&ZF==0)continue
41        inc    ecx      ;Should not include the terminating 0 into the count
_end:
f7 d9     neg    ecx      ;Counting from 0 downward, so ECX=-ECX
c3        ret
```
[Answer]
## Python 3, 59 bytes
```
def f(l):
 L=[]
 for x in l:
  if x%2:break
  L+=x,
 return L
```
Can ~~surely~~ probably be golfed more.
Thanks to everyone who commented :D
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 7 bytes
```
⁽₂Ḋ¾wJh
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwi4oG94oKC4biKwr53SmgiLCIiLCJbMTQsIDQyLCAyMzI0LCA5NzA5MCwgNDA4MDYyMiwgMTcxNDgwMzcyXVxuWzQyLCAxNCwgNDIsIDQzLCA0MSwgNDA4MDYyMiwgMTcxNDgwMzcyXVxuW10iXQ==)
### Explained
```
⁽₂Ḋ¾wJh
⁽       # 1-element lambda
 ₂      # check if even
  Ḋ     # group if true
   ¾wJ  # add empty list to end
      h # get head of the list
```
[Answer]
# [Factor](https://factorcode.org), 24 bytes
```
[ [ even? ] take-while ]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=jY9PboJAFMbjllN8PQBmZpgUtIldNm66McYFcTEhj0BApMNoNYaTuGHTXqE9S09TGhANJqRv816-7_f-nT9DFZitrn5Gq-Vi_voyRUI6oxQFve0oC6i4VmM6GK0KbJSJkGsy5pjrODN4sqyThTpO4BJSQDhCYuKyCYNkHnsUAtzl0mOOK1DiAfbsn2w7tuZu6G5CT25htxU77GLcCddF3Ok3DRwhHUg-9FlHllb5sTOh7X378EF7yp6xhlEJ2e9RnBLWjf21UXkN_J2YxglhXFOkgqhxq6rJvw)
[Answer]
# [jq](https://stedolan.github.io/jq/), 20 bytes
```
.[:map(.%2)[[1]][0]]
```
[Try it online!](https://tio.run/##yyr8/18v2io3sUBDT9VIMzraMDY22iA29v//aEMTHQUTIx0FI2MjIMvS3MDSAChgYGFgZgQUNTQ3NLEwMDY3iuWKBqlCVg0UMtcBCpiAJIEIrhaozBimFE2fCVDCxBCrBf/yC0oy8/OK/@smAwA "jq – Try It Online")
Explanation:
```
   map(.%2)            Maps the array items to their remainders when divided by 2
           [[1]]       Returns an array of indices where those items equal 1 (odds)
                [0]    Returns the first item of that array of indices
.[:                ]   Returns the original array up until that index
```
[Answer]
# [tinylisp 2](https://github.com/dloscutoff/tinylisp2), 6 bytes
```
(p ] e
```
Try it at [Replit](https://replit.com/@dloscutoff/tinylisp2). Example session:
```
tl2> (p ] e
(() remaining-args (eval (concat (q (] e)) (quote-each remaining-args))))
tl2> (def take-while-even _)
take-while-even
tl2> (take-while-even (list 2 4 6 7 8))
(2 4 6)
```
### Explanation
Uses (abbreviated aliases for) the library functions `take-while` and `even?`:
```
(p ] e)
(p    )  ; Partially apply
   ]     ; the take-while function
     e   ; to the even? function
```
---
Without using the library's `take-while` function, I found a rather elegant solution using `foldr` which is **26 bytes**:
```
(p {(\(N A)(?(e N)(c N A)(
```
That is, partially apply the `{` (foldr) function to the following argument:
```
(\(N A)(?(e N)(c N A)()))
(\                      ) ; Lambda function
  (N A)                   ; that takes a number N and a list A:
       (?              )  ;  If
         (e N)            ;  N is even
              (c N A)     ;  cons N to A
                     ()   ;  Else return empty list
```
So we end up with a function that takes a list and right-folds it on the above function, with a default starting accumulator value of nil (empty list). This starts from the right end of the list, collecting values as long as they are even, but whenever it encounters an odd value it discards all previous values and starts over.
[Answer]
# Rust, 25 bytes
```
|x|x.take_while(|x|x%2<1)
```
[Answer]
# K, 12 bytes
```
{x@&~|\2!'x}
```
## Explanation
```
{           } Function definition.
         'x   For each item in the input list...
       2!     Modulo it with 2 (e.g. 1%2, 5%2, 2%2, etc.) to get a list of booleans.
     |\       Fold | over the list to figure out where the odd numbers begin.
    ~         Flip the values it to get the beginning even numbers (until they turn odd).
   &          Get the indices.
 x@           Index the original list.
```
[Answer]
## [Minkolang 0.15](https://github.com/elendiastarman/Minkolang), 12 bytes
```
nd2%,5&xr$N.
```
[Try it here!](http://play.starmaninnovations.com/minkolang/?code=nd2%25%2C5%26xr%24N%2E&input=%5B42%2C%2014%2C%2042%2C%2043%2C%2041%2C%204080622%2C%20171480372%5D)
### Explanation
```
nd              Take number from input and duplicate
  2%            Modulo 2
    ,           Logical NOT
     5&         Pop top of stack and jump 5 spaces if truthy
       x        Dump top element
        r       Reverse stack
         $N.    Output whole stack as numbers and stop.
```
Minkolang's codebox is toroidal, so if the instruction pointer does not stop, then it loops around to the beginning again. Trying to take a number after all input has been exhausted pushes -1, which is very conveniently odd.
[Answer]
## Python, 43 bytes
```
lambda l:[x for x in l if l.__imul__(~x%2)]
```
Calling `l.__imul__(n)` does `l*=n`. For `n=~x%2`, it empties the list when `x` is even and otherwise leaves it unchanged. The list comprehension iterates and collect elements until it hits an odd number, which stops the iteration by emptying the list. Moreover, because it outputs the now-empty list, the `if` fails and the current odd value is not included.
[Answer]
## Lua, 67 Bytes
Simply iterate on each elements of the input using a `repeat..until` loop. The first iteration will use `i=0`, which isn't the first element of the input as Lua's tables are 1-indexed, resulting in `r[0]=nil` which won't do anything as `r[0]` is already `nil`.
```
function f(t)r={}i=0repeat r[i]=t[i]i=i+1until t[i]%2<1return r end
```
[Answer]
# Python 2, ~~59~~ ~~57~~ 56 bytes
```
def f(L,E=[]):
 while L and~L[0]%2:E+=L.pop(0),
 print E
```
[**Try it online**](https://repl.it/C8vD/2)
If printing rather than returning a list is allowed, **44 bytes**:
```
L=input()
while L and~L[0]%2:print L.pop(0)
```
And shorter by xnor, **34 bytes**, exits with an error on encountering an odd number:
```
for x in input():
    0>>x%-2;print x
```
[Answer]
# Perl, 21 bytes
20 bytes code + 1 bytes command line (-p)
```
s/ ?\d*[13579]\b.*//
```
Usage example:
```
echo "20 4 6 5 3 4" | perl -pe "s/ ?\d*[13579]\b.*//"
```
[Answer]
# C, ~~73~~ ~~69~~ ~~63~~ ~~60~~ ~~54~~ ~~45~~ 42
This requires a NULL-terminated array of strings as input.
It modifies the parameter by chopping the list down to only even entries.
```
f(char**v){for(;*v&&~atoi(*v++)&1;);*v=0;}
```
If printing is allowed (45 bytes, doesn't modify parameter):
```
f(char**v){for(;*v&&~atoi(*v)&1;puts(*v++));}
```
Here is the previous complete program version (63 bytes):
```
i;main(int c,char**v){for(;(++i<c)-(atoi(v[i])&1);puts(v[i]));}
```
Takes input as program arguments.
[Answer]
# PowerShell 26 bytes
```
process{if($_%2){break}$_}
```
Explanation
```
process{if($_%2){break}$_}
process{                 } # runs the script block once per item in the passed parameter
        if($_%2){break}    # if odd, break out of process{}
                       $_  # implicit output
```
Testing (save as evenodd.ps1):
```
PS> 42,14,42,2324 | .\evenodd.ps1
42
14
42
2324
PS> 7,14,42 | .\evenodd.ps1
PS> 171480372,13,14,42 | .\evenodd.ps1
171480372
```
[Answer]
# Common Lisp, 44 bytes
```
 (loop as x in(read)while(evenp x)collect x)
```
[Try it online!](https://tio.run/##DcjLCoAgEEbhV/mX487LUL5O2EDCoJJRvr25OXycpLm3Se3O5ZkgrbXh6BjIhW45TvNdWYXkldIwTKqqkp6laSaxh2OscgA7sI128@vtjqMNuzc/)
[Answer]
# [Husk](https://github.com/barbuz/Husk), 3 bytes
```
↑¦2
```
[Try it online!](https://tio.run/##yygtzv6f@6ip8f@jtomHlhn9//8/OtrQRMfESMfI2MhEx9LcwNJAx8TAwsDMyEjH0NzQxMLA2NwoVicaqAKhDsg3h3CBLCCCK9QxNIaLw3WYGOuYGGIxNBYA "Husk – Try It Online")
After [my adventures](https://codegolf.stackexchange.com/a/182367/85334) with using drop-while to set a default input value with Husk's type inference system, I jumped at the opportunity to use take-while for something normal.
```
↑      The largest prefix of
       the input
 ¦     in which each element is divisible by
  2    two.
```
[Answer]
# [Java (JDK)](http://jdk.java.net/), 58 bytes
```
a->a.stream().mapToInt(i->i).takeWhile(i->i%2<1).toArray()
```
[Try it online!](https://tio.run/##nVNda9swFH33r7gUAjIownbM0japYQwKhb11sIcsD5ojp0pty5Pk0BDy2zN9@KNdulGGMfjee3TO0bG0o3s63W2ez7xqhNSwMzVpNS9J0da55qIm993HIrjAKC0ZrcgXUZYs10KqdzCfpaSH9wZfudKLIOC1ZrKgOYP7YwCgNNU8h73gG9BMaWTmqzXwumk1Bl@wl8bIsU1oFwD0BpeWcflg@LZMZthhMyjg7kynGe3MopBUtPkmDAzxacZDoukz@/7ES@bqSbKMTU842yg8W4GFk9lTCTTXLS0frBm4A7@1nthZDMlP8cI2RiX3oaAxHMNqHaIw9IR@M5KptrRsBaFNUx7QK40eWADqtNgvM1PIL8JDECH4KAAeD0qziohWk0YahQJdTRRMM5ioH/UV7j1r8ajNeNu5vux7hd7qCVip2EdEAPWmTBH@j@TlYNxm5yaw73hYXJD2cScmp4opk6c3ezzGKYY0wZDMEvN1M49uItOIrqNPienG8zi9jmbz5IThw9AT7rgt@PUiS3LRG9BzbPqpUxqbb6tBw3DMeh5n7d/iqQGn8d/2NSL96tMi@OOqVZTXyMdtYqRyq/ojVQgJqEt4yBdux6jHs@fua99fRWs8gFbx@s2/O51/Aw "Java (JDK) – Try It Online")
Takes a `List<Integer>` and outputs an `int[]`.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 25 bytes
```
->a{a.take_while &:even?}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuhY7de0SqxP1ShKzU-PLMzJzUhXUrFLLUvPsayHyN-0LFNyio02MdBQMTXQUQLSJMRAbArGBhYGZEUjC3NDEwsDY3Cg2VkFZQddOAUl5LMSYBQsgNAA)
[Answer]
# [J-uby](https://github.com/cyoce/J-uby), 18 bytes
```
:take_while+:even?
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m700K740qXLBIjfbpaUlaboWm6xKErNT48szMnNSta1Sy1Lz7CESN-0LFNyio02MdBQMTXQUQLSJMRAbArGBhYGZEUjC3NDEwsDY3Cg2VkFZQddOAUl5LMSYBQsgNAA)
[Answer]
# [Prolog (SWI)](http://www.swi-prolog.org), 59 bytes
```
[]+[].
[H|_]+[]:-1is H mod 2.
[H|T]+[H|R]:-0is H mod 2,T+R.
```
[Try it online!](https://tio.run/##bY5NC4JAEEDv/gqPyY7LftFql/ATz@JtWboUIViGBl7875vVlBDdhvfmMXMb@q4/h@PUOmcsMZZ6ppoPz2kX8nb0K//SH33xws2Cq7leDFsNNKSmbh8arkAJEFIoiDWLGSgWsa0QwDVXEZNaWJLANLT30yYJ4NqBZ5ZgzSxJUaeo9dtakqHIUFiSI8mRfI8Al5@qwJ3i95qSoPi//0osyoC6Bw "Prolog (SWI) – Try It Online")
[Answer]
# ARM Thumb-2 machine code, 12 bytes
```
00000000: 04 c8 52 ea c2 72 04 c1 fa d5 70 47              ..R..r....pG
```
Assembly:
```
    .syntax unified
    .arch armv7-a
    .thumb
    .globl takewhile
    .thumb_func
    // input: int *, r0
    // output: int *, r1
    // lists are terminated with a negative number
takewhile:
.Lloop:
    // Load number into r2, increment r0
    ldmia   r0!, {r2}
    //  1. shift the LSB of r0 into the MSB
    //  2. Logical OR
    //  3. Set flags on the result
    // On either a terminator or an odd number, the MSB
    // will be set, which sets the N flag. Additionally,
    // this will terminate the list when stored.
    //    r2 = r2 | (r2 << 31);
    //    NF = r2 & 0x80000000;
    orrs.w  r2, r2, r2, lsl #31
    // Store r2 into r1, increment r1
    stmia   r1!, {r2}
    // Loop if MSB was not set (N flag not set)
    bpl     .Lloop
    // Return
    bx      lr
```
This function requires and outputs an array of positive `int32_t`s terminated with any negative `int32_t`. It follows standard C calling convention:
```
#include <stdint.h>
#include <stdio.h>
void takewhile(const int32_t *input /* r0 */, int32_t *output /* r1 */);
int main(void)
{
    const int32_t input[5] = { 171480372, 13, 14, 42, -1 };
    int32_t output[5];
    takewhile(input, output);
    for (int i = 0; output[i] >= 0; i++) {
        printf("%d, ", output[i]);
    }
    putchar('\n');
}
```
This takes advantage of the "numbers are positive" condition, and how ARM lets me set the condition codes for free.
I repeatedly logical OR the lowest bit of the values with the highest bit, and test the result. If the result is negative, one of the following is true:
1. The end of the list was reached (the upper bit was already set)
2. The number was odd (the lowest bit was set, which when shifted sets the upper bit).
With the example above, the outputted values will be this:
```
{ 171480372, /* -2147483635 */ 13 | 0x80000000 }
```
[Answer]
# [Fig](https://github.com/Seggan/Fig), \$3\log\_{256}(96)\approx\$ 2.469 bytes
```
t@E
```
[Try it online!](https://fig.fly.dev/#WyJ0QEUiLCJbNDIsIDE0LCA0MiwgNDMsIDQxLCA0MDgwNjIyLCAxNzE0ODAzNzJdIl0=)
Builtin. Can't have a functional language without one.
```
t@E
t@  # Take while
  E # Even
```
[Answer]
# [Nim](https://nim-lang.org/), 87 bytes
```
proc t(a:seq[int]):seq[int]=
  var i=0;while i<a.len and a[i]mod 2==0:inc i
  a[0..i-1]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m704LzN3wYKlpSVpuhY3wwuK8pMVSjQSrYpTC6Mz80piNeEsWy4FhbLEIoVMWwPr8ozMnFSFTJtEvZzUPIXEvBSFxOjM2Nz8FAUjW1sDq8y8ZIVMoPLEaAM9vUxdw1iI8VBbYLYBAA)
[Answer]
# [Go](https://go.dev), ~~78~~ 64 bytes
```
func(s[]int,c func(int)){for _,x:=range s{if x%2>0{break}
c(x)}}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=bVBtSsQwEMVfQk4xLAgNREnTYLsLFY_g_2WR2G2WsDYpaVcKoSfxTxE81Hoap6mKiBDIzHtv3ny8vh3cdIZWVUd1qKFRxhLTtM73Nyvd9Cvyojzo8v3U6-vifK9Ptkq67c7YnlUQMwwpDdp5eGTDpvTKok8XjIbhStzx8ORrdRxJlQx0HBefj4vLuTR2S2ggaNHBpoTtLjqHkEoGUjAQmcBonfM1R4AX_FYgmuapLHiWi5GFWfVbjVDOEJAzie9Hi7LsW_qnTiIh038bjIQsm5k44LJcHDfEyziIExOdmI7FcwwzTZEGcKVq29ruE8cGSkZKHjxyz3bWgkOEfN1jmpb_Ew)
* -14 bytes by @Steffan
### [Go](https://go.dev), generic with predicate, 96 bytes
```
func f[T any](s[]T,b func(T)bool)(o[]T){for i:=0;i<len(s)&&b(s[i]);i++{o=append(o,s[i])}
return}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=bZDNSsQwFIVxm5WPcBlwSJgoaafYzoxdunfRXSljOrZDsE1KfwYk9EncFMGH8FH0abxtVUSEkFxOvuTec55fjmZ4q-ThUR4zKKXSRJWVqdurRV62i9euzS-D9_u80wfI4wikfkpoEycRT2EUacRSYwpGDWrM5qYGtQ3FTt0UmaYNWy5TxFXCdmq1siaUVZXpB2r4JPakztqu1v3c5-PsfGo0jkGZJUq3DWxDiJM4wdpax-PguRzctYvVxhcbgYIIxLWLquM7XiDWvttzO1K_aZR8joI3XuL6YRFbf6N_3nl44Tn_NugJOUm02tyeMg3hHIUCHHKKw862QF24EIYgEB-T2XM1-amlxrAnd5bc1VgUmqqGQz7t86-MkZ58BTMM8_kJ)
]


[Question]
      [
>
> The challenge involve simply toggling a string within another string.
>
>
>
## Explanation
If the **toggle string** is a substring of the **main string**, remove all instances of the **toggle string** from the **main string**; otherwise, append the **toggle string** at the end of the **main string**.
## Rules
* All string are composed of printable ASCII characters
* The function should take two parameters: the **main string** and the **toggle string**.
* The **main string** can be empty.
* The **toggle string** cannot be empty.
* The result should be a string, which can be empty.
* The shortest answer wins.
## Examples
```
function toggle(main_string, toggle_string){ ... }
toggle('this string has 6 words ', 'now')
=> 'this string has 6 words now'
toggle('this string has 5 words now', ' now')
=> 'this string has 5 words'
```
## Tests cases
```
'','a'          => 'a'
'a','a'         => ''
'b','a'         => 'ba'
'ab','a'        => 'b'
'aba','a'       => 'b'
'ababa', 'aba'  => 'ba'
```

[Answer]
# Java 8, ~~80~~ ~~70~~ ~~65~~ 34 bytes
```
t->m->m==(m=m.replace(t,""))?m+t:m
```
Probably my shortest Java 'codegolf' so far.. xD
with some help from the comments.. ;)
**Explanation:**
[Try it online.](https://tio.run/##nY5BC4JAEIXv/orB00q6PyDTbt06eYwO42qxtrsuOgoS/nbb0IJuGgzMg3nvzVdhj1FtS1MVj0kobFs4ozRPD6AlJCmgcg7ekVT81hlBsjb8tIhDRo0093CVZ95pCgISmChKtZskYTrRvCmtQlEyCn0/CI56R3s9xZ6DsF2uHMTC0teyAO342Nx2uWLwRgXIhpZKzeuOuHUXUoYJjtaqgfnoBx/p2uMtftwayDd/@COxkir/DX1jozdOLw)
```
t->m->                     // Method with two String parameters and String return-type
                           // (NOTE: Takes the toggle `t` and main `m` in reversed order)
  m==(m=m.replace(t,""))?  //  If `m` equals `m` with all `t`-substrings removed:
                           //  (And set `m` to `m` with all `t`-substrings removed)
   m+t                     //   Output this new `m` concatted with `t`
  :                        //  Else:
   m                       //   Output just this new `m`
```
[Answer]
# MATL, 11 bytes
```
yyXf?''YX}h
```
[Try it Online!](http://matl.tryitonline.net/#code=eXlYZj8nJ1lYfWg&input=J2FiYWJhJwonYWJhJw)
[All test cases](http://matl.tryitonline.net/#code=YGlpeXlYZj8nJ1lYfWhdRFRd&input=JycKJ2EnCidhJwonYScKJ2InCidhJwonYWInCidhJwonYWJhJwonYScKJ2FiYWJhJwonYWJhJw)
**Explanation**
```
            % Implicitly grab the main string
            % Implicitly grab the toggle string
y           % Copy the main string
y           % Copy the toggle string
Xf          % Check to see if the toggle string is present in the main string
?           % If so
    ''YX    % Replace with an empty string
}           % else
    h       % Horizontally concatenate the two strings
            % Implicit end of if...else
            % Implicitly display the result
```
[Answer]
# Python 3, 38 bytes
```
lambda s,t:(s+t,s.replace(t,""))[t in s]
```
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
œṣȮ⁸e⁹ẋ
```
[Try it online!](http://jelly.tryitonline.net/#code=xZPhuaPIruKBuGXigbnhuos&input=&args=J3RoaXMgc3RyaW5nIGhhcyA2IHdvcmRzICc+J25vdyc)
### How it works
```
œṣȮ⁸e⁹ẋ  Main link. Arguments: s (string), t (toggle string)
œṣ       Split s at occurrences of t.
  Ȯ      Print the result.
   ⁸e    Check if s occurs in the split s. Yields 1 (true) or 0 (false).
     ⁹ẋ  Repeat t that many times.
```
[Answer]
## JavaScript (ES6), ~~39~~ 37 bytes
```
(s,t,u=s.split(t).join``)=>u==s?s+t:u
```
[Answer]
## Pyke, 14 bytes
```
DX{iIXRk:)i!IJ
```
[Try it here!](http://pyke.catbus.co.uk/?code=DX%7BiIXRk%3A%29i%21IJ&input=%5B%22this+string+has+5+words+now%22%2C%22now%22%5D)
Given that Pyke has no `else` structure, I think this is pretty reasonable score
Explanation:
```
D              -    Duplicate input
 X             -   a,b = ^
  {            -  a in b
   i           - i = ^
    I          - if i:
     XRk:      -  a = b.replace(a,"")
         i!I   - if not i:
            J  -  a = "".join(input)
               - print a
```
[Answer]
# CJam, 9
```
q~:B/2Be]
```
[Try it online.](http://cjam.aditsu.net/#code=q%7E%3AB%2F2Be%5D&input=%22code%20golf%22%20%22o%22) Thanks jimmy23013 for chopping off 1 byte :)
**Explanation:**
```
q~     read and evaluate the input (given as 2 quoted strings)
:B     store the toggle string in B
/      split the main string by the toggle string
2Be]   pad the array of pieces to the right with B, up to length 2 (if shorter)
```
[Answer]
# Javascript (ECMAScript 6): 47 bytes
```
(a,b)=>(c=a.replace(RegExp(b,'g'),''))!=a?c:a+b
```
[Answer]
## [Retina](https://github.com/mbuettner/retina/), ~~38~~ 31 bytes
Byte count assumes ISO 8859-1 encoding.
```
(.+)(?=.*¶\1$)
·
1>`·|¶.+
T`·¶
```
The trailing linefeed is significant. Input format is both strings separated with a linefeed.
[Try it online!](http://retina.tryitonline.net/#code=JShHYAooLispKD89Lio7XDEkKQohCjE-YCF8Oy4rCgpUYCE7&input=dGhpcyBzdHJpbmcgaGFzIDYgd29yZHMgO25vdwp0aGlzIHN0cmluZyBoYXMgNSB3b3JkcyBub3c7IG5vdwo7YQphO2EKYjthCmFiO2EKYWJhO2EKYWJhYmE7YWJhCmFiYWJhYmFiYTthYmE) The first line allows running several test cases at once (for the test suite, use `;` to separate the strings and linefeeds to separate test cases; the first line takes care of the conversion).
### Explanation
```
(.+)(?=.*¶\1$)
·
```
In this first step we replace all occurrences of the toggle string in the main string with `·`. We need to insert these markers so that we can determine afterwards if any substitution happened.
```
1>`·|¶.+
```
This is another substitution which removes a `·` marker, or the second line (including the separating linefeed). However, the `1>` is a limit which means that only matches *after* the first are considered. Hence, if the toggle string did not occur in the main string, we won't have inserted any `·`, so the second line will be the first match and won't be removed. Otherwise, we remove the second line along with all but the first marker.
```
T`·¶
```
While this uses a transliteration stage, it's also used simply for removing characters. In particular, we move both `·` and linefeeds. We need the first one, in case there was a match (because then the first `·` will have been left behind by the previous stage) and we need the second one in case there wasn't a match (to join the two lines together and thereby append the toggle string to the main string).
[Answer]
# Python (3.4): ~~55~~ ~~54~~ ~~47~~ 44 Bytes
```
lambda m,t:m.replace(t,'')if t in m else m+t
```
Testing:
```
toggle=lambda m,t:m.replace(t,'')if t in m else m+t
print('', 'a', toggle('','a'))
print('a', 'a', toggle('a','a'))
print('b', 'a', toggle('b','a'))
print('ab', 'a', toggle('ab','a'))
print('aba', 'a', toggle('aba','a'))
print('ababa', 'aba', toggle('ababa','aba'))
```
The Test output
```
 a a
a a
b a ba
ab a b
aba a b
ababa aba ba
```
~~Using a def would be longer because you have to use a return statement, if it were possible without return it would save 2 Bytes~~
Since explicit declaration of the function is not needed (sorry I didn't know that) 7 Bytes were saved.
[Answer]
# C#, 63
```
string F(string s,string t)=>s.Contains(t)?s.Replace(t,""):s+t;
```
Better than Java :)
Test code:
```
public static void Main()
{
    Console.WriteLine(F("", "a"));
    Console.WriteLine(F("a", "a"));
    Console.WriteLine(F("b", "a"));
    Console.WriteLine(F("ab", "a"));
    Console.WriteLine(F("aba", "a"));
    Console.WriteLine(F("ababa", "aba"));
    Console.ReadLine();
}
```
Output:
```
a
ba
b
b
ba
```
[Answer]
# Pyth, ~~13~~ ~~11~~ 10 bytes
```
?/Qz:Qzk+z
```
[Test suite.](http://pyth.herokuapp.com/?code=%3F%2FQz%3AQzk%2Bz&test_suite=1&test_suite_input=%22%22%0Aa%0A%0A%22a%22%0Aa%0A%0A%22b%22%0Aa%0A%0A%22ab%22%0Aa%0A%0A%22aba%22%0Aa%0A%0A%22ababa%22%0Aaba%0A&debug=0&input_size=3)
Input format: first string in quotes, second string without quotes.
### This is also 10 bytes:
```
?tJcQzsJ+z
```
[Test suite.](http://pyth.herokuapp.com/?code=%3FtJcQzsJ%2Bz&test_suite=1&test_suite_input=%22%22%0Aa%0A%0A%22a%22%0Aa%0A%0A%22b%22%0Aa%0A%0A%22ab%22%0Aa%0A%0A%22aba%22%0Aa%0A%0A%22ababa%22%0Aaba%0A&debug=0&input_size=3)
### This is 11 bytes:
```
pscQz*!}zQz
```
[Test suite.](http://pyth.herokuapp.com/?code=pscQz*!%7DzQz&test_suite=1&test_suite_input=%22%22%0Aa%0A%0A%22a%22%0Aa%0A%0A%22b%22%0Aa%0A%0A%22ab%22%0Aa%0A%0A%22aba%22%0Aa%0A%0A%22ababa%22%0Aaba%0A&debug=0&input_size=3)
### Previous 13-byte solution:
```
?:IQzk+Qz:Qzk
```
[Test suite.](http://pyth.herokuapp.com/?code=%3F%3AIQzk%2BQz%3AQzk&test_suite=1&test_suite_input=%22%22%0Aa%0A%0A%22a%22%0Aa%0A%0A%22b%22%0Aa%0A%0A%22ab%22%0Aa%0A%0A%22aba%22%0Aa%0A%0A%22ababa%22%0Aaba%0A&debug=0&input_size=3)
[Answer]
# Jolf, 12 bytes
```
?=iγρiIE+iIγ
```
Or, if we must include regex-sensitive chars:
```
?=iγρiLeIE+iIγ
```
[Try it here!](http://conorobrien-foxx.github.io/Jolf/#code=Pz1pzrPPgWlMZUlFK2lJzrM&input=SGVsbG8sIHBlcnNvbiEKCiwgcGVyc29uIQ)
## Explanation
```
?=iγρiIE+iIγ    if(i === (γ = i.replace(I, E))) alert(i + I); else alert(γ);
  i                i
 =                   ===
    ρ                          .replace( ,  )
     iI                       i         I
       E                                   E
   γ                     (γ =                )
?               if(                           )
        +iI                                     alert(i + I);
                                                              else
           γ                                                       alert(γ);
```
[Answer]
# JavaScript (ES6), 37 Bytes
```
(m,t)=>(w=m.split(t).join``)==m?m+t:w
```
Slightly shorter than @nobe4 's answer by taking advantage of split and join
[Answer]
# Racket, 70 bytes
Pretty straight forward.
```
(λ(s t)((if(string-contains? s t)string-replace string-append)s t""))
```
[Answer]
# Scala, 72 70 bytes
```
def x(m:String,s:String)={val r=m.replaceAll(s,"");if(r==m)m+s else r}
```
Online interpreter: [www.tryscala.com](http://www.tryscala.com)
[Answer]
# Oracle SQL 11.2, 66 bytes
```
SELECT DECODE(:1,s,s||:2,s)FROM(SELECT REPLACE(:1,:2)s FROM DUAL);
```
[Answer]
# Ruby, ~~33 bytes~~ ~~27 bytes (28 if using global subtitution)~~ definitely 28 bytes
```
->u,v{u[v]?u.gsub(v,''):u+v}
```
[Answer]
# Ruby, ~~35~~ ~~37~~ 28 bytes
```
->m,t{m[t]?m.gsub(t,''):m+t}
```
Hooray for string interpolation! It even works in regexes. The rest is simple: if the string in `t` matches to `m`, replace `t` with `''`, else return `m+t`.
**Edit:** Fixed a bug.
**Edit:** I applied Kevin Lau's suggestion, but it appears that I have reached the same algorithm as the one used in [Luis Masuelli's answer](https://codegolf.stackexchange.com/a/80303/47581).
[Answer]
# Perl, ~~37~~ 30 bytes
```
{$_=shift;s/\Q@_//g?$_:"$_@_"}
```
Regular expressions inside the toggle string are not evaluate because of the quoting with `\Q`...`\E`.
`sub F` and `\E` are removed according to the [comment](https://codegolf.stackexchange.com/questions/80243/toggle-a-string/80306?noredirect=1#comment197404_80306) by msh210.
It is not entirely free of side effects because of setting `$_`. Using a local variable will cost six additional bytes:
```
{my$a=shift;$a=~s/\Q@_//g?$a:"$a@_"}
```
On the other hand, with switched input parameters two bytes can be saved by using `pop` instead of `shift` (28 bytes):
```
{$_=pop;s/\Q@_//g?$_:"$_@_"}
```
Test file:
```
#!/usr/bin/env perl
sub F{$_=shift;s/\Q@_//g?$_:"$_@_"}
sub test ($$$) {
  my ($m, $t, $r) = @_;
  my $result = F($m, $t);
  print "F('$m', '$t') -> '$result' ",
    ($result eq $r ? '=OK=' : '<ERROR>'), " '$r'\n";
}
test '', 'a', 'a';
test 'a', 'a', '';
test 'b', 'a', 'ba';
test 'ab', 'a', 'b';
test 'aba', 'a', 'b';
test 'ababa', 'aba', 'ba';
test 'ababa', 'a*', 'ababaa*';
test 'foobar', '.', 'foobar.';
__END__
```
Test result:
```
F('', 'a') -> 'a' =OK= 'a'
F('a', 'a') -> '' =OK= ''
F('b', 'a') -> 'ba' =OK= 'ba'
F('ab', 'a') -> 'b' =OK= 'b'
F('aba', 'a') -> 'b' =OK= 'b'
F('ababa', 'aba') -> 'ba' =OK= 'ba'
F('ababa', 'a*') -> 'ababaa*' =OK= 'ababaa*'
F('foobar', '.') -> 'foobar.' =OK= 'foobar.'
```
[Answer]
# C# (58 bytes)
`string F(string s,string t)=>s==(s=s.Replace(t,""))?s+t:s;`
It uses an inline assignment to shave a few bytes off
[Answer]
# bash + sed, 28 bytes
```
sed "s/$2//g;t;s/$/$2/"<<<$1
```
The script lives in a toggle-string.bash file, which we call with `bash toggle-string.bash mainstring togglestring`.
`s/$2//g` removes the toggle string from the main string
`t` jumps to the end if the previous substitution was successful (ie. the main string contained the toggle string)
`/$/$2/` adds the toggle string at the end (`$`), if we didn't jump to the end
bash is required for the herestring
[Answer]
# Julia, ~~33~~ 31 bytes
```
s|t=(r=replace(s,t,""))t^(s==r)
```
[Try it online!](http://julia.tryitonline.net/#code=c3x0PShyPXJlcGxhY2Uocyx0LCIiKSl0XihzPT1yKQoKcHJpbnRsbigidGhpcyBzdHJpbmcgaGFzIDYgd29yZHMgInwibm93IikKcHJpbnRsbigidGhpcyBzdHJpbmcgaGFzIDUgd29yZHMgbm93InwiIG5vdyIpCnByaW50bG4oIiJ8ImEiKQpwcmludGxuKCJhInwiYSIpCnByaW50bG4oImIifCJhIikKcHJpbnRsbigiYWIifCJhIikKcHJpbnRsbigiYWJhInwiYSIpCnByaW50bG4oImFiYWJhInwiYWJhIik&input=)
[Answer]
## PowerShell v2+, 47 bytes
```
param($a,$b)(($c=$a-replace$b),"$a$b")[$c-eq$a]
```
Takes input `$a,$b` and then uses a pseudo-ternary `(... , ...)[...]` statement to perform an if/else. The inner parts are evaluated first to form an array of two elements. The 0th is `$a` with all occurrences of `$b` `-replace`d with nothing, which is stored into `$c`. The 1st is just a string concatenation of `$a` and `$b`.
If `$c` is `-eq`ual to `$a`, meaning that `$b` wasn't found, that's Boolean `$true` or `1`, and so the 1st element of the array (the concatenation) is chosen. Else, it's Boolean `$false`, so we output `$c`, the 0th element.
Note that `-replace` is greedy, so it will replace from the left first, meaning the `ababa / aba` test case will properly return `ba`.
[Answer]
# Java 8, 65 bytes
```
BinaryOperator<String>l=(m,t)->m.contains(t)?m.replace(t,""):m+t;
```
The same logic as the Java 7 solution, written with a lambda.
[Try it here](http://ideone.com/v5Uh0G)
[Answer]
# Mathematica, 45 bytes
```
If[StringContainsQ@##,StringDelete@##,#<>#2]&
```
Anonymous function that takes the main string and the toggle string (in that order) and returns the result. Explanation:
```
                                            &  Anonymous function returning...
If[StringContainsQ@##,               ,     ]    if its first argument contains
                                                its second argument, then...
                      StringDelete@##            its first argument with its
                                                 second argument removed, else...
                                      #<>#2      its second argument appended to
                                                 its first argument.
```
[Answer]
**TSQL, 143 129 121 Bytes**
```
DECLARE @1 VARCHAR(10)='',@2 VARCHAR(10)='a'SELECT CASE WHEN @1 LIKE'%'+@2+'%'THEN REPLACE(@1,@2,'')ELSE CONCAT(@1,@2)END
```
Readable:
```
   DECLARE @1 VARCHAR(10) = ''
    , @2 VARCHAR(10) = 'a'
SELECT CASE WHEN @1 LIKE '%' + @2 + '%'
            THEN REPLACE(@1, @2, '')
            ELSE CONCAT (@1, @2)
            END
```
`**[`Live Demo`](https://data.stackexchange.com/stackoverflow/query/edit/488831)**`
**114 Bytes** with strictly 1 character input
```
DECLARE @1 CHAR(1) = 'a'
    , @2 CHAR(1) = '.'
SELECT CASE WHEN @1 LIKE '%' + @2 + '%'
            THEN REPLACE(@1, @2, '')
            ELSE CONCAT (@1, @2) END
```
[Answer]
# TSQL(Sqlserver 2012), 49 bytes
```
DECLARE @ VARCHAR(10) = 'hello',@x VARCHAR(10) = 'o'
PRINT IIF(@ LIKE'%'+@x+'%',REPLACE(@,@x,''),@+@x)
```
[Try it online!](https://data.stackexchange.com/stackoverflow/query/488976/toggle-a-string)
[Answer]
# k (23 bytes)
```
{$[#x ss y;,/y\:x;x,y]}
```
Examples:
```
k){$[#x ss y;,/y\:x;x,y]}["aba";"a"]
,"b"
k){$[#x ss y;,/y\:x;x,y]}["this string has 6 words ";"now"]
"this string has 6 words now"
k){$[#x ss y;,/y\:x;x,y]}["this string has 5 words now";"now"]
"this string has 5 words "
k){$[#x ss y;,/y\:x;x,y]}["ababa";"ba"]
,"a"
k){$[#x ss y;,/y\:x;x,y]}["";"a"]
,"a"
```
[Answer]
## Kotlin, 61 Bytes
```
{m:String,t:String->var n=m.replace(t,"");if(m==n)m+t else n}
```
This is would be shorter if assignment was an expression in Kotlin,and parameters were mutable,and there was a ternary conditional operator, sadly this isn't the case :(
[Try it Online!](http://try.kotlinlang.org/#/UserProjects/imoa5gjbnol7adr9n38tqja56a/q2a6ai0gv7gqjialn6rkrpo2bg)
### UnGolfed
```
fun t(m:String, t:String):String{
    var n=m.replace(t, "")
    return if(m==n)m+t else n
}
```
]


[Question]
      []


[Question]
      [
In the C programming language, arrays are defined like this:
```
int foo[] = {4, 8, 15, 16, 23, 42};      //Foo implicitly has a size of 6
```
The size of the array is inferred from the initializing elements, which in this case is 6. You can also write a C array this way, explicitly sizing it then defining each element in order:
```
int foo[6];        //Give the array an explicit size of 6
foo[0] = 4;
foo[1] = 8;
foo[2] = 15;
foo[3] = 16;
foo[4] = 23;
foo[5] = 42;
```
# The challenge
You must write a program or function that expands arrays from the first way to the second. Since you are writing a program to make code longer, and you love irony, you must make your code as short as possible.
The input will be a string representing the original array, and the output will be the expanded array-definition. You can safely assume that the input will always look like this:
```
<type> <array_name>[] = {<int>, <int>, <int> ... };
```
"Type" and "array\_name" will made up entirely of alphabet characters and underscores `_`. The elements of the list will always be a number in the range -2,147,483,648 to 2,147,483,647. Inputs in any other format do not need to be handled.
The whitespace in your output must exactly match the whitespace in the test output, although a trailing newline is allowed.
# Test IO:
```
#in
short array[] = {4, 3, 2, 1};
#out
short array[4];
array[0] = 4;
array[1] = 3;
array[2] = 2;
array[3] = 1;
#in
spam EGGS[] = {42};
#out
spam EGGS[1];
EGGS[0] = 42;
#in
terrible_long_type_name awful_array_name[] = {7, -8, 1337, 0, 13};
#out
terrible_long_type_name awful_array_name[5];
awful_array_name[0] = 7;
awful_array_name[1] = -8;
awful_array_name[2] = 1337;
awful_array_name[3] = 0;
awful_array_name[4] = 13;
```
Submissions in any language are encouraged, but bonus points if you can do it *in* C.
# Leaderboard:
Here is a leaderboard showing the top answers:
```
var QUESTION_ID=77857,OVERRIDE_USER=31716;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```
```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```

[Answer]
# Vim, ~~54, 52, 49~~ 47 keystrokes
---
```
2wa0<esc>qqYp<c-a>6ldf @qq@q$dT]dd:%norm dwf{xwC;<CR>gg"0P
```
Explanation:
```
2wa0<esc>                     'Move 2 words forward, and insert a 0.
         qq                   'Start recording in register Q
           Yp                 'Duplicate the line
             <c-a>6l          'Increment the next number then move 6 spaces right
                    df        'Delete until the next space
                       @qq@q  'Recursively call this macro
```
Now our buffer looks like this:
```
int foo[0] = {4, 8, 15, 16, 23, 42};
int foo[1] = {8, 15, 16, 23, 42};
int foo[2] = {15, 16, 23, 42};
int foo[3] = {16, 23, 42};
int foo[4] = {23, 42};
int foo[5] = {42};
int foo[6] = {42};
```
and our cursor is on the last line.
Second half:
```
$                           'Move to the end of the line
 dT]                        'Delete back until we hit a ']'
    dd                      'Delete this whole line.
      :%norm         <CR>   'Apply the following keystrokes to every line:
             dw             'Delete a word (in this case "int")
               f{x          '(f)ind the next '{', then delete it.
                  wC;       'Move a word, then (C)hange to the end of this line,
                            'and enter a ';'

```
Now everything looks good, we just need to add the original array-declaration. So we do:
```
gg        'Move to line one
  "0P     'Print buffer '0' behind us. Buffer '0' always holds the last deleted line,
          'Which in this case is "int foo[6];"
```
[Answer]
# Pyth, 44 bytes
```
++Khcz\]lJ:z"-?\d+"1"];"VJs[ecKd~hZ"] = "N\;
```
[Test suite](https://pyth.herokuapp.com/?code=%2B%2BKhcz%5C%5DlJ%3Az%22-%3F%5Cd%2B%221%22%5D%3B%22VJs%5BecKd~hZ%22%5D+%3D+%22N%5C%3B&input=int+foo%5B%5D+%3D+%7B4%2C+8%2C+15%2C+16%2C+23%2C+42%7D%3B&test_suite=1&test_suite_input=int+foo%5B%5D+%3D+%7B4%2C+8%2C+15%2C+16%2C+23%2C+42%7D%3B%0Ashort+array%5B%5D+%3D+%7B4%2C+3%2C+2%2C+1%7D%3B%0Aspam+EGGS%5B%5D+%3D+%7B42%7D%3B%0Aterrible_long_type_name+awful_array_name%5B%5D+%3D+%7B7%2C+-8%2C+1337%2C+0%2C+13%7D%3B&debug=0)
Regular expression and string chopping. Not particularly clever.
Explanation:
```
++Khcz\]lJ:z"-?\d+"1"];"VJs[ecKd~hZ"] = "N\;
                                                Implicit: z = input()
    cz\]                                        Chop z on ']'
   h                                            Take string before the ']'
  K                                             Store it in K
 +                                              Add to that
         :z"-?\d+"1                             Find all numbers in the input
        J                                       Store them in J
       l                                        Take its length.
+                  "];"                         Add on "];" and print.
                       VJ                       For N in J:
                         s[                     Print the following, concatenated:
                            cKd                 Chop K on spaces.
                           e                    Take the last piece (array name)
                               ~hZ              The current interation number
                                  "] = "        That string
                                        N       The number from the input
                                         \;     And the trailing semicolon.
```
[Answer]
# Retina, ~~108~~ ~~104~~ ~~100~~ 69 bytes
Byte count assumes ISO 8859-1 encoding.
```
].+{((\S+ ?)+)
$#2];$1
+`((\w+\[).+;(\S+ )*)(-?\d+).+
$1¶$2$#3] = $4;
```
Beat this, PowerShell...
## Code explanation
**First line:** `].+{((\S+ ?)+)`
First, we need to keep the type, array name, and opening bracket (it saves a byte), so we don't match them. So we match the closing bracket, any number of characters, and an opening curly brace: `].+{`. Then we match the number list. Shortest I've been able to find so far is this: `((\S+ ?)+)`. We match any number of non-space characters (this includes numbers, possible negative sign, and possible comma), followed by a space, that may or may not be there: `\S+ ?`. This group of characters is then repeated as many times as needed: `(\S+ ?)+` and put into the large capturing group. Note that we don't match the closing curly brace or semicolon. Third line explanation tells why.
**Second line:** `$#2];$1`
Since we only matched a part of input, the unmatched parts will still be there. So we put the length of the list after the unmatched opening bracket: `$#2`. The replace modifier `#` helps us with that, as it gives us the number of matches a particular capturing group made. In this case capturing group `2`. Then we put a closing bracket and a semicolon, and finally our whole list.
With input `short array[] = {4, 3, 2, 1};`, the internal representation after this replacing is:
```
short array[4];4, 3, 2, 1};
```
(note the closing curly brace and semicolon)
**Third line:** `+`((\w+[).+;(\S+ )*)(-?\d+).+`
This is a looped section. That means it runs until no stage in the loop makes a change to the input. First we match the array name, followed by an opening bracket: `(\w+\[)`. Then an arbitrary number of any characters and a semicolon: `.+;`. Then we match the list again, but this time only numbers and the comma after each number, which have a space following them: `(\S+ )*`. Then we capture the last number in the list: `(-?\d+)` and any remaining characters behind it: `.+`.
**Fourth line:** `$1¶$2$#3] = $4;`
We then replace it with the array name and list followed by a newline: `$1¶`. Next, we put the array name, followed by the length of previously matched list, without the last element (essentially `list.length - 1`): `$2$#3`. Followed by a closing bracket and assigment operator with spaces, and this followed by the last element of our number list: `] = $4;`
After first replacing, the internal representation looks like this:
```
short array[4];4, 3, 2,
array[3] = 1;
```
Note that the closing curly brace and the semicolon disappeared, thanks to the `.+` at the end of third line.
After three more replacings, the internal representation looks like this:
```
short array[4];
array[0] = 4;
array[1] = 3;
array[2] = 2;
array[3] = 1;
```
Since there's nothing more to match by third line, fourth doesn't replace anything and the string is returned.
**TL;DR:** First we change up the int list format a bit. Then we take the last element of the list and the name, and put them after the array initialization. We do this until the int list is empty. Then we give the changed code back.
[Try it online!](http://retina.tryitonline.net/#code=XS4reygoXFMrID8pKykKJCMyXTskMQorYCgoXHcrXFspLis7KFxTKyApKikoLT9cZCspLisKJDHCtiQyJCMzXSA9ICQ0Ow&input=dGVycmlibGVfbG9uZ190eXBlX25hbWUgYXdmdWxfYXJyYXlfbmFtZVtdID0gezcsIC04LCAxMzM3LCAwLCAxM307)
[Answer]
# C, 215 bytes, 196 bytes
*19 bytes saved thanks to @tucuxi!*
**Golfed:**
```
char i[99],o[999],b[99],z[99];t,x,n,c;main(){gets(i);sscanf(i,"%s %[^[]s",b,z);while(sscanf(i+t,"%*[^0-9]%d%n",&x,&n)==1)sprintf(o,"%s[%d] = %d;\n",z,c++,x),t+=n;printf("%s %s[%d];\n%s",b,z,c,o);}
```
**Ungolfed:**
```
/*
 *  Global strings:
 *   i: input string
 *   o: output string
 *   b: input array type
 *   z: input array name
*/
char i[ 99 ], o[ 999 ], b[ 99 ], z[ 99 ];
/* Global ints initialized to zeros */
t, x, n, c;
main()
{
    /* Grab input string from stdin, store into i */
    gets( i );
    /* Grab the <type> <array_name> and store into b and z */
    sscanf( i, "%s %[^[]s", b, z );
    /* Grab only the int values and concatenate to output string */
    while( sscanf( i + t, "%*[^0-9]%d%n", &x, &n ) == 1 )
    {
        /* Format the string and store into a */
        sprintf( o, "%s[%d] = %d;\n", z, c++, x );
        /* Get the current location of the pointer */
        t += n;
    }
    /* Print the <type> <array_name>[<size>]; and output string */
    printf( "%s %s[%d];\n%s", b, z, c, o );
}
```
**Link:**
<http://ideone.com/h81XbI>
**Explanation:**
To get the `<type> <array_name>`, the `sscanf()` format string is this:
```
%s          A string delimited by a space
    %[^[]   The character set that contains anything but a `[` symbol
         s  A string of that character set
```
To extract the int values from the string `int foo[] = {4, 8, 15, 16, 23, 42};`, I essentially tokenize the string with this function:
```
while( sscanf( i + t, "%*[^0-9]%d%n", &x, &n ) == 1 )
```
where:
* `i` is the input string (a `char*`)
* `t` is the pointer location offset of `i`
* `x` is the actual `int` parsed from the string
* `n` is the total characters consumed, including the found digit
The `sscanf()` format string means this:
```
%*            Ignore the following, which is..
  [^0-9]      ..anything that isn't a digit
        %d    Read and store the digit found
          %n  Store the number of characters consumed
```
If you visualize the input string as a char array:
```
int foo[] = {4, 8, 15, 16, 23, 42};
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
00000000001111111111222222222233333
01234567890123456789012345678901234
```
with the `int` `4` being located at index 13, `8` at index 16, and so on, this is what the result of each run in the loop looks like:
```
Run 1)  String: "int foo[] = {4, 8, 15, 16, 23, 42};"
        Starting string pointer: str[ 0 ]
        Num chars consumed until after found digit: 14
        Digit that was found: 4
        Ending string pointer: str[ 14 ]
Run 2)  String: ", 8, 15, 16, 23, 42};"
        Starting string pointer: str[ 14 ]
        Num chars consumed until after found digit: 3
        Digit that was found: 8
        Ending string pointer: str[ 17 ]
Run 3)  String: ", 15, 16, 23, 42};"
        Starting string pointer: str[ 17 ]
        Num chars consumed until after found digit: 4
        Digit that was found: 15
        Ending string pointer: str[ 21 ]
Run 4)  String: ", 16, 23, 42};"
        Starting string pointer: str[ 21 ]
        Num chars consumed until after found digit: 4
        Digit that was found: 16
        Ending string pointer: str[ 25 ]
Run 5)  String: ", 23, 42};"
        Starting string pointer: str[ 25 ]
        Num chars consumed until after found digit: 4
        Digit that was found: 23
        Ending string pointer: str[ 29 ]
Run 6)  String: ", 42};"
        Starting string pointer: str[ 29 ]
        Num chars consumed until after found digit: 4
        Digit that was found: 42
        Ending string pointer: str[ 33 ]
```
[Answer]
# V, 37 Bytes
```
2Eé0òYp6ldf ò$dT]ddÎdwf{xwC;
gg"1P
```
V is a 2D, string based golfing language that I wrote, designed off of vim. This works as of [commit 17](https://github.com/DJMcMayhem/V/commit/3e52ff77850f2d7897167eb9a20a859ca0169968).
Explanation:
This is pretty much a direct translation of [my vim answer](https://codegolf.stackexchange.com/a/77862/31716), albeit significantly shorter.
```
2E                               "Move to the end of 2 words forward.
  é0                             "Insert a single '0'
    ò       ò                    "Recursively do:
     Yp6ldf                      "Yank, paste, move 6 right, delete until space.
             $dT]                "Move to the end of line, delete backwards until ']'
                 dd              "Delete this line
                   Î             "Apply the following to every line:
                    dwf{xwC;<\n> "Delete word, move to '{' and delete it, Change to end of line, and enter ';'
```
Then we just have:
```
gg"1P     "Move to line 1, and paste buffer '1' behind us.
```
Since this unicode madness can be hard to enter, you can create the file with this reversible hexdump:
```
00000000: 3245 e930 f259 7001 366c 6466 20f2 2464  2E.0.Yp.6ldf .$d
00000010: 545d 6464 ce64 7766 7b78 7743 3b0d 6767  T]dd.dwf{xwC;.gg
00000020: 2231 500a                                "1P.
```
This can be run by installing V and typing:
```
python main.py c_array.v --f=file_with_original_text.txt
```
[Answer]
# C, ~~195~~ 180 bytes
195-byte original:
golfed:
```
char*a,*b,*c,*d;j;main(i){scanf("%ms %m[^]]%m[^;]",&a,&b,&c);
for(d=c;*d++;i+=*d==44);printf("%s %s%d];\n",a,b,i);
for(d=strtok(c,"] =,{}");j<i;j++,d=strtok(0," ,}"))printf("%s%d] = %s;\n",b,j,d);}
```
ungolfed:
```
char*a,*b,*c,*d;
j;
main(i){
    scanf("%ms %m[^]]%m[^;]",&a,&b,&c); // m-modifier does its own mallocs
    for(d=c;*d++;i+=*d==44);            // count commas
    printf("%s %s%d];\n",a,b,i);        // first line
    for(d=strtok(c,"] =,{}");j<i;j++,d=strtok(0," ,}"))
        printf("%s%d] = %s;\n",b,j,d);  // each array value
}
```
The two shortcuts are using the `m` modifier to to get scanf's `%s` to allocate its own memory (saves declaring char arrays), and using `strtok` (which is also available by default, without includes) to do the number-parsing part.
---
180-byte update:
```
char*a,*b,*c,e[999];i;main(){scanf("%ms %m[^]]%m[^}]",&a,&b,&c);
for(c=strtok(c,"] =,{}");sprintf(e,"%s%s%d] = %s;\n",e,b,i++,c),
c=strtok(0," ,"););printf("%s %s%d];\n%s",a,b,i,e);}
```
ungolfed:
```
char*a,*b,*c,e[999];
i;
main(){
    scanf("%ms %m[^]]%m[^}]",&a,&b,&c);
    for(c=strtok(c,"] =,{}");sprintf(e,"%s%s%d] = %s;\n",e,b,i++,c),c=strtok(0," ,"););
    printf("%s %s%d];\n%s",a,b,i,e);
}
```
Uses [bnf679's](https://codegolf.stackexchange.com/a/77983/41288) idea of appending to a string to avoid having to count commas.
[Answer]
## Python 3.6 (pre-release), 133
```
m,p=str.split,print;y,u=m(input(),'[');t,n=m(y);i=m(u[5:-2],', ')
l=len(i);p(t,n+f'[{l}];')
for x in range(l):p(n+f'[{x}] = {i[x]};')
```
Makes heavy use of [f-strings](https://www.python.org/dev/peps/pep-0498/).
Ungolfed version:
```
y, u = input().split('[')
t, n = y.split()
i = u[5:-2].split(', ')
l = len(i)
print(t, n + f'[{l}];')
for x in range(l):
    print(n + f'[{x}] = {i[x]};')
```
[Answer]
# Ruby, ~~127~~ ~~110~~ ~~108~~ ~~99~~ 88 bytes
~~Anonymous function with a single argument as input.~~ Full program, reads the input from STDIN. (If you pipe a file in, the trailing newline is optional.) ~~Returns~~ Prints the output string.
Took @TimmyD bragging about their solution beating all other non-esolangs as a challenge, and finally overcome the (at the time of writing) 114 byte Powershell solution they had posted. ~~Cᴏɴᴏʀ O'Bʀɪᴇɴ's trick with splitting on `]` and splicing the second half to get the numbers helped.~~
I need to use the splat operator more. It's so useful!
Borrowed a trick from @Neil's JavaScript ES6 answer to save more bytes by scanning for words instead of using `gsub` and `split`..
```
t,n,*l=gets.scan /-?\w+/;i=-1
puts t+" #{n}[#{l.size}];",l.map{|e|n+"[#{i+=1}] = #{e};"}
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), ~~52~~ ~~50~~ 47 bytes
Code:
```
… = ¡`¦¨¨ð-',¡©gr¨s«„];«,®v¹ð¡¦¬s\¨N"] = "y';J,
```
Uses **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=4oCmID0gwqFgwqbCqMKow7AtJyzCocKpZ3LCqHPCq-KAnl07wqsswq52wrnDsMKhwqbCrHNcwqhOIl0gPSAieSc7Siw&input=aW50IGZvb1tdID0gezQsIDgsIDE1LCAxNiwgMjMsIDQyfTs).
[Answer]
## JavaScript (ES6), 100 bytes
```
(s,[t,n,...m]=s.match(/-?\w+/g))=>t+` ${n}[${m.length}];`+m.map((v,i)=>`
${n}[${i}] = ${v};`).join``
```
Since only the words are important, this works by just matching all the words in the original string, plus leading minus signs, then building the result. (I originally thought I was going to use `replace` but that turned out to be a red herring.)
[Answer]
# Pyth - ~~53~~ ~~50~~ ~~46~~ ~~45~~ 44 bytes
*2 bytes saved thanks to @FryAmTheEggman.*
```
+Jhcz\[+`]lKcPecz\{d\;j.es[ecJd`]kd\=dPb\;)K
```
[Test Suite](http://pyth.herokuapp.com/?code=%2BJhcz%5C%5B%2B%60%5DlKcPecz%5C%7Bd%5C%3Bj.es%5BecJd%60%5Dkd%5C%3DdPb%5C%3B%29K&input=int+foo%5B%5D+%3D+%7B4%2C+8%2C+15%2C+16%2C+23%2C+42%7D%3B&test_suite=1&test_suite_input=int+foo%5B%5D+%3D+%7B4%2C+8%2C+15%2C+16%2C+23%2C+42%7D%3B%0Ashort+array%5B%5D+%3D+%7B4%2C+3%2C+2%2C+1%7D%3B%0Aspam+EGGS%5B%5D+%3D+%7B42%7D%3B%0Aterrible_long_type_name+awful_array_name%5B%5D+%3D+%7B7%2C+-8%2C+1337%2C+0%2C+13%7D%3B&debug=0).
[Answer]
# [Pip](https://github.com/dloscutoff/pip), ~~48~~ 47 bytes
```
qR`(\S+)(. = ).(.+)}`{[b#Yd^k']';.n.b.,#y.c.y]}
```
Takes input from stdin and prints to stdout.
### Explanation
**Tl;dr:** Does a regex replacement, using capture groups and a callback function to construct the result.
The `q` special variable reads a line of input. The regex is `(\S+)(. = ).(.+)}`, which matches everything except the type (including trailing space) and the final semicolon. Using the first example from the question, the capturing groups get `foo[`, `] =` , and `4, 8, 15, 16, 23, 42`.
The replacement is the return value of the unnamed function `{[b#Yd^k']';.n.b.,#y.c.y]}`, which is called with the whole match plus the capturing groups as arguments. Thus, within the function, `b` gets capture group 1, `c` gets group 2, and `d` gets group 3.
We construct a list, the first three items of which will be `"foo["`, `6`, and `"]"`. To get the `6`, we split `d` on the built-in variable `k` = `", "`, `Y`ank the resulting list of integers into the `y` variable for future use, and take the length (`#`). `']` is a character literal.
What remains is to construct a series of strings of the form `";\nfoo[i] = x"`. To do so, we concatenate the following: `';`, `n` (a built-in for newline), `b` (1st capture group), `,#y` (equivalent to Python `range(len(y))`), `c` (2nd capture group), and `y`. Concatenation works itemwise on lists and ranges, so the result is a list of strings. Putting it all together, the return value of the function will be a list such as this:
```
["foo[" 6 "]"
 [";" n "foo[" 0 "] = " 4]
 [";" n "foo[" 1 "] = " 8]
 [";" n "foo[" 2 "] = " 15]
 [";" n "foo[" 3 "] = " 16]
 [";" n "foo[" 4 "] = " 23]
 [";" n "foo[" 5 "] = " 42]
]
```
Since this list is being used in a string `R`eplacement, it is implicitly cast to a string. The default list-to-string conversion in Pip is concatenating all the elements:
```
"foo[6];
foo[0] = 4;
foo[1] = 5;
foo[2] = 15;
foo[3] = 16;
foo[4] = 23;
foo[5] = 42"
```
Finally, the result (including the type and the final semicolon, which weren't matched by the regex and thus remain unchanged) is auto-printed.
[Answer]
## Perl 5.10, 73 72 68 66 + 1 (for -n switch) = 67 bytes
```
perl -nE '($t,$n,@a)=/[-[\w]+/g;say"$t $n".@a."];";say$n,$i++,"] = $_;"for@a'
```
This is a nice challenge for Perl and the shortest among general-purpose languages so far. Equivalent to
```
($t, $n, @a) = /[-[\w]+/g;
say "$t $n" . @a . "];";
say $n, $i++, "] = $_;" for @a;
```
[Answer]
## PowerShell v2+, ~~114~~ 105 bytes
```
$a,$b,$c,$d=-split$args-replace'\[]';"$a $b[$(($d=-join$d|iex|iex).length)];";$d|%{"$b[$(($i++))] = $_;"}
```
Takes input string `$args` and `-replace`s the square bracket with nothing, then performs a `-split` on whitespace. We store the first bit into `$a`, the second bit into `$b`, the `=` into `$c`, and the array elements into `$d`. For the example below, this stores `foo` into `$a` and `bar` into `$b`, and all of the array into `$d`.
We then output our first line with `"$a ..."` and in the middle transform `$d` from a an array of strings of form `{1,`,`2,`,...`100};` to a regular int array by `-join`ing it together into one string, then running it through `iex` twice (similar to `eval`). We store that resultant array back in `$d` before calling the `.length` method to populate the appropriate number in between the `[]` in the output line.
We then send `$d` through a loop with `|%{...}`. Each iteration we output `"$b..."` with a counter variable `$i` encapsulated in brackets and the current value `$_`. The `$i` variable starts uninitialized (equivalent to `$null`) but the `++` will cast it to an `int` before the output, so it will start output at `0`, all before incrementing `$i` for the next loop iteration.
All output lines are left on the pipeline, and output to the terminal is implicit at program termination.
### Example
```
PS C:\Tools\Scripts\golfing> .\expand-a-c-array.ps1 "foo bar[] = {1, 2, 3, -99, 100};"
foo bar[5];
bar[0] = 1;
bar[1] = 2;
bar[2] = 3;
bar[3] = -99;
bar[4] = 100;
```
[Answer]
## C,~~278~~ 280 bytes
golfed:
```
x,e,l,d;char *m,*r,*a;char i[999];c(x){return isdigit(x)||x==45;}main(){gets(i);m=r=&i;while(*r++!=32);a=r;while(*++r!=93);l=r-a;d=r-m;for(;*r++;*r==44?e++:1);printf("%.*s%d];\n",d,m,e+1);r=&i;while(*r++){if(c(*r)){m=r;while(c(*++r));printf("%.*s%d] = %.*s;\n",l,a,x++,r-m,m);}}}
```
ungolfed:
```
/* global ints
 * x = generic counter
 * e = number of elements
 * l = length of the array type
 * d = array defination upto the first '['
 */
x,e,l,d;
/* global pointers
 * m = memory pointer
 * r = memory reference / index
 * a = pointer to the start of the array type string
 */
char *m,*r,*a;
/* data storage for stdin */
char i[999];
c(x){return isdigit(x)||x=='-';}
main(){
    gets(i);
    m=r=&i;
    while(*r++!=32);                // skip first space
    a=r;
    while(*++r!=93);                // skip to ']'
    l=r-a;
    d=r-m;
    for(;*r++;*r==44?e++:1);        // count elements
    printf("%.*s%d];\n",d,m,e+1);   // print array define
    r=&i;
    while(*r++) {                   // print elements
        if(c(*r)) {                 // is char a - or a digit?
            m=r;
            while(c(*++r));         // count -/digit chars
            printf("%.*s%d] = %.*s;\n",l,a,x++,r-m,m);
        }
    }
}
```
While working on this someones posted a shorter version using sscanf for the parsing rather than using data pointers... nice one!
UPDATE:
Spotted missing spaces around the equals in the element printing, IDE online link: <http://ideone.com/KrgRt0> . Note this implementation does support negative numbers...
[Answer]
# Awk, 101 bytes
```
{FS="[^[:alnum:]_-]+";printf"%s %s[%d];\n",$1,$2,NF-3;for(i=3;i<NF;i++)printf$2"[%d] = %d;\n",i-3,$i}
```
More readably:
```
{
FS="[^[:alnum:]_-]+"
printf "%s %s[%d];\n", $1, $2, NF - 3
for (i=3; i < NF; i++)
    printf $2"[%d] = %d;\n", i-3, $i
}
```
* I set the field separator to everything except alphabets, digits, the underscore and `-`. So, the fields would be the type name, the variable name, and the numbers.
* The number of fields will be 1 (for the type) + 1 (for the name) + N (numbers) + 1 (an empty field after the trailing `};`). So, the size of the array is `NF - 3`.
* Then it's just printing a special line for the declaration, and looping over the numbers.
* I *should* assign `FS` either when invoking awk (using `-F`) or in a `BEGIN` block. In the interests of brevity, ….
[Answer]
# JavaScript ES6, ~~134~~ ~~132~~ ~~130~~ 129 bytes
Saved 1 byte thanks to Neil.
```
x=>(m=x.match(/(\w+) (\w+).+{(.+)}/),m[1]+` `+(q=m[2])+`[${q.length-1}];
`+m[3].split`, `.map((t,i)=>q+`[${i}] = ${t};`).join`
`)
```
[Answer]
## bash, ~~133~~ 129 bytes
```
read -a l
d="${l[@]:0:2}"
e=("${l[@]:3}")
echo "${d%?}${#e[@]}];"
for i in "${!e[@]}"
{
echo "${l[0]}[$i] = ${e[$i]//[!0-9]/};"
}
```
First attempt, sure its posible to get it shorter.
[Answer]
# D, 197, 188 bytes
```
import std.array,std.stdio;void main(){string t,n,e;readf("%s %s] = {%s}",&t,&n,&e);auto v=e.replace(",","").split;writeln(t,' ',n,v.length,"];");foreach(i,c;v)writeln(n,i,"] = ",c,";");}
```
or ungolfed:
```
import std.array, std.stdio;
void main() {
    string type, nameAndBracket, elems;
    readf("%s %s] = {%s}", &type, &nameAndBracket, &elems);
    // remove all commas before splitting the string into substrings
    auto vector = elems.replace(",","").split();
    // writeln is shorter than fln by 1 char when filled in
    writeln(type, ' ', nameAndBracket, vector.length, "];");
    // print each element being assigned
    foreach(index, content; vector)
        writeln(nameAndBraket, index, "] = ", content, ";");
}
```
[Answer]
# Julia, ~~154~~ ~~134~~ 101 bytes
```
f(s,c=matchall(r"-?\w+",s),n=endof(c)-2)=c[]" "c[2]"[$n];
"join([c[2]"[$i] = "c[i+3]";
"for i=0:n-1])
```
This is a function that accepts a string and returns a string with a single trailing newline.
Ungolfed:
```
function f(s, c = matchall(r"-?\w+", s), n = endof(c) - 2)
    c[] " " c[2] "[$n];\n" join([c[2] "[$i] = " x[i+3] ";\n" for i = 0:n-1])
end
```
We define `c` to be an array of matches of the input on the regular expression `-?\w+`. It caputres the type, array name, then each value. We store `n` as the length of `c` - 2, which is the number of values. The output is constructed as the type, name and length string interpolated, combined with each definition line separated by newlines. For whatever reason, `c[]` is the same as `c[1]`.
Saved 32 bytes with help from Dennis!
[Answer]
## Python 2, 159 bytes
```
s=input().split()
t,n,v=s[0],s[1][:-2],''.join(s[3:])
a=v[1:-2].split(',')
print'%s %s[%d];'%(t,n,len(a))
for i in range(len(a)):print'%s[%d] = %s;'%(n,i,a[i])
```
[Try it online](http://ideone.com/fork/mm2tbz)
Thanks Kevin Lau for some golfing suggestions
[Answer]
## Python 3, 116 bytes
```
t,v,_,*l=input().split();v=v[:-1]+'%s]'
print(t,v%len(l)+';');i=0
for x in l:print(v%i,'= %s;'%x.strip('{,};'));i+=1
```
Splits the input into the type, name, and the list of numbers. After printing the array declaring, prints the elements by manually enumerating through the numbers, removing excess punctuation that attached to the first and last one.
A different approach in Python 2 came out to 122 bytes:
```
a,b=input()[:-2].split('] = {')
l=eval(b+',')
print a+`len(l)`+"];"
for y in enumerate(l):print a.split()[1]+'%s] = %s;'%y
```
The idea is to `eval` the list of numbers as a tuple, with a comma at the end so that a single number is recognized as a type. The enumerated list of numbers provides tuples to string-format in.
[Answer]
## PHP, 143 bytes
**Golfed**
```
<?$t=count($n=explode(' ',preg_replace('/[^\s\w]/','',$argv[1])))-3;echo"$n[0] {$n[1]}[$t];";for($i=2;$t>$j=++$i-3;)echo$n[1]."[$j] = $n[$i];";
```
**Ungolfed**
```
<?
$t = count(                                  // Get the number of elements for our array...
    $n = explode(' ',                            // After split the input on whitespace...
    preg_replace('/[^\s\w]/','',$argv[1])))-3;  // After removing all special characters.
echo "$n[0] {$n[1]}[$t];";                     // First line is type, name, and count.
for($i=2;                                        // Loop through array elements
    $t > $j = ++$i-3;)                         // Assign j to be the actual index for our new array
    echo $n[1]."[$j] = $n[$i];";                // Print each line
```
Input is taken through command line argument. Sample:
```
C:\(filepath)>php Expand.php "int foo[] = {4,8,15,16,23,42};"
```
Output:
```
int foo[6];foo[0] = 4;foo[1] = 8;foo[2] = 15;foo[3] = 16;foo[4] = 23;foo[5] = 42;
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~68~~ ~~64~~ 58 bytes
```
'\w+'XX2:H#)XKxXIZc'['KnV'];'v!K"I2X)'['X@qV'] = '@g';'6$h
```
This isn't C, ~~but it does use C-like `sprintf` function~~ Nah, that was wasting 4 bytes.
[**Try it online!**](http://matl.tryitonline.net/#code=J1x3KydYWDI6SCMpWEt4WElaYydbJ0tuViddOyd2IUsiSTJYKSdbJ1hAcVYnXSA9ICdAZyc7JzYkaA&input=J2ludCBmb29bXSA9IHs0LCA4LCAxNSwgMTYsIDIzLCA0Mn07Jw)
```
          % Take input implicitly
'\w+'XX   % Find substrings that match regex '\w+'. Gives a cell array
2:H#)     % Split into a subarray with the first two substrings (type and name), and
          % another with the rest (numbers that form the array)
XKx       % Copy the latter (numbers) into clipboard K. Delete it
XI        % Copy the former (type and name) into clipboard I
Zc        % Join the first two substrings with a space
'['       % Push this string
K         % Paste array of numbers
nV        % Get its length. Convert to string
'];'      % Push this string
v!        % Concatenate all strings up to now. Gives first line of the output
K"        % For each number in the array
  I2X)    %   Get name of array as a string
  '['     %   Push this string
  X@qV    %   Current iteration index, starting at 0, as a string
  '] = '  %   Push this string
  @g      %   Current number of the array, as a string
  ';'     %   Push this string
  5$h     %   Concatenate top 6 strings. This is a line of the output
          % Implicity end for each
          % Implicitly display
```
[Answer]
## Clojure, 115 bytes
```
#(let[[t n & v](re-seq #"-?\w+"%)](apply str t" "n\[(count v)"];\n"(map(fn[i v](str n"["i"] = "v";\n"))(range)v))))
```
I wasn't able to nicely merge `awful_array_name[5];` and `awful_array_name[0] = 7;` parts so that they'd re-use code :/
]


[Question]
      [
You are to approximate the value of:
$$\int^I\_0 \frac {e^x} {x^x} dx$$
Where your input is \$I\$.
# Rules
* You may not use any built-in integral functions.
* You may not use any built-in infinite summation functions.
* Your code must execute in a reasonable amount of time ( < 20 seconds on my machine)
* You may assume that input is greater than 0 but less than your language's upper limit.
* It may be any form of standard return/output.
You can verify your results at [Wolfram | Alpha](http://www.wolframalpha.com/input/?i=integrate+e%5Ex%2Fx%5Ex+from+0+to) (you can verify by concatenating your intended input to the linked query).
# Examples
(let's call the function `f`)
```
f(1) -> 2.18273
f(50) -> 6.39981
f(10000) -> 6.39981
f(2.71828) -> 5.58040
f(3.14159) -> 5.92228
```
Your answer should be accurate to `±.0001`.

[Answer]
# Julia, ~~79~~ ~~77~~ 38 bytes
```
I->sum(x->(e/x)^x,0:1e-5:min(I,9))/1e5
```
This is an anonymous function that accepts a numeric value and returns a float. To call it, assign it to a variable.
The approach here is to use a right Riemann sum to approximate the integral, which is given by the following formula:
$$\int\_a^b f(x) dx \approx \sum f(x) \Delta x$$
In our case, \$a = 0\$ and \$b = I\$, the input. We divide the region of integration into \$n = 10^5\$ discrete portions, so \$∆x = \frac 1 n = 10^{-5}\$. Since this is a constant relative to the sum, we can pull this outside of the sum and simply sum the function evaluations at each point and divide by \$n\$.
The function is surprisingly well-behaved (plot from Mathematica):
[![mathematicaplot](https://i.stack.imgur.com/RLKPH.png)](https://i.stack.imgur.com/RLKPH.png)
Since the function evaluates nearly to 0 for inputs greater than about 9, we truncate the input to be \$I\$ if \$I\$ is less than 9, or 9 otherwise. This simplifies the calculations we have to do significantly.
Ungolfed code:
```
function g(I)
    # Define the range over which to sum. We truncate the input
    # at 9 and subdivide the region into 1e5 pieces.
    range = 0:1e-5:min(I,9)
    # Evaluate the function at each of the 1e5 points, sum the
    # results, and divide by the number of points.
    return sum(x -> (e / x)^x, range) / 1e5
end
```
Saved 39 bytes thanks to Dennis!
[Answer]
# Jelly, ~~20~~ ~~19~~ 17 bytes
```
ð«9×R÷øȷ5µØe÷*×ḢS
```
This borrows the clever *truncate at 9* trick from [@AlexA.'s answer](https://codegolf.stackexchange.com/a/71314), and uses a [right Riemann sum](https://en.wikipedia.org/wiki/Riemann_sum#Right_Riemann_Sum) to estimate the corresponding integral.
Truncated test cases take a while, but are fast enough on [Try it online!](http://jelly.tryitonline.net/#code=w7DCqznDl1LDt8O4yLc1wrXDmGXDtyrDl-G4olM&input=&args=MTA&debug=on)
### How it works
```
ð«9×R÷øȷ5µØe÷*×ḢS  Main link. Input: I
      øȷ5          Niladic chain. Yields 1e5 = 100,000.
ð                  Dyadic chain. Left argument: I. Right argument: 1e5.
 «9                Compute min(I, 9).
   ×               Multiply the minimum with 1e5.
    R              Range; yield [1, 2, ..., min(I, 9) * 1e5] or [0] if I < 1e-5.
     ÷             Divide the range's items by 1e5.
                   This yields r := [1e-5, 2e-5, ... min(I, 9)] or [0] if I < 1e-5.
         µ         Monadic chain. Argument: r
          Øe÷      Divide e by each element of r.
             *     Elevate the resulting quotients to the corresponding elements,
                   mapping t -> (e/t) ** t over r.
                   For the special case of r = [0], this yields [1], since
                   (e/0) ** 0 = inf ** 0 = 1 in Jelly.
              ×Ḣ   Multiply each power by the first element of r, i.e., 1e-5 or 0.
                S  Add the resulting products.
```
[Answer]
## ES7, 78 bytes
```
i=>[...Array(n=2e3)].reduce(r=>r+Math.exp(j+=i)/j**j,0,i>9?i=9:0,i/=n,j=-i/2)*i
```
This uses the rectangle rule with 2000 rectangles, which (at least for the examples) seem to produce a sufficiently accurate answer, but the accuracy could easily be increased if necessary. It has to use the 9 trick otherwise the accuracy drops off for large values.
73 byte version that uses rectangles of width ~0.001 so it doesn't work above ~700 because Math.exp hits Infinity:
```
i=>[...Array(n=i*1e3|0)].reduce(r=>r+Math.exp(j+=i)/j**j,0,i/=n,j=-i/2)*i
```
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 26 bytes
```
9hX<t1e6XK:K/*ttZebb^/sK/*
```
This approximates the integral as a Riemann sum. As argued by Alex, we can truncate the integration interval at approximately 9 because the function values are very small beyond that.
The maximum value of the function is less than 3, so a step of about 1e-5 should be enough to obtain the desired accuracy. So for the maximum input 9 we need about 1e6 points.
This takes about 1.5 seconds in the online compiler, for any input value.
[**Try it online**!](http://matl.tryitonline.net/#code=OWhYPHQxZTZYSzpLLyp0dFplYmJeL3NLLyo&input=My4xNDE1OQ)
```
9hX<         % input number, and limit to 9
t            % duplicate
1e6XK:       % generate vector [1,2,...,1e6]. Copy 1e6 to clipboard K
K/*          % divide by 1e6 and multiply by truncated input. This gives
             % a vector with 1e6 values of x from 0 to truncated input
ttZe         % duplicate twice. Compute exp(x)
bb^          % rotate top three elements of stack twice. Compute x^x
/            % divide to compute exp(x)/x^x
s            % sum function values
K/*          % multiply by the step, which is the truncated input divided
             % by 1e6
```
[Answer]
# [golflua](http://mniip.com/misc/conv/golflua/), 83 chars
I'll admit it: it took my a while to figure out the `min(I,9)` trick Alex presented allowed computing arbitrarily high numbers because the integral converged by then.
```
\f(x)~M.e(x)/x^x$b=M.mn(I.r(),9)n=1e6t=b/n g=0.5+f(b/2)~@k=1,n-1g=g+f(k*t)$I.w(t*g)
```
An ungolfed Lua equivalent would be
```
function f(x)
   return math.exp(x)/x^x
end
b=math.min(io.read("*n"),9)
n=1e6
t=b/n
g=0.5+f(b/2)
for k=1,n-1 do
   g=g+f(k*t)
end
io.write(t*g)
```
[Answer]
# Python 2, ~~94~~ 76 bytes
Thanks to @Dennis for saving me 18 bytes!
```
lambda I,x=1e5:sum((2.71828/i*x)**(i/x)/x for i in range(1,int(min(I,9)*x)))
```
[Try it online with testcases!](https://repl.it/Bk6w/2)
Using the rectangle method for the approximation. Using a rectangle width of 0.0001 which gives me the demanded precision. Also truncating inputs greater 9 to prevent memory errors with very big inputs.
[Answer]
# Perl 6, ~~90~~ 55 bytes
```
{my \x=1e5;sum ((e/$_*x)**($_/x)/x for 1..min($_,9)*x)}
```
**usage**
```
my &f = {my \x=1e5;sum ((e/$_*x)**($_/x)/x for 1..min($_,9)*x)}
f(1).say;       # 2.1827350239231
f(50).say;      # 6.39979602775846
f(10000).say;   # 6.39979602775846
f(2.71828).say; # 5.58039854392816
f(3.14159).say; # 5.92227602782184
```
It's late and I need to sleep, I'll see if I can get this any shorter tomorrow.
EDIT: Managed to get it quite a bit shorter after seeing @DenkerAffe 's method.
[Answer]
# Pyth, ~~34~~ 29 bytes
Saved 5 Bytes with some help from @Dennis!
```
J^T5smcc^.n1d^ddJmcdJU*hS,Q9J
```
[Try it online!](http://pyth.herokuapp.com/?code=J%5ET5smcc%5E.n1d%5EddJmcdJU*hS%2CQ9J&input=1&test_suite_input=1%0A50%0A10000%0A2.71828%0A3.14159&debug=0)
### Explanation
Same algorithm as in [my Python answer](https://codegolf.stackexchange.com/a/71346/49110).
```
J^T5smcc^.n1d^ddJmcdJU*hS,Q9J        # Q=input
J^T5                                 # set J so rectangle width *10^5
                       hS,Q9         # truncate inputs greater 9
                 mcdJU/     J        # range from zero to Input in J steps
     mcc^.n1d^ddJ                    # calculate area for each element in the list
    s                                # Sum all areas and output result

```
[Answer]
# Vitsy, 39 bytes
Thought I might as well give my own contribution. ¯\\_(ツ)\_/¯ This uses the Left-Hand Riemann Sum estimation of integrals.
```
D9/([X9]1a5^D{/V}*0v1{\[EvV+DDv{/}^+]V*
D9/([X9]               Truncation trick from Alex A.'s answer.
D                      Duplicate input.
 9/                    Divide it by 9.
   ([  ]               If the result is greater than 0
     X9                Remove the top item of the stack, and push 9.
1a5^D{/V}*0v0{         Setting up for the summation.
1                      Push 1.
 a5^                   Push 100000.
    D                  Duplicate the top item of the stack.
     {                 Push the top item of the stack to the back.
      /                Divide the top two items of the stack. (1/100000)
       V               Save it as a global variable.
                       Our global variable is ∆x.
        }              Push the bottom item of the stack to the top.
         *             Multiply the top two items.
                       input*100000 is now on the stack.
          0v           Save 0 as a temporary variable.
            0          Push 1.
             {         Push the bottom item of the stack to the top.
                       input*100000 is now the top of the stack.
\[EvV+DDv{/}^+]        Summation.
\[            ]        Loop over this top item of the stack times.
                       input*100000 times, to be exact.
  E                    Push Math.E to the stack.
   v                   Push the temporary variable to the stack.
                       This is the current value of x.
    V+                 Add ∆x.
      DD               Duplicate twice.
        v              Save the temporary variable again.
         {             Push the top item of the stack to the back.
          /            Divide the top two items.
                       e/x
           }           Push the top item back to the top of the stack.
            ^          Put the second to top item of the stack to the power of the top item.
                       (e/x)^x
             +         Add that to the current sum.
V*                     Multiply by ∆x
```
This leaves the sum on the top of the stack. The try it online link below has `N` on the end to show you the result.
[Try it Online!](http://vitsy.tryitonline.net/#code=RDkvKFtYOV0xYTVeRHsvVn0qMHYwe1xbRXZWK0REdnsvfV4rXVYqTg&input=&args=OQ)
]