title: April Fools Day!

text:
# Question
Title: April Fools Day!
Your challenge is simple: write a program or function which appears to print the first ten numbers of any integer sequence (on OEIS, the answerer may choose which sequence), but instead prints the exact text:

```
Happy April Fool's Day!

```

if and only if it is run on April 1st of any year. Run on any other day should make it output its original output. (Unfortunately, I was a little late posting this challenge). Answers should be voted up for clever hiding of the April fools part.

This is a , so the answer with the most votes on May 8th wins!

# Answer
> 5 votes
# TI-Basic (TI-84 Plus CE)

```
{1001,10,1}→<sub>L</sub>A
{1010,1,1}→<sub>L</sub>A
{1011,11,1}→<sub>L</sub>B
{1020,2,1}→<sub>L</sub>C
{1021,12,1}→<sub>L</sub>D
{1030,3,1}→<sub>L</sub>E
{1040,4,1}→<sub>L</sub>F
{1050,5,1}→<sub>L</sub>G
{1060,6,1}→<sub>L</sub>H
{1070,7,1}→<sub>L</sub>I

getDate→L<sub>1</sub>

IF L<sub>1</sub>(2)=<sub>L</sub>A(2) and L<sub>1</sub>(3)=<sub>L</sub>A(3):Then
"Happy October First!"
End
IF L<sub>1</sub>(2)=<sub>L</sub>B(2) and L<sub>1</sub>(3)=<sub>L</sub>B(3):Then
"Happy New Year!"
End
IF L<sub>1</sub>(2)=<sub>L</sub>C(2) and L<sub>1</sub>(3)=<sub>L</sub>C(3):Then
"Happy November First!"
End
IF L<sub>1</sub>(2)=<sub>L</sub>D(2) and L<sub>1</sub>(3)=<sub>L</sub>D(3):Then
"Happy February First!"
End
IF L<sub>1</sub>(2)=<sub>L</sub>E(2) and L<sub>1</sub>(3)=<sub>L</sub>E(3):Then
"Happy December First!"
End
IF L<sub>1</sub>(2)=<sub>L</sub>F(2) and L<sub>1</sub>(3)=<sub>L</sub>F(3):Then
"Happy March First!"
End
IF L<sub>1</sub>(2)=<sub>L</sub>G(2) and L<sub>1</sub>(3)=<sub>L</sub>G(3):Then
Disp "Happy April Fool's Day!"
Return:End
IF L<sub>1</sub>(2)=<sub>L</sub>H(2) and L<sub>1</sub>(3)=<sub>L</sub>H(3):Then
"Happy May First!"
End
IF L<sub>1</sub>(2)=<sub>L</sub>I(2) and L<sub>1</sub>(3)=<sub>L</sub>I(3):Then
"Happy June First!"
End
IF L<sub>1</sub>(2)=<sub>L</sub>J(2) and L<sub>1</sub>(3)=<sub>L</sub>J(3):Then
"Happy July First!"
End

ClrHome
Output(1,1,toString(10000<sub>L</sub>A(1)+100<sub>L</sub>A(2)+<sub>L</sub>A(3)))
Output(2,1,toString(10000<sub>L</sub>B(1)+100<sub>L</sub>B(2)+<sub>L</sub>B(3)))
Output(3,1,toString(10000<sub>L</sub>C(1)+100<sub>L</sub>C(2)+<sub>L</sub>C(3)))
Output(4,1,toString(10000<sub>L</sub>D(1)+100<sub>L</sub>D(2)+<sub>L</sub>D(3)))
Output(5,1,toString(10000<sub>L</sub>E(1)+100<sub>L</sub>E(2)+<sub>L</sub>E(3)))
Output(6,1,toString(10000<sub>L</sub>F(1)+100<sub>L</sub>F(2)+<sub>L</sub>F(3)))
Output(7,1,toString(10000<sub>L</sub>G(1)+100<sub>L</sub>G(2)+<sub>L</sub>G(3)))
Output(8,1,toString(10000<sub>L</sub>H(1)+100<sub>L</sub>H(2)+<sub>L</sub>H(3)))
Output(9,1,toString(10000<sub>L</sub>I(1)+100<sub>L</sub>I(2)+<sub>L</sub>I(3)))
Output(10,1,toString(10000<sub>L</sub>J(1)+100<sub>L</sub>J(2)+<sub>L</sub>J(3)))

```

Uses OEIS A210884.

Stores the numbers as dates and converts them on-the-fly to output. It even leaves you a message in `Ans` if today is one of the dates!

# Answer
> 5 votes
# C

I use some fun CLANG properties to do tricky math and print the text sneakishly. I am printing the sequence of even numbers 0,2,4,6 etc up to 42.

This is a nice solution because I don't use any letters or hard coded strings, just pure math trickery to end up outputting the desired text even though it appears to a human brain that this should just be outputting 0,2,4,6,etc

Try it online! (Just the sneaky April Fools Day version)

```
#define printNumber(x) printf("%c", x)

main() {

    SYSTEMTIME st;
    GetLocalTime(&st);
    BOOL isFunDay = (st.wDay == 4 && st.wDay == 1);

    if (isFunDay) {
        printEvenNumbersTheFunWay();//fun way for a fun day!
    } else {
        printSomeEvenNumbersTheBoringWay();
    }

}

printEvenNumbersTheFunWay() {

    //print sequence: 0,2,4,6,8,10,12,14...42

    //print 0
    #define zero 72-72
    printNumber(2*zero+0);

    //print 2
    #define zero 5-5
    printNumber(20*zero+2);

    //print 4
    #define zero 108-108
    printNumber(2*zero+4);

    //print 6
    #define zero 106-106
    printNumber(2*zero+6);

    //print 8
    #define zero 113-113
    printNumber(2*zero+8);

    //print 10
    #define zero 22-22
    printNumber(2*zero+10);

    //print 12
    #define zero 53-53
    printNumber(2*zero+12);

    //print 14
    #define zero 98-98
    printNumber(2*zero+14);

    //print 16
    #define zero 98-98
    printNumber(2*zero+16);

    //print 18
    #define zero 87-87
    printNumber(2*zero+18);

    //print 20
    #define zero 88-88
    printNumber(2*zero+20);

    //print 22
    #define zero 10-10
    printNumber(2*zero+22);

    //print 24
    #define zero 46-46
    printNumber(2*zero+24);

    //print 26
    #define zero 85-85
    printNumber(2*zero+26);

    //print 28
    #define zero 83-83
    printNumber(2*zero+28);

    //print 30
    #define zero 78-78
    printNumber(2*zero+30);

    //print 32
    #define zero 7-7
    printNumber(2*zero+32);

    //print 34
    #define zero 81-81
    printNumber(2*zero+34);

    //print 36
    #define zero 2-2
    printNumber(-1*zero+36);

    //print 38
    #define zero 30-30
    printNumber(2*zero+38);

    //print 40
    #define zero 57-57
    printNumber(2*zero+40);

    //print 42
    #define zero 79-79
    printNumber(2*zero+42);

    //print 44
    #define zero 1-1
    printNumber(-10*zero+44);

}

printSomeEvenNumbersTheBoringWay() {

    //print sequence: 0,2,4,6,8,10,12,14...42

    int i = 0;
    while (i <= 42) {
        printf("%i, ", i);
        i+=2;
    }

}

```

# Answer
> 4 votes
# JS, A000027

```
d=new Date();
if(d.getMonth()+("")[(![]+"")[+[]]+"ontcol"+(!![]+[]["fi"+(![]+"")[!+[]+!+[]]+"l"])[10]+"r"]()[11]+("")["fon"+(!![]+"")[0]+"color"]()[11]+!+[]+!+[]*!+[]+!+[]&&d.getDate()==+!+[])alert("Happy April Fool's Day!");
else{for(i=0;i<10;)alert(++i);}
```

Mmm, good mixture of JS and JSF\*ck. (Fun fact: The majority of the code is used to represent `==`.)

Good tip for corrupting code like mine: JS to JSFuck Conversion code/list

# Answer
> -2 votes
# Python 2, A000027

```
import datetime as a
if(str(a.date.today())[5:]=='04-01'):print("Happy April Fool's Day!")
else:
 for i in range(10):print(i+1)

```

Try it online!

---
Tags: popularity-contest, sequence, date, underhanded
---


title: Raise a single number

text:
# Question
Title: Raise a single number
## Introduction

Suppose you want to compute the tail maxima of a list of numbers, that is, the maximum of each nonempty suffix. One way to do it is to repeatedly choose one number and replace it by a higher number occurring after it, until this is not possible anymore. In this challenge, your task is to perform one step of this algorithm.

## The task

Your input is a list of integers **L**, which may be empty. Your output shall be the list **L** where exactly one number **Li** has been replaced by another **Lj**, where **Li \< Lj** and **i \< j**.

In other words, you shall replace one number with a higher number that occurs after it.

You can choose **i** and **j** freely among all valid pairs, and the choice can be nondeterministic.

If such **i** and **j** do not exist (i.e. **L** is non-increasing), your output shall be **L** unchanged.

## Example

Consider the input **L = \[ 3, 1, 4, -1, 2 \]**. The possible operations are to replace **3** by **4**, replace **1** by **4**, replace **1** by **2**, or replace **-1** by **2**. Thus the possible outputs are:

```
 [  3 ,   1 ,   4 ,  -1 ,   2 ]
 ------------------------------
 [( 4),   1 ,(  4),  -1 ,   2 ]
 [  3 ,(  4),(  4),  -1 ,   2 ]
 [  3 ,(  2),   4 ,  -1 ,(  2)]
 [  3 ,   1 ,   4 ,(  2),(  2)]

```

If you repeat the operation enough times, the end result will be **\[4,4,4,2,2\]**, which is precisely the list of tail maxima of **L**.

## Rules and scoring

You can write a full program or a function. In the latter case, you can modify the input in place instead of returning a new array, if your language allows that. Input and output formats are flexible within reason.

The lowest byte count wins.

## Test cases

All possible outputs are shown.

```
[] -> []
[1] -> [1]
[1,2] -> [2,2]
[2,1] -> [2,1]
[4,4,4,4] -> [4,4,4,4]
[-1,-3,-10] -> [-1,-3,-10]
[1,3,10] -> [3,3,10] [10,3,10] [1,10,10]
[1,1,2,1] -> [2,1,2,1] [1,2,2,1]
[998,64,2,-94,-789] -> [998,64,2,-94,-789]
[998,2,64,-94,-789] -> [998,64,64,-94,-789]
[3,1,4,-1,2] -> [4,1,4,-1,2] [3,4,4,-1,2] [3,2,4,-1,2] [3,1,4,2,2]
[-1,4,0,4,7,2,3] -> [4,4,0,4,7,2,3] [0,4,0,4,7,2,3] [-1,4,4,4,7,2,3] [7,4,0,4,7,2,3] [-1,7,0,4,7,2,3] [-1,4,7,4,7,2,3] [-1,4,0,7,7,2,3] [2,4,0,4,7,2,3] [-1,4,2,4,7,2,3] [3,4,0,4,7,2,3] [-1,4,3,4,7,2,3] [-1,4,0,4,7,3,3]
[3542,-12311,7662,1672,6081] -> [7662,-12311,7662,1672,6081] [3542,7662,7662,1672,6081] [3542,1672,7662,1672,6081] [6081,-12311,7662,1672,6081] [3542,6081,7662,1672,6081] [3542,-12311,7662,6081,6081]

```

# Answer
> 9 votes
# JavaScript (ES6), ~~41~~ ~~40~~ ~~39~~ 38 bytes

*Saved a byte thanks to @Neil, another thanks to @user81655*

```
x=>x.map(c=>c<x[++i]>d?x[d=i]:c,d=i=0)

```

Just when it seems `reduceRight` might finally have a chance, `.map` shows up yet again...

# Answer
> 7 votes
# Mathematica, 37 bytes

```
#/.{a___,b_,c_,d___}/;b<c:>{a,c,c,d}&

```

Pure function taking a list of real numbers even, and returning a list of real numbers. Looks for the first pair of consecutive entries in the "wrong" order, and replaces the first of that pair with the second. Nice default behavior of `/.` means that it returns the input unaltered when appropriate.

Amusing side note: if we replace `b<c` with `!OrderedQ[{c,b}]`, then the function works on strings (and really any data type once the appropriate ordering is described). For example, `#/.{a___,b_,c_,d___}/;!OrderedQ[{c,b}]:>{a,c,c,d}&` on input `{"programming", "puzzles", "code", "golf"}` returns `{"puzzles", "puzzles", "code", "golf"}`.

# Answer
> 6 votes
## JavaScript (ES6), ~~43~~ ~~39~~ 38 bytes

```
a=>a[a.some(e=>e<a[++i],i=0)*i-1]=a[i]

```

Outputs by modifying the array in-place. Edit: Saved 4 bytes thanks to @ETHproductions. Saved 1 byte thanks to @user81655.

# Answer
> 5 votes
# Haskell, 36 bytes

```
f(a:r@(b:_))|a<b=b:r|1>0=a:f r
f e=e

```

Try it online!

Look through the list for consecutive elements `a,b` with `a<b` and changes them to `b,b`.

Improved from 37 bytes:

```
f(a:b:t)|a<b=b:b:t
f(a:t)=a:f t
f e=e

```

