title: Am I over the speed limit?

text:
# Question
Title: Am I over the speed limit?
Given an road and the time it took me to cross it, tell me if I was speeding.

## Units

Distance is in the arbitrary unit of `d`. Time is in the arbitrary unit of `t`.

## The road

Here is a simple road:

```
10=====

```

The `10` means 10 `d` per `t`. That is the speed limit for the road. The road has 5 `=`s, so its `d` is 5. Therefore, if I cross that road in 0.5 `t`, I went 10 `d` per `t`, because 5/0.5 = 10. The speed limit of that road is 10, so I stayed within the speed limit.

But if I cross that road in **0.25** `t`, I went 20 `d` per `t`, because 5/**0.25** = 20. The speed limit of that road is 10, so I went 10 over the speed limit.

## Examples and calculations

Note that input 1 is the time I took to travel the road, and input 2 is the road itself.

Here is a complex road:

```
Input 1: 1.5
Input 2: 5=====10=====

```

The fastest I could have (legally) gone on the first road (the first 5 `=`s) is 5 `d` per `t`. Since 5 (distance) divided by 5 (speed limit) is 1, the fastest I could have gone on that road is 1 `t`.

On the next road, the speed limit is 10 and the distance is also 5, the fastest I could cross that is 0.5 (5/10). Totaling the minimum times results in 1.5, meaning I went at *exactly the speed limit.*

*Note: I know, I might have been going really fast on one road and really slow on another and still cross in 1.5, but assume the best here.*

A final example:

```
Input 1: 3.2
Input 2: 3.0==========20===

```

The first road is 10 long and has a speed limit of 3, so the minimum time is 3.33333... (10 / 3.)

The second road is 3 long and has a speed limit of 20, so the minimum time is 0.15 (3 / 20.)

Totaling the times results in 3.483333333... I crossed it in 3.2, so I had to be speeding somewhere.

## Notes:

* You must output one distinct value if I am undoubtedly speeding, and another different value if I might not be.
* Your program or function may require input or output to have a trailing newline, but please say so in your submission.
* Your first input will be my speed. It will be a positive float or integer or string.
* Your second input will be the road. It will always match the regex `^(([1-9]+[0-9]*|[0-9]+\.[0-9]+)=+)+\n?$`. You may test out potential inputs here if you are interested.
* You may take input in 2 parameters of a function or program, in 2 separate files, from STDIN twice, or from a space-separated string passed to STDIN, a function, a file or a command-line parameter.
* If you would like to, you can change the order of the inputs.
* Any questions? Ask below in comments and **happy ing!**

# Answer
# 05AB1E, ~~24~~ 22 bytes

Returns **1** when undoubtedly speeding and **0** otherwise.

Saved 2 bytes thanks to *carusocomputing*.

```
'=¡õK¹S'=Q.¡O0K/O-§'-å

```

Try it online!

`-§'-å` shouldn't have to be more than a simple comparison, but for some reason neither  nor  seem to work between the calculated value and the second input.

**Explanation**

Using `3.0==========20===, 3.2` as example

```
'=¡                        # split first input on "="
   õK                      # remove empty strings
                           # STACK: ['3.0', '20']
     ¹S                    # split first input into a list of chars
       '=Q                 # compare each to "="
          .¡O              # split into chunks of consecutive equal elements and sum
                           # STACK: ['3.0', '20'], [0, 10, 0, 3]
             0K            # remove zeroes
                           # STACK: ['3.0', '20'], [10, 3]
               /           # element-wise division
                           # STACK: [3.3333333333333335, 0.15]
                O          # sum
                           # STACK: 3.4833333333333334
                 -         # subtract from second input
                           # STACK: -0.2833333333333332
                  §        # implicitly convert to string
                   '-å     # check if negative
                           # OUTPUT: 1

```
> 5 votes

# Answer
# Python 2, 71 bytes

```
m,s=input()
for c in s.split('=')[:-1]:s=float(c or s);m-=1/s
print m<0

```

Try it online!

Python's dynamic type system can take quite some abuse.

Splitting the input string `s.split('=')` turns `k` equal signs into `k-1` empty-string list elements (except at the end, where one must be cut off). For example,

```
"3.0===20====".split('=')[:-1] == ['3.0', '', '', '20', '', '', '']

```

The code iterates over these elements, updating the current speed `s` each time it sees a number. The update is done as `s=float(c or s)`, where if `c` is a nonempty string, we get `float(c)`, and otherwise `c or s` evaluates to `s`, where `float(s)` just keeps `s`. Note that `c` is a string and `s` is a number, but Python doesn't require doesn't require consistent input types, and `float` accepts either.

Note also that the variable `s` storing the speed is the same one as taking the input string. The string is evaluated when the loop begins, and changing it within the loop doesn't change what is iterated over. So, the same variable can be reused to save on an initialization. The first loop always has `c` as a number, so `s=float(c or s)` doesn't care about `s`'s initial role as a string.

Each iteration subtracts the current speed from the allowance, which starts as the speed limit. At the end, the speed limit has been violated if this falls below `0`.
> 23 votes

# Answer
# Python 3, 79 bytes

```
import re;g=re.sub
lambda m,s:eval(g('=','-~',g('([^=]+)',r'0+1/\1*',s))+'0')>m

```

Try it online!

For example, the input `3.0==========20===` is converted to the string

```
0+1/3.0*-~-~-~-~-~-~-~-~-~-~0+1/20*-~-~-~0

```

and evaluated, and the result is compared to the input speed. Each `-~` increments by `1`. I'm new to regexes, so perhaps there's a better way, like making both substitutions at once. Thanks to Jonathan Allan for pointing out how to match on all but the `=` character.
> 16 votes

# Answer
# GNU C, 128 bytes

```
#import<stdlib.h>
f(float t,char*r){float l,s=0;for(;*r;){for(l=atof(r);*(++r)-61;);for(;*r++==61;)s+=1/l;--r;}return t<s-.001;}

```

Handles non-integer speed limits also. `#import<stdlib.h>` is needed for the compiler not to assume that `atof()` returns an `int`.

`t<s-.001` is needed to make the exact speed limit test case to work, otherwise rounding errors cause it to think you were speeding. Of course, now if the time is `1.4999` instead of `1.5`, it doesn't consider that speeding. I hope that's okay.

Try it online!
> 5 votes

# Answer
# Javascript (ES6), 63 bytes

```
a=>b=>eval(b.replace(/([^=]+)(=+)/g,(_,c,d)=>'+'+d.length/c))>a

```

# Usage

Assign this function to a variable and call it using the currying syntax. The first argument is the time, the second is the road.

# Explanation

Matches all consecutive runs of characters that are not equal signs followed by a run of equal signs. Each match is replaced by the result of the inner function, which uses two arguments: the run of equal signs (in variable `d`) and the number (variable `c`). The function returns the length of the road devided by the number, prepended by a +.

The resulting string is then evaluated, and compared against the first input.

# Stack Snippet

```
let f=
a=>b=>eval(b.replace(/([^=]+)(=+)/g,(_,c,d)=>'+'+d.length/c))>a
```

```
<input id="time" placeholder="time" type="number">
<input id="road" placeholder="road">
<button onclick="output.innerHTML=f(time.value)(road.value)">Process</button>
<div id="output"></div>
```
> 5 votes

# Answer
# Perl 5, 43 bytes

42 bytes of code + `-p` flag.

```
s%[^=]+(=+)%$t+=(length$1)/$&%ge;$_=$t<=<>

```

Try it online!

For each group of digit followed by some equal signs (`[^=]+(=+)`), we calculate how much time is needed to cross it (number of equals divided by the speed: `(length$1)/$&`) and sum those times inside `$t`. At the end, we just need to check that `$t` is less than the time you took to cross it (`$_=$t < <>`). The result will be `1` (true) or *nothing* (false).
> 4 votes

# Answer
# Mathematica, 98 bytes

```
Tr[#2~StringSplit~"="//.{z___,a_,b:Longest@""..,c__}:>{z,(Length@{b}+1)/ToExpression@a,c}]-"
"<=#&

```

Pure function taking two arguments, a number (which can be an integer, fraction, decimal, even `π` or a number in scientific notation) and a newline-terminated string, and returning `True` or `False`. Explanation by way of example, using the inputs `3.2` and `"3==========20===\n"`:

`#2~StringSplit~"="` produces `{"3","","","","","","","","","","20","","","\n"}`. Notice that the number of consecutive `""`s is one fewer than the number of consecutive `=`s in each run.

`//.{z___,a_,b:Longest@""..,c__}:>{z,(Length@{b}+1)/ToExpression@a,c}` is a repeating replacement rule. First it sets `z` to the empty sequence, `a` to `"3"`, `b` to `"","","","","","","","",""` (the longest run of `""`s it could find), and `c` to `"20","","","\n"`; the command `(Length@{b}+1)/ToExpression@a` evaluates to `(9+1)/3`, and so the result of the replacement is the list `{10/3, "20","","","\n"}`.

Next the replacement rule sets `z` to `10/3`, `a` to `"20"`, `b` to `"",""`, and `c` to `"\n"`. Now `(Length@{b}+1)/ToExpression@a` evaluates to `(2+1)/20`, and so the result of the replacement is `{10/3, 3/20, "\n"}`. The replacement rule can't find another match, so it halts.

Finally, `Tr[...]-"\n"` (it saves a byte to use an actual newline between the quotes instead of `"\n"`) adds the elements of the list, obtaining `10/3 + 3/20 + "\n"`, and then subtracts off the `"\n"`, which Mathematica is perfectly happy to do. Finally, `<=#` compares the result to the first input (`3.2` in this case), which yields `False`.
> 3 votes

# Answer
# Jelly, 27 bytes

```
ṣ”=V€ḟ0
Œr”=e$ÐfṪ€ż⁸Ç¤÷/€S>

```

**Try it online!**

Note: assumes that the regex given in the question should be such that a speed limit cannot be `0.0`, `0.00`, etc. - just like it cannot be `0` (confirmed as an unintentional property).

### How?

```
ṣ”=V€ḟ0 - Link 1, speed limits: road          e.g. "4.0===22=="
ṣ”=     - split by '='                             [['4','.','0'],[],[],['2','2'],[],[]]
   V€   - evaluate €ach as Jelly code              [4.0,0,0,22,0,0]
     ḟ0 - filter discard zero                      [4.0,22]

Œr”=e$ÐfṪ€ż⁸Ç¤÷/€S> - Main link: road, time   e.g. "4.0===22==", 0.84
Œr                  - run-length encode            [['4',1],['.',1],['0',1],['=',3],['2',2],['=',2]]
      Ðf            - filter keep:
     $              -     last two links as a monad:
  ”=                -         "="
    e               -         is an element of?    [['=',3],['=',2]]
        Ṫ€          - tail €ach                    [3,2]
             ¤      - nilad followed by link(s) as a nilad:
           ⁸        -     left argument (road)
            Ç       -     last link (1) as a monad [4.0,22]
          ż         - zip                          [[3,4.0],[2,22]]
              ÷/€   - reduce €ach by division      [0.75, 0.09090909090909091]
                 S  - sum                          0.8409090909090909
                  > - greater than time?           1 (would be 0 if maybe not speeding)

```
> 3 votes

# Answer
# Python 3, 90 bytes

```
import re
lambda t,r:sum(x.count("=")/eval(x.strip("="))for x in re.findall("\d+\D+",r))>t

```

Outputs `True` if you're speeding, `False` if you might not be. Does not require (but will work with) trailing newline.

Despite it not looking like it would, it correctly handles floats in both input time and speed limits, because the regex is just used to seperate the road segments.
> 2 votes

# Answer
# MATL, ~~31~~ 30 bytes

```
t61=TwFhhdfd1wY{1L&)o!oswcU!/s<

```

Inputs are: a string (speed limits and roads), then a number (used speed). Output is `1` if undoubtedly speeding, `0` if not.

Try it online!

### Explanation with example

Consider inputs `'3.0==========20==='` and `3.2`.

```
1       % Push 1
        % STACK: 1
y       % Implicitly input string. Duplicate from below
        % STACK: '3.0==========20===', 1, '3.0==========20==='
61=     % Compare with 61 (ASCII for '=')
        % STACK: '3.0==========20===', 1, [0 0 0 1 1 1 1 1 1 1 1 1 1 0 0 1 1 1]
TwFhh   % Prepend true (1) and append false (0)
        % STACK: '3.0==========20===', 1, [1 0 0 0 1 1 1 1 1 1 1 1 1 1 0 0 1 1 1 0]
d       % Consecutive differences
        % STACK: '3.0==========20===', 1, [-1 0 0 1 0 0 0 0 0 0 0 0 0 -1 0 1 0 0 -1]
f       % Find: indices of nonzeros
        % STACK: '3.0==========20===', 1, [1  4 14 16 19]
d       % Consecutive differences. Gives length of substrings of numbers or roads
        % STACK: '3.0==========20===', 1, [3 10 2 3]
Y{      % Split string according to those lenghts. Gives a cell array of strings
        % STACK: {'3.0', '==========', '20', '==='}
1L&)    % Split into odd- and even-indexed subarrays
        % STACK: {'3.0', '20'}, {'==========', '==='}
o       % Convert to 2D numeric array. Right-pads with zeros
        % STACK: {'3.0', '20'}, [61 61 61 61 61 61 61 61 61 61; 61 61 61 0 0 0 0 0 0 0]
!gs     % Number of nonzeros in each row
        % STACK: {'3.0', '20'}, [10 3]
w       % Swap
        % STACK: [10 3], {'3.0', '20'}
c       % Convert to 2D char array. Right-pads with spaces
        % STACK: [10 3], ['3.0'; '20 ']
U       % Convert each row to a number
        % STACK: [10 3], [3.0; 20]
!       % Transpose
        % STACK: [10 3], [3.0 20]
/       % Divide, element-wise
        % STACK: [3.3333 0.15]
s       % Sum of array
        % STACK: 3.4833
<       % Implicitly input number. Less than? Implicitly display (true: 1; false: 0)
        % STACK: true

```
> 2 votes

# Answer
# TI-Basic, ~~168~~ 165 bytes

```
Prompt Str0,T
Str0+"0→Str0
0→I
1→A
While inString(Str0,"=",A
I+1→I
I→dim(L<sub>1</sub>
I→dim(L<sub>2</sub>
0→L
inString(Str0,"=",A→B
expr(sub(Str0,A,B–A→L<sub>1</sub>(I
While 1=expr("9"+sub(Str0,B,1)+"9
L+1→L
B+1→B
If B>length(Str0
Return
End
B→A
L→L<sub>2</sub>(I
End
T≥sum(seq(L<sub>2</sub>(X)/L<sub>1</sub>(X),X,1,I

```

Input is the road as `Str0` and the time as `T`. Make sure to precede the road with a quote, eg `Str0=?"14========3===`.

Output is 0 if speeding, 1 if possibly not speeding.

```
Prompt Str0,T                      # 6 bytes
Str0+"0→Str0                       # 9 bytes
0→I                                # 4 bytes
1→A                                # 4 bytes
While inString(Str0,"=",A          # 12 bytes
I+1→I                              # 6 bytes
I→dim(L<sub>1</sub>                           # 6 bytes
I→dim(L<sub>2</sub>                           # 6 bytes
0→L                                # 4 bytes
inString(Str0,"=",A→B              # 13 bytes
expr(sub(Str0,A,B–A→L<sub>1</sub>(I           # 16 bytes
While 1=expr("9"+sub(Str0,B,1)+"9  # 21 bytes
L+1→L                              # 6 bytes
B+1→B                              # 6 bytes
If B>length(Str0                   # 8 bytes
Return                             # 2 bytes
End                                # 2 bytes
B→A                                # 4 bytes
L→L<sub>2</sub>(I                             # 7 bytes
End                                # 2 bytes
T≥sum(seq(L<sub>2</sub>(X)/L<sub>1</sub>(X),X,1,I        # 21 bytes

```
> 1 votes

# Answer
# APL, 41 bytes

```
{⍺<+/{(≢⍵)÷⍎⍺}/¨Y⊂⍨2|⍳⍴Y←⍵⊂⍨X≠¯1⌽X←⍵='='}

```

This takes the road as a string as its right argument, and the time taken as its left argument, and returns `1` if you were speeding and `0` if not, like so:

```
      3.2{⍺<+/{(≢⍵)÷⍎⍺}/¨Y⊂⍨2|⍳⍴Y←⍵⊂⍨X≠¯1⌽X←⍵='='}'3.0==========20==='
1

```

Explanation:

* `X←⍵='='`: store in `X` a bit vector of all positions in  that are part of the road.
* `X≠¯1⌽X`: mark each position of `X` that is not equal to its right neighbour (wrapping around), giving the positions where numbers and roads start
* `Y←⍵⊂⍨`: split  at these positions (giving an array of alternating number and road strings), and store it in `Y`.
* `Y⊂⍨2|⍳⍴Y`: split up `Y` in consecutive pairs.
* `{(≢⍵)÷⍎⍺}/¨`: for each pair, divide the length of the road part (`≢⍵`) by the result of evaluating the number part (`⍎⍺`). This gives the minimum time for each segment.
* `+/`: Sum the times for all segments to get the total minimum time.
* `⍺<`: Check whether the given time is less than the minimum or not.
> 1 votes

# Answer
# Bash, 151 bytes

Running as (for example) `$ bash golf.sh .5 10=====`:

```
shopt -s extglob
r=$2
while [ -n "$r" ];do
f=${r%%+(=)}
s=`dc<<<"9k$s $[${#r}-${#f}] ${f##*=}/+p"`
r=${f%%+([0-9.])}
done
[[ `dc<<<"$1 $s-p"` != -* ]]

```

## Explanation

```
shopt -s extglob
r=$2

```

Enable bash's extended pattern-matching operators and assign the road to a variable `r`.

```
while [ -n "$r" ];do
f=${r%%+(=)}

```

Loop until `r` is empty. Set `f` to `r` with all equal signs removed from the end, using the `%%` parameter expansion and the `+()` extended globbing operator.

```
s=`dc<<<"9k$s $[${#r}-${#f}] ${f##*=}/+p"`

```

Assign to `s` a running sum of the minimum times for each road segment. This can be re-written (perhaps slightly) more readably as:

```
s=$(dc <<< "9k $s $[${#r}-${#f}] ${f##*=} / + p")

```

Basically what's going on here is we're using a here-string to get the `dc` command to do math for us, since bash can't do floating-point arithmetic by itself. `9k` sets the precision so our division is floating-point, and `p` prints the result when we're done. It's a reverse-polish calculator, so what we're really calculating is `${f##*=}` divided by `$[${#r}-${#f}]`, plus our current sum (or, when we first run through and `s` hasn't been set yet, nothing, which gets us a warning message on stderr about `dc`'s stack being empty, but it still prints the right number because we'd be adding to zero anyway).

As for the actual values we're dividing: `${f##*=}` is `f` with the largest pattern matching `*=` removed from the front. Since `f` is our current road with all the equal signs removed from the end, this means `${f##*=}` is the speed limit for this particular stretch of road. For example, if our road `r` were '10=====5===', then `f` would be '10=====5', and so `${f##*=}` would be '5'.

`$[${#r}-${#f}]` is the number of equal signs at the end of our stretch of road. `${#r}` is the length of `r`; since `f` is just `r` with all the equal signs at the end removed, we can just subtract its length from that of `r` to get the length of this road section.

```
r=${f%%+([0-9.])}
done

```

Remove this section of road's speed limit from the end of `f`, leaving all the other sections of road, and set `r` to that, continuing the loop to process the next bit of road.

```
[[ `dc<<<"$1 $s-p"` != -* ]]

```

Test to see if the time we took to travel the road (provided as `$1`) is less than the minimum allowed by the speed limit. This minimum, `s`, can be a float, so we turn to `dc` again to do the comparison. `dc` does have a comparison operator, but actually using it ended up being 9 more bytes than this, so instead I subtract our travel time from the minimum and check to see if it's negative by checking if it starts with a dash. Perhaps inelegant, but all's fair in love and codegolf.

Since this check is the last command in the script, its return value will be returned by the script as well: 0 if possibly speeding, 1 if definitely speeding:

```
$ bash golf.sh .5 10===== 2>/dev/null && echo maybe || echo definitely
maybe
$ bash golf.sh .4 10===== 2>/dev/null && echo maybe || echo definitely
definitely

```
> 0 votes

# Answer
# Python 3.6, 111 bytes

My first code golf!

```
import re
def f(a,b):
 t=0
 for c in re.split('(=+)',b)[:-1]:
  try:s=float(c)
  except:t+=len(c)/s
 return a<t

```

Try it online!

`re.split('(=+)',b)[:-1]` Splits the road by chunks of `=`.

It then iterates over the result, using `try:s=float(c)` to set the current speed limit if the current item is a number or `except:t+=len(c)/s` to add the time to traverse this section of road to the cumulative total.

Finally it returns the time taken to the fastest possible time.
> 0 votes

# Answer
# C# method (137 122 bytes)

Requires `using System.Linq` adding 19 bytes, included in the 122:

```
bool C(float t,string r,float p=0)=>r.Split('=').Aggregate(t,(f,s)=>f-(s==""?p:p=1/float.Parse(s)))<-p;

```

Expanded version:

```
bool Check(float time, string road, float pace=0) =>
    road.Split('=')
        .Aggregate(time, (f, s) => f - (
            s == ""
            ? pace
            : pace = 1 / float.Parse(s)))
        < -pace;

```

The `road` string is split on the `=` character. Depending on whether a string is the resulting array is empty, the aggregate function sets the `pace` variable for the segment (denoting the time it takes to travel a single `=`) and subtracts it from the time supplied. This will do one too many substractions (for the final road segment), so instead of comparing to `0`, we compare to `-pace`
> 0 votes

# Answer
# PHP5 ~~207~~ 202 bytes

First effort at a code golf answer, please go easy on me. I'm sure one of you geniuses will be able to shorten this significantly, any golfing tips are welcome.

```
function s($c,$d){foreach(array_filter(split("[{$d}/=]",$c)) as $e){$f[]=$e;};return $f;}function x($a,$b){$c=s($b,"^");$d=s($b,"");for($i=0;$i<sizeof($c);$i++){$z+=strlen($c[$i])/$d[$i];}return $a<$b;}

```

Invoke with

```
x("1.5","3.0==========20===")

```

Returns true if you have been under the speed limit, false otherwise
> 0 votes

# Answer
# Dyalog APL, 27 bytes

`<∘(+/(⍎'='⎕r' ')÷⍨'=+'⎕s 1)`

`'=+'⎕s 1` is a function that identifies stretches of `'='` with a regex and returns a vector of their lengths (`⎕s`'s right operand 0 would mean offsets; 1 - lengths; 2 - indices of regexes that matched)

`'='⎕r' '` replaces `'='`s with spaces

`⍎'='⎕r' '` executes it - returns a vector of speeds

`÷⍨` in the middle divides the two vectors ( swaps the arguments, so it's distance divided by speed)

`+/` is sum

everything so far is a 4-train - a function without an explicit argument

`<∘` composes "less than" in front of that function; so, the function will act only on the right argument and its result will be compared against the left argument
> 0 votes

# Answer
# F# (165 bytes)

```
let rec c t p l=
 match l with
 |[]->t<0.0
 |x::xs->
  match x with
  |""->c(t-p)p xs
  |_->c(t-p)(1.0/float x)xs
let s t (r:string)=r.Split '='|>Seq.toList|>c t 0.0

```

I'm still new to F#, so if I did anything weird or stupid, let me know.
> 0 votes

# Answer
# , 100 bytes

```
function(S,R){s=strsplit(R,"=")[[1]]
s[s==""]=0
S<sum((1+(a=rle(as.double(s)))$l[!a$v])/a$v[a$v>0])}

```

Try it online!

Returns `TRUE` for unambiguously speeding values, `FALSE` for possibly unspeedy ones.
> 0 votes

# Answer
# PowerShell, 71 bytes

```
param($t,$r)$t-lt($r-replace'(.+?)(=+)','+($2)/$1'-replace'=','+1'|iex)

```

Try it online!

Test script:

```
$f = {

param($t,$r)$t-lt($r-replace'(.+?)(=+)','+($2)/$1'-replace'=','+1'|iex)

}

@(
    ,(1.5, "5=====10=====", $false)
    ,(3.2, "3.0==========20===", $true)
) | % {
    $time,$road,$expected = $_
    $result = &$f $time $road
    "$($result-eq$expected): $result"
}

```

Output:

```
True: False
True: True

```

Explanation:

1. The script gets the elements of the road `5=====10=====`, swaps elements, adds brackets and operators `+(=====)/5+(=====)/10`
2. Then the script replaces each `=` with `+1`: `+(+1+1+1+1+1)/5+(+1+1+1+1+1)/10`
3. Finally, the script evaluates the string as a Powershell expression and compare it with the first argument.
> 0 votes

---
Tags: code-golf, ascii-art
---


# Question
Title: Write a program that reverses the name of its source file
In a single file, write a program that requires no input and produces no output. When run it should reverse the name of the file it is contained in, **regardless of what the name is**, without altering the code or producing other lasting side effects.

Any way of achieving this is fine. It only matters that once the program is run the only lasting change is that its file name has been reversed. e.g. no new files should be in the directory.

Running the program again should reverse the name back. Indeed, the program should be able to be run arbitrarily many times.

For the purposes of this challenge:

* You may assume filenames are always strings of lowercase letters (a-z) between 1 and 127 characters long. (If your language requires files to have extensions to run then just reverse the part before the extension, e.g. `mycode.bat``edocym.bat`.)
* You may assume the code file is in a directory by itself so it will not have naming conflicts (except with itself).
* You may **not** assume the filename is not a palindrome, i.e. the same when reversed. Filenames that are palindromes should work just as well as those that aren't.
* You may read your file's contents or metadata. There are no restrictions here.
* You may assume your program will be run on a particular, modern, commonplace operating system (e.g. Windows/Linux), since not all shells have the same command set.

> As a concrete example, say you have a Python program in a file called `mycode` in its own directory. Running
>
> ```
> python mycode
>
> ```
>
> in the terminal should result in the filename being reversed to `edocym`. The file `edocym` should be alone in its directory - no file named `mycode` should exist anymore. Running
>
> ```
> python edocym
>
> ```
>
> will reverse the name back to `mycode`, at which point the process can be repeated indefinitely.
>
> If the same Python file was renamed `racecar` (without changing the code) and then run
>
> ```
> python racecar
>
> ```
>
> nothing should visibly change since "racecar" is a palindrome. That same goes if the filename were, say, `a` or `xx`.

**The shortest code in bytes wins. Tiebreaker is higher voted answer.**

# Answer
# Bash + common linux utils, 13 bytes

My method is similar to @DigitalTrauma's but a bit shorter due to the pipe with `ls`:

```
mv * `ls|rev`

```
> 41 votes

# Answer
## C#, 153 bytes

```
void f(){var x=System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name;File.Move(x,new string(x.Reverse().ToArray()).Substring(4)+".exe");}

```

OO is cool and all untill you have a variable defined:

**System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name**

thats just mean
> 15 votes

# Answer
# Bash + common linux utils, 15

* 1 byte saved thanks to @Dennis

Assumes that the script is in a directory by itself.

```
mv * `rev<<<$0`

```
> 13 votes

# Answer
# MATLAB, ~~50~~ 46 bytes

```
e='.m';x=mfilename;movefile([x e],[flip(x) e])

```

*Thanks to @Suever for removing 4 bytes and for the testing!*

Tested on OS X El Capitan and Debian Jessie, both with Matlab version R2014a.

On Windows a flag `'f'` is needed ( `e='.m';x=mfilename;movefile([x e],[flip(x) e]),'f'`) to change file name while the file is being used.

### How it works

```
e='.m';                       % Store file extension '.m' in variable `e`
x=mfilename;                  % Get name of file being run, without the extension
movefile([x e],[flip(x) e])   % Move (rename) file. `flip` is used for reversing the
                              % name without extension. [...] is (string) concatenation

```
> 7 votes

# Answer
# Julia, 51 bytes

```
d,f=splitdir(@__FILE__)
cd(d)do
mv(f,reverse(f))end

```

This program should be operating system agnostic, though it was only tested on OS X.

Ungolfed:

```
# Get the directory and file name of the current source file
d, f = splitdir(@__FILE__)

# Change the working directory temporarily to d
cd(d) do
    # Overwrite the file with the reverse of its name
    mv(f, reverse(f))
end

```
> 7 votes

# Answer
## Batch, 109 bytes

```
@echo off
set f=%0
set r=
:l
set r=%f:~0,1%%r%
set f=%f:~1%
if not .%f%==. goto l
ren %0.bat %r%.bat

```

Note 1: Batch files must end in `.bat`; it is assumed that the batch file is executed by its name without extension, and that the `.bat` is not to be reversed. For example, `reverse` would attempt to rename `reverse.bat` to `esrever.bat`.
Note 2: `CMD.EXE` errors out after renaming the batch file. (`COMMAND.COM` wouldn't, except that it's incapable of string manipulation in the first place.)

Edit: Saved 2 bytes by using the guarantee that the file name is alphabetic (based on @CᴏɴᴏʀO'Bʀɪᴇɴ's comment).
> 5 votes

# Answer
# C, 102 bytes

```
main(c,v)char**v;{char*b=strdup(*v),*n=strrchr(*v,47),*t=strchr(b,0);for(;*++n;*--t=*n);rename(*v,b);}

```

Breakdown:

```
                            // No #include lines required (for GCC at least)
main(c,v)char**v;{          // K&R style function to save 2 bytes
    char*b=strdup(*v),      // Duplicate args[0] (script path)
        *n=strrchr(*v,47),  // Find last "/" in input
        *t=strchr(b,0);     // Go to end of output string
    for(;*++n;*--t=*n);     // Reverse input into output character-by-character
    rename(*v,b);           // Rename the file
}                           // Implicit return 0

```

Finally a challenge where C isn't (quite so hopelessly) uncompetitive!

---

If we take "You can assume the working directory of the shell will be the folder the file is in" to mean that the program will always be invoked as `./myexecutable`, we can simplify `*n=strrchr(*v,47)` to `*n=*v+1` to save 10 characters, but this isn't entirely valid (it could be invoked as `././myexecutable`, for example).

---

Also if you want to keep a file extension (e.g. ".out") in-tact, you can change `*t=strchr(b,0)` to `*t=strrchr(b,46)`, costing 2 bytes. Not required though.
> 5 votes

# Answer
## Ruby, 24 bytes

```
File.rename$0,$0.reverse

```

Fairly self-explanatory. (`$0` is the name of the file being executed.)

Run with `ruby whatever` with a working directory of the directory that contains the file.
> 4 votes

# Answer
# Vitsy \+ \*sh, 15 bytes

```
iG:`?r.iG' mr',

```

### Explanation

```
iG:`?r.iG' mr',
i               Push -1 to the stack. (this assumes that no arguments are passed)
 G              Get the use name of the class specified by the top item of the
                stack. (-1 refers to the origin class, so this class)
  :             Duplicate stack and jump to it.
   `            Read a file with the current stack as its name, replacing the stack
                with the file's contents.
    ?           Shift one stack to the right.
     r          Reverse the current stack.
      .         Write a file with the name specified by the top stack and the
                contents as the second-to-top stack.
       iG       Get the name of the current class again.
         ' mr'  Push 'rm ' to the stack.
              , Execute the current stack as a command.

```

Note that this submission must use the non-safe version of Vitsy (cannot be done on Try It Online!)
> 3 votes

# Answer
# Perl 5, 18 bytes

A bit like the Ruby one (run `perl nameofscript`):

```
rename$0,reverse$0

```

Taking a possible path into account is uglier (47 bytes)

```
($a,$b)=$0=~/(.*\/)?(.*)/;rename$0,$a.reverse$b

```
> 3 votes

# Answer
## Python 3, 105 bytes

```
import os;a=__file__.split('\\')[::-1][0].split('.');os.rename('.'.join(a),'.'.join([a[0][::-1],a[1]]))

```

-Alex.A removed 1 byte.

-Digital Trauma showed me os.rename() which took away 62 bytes.

-muddyfish removed 7 bytes.
> 2 votes

# Answer
# PHP, ~~84~~, ~~70~~, 54 bytes

```
rename($f=__FILE__,strrev(basename($f,$e='.php')).$e);

```

---

**EDIT:** removed 14 bytes thanks to `insertusernamehere` in the comments

---

**EDIT:** removed 16 bytes thanks to `Martijn` in the comments
> 2 votes

# Answer
# , ~~29~~ 26 bytes

```
:se ri
izyw:!mv z "
dd

```

Since this contains unprintables, here is a hex dump:

```
00000000: 3a73 6520 7269 0a69 127a 1b79 773a 216d  :se ri.i.z.yw:!m
00000010: 7620 127a 2012 220a 6464                 v .z .".dd

```

*Note:* this will not run on v.tryitonline.net since TIO does not allow file access.

Explanation:

```
:se ri            "Turn on 'reverse mode' (all text is inserted backwards)
i<C-r>z<esc>      "Enter the path to the file in reverse
yw                "Yank a word. This first word is the name we will save the new file as

"Run an "mv" in the terminal with the contents of register 'z' (the path to the file)
"And the contents of register '"' (the word we yanked)
:!mv <C-r>z <C-r>"

dd                "Delete a line so that we don't have any text printed.

```
> 2 votes

# Answer
## PowerShell, 39 bytes

```
mi *(-join((ls).name)[-5..-999]+'.ps1')

```
> 2 votes

# Answer
# Python 2, 41 bytes

```
import os;s=__file__;os.rename(s,s[::-1])

```

Demo on Bash.

Python really doesn't care the file extension, so we can just flip the entire file name.
> 2 votes

# Answer
# JavaScript (Node), ~~108~~ ~~104~~ 68 bytes

36 bytes saved, thanks to Downgoat!

Windows version:

```
require("fs").rename(F=__filename,F.split(/.*\\|/).reverse().join``)

```

Other version:

```
require("fs").rename(F=__filename,F.split(/.*\/|/).reverse().join``)

```
> 1 votes

# Answer
# PHP, 31 bytes

Nothing much to explain I guess:

```
rename($x=$argv[0],strrev($x));

```
> 1 votes

# Answer
# Perl 6,  ~~70~~  27 bytes

If it needed to work in a different working directory you would need something like this:

```
$_=$*PROGRAM;.rename: .basename.flip.IO.absolute: .absolute.IO.dirname

```

Since the working directory will be the same directory as the program it can be simplified to just:

```
$_=$*PROGRAM;.rename: .flip

```

### Explanation:

```
$_ = $*PROGRAM;  # IO::Path object

$_.rename:
    $_.basename
      .flip      # reverse characters
      .IO        # turn into an IO object (IO::Path)
      .absolute: # turn it into an absolute path Str in the following dir
        $_.absolute.IO.dirname

```
> 1 votes

# Answer
# JavaScript ES6 (Node.js) 70 Bytes

No Regex Yay!

```
require("fs").rename(a=__filename,[...a].reverse().join``.split`/`[0])

```

Any help is appreciated
> 1 votes

# Answer
# Python (2.7 or 3.4+), 61 49 bytes

I believe this is close to the optimal Python solution:

```
import os;a=__file__;os.rename(a,a[-4::-1]+".py")

```

Inspired by `s4b3r6`'s answer, but uses list slicing instead of reverse, and saves `__file__` to a variable to save bytes when using it twice.

**Note:** This assumes that the filename is always `*.py`. A slightly more generic solution that can handle any two-character file extension would be to use `a[-3:]` to replace `".py"`, at the cost of 1 extra byte.

**Update:** Saved 12 bytes by using the list slicing trick `a[-4::-1]` to remove the file extension, instead of splitting and then reversing with `a.split(".")[0][::-1]`.
> 1 votes

# Answer
## PowerShell v4+, 68 bytes

```
$a,$b=($c=(ls).Name)-split'\.';mv $c "$(-join($a[$a.length..0])).$b"

```

Only works because the script is guaranteed to be in a directory all by itself. Performs an `ls` (alias for `Get-ChildItem`) and takes the `.Name` of the resultant object(s). We store that in `$c` and then `-split` it on literal period to get the filename and extension, and store those in `$a` and `$b`, respectively.

Next is the `mv` (alias for `Move-Item`) command, where we're moving `$c` to `$a`(reversed)`.$b`.

### Example

```
PS C:\Tools\Scripts\golfing\reverse> ls

    Directory: C:\Tools\Scripts\golfing\reverse

Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---         6/13/2016   7:58 AM         88 reverse.ps1

PS C:\Tools\Scripts\golfing\reverse> .\reverse.ps1

PS C:\Tools\Scripts\golfing\reverse> ls

    Directory: C:\Tools\Scripts\golfing\reverse

Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---         6/13/2016   7:58 AM         88 esrever.ps1

```
> 1 votes

# Answer
## Powershell, 112 bytes

I'm not going to beat the unix cmds, just adding my two pence for fun :-)

```
gci * | % { $n=($_.basename[-1..-(($_.basename).length)] -join “”)+$_.Extension; mv -Path $_.Fullname -Dest $n }

```
> 1 votes

# Answer
# Python (2 & 3), 88 78 bytes

```
import os;os.rename(__file__,''.join(reversed(__file__.split(".")[0]))+".py"))

```

Exploits the fact that the filename is given by sys.argv (as the working directory is the folder the file is in), and makes use of os.rename. Annoyingly, reversed returns an iterator, so we have to use join.

Edit: Saved 10 bytes by using \__file\__ instead of sys.argv\[0\], as suggested by @muddyfish to @DigitalTrauma.
> 0 votes

# Answer
## PowerShell, 50 bytes

```
mv *(-join($f=(ls).BaseName)[$f.Length..0]+'.ps1')

```

There is only one file, so `mv *` shell wildcard will only have one result. The destination name is `(ls).basename` which lists all the files (alias for 'dir'), calls for the BaseName property - and since there's only one file, PowerShell will unpack the 1-item array into a string. Store that filename in `$f`, then index it with a countdown and `-join` the reversed characters back up into a string. Add the mandatory `.ps1` suffix.
> 0 votes

# Answer
# AutoIt, 45 bytes

```
$a=@ScriptName
FileMove($a,StringReverse($a))

```
> 0 votes

# Answer
# Python 2.7, 68 bytes

```
import os;a=__file__;os.rename(a,a.split("\\")[-1][:-3][::-1]+".py")

```

This is probably the best I can get it. I just proved myself wrong.
> 0 votes

# Answer
# tcl, 42

```
file rename $argv0 [string reverse $argv0]

```
> 0 votes

# Answer
# Visual Basic Script, 44 Bytes

```
WScript.Echo(StrReverse(WScript.ScriptName))

```

Example output for file called `reverse.vbs` (Run with cscript):

```
sbv.esrever

```
> 0 votes

# Answer
# sfk, 83 bytes

```
list -maxfiles=1 . +setvar n +getvar n +swap +setvar m +ren -var . /#(n)/#(m)/ -yes

```

Try it online!
> 0 votes

# Answer
# SmileBASIC 60 bytes

```
P$=PRGNAME$()FOR I=1-LEN(P$)TO.Q$=Q$+P$[-I]NEXT
RENAME P$,Q$

```

Alternative:

```
P$=PRGNAME$()T$=P$*1WHILE""<T$Q$=Q$+POP(T$)WEND
RENAME P$,Q$

```
> 0 votes

---
Tags: code-golf, string, file-system
---


title: Javascript: Create a 10x10 array of 1s

text:
# Question
Title: Javascript: Create a 10x10 array of 1s
Obviously this challenge would be trivial with separate functions and libraries, so they aren't allowed.

Your code must conform to an ECMAscript specification (any spec will do), so no browser-specific answers.

The array must be accessible after it is instantiated.

I have an answer that I'll withhold for now.

**Note:** this challenge is specific to javascript because it is notoriously inconvenient to make multi-dimensional arrays in javascript.

# Answer
> 11 votes
# Javascript ES6, 30

```
(x=i=>Array(10).fill(i))(x(1))

```

ES6 in action :)

# Answer
> 27 votes
# Javascript, 34 bytes

```
for(r=[b=[i=10]];i--;r[i]=b)b[i]=1

```

Since it's apparently OK to make the rows equal by reference, I guess it's apparently OK to rely on that fact. This helps us shave off one for-loop by building the table at the same time as its rows. So, here's my new contestant.

Since `r[0]` and `b[0]` are overwritten during the loop, they can contain garbage. This gives us another free execution slot to shave off some commas. Sadly, `r=b=[]` won't do, since then they are equal by-ref.

Also, it scales well (99x99 is still 34 bytes), doesn't require ES5 (the new functions have terribly long names, anyways), and as a bonus, it's unreadable :-)

# Answer
> 19 votes
# ECMAScript 6 - 33 Characters

```
x=(y=[..."1111111111"]).map(x=>y)

```

Outputs a 10x10 array of "1"s.

This abuses the fact that the string "1111111111" has all the requisite properties to be treated as if it is an array so you can use the spread operator `...` to transform it into an array of characters and then map it to a copy of the array with each element referencing the "original".

Or with only one variable name (for 35 characters):

```
x=(x=x=>[..."1111111111"])().map(x)

```

Or for extra confusion (but at 45 characters)

```
x=[];x[9]=x;x=[...x].map(y=>[...x].map(x=>1))

```

or (43 characters)

```
y=y=>[...x].map(x=>y);x=[];x[9]=x;x=y(y(1))

```

# Answer
> 14 votes
# 44 bytes

```
for(a=[i=10];i;)a[--i]=[1,1,1,1,1,1,1,1,1,1]

```

Previous version:

```
for(a=i=[];i^10;)a[i++]=[1,1,1,1,1,1,1,1,1,1]

```

# Answer
> 13 votes
# 45 characters

```
x=[a=[1,1,1,1,1,1,1,1,1,1],a,a,a,a,a,a,a,a,a]

```

Each element points to the same array, but the spec doesn't mention anything against that!

# Answer
> 7 votes
## Javascript, 51

```
a=[];for(i=10;i;i--,a.push([1,1,1,1,1,1,1,1,1,1]));

```

Or if all indices are allowed to point to the same array:

## Javascript, 41

```
a=[1,1,1,1,1,1,1,1,1,1];a=a.map(a.sort,a)

```

# Answer
> 6 votes
# JavaScript, 45 44 Bytes

Best I have so far. (Still trying).

```
x=[];while(x.push([1,1,1,1,1,1,1,1,1,1])-10);

```

Shorter (thanks mellamokb!)

```
for(x=[];x.push([1,1,1,1,1,1,1,1,1,1])-10;);

```

# Answer
> 5 votes
## Javascript, 47

Since my original solution has been beaten, I will now post it.

```
for(a=[],i=10;i--;a[i]='1111111111'.split(''));

```

Unfortunately, `0x3FF.toString(2)` isn't quite as efficient as just listing the string out, which isn't quite as efficient as just statically declaring the array.

You can shave off one character this way (**46**):

```
for(a=[],i=10;i--;a[i]=[1,1,1,1,1,1,1,1,1,1]);

```

You can save 2 more characters like so: (**44**)

```
for(a=[i=10];i--;)a[i]=[1,1,1,1,1,1,1,1,1,1]

```

Another 44 byte solution using JS 1.8 function expression closures (FF only atm):

```
x=(x=[1,1,1,1,1,1,1,1,1,1]).map(function()x)

```

# Answer
> 4 votes
# JavaScript, 57 bytes

```
r=eval("["+(A=Array(11)).join("["+A.join("1,")+"],")+"]")

```

Before golfing:

```
a=Array(11).join("1,");
b=Array(11).join("["+a+"],")
c=eval("["+b+"]")

```

Note: This needs ES5, so don't expect much from IE.

# Answer
> 3 votes
# 54

This has already been beaten, but here's my solution:

```
function x(){return[1,1,1,1,1,1,1,1,1,1]}x=x().map(x)

```

# Answer
> 3 votes
# 39 bytes

Using array comprehension in ECMAScript 7:

```
x=[x for(y in x=[1,1,1,1,1,1,1,1,1,1])]

```

# Answer
> 2 votes
**56 characters**

Rather long answer, but will be better for 100x100 etc.

```
for(a=[[i=k=0]];++i<100;m?0:a[k=i/10]=[1])a[k][m=i%10]=1

```

# Answer
> 2 votes
# ES6, 54

It's not the shortest, but I thought I'd go for a different approach to what's already here.

```
a=(''+{}).split('').slice(0,10).map(_=>a.map(_=>1))

```

> Cast an object to a string `"[object Object]"`
> Split the string into chars \["\[", "o", "b", ... "\]" \]
> Grab a slice of just 10
> Map the result of mapping 1 onto the initial slice

# Answer
> 2 votes
# Javascript, 36 chars (ECMA 6)

```
(a=[b=[]]).fill(b.fill(a[9]=b[9]=1))

```

Tested in my browser (Firefox on Ubuntu) and in the Codecademy Javascript interpreter

# Answer
> 1 votes
# 61 for fun

```
eval("r=["+("["+(Array(11).join("1,"))+"],").repeat(11)+"]")

```

# Answer
> 0 votes
# Javascript - 64 63 59 characters

```
for(var a=b=[],i=100;i-->0;b[i%10]=1)if(i%10==0){a[i/10]=b;b=[]}

```

```
for(var a=b=[i=100];i-->0;b[i%10]=1)if(i%10==0){a[i/10]=b;b=[]}

```

One char saved by hiding the iterator in the array.

```
for(a=b=[1],i=100;i--;b[i%10]=1)if(i%10==0){a[i/10]=b;b=[]}

```

Saved some chars with Jans suggestions.

Readable version:

```
for(var a = b = [i = 100]; i-- > 0; b[i % 10] = 1) {
  if(i % 10 == 0) {
    a[i / 10] = b;
    b = [];
  }
}

```

Yes, it's not the shortest solution, but another approach without using readymade `[1,1,1,1,1,1,1,1,1,1]` arrays.

# Answer
> 0 votes
**Javascript 69 characters (for now)**

```
b=[]
a=[]
for(i=100;i-->0;){
a.push(1)
if(i%10===0){b.push(a);a=[]}
}

```

# Answer
> 0 votes
## JavaScript 73

```
function h(){s="1111111111",r=[10],i=-1;while(++i<10){r[i]=s.split("");}}

```

# Answer
> 0 votes
## Javascript ES6, 53

```
x="1".repeat(100).match(/.{10}/g).map(s=>s.split(""))

```

But the ones in the array are strings :)

# Answer
> 0 votes
## Javscript ES6, 53

```
x=eval("["+("["+"1,".repeat(10)+"],").repeat(10)+"]")

```

# Answer
> 0 votes
# JavaScript (ES6), 35 bytes

```
A=Array(10).fill(Array(10).fill(1))

```

---
Tags: code-golf, javascript, array
---


title: Make a simple word wrapper

text:
# Question
Title: Make a simple word wrapper
(Note: This is my first ever code golf question, but as far as I can tell, nobody else has done exactly this, so I should be good.)

Your task is to make a program or function that takes in a string `s` and an integer `n`, and returns or outputs that text wrapped into multiple lines. Each word must be wholly on a line; i.e. no words split in the middle. Each line can be no longer than `n` characters long, and you must fit as many words as possible on each line.

Example:

```
s = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed eget erat lectus. Morbi mi mi, fringilla sed suscipit ullamcorper, tristique at mauris. Morbi non commodo nibh. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed at iaculis mauris. Praesent a sem augue. Nulla lectus sapien, auctor nec pharetra eu, tincidunt ac diam. Sed ligula arcu, aliquam quis velit aliquam, dictum varius erat."
n = 50

output:
Lorem ipsum dolor sit amet, consectetur adipiscing
elit. Sed eget erat lectus. Morbi mi mi, fringilla
sed suscipit ullamcorper, tristique at mauris.
Morbi non commodo nibh. Pellentesque habitant
morbi tristique senectus et netus et malesuada
fames ac turpis egestas. Sed at iaculis mauris.
Praesent a sem augue. Nulla lectus sapien, auctor
nec pharetra eu, tincidunt ac diam. Sed ligula
arcu, aliquam quis velit aliquam, dictum varius
erat.

```

Your output can be an array of strings or a single string with line breaks. Also, you can assume no words will be longer than `n`, so don't worry about dealing with weird cases.

Standard I/O rules apply, and standard loopholes are prohibited. Trailing spaces are allowed.

Since this is , the shortes solution in bytes wins.

Here is an example program in Python that would work.

# Answer
# Python 2, 26 bytes

```
from textwrap import*
fill

```

Try it online!

Meh... built-ins are boring... instead, have a nice 87-byte solution here:

```
s,n=input()
x=''
for i in s.split():c=n<len(x+i);exec'print x'*c;x=x*-~-c+i+' '
print x

```

Try it online!

Outputs trailing spaces.
> 7 votes

# Answer
# JavaScript (ES6),  ~~75 73~~  72 bytes

Takes input as `(string)(n)`.

```
s=>n=>s.split` `.map(w=>r=(u=r?r+' '+w:w)[n]?(o+=r+`
`,w):u,o=r='')&&o+r

```

Try it online!

### Variables

The formatted output is stored in \\$o\\$ (in green below).

The updated line \\$u\\$ is defined as the concatenation of:

* the current line \\$r\\$ (in black below)
* a space if \\$r\\$ is not empty, or nothing otherwise (in orange below)
* the new word \\$w\\$ (in blue below)

We need to insert a line break whenever the \\$n\\$-th character of \\$u\\$ is set (0-indexed, in red below).

### Example

\\$n=16\\$ and \\$s\\$ = "LOREM IPSUM DOLOR"

Adding "LOREM": $$\small\begin{array}{|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|} \hline 00&01&02&03&04&05&06&07&08&09&10&11&12&13&14&15&\color{red}{16}\\ \hline \color{blue}L&\color{blue}O&\color{blue}R&\color{blue}E&\color{blue}M&&&&&&&&&&&&\\ \hline\end{array} $$

Adding "IPSUM": $$\small\begin{array}{|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|} \hline 00&01&02&03&04&05&06&07&08&09&10&11&12&13&14&15&\color{red}{16}\\ \hline L&O&R&E&M&\color{orange}\bullet&\color{blue}I&\color{blue}P&\color{blue}S&\color{blue}U&\color{blue}M&&&&&&\\ \hline\end{array} $$

Adding "DOLOR": $$\small\begin{array}{|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|} \hline 00&01&02&03&04&05&06&07&08&09&10&11&12&13&14&15&\color{red}{16}\\ \hline L&O&R&E&M&\bullet&I&P&S&U&M&\color{orange}\bullet&\color{blue}D&\color{blue}O&\color{blue}L&\color{blue}O&\color{blue}R\\ \hline\end{array} $$

$$\small\begin{array}{|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|} \hline 00&01&02&03&04&05&06&07&08&09&10&11&12&13&14&15&\color{red}{16}\\ \hline \color{green}L&\color{green}O&\color{green}R&\color{green}E&\color{green}M&\color{green}\bullet&\color{green}I&\color{green}P&\color{green}S&\color{green}U&\color{green}M&\color{green}\hookleftarrow&&&&&\\ \hline D&O&L&O&R&&&&&&&&&&&&\\ \hline\end{array} $$
> 5 votes

# Answer
# PHP, 8 bytes

Admittedly not the most original solution, but PHP has a native function that matches your requirements perfectly!

## `wordwrap`:

> `string wordwrap ( string $str [, int $width = 75 [, string $break = "\n" [, bool $cut = FALSE ]]] )`
>
> Wraps a string to a given number of characters using a string break character.

Use like so:

```
$str = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed eget erat lectus. Morbi mi mi, fringilla sed suscipit ullamcorper, tristique at mauris. Morbi non commodo nibh. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed at iaculis mauris. Praesent a sem augue. Nulla lectus sapien, auctor nec pharetra eu, tincidunt ac diam. Sed ligula arcu, aliquam quis velit aliquam, dictum varius erat.";
echo wordwrap($str, 50);

```

Or Try it online!
> 5 votes

# Answer
# Perl 6, ~~46~~ 29 bytes

```
{;*.comb(/.**{1..$_}[\s|$]/)}

```

Try it online!

Regex based solution that takes input curried, like `f(n)(s)` and returns a list of lines. Each line except the last has a trailing whitespace

### Explanation:

```
{;*                         }   # Anonymous code block that returns a Whatever lambda
   .comb(/                /)    # Split the string by
          .**{1..$_}            # Up to n characters
                    [\s|$]      # Terminated by a whitespace char or the end of the string

```
> 5 votes

# Answer
# Vim, 15 bytes/keystrokes

```
DJ:se tw=<C-r>"
gq_

```

A text formatting question? I know just the tool for the job! And it even has my name in the first two keystrokes :D

`<C-r>` means `ctrl-r`.

This could *ever* so slightly shorter in V, but I prefer answering in vanilla vim for answers that really show off how concise vim can be for the right challenge. And the difference is so small anyway.

This could also be the following for 15 bytes as well:

```
:se tw=<C-r><C-w>
ddgq_

```

Try it online!
> 4 votes

# Answer
# , ~~36~~ 27 bytes

R has this as a built-in (`strwrap`), we return a vector of split lines.

```
function(s,n)strwrap(s,n+1)

```

Try it online!
> 4 votes

# Answer
# Haskell, 70 bytes

```
s!n|length s<=n=[s]|(t,_:d)<-splitAt(until((<'!').(s!!))pred n)s=t:d!n

```
> 4 votes

# Answer
# Python 2, 74 bytes

```
s,n=input()
while s:i=n;exec"i-=' '<(s+' '*n)[i];"*n;print s[:i];s=s[i+1:]

```

Try it online!
> 3 votes

# Answer
# Java (JDK), 46 44 bytes

Basically a pure regex solution in Java, almost certainly the shortest I've written.

Cheers to Kevin for helping to cut down the bytes in the regex even further!

```
n->s->s.replaceAll(".{1,"+n+"}( |$)","$0\n")

```

Try it online!

Using a curried lamdba, it creates a regex to greedily match up to `n` characters followed by either a space or end of string. It then replaces those characters with themselves followed by a newline.
> 3 votes

# Answer
# Japt, 20 bytes

```
¸rÈ+Yi[X·ÌY]¸Ê>V?R:S

```

Try it online!

Thanks to Bubbler and Shaggy for their help

Explanation:

```
¸                       #Split into words
 r                      #For each word, add them to the output in this way:
     i                  # Choose a character using this process:
       X·Ì              #  Get the last line of the output
          Y             #  And the current word
      [    ]¸           #  Join them with a space
             Ê>V?       #  If the resulting line is greater than the allowed length:
                ?R      #   Choose "/n" (newline)
                  :S    #  Otherwise choose " " (space)
     i                  # Add the chosen character to the output
  È+Y                   # Add the current word to the output

```
> 2 votes

# Answer
# Powershell, ~~40~~ 83 bytes

Test case with `n=80` added.

```
param($s,$n)$s-split' '|%{if(($o+$_|% le*)-lt$n){$o+=' '*!!$o+$_}else{$o;$o=$_}}
$o

```

Test script:

```
$f = {

param($s,$n)$s-split' '|%{if(($o+$_|% le*)-lt$n){$o+=' '*!!$o+$_}else{$o;$o=$_}}
$o

}

@(
,(50, "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed eget erat lectus. Morbi mi mi, fringilla sed suscipit ullamcorper, tristique at mauris. Morbi non commodo nibh. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed at iaculis mauris. Praesent a sem augue. Nulla lectus sapien, auctor nec pharetra eu, tincidunt ac diam. Sed ligula arcu, aliquam quis velit aliquam, dictum varius erat.",
"Lorem ipsum dolor sit amet, consectetur adipiscing",
"elit. Sed eget erat lectus. Morbi mi mi, fringilla",
"sed suscipit ullamcorper, tristique at mauris.",
"Morbi non commodo nibh. Pellentesque habitant",
"morbi tristique senectus et netus et malesuada",
"fames ac turpis egestas. Sed at iaculis mauris.",
"Praesent a sem augue. Nulla lectus sapien, auctor",
"nec pharetra eu, tincidunt ac diam. Sed ligula",
"arcu, aliquam quis velit aliquam, dictum varius",
"erat.")
,(80, "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed eget erat lectus. Morbi mi mi, fringilla sed suscipit ullamcorper, tristique at mauris. Morbi non commodo nibh. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed at iaculis mauris. Praesent a sem augue. Nulla lectus sapien, auctor nec pharetra eu, tincidunt ac diam. Sed ligula arcu, aliquam quis velit aliquam, dictum varius erat.",
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed eget erat lectus.",
"Morbi mi mi, fringilla sed suscipit ullamcorper, tristique at mauris. Morbi non",
"commodo nibh. Pellentesque habitant morbi tristique senectus et netus et",
"malesuada fames ac turpis egestas. Sed at iaculis mauris. Praesent a sem augue.",
"Nulla lectus sapien, auctor nec pharetra eu, tincidunt ac diam. Sed ligula arcu,",
"aliquam quis velit aliquam, dictum varius erat.")
) | %{
    $n,$s,$expected = $_
    $result = &$f $s $n
    "$result"-eq"$expected"
    # $result   # uncomment this line to dispaly a result
}

```

Output:

```
True
True

```
> 2 votes

# Answer
# Mathematica, 16 bytes

```
InsertLinebreaks

```

Built-in function. Takes a string and an integer as input and returns a string as output.

> `InsertLinebreaks["*string*", *n*]`
> inserts newline characters to make no line longer than *n* characters.
> 2 votes

# Answer
# C (gcc), 68 bytes

```
i;b(s,n,l)char*s,*l;{for(i=n;*++s;i--||(i=l-s+n,*l=10))l=*s-32?l:s;}

```

Try it online!

Thanks to ceilingcat, save 2 bytes by moving global `char*l` to parameter.
> 2 votes

# Answer
# APL (Dyalog Unicode), 14 bytesSBCS

Infix function; left argument is `n`, right argument is `n`.

```
⎕CY'dfns'⋄wrap

```

Try it online!

`⎕CY`**c**op**y** in the dfns library

then

`wrap`\[c\] use the wrap\[n\] function

\[c\] code of that function
\[n\] notes for that function

---

### Golfed version of `wrap`, 59 bytesSBCS

```
{⍺≥≢⍵:⍵⋄(t↑⍵),2↓⎕TC,⍺∇⍵↓⍨t+b⊃⍨t←⊃⌽⍺,g/⍨⍺≥g←⍸(⍺+1)↑b←' '=⍵}

```

Try it online!

`{``}` dfn;  is left argument (width),  is right argument (string)

`≢⍵` tally (number of characters) of string

`⍺≥``:` if width is greater than or equal to that, then:

return the string

otherwise:

`' '=⍵` Boolean mask where blanks are equal to the string

`b←` store in `b` (for **b**lanks)

`(``)↑` take the following number of elements from that:

`⍺+1` one more than the width

**i**ndices where true

`g←` store in `g` (for **g**aps)

`⍺≥` Boolean mask where the width is greater than or equal to that

`g/⍨` filter the gap indices by that

`⍺,` append that to the width

`⊃⌽` pick the last element of that (lit. pick the first of the reversed)

`t←` store in `t` (for **t**ake)

`b⊃⍨` use that to pick an element from the mask of **b**lanks

`t+` add that to `t`

`⍵↓⍨` drop that many characters from the string

`⍺∇` recurse on that with the same left left argument

`⎕TC,` append that to the list of **t**erminal **c**ontrol characters (8:HT, 10:NL, 13:CR)

`2↓` drop the first two character from that (leaving just a leading 13:CR)

`(``),` append that to the following:

`t↑⍵` the first `t` characters of the string
> 2 votes

# Answer
## JavaScript + HTML + CSS, ~~117~~ 64 bytes

*-53 bytes courtesy of @Neil*

```
n=50
s="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed eget erat lectus. Morbi mi mi, fringilla sed suscipit ullamcorper, tristique at mauris. Morbi non commodo nibh. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed at iaculis mauris. Praesent a sem augue. Nulla lectus sapien, auctor nec pharetra eu, tincidunt ac diam. Sed ligula arcu, aliquam quis velit aliquam, dictum varius erat."
f=(n,s)=>document.body.innerHTML+=`<tt><p style=width:${n}ch>${s}`
f(n,s)
```
> 1 votes

# Answer
# Red, 125, 117, 114  112 bytes

```
func[s n][d: 0 parse s[any[to" "p:" "opt[[to" "| to end]q:(if(-1 - d + index? q)> n[p/1: #"^/"d: index? p])]]]s]

```

Try it online!
> 1 votes

# Answer
# Retina 0.8.2, 37 bytes

```
.+$
$*
!`(?=\S.*¶(1)+)(?<-1>.)+(?=\s)

```

Try it online! Takes `s` and `n` on separate lines. Explanation:

```
.+$
$*

```

Convert `n` to unary.

```
(?=\S.*¶(1)+)(?<-1>.)+(?=\s)

```

Match non-whitespace, then look ahead to `n` and count it as `$#1`. Then go back and use a balancing group to match up to `n` characters followed by whitespace.

```
!`

```

Output the matches as a list of lines.
> 1 votes

# Answer
# Charcoal, 19 bytes

```
Ｎθ←Ｆ⪪Ｓ «¿‹⁺ＬιⅈθＭ→⸿ι

```

Try it online! Link is to verbose version of code. Takes input of `n` and `s` on separate lines. Explanation:

```
Ｎθ

```

Input `n`.

Move the cursor left one square to balance the right movement from the first iteration of the loop.

```
Ｆ⪪Ｓ «

```

Split the string on spaces and loop over the words.

```
¿‹⁺Ｌιⅈθ

```

Calculate whether the next word will reach the right edge.

```
Ｍ→

```

If it will not then move one square right.

```
⸿

```

If it will then start a new line.

```
ι

```

Output the word.
> 1 votes

# Answer
# JavaScript, 40 bytes

```
s=>n=>eval(`s.match(/.{1,${n}}( |$)/g)`)

```

Try it online!
> 1 votes

# Answer
# 05AB1E, 18 bytes

```
õs#vDy«g²›i,}yðJ}?

```

Try it online.

**Explanation:**

```
õ                   # Push an empty string "" to the stack
 s                  # Swap to take the (implicit) string input
  #                 # Split it by spaces
   v            }   # For-each `y` over the words:
    D               #  Duplicate the top of the stack
                    #  (which is the empty string in the very first iteration)
     y«             #  Append the current word `y`
       g            #  Get its length
        ²›i }       #  If its lengthy is larger than the second input:
           ,        #   Pop and output the current duplicated value with trailing newline
             yð     #  Push the word `y` and a space " "
               J    #  Join the entire stack together
                 ?  # After the loop, output the last part as well (without newline)

```
> 1 votes

# Answer
# Java 8, 135 bytes

```
n->s->{String r="",S[]=s.split(" "),t=r;for(int i=0;i<S.length;)if((t+S[i]).length()>n){r+=t+"\n";t="";}else t+=S[i++]+" ";return r+t;}

```

Try it online.

**Explanation:**

```
n->s->{                      // Method with integer & String parameters and String return
  String r="",               //  Result-String, starting empty
         S[]=s.split(" "),   //  Input-String split by spaces
         t=r;                //  Temp-String, starting empty as well
  for(int i=0;i<S.length;)   //  Loop `i` in the range [0, amount_of_words):
    if((t+S[i]).length()>n){ //   If `t` and the word are larger than the integer input:
      r+=t+"\n";             //    Add `t` and a newline to the result
      t="";}                 //    And reset `t` to an empty String
     else                    //   Else:
       t+=S[i++]+" ";        //    Append the word and a space to `t`
                             //    (and then increase `i` by 1 with `i++` for the next word
                             //     of the next iteration)
  return r+t;}               //  Return the result-String appended with `t` as result

```
> 1 votes

# Answer
Thanks to @Erik the Outgolfer, a golfed version :

# Python 3, 94 bytes

```
def f(t,n):
 while t:i=n+(t[min(len(t)-1,n)]==" "or-t[n-1::-1].find(' '));print(t[:i]);t=t[i:]

```

Try it online!

~~\# Python 3, 130 bytes~~

~~```
def f(t,n):
 l=[]
 while len(t):
  i=(n-t[:n][::-1].find(' '),n+1)[t[min(len(t)-1,n)]==" "]
  l.append(t[:i])
  t=t[i::]
 return l

```
Try it online!
~~

~~Not so golfed version...~~
> 0 votes

# Answer
# C# (Visual C# Interactive Compiler), 78 bytes

```
s=>n=>System.Text.RegularExpressions.Regex.Replace(s,".{1,"+n+"}( |$)","$0\n")

```

Try it online!

Credit goes to @LukeStevens for coming up with the Java version... Apparently .NET makes you import the `RegularExpressions` namespace in order to do a replace :(

Here is my original version that splits on the space character and uses LINQ to join them back together:

# C# (Visual C# Interactive Compiler), 91 bytes

```
s=>n=>s.Split(' ').Aggregate((a,w)=>a+(a.Length-a.LastIndexOf('\n')+w.Length>n?'\n':' ')+w)

```

Try it online!
> 0 votes

# Answer
# Jelly, 12 bytes

```
ḲŒṖK€€ḣ€ƑƇṪY

```

Try it online!

Unfortunately, this is too slow to work for the provided test case in under a minute over TIO.
> 0 votes

# Answer
# C# (.NET Core), 162 bytes

```
string[]t(string n,int a){var g="";for(int i=0;i++<Math.Floor((double)n.Length/a);)g+=$"^.{{{i*a-1}}}|";return Regex.Split(n,$@"(?n)(?<=({g.Trim('|')})\S*)\s");}}

```

This function uses a regex which matches the closest whitespace that is near the nth or multiple of nth character and splits the string based on it.

Try it online!

The TIO link is a full program, and the function has a static keyword so the function can be called from main.

Test Regex
> 0 votes

# Answer
# C, 63 bytes

```
b(a,n)char*a;{while(strlen(a)>n){for(a+=n;*a-32;--a);*a++=10;}}

```

The function of this exercise b(a,n) would break the line "a" as exercise said, in the way not change its length (if we see the result as one string) because change some spaces in \n or new line in place. The input string "a" should have no \n character too in it for b() function (it could have \n in input string for bs())

b(a,n) function would be ok only because the restriction of this exercise, that impose each word of "a" string has length \< n if this is not true, that function can go
to one infinite loop...(very wrong in my way of see so i copy too the function more good because in that case would return -1 and not would go to one infinite loop; it is bs(a,n) below)I not exclude both functions are bugged...

```
#define R(x,y) if(x)return y
#define U unsigned
U bs(char*a,U n)
{U c,q,r=1,i,j;
 R(!a||n<1||n++>0xFFFF,-1);
 for(j=c=i=0;;++i,++c)
    {R(i==-1,-1);q=a[i];
     if(q==10)goto l;
     if(c>=n){R(i-j>n,-1);a[i=j]=10;l:c=-1;++r;}
     R(!q,r);
     if(q==32)j=i;
    }
}

```

result of b() passed on one function that add line lenght each line

```
Lorem ipsum dolor sit amet, consectetur adipiscing [50]
elit. Sed eget erat lectus. Morbi mi mi, fringilla [50]
sed suscipit ullamcorper, tristique at mauris. [46]
Morbi non commodo nibh. Pellentesque habitant [45]
morbi tristique senectus et netus et malesuada [46]
fames ac turpis egestas. Sed at iaculis mauris. [47]
Praesent a sem augue. Nulla lectus sapien, auctor [49]
nec pharetra eu, tincidunt ac diam. Sed ligula [46]
arcu, aliquam quis velit aliquam, dictum varius [47]
erat. [5]

```
> 0 votes

# Answer
# Dart, 112 bytes

```
f(s,n){var l=[''];s.split(' ').forEach((w){if((l.last+w).length<=n)l.last+=w+' ';else l.add(w+' ');});return l;}

```

Try it online!
> 0 votes

# Answer
# APL(NARS), 48 chars, 96 bytes

```
{⊃⍵{⍺≥≢⍵:⊂⍵⋄k←1+⍺-' '⍳⍨⌽r←⍺↑⍵⋄(⊂k↑r),⍺∇k↓⍵}⍨⍺+1}

```

test:

```
  f←{⊃⍵{⍺≥≢⍵:⊂⍵⋄k←1+⍺-' '⍳⍨⌽r←⍺↑⍵⋄(⊂k↑r),⍺∇k↓⍵}⍨⍺+1}
  s←"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed eget erat lectus. Morbi mi mi, fringilla sed suscipit ullamcorper, tristique at mauris. Morbi non commodo nibh. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed at iaculis mauris. Praesent a sem augue. Nulla lectus sapien, auctor nec pharetra eu, tincidunt ac diam. Sed ligula arcu, aliquam quis velit aliquam, dictum varius erat."
  50 f s
Lorem ipsum dolor sit amet, consectetur adipiscing
elit. Sed eget erat lectus. Morbi mi mi, fringilla
sed suscipit ullamcorper, tristique at mauris.
Morbi non commodo nibh. Pellentesque habitant
morbi tristique senectus et netus et malesuada
fames ac turpis egestas. Sed at iaculis mauris.
Praesent a sem augue. Nulla lectus sapien, auctor
nec pharetra eu, tincidunt ac diam. Sed ligula
arcu, aliquam quis velit aliquam, dictum varius
erat.

```
> 0 votes

---
Tags: code-golf, string
---


title: Display Frames from .txt file

text:
# Question
Title: Display Frames from .txt file
# The Task:

Given a `.txt` file with frames of ASCII art each separated by a `\n` (see this example if you are unclear) output a motion picture with frame with 1 frame per second.

Note that there is a trailing `\n` on the final frame.

Each frames dimensions will be:

* X\<80
* Y\<20

# The Rules

* The Previous frame must be cleared before the next is displayed, so just printing each frame onto the terminal isn't a valid answer.
* **New** You can grab the file name however you want, either from it being stored in a variable or from sys args.
* **New** The images must Loop indefinitely
* This is code golf: smallest program wins.

# Example

### Input

```
0   0
0   0
00000
0   0
0   0

00000
0
00000
0
00000

0   0
 0 0
  0
  0
  0

```

### Output

### Un-golfed

```
import curses, time

stdscr = curses.initscr()

Frames = file.read(file('Frames.txt')).split('\n')
while True:
    y = 0
    for i in range(len(Frames)):
        stdscr.addstr(y,0,Frames[i])
        stdscr.refresh()
        y += 1
        if Frames[i] == '':
            y = 0
            stdscr.clear()
            time.sleep(1)

```

# Answer
> 10 votes
## Mathematica, 41 bytes

```
Import@f~StringSplit~"\n\n"~ListAnimate~1

```

Expects the file name to be stored in variable `f`.

This is the first time Mathematica's precedence rules for `@` and `.~.~.` are exactly the way I need them.

Btw, this snippet could go horribly wrong if the file extension is anything else than `.txt` (because Mathematica will try to guess how to do the import based on that), but luckily that file ending is part of the challenge specification.

# Answer
> 6 votes
## Bash, 82

```
IFS=
clear
for((;;)){
while read a;do
[ "$a" ]&&echo $a||(sleep 1;clear)
done<$1
}

```

Assumes the file name of the .txt file is provided as the first argument to the script.

Note that a trailing empty line must be present at the end of the .txt file for this to work.

Special thanks to @professorfish and @DigitalTrauma.

# Answer
> 4 votes
# Ruby, ~~88~~ ~~86~~ ~~56~~ 55 characters

```
$<.read.split($/*2).cycle{|i|system'cls';$><<i;sleep 1}

```

This program assumes the file name is given as the first argument.

Thanks a lot to Ventero for sharing great improvements!

Un-golfed:

```
$<.read.split($/*2).cycle{ |i|   # read file, split by two newlines, and loop
    system 'cls'   # clear screen
    $><<i   # print the current array item
    sleep 1   # sleep one second
}

```

This program reads the file, splits it into chunks, and prints each chunk separately after clearing the screen. `cls` only works on Windows. A variant with `clear` is 57 characters.

# Answer
> 2 votes
## Dyalog APL (64)

(Can't beat Mathematica this time. It seems to have a built-in for everything.)

```
{⎕ML←3⋄{⎕SM←1 1,⍨⊂⊃⍵⊂⍨~⍵∊⎕TC⋄⎕DL 1}¨M⊂⍨~(4/1)⍷⎕TC∊⍨M←80 ¯1⎕MAP⍵}

```

This is a function that takes the filename as its argument. It assumes the file is in Windows (`\r\n`) format.

Explanation:

* `⎕ML←3`: set migration level to 3 (allowing  to be used as APL2's split feature)
* `M←80 ¯1⎕MAP⍵`: read the file given by the right argument as an ASCII file, and store the contents in `M`.
* `M⊂⍨~(4/1)⍷⎕TC∊⍨M`: find all occurrences of four consecutive terminal control characters, and split `M` on those. This gives each frame.
* `{`...: for each of these...
    + `⊂⊃⍵⊂⍨~⍵∊⎕TC`: split the argument (=one frame) on terminal control characters, and then turn the vector-of-vectors into a matrix (so it will display each line on a separate line, this is necessary because `⎕SM` does not understand control characters.)
    + `⎕SM←1 1,⍨`: then display it in the upper left of the `⎕SM` window.
    + `⎕DL 1`: and then wait for one second.

# Answer
> 2 votes
# ~~Awk, 53~~

~~```
BEGIN{RS=RS RS}{system("clear")}1;{system("sleep 1")}

```~~

---

New rules:

# Awk, 74

```
BEGIN{RS=z}{a[NR]=$0}END{while(!system("sleep 1;clear"))print a[i++%NR+1]}

```

# Answer
> 1 votes
# Python 117

Assumes the file name is stored in variable `f`.

```
import time,os
while 1:
 for i in file.read(file(f)).split('\n'):
  print i
  if i=='':time.sleep(1);os.system('cls')

```

Note: replace `'cls'` with `'clear'` if on a unix based system, adding 2 chrs.

`ctl+C` to quit

# Answer
> 1 votes
## Perl, 40

```
seek ARGV,0,!eof;sleep 1;system clear

```

run as

```
perl -p00 frames.pl < animation.txt

```

(i.e. animation file is read through STDIN). 3 bytes for `p00` were added to count. It's 2 characters shorter i.e. **38** on Windows because of `cls` instead of `clear`. Or, to be portable:

```
seek ARGV,0,!eof;sleep 1;system$^O=~/Win/?cls:clear

```

Or, stretching rules a bit (and then 31+3=**34**):

```
seek ARGV,sleep(1)&`reset`,!eof

```

# Answer
> 1 votes
# Rebol, 74

```
forever[foreach s split to-string read f"^/^/"[call"clear"print s wait 1]]

```

Expects the filename to be stored in variable `f`. Below is an ungolfed example:

```
f: %ascii-art.txt

forever [
    foreach s split to-string read f "^/^/" [
        call "clear"
        print s
        wait 1
    ]
]

```

# Answer
> 1 votes
**Java, 678 characters(when golfed)**

Of course with GUI, since doing stuff in console sucks with Java, especially if you want to clear the screen ...

```
import java.awt.Font;
import java.io.File;
import java.util.Scanner;

import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.SwingWorker;

public class G extends JFrame
{
    static JTextArea b = new JTextArea();

    G()
    {
        setSize(170, 370);

        add(b);
        b.setFont(new Font(Font.MONOSPACED, 0, 50));
    }

    public static void main(final String[] args)
    {
        new G().setVisible(true);
        new SwingWorker()
        {
            protected Void doInBackground()
            {
                for(;;)
                {
                    try(Scanner s = new Scanner(new File(args[0])))
                    {
                        String l = null;
                        while(s.hasNextLine())
                        {
                            if(l == null  || (l = s.nextLine()).isEmpty())
                            {
                                Thread.sleep(1000);
                                b.setText(l == null ? (l = s.nextLine()) + '\n' : null);
                            }
                            else
                                b.setText(b.getText() + l + '\n');
                        }
                    }
                    catch(Exception i){}
                }
            }
        }.execute();
    }
}

```

# Answer
> 1 votes
# Cobra - 163

```
class P
    def main
        while 1
            for i in File.readAllLines("t.txt")
                print i
                if i=="",.x
            .x
    def x
        Threading.Thread.sleep(1000)
        Console.clear

```

# Answer
> 0 votes
## Groovy - 121 119 chars

Ported ProgramFOX's answer to Groovy 2.2.1. The "clear console" is weak.

***edit***: replaced recursive closure with simple while loop, which is shorter and no stack overflow

```
a=new File(args[0]).text.split "\n\n";i=0;p={println it};while(1){p a[i++%a.size()];Thread.sleep(1000);80.times{p ""}}

```

Ungolfed:

```
a = new File(args[0]).text.split "\n\n"
i = 0

p = { println it }

while(1) {
    p a[i++%a.size()]
    Thread.sleep(1000)
    80.times{p ""}
}

```

# Answer
> 0 votes
# Groovy, 81

This is a more groovy way:

```
new File(args[0]).text.split("\n\n").each{["cls"].execute();print it;sleep(1000)}

```

ungolfed

```
new File(args[0]).text.split("\n\n").each{
    ["cls"].execute()
    print it
    sleep(1000)
}

```

# Answer
> 0 votes
# GNU sed, 32

```
1eclear
/^$/{
esleep 1;clear
d
}

```

# Answer
> 0 votes
# C# 226

Why bother eh?

```
namespace System{class P{static void Main(){for(;;)foreach(var x in Text.RegularExpressions.Regex.Split(new IO.StreamReader("f.txt").ReadToEnd(),"\n\r\n")){Console.Clear();Console.WriteLine(x);Threading.Thread.Sleep(1000);}}}}

```

**Un-golfed**:

```
namespace System
{
    class P
    {
        static void Main()
        {
            for(;;)
            foreach (var x in Text.RegularExpressions.Regex.Split(new IO.StreamReader("f.txt").ReadToEnd(), "\n\r\n"))
            {
                Console.Clear();
                Console.WriteLine(x);
                Threading.Thread.Sleep(1000);
            }
        }
    }
}

```

---

Or in LINQPAD (so C# can stay semi-competitive with uber shorthand langs :D)

**C# LINQPAD - 134**

```
for(;;)foreach(var x in Regex.Split(new StreamReader("f.txt").ReadToEnd(),"\n\r\n")){x.Dump();Thread.Sleep(1000);Util.ClearResults();}

```

I feel a bit dirty, but hey, this is code-golf.

# Answer
> 0 votes
# SmileBASIC, 74 bytes

```
F=LOAD(F)@L
IF" "*!CSRX>F[I]THEN WAIT 60CLS
?F[I];
I=(I+1)MOD LEN(F)GOTO@L

```

F should be the file name

---
Tags: code-golf
---


title: Satisfying Rounding

text:
# Question
Title: Satisfying Rounding
# Satisfying Rounding

You know when you're in science class, and asked to round to 2 sig figs, but your answer is `5.2501...`? You should round to `5.3`, but that's just so unsatisfying! By rounding to `5.3`, you're off by a whole 0.05, which is a large amount compared to 0.1 (the place value you're rounding to)! So help me round in a satisfying way.

To round in a satisfying way, you must round at the first digit you come across that produces a relatively small error - less than half of the maximum error possible when rounding. Basically, you need to round whenever you encounter 0, 1, 8, or 9. If that never happens, return the input as is. Do not round on leading zeroes or ones - that just doesn't feel satisfying.

# Input

A string or float value that represents a nonnegative decimal number.

# Output

The same decimal number rounded satisfactorily, in either string or float format.

# Examples

```
Input -> Output
0 -> 0
0.5 -> 0.5
0.19 -> 0
0.8 -> 1
5.64511 -> 5.645
18.913 -> 20
88.913 -> 100
36.38299 -> 36.4
621 -> 620
803.22 -> 1000
547.4726 -> 547.4726

```

This is a challenge, so shortest code wins!

# Answer
> 2 votes
# JavaScript (ES6),  ~~100 99 98~~  78 bytes

Takes input as a string. Returns a float.

```
s=>+(0+s).replace(/\d/g,(d,i)=>j&&+d+((n=s[i+!++s[i]])<2&&i?--j:n>7&&j--),j=1)

```

Try it online!

### How?

We first prepend a leading \\$0\\$ to the input string, so that we're guaranteed to have a digit before a possible leading \\$8\\$ or \\$9\\$, that must trigger the rounding right away.

The flag \\$j\\$ is set to \\$1\\$ as long as we are looking for a digit on which we can do a satisfying rounding, and set to \\$0\\$ afterwards.

Because a leading \\$0\\$ was added to the string that we're walking through but \\$s\\$ was left unchanged, \\$d\\$ contains the current character and \\$s\[i\]\\$ is pointing to the *next* character.

We use the following code to load the next digit in \\$n\\$, skipping a possible decimal separator:

```
n = s[i + !++s[i]]

```

Although strings are immutable in JavaScript, the expression `++s[i]` will return \\$s\[i\]+1\\$ if it contains a numeric value, even though \\$s\[i\]\\$ is not actually incremented. Therefore, the expression `!++s[i]` is evaluated to \\$false\\$ (coerced to \\$0\\$) for all digits (including \\$0\\$) and to \\$true\\$ (coerced to \\$1\\$) for the decimal separator `"."`.

When the rounding occurs, we yield `d + --j` if the next digit \\$n\\$ is \\$0\\$ or \\$1\\$ (and it's not the leading digit of the original input) and `d + j--` if \\$n\\$ is \\$8\\$ or \\$9\\$. Therefore, \\$j\\$ is set to \\$0\\$ in both cases but we add \\$0\\$ to \\$d\\$ in the first case (rounding down) and \\$1\\$ in the second case (rounding up).

# Answer
> 2 votes
# Ruby, ~~79~~ ~~77~~ ~~69~~ ~~67~~ 65 bytes

```
->n,z=n+".0"{z[i=z=~/\./]='';n.to_f.round (z=~/(?!^)[01]|8|9/)-i}

```

Try it online!

### Explanation

* `->n` Take input as a string
* `z=n+".0"` Create a temporary string `z` that is guaranteed to contain a dot and a relevant digit.
* `i=z=~/\./` Determine the position of the decimal dot in `z` and assign to `i`.
* `z[i]=''` Drop the dot so that it doesn't get in the way further on.
* `z=~/(?!^)[01]|8|9/` Determine the position of non-starting `0-1` or any `8-9`, whichever comes first.
* `(...)-i` This difference will be the number of decimal places to keep, negative if we will be rounding left of the dot.
* `n.to_f.round ...` Convert to float and do the rounding.

# Answer
> 1 votes
# Jelly, 34 bytes

```
;”.ḟ$µ»"”2e€⁽¡XṾ¤;1i1_i”.$_>¥0ɓVær

```

Try it online!

-1 thanks to Jonathan Allan.

# Answer
> 1 votes
# Jelly,  ~~30~~  29 bytes

-1 thanks to Erik the Outgolfer (use of dyadic quick `¥` from his answer)

```
O;0µ_8H1¦%8ỊTḢ_<48TḢƊ_>¥0ɓVær

```

A monadic link accepting a list of characters which yields a float.

**Try it online!** Or see the test-suite.

### How

First note that the input string is made exclusively from the characters `0123456789.` which have ordinals `[48,49,50,51,52,53,54,55,56,57,46]`, which have remainders when divided by eight of `[0,1,2,3,4,5,6,7,0,1,6]`. The only characters which are between `-1` and `1` inclusive are `0`, `1`, `8`, and `9`.

Furthermore if we subtract eight from the ordinals (`[40,41,42,43,44,45,46,47,48,49,38]`) the same (fairly obviously) holds. If we halve these (`[20,20.5,21,21.5,22,22.5,23,23.5,24,24.5,19]`) the only characters which have remainders when divided by eight which are between `-1` and `1` inclusive are `8` and `9`.

```
O;0µ_8H1¦%8ỊTḢ_<48TḢƊ_>¥0ɓVær - Link: list of characters, S
O                             - ordinal (vectorises across S)
 ;0                           - concatenate a zero
                              - (to cater BOTH for no '0', '1', '8', or '9' AND for no '.')
   µ                          - start a new monadic link (call that X)
    _8                        - subtract eight (vectorises across X)
        ¦                     - sparse application...
       1                      - ...to: indices: one
      H                       - ...do: halve (i.e. halve first ordinal)
         %8                   - modulo by eight (vectorises)
           Ị                  - insignificant (abs(v)<=1?) (vectorises)
            T                 - truthy indices
             Ḣ                - head
                    Ɗ         - last three links as a monad (i.e. f(X)):
               <48            -   less than 48? (i.e. was it a '.' in S or the added 0?)
                  T           -   truthy indices
                   Ḣ          -   head
              _               - subtract
                       ¥      - last two links as a dyad
                      < 0     -   less than zero? (1 if so 0 otherwise)
                     _        -   subtract
                         ɓ    - start a new dyadic chain (i.e. f(S,X))
                          V   - evaluate S as Jelly code (i.e. get S as a float)
                           ær - round to the nearest multiple of 10^(-X)

```

# Answer
> 1 votes
# Retina 0.8.2, 75 bytes

```
^[89]
10
T`d`0`(?<=.)[01].*|(?<=8|9).*
T`89d`0d`.\.?[89]
(\.|(\..+?))0+$
$2

```

Try it online! Link includes test cases. Explanation:

```
^[89]
10

```

Handle the case of a leading `8` or `9`.

```
T`d`0`(?<=.)[01].*|(?<=8|9).*

```

If there's a non-leading `0` or `1`, then zero it and the rest of the string out. Also, if there's an `8` or `9`, then leave it, but zero out the rest of the string. (But leave the decimal point unchanged in either case.)

```
T`89d`0d`.\.?[89]

```

If there's still an `8` or a `9` at this point, then zero it out, and increment the preceding digit (possibly before the decimal point).

```
(\.|(\..+?))0+$
$2

```

Delete trailing zeros if they are after a decimal point, but only delete the decimal point if there are no other digits in between.

# Answer
> 1 votes
# C (gcc), ~~111~~ 102 bytes

```
g(_,i,j,k)char*_;{for(i=*_<56?*_++:48,j=3;j;j&=k%8>1|(i=*_++)/48*2)putchar(j&1?i+(k=_[*_<48])/56:48);}

```

Try it online!

```
//_: input, as string
//i: current digit, rounded if applicable
//j: tracks whether number is rounded, and whether \0 or '.' has been encountered
//k: digit to test rounding (round if k is one of 0,1,8,9)
//'0'==48, '8'==56
g(_,i,j,k)char*_;{
    for(i=*_<56?*_++:48,j=3;                //special case: if first digit is 8 or 9, use a
                                            //placeholder digit with value 0. initialize j.
        j;                                  //only stop execution when number is rounded and
                                            //'.' or \0 has been encountered.
        j&=k%8>1|(i=*_++)/48*2)             //check if execution should stop.
        putchar(j&1?i+(k=_[*_<48])/56:48);  //print '0' if rounding had already been done;
                                            //otherwise, print digit. round up as needed.
}

```

# Answer
> 0 votes
# C# (Visual C# Interactive Compiler), 280 bytes

```
c=>{int d=c.IndexOf('.');int t=c.IndexOfAny(new char[]{'8','9','0','1'},1);var m=c[0]=='8'||c[0]=='9'?1>0:0>1;var z=decimal.Parse(c);Func<decimal>q=()=>(decimal)Math.Pow(10,m?d<0?c.Length:d:d<0?c.Length-t:d>t?d-t:d-t+1);return m?Math.Round(z/q())*q():t<0?z:Math.Round(z/q())*q();}

```

Try it online!

It can be shorter if I used doubles instead of decimals, but I used decimals to preserve accuracy, or else a number like 547.4726 would be 547.472595214844.

# C# (Visual C# Interactive Compiler), 268 bytes

```
c=>{int d=c.IndexOf('.');int t=c.IndexOfAny(new char[]{'8','9','0','1'},1);var m=c[0]=='8'||c[0]=='9'?1>0:0>1;var z=float.Parse(c);Func<double>q=()=>Math.Pow(10,m?d<0?c.Length:d:d<0?c.Length-t:d>t?d-t:d-t+1);return m?Math.Round(z/q())*q():t<0?z:Math.Round(z/q())*q();}

```

Try it online!(Less accurate version)

---
Tags: code-golf, number, rational-numbers
---


# Question
Title: Given a number, program must return the alphabet letter correspondent
## The program

Given a number, program must return the alphabet letter correspondent.

## Rules

* The challenge here is to make it as short as possible, everyone knows it is a very easy program to do.
* The number is not zero-based, it means `1` is `A`, `2` is `B`, `3` is `C` and so it goes...
* Any language will be accepted.

# Answer
> 2 votes
# DC - 6 characters

*Full program* including input and output.

```
?64+af

```

save to file and run with `$ dc file`

# Answer
> 7 votes
## APL (4)

(Full program)

```
⎕⌷⎕A

```

Explanation:

(user input)  (index) `⎕A` (alphabet)

(They're supposed to be boxes, it's not an encoding problem.)

# Answer
> 7 votes
# Brainfuck, 107 bytes

```
>,----------[>++++++[-<------>],----------]<[<]>>[<--[->++++++++++<]>>]+++++++[-<+++++++++>]<-.>++++++++++.

```

# Answer
> 3 votes
# brainfuck, ~~64 56~~ 50 bytes

*Thanks to Dorian for saving 3 bytes and inspiring 3 more*

```
,>,[<+[-<+>[-<]>>]<[<++<-]>++>>]<<+++[->+++++<]>+.

```

Try it online!

## How it works

```
,>, Gets input
   [ if a two digit number
    <+[-<+>[-<]>>] Gets modulo 2 of first number plus 1
                  <[<++<-] Sets the fives cell to 2 if the first number is a 2
                          >++ Adds another 2 to the fives cell
                             >>]  Moves to cell after ones cell
                                <<+++ Adds 3 to fives cell
                                     [->+++++<] Multiply the fives cell by 5 and add it to the ones cell
                                               >+.  Add one and print

```

# Answer
> 2 votes
## R, 11 characters

```
LETTERS[x]

```

Usage:

```
LETTERS[21]
[1] "U"

```

# Answer
> 2 votes
# Befunge-93, ~~7~~ 6 bytes

```
"&++,@

```

Try it online!

Takes advantage of the extra spaces at the end of a wrapping string literal by adding two spaces (`32*2 = 64`) to the inputted number to turn it into the corresponding alphabetic character. Funnily enough, if we use a implementation that doesn’t include the wrapping spaces, we can do `"&+.@` to add the `@` (64) to the number instead.

# Answer
> 1 votes
## J, 7 characters

```
a.{~64+

```

Usage:

```
   a.{~64+1
A

```

# Answer
> 1 votes
# Perl, 20 characters

```
chr(($ARGV[0] + 64))

```

Verification :

```
risk@skynet:~/perl$ for x in {1..26}; do perl ./ord.pl $x; done;
ABCDEFGHIJKLMNOPQRSTUVWXYZrisk@skynet:~/perl$

```

# Answer
> 1 votes
# TI-Basic, 34 bytes

```
sub("ABCDEFGHIJKLMNOPQRSTUVWXYZ",Ans,1

```

This is as short as it gets...

# Answer
> 1 votes
# PHP, 17 bytes

```
<?=chr(64+$argn);

```

Run s pipe with `-F`

# Answer
> 1 votes
# MATL, 4 bytes

```
64+c

```

Try it online!

Because, why not. Takes input implicitly, pushes `64` and adds it to the input number. Finally it converts the number to its ASCII-equivalent using `c`.

# Answer
> 1 votes
# Pyth - ~~5~~ 3 Bytes

```
@Gt

```

Saved two bytes thanks to ovs

Completely forgot about `t` and implicit `Q`

Explanation:

```
@    Index
 G   in alphabet of
  t  one less than
   Q Input (implicitly added to solve arity)

```

# Answer
> 1 votes
# Ly, 6 bytes

```
n8:*+o

```

Try it online!

# Answer
> 1 votes
# Husk, 4 bytes

```
c+64

```

Try it online!

Boring, but probably optimal. Adds 64 to the given number and converts it to ASCII. `!¡→'A` is cuter (awww, the exclamation marks are friends!) but one byte longer.

# Answer
> 1 votes
# Hexagony, 10 Bytes

Try it online!

```
A({/'+;?/@

```

Expanded:

```
  A ( {
 / ' + ;
? / @ . .
 . . . .
  . . .

```

This honestly took me way longer than it should have, as it's just 2 simple reflections.

---

The simplest version for this problem is only 2 bytes longer
```
  A ( {
 . . . .
? ' + ; @
 . . . .
  . . .

```

# Answer
> 1 votes
# PowerShell, 19 18 bytes

-1 byte thanks to @mazzy lol
I don't think it'll get much shorter than this.

```
[char](64+"$args")

```

Try it online!

Takes input from a command line argument.

# Answer
> 1 votes
# Powershell 6, 17 bytes

```
('@'..'Z')[$args]

```

# Answer
> 0 votes
# q/k (7)

As partially applied composition:

```
10h$64+

```

# Answer
> 0 votes
## Ruby 1.9 (10)

```
(x+64).chr

```

Reading from STDIN and printing to STDOUT:

```
$><<(gets.to_i+64).chr

```

# Answer
> 0 votes
# Burlesque (6 characters)

Assuming the number is already on the stack:

```
64.+L[
```
(see here in action.).

Does the usual: Add 64, convert to character based on ASCII value.

If number is supplied as a string via stdin to stdout (10 characters):

```
ri64.+L[sh
```

Alternative version without using ASCII value conversion:

```
'@'Zr@\/!!
```

# Answer
> 0 votes
# Python 2, 9 bytes

```
chr(64+x)

```

### Or, reading from stdin and printing to stdout: 21

```
print chr(64+input())

```

# Answer
> 0 votes
# GolfScript, 7

```
64+]''+

```

### Commentary

```
64    # corresponds to '@' in ASCII (65 is 'A')
+]    # add the input to 64. ']' is used for ASCII.
''+   # the conversion process

```

**1 corresponds to A**

**26 corresponds to Z**

# Answer
> 0 votes
## Javascript, 25 chars

```
String.fromCharCode(66-x);

```

## PHP, 22 chars

```
echo chr(66-$argv[0])

```

# Answer
> 0 votes
# Classic ASP (14 bytes):

```
<%=Chr(c+64)%>

```

*Expects `c` to hold the character number.*

# Answer
> 0 votes
**C#** 4,50KB (196 characters)

My first time here =)

```
using System; namespace W { class P { static void Main(string[] args) {
            Console.WriteLine(" abcdefghijklmnopqrstuvwxyz".ToCharArray()[int.Parse(Console.ReadLine())]);
        }
    }
}

```

# Answer
> 0 votes
# Haskell, 38 bytes

```
main = putChar $ ('a':['a'..'z']) !! c

```

Where `c` is the number.

# Answer
> 0 votes
# C#, 87

```
class P{static void Main(string[]a){System.Console.Write((char)(int.Parse(a[0])+64));}}

```

Complete program (not some (part of a) "function" expecting foo to be bar to work), accepts command line parameter: `foo.exe 1` prints `A`, `foo.exe 16` prints `P`

# C#, 10

When I make the same assumptions as, for example, the 'code-golfers' that posted the ~~VSCript~~ Classic ASP, Python, Burlesque, Ruby,  solutions we can get it down to 10:

```
(char)x+64

```

"Assuming `x` is magically initialized / passed in / on the stack / whatever excuse" and the contest doesn't explicitly require me to print it, just "return" it (which most of the above solutions don't do, either).

# Answer
> 0 votes
# Tcl, 30 bytes

```
puts [expr [scan $argv %c]-64]

```

Try it online!

# Answer
> 0 votes
BrainFuck, 66

```
,>,----------[<[->++++++++++<]++++++[>+++++++<-]>>]++++[<++++>-]<.

```

# Answer
> 0 votes
# Jelly, 3 bytes

```
ịØA

```

Try it online!

# Answer
> 0 votes
# SmileBASIC, 18 bytes

```
INPUT N?CHR$(N+64)

```

# Answer
> 0 votes
# Java 8, 15 bytes (as lambda function)

```
n->(char)(n+64)

```

Try it online.

# Java 8, 84 bytes (as full program)

```
interface M{static void main(String[]a){System.out.printf("%c",new Byte(a[0])+64);}}

```

Try it online.

# Answer
> 0 votes
# Haskell, 11 bytes

```
(['@'..]!!)

```

Try it online! This anonymous function indexes into the string `"@ABCDEFG ..."`.

# Answer
> 0 votes
# Fortran (GFortran), 30 bytes

```
READ*,I
PRINT*,ACHAR(I+64)
END

```

My entry in the good ol' Fortran.

Try it online!

# Answer
> 0 votes
# **FORTH 16 BYTES**

```
: n 64 + EMIT ;

```

**OUTPUT:**

```
8 N
8 N H ok
5 N
5 N E ok
12 N
12 N L ok
12 N
12 N L ok
15 N
15 N O ok
23 N
23 N W ok
15 N
15 N O ok
18 N
18 N R ok
12 N
12 N L ok
4 N
4 N D ok

```

# Answer
> 0 votes
# Tcl, 31 bytes

```
puts [format %c [incr argv 64]]

```

Try it online!

# Answer
> 0 votes
# Japt, 2 bytes

```
dI

```

Try it or test all numbers

# Answer
> -1 votes
# PHP 442

```
$alphabet = Array('A' => 1,'B' => 2,'C' => 3,'D' => 4,'E' => 5,'F' => 6,'G' => 7,'H' => 8,
'I' => 9,'J' => 10,'K' => 11,'L' => 12,'M' => 13,'N' => 14,'O' => 15,'P' => 16,'Q' => 17,
'R' => 18,'S' => 19,'T' => 20,'U' => 21,'V' => 22,'W' => 23,'X' => 24,'Y' => 25,'Z' => 26
)

function testInputForAlphabetCharacter($input){
    for($index = 0; $index < count($alphabet); $i = $i + 1){
        if($alphabet[$index] == $input){
            echo($index);
        }
    }
}

$input = $_GET['input'];
testInputForAlphabetCharacter($input);

```

---
Tags: code-golf, number
---


title: Organize Your Christmas Party!

text:
# Question
Title: Organize Your Christmas Party!
Christmas is coming up, and this year you have been charged with organizing your family's christmas get-together. You have a list of foods you want be there, but before you assign foods to people, you need to know who's coming. So...

# Challenge

Given an input of relative's names separated by commas or whatever (note that the names may have spaces in them, e.g. "Aunt Gertrude") and a list of meals including turkey, divide the meals among them equally, but saving the turkey and any extra for yourself, because you don't want to be unfair. In other words, if 6 people are coming and there are 10 meals, you have to do the turkey and 3 others, because 6 goes into 9 once, leaving 4 for you. Input will never have more people than meals.

# Full list of possible dishes (Taken from Wikipedia)

```
Apple Cider
Boiled Custard
Candy canes
Champagne
Chocolate fudge
Christmas cookies
Cranberry sauce
Eggnog
Fish
Fruitcake
Gingerbread Men
Christmas ham
Hot buttered rum
Hot chocolate
Mashed potato
Mixed nuts
Oyster stew
Persimmon pudding
Apple pie
Pecan pie
Pumpkin pie
Sparkling cider
Stuffing
Sweet potato pie
Sweet potato casserole with marshmallow
Russian tea cakes
Tom and Jerry
Turkey

Here is a formatted version if you prefer:
["Apple Cider","Boiled Custard","Candy canes","Champagne","Chocolate fudge","Christmas cookies","Cranberry Sauce","Eggnog","Fish","Fruitcake","Gingerbread Men","Christmas Ham","Hot buttered rum","Hot chocolate","Mashed potato","Mixed nuts","Oyster stew","Persimmon pudding","Apple pie","Pecan pie","Pumpkin pie","Sparkling cider","Stuffing","Sweet potato pie","Sweet potato casserole with marshmallow","Russian tea cakes","Tom and Jerry","Turkey"]

```

# Name format

Relative's names will take any of the following formats

```
Aunt x
Uncle x
Creepy Uncle x
Grandpa x
Grandma x
Cousin x
Mother-in-law x
Father-in-law x
Papa x
Nana x
x
x can be any 20 char or less combination of upper/lower case letters

```

# I/O

**Input** can be taken in any reasonable, convenient format, but I will assume list if not otherwise specified: \[relative a,b,c\],\[food x,y,z\]

**Output** can also be in any reasonable convenient format, I personally prefer a list of lists You do **not** need to output the turkey or extra meals

# Examples

```
["Aunt Gertrude", "Cousin Sally", "Grandpa Joe", "Creepy Uncle Rick"],["Sparkling Cider", "Pumpkin Pie", "Pecan Pie", "Oyster Stew", "Chocolate Fudge", "Turkey"] -> [["Aunt Gertrude","Sparkling Cider"],["Cousin Sally", "Pumpkin Pie"],["Grandpa Joe","Pecan Pie"],["Creepy Uncle Rick","Oyster Stew"]]

["Aunt getoFFmyLAWn","Grandpa Lipbalm","Cousin onlyplaysroblox","Papa losthisjob"],["Pumpkin pie","Sparkling cider","Stuffing","Sweet potato pie","Sweet potato casserole with marshmallow","Russian tea cakes","Tom and Jerry"] -> [['Aunt getoFFmyLAWn', 'Pumpkin pie'], ['Grandpa Lipbalm', 'Sparkling cider'], ['Cousin onlyplaysroblox', 'Stuffing'], ['Papa losthisjob', 'Sweet potato pie']]

```

As christmas is almost here, you don't have time to be planning more than needed, so use those skills and program up some lists!

# Notes

* No standard loopholes
* If you have only a function, please provide code to call it as well
* Please provide an explanation
* Smallest byte count ~ 2-3 days after Christmas wins!

# Answer
> 3 votes
# Jelly, 17 bytes

I went off-piste with the meals in my example without realising! It shouldn't matter I think, and looks tastier to my British eyes.

```
ḟ“Øẇ½»W¤s⁹L‘¤ṖZṖż

```

A dyadic link taking a list of foods (lists of characters) on the left and people (also lists of characters) on the right which returns a list containing a list per person containing a list of characters (their name) and a list of foods (each a list of characters).

e.g. (using `"..."` to represent a list of characters):

```
left = ["Champagne", "Turkey", "Stuffing", "Port", "Roast Potatoes", "Brussel Sprouts", "Parsnips", "Pigs In Blankets", "Gravy", "Steamed Vegetables", "Cheese Plate", "Christmas Pudding"]
right = ["Aunt Gertrude", "Cousin Sally", "Grandpa Joe"]

output = [[["Champagne", "Brussel Sprouts"],"Aunt Gertrude"],[["Stuffing", "Parsnips"],"Cousin Sally"],[["Port", "Pigs In Blankets"],"Grandpa Joe"]]

(leaving us with Turkey, Roast Potatoes, Gravy, Steamed Vegetables, and Christmas Pudding.)

```

**Try it online!** (The footer calls the dyadic link and then pretty prints the result)

### How?

```
ḟ“Øẇ½»W¤s⁹L‘¤ṖZṖż - Link: foods, people
            ¤     - nilad followed by link(s) as a nilad:
         ⁹        -   chain's right argument, people
          L       -   length
           ‘      -   increment (add yourself to the cook count)
       ¤          - nilad followed by link(s) as a nilad:
 “Øẇ½»            -   compressed string = list of characters, ['T','u','r','k','e','y']
      W           -   wrap in a list                          [['T','u','r','k','e','y']]
ḟ                 - filter discard (from foods) if exists in that list (we cook any Turkey)
        s         - split (the resulting list of foods) into chunks (of number of cooks)
             Ṗ    - pop off the excess
              Z   - transpose to a list of fair shares
               Ṗ  - pop off our share
                ż - zip with people names (to provide the allocations)

```

# Answer
> 1 votes
# Operation Flashpoint scripting language, 155 bytes

```
f={t=_this;a=t select 0;b=(t select 1)-["Turkey"];i=0;d=count a;e=count b;c=e/d;c=c-c%1;while{i<c*d}do{a set[i%d,(a select i%d)+","+(b select i)];i=i+1};a}

```

**Call with:**

```
array = [["Aunt Gertrude", "Cousin Sally", "Grandpa Joe", "Creepy Uncle Rick"],["Sparkling Cider", "Pumpkin Pie", "Pecan Pie", "Oyster Stew", "Chocolate Fudge", "Turkey"]];
hint format["%1", array call f]

```

**Output:**

# Answer
> 0 votes
# PHP, 112 bytes

```
function($p,$f){return array_combine($p+[($n=count($p))=>0],array_chunk(array_diff($f,[Turkey]),count($f)/$n));}

```

anonymous function, takes an array of people and an array of meals,
returns an associative array `name=>array of meals` plus one element `0=>extra meals` (without the Turkey).

Try it online.

---
Tags: code-golf, sorting
---