title: Help me golf my numbers!

text:
# Question
Title: Help me golf my numbers!
When writing programs, I usually end up using some numeric constants. I always put them in decimal because that's how I think, but I just realized that my language supports other number formats that might let me shorten my code slightly.

# Challenge

Given a non-negative integer less than 2^53-1, decide whether that integer has the shortest representation in:

* Decimal
* Hexadecimal
* Scientific Notation

### Decimal

Since this is the default format of my language, there is no extra notation needed for this format. Every number is represented as usual for decimal.

### Hexadecimal

My languages uses the `0x` prefix for hexadecimal constants. This means that if a number has 4 hexadecimal digits, it will take 6 bytes to represent that number.

### Scientific notation

My language uses the following format for scientific notation:

> \[Real base\]e\[Integer exponent of 10\]

For example, `700` would be represented as `7e3`, and `699` would be represented as `6.99e3`, because *the base must be between -10 and 10* (non-inclusive). For the purposes of this challenge, the base will always be at least 0, since the inputted number is non-negative.

# Output

You should return a way of identifying which format is shortest (i.e. 0 for decimal, 1 for hex, 2 for scientific). Alternatively, you may output the smallest representation of the number itself.

# Test cases

```
Decimal       | Hexadecimal  | Scientific        | Winner
--------------|--------------|-------------------|-------------
0             | 0x0          | 0e0               | Decimal
15            | 0xF          | 1.5e1             | Decimal
6999          | 0x1B57       | 6.999e3           | Decimal
7000          | 0x1B58       | 7e3               | Scientific
1000000000000 | 0xE8D4A51000 | 1e12              | Scientific
1000000000001 | 0xE8D4A51001 | 1.000000000001e12 | Hexadecimal
1000000001000 | 0xE8D4A513E8 | 1.000000001e12    | Hexadecimal
1000001000000 | 0xE8D4B45240 | 1.000001e12       | Scientific

```

# Scoring

This is , so the answer in the shortest bytes for each language wins.

# Answer
# 05AB1E, 23 bytes

```
hgÌ¹gD<g>¹ÀðìÁ0ÜðÜg+)Wk

```

Try it online!

-1 thanks to Emigna.

`0` for hexadecimal, `1` for decimal, `2` for scientific.
> 5 votes

# Answer
# 05AB1E, 27 bytes

```
Dg<¹À'.ìÁ0Ü'.Ü…ÿeÿIh…0xÿ)é¬

```

Try it online!

**Explanation**

```
D                            # duplicate input, one copy will be used as decimal notation
 g<                          # len(input)-1
   ¹À                        # push input and rotate left
     '.ìÁ                    # prepend a dot and rotate right
         0Ü'.Ü               # remove trailing zeroes and then any trailing dot
              …ÿeÿ           # format scientific notation
                  Ih         # input converted to hex
                    …0xÿ     # format hex
                        )    # wrap in a list
                         é   # sort by length
                          ¬  # get the first (shortest) item

```
> 4 votes

# Answer
# Jelly, 28 bytes

```
TṀµỊ¬+‘
DµL’DL+Ç,L
b⁴L+2;ÇỤḢ

```

A monadic link returning `1`, `2`, or `3` for hexadecimal, scientific, or decimal respectively.

**Try it online!** or see a test suite.

*I thought this would be shorter, but I can't see it so am posting.*

### How this monstrosity works...

```
TṀµỊ¬+‘    - Link 1, length of mantissa + "e": list of decimal digits  e.g. [7,0,1,0]
T          - truthy indexes                                                 [1,  3  ]
 Ṁ         - maximum                                                             3
  µ        - monadic chain separation, call that m
   Ị       - insignificant? (abs(m)<=1) -- here: 1 for m=1, 0 otherwise          0
    ¬      - logical not                  i.e. 1 if a "." will be used           1
     +     - add m                                                               4
      ‘    - increment                    always uses an 'e'                     5

DµL’DL+Ç,L - Link 2, lengths of scientific and decimal notations: non-negative-integer, n
D          - cast to decimal list
 µ         - monadic chain separation, call that d
  L        - length of d (number of decimal digits of n)
   ’       - decrement (value of exponent)
    D      - cast to decimal list (exponent's digits)
     L     - length (number of characters in the exponent)
       Ç   - call last link (1) as a monad(d) (number of characters in mantissa + "e")
         L - length of d (number of decimal digits of n)
        ,  - pair

b⁴L+2;ÇỤḢ - Main link: non-negative-integer, n
 ⁴        - literal 16
b         - convert n to base 16
  L       - length (number of hexadecimal digits)
   +2     - add two (number of characters including the "0x")
      Ç   - call the last link (2) as a monad (characters in scientific and decimal)
     ;    - concatenate ([charsInHexadecimal, charsInScientific, charsInDecimal])
       Ụ  - sort indexes by value
        Ḣ - head (1-based-index in the above list of (one of) the shortest)

```
> 3 votes

# Answer
# JavaScript (ES6), 90 bytes

Returns 0 for decimal, 1 for hexadecimal, -1 for scientific.

```
n=>(l=Math.log,D=l(n)/l(10),H=l(n)/l(16)+2,S=n.toExponential().length-1,S<H?-(S<D):+(H<D))

```

```
f=
n=>(l=Math.log,D=l(n)/l(10),H=l(n)/l(16)+2,S=n.toExponential().length-1,S<H?-(S<D):+(H<D))

console.log(
    f(0),
    f(15),
    f(6999),
    f(7000),
    f(1000000000000),
    f(1000000000001),
    f(1000000001000),
    f(1000001000000)
)
```

## Explanation

* `log(n) / log(10)`: base-10 logarithm of `n`; roughly the length of `n` as a decimal.
* `log(n) / log(16) + 2`: base-16 logarithm of `n` plus 2; roughly the length of `n` as a hexadecimal plus the prepended `0x`.
* `n.toExponential().length - 1`: `n.toExponential()` returns a string with `n` in scientific format (e.g. `7e+3`) but we subtract 1 from its length to account for the extraneous `+`.

Now that we have the lengths of all 3 representations `D`, `H`, and`S`, we compare:
`S<H?-(S<D):+(H<D)`

---

# JavaScript (ES6), 97 bytes

This one outputs the number in the format with the shortest length. Inspired by @Shaggy's deleted attempt.

```
n=>[n+'','0x'+n.toString(16),n.toExponential().replace('+','')].sort((x,y)=>x.length-y.length)[0]

```

```
f=
n=>[n+'','0x'+n.toString(16),n.toExponential().replace('+','')].sort((x,y)=>x.length-y.length)[0]

console.log(
    f(0),
    f(15),
    f(6999),
    f(7000),
    f(1000000000000),
    f(1000000000001),
    f(1000000001000),
    f(1000001000000)
)
```
> 2 votes

# Answer
# C#, ~~106~~ ~~97~~ ~~96~~ ~~143~~ 132 bytes

```
using System.Linq;n=>new[]{n+"",$"0x{n:X}",(n+"").Insert(1,".").TrimEnd('0','.')+"e"+((n+"").Length-1)}.OrderBy(s=>s.Length).First()

```

Annoyingly in C# the `ulong.ToString` format specifier `e` loses precision on the higher numbers so I've had to do it manually. There's probably a shorter way to do it but this works for now. It also formats it incorrectly for this challenge so I would have to manually strip it's output anyway.

If I set a string to the value of `n` as `var s=n+"";` it works out longer because of the explicit return and extra curly braces.

It returns the shortest value from the array of each different value where `[0] = decimal, [1] = hexadecimal, [2] = scientific`.

Full/Formatted version:

```
using System.Linq;
Func<ulong, string> f = n =>
    new[]
    {
        n + "",
        $"0x{n:X}",
        (n + "").Insert(1, ".").TrimEnd('0', '.') + "e" + ((n + "").Length - 1)
    }.OrderBy(s => s.Length).First();

```

The correct way to calculate the scientific output is:

```
(n < 1 ? n + "" : (n + "").Insert(1, ".").TrimEnd('0', '.')) + "e" + ((n + "").Length - 1)

```

However, seeing as `0` is shorter than `0e0` I can remove that special case.
> 1 votes

# Answer
# Python 2, ~~83~~ 77 bytes

Outputs the smallest representation of the number.

```
import re
lambda n:min(`n`,hex(n),re.sub('\.?0*e\+0?','e','%.15e'%n),key=len)

```

**Try it online**

**Ungolfed:**

```
import re
n=input()
d=`n`
h=hex(n)
s=re.sub('(.)\.?0*e\+0?',r'\1e','%.15e'%n)
print min(d,h,s,key=len)

```

The regex removes trailing zeros and the decimal point if necessary, as well as the plus sign and leading zero from the exponent if there is one.
> 1 votes

# Answer
# Ohm, 35 bytes

```
l┼xl2+┼DRîsRl≥al≤Dla°┼îa/ì\?≥;+WD╤k

```

Try it online!

Outputs 0 for decimal, 1 for hex and 2 for scientific.

Explanation:

```
l                                      Implicit input, get length
 ┼                                     Input again
  x                                    To hex
   l                                   Get length
    2+                                 Add 2 because of "0x"
      ┼                                Get input again
       D                               Duplicate on the stack
        RîsR                           Remove zeroes at the end (reverse, to int, to string, reverse)
            l                          Get length (= length of base)
             ≥                         Add 1 because to count "e" in the scientific notation
              a                        Swap top two values on the stack
               l≤                      Get length - 1 ( = get the exponent of 10 in scientific notation)
                 D                     Duplicate on the stack
                  l                    Get length ( = length of the exponent)
                   a                   Swap. Now on top of the stack we have the exponent again
                    °                  10^exponent
                     ┼î                Get input for the fourth time
                       a/              Divide input by the 10^exp calculated earlier
                         ì\?           If this thing is not an integer...
                            ≥;         ...add one to count the "."
                              +        Sum base length ( + "e") + exponent length ( + ".")
                               W       Wrap stack in array
                                D      Duplicate
                                 ╤k    Get index of min value

```
> 1 votes

# Answer
# C, 187185 bytes

```
main(){long long N;scanf("%lli",&N);long long D=log10(N)+1,H=log(N)/log(16)+3,F,S,i=1;while(N>i&&!(N%i))i*=10,F++;S=ceil(log10(D-1))+1+D-F+(D-F>1);printf("%i",N?H>D?2*(D>S):1+(H>S):N);}

```

Decompressed:

```
void main(){
    long long N;
    scans("%lli", &N);
    long long D = log10(N) + 1; // Length of number (decimal)
    long long H = log(N)/log(16) + 3; // Length of number (hexadecimal)
    long long F; // Number of 0s at the end of decimal number
    long long S; // Length of number (scientific notation)
    long long i; // Counter (more or less)
    // Get number of zeros at the end of decimal number
    while(N > i && (N % i) == 0){
        i = i * 10;
        F++;
    }
    S = ceil(log10(D - 1)) + 1 + D - F + (D-F>1); // (Power) + (e) + (multiplier + (1 if len(multiplier) > 1))
    printf("%i", N!=0 ?
                (H > D ? 2 * (D > S) : 1 + (H > S))
              : 0); // Print the shortest number
}

```

Prints 0 for decimal, 1 for hex, 2 for scientific notation.
> 0 votes

# Answer
# PHP, 90 bytes

prints 0 for decimal, 1 for hexadecimal and 2 for scientific