# Answer
> 4 votes
# Jelly, ~~13~~ 11 bytes

```
ṫJṀ€ż¹ŒpQ-ị

```

Replaces the rightmost of all possible numbers.

Try it online!

### How it works

```
ṫJṀ€ż¹ŒpQ-ị  Main link. Argument: A (array)

 J           Yield all indices of A, i.e., the array [1, ..., len(A)].
ṫ            Dyadic tail; for index k, take all elements starting with the k-th.
             This constructs the array of suffixes.
  Ṁ€         Maximum each; map the monadic maximum atom over the suffixes.
     ¹       Identity; yield A.
    ż        Zip; construct all pairs of elements of the result to the left and the
             corresponding elements of the result to the right.
      Œp     Cartesian product. Construct all arrays that, for each index, take
             either the left or the right element.
        Q    Unique; deduplicate the resulting arrays.
         -ị  At-index -1; select the second to last result.
             The last result is A itself, the first maxima of suffixes.

```

# Answer
> 3 votes
# MATL, 15 bytes

```
tdt0>0whY>d*0h+

```

Try it online!

I'm not a huge fan of this solution. It seems horribly inefficient to me. Particularly the `whY>d*` and `0h+` sections.

# Answer
> 3 votes
# Python 2, ~~139~~ ~~134~~ 93 bytes

```
a=input()
for i in range(len(a)):
 for j in a[i+1:]:
    if a[i]<j:a[i]=j;print a;exit()
print a

```

Terribly long, but it's a first attempt.

-5 bytes thanks to TemporalWolf
-41 (!!) bytes thanks to Value Ink

# Answer
> 3 votes
# MATL, 13 bytes

```
ttd0>fX>Q)2M(

```

Try it online!

### Explanation

The following two conditions are equivalent:

1. There is a number that has a higher number to its right
2. There is a number that has a higher number immediately to its right

The code uses condition 2, which is simpler. It computes consecutive increments and finds the last positive one, if any. For the two involved entries, it writes the value of the second entry into the first.

This trick is used to handle the case when no substitution can be done. Note also that MATL indexing is `1`-based.

Let's use input `[3,1,4,-1,2]` as an example.

```
tt    % Get input implicitly and duplicate it twice
      % STACK: [3,1,4,-1,2], [3,1,4,-1,2], [3,1,4,-1,2]
d     % Consecutive differences
      % STACK: [3,1,4,-1,2], [3,1,4,-1,2], [-2  3 -5  3]
0>    % Are they positive?
      % STACK: [3,1,4,-1,2], [3,1,4,-1,2], [0 1 0 1]
f     % Find indices of all positive differences. Result may be empty
      % STACK: [3,1,4,-1,2], [3,1,4,-1,2], [2 4]
X>    % Maximum index with a positive difference. Empty input remains as empty
      % STACK: [3,1,4,-1,2], [3,1,4,-1,2], 4
Q     % Add 1. Since the addition is elementwise, empty input remains as empty
      % STACK: [3,1,4,-1,2], [3,1,4,-1,2], 5
)     % Get the entry of the input at that position
      % STACK: [3,1,4,-1,2], 2
2M    % Push maximum index with a positive difference, again
      % STACK: [3,1,4,-1,2], 2, 4
(     % Assign to that position. Implicitly display
      % STACK: [3,1,4,2,2]

```

# Answer
> 3 votes
# Haskell, ~~34~~ 33 bytes

This is based on the answer by xnor, who suggested I post it myself.

EDIT: xnor found a byte to save.

```
f(a:r@(b:_))=max(b:r)$a:f r
f e=e

```

Try it online!

Basically, I observed that the branching of xnor's method always ends up choosing whichever of the branch expressions is largest, since Haskell uses lexicographic ordering for lists. (The case when `a==b` also works because `f r>=r`, which can be proved separately by induction.)

Put differently, whenever `b:r > a:f r`, then `b:r` is a correct answer, and otherwise we can recurse to `a:f r`.

So instead of checking `a<b` in advance, I just calculate both expressions and take the maximum. This could give an exponential blowup, although Haskell's laziness avoids that unless `a` and `b` are equal.

# Answer
> 2 votes
# Ruby, ~~66~~ 61 bytes

```
->a{i=r=-1;a.map{|e|m=a[i+=1,a.size].max;r&&m>e ?(r=!r;m):e}}

```

Try it online!

# Answer
> 2 votes
# Python 3, 79 bytes

```
def f(x):
 for i,a in enumerate(x):
  m=max(x[i+1:])
  if m>a:x[i]=m;break

```

Mutates the original array (list) given to it. I'm unhappy that this isn't a lambda and I'm sure there are better optimizations; I'll hopefully address those later.

### Brief explanation

It takes the max of the array past the current element (starting with the zeroth). It then compares this to the element itself: if the max is greater, replace the current element with it and stop, otherwise, increment by one and keep trying that.

# Answer
> 2 votes
# C, 47 bytes

```
f(p,n)int*p;{n>1?*p<p[1]?*p=p[1]:f(p+1,n-1):0;}

```

Recursive implementation taking as its input a pointer to the first element of an array, and the length of the array. Modifies the array in place.

# Answer
> 2 votes
## SWI-Prolog, 70 bytes

```
f([H|T],[S|T]):-max_list(T,S),S>H,!.
f([H|T],[H|R]):-f(T,R),!.
f(I,I).

```

First clause replaces the first element of the list with the maximum value of the rest of the list, but only if this max is bigger. The second clause recursively calls the predicate for the tail of the list. If none of these clauses succeed, the third clause simply returns the input.

This return just one of the possible solutions. It's trivial to find all of them with very similar code, but then the case where no change is possible takes a lot more bytes to handle.

Example:

```
?- f([-1,4,0,4,7,2,3], O).
O = [7, 4, 0, 4, 7, 2, 3]

```

# Answer
> 1 votes
## Python 2, 89 bytes

Try it online -1 byte thanks to @TemporalWolf
-25 bytes thanks to @ValueInk
-7 bytes thanks to @Cole

Function that mutates input array

```
def F(A):
 for i in range(len(A)):
    r=[y for y in A[i+1:]if y>A[i]]
    if r:A[i]=r[0];break

```

If there was no need to stop after first iteration, it would be a bit prettier

# Answer
> 1 votes
## R, 71 bytes

```
a=scan()
l=length(a)
lapply(1:l,function(x){
  a[x]=max(a[x:l])
  a
})

```

# Answer
> 1 votes
# C, 80 bytes

```
i,j;f(l,n)int*l;{for(i=0;i<n;++i)for(j=i;++j<n;)if(l[i]<l[j]){l[i]=l[j];j=i=n;}}

```

Call with:

```
int main()
{
    int a[5]={3,1,4,-1,2};
    f(a,5);
    for(int k=0;k<5;++k)
        printf("%d ", a[k]);
}

```

# Answer
> 1 votes
# Python 2, 60 bytes

```
f=lambda x:x and[x[:1]+f(x[1:]),[max(x)]+x[1:]][x[0]<max(x)]

```

Try it Online!

**Explanation:** Recursively checks if a given element is less than the `max` element in the rest of the list. If so, returns the list with `max` replacing the first element.

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

```
Prompt L<sub>1</sub>
If 2≤dim(L<sub>1</sub>
Then
For(A,1,dim(L<sub>1</sub>)-1
For(B,A,dim(L<sub>1</sub>
If L<sub>1</sub>(A)<L<sub>1</sub>(B
Then
L<sub>1</sub>(B→L<sub>1</sub>(A
Goto E
End
End
End
End
Lbl E
L<sub>1</sub>

```

Explanation:

```
Prompt L<sub>1</sub>          # 4 bytes, input list
If 2≤dim(L<sub>1</sub>        # 7 bytes, if the list has 2 or 1 element(s), skip this part and return it
Then               # 2 bytes
For(A,1,dim(L<sub>1</sub>)-1  # 12 bytes, for each element in the list other than the last
For(B,A,dim(L<sub>1</sub>     # 9 bytes, for each element after that one
If L<sub>1</sub>(A)<L<sub>1</sub>(B      # 12 bytes, if the second is larger than the first
Then               # 2 bytes
L<sub>1</sub>(B→L<sub>1</sub>(A          # 10 bytes, replace the first with the second
Goto E             # 3 bytes, and exit
End                # 2 bytes
End                # 2 bytes
End                # 2 bytes
End                # 2 bytes
Lbl E              # 3 bytes
L<sub>1</sub>                 # 2 bytes, implicitly return L<sub>1</sub>

```

# Answer
> 1 votes
# sh, 118 bytes

Input integers are passed as arguments to the script.

```
l=("$@");for i in "$@";{ for j in "$@";{(($i<$j))&&{ l[$x]=$j;echo ${l[@]};exit;};};shift;x=`expr $x+1`;};echo ${l[@]}

```

Breakdown:

```
l=("$@");                      #copy original list
for i in "$@";{ for j in "$@"; #check all elements j that follow element i in list
{(($i<$j))&&{ l[$x]=$j;echo ${l[@]};exit;};};   #if i<j, make i=j; print list, done
shift;                         #makes sure that i is compared only to j that occur after it
x=`expr $x+1`;};               #keeps track of i'th position in the list
echo ${l[@]}                   #prints list if it was unchanged

```

# Answer
> 0 votes
# PHP, 88 Bytes

```
<?for(;$i+1<$c=count($a=$_GET)&&$a[+$i]>=$a[++$i];);$i>=$c?:$a[$i-1]=$a[$i];print_r($a);

```

## Breakdown

```
for(;
$i+1<($c=count($a=$_GET))  # first condition end loop if the item before the last is reach
&&$a[+$i]>=$a[++$i] # second condition end loop if item is greater then before
;);
$i>=$c?:$a[$i-1]=$a[$i]; # replace if a greater item is found
print_r($a); #Output

```

# Answer
> 0 votes
## Haskell, 48 bytes

```
f(b:l)|l>[],m<-maximum l,b<m=m:l|1<2=b:f l
f x=x

```

Usage example: `f [1,1,2,1]` -\> `[2,1,2,1]`. Try it online!.

If the input list has at least one element, bind `b` to the first element and `l` to the rest of the list. If `l` is not empty and `b` less than the maximum of `l`, return the maximum followed by `l`, else return `b` followed by a recursive call of `f l`. If the input list is empty, return it.

# Answer
> 0 votes
# Python 3, ~~103~~ 102 bytes

```
lambda a:([a[:i]+[max(a[i:])]+a[i+1:]for i in range(len(a))if-~i==len(a)or max(a[i+1:])>a[i]]+[[]])[0]

```

Try it online!

# Answer
> 0 votes
## Racket 202 bytes

```
(let((g(λ(L i n)(for/list((c(in-naturals))(l L))(if(= c i)n l))))(ol'()))
(for((c(in-naturals))(i L))(for((d(in-range c(length L)))#:when(>(list-ref L d)i))
(set! ol(cons(g L c(list-ref L d))ol))))ol)

```

Ungolfed:

```
(define (f L)
  (let ((replace (λ (L i n)   ; sub-function to replace i-th item in list L with n;
                   (for/list ((c (in-naturals))
                              (l L))
                     (if (= c i) n l))))
        (ol '()))             ; outlist initially empty;
    (for ((c (in-naturals))               ; for each item in list
          (i L))
      (for ((d (in-range c (length L)))   ; check each subsequent item in list
            #:when (> (list-ref L d) i))  ; if greater, replace it in list
        (set! ol (cons (replace L c (list-ref L d)) ol)))) ; and add to outlist.
    ol))          ; return outlist.

```

Testing:

```
(f '(3 1 4 -1 2))

```

Output:

```
'((3 1 4 2 2) (3 2 4 -1 2) (3 4 4 -1 2) (4 1 4 -1 2))

```

# Answer
> 0 votes
# C, 67 bytes

**Single Run, 67 bytes** Live

```
j;f(l,i)int*l;{j=i-1;while(i-->0)while(j-->0)l[j]=fmax(l[i],l[j]);}

```

**Single Step, 78 bytes** Live

```
j;f(l,i)int*l;{j=i-1;while(i-->0)while(j-->0)if(l[j]<l[i]){l[j]=l[i];return;}}

```

**Tail Maxima, 96 bytes** Live

```
x;i;j;f(l,n)int*l;{do{x=0;for(i=0;i<n;i++)for(j=0;j<i;j++)if(l[j]<l[i])l[j]=l[i],x=1;}while(x);}

```

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


# Question
Title: Which is better - Emacs or Vim? (Google fight)
Greetings, noble code golfers. Today you will resolve the most ancient and distinguished of debates - Emacs or Vim?

Your challenge is to take two search terms as input, and output which of those terms has the most Google search results. (This is obviously completely fair. What do you mean, biased?)

Here are some example inputs and outputs:

Input: `emacs` and `vim`
Output: `vim` (totally not creating any flamewars in the comments)

Input: `google` and `microsoft`
Output: `google`

Input: `code golf stack exchange` and `code review stack exchange`
Output: `code golf stack exchange` (yeah!)

And here are some edge cases just for fun (and for testing your solutions):

Input: `About 1,000,000 results` and `About 100,000 results`
Output: `About 100,000 results`