in case of a tie the highest number will be print

```
<?=array_flip($m=[$l=log10($a=$argn)^0,2+(log($a,16)^0),strlen(($a/10**$l).$l)])[min($m)];

```

Try it online!

# PHP, 91 bytes

prints 0 for decimal, 1 for hexadecimal and 2 for scientific

in case of a tie the lowest number will be print

```
<?=array_search(min($m=[$l=log10($a=$argn)^0,2+(log($a,16)^0),strlen(($a/10**$l).$l)]),$m);

```

Try it online!

# PHP, 103 bytes

prints 0 for decimal, 1 for hexadecimal and 2 for scientific

in case of a tie all numbers will be print

```
foreach($m=[$l=log10($a=$argn)^0,2+(log($a,16)^0),strlen(($a/10**$l).$l)]as$k=>$v)echo$v-min($m)?"":$k;

```

Try it online!

# PHP, 109 bytes

Output an array with the shortest solutions

```
for(;!$p=preg_grep("#^.{".++$i."}$#",[$a=$argn,"0x".dechex($a),$a/10**($l=log10($a)^0)."e$l"]););print_r($p);

```

Try it online!
> 0 votes

# Answer
# TI-Basic, 130 bytes

```
Input N:If not(N:Goto 0:1+int(log(N→D:3+int(logBASE(N,16→H:0→F:1→I:While N>I and not(fPart(N/I:10I→I:F+1→F:End:log(D-1→L:1+D-F+(D-F>1):Ans+int(L)+(0≠fPart(L→S:(H>D)2(D>S)+(H≤D)(1+(H>S)→N:Lbl 0:N

```

Or, alternatively:

```
�N>θN>�0>1p��ND>3p�������BASEN+16H>0F>1I>�NlI@��N�I>10II>Fp1F>�>�Dq1L>1pDqFpDqFl1>rp�Lp0o�LS>HlD2DlSpHmD1pHlSN>�0>N

```

Or, in hex:

```
dc4e3eceb84e3ed7303e3170b1c04e04443e3370b1bbbcbbbfbbb642415345104e2b313604483e3004463e3104493ed14e6c4940b8ba4e83493e31304904493e46703104463ed43ec0447131044c3e317044714670104471466c31113e7270b14c117010306fba4c04533e10486c44113210446c53117010486d441110317010486c5311044e3ed6303e4e

```

Prints 0 for decimal, 1 for hex, 2 for scientific notation
> 0 votes

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


# Question
Title: Can my favourite team still become Football Champion?
As a fan of an at most moderately successful footballBE team, towards the end of the season I often wonder whether my favourite team still has any theoretical chance left of becoming champion. Your task in this challenge is to answer that question for me.

# Input

You will recieve three inputs: the current table, the list of remaining matches, and the current position of the team we are interested in.

**Input 1:** The *current table*, a sequence of numbers were the *i*-th number are the points gained by team *i* so far. For example, the input `[93, 86, 78, 76, 75]` encodes the following table (only the last column is of importance):

---

**Input 2**: The *remaining matches*, a sequence of tuples where each tuple (*i*,*j*) stands for a remaining match between team *i* and *j*. In the above example, a second input of `[(1,2), (4,3), (2,3), (3,2), (1,2)]` would mean that the remaining matches are:

```
Chelsea vs Tottenham, Liverpool vs Man. City, Tottenham vs Man. City, Man. City vs Tottenham, Chelsea vs Tottenham

```

---

**Input 3:** The *current position* of the team we are interested in. For example, an input of `2` for the above example would mean that we'd like to know whether Tottenham can still become champion.

# Output

For each remaining match of the form (*i*,*j*), there are three possible outcomes:

* Team *i* wins: Team *i* gets **3 points**, team *j* gets **0 points**
* Team *j* wins: Team *i* gets **0 points**, team *j* gets **3 points**
* Draw: Team *i* and *j* both get **1 point**

You must output a truthy value if there is some outcome for all remaining games such that at the end, no other team has more points than the team specified in the 3rd input. Otherwise, output a falsy value.

**Example**: Consider the exemplary input from the above section:

Input 1 = `[93, 86, 78, 76, 75]`, Input 2 = `[(1,2), (4,3), (2,3), (3,2), (1,2)]`, Input 3 = `2`

If team `2` wins all its remaining matches (i.e. `(1,2), (2,3), (3,2), (1,2)`), it gets 4\*3 = 12 additional points; none of the other teams gets any points from these matches. Let's say the other remaining match (i.e. `(4,3)`) is a draw. Then the final scores would be:

```
 Team 1: 93, Team 2: 86 + 12 = 98, Team 3: 78 + 1 = 79, Team 4: 76 + 1 = 77, Team 5: 75

```

This means that we have already found some outcome for the remaining matches such that no other team has more points than team `2`, so the output for this input must be truthy.

# Details

* You may assume the first input to be an ordered sequence, i.e. for *i* \< *j*, the *i*-th entry is equal to or greater than the *j*-th entry. The first input may be taken as a list, a string or the like.
* You may take the second input as a string, a list of tuples or the like. Alternatively, you may take it as a two-dimensional array `a` where `a[i][j]` is the number of entries of the form `(i,j)` in the list of remaining matches. For example, `a[1][2] = 2, a[2][3] = 1, a[3][2] = 1, a[4][3] = 1` corresponds to `[(1,2), (4,3), (2,3), (3,2), (1,2)]`.
* For the second and third input, you may assume 0-indexing instead of 1-indexing.
* You may take the three inputs in any order.

Please specify the exact input format you chose in your answer.

**Side node**: The problem underlying this challenge was shown to be NP-complete in "Football Elimination is Hard to Decide Under the 3-Point-Rule". Interestingly, if only two points are awarded for a win, the problem becomes solvable in polynomial time.

# Test Cases

All test cases are in the format `Input1`, `Input2`, `Input3`.

**Truthy:**

* `[93, 86, 78, 76, 75]`, `[(1,2), (4,3), (2,3), (3,2), (1,2)]`, `2`
* `[50]`, `[]`, `1`
* `[10, 10, 10]`, `[]`, `3`
* `[15, 10, 8]`, `[(2,3), (1,3), (1,3), (3,1), (2,1)]`, `2`

**Falsy:**

* `[10, 9, 8]`, `[]`, `2`
* `[10, 9, 9]`, `[(2,3), (3,2)]`, `1`
* `[21, 12, 11]`, `[(2,1), (1,2), (2,3), (1,3), (1,3), (3,1), (3,1)]`, `2`

# Winner

This is , so the shortest correct answer (in bytes) wins. The winner will be chosen one week after the first correct answer is posted.

# Answer
> 4 votes
# Haskell (Lambdabot), 84 bytes

Thanks to @bartavelle for saving me a byte.

Without Lambdabot, add 20 bytes for `import Control.Lens` plus a newline.

The function takes its arguments in the same order as described in the OP, 0-indexed. Its second argument (the list of remaining matchups) is a flat list of indexes (e.g. `[1,2,4,1]` corresponds to `[(Team 1 vs Team 2), (Team 4 vs Team 1)]`).

The rules are a little vague as to whether or not this is allowed. If it isn't allowed, the function can take input in the format provided by the examples – a list of tuples. In that case, add 2 bytes to this solution's score, due to replacing `a:b:r` with `(a,b):r`.

```
(!)=(+~).element
(t?(a:b:r))s=any(t?r)[a!3$s,b!3$s,b!1$a!1$s]
(t?_)s=s!!t==maximum s

```

### Explanation:

The first line defines an infix function `!` of three variables, of type `(!) :: Int -> Int -> [Int] -> [Int]`, which increments the value at a given index in a list. Since, oftentimes, code is easier to understand than words (and since Haskell syntax can be weird), here's a Python translation:

```
def add(index, amount, items):
    items[index] += amount
    return items

```

The second line defines another infix function `?`, also of three variables (the challenge input). I'll rewrite it more readably here:

```
(t ? a:b:r) s = any (t ? r) [a ! 3 $ s, b ! 3 $ s, (b ! 1 $ a) ! 1 $ s]
(t ? _) s = (s !! t) == maximum s

```

This is a recursive implementation of exhaustive search. It recurs over the list of remaining games, branching on the three possible outcomes, and then, once the list is empty, checking whether or not our team has the maximum number of points. Again in (non-idiomatic) Python, this is:

```
def can_still_win(standings, games_left, our_team):
    if games_left == []:
        return standings[our_team] == max(standings)
    team1, team2, other_games = games_left[0], games_left[1], games_left[2:]
    team1Wins, team2Wins, tie = standings.copy(), standings.copy(), standings.copy()
    team1Wins[team1] += 3
    team2Wins[team2] += 3
    tie[team1] += 1
    tie[team2] += 1
    return (can_still_win(team1Wins, other_games, our_team)
            or can_still_win(team2Wins, other_games, our_team)
            or can_still_win(tie, other_games, our_team))

```

Try it online!

*Sadly, TiO doesn't support Lens, so this link won't actually run.

# Answer
> 3 votes
# Microsoft SQL Server, 792 bytes

```
CREATE FUNCTION my.f(@s XML,@m XML,@ INT)RETURNS TABLE RETURN
WITH s AS(SELECT s.value('@p','INT')p FROM @s.nodes('S')s(s)),
m AS(SELECT m.value('@i','INT')i,m.value('@j','INT')j FROM @m.nodes('M')m(m)),
a AS(SELECT ROW_NUMBER()OVER(ORDER BY-p)t,p FROM s),
b AS(SELECT p+3*(SELECT COUNT(*)FROM m WHERE t IN(i,j))o FROM a WHERE t=@),
c AS(SELECT i,j,ROW_NUMBER()OVER(ORDER BY 1/0)k FROM m WHERE @ NOT IN(i,j)),
d AS(SELECT COUNT(*)u,POWER(3,COUNT(*))-1 v FROM c UNION ALL SELECT u,v-1 FROM d WHERE v>0),
e AS(SELECT v,u,v/3 q,v%3 r FROM d UNION ALL SELECT v,u-1,q/3,q%3 FROM e WHERE u>1),
f AS(SELECT v,p+SUM(IIF(t=i,r,(2-r))%3*3/2)s FROM a,c,e WHERE t IN(i,j)AND k=u GROUP BY v,t,p),
g AS(SELECT MAX(s)x FROM f GROUP BY v)SELECT SUM(IIF(o<ISNULL(x,p),0,1))f FROM a,(b OUTER APPLY g)WHERE t=1;

```

The function returns 0 for a false outcome and more than 0 for a truthy one.

The whole snippet:

```
SET NOCOUNT ON;
--USE tempdb;
USE rextester;
GO
IF SCHEMA_ID('my') IS NULL EXEC('CREATE SCHEMA my');
ELSE BEGIN
  IF OBJECT_ID('my.f', 'IF') IS NOT NULL DROP FUNCTION my.f;
  IF OBJECT_ID('my.s', 'U') IS NOT NULL DROP TABLE my.s;
  IF OBJECT_ID('my.m', 'U') IS NOT NULL DROP TABLE my.m;
  IF OBJECT_ID('my.c', 'U') IS NOT NULL DROP TABLE my.c;
END;
GO
CREATE TABLE my.c( -- Test cases
  c INT PRIMARY KEY CLUSTERED CHECK(c > 0), -- Test Case Id
  n INT CHECK(n > 0), -- Current position of the team of interest
);
CREATE TABLE my.s( -- Standings
  a INT FOREIGN KEY REFERENCES my.c(c) CHECK(a > 0), -- Test cAse Id
  p INT CHECK(p > 0) -- Team pts
);
CREATE TABLE my.m( -- Matches
  s INT FOREIGN KEY REFERENCES my.c(c) CHECK(s > 0), -- Test caSe Id
  i INT CHECK(i > 0), -- Team i
  j INT CHECK(j > 0), -- Team j
  CHECK(i != j)
);
GO
INSERT my.c(c, n) VALUES (1, 2), (2, 1), (3, 3), (4, 2), (5, 2), (6, 1), (7, 2);
INSERT my.s(a, p) VALUES (1, 93), (1, 86), (1, 78), (1, 76), (1, 75),
(2, 50), (3, 10), (3, 10), (3, 10), (4, 15), (4, 10), (4, 8),
(5, 10), (5, 9), (5, 8), (6, 10), (6, 9), (6, 9), (7, 21), (7, 12), (7, 11);
INSERT my.m(s, i, j) VALUES (1, 1, 2), (1, 4, 3), (1, 2, 3), (1, 3, 2), (1, 1, 2),
(4, 2, 3), (4, 1, 3), (4, 1, 3),(4, 3, 1), (4, 2, 1), (6, 2, 3), (6, 3, 2),
(7, 2, 1), (7, 1, 2), (7, 2, 3), (7, 1, 3), (7, 1, 3), (7, 3, 1), (7, 3, 1);
GO
CREATE FUNCTION my.f(@s XML,@m XML,@ INT)RETURNS TABLE RETURN
WITH s AS(SELECT s.value('@p','INT')p FROM @s.nodes('S')s(s)),
m AS(SELECT m.value('@i','INT')i,m.value('@j','INT')j FROM @m.nodes('M')m(m)),
a AS(SELECT ROW_NUMBER()OVER(ORDER BY-p)t,p FROM s),
b AS(SELECT p+3*(SELECT COUNT(*)FROM m WHERE t IN(i,j))o FROM a WHERE t=@),
c AS(SELECT i,j,ROW_NUMBER()OVER(ORDER BY 1/0)k FROM m WHERE @ NOT IN(i,j)),
d AS(SELECT COUNT(*)u,POWER(3,COUNT(*))-1 v FROM c UNION ALL SELECT u,v-1 FROM d WHERE v>0),
e AS(SELECT v,u,v/3 q,v%3 r FROM d UNION ALL SELECT v,u-1,q/3,q%3 FROM e WHERE u>1),
f AS(SELECT v,p+SUM(IIF(t=i,r,(2-r))%3*3/2)s FROM a,c,e WHERE t IN(i,j)AND k=u GROUP BY v,t,p),
g AS(SELECT MAX(s)x FROM f GROUP BY v)SELECT SUM(IIF(o<ISNULL(x,p),0,1))f FROM a,(b OUTER APPLY g)WHERE t=1;
GO
SELECT c, f
FROM my.c
OUTER APPLY(SELECT p FROM my.s S WHERE a = c FOR XML AUTO)S(s)
OUTER APPLY(SELECT i, j FROM my.m M WHERE s = c FOR XML AUTO)M(m)
OUTER APPLY my.f(s, m, n)
ORDER BY c
OPTION(MAXRECURSION 0);

```

Check It Online!

# Answer
> 1 votes
# Python 2, ~~242~~ 221 bytes

```
from itertools import*
def u(S,M,t,O):
 for m,o in zip(M,O):
  if t in m:S[t]+=3
  else:S[m[0]]+=(1,3,0)[o];S[m[1]]+=(1,0,3)[o]
 return S[t]>=max(S)
f=lambda s,m,t:any(u(s[:],m,t,O)for O in product([0,1,2],repeat=len(m)))

```

Try it online!

After a first pass with basic golf-thinking. Takes input with **0-based indexing**; test cases in TIO adjust for this via the function `F`.

The `product([0,1,2],repeat=len(m))` iteration evaluates the possible outcomes over tie/win/loss for each match unless the team-of-interest (TOI) is a part of the match (in which, the TOI is always assumed to win).

# Answer
> 1 votes
# JavaScript (ES6), 145 bytes

```
(s,d,t,o=[],g=(c=s,i=0)=>d[i]?[3,,0,3,1,1].map((a,j)=>(j%=2,r=j?r:[...c],r[d[i][j]]+=a,g(r,i+1))):o.push(c))=>o.some(r=>r[t]==Math.max(...r),g())

```

Takes score input as an array (`[93,86,78,76,75]`), upcoming games as an array of 2-value arrays (`[[0,1],[3,2],[1,2],[2,1],[0,1]]`), and team index as an integer (`1`). Everything is 0-indexed.

## Test Snippet

```
let f=
(s,d,t,o=[],g=(c=s,i=0)=>d[i]?[3,,0,3,1,1].map((a,j)=>(j%=2,r=j?r:[...c],r[d[i][j]]+=a,g(r,i+1))):o.push(c))=>o.some(r=>r[t]==Math.max(...r),g())

console.log("---Truthy---")
console.log(f([93, 86, 78, 76, 75], [[0,1], [3,2], [1,2], [2,1], [0,1]], 1))
console.log(f([50], [], 0))
console.log(f([10, 10, 10], [], 2))
console.log(f([15, 10, 8], [[1,2], [0,2], [0,2], [2,0], [1,0]], 1))
console.log("---Falsy---")
console.log(f([10, 9, 8], [], 1))
console.log(f([10, 9, 9], [[1,2],[2,1]], 0))
console.log(f([21, 12, 11], [[1,0], [0,1], [1,2], [0,2], [0,2], [2,0], [2,0]], 1))
```

```
.as-console-wrapper{max-height:100%!important}
```

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


title: Stealing sequences: Cops

text:
# Question
Title: Stealing sequences: Cops
This is . This is the **Cops** thread. For the robbers thread, go here.

I've noticed a number of OEIS (On-line Encyclopedia of Integer Sequences) challenges since I joined the site. It seems only fair that we have a cops-and-robbers challenge that determines who is the master of online integer sequences, once and for all.

Edit: In order to prevent trivial answers, cops lose 1/2 point for each submission that is cracked. Additionally, for the purposes of this challenge, constant sequences are not allowed. This only applies to solutions posted after this edit.

## Cops

Write a program or function that, given no input, deterministically prints any sequence from the OEIS. By deleting some subset of the characters, your program must be able to print a different OEIS sequence when run in the same language. The new sequence must be entirely new, not just the first by a different name or with a different offset. Neither sequence may be simply a repeated constant value.

You must provide the first function, along with the name of the OEIS sequence so correctness can be verified. It's OK if behavior gets questionable around your language's MAX\_INT value or 256, whichever is larger.

## Robbers

Delete characters from some Cop's submission such that your new program outputs any other sequence from the OEIS. Provide the new function along with the name of the new OEIS sequence. Here is a utility to make sure that your submission is valid (i.e. deletes characters without any funny business. Doesn't check the sequence itself.)

It's in your best interest to delete as many characters from the Cop's submission as possible. If another robber (anyone except the Cop who authored the original program) comes along and finds a shorter solution that finds another *different* sequence, that robber steals your point. (Note that simply golfing off characters and printing the same sequence is not sufficient to steal the point.)

## Rules & Scoring

If, after one week, nobody has been able to crack your solution, you can mark your solution as safe by providing the second program along with the name of the sequence it generates.

You get one point for each safe posting and one point for each submission you crack. Cops lose 1/2 point for each cracked submission. Note that another robber can steal your point from the cracked submission at any time by providing a shorter program that yields a different sequence.

Cops may only post one challenge per language, per person.

The player with the most points at 12:00 UTC on 7 July wins.

# Answer
> 2 votes
# MarioLANG, 23 bytes cracked

```
   >+
 :<":
>+^!<
===#=

```

Try it online!

produces the odd numbers A005408

# Answer
> 1 votes
# C, A000217, 239 bytes Cracked

This isn't so I didn't bother.

```
#include <stdio.h>
#include <limits.h>
int main()
{
    int i, n, temp = 0;
    for(i = 0; i < INT_MAX; i++)
    {
        n = 0;
        temp = i;
        while(temp)
            n+=temp--;
        printf("%d, ", n);
    }
    return 0;
}

```

Sequence: https://oeis.org/A000217

# Answer
> 1 votes
# Python 2, 273 bytes, cracked

## Initial Sequence: A004442

```
import zlib, base64;exec(zlib.decompress(base64.b64decode('eJzLtDUAAAHoANc=')))
while True:print eval(zlib.decompress(base64.b64decode('eJwzAgAAMwAz')))^eval(zlib.decompress(base64.b64decode('eJwzjssEAAHBAPs='))),;exec(zlib.decompress(base64.b64decode('eJzL1LY1BAAC1AED')))

```

Try it online!

# Answer
> 1 votes
# MOO, 86 bytes, safe

```
a=0;b=1;while(a>-1)a=$math_utils:sum(a,a);a=max(1,a);notify(player,tostr(a));endwhile

```

Prints powers of two (A000079).

Solution:

> a=1;while(a\>-1)a=$math\_utils:sum(a,a,a);notify(player,tostr(a));endwhile (which prints powers of 3 (A000244) instead)

# Answer
> 0 votes
# PHP, 20 bytes Cracked

```
for(;;)echo+!$i,",";

```

Try it online!

print sequence https://oeis.org/A000012

# Answer
> 0 votes
# cQuents (older commit), 10 bytes, cracked

```
=0,1,1:z+y

```

This is still a heavily WIP language, but I patched the interpreter up so it worked. Click the language name for the Github link.

This outputs the Fibonnacci sequence: A000045

# Explanation:

(because I have no documentation and I don't expect you to read my interpreter code)

```
=0,1,1      Set start to [0,1,1]
      :     Mode: sequence
       z+y  Each term is the previous two terms added together
            Because there is no input, output the whole sequence

```

If constant sequences were still allowed, this would be super easy to rob.

---
Tags: sequence, cops-and-robbers, rosetta-stone
---


title: Find the Closest Double Palindrome

text:
# Question
Title: Find the Closest Double Palindrome
Given a double-precision float, find the closest double-precision float whose binary representation is a palindrome.

# Input

A floating point number `x`. You may use any format you like for input, but the format you chose must be able to represent every possible IEEE 754 binary64 value, including denormals, distinct representations for `+0` and `-0`, and `+Inf`, `-Inf`, and `NaN`.

# Output

A floating point number `y`. You may use any format you like for output, with the same restrictions as the input format.

# The Task

`y` is any value such that:

* The IEEE 754 binary64 bitstring for `y` is a palindrome. That is, the first 32 bits are the reverse of the last 32 bits.
* `abs(x-y)` is minimal by the `totalOrder` predicate.

# Notes

* `abs(x-y)` must be computed with strict IEEE 754 double-precision floating point arithmetic.
* `totalOrder` puts non-numeric values and signed zeroes in this order: `- NaN < -Inf < -1 < -0 < +0 < +1 < +Inf < +NaN`. Otherwise it behaves like the normal `<` operator.
* The rules for performing arithmetic on non-numeric values can be found at this website
* For an overview of how binary64 floats work, see wikipedia.
* If there is more than one value for `y` that satisfies the conditions, output any one of them. Note that this can only occur if `abs(x-y1) == abs(x-y2)`, or if they are both `NaN`.
* The input and output formats may be different if desired; both formats still need to obey all the rules.
* It may be convenient to use a raw binary format for IO; this is permitted.
* For the purposes of this challenge you may consider all `NaN` values as equivalent, since `NaN` payload behavior is implementation defined.
* It is **not sufficient** to just mirror the first 32 bits. See test cases 2, 4, 5, and 7 for examples.
* Any non-`NaN` double palindrome is valid output for x=`+Inf` or x=`-Inf`, since the distance is still just `+Inf`. Reversing the first 32 bits would not be correct though since the resulting `NaN` value would have a distance of `+NaN > +Inf` from the input.
* A `NaN` though, any double palindrome would be correct.

# Test Cases

```
Input:  0x8A2B_7C82_A27D_6D8F = -1.1173033799881615e-259
Output: 0x8A2B_7C82_413E_D451 = -1.1173031443752871e-259

Input:  0x5000_0000_0000_0001 = 2.3158417847463244e+77
Output: 0x4FFF_FFFF_FFFF_FFF2 = 2.3158417847463203e+77

Input:  0x5000_0000_0000_0002 = 2.315841784746325e+77
Output: 0x5000_0000_0000_000A = 2.315841784746329e+77

Input:  0x7FF0_0000_0000_0000 = +Inf
Output: 0x0000_0000_0000_0000 (others are possible)

Input:  0xFFF0_0000_0000_0000 = -Inf
Output: 0x0000_0000_0000_0000 (others are possible)

Input:  0x7FFC_0498_90A3_38C4 = NaN
Output: 0x0000_0000_0000_0000 (others are possible)

Input:  0x8000_0000_0000_0000 = -0
Output: 0x0000_0000_0000_0000 = +0

Input:  0x0000_0000_0000_0000 = +0
Output: 0x0000_0000_0000_0000 = +0

Input:  0x8A2B_7C82_413E_D451 = -1.1173031443752871e-259
Output: 0x8A2B_7C82_413E_D451 = -1.1173031443752871e-259

Input:  0x000F_FFFF_FFFF_FFFF = 2.225073858507201e-308
Output: 0x000F_FFFF_FFFF_F000 = 2.2250738585051777e-308

Input:  0x0000_B815_7268_FDAF = 1e-309
Output: 0x0000_B815_A81D_0000 = 1.0000044514797e-309

```

---

scoring, Standard Loopholes forbidden.

# Answer
> 2 votes
# C (gcc), 172 bytes

```
#define D double
i;D f(D x){unsigned a[]={0,0};D*A=&a;D c=0;do{for(i=0;i<32;++i){*a=*a&~(1<<i)|!!(a[1]&1<<(31-i))<<i;};c=fabs(x-*A)<fabs(x-c)?*A:c;}while(++a[1]);return c;}

```

(Almost) purely brute-force; takes about 24 minutes per run on my machine.

`f` is a function that takes a double and returns the closest palindromic double. It iterates over every palindromic 64-bit sequence (as a double), storing the closing one, and returns it at the end.

This solution uses gcc on Ubuntu 16.04 32-bit, on a little-endian 32-bit single-core Pentium 4 2.8 GHz CPU.

Explanation/Ungolfed:

```
int i;
double f(double x) {
    unsigned int a[]={0, 0}; // a 2-array of ints is much easier to maipulate bitwise
    double *A = &a; // than a double, so refer to the same memory
    // in two different ways, a as int[2], A as double*
    double current = 0.0;
    do {
        for(i = 0; i < 32; ++i) {
            *a = ( *a&~(1<<i) )|( (!!( (a[1]&1)<<(31-i) ))<<i);
            // reverse the bits of the second half into the first half
            // (*a is shorter than a[0])
        }
        current = fabs(x-*A)<fabs(x-current) ? *A : current;
        // if *A is closer to x than current, replace c with *A
    } while (++a[1]);
    // do-while instead of while to ensure each value is tried
    // at UINT32_MAX, overflows to 0, ending the loop.
    return current;
}

```

A C float (binary32) version that takes ~0.0015% as long to run (about 0.02 seconds on my machine) because it checks 1/65536 as many values: (~~185~~ 179 bytes)

```
#define F float
i;F f(F x){unsigned short a[]={0,0};F*A=&a;F c=0;do{for(i=0;i<16;++i){*a=*a&~(1<<i)|!!(a[1]&1<<(15-i))<<i;};c=fabsf(x-*A)<fabsf(x-c)?*A:c;}while(++a[1]);return c;}

```

---
Tags: code-golf, palindrome, bitwise, floating-point
---


title: Your very own "for" instruction

text:
# Question
Title: Your very own "for" instruction
# Your very own "for" instruction

Assuming you have the following input : `a, b, c, d`

Input can be in one-line using any format "a/b/c/d" or "a,b,c,d" etc..

You can also have 4 inputs.

You must code the following behaviour (pseudo-code here) :

```
var i = <a>
while (i <b> <c>)
    print i
    i = i + <d>
    print "\n"

```

Here are some tests cases :

```
input : 1,<,10,1
output :
1
2
3
4
5
6
7
8
9

```

One more :

```
input : 20,>,10,1
output :
20
21
22
23
24
25
26
27
...
infinite loop / program crashes

```
* `a` is an **integer**, the initial value of `i`.
* `b` is a **string** or a **char**, it can't be something else, the comparator used in the ending condition of the `for` loop.

`b` can and **must** be one of the following strings :

```
- ">"
- "<"

```
* `c` is an **integer**, the number used in the ending condition of the `for` loop.
* `d` is an **integer** that is added to i at every loop.

This is code-golf, the shortest answer wins !

# Answer
## JavaScript (ES6),  ~~44~~  ~~43~~ 56 bytes

*Saved 1 byte thanks to ETHproductions*
*Edit: fixed to comply with output requirements*

```
(a,b,c,d)=>{for(s='';eval(a+b+c);a+=d)s+=a+`
`;alert(s)}

```

### Test

```
let f =

(a,b,c,d)=>{for(s='';eval(a+b+c);a+=d)s+=a+`
`;alert(s)}

f(1,'<',7,2)
```
> 25 votes

# Answer
## Javascript (ES6), ~~47~~ ~~42~~ 48 Bytes

Wanted to make the for version but someone was faster, so here's the recursive version.

```
(b,c,d)=>F=a=>eval(a+b+c)&&console.log(a)|F(a+d)

```

You need to add `f=` before and call it like `f(b,c,d)(a)`.

*Many thanks to Arnauld for the awesome golf.*

*`alert` changed to `console.log` because of output specification*
> 17 votes

# Answer
# Pure bash, 35

I assume its OK just to plug the parameters into the standard for loop:

```
for((i=$1;i$2$3;i+=$4));{ echo $i;}

```

Try it online.
> 15 votes

# Answer
# Jelly, 12 bytes

```
Ṅ+⁶µ⁴;⁵¹vµ¿t

```

Try it online!

Jelly has a lot of ways to tersely do iteration, create ranges, etc.. However, mirroring C++'s behaviour exactly is fairly hard, due to special cases like the increment being 0, the loop ending before it starts (due to the inequality being backwards), and the increment going in the wrong direction (thus meaning the exit condition of the loop can't be met naturally). As such, this solution is basically a direct translation of the C++, even though that makes it rather more low-level than a Jelly program normally is. Luckily, C++ has undefined behaviour on signed integer overflow (the question uses `int`), meaning that a program can do anything in that case, and thus there's no need to try to mimic the overflow behaviour.

## Explanation

```
Ṅ+⁶µ⁴;⁵¹vµ¿t
   µ     µ¿   While loop; while ((⁴;⁵¹v) counter) do (counter = (Ṅ+⁶)counter).
    ⁴;⁵       Second input (b) appended to third input (c), e.g. "<10"
        v     Evaluate, e.g. if the counter is 5, "<10" of the counter is true
       ¹      No-op, resolves a parser ambiguity
Ṅ             Output the counter, plus a newline
 +⁶           Add the fourth input (d)
           t  Crashes the program (because the counter is not a list)

```

Crashing the program is the tersest way to turn off Jelly's implicit output (otherwise, it would output the final value of the counter); it generates a bunch of error messges on stderr, but we normally consider that to be allowed.

Incidentally, the loop counter is initialised with the current value before the loop starts. As the loop appears at the start of the program, that'll be the first input.
> 13 votes

# Answer
# Python 2, 50 bytes

```
a,b,c,d=input()
while eval(`a`+b+`c`):print a;a+=d

```

Try it online!
> 12 votes

# Answer
## R, 63 bytes

```
function(a,b,c,d)while(do.call(b,list(a,c))){cat(a,"\n");a=a+d}

```
> 10 votes

# Answer
# Java, 58 bytes

```
(a,b,c,d)->{for(;b>61?a>c:a<c;a+=d)System.out.println(a);}

```
> 9 votes

# Answer
# SmileBASIC, 53 bytes

```
INPUT A,B$,C,D
S=ASC(B$)-61WHILE S*A>S*C?A
A=A+D
WEND

```

Explanation:

```
INPUT A,B$,C,D
IF B$=="<" THEN S=-1 ELSE S=1 'get comparison direction
I=A
WHILE S*I>S*C 'loop while I is less than/greater than the end
 PRINT I
 INC I,D
WEND

```

This uses the fact that `X<Y` is the same as `-X>-Y`
> 7 votes

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

```
[D²`'>Q"‹›"è.V_#D,³+

```

Try it online!

**Explanation**

```
[                       # start loop
 D                      # copy top of stack (current value of a)
  ²`                    # push b,c to stack
    '>Q                 # compare b to ">" for equality
       "‹›"             # push this string
           è            # index into the string with this result of the equality check
            .V          # execute this command comparing a with c
              _#        # if the condition is false, exit loop (and program)
                D,      # print a copy of the top of the stack (current value of a)
                  ³+    # increment top of stack (a) by d

```
> 7 votes

# Answer
# Stacked, 34 bytes

```
@d@c@b[show d+][:c b tofunc!]while

```

Try it online! (Testing included.) This is a function that expects the stack to look like:

```
a b c d

```

For example:

```
1 '<' 10 2
@d@c@b[show d+][:c b tofunc!]while

```

## Explanation

```
@d@c@b[show d+][:c b tofunc!]while
@d@c@b                               assign variables
               [............]while   while:
                :c                   duplicate "i" and push c
                   b tofunc!         convert b to a function and execute it
      [.......]                      do:
       show                          output "i" without popping
            d+                       and add the step to it

```
> 6 votes

# Answer
## Plain TeX, 88 bytes

```
\newcount\i\def\for#1 #2 #3 #4 {\i#1\loop\the\i\endgraf\advance\i#4\ifnum\i#2#3\repeat}

```

The command `\for` provides the requested function. Save this as `for.tex` and then run it and enter the variable values at the command line: `pdftex '\input for \for 1 < 5 1 \bye'` The variable values must be separated by spaces.
> 6 votes

# Answer
# Python 2, 45 bytes

```
exec"i=%d\nwhile i%c%d:print i;i+=%d"%input()

```

Try it online!

A very literal implementation of the spec. Takes the code template, substitutes in the inputs via string formatting, and executes it.
> 5 votes

# Answer
# C++, 80

Whoops, this is `C++` not `C`. Was a bit confused by the question.

```
void f(int a,char b,int c,int d){for(;b==62?a>c:a<c;a+=d)cout<<a<<endl;}

```
> 4 votes

# Answer
# C, 52 51 bytes

-1 byte thanks to H Walters

```
f(a,b,c,d){for(;b&2?a>c:a<c;a+=d)printf("%d\n",a);}

```

Try it online!
> 4 votes

# Answer
# Python 3, 52 bytes

```
def f(a,b,c,d):
 while[a>c,a<c][b<'>']:print(a);a+=d

```

**repl.it**
> 4 votes

# Answer
## Common Lisp, ~~82~~ ~~80~~ ~~79~~ ~~73~~ 64 bytes

```
(defmacro f(a b c d)`(do((i,a(+ i,d)))((not(,b i,c)))(print i)))