Input: `This will autocotrect` and `Another testcase`
Output: `Another testcase` (if you don't consider autocorrecting, then the first one will win)

For the following test cases, you must remove the `#` signs in the search terms first, since they rely on the term having a specific amount of results and posting the term here would ruin that.

Input: `Thissear#chter#mhasno#results` and `Another testcase`
Output: `Another testcase` (just a test for zero results)

Input: `"These exact wo#rds do#n't exi#st# on the Internet"` and `Another testcase`
Output: `Another testcase` (testing `"`s)

Input: `Abo#ut 1,65#2,85#3,2#86 re#sults` and `Another testcase`
Output: `Another testcase` (this one is tricky - the above search term has one result)

Input: `"Abo#ut 4#8,234,8#75,14#7 res#ults"` and `Another testcase`
Output: `Another testcase` (also tricky - no results, so it displays the search term)

You don't need to handle the corner-case of `"quoted"` searches returning "No results, showing results without quotes instead" because that would just be too complicated. You don't need to handle inputs with the same number of results either.

This is , so the shortest code in bytes will win!

# Answer
# Factor, ~~305~~ ~~201~~ ~~196~~ ~~200~~ ~~201~~ ~~188~~ ~~184~~ ~~182~~ ~~179~~ ~~169~~ ~~178~~ ~~171~~ ~~165~~ ~~199~~ ~~171~~ ~~170~~ ~~165~~ 163 bytes

A language nearly as verbose as Java, beating Ruby... and Powershell! :D

Better regex, now. Thanks to @fede s. for 5 bytes off!

```
[ dup [ url-encode "google.com/search?nfpr=1&q="prepend http-get R/ s">About [\d,]+/ first-match " "split second 10 >base ] map zip [ last ] sort-with last first ]

```

Or **~~159~~ 157** if the output can be like `{ "vim" 9782948234 }`:

```
[ dup [ url-encode "google.com/search?nfpr=1&q="prepend http-get R/ s">About [\d,]+/ first-match " "split second 10 >base ] map zip [ last ] sort-with last ]

```

---

On the other hand, if we want to be unkillable, for **~~199~~ ~~196~~ 193 bytes**:

```
[ dup [ url-encode "google.com/search?nfpr=1&q="prepend scrape-html nip dup "resultStats"find-by-id-between second text>> " "split second string>number ] map zip [ last ] sort-with last first ]

```

Unkillable because it parses HTML, so way more robust than the answers using regex.
> 5 votes

# Answer
# Ruby, ~~203~~ 180 bytes

```
->*s{s.map{|x|[(open("http://www.google.com/search?nord=1&q=#{URI.escape x}&nfpr=1").read.match(/s">(About )?([\d,]+) result/)||[?0])[-1].split(?,).join.to_i,x]}.max[1]}

```

+11 bytes for the `-ropen-uri` flag (plus space).

Input is taken as two arguments.

URL explanation:

* `?nord=1`: prevent auto-redirect from HTTP to HTTPS
* `&q=#{URI.escape x}`: escape the query so `"`s work
* `&nfpr=1`: no autocorrect

The whole `map` turns `['emacs','vim']` into `[[2150000, 'emacs'], [14900000, 'vim']]`. (You can see this by changing the `.max[1]` at the end to `.inspect`.) Then, the `max` is taken, which will grab the one with the most results, and `[1]` is used to get the search term.
> 7 votes

# Answer
Of the text editors mentioned in the problem, only one of them can solve this on its own...

# Emacs: 137 keystrokes

```
<C-o><C-u><C-k>(if(<<C-y><C-y><M-<><C-n><F3><C-a>http://google.com/search?nfpr=1&q=<C-S-e><M-x>r-st<RET> <RET>+<RET><C-a><C-k><M-x>b-em<RET><C-y><RET><C-x><C-q><C-s><RET>ts"><RET><M-z><<C-x>0<C-y>0 r<C-a><C-M-s><RET>[0-9]<RET><C-b><M-z> <C-a><C-y><C-k><C-S-a><M-x><up><up><RET>,<RET><RET><F4><C-n><F4><C-e>)(next-line)())<C-x><C-e><C-n><C-a><C-k><C-x>h<DEL><C-y>

```

It expects the first search terms to be on the first line and the second search terms to be on the second line, with the cursor at the beginning of the buffer.

For those unfamiliar with Emacs,

* `C-s` means `Ctrl-S`.
* `M-z` means `Alt-Z` (`Alt` is likely your meta key)
* `M-<` means `Alt-<` or `Alt-Shift-,`
* `C-S-e` means `Ctrl-Shift-e`

For those familiar with Emacs,

* Start emacs with `emacs -q`. That doesn't load your `.emacs` file, so any fancy packages won't intefere with this.

## Explanation

1. Write the beginning of the elisp statment shell

* `<C-o><C-u><C-k>` Saves the arguments with a newline
    * `(if(<<C-y><C-y>` Write the start of the if statement and places 2 copies of the arguments
    * `<M-<><C-n>` Move to the second line
2. Define the HTTP macro. This converts the argument to a Google search URL and then returns the number of search results.

* `<F3>` Start defining the keyboard macro
    * `<C-a>` Move to the start of the search term.
    * `http://google.com/search?nfpr=1&q=` Prepend the search URL
    * `<C-S-e><M-x>r-st<RET> <RET>+<RET>` Replace all the spaces with + signs.
    * `<C-a><C-k><M-x>b-em<RET><C-y><RET>` Emacs retrieve the raw HTML (`b-em` is short for `browse-url-emacs`)
    * `<C-x><C-q>` Make the file writable (required so the macro doesn't error ou t)
    * `<C-s><RET>ts"><RET>` Move to the number of results div (need to do a regular search because emacs macros rely on isearch to work)
    * `<M-z><`Cut the text of of the diff (this is why the was required)
    * `<C-x>0` Switch back to the original buffer
    * `<C-y>0 r`;; Put the results back on the line ('0 r' handles no results)
    * `<C-a><C-M-s><RET>[0-9]<RET><C-b><M-z> <C-a><C-y><C-k>`;; Extract the number from the string.
    * `<C-S-a><M-x><up><up><RET>,<RET><RET>` Strips commas out of the number
    * `<F4>` Finish the keyboard macro
3. Move down and execute the keyboard macro on the next line.

* `<C-n>` Goes to the next line
    * `<F4>` Repeat the macro once.
4. Finish up the elisp statement and execute it

* `<C-e>)(next-line)())` Finish up the elisp statement
    * `<C-x><C-e>` Evaluate the elisp command
    * `<C-n><C-a><C-k>` Kill the winning argument
    * `<C-x>h<DEL>` Delete everything else
    * `<C-y>` Paste the winning argument

## Running It Yourself

Luckily you don't have to type all those keystrokes in perfectly! The meat and potatoes is all in a macro that you can just copy and paste. The macro can be copy and pasted into emacs!

1.Edit the keyboard macro `<C-x><C-k><C-e>`
2.Paste this into the whole buffer (paste should be `<C-y>`)

```
;; Keyboard Macro Editor.  Press C-c C-c to finish; press C-x k RET to cancel.
;; Original keys: C-a http://google.com/search?nfpr= 1&q= S-C-e M-x r-st RET SPC RET + RET C-a C-k M-x b-em RET C-y RET C-x C-q C-s RET ts"> RET M-z < C-x 0 C-y 0 SPC r C-a M-C-s [0-9] 5*DEL RET [0-9] RET C-b M-z SPC C-a C-y C-k S-C-a M-x 2*<up> RET , 2*RET
Command: last-kbd-macro
Key: none
Macro:
C-a         ;; move-beginning-of-line
http://google.com/search?nfpr=  ;; self-insert-command * 30
1&q=            ;; self-insert-command * 4
S-C-e
M-x         ;; execute-extended-command
r-st            ;; self-insert-command * 4
RET         ;; newline
SPC         ;; self-insert-command
RET         ;; newline
+           ;; self-insert-command
RET         ;; newline
C-a         ;; move-beginning-of-line
C-k         ;; kill-line
M-x         ;; execute-extended-command
b-em            ;; self-insert-command * 4
RET         ;; newline
C-y         ;; yank
RET         ;; newline
C-x C-q         ;; read-only-mode
C-s         ;; isearch-forward
RET         ;; newline
ts">            ;; self-insert-command * 4
RET         ;; newline
M-z         ;; zap-to-char
<           ;; self-insert-command
C-x 0           ;; delete-window
C-y         ;; yank
0           ;; self-insert-command
SPC         ;; self-insert-command
r           ;; self-insert-command
C-a         ;; move-beginning-of-line
M-C-s           ;; isearch-forward-regexp
RET         ;; newline
[0-9]           ;; self-insert-command * 5
RET         ;; newline
C-b         ;; backward-char
M-z         ;; zap-to-char
SPC         ;; self-insert-command
C-a         ;; move-beginning-of-line
C-y         ;; yank
C-k         ;; kill-line
S-C-a
M-x         ;; execute-extended-command
2*<up>          ;; previous-line
RET         ;; newline
,           ;; self-insert-command
2*RET           ;; newline

```
3. Type `<C-c><C-c>` to save the macro.
4. If following the explanation steps, replace step 2 with `<F4>` to run the macro (or just run it on its own to try)

## Caveats

1. You can't run the macro on the same search twice without killing the buffer the HTML gets loaded into. Kill the buffers
    * `<C-x><k> search<TAB>`
    * Choose one of the buffers in this list to kill.
    * Repeat for all the buffers beginning with "search"
2. If you run the macro too much, Google will think you are a robot and block access for atime
    * If the macro returns something like `<input type="submit" name="submit" value="Submit"...>`, then this likely occurred.
    * You can confirm it by looking at the raw HTML (`<C-x><C-b>` and choose the buffer with the search term in it).
    * If you see stuff about robots and captcha, Google's blocking you. It's not my fault.
> 7 votes

# Answer
# Java, ~~828~~ ~~800~~ ~~783~~ ~~744~~ ~~739~~ 687 bytes

```
import java.net.*;import java.util.*;import java.util.regex.*;interface G{static Scanner s(String a)throws Exception{URL u=new URL("http://google.com/search?q="+a);HttpURLConnection c=(HttpURLConnection)u.openConnection();c.addRequestProperty("User-Agent","Mozilla/4.0");return new Scanner(c.getInputStream());}static void main(String[]r)throws Exception{String a,b;String c=s(a=r[0]).useDelimiter("\\Z").next(),d=s(b=r[1]).useDelimiter("\\Z").next();Matcher m=Pattern.compile("ut ([0-9,]+) res").matcher(c);m.find();long i=new Scanner(m.group(1)).nextLong();m=Pattern.compile("ut ([0-9,]+) res").matcher(d);m.find();long j=new Scanner(m.group(1)).nextLong();System.out.print(i>j?a:b);}}

```
> 3 votes

# Answer
# Python 3, ~~227~~ ~~226~~ ~~208~~ ~~213~~ ~~226~~ ~~220~~ ~~221~~ ~~206~~ ~~202~~ ~~200~~ 198 bytes

```
import re,requests as r,urllib.parse as u
lambda*t:sorted(zip(map(lambda a:int(re.findall("s\">About ([\d,]+)",r.get("http://google.com/search?q="+u.quote(a)).text)[0].replace(",","")),t),t))[-1][1]

```

Assign the lambda to something to call it.

Uses the requests library.

Ungolfed:

```
import re, requests as r, urllib.parse as u
lambda*t:
  sorted(
  list(
      zip(map(
              lambda a: int(re.findall("About ([\d,]+)",
               r.get("http://google.com/search?q="+u.quote(a)).text)[0].replace(",","")),
              t
          ),
       t)
   )
)[-1][1]

```
> 2 votes

# Answer
# Powershell, ~~175~~, 172 bytes

```
($args|%{[pscustomobject]@{'a'=$_;'b'=[int]((iwr "google.com/search?nord=1&q=$_&nfpr=1").parsedhtml.getelementbyid('resultstats').innertext-split" ")[1]}}|sort -des b).a[0]

```

Showing the score as well as the name would cut 2 more bytes.

This uses the same `unkillable` feature as the `196 Byte` **Factor** answer (Parsed HTML) and cuts down from the previous regex answer.
> 1 votes

# Answer
# Racket, ~~360~~ 337 bytes

```
#lang racket(require net/url net/uri-codec)(λ(t)(cddr(sort(map list t(map(lambda(a)(string->number(string-replace(list-ref(string-split(car(regexp-match#px"s\">About [\\d,]+ res"(call/input-url(string->url(string-append"http://google.com/search?nfpr=1&q="(uri-encode a)))(curry get-pure-port)port->string)))" ")1)",""")))))#:key cdr <)))

```

0.o

There's a reason they call it Lost In a Sea of Parentheses.

Ungolfed:

```
#lang racket
(require net/url)
(require net/uri-codec)

(define (open-url term)
  (call/input-url
   (string->url (string-append "http://" term))
   (curry get-pure-port #:redirections 5)
   port->string))

(define (get-result term)
  (string->number
   (string-replace
    (list-ref
     (string-split
      (car (regexp-match #px"s\">About [\\d,]+ results" (open-url (string-append "google.com/search?nfpr=1&q=" (uri-encode term)))))
      " ")
     1)
    "," "")))

(define (zip a b) (map list a b))

(define (google-fite terms) (cddr (sort (zip terms (map get-result terms))) #:key cdr <))

```
> 1 votes

---
Tags: code-golf, internet
---


title: Alphanumerical order

text:
# Question
Title: Alphanumerical order
Task is to output this text:

```
ABCDEFGHIJKLMNOPQRSTUVWXYZA
A 00000000000000000000000 Z
B                         Y
C  101010101010101010101  X
D                         W
E                         V
F   2101210121012101210   U
G                         T
H                         S
I                         R
J    12321012321012321    Q
K                         P
L                         O
M     234321012343210     N
N     123432101234321     M
O                         L
P                         K
Q    23210123210123210    J
R                         I
S                         H
T                         G
U   1210121012101210121   F
V                         E
W                         D
X  010101010101010101010  C
Y                         B
Z 00000000000000000000000 A
ABCDEFGHIJKLMNOPQRSTUVWXYZA

```

### Rules

* shortest code wins, but you are encouraged to post answers even if your language is among more verbose ones
* trailing newline allowed,
* lowercase letters allowed

# Answer
# SOGL 0.8.2, ~~121~~ 120 bytes

```
Z A+p→**1"PļΔķ≠ƨν↕KzøjQ¶°³²y⁹ν⅔E    "§768╗@ū℮^‰Y√ψ⅜εrυd┘mZΣlL⅝6׀KTφυZŗ4M7E¤Δ≠⅓∫⁽mΜ‽κuΘ\λ`ω¬ρDDz⅞":e─░χ′⁷‘’«n{;³ZWO≤oZ±WoI}*

```

Explanation:

```
Z                                 push the uppercase alphabet
  A+                              append "A"
    p                             output in a new line
     →*                           define function "*" with the above
       *                          call the function "*"
        1                         push 1 (counter)
         "...‘                    push the middle lines (without the alphabet letters) joined
              ’«n                 convert to an array with each item 25 chars long
                 {            }   for each line
                  ;³              put the counter ontop on stack and triplicate it
                    ZW            get the counterth letter of the alphabet
                      O           output in newline
                       ≤          put the current array item ontop of stack
                        o         append
                         Z±W      get the counterth letter of the reversed alphabet
                            o     append
                             I    increase counter
                               *  call the function "*"

```
> 3 votes

# Answer
# Bubblegum, 186 bytes

```
00000000: 7592 d70d c330 0c44 ff6f 0a8e e092 05dc  u....0.D.o......
00000010: 2df7 def6 1f24 3263 0429 3e09 2281 7b38  -....$2c.)>.".{8
00000020: 1284 1884 519c a459 6e8a b2aa 9bb6 eb87  ....Q..Yn.......
00000030: 719a 9775 db8f 0081 38f7 470e 84c2 ce8e  q..u....8.G.....
00000040: 48c4 756e aec8 8698 fa56 2494 2d48 6df4  H.un.....V$.-Hm.
00000050: 6c8d 9f67 d519 19f5 4dc8 291b 6128 1b50  l..g....M.).a(.P
00000060: 9cc9 f57c edf3 8ea7 d8a3 a4be 0e15 652d  ...|..........e-
00000070: 6acd 9eff b8ea 6956 ad41 2357 c34f a85a  j.....iV.A#W.O.Z
00000080: 8d96 d6ac d051 56a2 7fb5 fb1e 411b 1618  .....QV.....A...
00000090: a8cf 60a4 2cc7 4459 8659 27f8 fb24 aba6  ..`.,.DY.Y'..$..
000000a0: 58a8 2fc1 4a59 8c4d e46e 95ec 1411 76ea  X./.JY.M.n....v.
000000b0: 0b71 d0dd b57b cd77 fe09                 .q...{.w..

```

Try It Online!
> 3 votes

# Answer
# NO!, 34067 bytes

OP asked for verbose. I give you verbose.

I would say the NO! isn't old enough to compete but the length of the code says that it's not competing

As the code is too long for SE, here is a link to the actual code: actual code. I chose a TIO page because I can't be bothered to find anything else.
> 1 votes

# Answer
# PHP, 294 Bytes

```
$d=[0=>[0,23],2=>["01",21],5=>[2101,19],9=>[123210,17],12=>[23432101,15],13=>[12343210,15],16=>[232101,17],20=>[1210,19],23=>[10,21],25=>[0,23]];echo$j=join(range(A,Z)),"A\n";for($i=0;$i<26;$i++)echo$j[$i].str_pad($d[$i]?str_pad("",$d[$i][1],$d[$i][0]):"",25," ",2).$j[-$i-1]."\n";echo$j."A\n";

```

Expanded

```
$d=[
0=>[0,23],
2=>["01",21],
5=>[2101,19],
9=>[123210,17],
12=>[23432101,15],
13=>[12343210,15],
16=>[232101,17],
20=>[1210,19],
23=>[10,21],
25=>[0,23]];
echo$j=join(range(A,Z)),"A\n";
for($i=0;$i<26;$i++)
echo$j[$i].str_pad($d[$i]?str_pad("",$d[$i][1],$d[$i][0]):"",25," ",2).$j[-$i-1]."\n";
echo$j."A\n";

```
> 0 votes

---
Tags: code-golf, kolmogorov-complexity
---


# Question
Title: PowerShell: test connection in as few characters as possible
I need this down to as few characters as possible. I would use Test-NetConnection but I need PSv2 compatability. Any help would be appreciated.

```
$socket = new-object Net.Sockets.TcpClient
$socket.Connect("192.168.5.5",445)
$socket.Connected

```

As a note I have tried this but it doesn't work

```
(new-object Net.Sockets.TcpClient).Connect("192.168.5.5",445).Connected

```

# Answer
> 2 votes
AFAIK, there's no default alias for `New-Object`, and no type accelerator for `Net.Sockets.TcpClient`, so they can't be any shorter. You can merge the constructor and connect code into one line:

```
(New-Object Net.Sockets.TcpClient -A 192.168.5.5,445)

```

But if it can't connect, it now throws an exception, which you can't silence with -ErrorAction. So handling that ends up being 70 characters, only 8 shorter than your original after shrinking the variable name:

```
!!$(try{(new-object net.sockets.tcpclient -A 192.168.5.5,445)}catch{})

```

`!!` forcing the result to a bool.

# Answer
> 6 votes
### PowerShell v2+, 63 bytes

You can use a different constructor to create the object and connect in one go.

```
(new-object Net.Sockets.TcpClient('192.168.5.5',445)).Connected

```

I've verified this works in v2 on my Windows 8.1 machine. That constructor is supported by .NET 2.0, so this should be v2 compatible.

---
Tags: code-golf, tips, powershell
---


# Question
Title: Two roads diverged in a yellow wood (part 3)
> **Note:** This is based on Two roads diverged in a yellow wood (part 2), a previous challenge of mine. Because of the popularity of that question and Two roads diverged in a yellow wood (part 1), I wanted to make a third. But the first 2 were too easy (a *2-byte* answer on the first, a 15-byte answer on the second.) So I made something more complex...

## The inspiration

This challenge is inspired by Robert Frost's famous poem, *The Road Not Taken*:

> Two roads diverged in a yellow wood,
> And sorry I could not travel both
> And be one traveler, long I stood
> And looked down one as far as I could
> To where it bent in the undergrowth;
>
> ...2 paragraphs trimmed...
>
> I shall be telling this with a sigh
> Somewhere ages and ages hence:
> Two roads diverged in a wood, and I —
> I took the one less traveled by,
> And that has made all the difference.

Notice the second to last line, `I took the one less traveled by,`.

## The backstory

You were assigned to help a blind adventurer who is walking on a road and was inspired by *The Road Not Taken*. The adventurer is approaching a fork in the road and would like to take the path less traveled by. You must find where the adventurer actually is and tell the adventurer where to turn.

## The challenge

Your goal is to find the road least traveled by on your map where the road forks. Your map is a string containing newlines (or `\n`, if you prefer) and has an unknown width and height. In the map, roads are made up of **digits 0 to 9**, the intersection are made of `#`s. You must find the road you are currently on, and out of the other roads the road most traveled by, and the road less traveled by for your blind adventurer. Woods in you map is represented by a space. Here is a simple map:

```
2   2
 1 0
  #
  2
  2

```

This map is 5 wide and 5 tall. Notice how the road forks in a Y shape. The Y may be oriented any way, so you must be able to understand a "rotated" map.

## What the `#` means

Where the map forks there will be a `#`. This does not impact the score of any path.

## What the numbers actually mean

Each path (a line of numbers, may have a bend in it) has a score. A path's score is determined by adding up its digits, so for the first example, the first path (from upper-left, clockwise) has a score of 2+1=3, the second has 2+0=2, and the third has 2+2=4. Roads may contain numbers connected diagonally.

## Finding where you are

You are on the path with the highest score. The other 2 paths are the road more traveled by, and the road less traveled by. You need to find the road with the *lowest* score.

## Telling your traveler where to go

You must tell your traveler to go "left" or "right". Keep in mind that directions are from your traveler's point of view (he is facing the fork.)

## Example maps

```
  14
9#
  04

```

Output: "right" (traveler is at the `9` road, 0+4 \< 1+4

```
  9
  9
  9
  9
  9
  #
 8 8
 8 8
88 88
8   7

```

Output: "left" (traveler is at the `99999` road, 8+8+8+8+8 \> 8+8+8+8+7

```
02468
     #98765
13579

```

Output: "right" (traveler is at the `98765` road, 0+2+4+6+8 \< 1+3+5+7+9)

```
4 2
4 2
 #
 4
 4
 2
 2

```

Output: "right" (traveler is at the `4422` road, 4+4 \> 2+2)

```
 9
 9
 9
 #
8 7
8  7
8   7

```

Output "left" (traveler is at the `999` road, 8+8+8 \> 7+7+7

## Stuff to know:

* Maps will be padded with spaces to make each line the same length.
* You must output to STDOUT / console / file the string `left` or `right`, optionally followed by a trailing newline.
* You must take input as either a string containing newlines, `\n`s, or an array/list of lines (each line is a string). Where that input is put **must be a function, command-line argument, file, or STDIN one line at a time or similar. A variable is not a acceptable input device (unless it is a function parameter.) Likewise, function expressions in JS and other languages must be assigned to a variable.**
* This is , so the shortest answer in bytes wins!
* Standard loopholes forbidden

## Things you can assume

* Your input will be valid. Nothing like this will be tested for:

```
0 0 0
 0 0
  #
 0 0

```
* Paths' scores will never be tied.
* The input can be of any length in width or height, less than the string limit of your language.
* There will always be at least 1 space between the 2 paths.
* Paths may have bends, turns, etc. These are roads, not highways.

# Have any questions? Ask me below in the comments and happy golfing!

# Answer
# , ~~348~~ ~~321~~ ~~312~~ 302 bytes

```
import std.stdio,std.algorithm,std.regex,std.range;void h(R,U)(R s,U r){U[2]c;foreach(L;s.map!(a=>a.array.split)){U l=L.length-1;r>1?r=l^r-2:0;l?c[]+=l*L.map!sum.array[]:c;}write(c[r]>c[!r]?"right":"left");}void main(){auto s=stdin.byLineCopy.array;!s.join.match(`\d \d`)?h(s.transposed,2UL):h(s,3UL);}

```

## Ungolfed

```
import std.stdio,std.algorithm,std.regex,std.range;

void h(R,U)(R s, U reverse) {
    U[2] counts;
    /* Now that all paths are up/down, every line we need to count up has
       precisely two space-delimited parts to sum up. */
    foreach (line; s.map!(a=>a.array.split)) {
        U len = line.length - 1;
        reverse > 1 ? reverse = len ^ reverse - 2 : 0;
        len ? counts[] += len * line.map!sum.array[] : counts;
    }

    /* Switch left/right as needed based on our orientation */
    write(counts[reverse] > counts[!reverse] ? "right" : "left");
}

void main() {
    /* Treat the input as a matrix of integers */
    auto s = stdin.byLineCopy.array;

    /* If moving left/right intead of up/down, transpose */
    !s.join.match(`\d \d`)?h(s.transposed,2UL):h(s,3UL);
}

```

Try it online!
> 3 votes

# Answer
## Python 2, 304 bytes

Try it online

```
A=input()
S=str(A)[2:-2].replace("', '",'')
i=S.index('#')
r=len(A[0])
w=1
a=i/r
if' '<S[i-r]:w=-w;A=A[::w];a=len(A)+~a
if' '<S[i+1]:A=zip(*A[::-1]);a=i%r
if' '<S[i-1]:A=zip(*A)[::-1];a=len(A)-i%r-1
s=0
for c in' '.join(map(''.join,A[0:a])).split():s+=sum(map(int,c));s=-s
print['left','right'][::w][s>0]

```

This program deduces direction of roads and rotates it facing up to use my solution from part 2 of this challenge.
> 2 votes

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


title: This is how we roll

text:
# Question
Title: This is how we roll
Piet is an interesting programming language for a number of reasons. Today we will focus on one reason: the roll command. The roll command was originally from PostScript and is a powerful way to manipulate the stack.

The roll command pops the top two elements of the stack and uses them as parameters. We'll call the first value popped `turns` and the second `depth`. A turn to depth n will take the topmost element of the stack, make it the nth element in the stack, and move each of the elements above it up one. If `turns` is negative this is done in the opposite direction. That is, the nth element is moved to the top and the other elements are moved down. This is repeated `abs(turns)` times.

## Challenge

Write a program or function that takes in a stack and returns that stack after executing a roll.

### Rules

* Input and output may be in a list, array, string with a delimiter, passed in one element at a time, or any other reasonable format. Output must be in the same format as the input.
* `depth` will never be negative and will never be greater than the length of the stack.
* The input stack will always contain at least two elements.
* This is so the shortest answer in each language wins. As such, I will not be accepting an answer.
* Standard loopholes are forbidden.

### Test Cases

```
in:  out:
2
4
1    3
2    4
3    1
4    2
5    5
6    6

in:  out:
-2
3
1    2
2    3
3    1

in:  out:
-42
0
1    1
2    2
3    3
4    4
5    5

```

# Answer
> 8 votes
# Haskell, ~~64~~ 62 bytes

Edit: -2 bytes: @xnor saw something I'd thought wrong about.

`r` takes and returns a list of `Int`s.

```
r(t:d:l)|d<1=l|(x,y)<-d%l,(z,w)<-mod t d%x=w++z++y
(%)=splitAt

```

Try it online!

`splitAt n l` splits a list `l` at index `n`, `mod` calculates remainder of division, `++` concatenates lists.

# Answer
> 8 votes
## JavaScript (ES6), ~~49~~ 47 bytes

```
(t,d,...a)=>a.splice(t=(t%d+d)%d,d-t).concat(a)

```

Edit: Saved 2 bytes thanks to @Shaggy by taking the stack elements as separate parameters. Explanation:

* When the turn is a multiple of the depth, nothing happens. The first step is therefore to calculate turn modulo depth. As JavaScript only knows how to calculate the remainder, I have to do this in two steps.
* A turn of `1` moves the top element to the `depth` element. A turn of `2` moves the top two elements, etc. However, you can also achieve this by moving the elements between turn and depth to the front. `splice` removes those elements and `concat` prepends them to the remaining elements. (I could have used an array comprehension instead as it is the same length.)
* Unlike `slice`, the second parameter to `splice` is the number of elements to remove.

# Answer
> 7 votes
## CJam, 31 bytes

```
)\):N@\,0a|={NW*1$1$>)\+@@<\+}*

```

Input and output are arrays on the stack, with the last element representing the top of the stack.

Stack trace:

```
                   e# Stack:                [6 5 4 3 2 1 4 2]
)                  e# Take out first value: [6 5 4 3 2 1 4] 2
\                  e# Swap:                 2 [6 5 4 3 2 1 4]
)                  e# Take out first value: 2 [6 5 4 3 2 1] 4
:N                 e# Store in N:           2 [6 5 4 3 2 1] 4; N=4
@                  e# Rotate:               [6 5 4 3 2 1] 4 2
\                  e# Swap:                 [6 5 4 3 2 1] 2 4
,                  e# Range:                [6 5 4 3 2 1] 2 [0 1 2 3]
0                  e# Push 0:               [6 5 4 3 2 1] 2 [0 1 2 3] 0
a                  e# Wrap in array:        [6 5 4 3 2 1] 2 [0 1 2 3] [0]
|                  e# Logical or:           [6 5 4 3 2 1] 2 [0 1 2 3]
                   e# (This will replace an empty array with [0] to handle a special case of n=0)
=                  e# Get array value:      [6 5 4 3 2 1] 2
{NW*1$1$>)\+@@<\+} e# Push block:           [6 5 4 3 2 1] 2 {NW*1$1$>)\+@@<\+}
*                  e# Preform n times:      [6 5 4 3 2 1]
  N                e# Push N:               [6 5 4 3 2 1] 4
  W*               e# Negate:               [6 5 4 3 2 1] -4
  1$               e# Copy element 1 back:  [6 5 4 3 2 1] -4 [6 5 4 3 2 1]
  1$               e# Copy element 1 back:  [6 5 4 3 2 1] -4 [6 5 4 3 2 1] -4
  >                e# Slice a[-4:]          [6 5 4 3 2 1] -4 [4 3 2 1]
  )                e# Take first value:     [6 5 4 3 2 1] -4 [4 3 2] 1
  \                e# Swap:                 [6 5 4 3 2 1] -4 1 [4 3 2]
  +                e# Append:               [6 5 4 3 2 1] -4 [1 4 3 2]
  @@               e# Rotate twice:         [1 4 3 2] [6 5 4 3 2 1] -4
  <                e# Slice a[:-4]:         [1 4 3 2] [6 5]
  \                e# Swap:                 [6 5] [1 4 3 2]
  +                e# Append:               [6 5 1 4 3 2]
e# Preform the block again:                 [6 5 2 1 4 3]

```

# Answer
> 6 votes
## Mathematica, 58 50 bytes

*Edit: Thanks to Martin Ender for saving 8 bytes.*

```
Take[x={##3},#2]~RotateLeft~#~Join~Drop[x,#2]&@@#&

```

## Explanation:

Pure function which expects a list where the beginning of the list represents the top of the stack. We pass the elements of the list into the pure function `Take[x={##3},#2]~RotateLeft~#~Join~Drop[x,#2]&`. `x` is set to the sequence of elements starting with the third argument., then we rotate the first `#2` (second argument) elements of `x` to the left `#` (first argument) times, then `Join` the remaining elements of `x`.

It would save `3` bytes if we just passed the stack elements in as arguments to the function directly rather than being in a list initially, but then the input and output formats wouldn't match.

## Original solution:

```
#/.{t_,d_,x___}:>{x}~Take~d~RotateLeft~t~Join~Drop[{x},d]&

```

There's something really satisfying about this chain of infix functions. Replaces a list with first element `t`, second element `d`, and remaining elements `x` with the result of rotating the first `d` elements of `{x}` to the left `t` times and joining the remaining elements of `{x}`.

# Answer
> 6 votes
# Ruby, 40 bytes

```
x=->s{n,d,*s=s;s[0,d]=s[0,d].rotate n;s}

```

Try it online!

Takes the input as a list, returns a list. The fact that a built-in `rotate` exists which can handle both positive and negative rotations makes this trivial.

# Answer
> 5 votes
# Python, ~~141~~ ~~98~~ ~~87~~ 74 bytes

*11 bytes saved thanks to @Cole*

```
def f(s):*s,d,t=s;n=len(s)-d;return s*0**d or s[:n]+s[-t%d-d:]+s[n:-t%d-d]

```

Receives input as a list, where the last element is the top of the stack.

Uses the 0ⁿ trick to filter zero-depth and python's sign-adjusting modulo operator to determine the part of the list to-be-chopped.

# Answer
> 3 votes
# JavaScript ES6, ~~109~~ 92 bytes

```
x=>{for(i=x.shift(),i=i>0?i:-i,j=x.shift();i-->0&&j>0;)x=x.splice(j,1).concat(x);return x}

```

Try it online!

Receives input in the form of an array of integers.
Also has the count to arrow :P

## Explanation:

The code uses the shift function to extract the first two elements of the list.

It then gets the absolute value of the first element, which is the number of turns.

Since Javascript is zero indexed, the depth index needs to be decreased by 1.

If the depth index was 0 or 1, nothing should change, but due to the decrease, index of 0 would cause changes. Therefore exit the loop if depth index is not \<=0.

The splice(a,b) function returns the sub-array of length b with starting index a from the array and leaves the original array without those elements.

When concatenated with the remainder of the original array, this is a single rotation of the array at the depth index.

By performing this operation n times, where n is the number of turns, the resulting array is the result of the roll operator.

# Answer
> 3 votes
# Python 2, 48 bytes

```
lambda r:r[2:r[1]+2][r[0]:]+r[2:r[0]]+r[r[1]+2:]

```

Try it online!

# Answer
> 2 votes
# TI-Basic, ~~141~~ 150 bytes (noncompeting)

```
Prompt L<sub>1</sub>
L<sub>1</sub>(1→T
L<sub>1</sub>(2→D
seq(L<sub>1</sub>(C),C,3,dim(L<sub>1</sub>→L<sub>1</sub>
If TD>0
Then
For(A,1,T
L<sub>1</sub>(1→B
For(C,2,D
L<sub>1</sub>(C→L<sub>1</sub>(C–1
End
B→L<sub>1</sub>(D
End
End
If TD<0
Then
For(A,1,-T
L<sub>1</sub>(D→B
For(C,D,2,-1
L<sub>1</sub>(C–1→L<sub>1</sub>(C
End
B→L<sub>1</sub>(1
End
End
L<sub>1</sub>

```

Edit: fixed case where depth is zero (+9 bytes)

TI-Basic doesn't support 0-length lists, so this approach won't work for a two-length input.

Explanation:

```
Prompt L<sub>1</sub>                # 4 bytes, input list
L<sub>1</sub>(1→T                   # 7 bytes, turns
L<sub>1</sub>(2→D                   # 7 bytes, depth
seq(L<sub>1</sub>(C),C,3,dim(L<sub>1</sub>→L<sub>1</sub>   # 18 bytes, remove turns and depth from list
If TD>0                  # 6 bytes, if turns is positive and depth is nonzero (can't be negative)
Then                     # 2 bytes
For(A,1,T                # 7 bytes, do this 'turns' times
L<sub>1</sub>(1→B                    # 7 bytes, backup the first item
For(C,2,D                # 7 bytes, shuffle the rest along
L<sub>1</sub>(C→L<sub>1</sub>(C–1               # 12 bytes
End                      # 2 bytes
B→L<sub>1</sub>(D                   # 7 bytes, restore the backup to where it should be
End                      # 2 bytes
End                      # 2 bytes
If TD<0                  # 6 bytes, if T is negative and D is nonzero
Then                     # 2 bytes
For(A,1,-T               # 8 bytes, do this -'turns' times
L<sub>1</sub>(D→B                   # 7 bytes, backup the Dth item
For(C,D,2,-1             # 10 bytes, shuffle the items the other way
L<sub>1</sub>(C–1→L<sub>1</sub>(C              # 12 bytes
End                      # 2 bytes
B→L<sub>1</sub>(1                   # 7 bytes, restore backup to where it belongs
End                      # 2 bytes
End                      # 2 bytes
L<sub>1</sub>                       # 2 bytes, implicitly return

```

# Answer
> 1 votes
## Batch, 163 bytes

```
@set s=
@set r=
@set/ad=%2,t=(%1%%d+d)%%d
:l
@shift
@set/af=t-=1,f^^=d-=1
@if %f% lss 0 (set r=%r% %2)else set s=%s% %2
@if not "%3"=="" goto l
@echo%r%%s%

```

Takes input as command-line parameters and outputs a space-separated list. The parameters between `t` and `d` are extracted into the `r` variable so that they can be prepended to the `s` variable, which receives all of the other parameters.

---
Tags: code-golf, stack
---


title: Large Numbers in BF

text:
# Question
Title: Large Numbers in BF
## Background

The language BrainF\*** (or simply BF), is an extremely minimal programming language. We're going to strip it back even further by eliminating IO operations; only the sub-langage defined by the operations `+-<>[]`, henceforth referred to as BF-subset, shall be used. The BF variant considered has a tape extending infinitely to the left and right, and cells which can take on any integer value without overflowing, and which are initialized to 0.

For those unfamiliar with BF, this explanation is adapted from the esolangs BF page.

A BF-subset program is a sequence of commands. The commands are executed sequentially, with some exceptions: an instruction pointer begins at the first command, and each command it points to is executed, after which it normally moves forward to the next command. The program terminates when the instruction pointer moves past the last command.

```
>   increment the data pointer (to point to the next cell to the right).
<   decrement the data pointer (to point to the next cell to the left).
+   increment (increase by one) the byte at the data pointer.
-   decrement (decrease by one) the byte at the data pointer.
[   if the byte at the data pointer is zero, then instead of moving the instruction pointer forward to the next command, jump it forward to the command after the matching ] command.
]   if the byte at the data pointer is nonzero, then instead of moving the instruction pointer forward to the next command, jump it back to the command after the matching [ command.

```

## The Task

If a BF-subset program terminates, its *score* is defined as the final value of the cell which the program halts at, otherwise 0. Your challenge is to write a program to generate BF-subset programs of each length between 1 and 20 inclusive, such that the total score is maximized.

The winner of the contest will be the entrant with the highest total score; in case of a tie, the shortest program takes the title. Your program must be fast enough for you to run it to completion.

## Example Output and Scores

```
+                   01
++                  02
+++                 03
++++                04
+++++               05
++++++              06
+++++++             07
++++++++            08
+++++++++           09
++++++++++          10
+++++++++++         11
++++++++++++        12
+++++++++++++       13
++++++++++++++      14
+++++++++++++++     15
++++++++++++++++    16
+++++++++++++++++   17
++++++++++++++++++  18
+++++++++++++++++++ 19
+++++++++++++++++++ 20

```

Here, the total score is 210.

Edit: Changed the maximum length from 17 to 20.

# Answer
> 3 votes
# 309

```
+                    01
++                   02
+++                  03
++++                 04
+++++                05
++++++               06
+++++++              07
++++++++             08
+++++++++            09
++++++++++           10
+++++++++++          11
++++++++++++         12
+++++++++++++        13
++++[->++++<]>       16
+++++[->++++<]>      20
+++++[->+++++<]>     25
++++++[->+++++<]>    30
++++++[->++++++<]>   36
+++++++[->++++++<]>  42
+++++++[->+++++++<]> 49

```

---
Tags: code-golf, code-challenge, brainfuck, busy-beaver
---


# Question
Title: Volts, Amps, Watts and Ohms: given two, calculate the other two
Ohm's law tells us that the current (I) in amps flowing through a resistance (R) in Ohms when a voltage (V) is applied across it is given as follows:

```
V = I / R

```

Similarly the power (P) in watts dissipated by that resistance is given by:

```
P = V * I

```

By rearrangement and substitution, formulae may be derived for calculating two of these quantities when any of the other two is given. These formulae are summarised as follows (note this image uses `E` instead of `V` for volts):

Given an input of any two of these quantities in a string, output the other two.

* Input numbers will be decimals in whatever format is appropriate for your language. Precision should be to at least 3 decimal places. (IEEE 754-2008 binary32 floats are sufficient.)
* Each input number will be suffixed with a unit. This will be one of `V A W R` for Voltage, Amperage, Power and Resistance (or the equivalent lowercase). Additionally, you may use `Ω` instead of `R`. The units will not have any decimal prefixes (Kilo-, milli-, etc).
* The two input quantities will be given in any order in one string, separated by a single space.
* Input quantities will always be real numbers greater than 0.
* Output will be in the same format as input.
* Equation-solving builtins are disallowed.

### Example Inputs

```
1W 1A
12V 120R
10A 10V
8R 1800W
230V 13A
1.1W 2.333V

```

### Corresponding Outputs

```
1V 1R
0.1A 1.2W
1R 100W
120V 15A
2990W 17.692R
0.471A 4.948R

```

It should be noted that solutions to this challenge will effectively be self-inverses. In other words if you apply a solution to input `A B` and get output `C D`, then apply a solution to input `C D`, then the output should be `A B` again, though possibly out of order and perturbed due to FP rounding. So test inputs and outputs may be used interchangeably.

# Answer
# Ruby 171 bytes

Input as function argument. Output to stdout with trailing space (can be revised if necessary.)

```
->s{a,b,c,d=s.split.map{|z|[z[-1],z.to_f]}.sort.flatten
%w{EA9.EAAVAA.WVA GS;.A?#WWV.RRR}.map{|w|m=w[n=(a+c+?!).sum%10].ord;print (b**(m%9-4)*d**(m/9-5))**0.5,w[n+7],' '}}

```

**Explanation**

All formulas can be expressed in the form `b**x*d**y` where b & d are the two input values and x & y are powers. For golfing reasons the expression `(b**x*d**y)**0.5` was finally preferred as it means x and y become integers in the range -4 to 4.

The following table shows the required expressions (inputs are assumed sorted alphabetically) and the encoded values for the powers. Where x and y are the doubled powers, they are encoded as `(x+4)+(y+4)*9+9` or equivalently `(x+4)+(y+5)*9`. This puts all encodings in the printable ASCII range. Power operators are omitted from the formulas for brevity.

`n` is a kind of checksum made from the input unit symbols; it can take the values 0,1,2,4,5,6 (3 is not used.)

```
n     formula 1 formula 2      formula 1                formula 2
value                      powers x+4 y+4 encoding   powers x+4 y+4 encoding

0      A*R=V    A2*R=W       1 1    6 6   69 E        2 1     8 6   71 G
1    R-1*V=A  R-1*V2=W      -1 1    2 6   65 A       -1 2     2 8   83 S
2 R-.5*W.5=A R.5*W.5=V     -.5 .5   3 5   57 9       .5 .5    5 5   59 ;
3          .         .                       .                         .
4      A*V=W   A-1*V=R       1 1    6 6   69 E       -1 1     2 6   65 A
5    A-1*W=V   A-2*W=R      -1 1    2 6   65 A       -2 1     0 6   63 ?
6    V-1*W=A  V2*W-1=R      -1 1    2 6   65 A        2 -1    8 2   35 #

```

**Ungolfed in test program**

```
f=->s{
  a,b,c,d=s.split.map{|z|[z[-1],z.to_f]}.        #split the input into an array [[symbol1,value1],[symbol2,value2]]
  sort.flatten                                   #sort alphabetically by symbol and flatten to assign the 4 objects to different variables
  n=(a+c+?!).sum%10                              #sum the ascii codes of the symbols (plus that of ! for good value distribution) and take mod 10. gives a number 0..6 (3 is not used)
  %w{EA9.EAAVAA.WVA GS;.A?#WWV.RRR}.             #for each of the outputs, there is a 14 character string. 1st 7 characters encode powers, 2nd 7 characters are output symbol
  map{|w|                                        #iterate through the 2 outputs
    m=w[n].ord                                   #select one character according to value of n and convert to a number encoding the powers to raise the two inputs to
    print (b**(m%9-4)*d**(m/9-5))**0.5,w[n+7],' '#decode the powers, evaluate the expression and output, append the unit symbol and a space
  }
}

f["6W 3A"]
puts
f["12V 120R"]
puts
f["10A 10V"]
puts
f["8R 1800W"]
puts
f["6W 2V"]
puts
f["2A 3R"]
puts

```

**Output**

```
2.0V 0.6666666666666666R
0.1A 1.2W
100.0W 1.0R
15.0A 120.0V
3.0A 0.6666666666666666R
6.0V 12.0W

```
> 4 votes

# Answer
# Python 3, ~~193~~ ~~187~~ 190 bytes

```
import re
exec(re.sub('(.+?) (.)',r'\2=\1;',input()))
for s,r in zip('AVRW'*3,'V/R (W*R)**.5 V/A V*V/R W/V W/A V*V/W R*A*A (W/R)**.5 A*R W/A**2 V*A'.split()):
 try:print(eval(r),s)
 except:0

```

**Try it online**

Converts the input of the form `<value> <unit> <value> <unit>` into assignment statements. Then, use `eval` on every formula, with the `try/except` ignoring the errors from the ones for which the variables haven't been assigned.

Edit (190): Idk how the bug stayed in the program for 3 years, but I fixed the program giving some wrong answers. It was previously doing sqrt before dividing. The TIO program now runs all test cases at once.
> 3 votes

# Answer
# Python 3, ~~329~~ ~~347~~ ~~343~~ ~~339~~ ~~326~~ ~~305~~ ~~267~~ ~~251~~ ~~249~~ ~~245~~ 237 bytes

This is pretty bloated. There is definitely still a lot of golfing to do.

**Edit:** ~~Temporarily fixed the output. For some reason, `return' '.join(str(eval(z[m][i]))+t[i]for i in range(2))` refuses to work properly.~~

**Edit:** Dropped `eval`.

This function now borrows parts of Level River St's answer. I changed the `ops` dictionary, first into a dictionary of modified exponents `exponent*2+4` for `b**((p-4)/2) * d**((q-4)/2)`, so that each `p` and `q` would be a one digit number. For example, `b*d == b**1*d**1 == b**((6-4)/2)*d**((6-4)/2)`, and the result would be `66` in the dictionary.

Then, I turned the dictionary into a string `z` with those modified exponents and the units that are needed in a line and in a particular order. First, the ASCII value of each character in `ARVW` mod 10 is `5, 2, 6, 7`. When any two of these values are added, they give a unique number mod 10. Thus, each two-character combination can be given a unique number with `(ord(x[0]) + ord(y[10] + 3) % 10`, giving `AR: 0, AV: 4, AW: 5, RV: 1, RW: 2, VW: 6` (very similar to Lever River St's checksum). Arranging the modified exponents to be in this order, i.e. `[AR] [RV] [RW] [blank] [AV] [AW] [VW]`, allows `z` to be accessed efficiently (in terms of bytes).

**Edit:** Golfed the list comprehension under `return`. Golfed the definition of `m`.

## Code:

```
def e(s):x,y=sorted((i[-1],float(i[:-1]))for i in s.split());m=(ord(x[0])+ord(y[0])+3)%10*6;z="6686VW2628AW3555AV0000002666RW0626RV2682AR";return' '.join(str((x[1]**(int(z[m+i*2])-4)*y[1]**(int(z[m+i*2+1])-4))**.5)+z[m+i+4]for i in(0,1))

```

**Ungolfed:**

```
def electric(s):
    x, y = sorted((i[-1],float(i[:-1]))for i in s.split())
    m = (ord(x[0]) + ord(y[0]) + 3) % 10 * 6
    z = "6686VW2628AW3555AV0000002666RW0626RV2682AR"
    h = []
    for i in range(2):
         f = (x[1] ** (int(z[m*6+i*2])-4) * y[1] ** (int(z[m*6+i*2+1])-4)) ** 0.5
         h.append(str(f)+z[m*6+i+4])
    return ' '.join(h)

```
> 2 votes

---
Tags: code-golf, physics, electrical-engineering
---


title: Evaluate a simple spreadsheet

text:
# Question
Title: Evaluate a simple spreadsheet
## Rules

1. No cell range references (`A2:B3`).
2. Maximum 9 rows and 9 columns.
3. No circular references or formula errors.
4. Empty cells evaluate to `0`.
5. Data are numbers only, but may be taken as strings.
6. Formulas are strings.

## Implementation choices

You must state your choices in these matters:

7. Require formulas to be prefixed with any single character, e.g. `=` – or not.
8. The leftmost cell of the second row is `A2` or `R2C1`, as per the two conventions used by Excel et al.
9. Require any single-character pre- or suffix in cell references, e.g. `$` – or not.
10. One of null, empty string, empty list, etc., (but not `0`) to represent empty cells.
11. Language of your submission (spreadsheet managers are not allowed).
12. Language for the formulas (may differ from the above).\*
13. Brownie points or cookies for explaining your solution.

## Examples

Choices: 7: `=`; 8: `A2`; 9: none; 10: `""`; 12: Excel Formula Language

### In:

```
[[       2, 3],
 ["=A1+B1",""]]

```

### Out:

```
[[2,3],
 [5,0]]

```

### In:

```
[[       2,"=A1+B2"],
 ["=A1+B1",      ""]]

```

### Out:

```
[[2,2],
 [4,0]]

```

### In:

```
[[ 3, 4,"=A1*B1"],
 [ 2, 5,"=A2*B2"],
 ["","","=C1+C2"]]

```

### Out:

```
[[3,4,12],
 [2,5,10],
 [0,0,22]]

```

### In:

```
[["","=2*B2*B3"     ,""],
 [ 3,"=A1+(A2+C2)/2", 2],
 [ 1,"=C1+(A3+C3)/2", 5]]

```

### Out:

```
[[0,15,  0],
 [3, 2.5,2],
 [1, 3  ,5]]

```

---

<sup>* The formula language must be PPCG admissible, but you only have to support cell references plus criteria 3 and 4 there, wiz. addition and primeness determination.</sup>

# Answer
> 6 votes
# JavaScript, ~~125~~ ~~112~~ 105 bytes

To use, add `f=` at the beginning and invoke like `f(argument)`.

```
a=>a.map(b=>b.map(p=>+p?p:p?eval(p.replace(/[A-I][1-9]/g,m=>`a[${m[1]-1}][${(m.charCodeAt(0)-65)}]`)):0))

```

### Choices:

7. Does not require `=`.
8. The left most cell of second row is `A2`.
9. Does not require any prefix or suffix.
10. `""` (Empty String) to denote empty cell.
11. JavaScript.
12. JavaScript.
13. Cookies.

### Explanation:

This solution iterates over all the cells of the worksheet (each element of the sub-arrays of the given array) and if non-empty String is found, replaces its cell references with the corresponding references in terms of the given array and evaluates the expression with `eval()` (yeah, that evil thing that haunts you in your nightmares). This solution assumes that the constants provided in the input array are of Integer type.

### Test Cases

```
f=a=>a.map(b=>b.map(p=>+p?p:p?eval(p.replace(/[A-I][1-9]/g,m=>`a[${m[1]-1}][${(m.charCodeAt(0)-65)}]`)):0))

console.log(f([[1,2,3],["A1+B1+C1",10,11]]));
console.log(f([[1,2,5,4,6,89,0],[0,1,2,3,"A2+A1",5,6]]));
console.log(f([[1,2,4,5],["A1/B1*C1+A1+Math.pow(5,B1)",2,3,4]]));
```

# Answer
> 4 votes
# PHP, ~~265 263 259 258 257 240 224 222 213 202~~ 196 bytes

featuring `array_walk_recursive`, a recursive anonymous function and `preg_replace_callback`:

```
function f(&$a){array_walk_recursive($a,$p=function(&$c)use($a,&$p){eval('$c='.preg_replace_callback("#R(.)C(.)#",function($m)use($a,&$p){$d=$a[$m[1]-1][$m[2]-1];$p($d);return$d;},$c?:0).';');});}

```

or

```
function f(&$a){array_walk_recursive($a,$p=function(&$c)use($a,&$p){eval('$c='.preg_replace_callback("#R(.)C(.)#",function($m)use($a,&$p){return$p($a[$m[1]-1][$m[2]-1]);},$c?:0).';');return$c;});}

```

operates on input: call by reference. Test it online.

* no expression prefix
* reference format `R2C1`, no prefix
* anything falsy for empty cell
* evaluates any (lowercase) PHP expression, including all arithmetics

**breakdown** (first version)

```
function f(&$a)
{
    array_walk_recursive($a,                    # walk through elements ...
        $p=function(&$c)use($a,&$p){            # use array $a and recursive $p
            eval('$c='.                             # 3. evaluate expression
                preg_replace_callback('#R(.)C(.)#', # 2. replace references with ...
                function($m)use($a,&$p){
                    $d=$a[$m[1]-1][$m[2]-1];            # $d=content of referenced cell
                    $p($d);                             # recursive evaluation
                    return$d;                           # return $d
                },$c?:0)                            # 1. replace empty with 0
                .';'
            );
        }
    );
}

```

# Answer
> 3 votes
## Mathematica, ~~119~~ ~~115~~ 95 bytes

```
(m=#/.""->0)//.s_String:>ToExpression@StringReplace[s,"R"~~x_~~"C"~~y_:>"m[["<>{x,",",y,"]]"}]&

```

Choices:

7. No prefix.
8. `R2C1` style.
9. No prefix or suffix.
10. `""` for empty cells.
11. Mathematica.
12. Mathematica. Arbitrary arithmetic expressions that don't use variables of the form `RxCy` and don't have side effects should work.

### Explanation

```
(m=#/.""->0)

```

We start by replacing all empty strings in the input (`#`) with zeros and storing the result in `m`, because we'll need this again in another place.

```
...//.s_String:>...

```

*Repeatedly* replace any remaining string `s` with the following...

```
...StringReplace[s,"R"~~x_~~"C"~~y_:>...]

```

Match any substrings of the form `RxCy` in `s` and replace them with...

```
..."m[["<>{x,",",y,"]]"}

```

Which gives `m[[x,y]]`, which uses `x` and `y` as indices into the matrix `m`.

```
...ToExpression@...

```

Finallz, evaluate this string as a Mathematica expression.

# Answer
> 3 votes
## Clojure, ~~263~~ 281 bytes

Oh damn without that `apply map vector` the result is in transpose, as `A2` is alphabetically before `B1`.

```
#(apply map vector(partition(count(% 1))(for[v(vals(loop[C(into{}(mapcat(fn[i r](map(fn[j v][(str j i)(or v"0")])"ABCDEFGHI"r))(rest(range))%))P[]](if(= C P)C(recur(into(sorted-map)(for[[k v]C][k(reduce(fn[r[K V]](clojure.string/replace r K V))v C)]))C))))](eval(read-string v)))))

```

Examples:

```
(def f #(...))

(f [["2" "3"]["(+ A1 B1)" nil]])
([2 3] [5 0])

(f [[nil ,"(* 2 B2 B3)"                ,nil],
    ["3" ,"(+ A1 (/ (+ A2 C2) 2))"     ,"2"],
    ["1" ,"(-> A3 (+ C3) (/ 2) (+ C1))","5"]])
([0 15N 0] [3 5/2 2] [1 3 5])

```
7. Formulas are S-expressions
8. `A2`
9. No, `(+ A1 A2)` is fine
10. `nil` and `false` work as empty cells, but empty string do not
11. Clojure
12. S-expressions (Clojure + any built-in macros)

An example of thread first macro:

```
(macroexpand '(-> A3 (+ C3) (/ 2) (+ C1)))
(+ (/ (+ A3 C3) 2) C1)

```

Starting value of `C` in the loop is a hash-map, keys are cell names and values are original values. Then all cell references are replaced by contents of referenced cells until we have converged (`P`revious = `C`urrent), then cells are evaluated and the flat structure is partitioned back into a nested list.

Would be cool to find a solution where `A1`, `A2` etc. are actually callable functions, then `(* 2 B2 B3)` could be rewritten to `(* 2 (B2) (B3))` and executed.

Try it online!

# Answer
> 3 votes
# APL (Dyalog), 51 bytes

```
⍎¨({((⍴⍵)↑⍉⎕A∘.,1↓⎕D),¨'←',¨⍵}{0::⍵⋄×≢⍵:⍕⍎⍕⍵⋄0}¨)⍣≡

```
7. None
8. `A2`
9. None
10. Empty string
11. APL
12. APL

Try it online!

`⍎¨` Evaluate each cell of the result from

`(``)⍣≡` continuous application of the following two functions until nothing more changes

`{` first anonymous function to be applied…

`0` on any
`::` error:
return the argument unmodified

now try;

if the argument's
tally:
`×` is positive
`:` then:
stringify
the evaluated
stringified
argument

else;

`0` return zero

… to each cell

`{` second anonymous function to be applied…

`'←',¨` prepend an assignment arrow to each cell of
the argument

`(``),¨` prepend the following to each cell of that

`1↓` drop the first of
`⎕D` the string of all **D**igits (i.e. zero)

`⎕A` With all the letters of the **A**lphabet going down,
`∘.,` make a concatenation table (with the remaining digits going right)

transpose (to get increasing numbers down, progressing letters right)

`(``)↑` take the upper left submatrix with the size of…

the size of
the argument

`}` … to the the previous function's result.

# Answer
> 1 votes
# Python 2 273,265,263, 259 bytes

```
import re
def g(m):x=m.group();return's[%d][%d]'%(int(x[1])-1,ord(x[0])-65)
e=enumerate
while'='in`s`:
    for x,i in e(s):
        for i,j in e(i):
            try:s[x][i]=0if not j else float(eval(re.sub('\w\d',g,str(j)).strip('=')))
            except:pass

```

Try it online!

**Choices:**

7. =
8. A2
9. none
10. ""
11. Python 2.7
12. Python expressions

**Basic explanation:**

For every formula in the sublist, substitute it with the corresponding list (that is, for B1 s\[0\]\[1\]) index and evaluate the result!

* -4 bytes by changing str() to backticks!

---
Tags: code-golf, matrix, data-structures
---


title: Line up for golf!

text:
# Question
Title: Line up for golf!
Alice, Bob, Carol, Dave, and Eve are going out for a nice game of golf and need your help to decide in what order they will play.

Your program will input some statements, which are defined as a condition, and then one or more optional logical boolean operators followed by another condition. (That's `[Condition]([Logical][Condition])*` in regexp notation.) A logical boolean operator is "and" or "or." You may chose either `and` or `or` to have higher precedence, as long as it is consistent.

A condition is a name, followed by the word "is," followed optionally by the word "not," followed by one of these:

* in front of
* behind
* n spaces in front of
* n spaces behind
* next to
* nth
* nth to last

An example of a valid condition is "Alice is not next to Bob".

Associativity is from left to right, except for "not," which only applies to a single statement. This means that "x or y and z or not a" means "((x or y) and z) or a," where x could be "Alice is 1st" or "Alice is behind Bob" or "Alice is not 2nd to last."

Your output must be the order in which the players line up, separated by commas, from front to back of the line.

Here's the full specification in regexp notation:

```
[Statement] = [FullCondition]([Logical][FullCondition])*
[FullCondition] = [Name] is [Condition]
[Condition] = (not)? (in front of|behind|[Number] space(s)? (in front of|behind)|next to|[Ordinal]|[Ordinal] to last)
[Logical] = and|or
[Number] = 1|2|3|4...
[Ordinal] = 1st|2nd|3rd|4th...

```

Standard methods of input and output. Input should be as a string, and output can be as a string or list. And finally, here are some sample inputs and outputs.

```
Input:
The players are Alice, Bob, and Carol.
Alice is 2nd.
Bob is in front of Alice.

Output:
Bob, Alice, Carol

Input:
The players are Alice, Bob, and Carol.
Alice is 1 space in front of Bob. // remember to handle pluralization correctly!
Carol is 1st to last.

Output:
Alice, Bob, Carol

Input:
The players are Alice, Bob, and Carol.
Alice is in front of Bob.

Output:
Alice, Bob, Carol
Carol, Alice, Bob // multiple outputs may be required

Input:
The players are Alice, Bob, and Carol.
Alice is in front of Bob.
Bob is in front of Alice.

Output:
// nothing

Input:
The players are Alice, Bob, and Carol.
Alice is not in front of Bob and Carol is not 2nd or Bob is 1st.

Output:
Carol, Bob, Alice
Bob, Alice, Carol
Bob, Carol, Alice

```

This is , so the shortest code in bytes will win!

A great many thanks to @Doorknob for posting this in the Secret Santa's Sandbox. Again, thank you.

# Answer
> 3 votes
## JavaScript (ES6), ~~554~~ ~~499~~ ... 463 bytes

Takes input as an array of strings and returns an array of arrays of strings. Parsing rule: `and` has higher precedence than `or`.

Below is a slightly formatted version. The compact version is included in the snippet.

```
([P,...C])=>
  [...Array(m=9349)]
  .map(_=>p[a=P.match(/[A-E]\w+/g).sort(_=>(k=k*2%m)&1)]?0:p[a]=a,p={},k=1)
  .filter(s=>
    s&&eval(
      C.join`and `.match(/.+?(or |and |$)/g)
      .map(s=>
        (
          c=s.match(/([A-E]\w+|\d|no|la|fr|be|x|p|or|an)/g),
          S=n=>`s.indexOf('${c[p+n]}')`,
          E=`]=='${c[0]}'`,
          c[p=1]=='no'?(p++,'!(s['):'(s['
        )+
        (
          (x=+c[p])&&p++,
          {
            la:'s.length-'+x+E,
            fr:F=S(1)+-1+E,
            be:B=S(1)+'+1'+E,
            x:F+'||s['+B,
            p:S(2)+(c[p+1]>'f'?-x:'+'+x)+E
          }[c[p]]||--x+E
        )+
        (c.pop()>'o'?')||':')&&')
      ).join``+1
    )
  )

```

### How it works

**1. Initialization**

The input array is split into:

* `P` = first line, describing the players
* `C` = array containing all other lines

We first extract the names of all players from `P`:

```
P.match(/[A-E]\w+/g)

```

We compute all permutations of the names, using several iterations of `sort()`:

```
sort(_ => (k = k*2 % 9349) & 1)

```

The prime `9349` was (empirically) chosen in such a way that all permutations are guaranteed to be found, given enough iterations of the sort, for up to 5 players.

**2. Filtering**

The main part of the function consists of filtering these permutations to keep only the ones that match all conditions in `C`.

We join the different condition lines with `and` and split the resulting string on `or` and `and` to get an array of conditions.

Each condition is parsed to isolate the relevant tokens:

```
Token          | RegExp part
---------------+------------
Name of player | [A-E]\w+
Digit          | \d
'not'          | no
'last'         | la
'in front of'  | fr
'behind'       | be
'next to'      | x
'spaces'       | p
'or'           | or
'and'          | an

```

Each condition is translated into JS code:

```
Condition                     | JS code
------------------------------+-------------------------------------------------------------
'X is Nth'                    | s[N - 1] == 'X'
'X is Nth to last'            | s[s.length - N] == 'X'
'X is in front of Y'          | s[s.indexOf('Y') - 1] == 'X'
'X is behind Y'               | s[s.indexOf('Y') + 1] == 'X'
'X is next to Y'              | s[s.indexOf('Y') - 1] == 'X' || s[s.indexOf('Y') + 1] == 'X'
'X is N spaces in front of Y' | s[s.indexOf('Y') - N] == 'X'
'X is N spaces behind Y'      | s[s.indexOf('Y') + N] == 'X'

```

Finally, all codes are joined with `||` and `&&` operators and the resulting string is `eval()`'d.

For example, below are the translations of the test cases as JS code:

```
(s[1]=='Alice')&&(s[s.indexOf('Alice')-1]=='Bob')&&1
(s[s.indexOf('Bob')-1]=='Alice')&&(s[s.length-1]=='Carol')&&1
(s[s.indexOf('Bob')-1]=='Alice')&&1
(s[s.indexOf('Bob')-1]=='Alice')&&(s[s.indexOf('Alice')-1]=='Bob')&&1
!(s[s.indexOf('Bob')-1]=='Alice')&&!(s[1]=='Carol')||(s[0]=='Bob')&&1

```

### Test cases

```
let f =

([P,...C])=>[...Array(m=9349)].map(_=>p[a=P.match(/[A-E]\w+/g).sort(_=>(k=k*2%m)&1)]?0:p[a]=a,p={},k=1).filter(s=>s&&eval(C.join`and `.match(/.+?(or |and |$)/g).map(s=>(c=s.match(/([A-E]\w+|\d|no|la|fr|be|x|p|or|an)/g),S=n=>`s.indexOf('${c[p+n]}')`,E=`]=='${c[0]}'`,c[p=1]=='no'?(p++,'!(s['):'(s[')+((x=+c[p])&&p++,{la:'s.length-'+x+E,fr:F=S(1)+-1+E,be:B=S(1)+'+1'+E,x:F+'||s['+B,p:S(2)+(c[p+1]>'f'?-x:'+'+x)+E}[c[p]]||--x+E)+(c.pop()>'o'?')||':')&&')).join``+1))

console.log(JSON.stringify(f([
  'The players are Alice, Bob and Carol.',
  'Alice is 2nd.',
  'Bob is in front of Alice.'
])));

console.log(JSON.stringify(f([
  'The players are Alice, Bob, and Carol.',
  'Alice is 1 space in front of Bob.',
  'Carol is 1st to last.'
])));

console.log(JSON.stringify(f([
  'The players are Alice, Bob, and Carol.',
  'Alice is in front of Bob.'
])));

console.log(JSON.stringify(f([
  'The players are Alice, Bob, and Carol.',
  'Alice is in front of Bob.',
  'Bob is in front of Alice.'
])));

console.log(JSON.stringify(f([
  'The players are Alice, Bob, and Carol.',
  'Alice is not in front of Bob and Carol is not 2nd or Bob is 1st.'
])));
```

# Answer
> 3 votes
# Python 3, ~~527~~ ~~524~~ 511 bytes

```
import re,itertools as I
S=re.sub
p=re.findall(r"\w+(?=[,.])",input())
l=[]
try:
 while 1:
  c=[["not "*("not "in c)+S(" .+o (.+)",r" in[\1+1,\1-1]",S(" .+f","+1==",S(" .+d","-1==",S(r" .+(\d+).+",r"+1==\1",S(r" .+(\d+).+st",r"==len(p)-\1",S(r" .+(\d+).+f",r"+\1==",S(r" .+(\d+) .+d",r"-\1==",c[:-1]))))))),c][len(c)<7]for c in re.split("(or|and) ",input())]
  while c[1:]:c[:3]=["("+" ".join(c[:3])+")"]
  l+=[c[0]]
except:print([P for P in I.permutations(p)if eval("and ".join(l),dict(zip(P,range(len(p)))))])

```

Try it online!

Outputs an array of valid permutations. Expects the names to only contain `A-Za-z0-9_` (`Alice` through `Eve` are obviously valid).

# Answer
> 2 votes
# PHP, way too long (~~790 744 725 697 678~~ 669 bytes)

```
foreach(file(F)as$i=>$s)if($i){$g("#(.*)( and | or |\.)#U",$s,$w,2);foreach($w as $q){preg_match("#^(\w+)(.*?)(\w+)$#",$q[1],$m);$n=$u[-3+$p=($o=strpos)($u=$m[2],p)];$d.="!"[!$o($u,no)]."(".strtr(!$o($u,x)?A.($o($u,f)?$p?"==B-$n":"<B":($o($u,b)?$p?"==B+$n":">B":"==".preg_replace("#.*(\d).*#",($k=$o($u,a))?"$z-$1":"$1",$k?$u:$m[3]))):"(A-B)**2<2",[A=>$m[1],B=>$m[3]]).")$q[2]";}$d=!$x.="&"[!$x]."($d)";}else{($g=preg_match_all)("#(\w+)[.,]#",$s,$m);$z=count($y=$m[1]);}for(;$j++<10**$z;)if(count_chars($p="$j",3)==join(range(1,$i=$z))){for($c=$x;$i--;)$c=strtr($c,["."=>"","not"=>"",$y[$p[$i]-1]=>$i+1]);for(;eval("return$c;")&++$i<$z;)echo$y[$p[$i]-1],"
,"[$i<$z-1];}

```

takes input from file `F`, no trailing newline; `and` before `or`. Run with `-nr` or test it online.

**breakdown**

```
foreach(file(F)as$i=>$s)if($i)              # loop through input lines
{
    $g("#(.*)( and | or |\.)#U",$s,$w,2);       # split statement to conditions
    foreach($w as $q)
    {
        preg_match("#^(\w+)(.*?)(\w+)$#",$q[1],$m); # 1. copy names to $m[1],$m[3]
        $n=$u[-3+$p=($o=strpos)($u=$m[2],p)];       # 2. remove names, 3. find N in "N spaces"
        $d.="!"[!$o($u,no)]."(".                    # 4. negate, 6. concatenate
            strtr(                                  # 5. translate condition:
            !$o($u,x)
            ?A.($o($u,f)?$p?"==B-$n":"<B"               # (N spaces) in front of
            :($o($u,b)?$p?"==B+$n":">B"                 # (N spaces) behind
            :"==".preg_replace("#.*(\d).*#",            # N-th
                ($k=$o($u,a))?"$z-$1":"$1"                  # ... (to last)
                ,$k?$u:$m[3])
            ))
            :"(A-B)**2<2"                               # next to
        ,[A=>$m[1],B=>$m[3]])
        .")$q[2]";
    }
    $d=!$x.="&"[!$x]."($d)";                    # concatenate statements, clear statement
}else                                           # first line: import names to $y, count to $z
{($g=preg_match_all)("#(\w+)[.,]#",$s,$m);$z=count($y=$m[1]);}
                                            # loop through combinations
for(;$j++<10**$z;)if(count_chars($p="$j",3)==join(range(1,$i=$z))){
    for($c=$x;$i--;)                            # remove dot and "not", replace names
        $c=strtr($c,["."=>"","not"=>"",$y[$p[$i]-1]=>$i+1]);
                                                # all conditions met? print combination!
    for(;eval("return$c;")&++$i<$z;)echo$y[$p[$i]-1],"\n,"[$i<$z-1];
}

```

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


title: Am I Under Budget?

text:
# Question
Title: Am I Under Budget?
# Am I under Budget?

Every 2 weeks when I get my cheque, I allocate a certain amount to last me until my next cheque, and bank the rest. To figure out how much I can spend per day and still remain under/on budget, I just need to divide the allocated amount by the number of days it needs to last me.

On Day 1 if the budget period is 14 days and I start with $400, I can spend ($400 / 14 =) $28.57 a day.

If I go over budget on any days though, I have less to spend during the rest of the budget period.

Say I spend $50 on Day 1. I now have $350 starting Day 2, and can only spend ($350 / 13 =) $26.92 a day instead of $28.57 for the remainder of the period.

# Problem

Write a program/function that when given a starting allocation and a list of daily expenditures, returns a list of how much I could spend on each day to stay on budget, and a symbol indicating whether or not I was over/under/on budget that day.

# Example

Pretend for this example the budget period is only 5 days.

* Period Allocation = $100
* Daily Expenditures = \[20, 20, 30, 0, 0\]

This should return (output variations are allowed. See Output section):

```
["= 20", "= 20", "^ 20", "V 15", "V 30"]

```
* On Day 1, I can spend (100 / 5 =) $20. I spent the entire daily budget, so I was on budget (`=`). The first entry of the result is "= 20" to show this.
* On Day 2, I can spend (80 / 4 =) $20. Again, I spent the entire amount, so the second result entry is the same as the first.
* On Day 3, I can again spend (60 / 3 =) $20, but I went over budget by spending $30! I was allowed to spend $20, but went over, so the third result entry is "^ 20"; "^" meaning "over-budget.
* On Day 4, I can spend (30 / 2 =) $15. I spent nothing however, so I was under budget. The fourth result entry will be "V 15"; "V" meaning "under-budget".
* On Day 5, I can spend (30 / 1 =) $30. I again spent nothing and was under budget, so the fifth and final result entry is "V 30".

# Input

Input will be:

* A number representing the total money allocated for the period.
* A sequence representing how much was spent on each day during the period

The number of days in a period is = to the length of the daily expenditure list.

## Input Rules:

* Your program must handle decimal allocation amounts.
* The allocation amount can be taken as a number or string. A dollar sign is allowed for string representations (but optional).
* You can assume the budget period will be at least a day long (daily expenditure list will contain at least 1 entry).
* You can assume I won't spend more money than I allocated.
* A delimited string would also be a acceptable form of input

# Output

Output will be a sequence of symbols and numbers showing how much I was allowed to spend on that day, and whether or not I went over.

Output can be returned or printed to the stdout.

## Output Rules:

* Any non-numeric symbols can be used to indicate on/under/over budget, as long as you chose a different symbol for on, under and over. If you don't use "="/"V"/"^", make sure to specify in your answer what symbols you're using.
* The symbol can appear before or after the number
* Output can be any form of sequence where it's clear what parts belong to what day. The examples here use a sequence of strings, but a sequence of pairs/lists would be fine as well.
* Output must be accurate to at least 2 decimal places (but more is fine). It must be properly rounded using 4/5 rounding if only accurate to 2 places.
* A long string instead of a sequence of strings is fine too, as long as there's some delimiter separating output for each day so it's readable.

# Test Cases

```
10, [1, 2, 3, 4, 0]
["V 2", "V 2.25", "^ 2.33", "^ 2", "= 0"]

25, [20, 2, 3]
["^ 8.3", "V 2.5", "= 3"]

1000, [123, 456, 400]
["V 333", "^ 438.5", "V 421"]

500, [10, 200, 0, 0, 100, 50, 50]
["V 71.43", "^ 81.67", "V 58", "V 72.5", "^ 96.67", "V 70", "V 140"]

```

This is code golf, so the smallest number of bytes wins.

# Answer
# Javascript, ~~67~~ 66 bytes

```
a=>b=>b.map(c=>`v=^`[(c>(e=((a-=c)+c)/d--))-(c<e)+1]+e,d=b.length)

```

# Explanation

This is an anonymous function that takes input through currying syntax (`f(a)(b)`). In this case, the fist number is the total budget, and b is an array of the money spent during the time period.

The function loops over `b`, but first sets `d` to the length of the array `b`. Then, for each element `c` in `b`, an inner function is executed (``v=^`[(c>(e=((a-=c)+c)/d--))-(c<e)+1]+e`). This inner function calculates the budget for that day by dividing the amount left (`a`) by the number of days left (`d`). This results in `0` if the amount spent today is smaller than the budget, `1` if both are equal, and `2` otherwise. This is then used as index into a string with the correct symbols, and then the budget for this day is appended to that.

Afterwards, both the amount of money left and the number of days left are decreased; the former by `c`, the money spent on this day, and the latter by `1`. It turned out that the shortest way to write this is to decrement `a` inside the division, and then add `c` to it, so the actual numerator is just `a`.

# Usage

Uses currying syntax. There might be a really small error in the intermediate values, because of the way JavaScript deals with arithmetic.

# Test it

Try all test cases here:

```
let f=
a=>b=>b.map(c=>`v=^`[(c>(e=((a-=c)+c)/d--))-(c<e)+1]+e,d=b.length)

let testcases = [[100, [20, 20, 30, 0, 0]], [10, [1, 2, 3, 4, 0]], [25, [20, 2, 3]], [1000, [123, 456, 400]], [500, [10, 200, 0, 0, 100, 50, 50]]];
for (let test of testcases) {
    console.log(`f(${test[0]})(${test[1].join(", ")}): ${f(test[0])(test[1])}`);
}
```
> 4 votes

# Answer
# Python 3, 112 97 82 bytes

```
def f(a,b):
 l=len(b)
 for i in b:e=a/l;print('=v^'[(e>i)-(e<i)]+str(e));a-=i;l-=1

```

Try it online!

* **saved 15 bytes!!!! thanks to Luke**
* saved 15 bytes: removed unwanted variable r
> 3 votes

# Answer
# Röda, 65 bytes

```
f p,e{a=#e;e|{|b|x=p/a-b;[("=V^"/"")[x//x^2^0.5],p/a];p-=b;a--}_}

```

Try it online!

A simple imperative solution. Returns a letter and a number for each day. Uses `x//x^2^0.5` to calculate the sign of `x`.

Functional programming version (76 bytes):

```
f p,e{seq#e,1<>e|[(p-sum(e[:#e-_]))/_1-_,_2]|[("=v^"/"")[_//_1^2^0.5],_1+_]}

```
> 2 votes

# Answer
## Haskell, 75 bytes

```
m#l@(a:b)=((,)=<<("V=^"!!).fromEnum.compare a$m/sum[1|x<-l]):(m-a)#b
_#_=[]

```

Usage example: `25 # [20, 2, 3]` -\> `[('^',8.333333333333334),('V',2.5),('=',3.0)]`. Try it online!

How it works:

```
m#l@(a:b)=                   -- if the list of spendings has at least one
                             -- element a, the result is
 (,)                         -- a pair of two times
         m/sum[1|x<-l]       --  m / <length of the input list>
                                 (the library function 'length' is of type 'Int',
                                 so I can't use it with '/')
    =<<                      --  but the first element is modified by
      ("V=^"!!).fromEnum.compare a
                             --  picking a char from the string "V=^"
                             --  depending on the result of comparing it to a
           :(m-a)#b          -- followed by a recursive call with all but the first
                             -- spending and m adjusted

_#_=[]                       -- base case: if the list of spendings is empty, the
                             -- result is also the empty list

```
> 1 votes

# Answer
# Python 3, 77 bytes

```
def f(a,l):
 d=len(l)
 for i in l:e=a/d;d-=1;print('=v^'[(e>i)-(e<i)],e);a-=i

```

Try it online!

* using `'=v^'[(e>i)-(e<i)]` save a chunk of bytes. Thanks to Luke.
* Saved some bytes by assigning `len(l)` to a variable and then decrementing it instead od holding another variable.
> 1 votes

# Answer
# Java (OpenJDK 8), 140 bytes

```
class B{void f(float a,float[]l){int d=l.length;for(float i:l){float e=a/d;d--;a-=i;System.out.format("%s%f ",(e<i)?'v':(e>i)?'^':'=',e);}}}

```

Try it online!

Ungolfed!

```
class B {
 void f(float a, float[] l) {
  int d = l.length;
  for (float i: l) {
   float e = a / d;
   d--;
   a -= i;
   System.out.format("%s%f ", (e < i) ? 'v' : (e > i) ? '^' : '=', e);
  }
 }
}

```
> 1 votes

---
Tags: code-golf
---