```

## Test

```
(f 1 < 10 1)

1
2
3
4
5
6
7
8
9
NIL
CL-USER>

```

-9 bytes thanks to PrzemysławP.
> 4 votes

# Answer
# Pip, 14 bytes

```
W Va.b.ca:d+Pa

```

Takes four command-line arguments. Supports negative & floating point numbers and comparison operators `< > = <= >= !=`. Try it online!

```
                a,b,c,d are cmdline args
W               While loop with the following condition:
  Va.b.c          Concatenate a,b,c and eval
            Pa  Print a with newline (expression also returns value of a)
        a:d+    Add d to that and assign back to a

```
> 4 votes

# Answer
# Jelly, 8 bytes

```
ḢṄ+⁹;µV¿

```

This is a dyadic link that takes **a,b,c** as its left argument and **d** as its right one. Output may be infinite and goes to STDOUT.

Try it online!

### How it works

```
ḢṄ+⁹;µV¿  Dyadic link.
          Left argument:  a,b,c (integer, character, integer)
          Right argument: d     (integer)

       ¿  While...
      V     the eval atom applied to a,b,c returns 1:
     µ       Combine the links to the left into a chain and apply it to a,b,c.
Ḣ              Head; pop and yield a from a,b,c.
 Ṅ             Print a, followed by a linefeed.
  +⁹           Add a and the right argument (d) of the dyadic link.
    ;          Concatenate the result and the popped argument of the chain,
               yielding a+d,b,c.

```
> 4 votes

# Answer
# Python 3, 61 bytes

One liner:

```
e=input;exec(f'i={e()}\nwhile i{e()}{e()}:print(i);i+={e()}')

```
> 4 votes

# Answer
# Haskell, ~~66~~ 64 bytes

```
f a b c d|last$(a<c):[a>c|b>"<"]=print a>>f(a+d)b c d|1<3=pure()

```

Try it online! Usage:

```
Prelude> f 0 "<" 9 2
0
2
4
6
8

```
> 3 votes

# Answer
# Ruby, ~~43~~ 41 bytes

```
->a,*i,d{a=d+p(a)while eval"%s"*3%[a,*i]}

```

If `b` can be taken in as a *Ruby symbol* instead of a string, you get **38 bytes**:

```
->a,b,c,d{a=d+p(a)while[a,c].reduce b}

```

Try either solution online!
> 3 votes

# Answer
# PHP, ~~69~~ 65 bytes

```
for(list(,$i,$b,$c,$d)=$argv);$b<"="?$i<$c:$i>$c;$i+=$d)echo"$i
";

```

Run with '-r'; provide command line arguments as input.

For ~~just one byte more~~ 4 more bytes, I can take every operator:

```
for(list(,$i,$b,$c,$d)=$argv;eval("return $i$b$c;");$i+=$d)echo"$i
";

```

Yeah, evil eval. Did you know that it can return something?

---

Shorthand destructuring `[,$i,$b,$c,$d]=$argv;` would save 4 more bytes;
but PHP 7.1 postdates the challenge.
> 3 votes

# Answer
# Bash (+Unix Tools), 29 bytes

**Golfed**

```
bc<<<"for(x=$1;x$2$3;x+=$4)x"

```

**Test**

```
./forloop 1 '<' 10 1
1
2
3
4
5
6
7
8
9

```
> 3 votes

# Answer
## Groovy, 51 bytes

```
{a,b,c,d->while(Eval.me("$a$b$c")){println a;a+=d}}

```

This is an unnamed closure. Try it Online!

**Caution** \- If you want to test this with `groovy console`, make sure you kill the entire process when the input causes an infinite loop. I noticed this after it consumed ~5 gigs of RAM.
> 2 votes

# Answer
# Perl 6, 44 bytes

```
{.say for $^a,*+$^d...^*cmp$^c!= $^b.ord-61}

```

### How it works

```
{                                          }  # A lambda.
          $^a                                 # Argument a.
             ,*+$^d                           # Iteratively add d,
                   ...^                       # until (but not including the endpoint)
                       *cmp$^c                # the current value compared to c
                                              # (less=-1, same=0, more=1)
                              != $^b.ord-61.  # isn't the codepoint of the b minus 61.
 .say for                                     # Print each number followed by a newline.

```

If it's okay to return a (potentially infinite) sequence of numbers as a value of type `Seq`, instead of printing the numbers to stdout, the `.say for` part could be removed, bringing it down to 35 bytes.
> 2 votes

# Answer
# Clojure, ~~66~~ 63 bytes

```
#(when((if(= %2"<")< >)% %3)(println %)(recur(+ % %4)%2 %3 %4))

```

-3 bytes by factoring out the `loop`. I'm "abusing" the init parameter to act as the running accumulator.

Recursive solution (with TCO). See comments in pregolfed code. I tried a non-TCO recursive solution, and it ended up being 67 bytes.

I'd love to see this beat in Clojure! I think this is the smallest I can get it.

```
(defn my-for [init-num com-str com-num inc-num]
  (let [op (if (= com-str "<") < >)] ; Figure out which operator to use
    (when (op init-num com-num) ; When the condition is true, print and recur
      (println init-num)
      (recur (+ init-num inc-num) com-str com-num inc-num))))
    ; Else, terminate (implicit)

```
> 2 votes

# Answer
## Clojure, 66 bytes

```
#(loop[i %](if(({">">"<"<}%2)i %3)(do(println i)(recur(+ i %4)))))

```

This could have been 55 bytes as`<` and `>` are functions in Clojure:

```
(def f #(loop[i %](if(%2 i %3)(do(println i)(recur(+ i %4))))))
(f 1 < 10 1)

```
> 2 votes

# Answer
## QBIC, ~~51~~ 40 bytes

```
:;::{?a┘a=a+c~A=@<`|~a>=b|_X]\~a<=b|_X

```

And three minutes after posting I realised I could simplify the terminator logic...

```
:;::      Consecutively read a, A$, b and c from the command line
{?a┘      Start an infinite loop; print a, add a newline to the source
a=a+c     increment a
~A=@<`|   If we are in LESS THAN mode
  ~a>=b   and IF we are no longer LESS
    |_X]  THEN QUIT, end if.
  \       ELSE (we're in GREATER THAN mode)
    ~a<=b IF we are no longer GREATER
    |_X   THEN QUIT
          The last IF and the loop are auto-closed

```
> 2 votes

# Answer
## Batch, 94 bytes

```
@set i=%1
@set o=gtr
@if "%~2"=="<" set o=lss
:g
@if %i% %o% %3 echo %i%&set/ai+=%4&goto g

```

If it wasn't for the second parameter behaviour, it could be done in 53 bytes:

```
@for /l %%i in (%1,%4,%n%)do @if not %%i==%3 echo %%i

```

This simply does nothing if the step has the wrong sign. The extra test is because Batch's `for` loop allows the loop variable to equal the end value.
> 2 votes

# Answer
# TI-Basic, ~~41~~ 34 bytes

```
Prompt A,Str2,Str3,D
While expr("A"+Str2+Str3
Disp A
A+D->A
End

```
> 2 votes

# Answer
# dc, 47 bytes

# dc, 48 bytes

# Also Bash \+ Unix utilities, 29 bytes

**dc (47 bytes):**

```
1sb[_1sb]s zz?sdlb*sc[pld+lnx]sl[dlb*lcr<l]dsnx

```

Try it online!

Note that negative numbers must be entered with an underscore instead of a minus sign, because that's how dc accepts numeric input. So write, for example, \_5 instead of -5.

---

dc can't read character or string input into a variable and process it (there's a more detailed explanation below), but I found two ways of working around this:

The **47-byte dc solution** works on input that has argument1 and argument2 reversed, with spaces as the delimiter. So counting from 1 up to (but not including) 10 in steps of 3 would be entered as:

`< 1 10 3`

If it's not acceptable to change the order of the arguments, I also give a **48-byte dc solution** which keeps the original order of the arguments. This one uses `zz` as the delimiter between arguments. So counting from 1 up to (but not including) 10 in steps of 3 again would use the following input line:

```
1zz<zz10zz3

```

Finally, the same ideas yield a **29-byte bash solution**.

---

**Details on dc's lack of string processing, and how this program deals with that:**

Handling this problem in dc is tricky, because dc doesn't accept string or char input as most languages do. When dc reads an input string, it immediately runs that string as a dc program (a macro), and then discards the string. You can't store the characters of the string in memory and process them later, or in any other way. This interferes with the requirement to have '\<' or '\>' in the input.

I'll show two ways around this. In the solution above (47 bytes), we switch the order of the first two inputs. The input delimiter is the space character. For example, to count from 1 up to (but not including) 10 in steps of 3, you'd input

```
< 1 10 3

```

Here's the idea behind this solution:

Macros in dc are stored in registers, and registers have single-character names. I store a macro in the register whose name is just a space character.

The program works by pushing a 0 and 1 on the stack before getting the input. Then, when the input is run as a dc program (which is what dc does with input lines), the '\<' or '\>' character is executed as a command, which is a conditional macro execution of the macro whose name is the next char after the '\<' or '\>'. Specifically, the top two items on the stack are popped. If the first item popped is \< (respectively, \>) the second item popped, the indicated macro is executed. The next character (after the '\<' or '\>') is a space, so the macro that we've stored in the register whose name is the space char is the one executed if the condition holds. But we had pushed 0 and 1 on the stack, so the first item popped was a 1, and the second item popped was a 0. As a result, the macro is executed only if the conditional test was \>, not \<. This lets us distinguish between '\<' and '\>' in the input.

The remaining items in the line are just numbers, and dc will simply push those numbers, in turn, on the stack.

Here's a detailed description. Most of the time, the counting variable (i in the pseudocode in the problem statement) is stored at the top of the stack.

```
1sb             Store 1 in register b.  (b will end up being 1 for '<', and -1 for '>').
[_1sb]s         Note that there is a space after the second s.  So the space char is the name of a macro which stores -1 in b.
z               Push 0 on the stack.
z               Push 1 on the stack.
?               Accept input in the format above.  This will:
                    - Store 1 or -1 in b, depending on whether you've typed "<" or ">"
                    - Push each of the three numbers in turn on the stack.
sd              Save the increment in register d.
lb*sc           Save either limit or -limit in register c, depending on whether the input started with "<" or ">".
[pld+lnx]sl     Define a macro called l which is the body of our loop:
                    - Prints the top of the stack
                    - Adds the increment to the top of the stack.
                    - Calls macro n (the loop test).

 [dlb*lcr<l]dsn  Define a macro called n which is the test of the loop:
                    It checks to see if i (at the top of the stack) times b is less than c; if so, it calls macro l (looping back).
 x               Execute the loop test macro initially (a while loop needs to have a test at the top before entering the loop the first time).

```

---

On the other hand, the OP stated:

```
Input can be in one-line using any format "a/b/c/d" or "a,b,c,d" etc.

```

So maybe it isn't legitimate to switch the order and require b before a in the input.

Here's an alternative which keeps a, b, c, and d in their original order. We are allowed to use any delimiter; I'll use zz as the delimiter. So counting from 1 up to (but not including) 10 in steps of 3 would be entered as:

```
1zz<zz10zz3

```

The new program, with zz-delimited input, is

**dc (48 bytes):**

```
1sb[_1sb]sz?sdiilb*sci[pld+lnx]sl[dlb*lcr<l]dsnx

```

This is one byte longer than the 47-byte first solution.

Try the zz-delimited version online!

I personally think the different-order `< 1 10 3` formatting is more in the spirit of the problem, but maybe `1zz<zz10zz3` better meets the actual technical specification.

You could probably get a shorter solution if you allowed different delimiters between the different input arguments, but I don't think that's in the spirit of the problem.

# Bash \+ Unix utilities, 29 bytes

You can turn the underlying idea above into a bash program (which calls dc); this avoids all the difficulties with "\<" and "\>", and it also simplifies handling the various numeric parameters, so it's only 29 bytes long, the same as @zeppelin's bash+bc answer.

**bash version (29 bytes):**

```
dc -e[p$4+d$3r$2l]sl$1d$3r$2l

```

Try the bash version online!

Here's a description of how the dc program inside the bash program works:

The value of i is stored at the top of the stack most of the time.

```
[      Start of macro (i is at the top of the stack). This macro will be called l.
p      Print i
$4+    i += (4th argument)
d      Duplicate i at the top of the stack.
$3     Push the 3rd argument onto the stack.
r      Swap the top two items on the stack, so i is at the top and arg3 is second
$2l    $2 is "<" or ">", causing the top two items to be popped from the stack, and macro l is then called (effectively looping back) if i < arg3 or i > arg3, respectively.
]sl    End of macro definition; store macro in register l.

$1     Push argument 1 onto the stack (i = 1st argument).
d$3r$2l Just as above, call macro l if i < arg3, or i > arg3, depending on whether arg2 is "<" or ">"

```
> 2 votes

# Answer
# tcl, 52

```
proc F {a b c d} {while \$a$b$c {puts $a;incr a $d}}

```

demo
> 2 votes

# Answer
# Pari/GP , 48 Bytes

```
f(a,b,c,d)=while(eval(Str(a,b,c)),print(a);a+=d)

```

Testing

```
f(4,"<",7,1)  \\ input
4             \\ output
5
6

```
> 1 votes

# Answer
# C#, 77 bytes

```
(a,b,c,d)=>{for(int i=a;b==">"?i<c:i>c;i+=d){System.Console.Write(i+"\n");}};

```
> 1 votes

# Answer
# F#, ~~71~~ ~~106~~ 97 bytes

~~`fun a b c d->let i=ref a in while(b !i c)do printfn"%i%s"!i d;i:=!i+1;done`~~

I didn't read the question fully!

```
fun a b c d->let i=ref a in while((if b='<'then(<)else(>))!i c)do printfn"%i%s"!i d;i:=!i+1;done

```
> 1 votes

# Answer
# Ruby, 37 bytes

```
->a,b,c,d{(p a;a+=d)while a.send b,c}

```

A pretty straightforward solution. Unlike Value Ink's Ruby solution `b` doesn't have to be a Ruby symbol; just ints and a string/char as per the challenge. And it's still a byte under :)

Try it online
> 1 votes

# Answer
# VBA, 87 Bytes

subroutine that does the thing

```
Sub f(a,b,c,d)
While IIf(b="<",a<c,a>c)
Debug.?a
a=a+d
Wend
End Sub

```
> 1 votes

# Answer
# APL (Dyalog), 19 bytes

```
{⍵⍺⍺⍨⊃⍺:⋄⍺∇2⊃⍺+⎕←⍵}

```

This is an operator taking (c,d) as left argument, b as left operand, and a as right argument.

`{` anonymous "something"

\[if\] the right argument

`⍺⍺⍨` is not *b*er than (also signals that this is an operator)

`⊃⍺` the first of the left arguments

`:` then terminate

else

`⍺∇` reuse the left argument to call the derived function (this operator with its operand) on

`2⊃` the second element of

`⍺+` the left argument added to

`⎕←` the printed

right argument

`}`

Try it online!
> 0 votes

# Answer
# Excel VBA, 47 Bytes

Anonymous VBE immediate window function that takes input as described in prompt from the range `[A1:D1]` on the `ActiveSheet` object and implicitly outputs back onto that object by modifying the value of the visible `[A1].Value` variable

```
While[If(B1="<",A1<C1,A1>C1)]:[A1]=[A1+D1]:Wend

```
> 0 votes

---
Tags: code-golf
---


# Question
Title: Operator precedence: How wrong can I be?
Say I have an expression:

```
9 * 8 + 1 - 4

```

This expression can be interpreted in six different ways, depending on operator precedence:

```
(((9 * 8) + 1) - 4) = 69 (* + -)
((9 * 8) + (1 - 4)) = 69 (* - +)
((9 * (8 + 1)) - 4) = 77 (+ * -)
(9 * ((8 + 1) - 4)) = 45 (+ - *)
((9 * 8) + (1 - 4)) = 69 (- * +)
(9 * (8 + (1 - 4))) = 45 (- + *)

```

Say I'm a developer, and I don't feel like memorizing precedence tables, etc., so I'm just going to guess.

In this case, the largest margin of error would be 45-77, which is a difference of 32. This means that my guess will only be off by a maximum of 32.

## The challenge

Given an expression consisting of numbers and `+`, `-`, `*`, `/` (integer division) and `%`, output the absolute difference of the largest and smallest possible value for that expression, based on the precedence of operators.

## Specifications

* The input expression will not contain parenthesis and every operator is left-associative.
* The input expression will only contain nonnegative integers. However, subexpressions may evaluate to negatives (e.g. `1 - 4`).
* You can take the expression in any reasonable format. For example:
    + `"9 * 8 + 1 - 4"`
    + `"9*8+1-4"`
    + `[9, "*", 8, "+", 1, "-", 4]`
    + `[9, 8, 1, 4], ["*", "+", "-"]`
* The input will contain at least 1 and at most 10 operators.
* Any expression that contains a division or modulo by 0 should be ignored.
* You can assume that modulo will not be given negative operands.

## Test Cases

```
9 * 8 + 1 - 4             32
1 + 3 * 4                  3
1 + 1                      0
8 - 6 + 1 * 0              8
60 / 8 % 8 * 6 % 4 * 5    63

```

# Answer
> 28 votes
# Python 2, ~~171~~ 156 bytes

```
lambda a:max(e(a))-min(e(a))
u=')%s('
def e(a,t=u):
 try:b=[eval(a)]
 except:b=[]
 return sum([e('(%s)'%a.replace(o,t%o),u%t)for o in"+-*/%"if' '+o in a],b)

```

Try it online!

### How it works

We surround each operator with a different number of outward-facing pairs of parentheses to simulate different precedences (in all possible ways), and wrap enough inward-facing pairs of parentheses around the entire string, to get an expression we can `eval`. For example, with

`+``)+(`
`*``))*((`
`-``)))-(((`

we get

`9 * 8 + 1 - 4``(((9 ))*(( 8 )+( 1 )))-((( 4)))` = `77`.

# Answer
> 7 votes
# Jelly, 126 bytes

"Operator Precedence? Parentheses? Pah, who needs that?" - challenges of using Jelly for an operator precedence challenge.

```
⁾[]i$€Ḥæ%3+\¬œp¹Ḋ€
ÇµḟØDO%9µÐṀṪɓœṣ⁹,ṚÑj@¥/
ÇµVṾµ1ĿFḟØDḟ”-Lµ?ÐL
5Ḷx@€“]“[”ż⁸j/€,@y³Fɓ³i@€Ṁ’x@“[“]”jÇ
“+_×:%”Œ!Ç€µṾL_L’ỊµÐfV€ṢIS

```

Try it online!

Input is taken as a string, e.g. "1+2\_3×4:5%6". Note multiplication uses "×" instead of "\*", division uses ":" instead of "/", and subtraction uses "\_" instead of "-".

**How it Works** The program is divided into three parts: generating all expressions of different operator precedence, evaluating them, and returning the difference between the maximum and minimum.

All expressions are generated with the code:

```
5Ḷx@€“]“[”ż⁸j/€,@y³Fɓ³i@€Ṁ’x@“[“]”jÇ (4) helper link: returns all outputs given a permutation. Input e.g. "_+:×%"
5Ḷx@€“]“[”           - repeat outer brackets to get ["",""],["]","["],["]]","[["],["]]]","[[["],["]]]]","[[[["]
          ż⁸j/€      - insert the operations in to get "_","]+[","]]:[[","]]]×[[[","]]]]%[[[["
               ,@    - turn this into a mapping equivalent to "_"↦"_","+"↦"]+[",":"↦"]]:[[","×"↦"]]]×[[[","%"↦"]]]]%[[[["
                 y³F - use this mapping to get the right number of outward brackets on each operation. e.g. "1]+[3]]]×[[[4"
ɓ³i@€Ṁ’x@“[“]”j      - add the right number of brackets to the end to get e.g."[[[1]+[3]]]×[[[4]]]"
               Ç     - this calls the link which evaluates the expression
“+_×:%”Œ!Ç€                          (5a) main link. Input e.g. "1+3×4"
“+_×:%”                                 - the string "+_×:%"
       Œ!                               - all permutations
         Ç€                             - apply link (4) to each permutation

```

The links are evaluated with this (I could probably improve with a different structure):

```
⁾[]i$€Ḥæ%3+\¬œp¹Ḋ€      (1) Helper link: Outputs a list of expressions within brackets, e.g. "[[[1]+[3]]]×[[[4]]]"↦"[[1]+[3]]","[[4]]"
⁾[]i$€Ḥæ%3                 - map "[" to 2, "]" to -2, and any other character to 0.
          +\¬              - cumulative sum negated: 1s at characters not in brackets (includes opening brackets), 0s otherwise (includes closing brackets)
             œp¹           - partition the input, not including borders, based on the sum to get "[[[1]+[3]]","[[[4]]"
                Ḋ€         - remove opening brackets
ÇµḟØDO%9µÐṀṪɓœṣ⁹,ṚÑj@¥/ (2) Return the input to this link with one of the expressions from (1) evaluated
ÇµVṾµ1ĿFḟØDḟ”-Lµ?ÐL     (3) link called from part 1: Evaluates expressions
 µ  µ          µ?          - if:
     1ĿFḟØDḟ”-L            - the input contains no operators within brackets:
  VṾ                         - evaluate this one expression with normal Jelly calculation and return to string
                           - otherwise:
Ç                            - evaluate one subexpression using link (2)
                  ÐL       - repeat this until a single output is determined

```

The difference between the maximum and minimum is computed with the code in link (5):

```
µṾL_L’ỊµÐfV€ṢIS (5b) determine difference between minimum and maximum
µ      µÐf        - filter out outputs involving division or modulo by 0. Determined with:
 ṾL_L’Ị           - actual numbers have their unevaled form Ṿ no more than one byte longer than the non-unevaled form.
          V€      - evaluate each of these valid numbers to get integers from strings
            Ṣ     - sort
             IS   - return the sum of all difference between consecutive elements.

```

# Answer
> 6 votes
# Python 2, 235 234 233 226 bytes

-1 byte (and a fix) thanks to Anders Kaseorg!

-7 bytes thanks to Step Hen!

```
from itertools import*
def f(e,a=()):
 for o in permutations("+-*/%"):
	l=e[:]
	for c in o:
	 for i in range(len(l),0,-1):
		if l[i-1]==c:l[i-2:i+1]=["("+l[i-2]+l[i-1]+l[i]+")"]
	try:a+=eval(*l),
	except:0
 print max(a)-min(a)

```

Try it online!

# Answer
> 4 votes
# Haskell 582 bytes

This didn't go nearly as well as I hoped it would...

```
import Data.List
f x=case x of '+'->(+);'-'->(-);'*'->(*);'/'->div;_->rem
e _ s[]=s
e 1 s(')':x:a)|0<-(read$e 0""a),(x=='%'||x=='/')=""|""<-(e 0""s)=""|""<-(e 0""a)=""|0<3=show$(f x)(read$e 0""s)$read$e 0""a
e 1 s")"=e 0""s
e n s(')':a)=e(n-1)(s++")")a
e 0 s('(':a)=e 1 s a
e n s('(':a)=e(n+1)(s++"(")a
e n s(x:a)=e n(s++[x])a
n?s=take n$cycle s
a!b=e 0""(9?"("++(concat$zipWith(++)a(b++[[]]))++9?")")
c#b|l<-[read x|x<-map(c!)(a b),x/=""]=maximum l-minimum l
a c=transpose$map(\x->map((\(Just q)->q).lookup x)$map(\a->zipWith(\x y->(y,x?")"++y:x?"("))[1..5]a)$permutations"+-*%/")c

```

Try It Online!

Trying to golf a long program just makes me write bad code :(

I tried to use Anders' algorithm in Haskell, but it got out of my control

The function e is like a specific case of eval. (#) takes a list of strings representing integers and a string of operators and returns the difference between the maximum and minimum possible values. e.g

```
(#) ["9","8","1","4"] "*+-" => 32

```

# Answer
> 4 votes
# Haskell, 254 bytes

```
import Data.List.Split
import Data.List
f s=(-)<$>maximum<*>minimum$permutations(zip"+-*/%"[p(+),p(-),p(*),c$div,c$mod])>>=(s!)
p=((pure.).)
c o a b=[o a b|b/=0]
s![]=[read s]
s!((x,o):y)=case splitOn[x]s>>=(!y)of[]->[];l->l?o
[a]?_=[a]
(a:b)?o=b?o>>=o a

```

Try it online!

Input is a whole string, such as 4+5 * 2. It generates all permutations of operations, and for each permutation splits the string recursively. It filters divisions by 0 with the list monad.

# Answer
> 3 votes
# Pyth, 45 bytes

```
KS.nm.x.vj\ u.nm+*H/kHckHGd]s.iFQY.p_{eQ-eKhK

```

I'm sure that a lot more optimization can be done, but I like it so far.

Takes input like this: `[9, 8, 1, 4], ["*", "+", "-"]`.

Try it online!

# Answer
> 2 votes
# Javascript, 280 bytes

**Note**: The integer division rounds using the floor function, which means that negative numbers round away from zero.

This solution is based on this answer.

```
b=>(Math.max(...(f=(a,h="(",i=")",r=[...a[d="replace"](/[^-+*/%]|(.)(?=.*\1)/g,"")])=>(r[0]?(r.map((c,j)=>s=s.concat(f(h+a[d](RegExp("\\"+(n=r.concat()).splice(j,1),"g"),i+c+h)+i,h+"(",i+")",n)),s=[]),s):(a=eval(`(${a})`[d](/\(/g,"Math.floor(")))==a&&1/a?a:r))(b))-Math.min(...f(b)))

```

Example code snippet:

```
g=

b=>(Math.max(...(f=(a,h="(",i=")",r=[...a[d="replace"](/[^-+*/%]|(.)(?=.*\1)/g,"")])=>(r[0]?(r.map((c,j)=>s=s.concat(f(h+a[d](RegExp("\\"+(n=r.concat()).splice(j,1),"g"),i+c+h)+i,h+"(",i+")",n)),s=[]),s):(a=eval(`(${a})`[d](/\(/g,"Math.floor(")))==a&&1/a?a:r))(b))-Math.min(...f(b)))

for(k=0;k<5;k++)
  v=["9*8+1-4","1+3*4","1+1","8-6+1*0","60/8%8*6%4*5"][k],
  console.log(`g(${v}) = ${g(v)}`)
```

# Answer
> 2 votes
# Mathematica, ~~186~~ ~~164~~ 159 bytes

```
eMax@#-Min@#&[Fold[#//.{m___,x_,#2[[0]],y_,n___}:>{m,x~Last@#2~y,n}&,e,#]&/@Permutations@{"+"@Plus,"-"[#-#2&],"*"@Times,"/"@Quotient,"%"@Mod}/. 0/0|1/0->{}]

```

`\[Function]` takes 3 bytes.

Some alternatives (keeps bytecount the same)

`#2-#&@MinMax[...]` to replace `Max@#-Min@#&[...]`

`Head@#2` to replace `#2[[0]]`

Try it online at http://sandbox.open.wolframcloud.com : enter `( .... )[{60, "/", 8, "%", 8, "*", 6, "%", 4, "*", 5}]` with `....` replaced by code above for test case `60 / 8 % 8 * 6 % 4 * 5`. Press `Shift + enter` to evaluate.

# Answer
> 1 votes
# Python 2, ~~262~~ ~~256~~ 254 bytes

```
from itertools import*
def r(s,o):
 try:
  while o in s:i=s.index(o)-1;s[i:i+3]=[`eval(''.join(s[i:i+3]))`]
  return s
 except:0
def f(s):
 u=[int(v[0])for v in [reduce(r,O,s.split(' '))for O in permutations('*/%+-')]if v!=None];return abs(max(u)-min(u))

```

Try it online!

# Answer
> 1 votes
# PHP, 316 bytes

```
<?for(;$t++<54322;)count_chars($t,3)!=12345?:$p[]=$t;foreach($p as$x){for(list($z,$q)=$_GET,$b=1,$i=0;$y=strtr($x,12345,"/%*+-")[$i++];)while(-1<$k=array_flip($q)[$y]){$n=$k+1;if($b&=$z[$n]||ord($y)%10<6)eval("\$z[$k]=$z[$k]$y$z[$n]^0;");($s=array_splice)($z,$n,1);$s($q,$k,1);}$b?$r[]=$z[0]:0;}echo max($r)-min($r);

```

Try it online!

```
Expanded
for(;$t++<54322;)
  count_chars($t,3)!=12345?:$p[]=$t;
foreach($p as$x){
  for(list($z,$q)=$_GET,$b=1,$i=0;$y=strtr($x,12345,"/%*+-")[$i++];)
    while(-1<$k=array_flip($q)[$y]){
      $n=$k+1;
      if($b&=$z[$n]||ord($y)%10<6)
        eval("\$z[$k]=$z[$k]$y$z[$n]^0;");
      ($s=array_splice)($z,$n,1);
      $s($q,$k,1);
    }
  $b?$r[]=$z[0]:0;
}
echo max($r)-min($r);

```

# Answer
> 1 votes
# JavaScript (ES6), 210 bytes

Input as an array of numbers and operators

```
k=>(m=n=-k,r=(o,k,j=0)=>{for(o||(m=m>k?m:k,n=n<k?n:k);q=o[j++];(q>'%'&q<'/'||z)&&r(o.slice(0,j-1)+o.slice(j),h))for(h=[...k],z=1;i=h.indexOf(q)+1;h.splice(i-2,3,eval(a=h[i-2]+q+h[i])|0))z*=h[i]})('+-*/%',k)|m-n

```

*Less golfed*

```
k=>(
  m = n = NaN,
  r =(o, k, j=0) => {
    // try all operators in o
    for(;q = o[j]; j++)
    {
      // q : current operator,
      // look for q inside the expression to evaluate
      for(h = [...k], z = 1; i = h.indexOf(q) + 1;)
      {
        a = h[i - 2]
        b = h[i]
        z *= b // trace if any second operand is zero
        // subst subexpression with its value
        h.splice(i - 2, 3, eval(a + q + b) | 0)
      }
      // now all subexp involving current operator are evaluated
      // the result is ok if current operator is not % or /
      //  OR if no second operand was zero
      (q > '%' & q < '/' || z) &&
        // try again recursively
        // using the remaining operators and the remaining expression
        r(o.slice(0, j) + o.slice(j+1), h)
    }
    // if no more operators to try, check max and min
    // k is an array with 1 element, can be used like a single number
    o || (
      m = m > k ? m : k,
      n = n < k ? n : k
    )
  },
  r('+-*/%', k),
  m-n
)

```

**Test**

```
var F=
k=>(m=n=-k,r=(o,k,j=0)=>{for(o||(m=m>k?m:k,n=n<k?n:k);q=o[j++];(q>'%'&q<'/'||z)&&r(o.slice(0,j-1)+o.slice(j),h))for(h=[...k],z=1;i=h.indexOf(q)+1;h.splice(i-2,3,eval(a=h[i-2]+q+h[i])|0))z*=h[i]})('+-*/%',k)|m-n

function update() {
  var input = I.value.match(/\d+|\S/g)
  var result = F(input)
  O.textContent = I.value + ' -> ' + result + ' (max:'+m+' min:'+n+')'
}

update()
```

```
<input id=I value="60 / 8 % 8 * 6 % 4 * 5" oninput='update()'>
<pre id=O></pre>
```

# Answer
> 0 votes
# Python 3, 284 bytes

Edit: seems like something's wrong with evaluating the last example. I'll look into it tomorrow.

Another Python answer. Couldn't outgolf everyone else, but I spent too long on this to not put it up.

```
from itertools import*
def f(n,o):
 z=[]
 for p in permutations("+-*/%"):
  try:
   p,x,a=[*p],n[:],o[:]
   while(p):
    for i,d in enumerate(a):
     if d==p[0]:x[i+1]=str(eval(x[i]+d+x[i+1]));x.pop(i);a.pop(i)
    p.pop(0)
   z+=x
  except:0
 z=[*map(float,z)];return max(z)-min(z)

```

Try it online!

# Answer
> 0 votes
# Clojure (+ combinatorics), ~~342~~ 377 + 41 = 418 bytes

*+35 bytes because of a bug.*

```
(fn[x y](let[l filter s first z #(l(fn[y]y)%)r(sort(z(for[e(q/permutations[+ - * quot mod])](try(loop[t e m y a x](if(=[]t)(s a)(let[j(s t)i(reverse(keep-indexed #(if(= j %2)%)m))](recur(rest t)(l #(not= j %)m)(loop[d 0 h a](if(=(count i)d)h(let[c(nth i d)f(inc c)](recur(inc d)(vec(z(assoc h c(j(nth h c)(nth h f))f nil)))))))))))(catch Exception _ nil)))))](-(last r)(s r))))

```

Try it online!

For this function to work, you have to `use` the `clojure.math.combinatorics` library (41 bytes):

```
(use '[clojure.math.combinatorics :as q])

```

## Nuances:

This function is an anonymous function, which means you must do this to use it:

```
((fn[x y]...) numbers operators)

```

Also, I'm using the word `quot` instead of `/` (since Clojure does fraction division by default), and `mod` instead of `%`.

## Ungolfed program:

```
(defn precedence [numbers operators]
  (let [results
        (sort
          (for [permute (c/permutations [+ - * / mod])]
            (loop [p-temp permute
                  o-temp operators
                  n-temp numbers]
              (if (empty? o-temp) (first n-temp)
                (let [first-p (first p-temp)
                      indices (reverse (keep-indexed #(when (= first-p %2) %) o-temp))]
                  (recur
                    (rest p-temp)
                    (filter #(not= first-p %) o-temp)
                    (loop [ind 0
                          n-through n-temp]
                      (if (= ind (count indices)) n-through
                        (let [current-ind (nth indices ind)]
                          (recur
                            (inc ind)
                            (vec
                              (filter #(not (nil? %))
                                (assoc n-through
                                  current-ind (first-p (nth n-through current-ind) (nth n-through (inc current-ind)))
                                  (inc current-ind) nil)))))))))))))]
    (- (last results) (first results))))

```

---
Tags: code-golf, number, arithmetic, expression-building
---


title: Finite Element Grid I

text:
# Question
Title: Finite Element Grid I
## Introduction

*Don't worry - no knowledge in mathematics is needed. It is possible to just skip the motivation part, but I think it is nice if a puzzle has a background story. Since the title contains the number* I *there will be more puzzles of this kind, if you like them. Feedback is highly appreciated. I hope you have fun with this puzzle! :)*

Sandbox-Answer

---

## Motivation

Many processes in the real life can be modelled with differential equations. A differential equation is an equation contain some differential expression, e.g.

```
x'(t) = λx(t)

```

This is a ordinary (= 1D) differential equation (ODE). And the solution to this is simply `x(t) = x₀e^{λt}` for any `x₀∈ℝ`. This ODE can be used as model for population growth (rabbits multiplying exponentially) or radiation decay. In both cases `x̧₀` is the initial population / initial amount of material.

Now not everything in the world of physics can be modelled with ODEs. Since we live in a multidimensional world there should be differential equations with more than just one component, right?
These equations are named partial differential equations (PDE).

For example flow fields can (in some cases) be modelled using the Stokes Equation:

```
-Δv + ∇p = f in Ω
     ∇∘v = 0 in Ω

```

where `v` is the velocity and `p` is the pressure of the flow. And `Ω⊂ℝ²` is just the geometry on which the equation is solved - e.g. a tube.

Now if you want to solve these equations there is a method called Finite Element Method. And this method requires a grid of your geometry. In most cases these grids contain quadrilaterals or triangles.

For this `code-golf` we will use a very simple grid:

```
(0,1)                     (1,1)
  x-----x-----x-----x-----x
  |     |     |     |     |
  |  1  |  2  |  3  |  4  |
  |     |     |     |     |
  x-----x-----x-----x-----x
  |     |     |     |     |
  |  5  |  6  |  7  |  8  |
  |     |     |     |     |
  x-----x-----x-----x-----x
  |     |     |     |     |
  |  9  | 10  | 11  | 12  |
  |     |     |     |     |
  x-----x-----x-----x-----x
  |     |     |     |     |
  | 13  | 14  | 15  | 16  |
  |     |     |     |     |
  x-----x-----x-----x-----x
(0,0)                     (1,0)

```

This 2D-grid consists of 5x5 points in (2D) unit cube \[0,1\]×\[0,1\]⊂ℝ². Therefore we have 16 cells. The four Cartesian coordinates and the numbers in the cells are **not** part of the grid. They are just to explain the Input/Output.

There is a connection between the grid-size and the accuracy of the solution - the finer the grid the higher the accuracy. (Actually that is not always true.) But a finer grid also has a draw-back: The finer the grid the higher the computation cost (RAM and CPU). So you only want to refine your grid at some locations. This idea is called `adaptive refinement` and is usually based on the behaviour of the solution - e.g. thinking about the flow problem above: refine that part of the grid, where the solution is turbulent, don't refine if the solution is boring.

## Task

The task is to implement this `adaptive refinement` in a general way. Since we don't solve any PDE in this `code-golf` the criteria to refine grid cells is based on a circle disk. This circle disk is simply defined by the midpoint `p=[p0,p1]∈[0,1]²` and the radius `r ∈ [0,1]`.

Every cell intersecting with that disk (including boundaries - see Example 1) will be refined.

The output is the 5x5 grid above with the refined cells.

## Asked Questions

*What is the purpose of 'x'?*

'x' represents nodes/vertices, '-' and '|' edges.

Refinement of a cell means, that you split one cell into 4:

```
  x-----x       x--x--x
  |     |       |  |  |
  |     |   >   x--x--x
  |     |       |  |  |
  x-----x       x--x--x

```

## Examples

```
Input: p=[0,0] r=0.5
Output:
  x-----x-----x-----x-----x
  |     |     |     |     |
  |     |     |     |     |
  |     |     |     |     |
  x--x--x-----x-----x-----x
  |  |  |     |     |     |
  x--x--x     |     |     |
  |  |  |     |     |     |
  x--x--x--x--x-----x-----x
  |  |  |  |  |     |     |
  x--x--x--x--x     |     |
  |  |  |  |  |     |     |
  x--x--x--x--x--x--x-----x
  |  |  |  |  |  |  |     |
  x--x--x--x--x--x--x     |
  |  |  |  |  |  |  |     |
  x--x--x--x--x--x--x-----x

The midpoint is located in (0,0) with radius 0.5.

Cell 13: Completely inside the cell.
Cell 9 : Intersects, since lower left corner has coords (0,0.25).
Cell 14: Intersects, since lower left corner has coords (0.25,0).
Cell 5 : Intersects, since lower left corner has the coordinates (0, 0.5).
Cell 15: Intersects, since lower left corner has the coordinates (0.5, 0).
Cell 10: Intersects, since lower left corner has the coordinates (0.25, 0.25).
The distance from (0,0) to that corner is √(0.25²+0.25²) < 0.36 < 0.5.

Cell 11:  Does not intersect, since the closest point is the lower left
corner with coordinate (0.5,0.25), so the distance is
√(0.5² + 0.25²) > √(0.5²) = 0.5

Input: p=[0.5,0.5] r=0.1
Output:
  x-----x-----x-----x-----x
  |     |     |     |     |
  |     |     |     |     |
  |     |     |     |     |
  x-----x--x--x--x--x-----x
  |     |  |  |  |  |     |
  |     x--x--|--x--x     |
  |     |  |  |  |  |     |
  x-----x--x--x--x--x-----x
  |     |  |  |  |  |     |
  |     x--x--x--x--x     |
  |     |  |  |  |  |     |
  x-----x--x--x--x--x-----x
  |     |     |     |     |
  |     |     |     |     |
  |     |     |     |     |
  x-----x-----x-----x-----x

The midpoint is located in (0.5,0.5) with radius 0.1.
Therefore the circle is completely inside the union of cells 6,7,10 and 11.
It does not touch any 'outer' boundaries of these four cells.
So the only refined cells are these four.

Input: p=[0.35,0.9] r=0.05
Output:
  x-----x--x--x-----x-----x
  |     |  |  |     |     |
  |     x--x--x     |     |
  |     |  |  |     |     |
  x-----x--x--x-----x-----x
  |     |     |     |     |
  |     |     |     |     |
  |     |     |     |     |
  x-----x-----x-----x-----x
  |     |     |     |     |
  |     |     |     |     |
  |     |     |     |     |
  x-----x-----x-----x-----x
  |     |     |     |     |
  |     |     |     |     |
  |     |     |     |     |
  x-----x-----x-----x-----x

Cell 2: Intersecting with the circle.
Cell 1: Not refined, since the right edge has x-coordinate 0.25 < 0.35-0.05 = 0.3.
Cell 3: Not refined, since the left edge has x-coordinate 0.5 > 0.35+0.05 = 0.4.
Cell 6: Not refined, since the top edge has y-coordinate 0.75 < 0.9 - 0.05 = 0.85.

```

## Rules

**Since this is my first puzzle / golf help is appreciated.**

* : Smallest byte size wins.
* Trailing / Leading whitespaces are allowed.
* The Cartesian coordinates are not part of the grid, and should not be seen in the output.
* Only allowed chars are '-', '|', 'x' and ' '
* Input: All three numbers will be floats. It does not matter if your input is a tuple `(p0,p1)` and a number `r`, or three numbers, or one array - just be reasonable.

# Answer
# Charcoal, ~~107~~ ~~105~~ 106 bytes

```
Ｆ²«x⁵↷²x³↷»Ｆ³«Ｃ⁰±⁴Ｃ⁶¦⁰»Ｆ⁴«Ａ⁻×⁴ＩθιεＦ⁴«Ａ⁻×⁴Ｉηκδ¿¬›⁺Ｘ⎇›ε¹⁻ε¹∧‹ε⁰ε²Ｘ⎇›δ¹⁻δ¹∧‹δ⁰δ²Ｘ×⁴Ｉζ²«Ｊ⁺³×⁶ι⁻²×⁴κＰ|x|xＰ-x--x

```

Try it online! Link is to verbose version of code, not that it helps. Edit: Saved 2 bytes by handling the reversed sense of the Y-axis in a different way, but added a byte to handle a clarification in the question. Explanation:

```
Ｆ²«x⁵↷²x³↷»

```

Prints a cell. It does this by printing an `x`, then printing `5` (which expands to `-----` because the default cursor direction is right), then it rotates downwards, prints another `x`, prints `3` (which now expands to three `|`s downwards), then rotates left. Doing all that twice completes the cell.

```
Ｆ³«Ｃ⁰±⁴Ｃ⁶¦⁰»

```

There are four cells horizontally and vertically, so the cell needs to be copied horizontally and vertically three times. The vertical copy is done upwards to simplify the calculation below.

```
Ｆ⁴«Ａ⁻×⁴ＩθιεＦ⁴«Ａ⁻×⁴Ｉηκδ

```

The 16 cells are now looped over using a four by four nested loop. The coordinates of the midpoint are multiplied by 4, scaling them from 0 to 4, which corresponds to our loop indices which are subtracted, so the resulting variables are now relative to the cell's bottom left corner.

```
¿¬›⁺Ｘ⎇›ε¹⁻ε¹∧‹ε⁰ε²Ｘ⎇›δ¹⁻δ¹∧‹δ⁰δ²Ｘ×⁴Ｉζ²«

```

The variables are now compared to the range 0 to 1 that represents the relative quadrupled cell coordinates. If they lie outside this range it means that the midpoint lies outside the cell, so the distance to the range is squared and the sum of the squares compared to the square of the quadrupled radius. If it is not greater, then the cell needs to be refined.

```
Ｊ⁺³×⁶ι⁻²×⁴κＰ|x|xＰ-x--x

```

The cursor is moved to the centre of the cell to be refined. The string `x|x` is printed vertically (both up and down), while the string `x--x` is printed horizontally (both left and right). (The middle `x`s overlap.)
> 3 votes

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