title: Optimal Alphabet Stepping

text:
# Question
Title: Optimal Alphabet Stepping
Given an input string consisting of only letters, return the step-size that results in the minimum amount of steps that are needed to visit all the letters in order over a wrapping alphabet, starting at any letter.

For example, take the word, `dog`. If we use a step-size of 1, we end up with:

```
defghijklmnopqrstuvwxyzabcdefg   Alphabet
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
defghijklmnopqrstuvwxyzabcdefg   Visited letters
d          o                 g   Needed letters

```

For a total of 30 steps.

However, if we use a step-size of 11, we get:

```
defghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefg
^          ^          ^          ^          ^          ^
d          o          z          k          v          g   Visited letters
d          o                                           g   Needed letters

```

For a total of 6 steps. This is the minimum amount of steps, so the return result for `dog` is the step-size; `11`.

Test cases:

```
"dog"      -> 11
"age"      -> 6
"apple"    -> 19
"alphabet" -> 9
"aaaaaaa"  -> 0 for 0 indexed, 26 for 1 indexed
"abcdefga" -> 1 or 9
"aba"      -> Any odd number except for 13
"ppcg"     -> 15
"codegolf" -> 15
"testcase" -> 9
"z"        -> Any number
"joking"   -> 19

```

### Rules

* Input will be a non-empty string or array of characters consisting only of the letters `a` to `z` (you can choose between uppercase or lowercase)
* Output can be 0 indexed (i.e. the range `0-25`) or 1 indexed (`1-26`)
* If there's a tie, you can output any step-size or all of them
* This is , so the lowest amount of bytes for each language wins!

# Answer
# Charcoal, 41 bytes

```
≔ＥＥβＥθ∧μ⌕⭆β§β⁺⌕β§θ⊖μ×κξλ⎇⊕⌊ιΣι⌊ιθＩ⌕θ⌊Φθ⊕ι

```

Try it online! Link is to verbose version of code. 0-indexed. Explanation:

```
Ｅβ

```

Loop over the 26 step sizes. (Actually I loop over the lowercase alphabet here and use the index variable.)

```
Ｅθ∧μ

```

Loop over each character of the input after the first.

```
⭆β§β⁺⌕β§θ⊖μ×κξ

```

Loop 26 times and generate the string of characters resulting by taking 26 steps at the given step size starting (0-indexed) with the previous character of the input.

```
⌕...λ

```

Find the position of the current character of the input in that string, or -1 if not found.

```
Ｅ...⎇⊕⌊ιΣι⌊ι

```

Take the sum of all the positions, unless one was not found, in which case use -1.

```
≔...θ

```

Save the sums.

```
⌊Φθ⊕ι

```

Find the minimum non-negative sum.

```
Ｉ⌕θ...

```

Find the first step size with that sum and output it.
> 6 votes

# Answer
# JavaScript, 143 bytes

```
w=>(a=[...Array(26).keys(m=1/0)]).map(s=>~[...w].map(c=>(t+=a.find(v=>!p|(u(c,36)+~v*s-u(p,36))%26==0),p=c),p=t=0,u=parseInt)+t<m&&(m=t,n=s))|n

```

Try it online!

Thanks to Shaggy, using `[...Array(26).keys()]` saves 9 bytes.
> 5 votes

# Answer
# Ruby, ~~121~~ ~~114~~ ~~112~~ ~~108~~ ~~102~~ 89 bytes

```
->s{(r=0..25).min_by{|l|p,=s;s.sum{|c|t=r.find{|i|(p.ord-c.ord+i*l)%26<1}||1/0.0;p=c;t}}}

```

Try it online!

0-indexed. Takes input as an array of characters.

Thanks to ASCII-only for golfing ideas worth 12 bytes.
> 4 votes

# Answer
# JavaScript (Node.js),  ~~123 121 116~~  114 bytes

```
s=>(i=26,F=m=>i--?F((g=x=>s[p]?s[k++>>5]?j=1+g(x+i,p+=b[p]==x%26+97):m:0)(b[p=k=0]+7)>m?m:(r=i,j)):r)(b=Buffer(s))

```

Try it online!

### Commented

**NB**: When trying to match a letter in the alphabet with a given step \\$i\\$, we need to advance the pointer at most \\$25\\$ times. After \\$26\\$ unsuccessful iterations, at least one letter must have been visited twice. So, the sequence is going to repeat forever and the letter we're looking for is not part of it. This is why we do `s[k++ >> 5]` in the recursive function \\$g\\$, so that it gives up after \\$32 \times L\\$ iterations, where \\$L\\$ is the length of the input string.

```
s => (                        // main function taking the string s
  i = 26,                     // i = current step, initialized to 26
  F = m =>                    // F = recursive function taking the current minimum m
    i-- ?                     // decrement i; if i was not equal to 0:
      F(                      //   do a recursive call to F:
        (g = x =>             //     g = recursive function taking a character ID x
          s[p] ?              //       if there's still at least one letter to match:
            s[k++ >> 5] ?     //         if we've done less than 32 * s.length iterations:
              j = 1 + g(      //           add 1 to the final result and add the result of
                x + i,        //             a recursive call to g with x = x + i
                p += b[p] ==  //             increment p if
                  x % 26 + 97 //             the current letter is matching
              )               //           end of recursive call to g
            :                 //         else (we've done too many iterations):
              m               //           stop recursion and yield the current minimum
          :                   //       else (all letters have been matched):
            0                 //         stop recursion and yield 0
        )(                    //     initial call to g with p = k = 0
          b[p = k = 0] + 7    //     and x = ID of 1st letter
        ) > m ?               //     if the result is not better than the current minimum:
          m                   //       leave m unchanged
        :                     //     else:
          (r = i, j)          //       update m to j and r to i
      )                       //   end of recursive call to F
    :                         // else (i = 0):
      r                       //   stop recursion and return the final result r
)(b = Buffer(s))              // initial call to F with m = b = list of ASCII codes of s

```
> 4 votes

# Answer
# Jelly, ~~28~~ ~~26~~ 23 bytes

```
S;þḅ26ŒpṢƑƇIŻ€S:g/ƊÞḢg/

```

Output is 0-indexed. Input is a bytestring and can be in any case, but uppercase is *much* faster.

Single-letter input has to be special-cased and costs 2 bytes. .\_.

Try it online!

Note that this is a brute-force approach; inputs with four or more letters will time out on TIO. The test suite prepends `_39` for "efficiency".

### How it works

```
S;þḅ26ŒpṢƑƇIŻ€S:g/ƊÞḢg/  Main link. Argument: b (bytestring)

S                        Take the sum (s) of the code points in b.
 ;þ                      Concatenate table; for each k in [1, ..., s] and each c in
                         b, yield [k, c], grouping by c.
   ḅ26                   Unbase 26; map [k, c] to (26k + c).
      Œp                 Take the Cartesian product.
        ṢƑƇ              Comb by fixed sort; keep only increasing lists.
           I             Increments; take the forward differences of each list.
            Ż€           Prepend a 0 to each list.
                         I returns empty lists for single-letter input, so this is
                         required to keep g/ (reduce by GCD) from crashing.
                   Þ     Sort the lists by the link to the left.
              S:g/Ɗ      Divide the sum by the GCD.
                    Ḣ    Head; extract the first, smallest element.
                     g/  Compute the GCD.

```
> 4 votes

# Answer
# Jelly, 17 bytes

```
ƓI%
26×þ%iþÇo!SỤḢ

```

Input is a bytestring on STDIN, output is 1-indexed.

Try it online!

### How it works

```
ƓI%            Helper link. Argument: m (26 when called)

Ɠ              Read a line from STDIN and eval it as Python code.
 I             Increments; take all forward differences.
  %            Take the differences modulo m.

26×þ%iþÇoSSỤḢ  Main link. No arguments.

26             Set the argument and the return value to 26.
  ×þ           Create the multiplication table of [1, ..., 26] by [1, ..., 26].
    %          Take all products modulo 26.
       Ç       Call the helper link with argument 26.
     iþ        Find the index of each integer to the right in each list to the left,
               grouping by the lists.
        o!     Replace zero indices (element not found) with 26!.
               This works for strings up to 25! = 15511210043330985984000000 chars,
               which exceeds Python's 9223372036854775807 character limit on x64.
          S    Take the sum of each column.
           Ụ   Sort the indices by their corresponding values.
            Ḣ  Head; extract the first index, which corresponds to the minimal value.

```
> 4 votes

# Answer
# Python 2, ~~230~~ ~~222~~ ~~216~~ ~~194~~ 169 bytes

```
def t(s,l,S=0):
 a=ord(s[0])
 for c in s[1:]:
	while a-ord(c)and S<len(s)*26:S+=1;a=(a-65+l)%26+65
 return S
def f(s):T=[t(s,l)for l in range(26)];return T.index(min(T))

```

Try it online!

-22 bytes from tsh

-39 bytes from Jo King

Older version with explanation:

```
A=map(chr,range(65,91)).index
def t(s,l,S=0):
 a=A(s[0])
 for c in s[1:]:
	while a!=A(c)and S<len(s)*26:
	 S+=1;a+=l;a%=26
 return S
def f(s):T=[t(s,l)for l in range(26)];return T.index(min(T))

```

Try it online!

~~This would be shorter in a language with a prime number of letters (wouldn't need the `float('inf')` handling of infinite loops). Actually, this submission would still need that for handling strings like "aaa".~~ This submission now uses `26*len(s)` as an upper bound, which stops infinite loops.

This submission is 0-indexed (returns values from 0 to 25 inclusive).

`f` takes a(n uppercase) string and returns the Optimal Alphabet Stepping

`t` is a helper function that takes the string and an alphabet stepping and returns the number of hops needed to finish the string (or `26*len(s)` if impossible).
> 3 votes

# Answer
# Red, 197 bytes

```
func[s][a: collect[repeat n 26[keep #"`"+ n]]m: p: 99 a: append/dup a a m
u: find a s/1 repeat n 26[v: extract u n
d: 0 foreach c s[until[(v/(d: d + 1) = c)or(d > length? v)]]if d < m[m: d p: n]]p]

```

Try it online!
> 2 votes

# Answer
# Python 3, ~~191~~ ~~178~~ 162 bytes

Thanks everyone for all your tips! this is looking much more golflike.

```
*w,=map(ord,input())
a=[]
for i in range(26):
 n=1;p=w[0]
 for c in w:
  while n<len(w)*26and p!=c:
   n+=1;p+=i;
   if p>122:p-=26
 a+=[n]
print(a.index(min(a)))

```

Try it online!

And my original code if anyone's interested.

Turns the word into a list of ASCII values, then iterates through step sizes 0 to 25, checking how many steps it takes to exhaust the list (there's a ceiling to stop infinite loops).

Number of steps is added to the list *a*.

After the big for loop, the index of the smallest value in *a* is printed. This is equal to the value of *i* (the step size) for that iteration of the loop, QED.
> 2 votes

# Answer
# 05AB1E (legacy), ~~33~~ ~~27~~ 26 bytes

```
Ç¥ε₂%U₂L<©ε®*₂%Xk'-žm:]øOWk

```

Uses the legacy version because there seems to be a bug when you want to modify/use the result after a nested map in the new 05AB1E version..

0-indexed output.

Try it online or verify all test cases.

**Explanation:**

```
Ç                        # ASCII values of the (implicit) input
 ¥                       # Deltas (differences between each pair)
  ε                      # Map each delta to:
   ₂%                    #  Take modulo-26 of the delta
     U                   #  Pop and store it in variable `X`
      ₂L<                #  Push a list in the range [0,25]
         ©               #  Store it in the register (without popping)
          ε              #  Map each `y` to:
           ®*            #   Multiply each `y` by the list [0,25] of the register
             ₂%          #   And take modulo-26
                         #   (We now have a list of size 26 in steps of `y` modulo-26)
               Xk        #   Get the index of `X` in this inner list (-1 if not found)
                 '-₄:   '#   Replace the minus sign with "1000"
                         #   (so -1 becomes 10001; others remain unchanged)
]                        # Close both maps
 ø                       # Zip; swapping rows/columns
  O                      # Sum each
   W                     # Get the smallest one (without popping the list)
    k                    # Get the index of this smallest value in the list
                         # (and output the result implicitly)

```
> 2 votes

# Answer
# JavaScript (Node.js), 85 bytes

```
s=>(b=Buffer(s),g=i=>s[g[j=i%26]=g[j]+!((b[0]-b[g[j]]+~~(i++/26)*j)%26)||1]?g(i):j)``

```

Try it online!

Branch First Search, needn't handle infinite loop

# JavaScript (Node.js), 83 bytes

```
s=>(b=Buffer(s),g=i=>s[g[j=i%26]=g[j]+!((b[0]-b[g[j]]-~(i++/26)*j)%26)|0]?g(i):j)``

```

Try it online!

Assumes even is always better than odd if possible, 13 is always better than other if possible, which seems correct

# JavaScript (Node.js), 82 bytes

```
s=>(g=i=>s[g[j=i%26]=g[j]+!((b[0]-b[g[j]]-~(i/26)*j)%26)|0]?g(-~i):j)(b=Buffer(s))

```

Try it online!

Less confident about correctness
> 1 votes

---
Tags: code-golf, alphabet
---


title: The Margin is too Narrow

text:
# Question
Title: The Margin is too Narrow
Around the year 1637, Pierre de Fermat wrote in the margins of his copy of the Arithmetica:

```
It is impossible to separate a cube into two cubes, or a fourth power
into two fourth powers, or in general, any power higher than the
second, into two like powers. I have discovered a truly marvelous
proof of this, which this margin is too narrow to contain.

```

Unfortunately for us, the margin is still too narrow to contain the proof. Today, we are going to write into the margins a simple program that confirms the proof for arbitrary inputs.

# The Challenge

We want a program for function that given a power, separates it into two pairs of two powers that are as close to the power as possible. We want the program that does this to be as small as possible so it can fit into the margins.

---

# Input

The power and the power number: `c`, `x`

Constraints: `c > 2` and `x > 2`

Input can be through program arguments, function arguments, or from the user.

# Output

This exact string: "`a^x + b^x < c^x`" with `a`, `b`, `c`, and `x` replaced with their literal integer values. `a` and `b` must be chosen so that `a^x + b^x < c^x` and no other values of `a` or `b` would make it closer to `c^x`. Also: `a>=b>0`

Output can be through function return value, stdout, saved to a file, or displayed on screen.

---

**Examples:**

```
> 3 3
2^3 + 2^3 < 3^3
> 4 3
3^3 + 3^3 < 4^3
> 5 3
4^3 + 3^3 < 5^3
> 6 3
5^3 + 4^3 < 6^3
> 7 3
6^3 + 5^3 < 7^3
> 8 3
7^3 + 5^3 < 8^3

```

Due to Fermat's average writing skills, unprintable characters are not allowed. The program with the least number of characters wins.

---

## Leaderboards

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```
## Language Name, N characters

```

Alternatively, you can start with:

```
## Language Name, N bytes

```

where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:

```
## Ruby, <s>104</s> <s>101</s> 96 bytes

```

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:

```
## Perl, 43 + 2 (-p flag) = 45 bytes

```

You can also make the language name a link which will then show up in the leaderboard snippet:

```
# [><>](http://esolangs.org/wiki/Fish), 121 bytes

```

```
var QUESTION_ID=57363,OVERRIDE_USER=32700;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"http://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```

```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```

# Answer
# Pyth, 38 bytes

```
Ls^Rvzbjd.imj\^,dz+eoyNf<yTy]Q^UQ2Q"+<

```

Takes input in this format:

```
x
c

```
> 9 votes

# Answer
# Matlab, ~~169~~ 153 bytes

~~The score can be +-1 depending on the unsolved problems in the comments=)~~ The score stays the same. This is just a bruteforce search for the best `(a,b)` pair.

Pretty disappointing: I first tried experimented with some 'fancy' stuff and then realized two simple nested for loops are way shorter...

```
function f(c,x);
m=0;p=@(x)int2str(x);
X=['^' p(x)];
for b=1:c;for a=b:c;
n=a^x+b^x;
if n<c^x&n>m;m=n;s=[p(a) X ' + ' p(b) X ' < ' p(c) X];end;end;end;
disp(s)

```

Old version:

```
function q=f(c,x);
[b,a]=meshgrid(1:c);
z=a.^x+b.^x;
k=find(z==max(z(z(:)<c^x & a(:)>=b(:))),1);
p=@(x)int2str(x);x=['^' p(x)];
disp([p(a(k)) x ' + ' p(b(k)) x ' < ' p(c) x])

```
> 8 votes

# Answer
# Mathematica, ~~79 95~~ 80 bytes

This just might fit onto the margin.

```
c_~f~x_:=Inactivate[a^x+b^x<c^x]/.Last@Solve[a^x+b^x<c^x&&a>=b>0,{a,b},Integers]

```

---

**Testing**

```
f[3, 3]
f[4, 3]
f[5, 3]
f[6, 3]
f[7, 3]
f[8, 3]

```
> 8 votes

# Answer
# CJam, ~~51~~ ~~46~~ 43 bytes

```
q~_2m*\f+{W$f#)\:+_@<*}$W='^@s+f+"+<".{S\S}

```

This full program reads the power, then the base from STDIN.

Try it online in the CJam interpreter.
> 7 votes

# Answer
## Matlab, ~~141~~ 140 bytes

This is coded as function that displays the result in stdout.

```
function f(c,x)
b=(1:c).^x;d=bsxfun(@plus,b,b');d(d>c^x)=0;[~,r]=max(d(:));sprintf('%i^%i + %i^%i < %i^%i',[mod(r-1,c)+1 ceil(r/c) c;x x x])

```

Example use:

```
>> f(8,3)
ans =
7^3 + 5^3 < 8^3

```

Or try it online in Octave.

Thanks to @flawr for removing one byte.
> 6 votes

# Answer
# R, 139 characters

```
function(c,x)with(expand.grid(a=1:c,b=1:c),{d=a^x+b^x-c^x
d[d>0]=-Inf
i=which.max(d)
sprintf("%i^%4$i + %i^%4$i < %i^%4$i",a[i],b[i],c,x)})

```
> 5 votes

# Answer
# CJam, ~~53~~ 51 bytes

```
l~:C\:X#:U;C2m*{Xf#:+_U<*}$W=~"^"X+:T" + "@T" < "CT

```

Try it online

The input format is `x c`, which is the reverse of the order used in the examples.

Explanation:

```
l~    Read and interpret input.
:C    Store c in variable C.
\     Swap x to top.
:X    Store it in variable X.
#     Calculate c^x.
:U;   Store it in variable U as the upper limit, and pop it from stack.
C2m*  Generate all pairs of values less than c. These are candidates for a/b.
{     Start of mapping function for sort.
  X     Get value of x.
  f#    Apply power to calculate [a^x b^x] for a/b candidates.
  :+    Sum them to get a^x+b^x.
  _U<   Compare value to upper limit.
  *     Multiply value and comparison result to get 0 for values above limit.
}$    End of sort block.
W=    Last a/b pair in sorted list is the solution.
~     Unpack it.
"^"X+ Build "^x" string with value of x.
:T    Store it in variable T, will use it 2 more times in output.
" + " Constant part of output.
@     Rotate b to top of stack.
T     "^x" again.
" < " Constant part of output.
C     Value of c.
T     And "^x" one more time, to conclude the output.

```
> 5 votes

# Answer
# Python 2, ~~182~~ ~~161~~ 157 bytes

I usually answer in MATLAB, but because there are already two solutions in that language, I'd figure I'd try another language :)

```
def f(c,x):print max([('%d^%d + %d^%d < %d^%d'%(a,x,b,x,c,x),a**x+b**x) for b in range(1,c+1) for a in range(b,c+1) if a**x+b**x<c**x],key=lambda x:x[1])[0]

```

# Ungolfed code with explanations

```
def f(c,x): # Function declaration - takes in c and x as inputs

    # This generates a list of tuples where the first element is
    # the a^x + b^x < c^x string and the second element is a^x + b^x
    # Only values that satisfy the theorem have their strings and their
    # corresponding values here
    # This is a brute force method for searching
    lst = [('%d^%d + %d^%d < %d^%d'%(a,x,b,x,c,x),a**x+b**x) for b in range(1,c+1) for a in range(b,c+1) if a**x+b**x<c**x]

    # Get the tuple that provides the largest a^x + b^x value
    i = max(lst, key=lambda x:x[1])

    # Print out the string for this corresponding tuple
    print(i[0])

```

# Example Runs

I ran this in IPython:

```
In [46]: f(3,3)
2^3 + 2^3 < 3^3

In [47]: f(4,3)
3^3 + 3^3 < 4^3

In [48]: f(5,3)
4^3 + 3^3 < 5^3

In [49]: f(6,3)
5^3 + 4^3 < 6^3

In [50]: f(7,3)
6^3 + 5^3 < 7^3

In [51]: f(8,3)
7^3 + 5^3 < 8^3

```

# Try it online!

http://ideone.com/tMjGdh

If you want to run the code, click on the *edit* link near the top, then modify the STDIN parameter with two integers separated by a space. The first integer is `c` and the next one is `x`. Right now, `c=3` and `x=3` and its result is currently displayed.
> 4 votes

# Answer
# Pyth, ~~53~~ ~~52~~ 50 bytes

```
Ls^ReQbs[j" + "+R+\^eQ_Sh.MyZf<yT^FQ^UhQ2" < "j\^Q

```

Try it online.

Takes as input `c,x` where `c` is the target number and `x` is the base.
> 3 votes

# Answer
# Pyth, 60 bytes

Input is given as c,k

```
=k^ReQUKhQLfghTeT^tb2jd.i+R+\^eQa@yUKxJsMykh.M?>Z^KeQ0ZJK"+<

```

Try it Online
> 2 votes

# Answer
# C, 175 bytes

```
a,b,m,A,B,M;p(
a,x){return--x
?a*p(a,x):a;}f
(c,x){M=p(c,x)
;for(a=c,b=1;a
>=b;)(m=p(c,x)
-p(a,x)-p(b,x
))<0?--a:m<M?
(M=m,B=b++,A=
a):b++;printf
("%d^%d + %d"
"^%d < %d^%d",
A,x,B,x,c,x);}

```

To fit the code into the margin, I've inserted newlines and split a string literal above - the golfed code to be counted/compiled is

```
a,b,m,A,B,M;p(a,x){return--x?a*p(a,x):a;}f(c,x){M=p(c,x);for(a=c,b=1;a>=b;)(m=p(c,x)-p(a,x)-p(b,x))<0?--a:m<M?(M=m,B=b++,A=a):b++;printf("%d^%d + %d^%d < %d^%d",A,x,B,x,c,x);}

```

Function `f` takes `c` and `x` as arguments, and produces the result on `stdout`.

### Explanation

This is an iterative solution that zigzags the line defined by `a^x + b^x = c^x`. We start with `a=c` and `b=1`. Obviously, that puts us on the wrong side of the line, because `c^x + 1 > c^x`. We decrement `a` until we cross the line. When we're below the line, we increment `b` until we cross it in the other direction. Repeat until `b` meets `a`, remembering the best solution in `A` and `B` as we go. Then print it.

`p` is a simple recursive implementation of `a^x` (for `x>0`) since C provides no operator for exponentiation.

In pseudo-code:

```
a=c
b=1
M = c^x

while a >= b
do
   m = c^x - a^x - b^x
   if m < 0
      a -= 1
   else // (m > 0, by Fermat's Last Theorem)
      if m < M
         A,B,M = a,b,m
      b += 1
done
return A,B

```

### Limitations

`c^x` must be representable within the range of `int`. If that limitation is too restrictive, the signature of `p` could be trivially modified to `long p(long,int)` or `double p(double,int)`, and `m` and `M` to `long` or `double` respectively, without any modification to `f()`.

### Test program

This accepts `c` and `x` as command-line arguments, and prints the result.

```
#include<stdio.h>
int main(int argc, char**argv) {
    if (argc <= 2) return 1;
    int c = atoi(argv[1]);
    int x = atoi(argv[2]);
    f(c,x);
    puts("");
    return 0;
}

```
> 2 votes

# Answer
# Japt `-S`, ~~38~~ ~~33~~ ~~31~~ 30 bytes

```
pV
õ ï Ôæ@>XxpVÃïNÅ iÄ p<N Ëq^

```

Try it

```
                      :Implicit input of integers U=c & V=x

pV\nõ ï Ôæ@>XxpVÃ     >FINDING THE PAIR
pV                    :Raise U to the power of V
  \n                  :Reassign to U
    õ                 :Range [1,U]
      ï               :Cartesian product with itself
        Ô             :Reverse
         æ            :Find the first element that returns true
          @           :When passed through the following function as X
           >          :  U is greater than
            Xx        :  X reduced by addition
              pV      :  After raising each to the power of V
                Ã     :End find

ïNÅ iÄ p<N Ëq^        >FORMATTING THE OUTPUT
ï                     :Cartesian product with
 N                    :  Array of all inputs (i.e., the original [U,V])
  Å                   :  Slice off the first element
    i                 :Insert
     Ä                :  "+" at 0-based index 1
       p<N            :Push "<", and the array of all inputs
           Ë          :Map
            q^        :  Join arrays with (and split strings on) "^"

                      :Implicit output joined with spaces

```
> 2 votes

# Answer
# Haskell, 120 bytes

I think I've golfed this as much as I can:

```
c%x=a&" + "++b&" < "++c&""where(_,a,b)=maximum[(a^x+b^x,a,b)|b<-[1..c],a<-[b..c],a^x+b^x<c^x];u&v=show u++"^"++show c++v

```

Ungolfed:

```
fn c x = format a " + " ++ format b " < " ++ format c ""
    where format :: Integer -> String -> String
          -- `format u v` converts `u`, appends an exponent string, and appends `v`
          format u v = show u ++ "^" ++ show c ++ v
          -- this defines the variables `a` and `b` above
          (_, a, b) = maximum [(a^x + b^x, a, b) | b <- [1..c],
                                                   a <- [b..c],
                                                   a^x + b^x < c^x]

```

Usage:

```
Prelude> 30 % 11
"28^30 + 28^30 < 30^30"

```
> 1 votes

# Answer
# Haskell, ~~132~~ 128 bytes

```
x!y=x++show y
c#x=(\[_,a,b]->""!a++"^"!x++" + "!b++"^"!x++" < "!c++"^"!x)$maximum[[a^x+b^x,a,b]|a<-[0..c],b<-[0..a],a^x+b^x<c^x]

```

Usage example: `7 # 3` returns the string `"6^3 + 5^3 < 7^3"`.
> 0 votes

# Answer
# Perl 5, 119 bytes

A subroutine:

```
{for$b(1..($z=$_[0])){for(1..$b){@c=("$b^$o + $_^$o < $z^$o",$d)if($d=$b**($o=$_[1])+$_**$o)<$z**$o and$d>$c[1]}}$c[0]}

```

Use as e.g.:

```
print sub{...}->(8,3)

```
> 0 votes

# Answer
# Ruby, 125 bytes

Anonymous function. Builds a list of `a` values, uses it to construct `a,b` pairs, then finds the max for the ones that fit the criteria and returns a string from there.

```
->c,x{r=[];(1..c).map{|a|r+=([a]*a).zip 1..a}
a,b=r.max_by{|a,b|z=a**x+b**x;z<c**x ?z:0}
"#{a}^#{x} + #{b}^#{x} < #{c}^#{x}"}

```
> 0 votes

# Answer
# JavaScript (Node.js), 114 bytes

```
c=>x=>{for(a=B=[];++a<c;)for(b=0;++b<c;)B[c**x-a**x-b**x]=`${a}^${x} + ${b}^${x} < ${c}^${x}`;return B.find(_=>_)}

```

Try it online!

# JavaScript (Node.js), 117 bytes

```
c=>x=>[...B=Array(c)].map((_,a,P)=>P.map((_,b)=>B[c**x-a**x-b**x]=`${a}^${x} + ${b}^${x} < ${c}^${x}`))&&B.find(_=>_)

```

Try it online!

Brute-force all a,b\<c
> 0 votes

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


# Question
Title: I reverse the source code, you negate the input!
*Blatant rip-off of a rip-off. Go upvote those!*

Your task, if you wish to accept it, is to write a program/function that outputs/returns its integer input/argument. The tricky part is that if I reverse your source code, the output must be the original integer negated.

## Examples

Let's say your source code is `ABC` and its input is `4`. If I write `CBA` instead and run it, the output must be `-4`.

Let's say your source code is `ABC` and its input is `-2`. If I write `CBA` instead and run it, the output must be `2`.

An input of `0` may give `0` or `-0`, however, if you do support signed zero, `-0` should give `0`.

# Answer
# , 3 bytes

```
-&0

```

Try it online!

`-&0` is "argument minus 0"

`0&-` is "0 minus argument"
> 25 votes

# Answer
# PowerShell, ~~18~~ 14 bytes

```
$args#"sgra$"-

```

Try it online! !enilno ti yrT

First of the trivial comment-abuse answers
> 20 votes

# Answer
# x86 machine code, 3 bytes

```
C3 D8 F7

```

The above bytes of code define a function that is a no-op: it simply returns control to the caller. That function is followed by two garbage bytes that will not be executed, since they come after a return—they are in "no man's land". In assembler mnemonics:

```
ret                     ; C3
fdiv  st(0), st(7)      ; D8 F7

```

Okay, so now some troll comes by and reverses the order of the bytes:

```
F7 D8 C3

```

These bytes now define a function that takes an integer argument in the `EAX` register, negates it, and returns control to the caller. In assembler mnemonics:

```
neg  eax     ; F7 D8
ret          ; C3

```

So…that was simple. :-)

Note that we can make the "negation" instruction be *anything* we want, since it is never executed in the "forward" orientation and only executed in the "reversed" orientation. Therefore, we can follow the same pattern to do arbitrarily more complicated stuff. For example, here we take an integer argument in a different register (say, `EDI`, to follow the System V calling convention commonly used on \*nix systems), negate it, and return it in the conventional `EAX` register:

```
C3      ret
D8 F7   fdiv  st(0), st(7)      ;  \ garbage bytes that
F8      clc                     ;  | never get executed,
89      .byte 0x89              ;  / so nobody cares

```

↓ ↓

```
89 F8   mov  eax, edi
F7 D8   neg  eax
C3      ret

```
> 16 votes

# Answer
# JavaScript, 11 bytes

```
n=>n//n->=n

```

Try it Online! | Reversed
> 15 votes

# Answer
# Jelly, 2 bytes

```
oN

```

**Try it online!** and its reverse.

```
oN - (input) OR ((input) negated)

No - ((input) negated) OR (input)

```
> 12 votes

# Answer
# Haskell, 8 bytes

Anonymous identity function, turning into subtraction from `0` when reversed.

```
id--)-0(

```

Try it online!

Reversed:

```
(0-)--di

```

Try it online!
> 9 votes

# Answer
# Whitespace, 48 bytes

```
S S S N
S N
S T N
T   T   T   T   T   T   N
S T N
N
N
T   S N
T   N
S S T   N
T   T   S S T   T   T   T   T   N
T   S N
S N
S S S

```

Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.

Minor modification of my Whitespace answer for the *I reverse the source code, you negate the output!* challenge.

Try it online or try it online reversed (with raw spaces, tabs and new-lines only).

**Explanation:**

Utilizing the *Exit Program* builtin being a short palindrome `NNN`.
The regular program will:

```
SSSN   # Push 0 to the stack
SNS    # Duplicate it
TNTT   # Read STDIN as integer, and store it at heap address 0
TTT    # Retrieve the input from heap address 0, and push it to the stack
TNST   # Pop and print the top of the stack as number
NNN    # Exit the program, making everything after it no-ops

```

The reverse program will:

```
SSSN   # Push 0 to the stack
SNS    # Duplicate it
TNTT   # Read STDIN as integer, and store it at heap address 0
TTT    # Retrieve the input from heap address 0, and push it to the stack
SSTTN  # Push -1 to the stack
TSSN   # Multiply the top two values on the stack together
TNST   # Pop and print the top of the stack as number
NNN    # Exit the program, making everything after it no-ops

```

Small additional explanation of pushing a number:

* First `S`: Enable Stack Manipulation
* Second `S`: Push a number to the stack
* `S` or `T`: Positive/negative respectively
* Some `S`/`T` followed by a trailing `N`: number in binary, where `S=0` and `T=1`

I.e. `SSTTSTSN` pushes `-10`. For the `0` we don't need an explicit `S=0`, so simply `SSSN` or `SSTN` is enough.
> 8 votes

# Answer
# , 23 bytes

I decided to give it a go without the comment trick.

### Forward

```
`+`=scan;""+-0;nacs=`+`

```

Try it online!

### Reverse

```
`+`=scan;0-+"";nacs=`+`

```

Try it online!

In the forward version `+` is acting a binary operator, and `-` is a unary operator.

In the reverse the `+` becomes unary and the `-` is binary. So scan function takes the arguments: `file=""` which means stdin and `what=0`, which are also defaults. So when the `+` is unary the first argument is on the right, when it is binary the first argument is on the left.

The

```
;nacs=`+`

```

part of the code does nothing really useful, so in a sense my code is not really very much more valid than using the comment trick.
> 8 votes

# Answer
# C (clang), 23 bytes

```
f(*x){}//};x*-=x*{)x*(g

```

Try it online!
> 6 votes

# Answer
# Labyrinth / Hexagony, 6 bytes

Labyrinth:

```
?!@!`?

```

**Try it online!** and its reverse.

Hexagony:

```
?!@!~?

```

**Try it online!** and its reverse.

### How?

```
?       - take a signed integer
(` / ~) - negate
!       - output top-of-stack / current-memory-edge
@       - exit

```
> 5 votes

# Answer
# Perl 6 / Raku, 3 bytes

```
*-0

```

Try it online!

Creates a Whatever code block. Read in normally its standard block equivalent is `-> \x {x - 0}`, but in reverse it becomes `-> \x {0 - x}`.
> 5 votes

# Answer
# Python 3, 22 bytes

```
lambda x:x#x-:x adbmal

```

Try it online!

A lambda which implements the identity function (or negation)
> 5 votes

# Answer
# Gaia, 2 bytes

```
_@

```

Try it online!

```
_	| implicit push input and negate
 @	| push next input OR push last input (when all inputs have been pushed)
	| implicit print TOS

```

Reversed:

```
@	| push input
 _	| negate
	| implicit print TOS

```
> 4 votes

# Answer
# Brain-Flak, 7 bytes

```
#)]}{[(

```

Try it online!

Reversed:

```
([{}])#

```

Try it online!

Note: Only works in interpreters that support comments (e.g. works in Rain-Flak, but not in BrainHack)

---

If we also swap opening/closing brackets instead of just reversing the bytes we can do this in 8 bytes without using comments:

```
({}[{}])

```

Try it online!
Try it reversed!
> 4 votes

# Answer
# Perl 5 (`-p`), ~~7~~ 6 bytes

-1 thanks to @primo

```
$_*=$#

```

TIO

A comment doesn't change input

```
#1-=*_$

```

Negate the input

```
$_*=-1#

```

TIO
> 4 votes

# Answer
# , 14 bytes

```
scan()#)(nacs-

```

Try it online!

A full program that reads a number, or reads and negates a number. The reverse functionality is protected by an inline comment
> 4 votes

# Answer
# Backhand, ~~6~~ 5 bytes

```
I@-Ov

```

Try it online! Try it doubled!

Made a little complex due to the nature of the pointer in Backhand. ~~I don't think it's possible to get any shorter~~ haha, turns out I was wrong. This duplicates *no* instruction and reuses both the input, output and terminate commands between the two programs. *Now* I think it is optimal, since you need all of the `IO-@` commands to work, and in a 4 byte program you can only execute two of those commands.

### Explanation:

The pointer in Backhand moves at three cells a tick and bounces off the boundaries of the cell, which means the general logic is overlapping. However you can manipulate this speed with the `v` and `^` commands.

The original program executes the instructions `IO-@`, which is input as number, output as number, subtract, terminate. Obviously the subtract is superfluous. In the code these are:

```
I@-Ov
^  ^    Reflect
  ^     Reflect again
 ^

```

The reversed program executes `v-I-vO-@`. The `v` reduces the pointer steps between ticks, and the `-` subtracts from the bottom of the stack, which is implicitly zero. The extra `-` commands do nothing. The program executes like

```
vO-@I
v       Reduce pointer speed to 2
  -     Subtract zero from zero
    I   Get input as number and reflect off boundary
  -     Subtract input from zero
v       Reduce pointer speed to 1
 O      Output as number
  -     Subtract zero from zero
   @    Terminate

```
> 4 votes

# Answer
# MarioLANG, 22 bytes

```
;:
=#
:)!
--
<(
"
[>
;

```

Try it online!

He just inputs and outputs the number before he falls to EOF

reversed:

```
;
>[
"
(<
--
!):
#=
:;

```

Try it online!

He loops until the input value is 0 and the output value is -input, the he says the number.
> 4 votes

# Answer
## Haskell, 12 bytes

```
f=id;x-0=x f

```

Try it online! Reverse:

```
f x=0-x;di=f

```

Try it online!

Not as short as Ørjan Johansen's answer, but without comments.
> 4 votes

# Answer
# Python 3, ~~22~~ 14 bytes

```
int#__bus__. 0

```

Try it online!

Uses the `int` class's constructor and a built-in pseudo-private method.
> 4 votes

# Answer
# APL (Dyalog Unicode), ~~13~~ 3 bytes

```
-∘0

```

Try it online!

Trivial answer. Returns `arg` or `¯arg`.

Saved 10 bytes by not being dumb (thanks Adám).

Altered the resulting 3-byter to a more fitting function.
> 3 votes

# Answer
# Wolfram Language (Mathematica), 9 bytes

```
1&0+#-0&1

```

Try it online!

Forward: read `((1)&*0+#-0)&*1`=`#&`

Backward: read `((1)&*0-#+0)&*1`=`-#&`
> 3 votes

# Answer
## Excel VBA, 12

```
?[A1]']1A[-?

```

Reversed:

```
?-[A1]']1A[?

```

Input is cell A1 of the ActiveSheet. Comments still work in the Immediate Window :)
> 3 votes

# Answer
# Batch, 34 bytes

```
@ECHO.%1 2>MER@
@REM>2 1%=-aa/TES@

```

Echoes (`ECHO.`) the input (`%1`). The rest of the first line technically redirects `STDERR` to a file called `MER@`, but this isn't impactful.
Second line is commented out (`REM...`).

### Reversed

```
@SET/aa-=%1 2>MER@
@REM>2 1%.OHCE@

```

Uses the arithmetic mode of the set command (`SET /a`) to subtract (`-=`) the input (`%1`) from an undefined variable (`a`) which is equivalent to `0 - input`. Again, the rest of the first line technically redirects `STDERR` to a file called `MER@`, but this isn't impactful.
Second line is commented out (`REM...`).
> 3 votes

# Answer
# Triangular, ~~8~~ 7 bytes

```
$%%.|.$

```

Try it online!

Ungolfed:

```
   $           | $: Read an Integer
  % %          | %: Output it
 . | .
$

```

Reversed:

```
$.|.%%$

```

Try it online!

**Previous Version (8 bytes):**

```
$.%..|.$

```
> 2 votes

# Answer
# 05AB1E, 2 bytes

```
(I

```

Try it online!

Reversed

```
(    negates nothing
  I  pushes input

I    pushes input
  (  negates input

```
> 2 votes

# Answer
# Befunge-98 (FBBI), 6 bytes

```
&.@.-&

```

Try it online! Try it reversed!
> 2 votes

# Answer
# Klein, 2 bytes

*Works in all 12 topologies!*

```
@-

```

Try it online!

# Reverse

```
-@

```

Try it online!

`-` negates the input and `@` ends the program
> 2 votes

# Answer
# Turing Machine Language, 39 bytes

The Positive

```
1 r - _ 0
0 l * * 0
0 - _ l 0
0 _ _ r 0

```

The Negative

```
0 r _ _ 0
0 l _ - 0
0 * * l 0
0 _ - r 1

```

This one was a bit trickier than I thought, mostly because I had to get past my prejudices of having code that runs with 'compile' errors.
> 2 votes

# Answer
# \>\<\>, ~~5~~ 4 bytes

```
n-r0

```

uses stack initialisation with the `-v` option, put your input variable there.

Try it online!

Or try the reversal

**Explanation**

```
n       Prints whatever is on the stack as a number
 -      Subtract the top 2 elements on the stack.
        There aren't 2 elements, so it crashes.
  r0    Never gets executed

or reversed:

0       Push a 0 onto the stack
 r      reverse the stack (now 0, -v)
  -     Subtract top 2 elements and push result (0-v, ie negated)
   n    Print as number
        The code wraps around and executes again.
        It crashes on the - as there is only one
        item on the stack: 0.

```
> 2 votes

# Answer
## Stack Cats `-mn`, 2 bytes

```
-X

```

Try it online!

Try the reverse!

### Explanation

Turns out this is actually a lot easier than the previous challenge in Stack Cats. The full program (after applying `-m`) here is `-X-`. `X` is used to swap the stacks left and right of the tape head, i.e. it doesn't affect the initial stack at all, so we can ignore it. But then the program is effectively just `--` (negate the top of the stack twice), which does nothing.

For the inverse program, applying `-m` gives `X-X`. Again, `X` does nothing, so the program is effectively just `-`, which negates the top of the stack.

The only other 2-byte solution is `-=`, but it's virtually the same. The only difference is that `=` swaps only the tops of the adjacent stacks, not the entire stacks.

But again, using `-m` feels a bit like cheating, so below is a solution that uses a fully mirrored program.

---

## Stack Cats `-n`, 7 bytes

```
:I<->I:

```

Try it online!

Try the reverse!

### Explanation

The considerations from the previous answer still apply: any valid solution needs to use the paired characters and `I`. The six possible solutions (included in the TIO link) are all virtually the same. `-` and `_` are equivalent in this program, and `:` can be replaced by `|` or `T` (which do the same for non-zero inputs and coincidentally also work for zero inputs). I've just picked this one to explain because it's easiest.

So remember that the initial stack holds the input on top of a `-1` (on top of infinitely many zeros) whereas all the other stacks along the tape only hold zeros. Stack Cats also has the property that any even-length program does nothing (provided it terminates, but we can't use loops for this challenge anyway). The same is then obviously true for any odd-length program whose centre character does nothing... let's see:

```
:    Swap the input with the -1 below.
I    Move the -1 one stack to the left and turn it into +1.
<    Move another stack left (without taking the value).
-    Negate the zero on top of that stack (i.e. do nothing).

```

Therefore, the second half of the program exactly undoes the first half and we end up with the input on top of a `-1` again.

The inverse program is `:I>-<I:`. Let's see how that changes things:

```
:    Swap the input with the -1 below.
I    Move the -1 one stack to the left and turn it into +1.
>    Move one stack right, i.e. back onto the initial stack which still holds the input.
-    Negate the input.
<    Move back to the left where we've parked the 1.
I    Move that 1 back onto the initial stack and turn it back into a -1.
:    Swap the -1 below the negated input to act as an EOF marker.

```
> 2 votes

# Answer
# Brachylog, 2 bytes

```
&ṅ

```

Brachylog implicitly inputs from the left and outputs from the right.
`&` ignores anything to the left and passes the input to the function rightwards.
constrains each side of it to be negated versions of each other.

Try it online
> 2 votes

# Answer
## , ~~3~~ 2 bytes

Pretty much a port of the Keg answer. Might get around to implement an implicit return.

```
%_

```

## Explanation

```
   % Since there is nothing on-stack, return the input.
%_ % Start a comment

```

## noitanalpxE

```
_  % Negate input & return
 % % Start a comment

```
> 2 votes

# Answer
# Vyxal, 2 bytes

```
#N

```

Try it Online!

!enilnO ti yrT

`#N` is a comment, so nothing happens and the input is outputted unchanged.

`N#` negates the input, which is then outputted implicitly.

If you’re not a fan of using comments for something like this, the `#` can be replaced with any of `? , ₴ ⁰`, etc.
> 2 votes

# Answer
# Alice, 15 bytes

```
/O\ /I@
@I/R\O/

```

Try it online!
!enilno ti yrT

## Flattened

Original `I O@`, reads from the input, output
Reversed `IRO@`, reads from the input, negate, output

The mirrors switches in and out of ordinal mode, which execute the code in diagonal
> 2 votes

# Answer
# Alice, 11 bytes

```
\ X'@
/I-O/

```

Try it online!

!enilno ti yrT

Operates entirely within ordinal mode. The negation is done by taking string symmetric difference `X` with the single-char string `"-"`. The code path `IXO` is common; when reversed, `'-` is also stepped, pushing `"-"` before the input.
> 2 votes

# Answer
# Japt, 3 bytes

```
TnU

```

Try it | Reversed

Same method as my earlier solution, with `T` being `0` and `U` being the input.
> 1 votes

# Answer
# V (vim), 5 bytes

```
É-ó--

```

Try it online!

Hexdump:

```
00000000: c92d f32d 2d                             .-.--

```
> 1 votes

# Answer
# C++ (gcc), 29 bytes

```
#define f(x)x//x-)x(g enifed#

```

Try it online!

Fixed issue brought up by @Nick Kennedy
> 1 votes

# Answer
# Stax, 2 bytes

```
pN

```

Run and debug it
> 1 votes

# Answer
# Retina 0.8.2, ~~13~~ 12 bytes

```
-*$1#$
)^(|-

```

Try it online! It's impossible for the first line to match anything, so nothing happens. In reverse:

```
-|(^)
$#1$*-

```

Try it online! Explanation: Either a leading (implicitly) `-` or a leading empty string is matched. This is replaced with `-` repeated according to the number of empty strings that were matched.

Edit: Saved 1 byte thanks to @MartinEnder (although, cunningly, the reversed original worked with floating-point numbers in scientific notation). As he points out, Retina 1 would be a further byte shorter as its syntax for `*` is slightly different and does not require the adjacent `$` (and it would therefore also modify illegal inputs such as `-1#` which this version ignores).
> 1 votes

# Answer
# Ruby -p , 7+1 = 8 bytes

```
#-?<<>$

```

Try it online!

Reverse:

Try it online!
> 1 votes

# Answer
# PHP, 20 bytes

```
<?=$argn;#;ngra$-=?<

```

Try it online!
> 1 votes

# Answer
# MathGolf, 4 bytes

```
*b╘k

```

Try it online or try it online reversed.

**Explanation:**

Regular:

```
*     # Multiply the (implicit) input with the (implicit) input
      #  STACK: [input**2]
 b    # Push -1
      #  STACK [input**2, -1]
  ╘   # Discard everything on the stack
      #  STACK: []
   k  # Push the input as integer
      #  STACK: [input]
      # (output the entire stack joined together as result)

```

Reversed:

```
k     # Push the input as integer
      #  STACK: [input]
 ╘    # Discard everything on the stack
      #  STACK: []
  b   # Push -1
      #  STACK: [-1]
   *  # Multiple the (implicit) input with this -1
      #  STACK: [-input]
      # (output the entire stack joined together as result)

```

And to answer your question: no, MathGolf does not have a 1-byte negate for integers. There is `~` for `-n-1`, but unfortunately nothing for `-n` (so `*b` could alternatively be `)~` for the same byte-count).
> 1 votes

# Answer
# Japt, 3 bytes

```
n U

```

Try it

Try it reversed

# 3 bytes

```
nÎN

```

Try it

Try it reversed
> 1 votes

# Answer
# Cubix, 5 bytes

```
@IO\n

```

Try it online!

Try it reversed!
> 1 votes

# Answer
# Scala, 6 bytes

```
+_//_-

```

Try it online!

Unfortunately a function can't just contain a `_` to return the first argument, but using `unary_+` will return the value unchanged.

Once flipped, the code is `-_` which does a `unary_-` on the first argument, which flips the sign.
> 1 votes

# Answer
# Gol\>\<\>, 4 bytes

```
Ih-I

```

One byte golfed off courtesy of JoKing

Try it online!
> 1 votes

# Answer
# Runic Enchantments, 4 bytes

```
i@Zi

```

Try it online! Try it reversed!

Its the answer I originally wrote on the other challenge when I misread the description.
> 1 votes

# Answer
## Perl 5 - 12 Bytes

```
say$_#_$-yas

```

### Reversed

```
say-$_#_$yas

```

Abides by the `-0` rule.

Does require the `-nE` flags on execution.
> 1 votes

# Answer
# BitCycle `-U`, 15 bytes

First, a word about the `-U` flag. Internally, BitCycle only deals in 1's and 0's, so to allow working with decimal integers, it has flags to convert decimal input to unary. In particular, `-U` allows for signed integers by adding a `0` to the front of any nonpositive integer's unary representation: `4` is `1111`, `-4` is `01111`, and `0` is `0`. The same transformation is applied in reverse to the output, with the convenient addition that empty output is treated as `0`.

### Forward

```
^>

?!+?
 <0/

```

Try it online!

The leftmost `?` gets the input, which goes straight into the `!` to be output unchanged.

### Reverse

```
 /0<
?+!?

 >^

```

Try it online!

The leftmost `?` gets the input. The `+` sends the leading `0` bit, if any, left (north), and the `1` bits right (south).

If there is a leading `0` bit, it hits the splitter `/` and turns east, deactivating the splitter. The `<` sends it west again, through the deactivated splitter and off the playfield. The `0` bit that started on the playfield also hits the `<` and goes through the deactivated splitter and off the playfield. Meanwhile, the `1` bits are directed around by the `>` and `^` and reach the `!`, where they are output.

If there is no leading `0` bit, the `0` bit that starts on the playfield hits the `<` and goes west to the splitter `/`. Since the splitter has not been deactivated, it directs the bit south, and the `+` sends it west into the output `!`. Meanwhile, the `1` bits are directed to the output, with enough delay to make sure they get there after the `0` bit.

**TL;DR:** Nonpositive inputs have their leading `0` bit stripped and their magnitude is output. Positive inputs have a leading `0` bit added and are thus output as negative numbers of the same magnitude.
> 1 votes

# Answer
# BitCycle `-U`, 14 bytes

```
<  ^
v/?!
+~ +

```

Try it online!

And reversed

```
+ ~+
!?/v
^  <

```

Try it online!

The `-U` flag translates input/output to signed Unary, i.e. unary 1s with a zero in front if the number is negative. The first program just pipes input (`?`) to the output (`!`) directly right of it.

The reverse instead takes only the first bit of the number with the `/` command and dupnegs (`~`). If it is a `1` then it sends `0` left and `1` right, where the `+`s redirect them to join the flow to the output. If the first bit is `0` instead, the `0` goes right and the `1` goes left, and the `+` redirect them *away* from the output. All in all, this has the behaviour of stripping a leading zero if the input has one, otherwise prepending a zero if it doesn't, which means inverting the sign of the input.
> 1 votes

# Answer
# Keg, 2 bytes

Try it online! !enilno ti yrT

Real simple. When run in normal direction, it simply prints the input. When run in reverse direction (`±#`), it negates the input.
> 1 votes

# Answer
# TI-BASIC, 3 bytes

```
Ans-0

```

Very simple and works the same way as the top J answer.

Input is an integer in `Ans`.

**Examples:**

```
4:Ans-0
              4
4:0-Ans
             -4

```
> 1 votes

# Answer
# APL (Dyalog Unicode), 3 bytes

```
-/⊢
-/ ⍝ Summation with alternating sign
  ⊢ ⍝ Identity function

```

Reversed

```
⊢/-
⊢/ ⍝ Reduce (fold) with the Right operator
  - ⍝ Negate

```

Mirrored

```
⊣\-
⊣ ⍝ Left
 \ ⍝ Expand
  - ⍝ Negate

```

Try it online!
> 1 votes

# Answer
# sed, ~~14~~ 13 bytes

*Thanks to Philippos for -1 byte.*

```
##--#s;#-#^#s
```

The code is only comment, which means the input is outputted unchanged.

Attempt This Online!

**Reversed:**

```
s#^#-#;s#--##
```

The code first append `-` in front of the string. Then if there are two minuses they get removed.

Attempt This Online!
> 1 votes

# Answer
# Lua, 23 bytes

```
print(...)--)...-(tnirp

```

Try it online!

Comment abuse all over again.
> 0 votes

# Answer
# Cascade, 6 bytes

```
# -
&#

```

Try it online!

and reversed:

```
#&
- #

```

Try it online!

I think this is the optimal answer for this question. In order to negate the input, we have to use the `-` operator, which means the code must be at least three wide so the left and the right operands aren't the same. It must then be two tall to have not loop infinitely. That means at least one row must be three wide, and the other has to be two wide, since if it was one wide, it must be the redirect to the `#`, which would have to be directly under it. Feel free to prove me wrong though.

### Explanation:

For the initial program, we only execute `#` (integer output) on `&` (integer input). Basically, the only instructions that matter are:

```
#
&

```

For the reversed program, the `#` on the second line leads to `-` (left minus right). This wraps around the program, with the right being the `&`, and the left as an empty space, which is zero. This results in `0 - input`, which is the negated input.
> 0 votes

# Answer
# Phooey, 3 bytes

```
+.-

```

Try it online! (Forwards)

Try it online! (Backwards)

This assumes an empty stack and an empty tape.

Explanation:

Each instruction in Phooey has a modifier:

* No modifier defaults to either the stack or the tape, depending on the instruction.
* A number (with a preceding `_` for negative) uses an immediate value
* A `.` applies to an integer from stdin
* A `:` applies to a char from stdin
* A `!` applies to the stack (for instructions where it isn't the default)

So, when read forwards, it is this:

```
+.-
+.  # Add to the tape
  - # pop and subtract (does nothing because stack is empty)

```

And backwards, it is the same for -.

---

# Phooey, universal, 5 bytes

```
;0@.&

```

This version works regardless of the stack and tape state, and also preserves the stack contents.

Forwards:

```
;0@.&
;0    # tape = 0 - tape (don't care)
  @.  # read input and push to stack
    & # pop from the stack to the tape

```

Try it online! (Forwards)

Backwards:

```
&.@0;
&.    # read int and store to tape
  @0  # push 0 to the stack
    ; # pop, tape is 0 (stack) - tape

```

Try it online! (Backwards)
> 0 votes

# Answer
# Pxem, Filename: ~~30~~ 27 bytes + Content: 0 bytes = ~~30~~ 27 bytes, does not support signed zero, not clean.

* Filename (escaped unprintable): `._.n.o.-a.d.n.-.-.00y.\001c._.`
    + Reversed: `._.c\001.y00.-.-.n.d.a-.o.n._.`
* Content: empty

Try it online!

!enilno ti yrT

## With comments

### Original

```
XX.z
.a._.nXX.z # push getint; putint pop
.a.o.-XX.z # DOTo and DOT- works like EOF for insufficient items
.aa.dXX.z # push ascii code of a; exit
.a.n.-.-.00y.\001c._.XX.z # deadcode
  ## NOTE this is syntaxically valid
.a

```

### Reversed

```
XX.z
.a._.cXX.z # push getint; dup
.a\001.yXX.z # push 1; while pop>pop; do
  .a00.-.-XX.z # (*essentially*) push abs(0-pop)
    # NOTE actually: push 48; push 48;
    #     push abs(pop-pop); push abs(pop-pop)
    # NOTE NULL char not supported for filename
  .a.n.dXX.z # putint pop; exit
.a.aXX.z # done
.a-.o.nXX.z # push hyphen; putchar pop; putint pop
.a._XX.z # this is why it aborts when only an integer is given
.a..c.sXX.z # push dot
.a

```

---

# Pxem, Filename: 34 bytes + Content: 0 bytes = 34 bytes, clean.

* Filename (escaped some): `._d..s.s.n.o.-a.d.n.-.-.00y.\001c._.`
    + Reversed: `._.c\001.y00.-.-.n.d.a-.o.n.s.s..d_.`
* Content: empty

This version deals with exiting; reversed version exits well against non-negative input, too.

Try it online!
> 0 votes

# Answer
# Rattle, 12 bytes

```
||1c0gI|\\&-

```

Try it online!

!enilno ti yrT

This takes advantage of how Rattle is parsed. As of right now, there is only support for one input section (everything before the first `|`) - this means that anything after any following `|`'s will be disregarded. This more or less splits the code into two sections:

```
|

```

This is the effective forward code, which is the cat program.

```
-&\\|Ig0c1

```

This is the reverse code, which spits out the negative of the input. There's still possibility that this could be golfed further!
> 0 votes

# Answer
# MMIXAL, 35 bytes

`f POP 1,0 # 0,1 POP ;0$,0,0$ UGEN f`

Very simple; when reversed, is just negate-and-return.
> 0 votes

# Answer
# MMIX, 12 bytes (3 instrs)

```
00000000: f8010000 000001f8 00000036           ẏ¢¡¡¡¡¢ẏ¡¡¡6

```

Disassembled:

```
f   POP  1,0
    TRAP 0,Fopen,248
    TRAP 0,Halt,36

```

Reversed and disassembled:

```
f   NEGU $0,0,$0
    POP  1,0
    TRAP 0,Fopen,248

```

This is essentially the same as my MMIXAL answer, except that that relied on comments and reversed the source code, while this just relies on early return.
> 0 votes

# Answer
# SNOBOL4 (CSNOBOL4), 38 bytes

```
	OUTPUT =INPUT;END;DNE;TUPIN-= TUPTUO

```

Try it online!

Reversed

Anything after an `END` label is ignored. `;` is an alternate newline delimiter which made this answer easier to think about.
> 0 votes

# Answer
# dc, 5 bytes

```
dp-r0

```

Try it online!
> 0 votes

# Answer
# Ly, 3 bytes

```
+0-

```

Try it online!

Forwards:

```
+    : compute "0 + STDIN"
 0   : push 0
  -  : subtract the top two stack entries
     : prints stack as a number automatically

```

Backwards:

```
-    : compute "0 - STDIN"
 0   : push 0
  +  : add the top two stack entries
     : prints stack as a number automatically

```
> 0 votes

# Answer
# Knight, 5 bytes

```
O P~O

```

Try It Online!

Try It Online reversed!
> 0 votes

# Answer
# Thunno, \\$ 2 \log\_{256}(96) \approx \\$ 1.65 bytes

```
nI

```

Attempt This Online! or !enilnO sihT tpmettA

Outputs inside brackets, e.g. `[5]`.

Port of jasanborn's 05AB1E answer. `n` = negate, `I` = push input.
> 0 votes

---
Tags: code-golf, math, number, source-layout
---


title: Fake Statistics

text:
# Question
Title: Fake Statistics
If you're going to invent some fake news, you'll want to fabricate some data to back it up. You must already have some preconceived conclusions and you want some statistics to strengthen the argument of your faulty logic. This challenge should help you!

Given three input numbers:

* *N* \- number of data points
* *μ* \- mean of data points
* *σ* \- standard deviation of data points, where *μ* and *σ* are given by:

Output an unordered list of numbers, *i*, which would generate the given *N*, *μ*, and *σ*.

I'm not going to be too picky about I/O formats, but I do expect some sort of decimals for *μ*, *σ*, and the output data points. As a minimum, at least 3 significant figures and magnitude of at least 1,000,000 should be supported. IEEE floats are just fine.

* *N* will always be an integer, where 1 ≤ N ≤ 1,000
* *μ* can be any real number
* *σ* will always be ≥ 0
* data points can be any real number
* if *N* is 1, then *σ* will always be 0.

Note that most inputs will have many possible outputs. You only need to give one valid output. The output may be deterministic or non-deterministic.

### Examples

```
Input (N, μ, σ) -> Possible Output [list]

2, 0.5, 1.5 -> [1, 2]
5, 3, 1.414 -> [1, 2, 3, 4, 5]
3, 5, 2.160 -> [2, 6, 7]
3, 5, 2.160 -> [8, 4, 3]
1, 0, 0 -> [0]

```

# Answer
> 8 votes
# Pyth, ~~44~~ ~~35~~ 34 bytes

```
~~?eA.DhQ2+eQ*G,-eQJ*E@hc1thQ2+eQJ*G,-eQKE+eQK~~
~~.N?eA.DN2+T*G+LT_B*Y@hc1tN2*G+LT_BY~~
.N?eA.DN2+T*G+LT_B*Y@cNtN2*G+LT_BY

```

Try it online! (The code above defines a function. `:.*` is appended on the link to invoke the function.)

## The maths

This constructs the data symmetrically. If `N` is even, then the data are just the mean plus or minus the standard deviation. However, if `N` is odd, then we just opened a can of worms, since the mean has to be present for the data to be symmetric, and so the fluctuations have to be multiplied by a certain factor.

### If `n` is even

* Half of the data are `μ+σ`.
* Half of the data are `μ-σ`.

### If `n` is odd

* One datum is `μ`.
* Less than half of the data are `μ+σ*sqrt(n/(n-1))`.
* Less than half of the data are `μ-σ*sqrt(n/(n-1))`.

# Answer
> 6 votes
# MATL, 22 bytes

*Thanks to @DigitalTrauma for a correction.*

```
:t&1Zs/tYm-*+tZN?3G9L(

```

Input order is: `N`, `σ`, `μ`.

Try it online!

Or see a modified version that also computes the mean and standard deviation of the produced data, as a check.

### Explanation

The code is divided into four parts:

1. `:` generates the array `[1 2 ... N]` where `N` is taken as implicit input.
2. `t&1Zs/` divides those numbers by their empirical standard deviation (computed normalizing by `N`), and `tYm-` subtracts the empirical mean of the resulting values. This ensures that the results have empirical mean `0` and empirical standard deviation `1`.
3. `*` multiplies by `σ` and `+` adds `μ`, both taken as implicit inputs.
4. `tZN?x3G` handles the special case that `N = 1`, `σ = 0`, for which the output should be `μ`. If this is indeed the case, then the empirical standard deviation computed in the second step was `0`, the division gave `inf`, and multiplying by `σ` in the third step gave `NaN`. So what the code does is: if the obtained array consists of all `NaN` values (code `tZN?`), delete it (`x`) and push the third input (`3G`), which is `μ`.

# Answer
> 5 votes
## R, ~~83~~ ~~62~~ 53 bytes

```
function(n,m,s)`if`(n>1,scale(1:n)*s*sqrt(1-1/n)+m,m)

```

If `n=1`, then it returns `m` (since `scale` would return `NA`), otherwise it scales the data `[1,...,n]` to have mean 0 and (sample) standard deviation 1, so it multiplies by `s*sqrt(1-1/n)` to get the correct population standard deviation, and adds `m` to shift to the appropriate mean. Thanks to Dason for introducing me to the scale function and dropping those bytes!

Try it online!

# Answer
> 4 votes
# Python, 50 bytes

```
lambda n,m,s:[m+s*(n-1)**.5]+[m-s/(n-1%n)**.5]*~-n

```

Try it online!

Uses the following `n`-element distribution with mean `0` and sdev `1`:

* With probability `1/n` (i.e. `1` element), output `(n-1)**0.5`
* With probability `1-1/n` (i.e. `n-1` elements), output `-(n-1)**(-0.5)`

This is rescaled to mean `m` and sdev `s` by transforming `x->m+s*x`. Annoyingly, `n=1` gives a division by zero error for a useless value, so we hack it away by doing `/(n-1%n)**.5`, with `1%n` giving `0` for `n==1` and `1` otherwise.

You might think `(n-1)**.5` can be shortened to `~-n**.5`, but the exponentiation happens first.

A `def` is one byte longer.

```
def f(n,m,s):a=(n-1%n)**.5;print[m+s*a]+[m-s/a]*~-n

```

# Answer
> 3 votes
# , ~~50~~ 46 bytes

```
function(n,m,s,l=n-1)m+s*c(rep(l^-.5,l),-l^.5)

```

Try it online!

(Reading the other answers now after posting, I realise that this is the same approach as xnor's Python answer)

# Answer
> 2 votes
# Jelly, 20 bytes

```
÷_Ḃ$©$*.;N$ṁ®;0ṁ⁸×⁵+

```

**Try it online!**

Full program taking three command line arguments: **n**, **μ**, **σ**.

### How?

Creates **floor(n / 2)** values equidistant from the mean and a value at the mean if **n** is odd such that the standard deviation is correct...

```
÷_Ḃ$©$*.;N$ṁ®;0ṁ⁸×⁵+ - Main link: n, μ (σ expected as third input, the 5th command argument)
   $                 - last two links as a monad:
 _                   -   n minus:
  Ḃ                  -     n mod 2            i.e. n-1 if n is odd, n if n is even
    ©                - copy value to register
÷                    - n divided by that
       .             - literal 0.5
      *              - exponentiate = (n / (n - (n mod 2))) ^ 0.5
                     -        i.e. 1 if n is even; or (n/(n-1))^0.5 if n is odd
         $           - last two links as a monad:
        N            -   negate
       ;             -   concatenate   i.e. [1,-1] or [(n/(n-1))^0.5,-(n/(n-1))^0.5]
            ®        - recall value from register
           ṁ         - mould the list like something of that length
             ;0      - concatenate a zero
                ⁸    - link's left argument, n
               ṁ     - mould the list like something of length n (removes the zero for even n)
                  ⁵  - fifth command argument, third program argument (σ)
                 ×   - multiply (vectorises)
                   + - add μ (vectorises)

```

# Answer
> 1 votes
# JavaScript (Node.js), 56 bytes

```
(N,m,s)=>[...Array(N)].map(_=>N--?m-s/a:m+s*a,a=--N**.5)

```

Try it online!

Port of Python solution

# JavaScript (Node.js)\], 70 bytes

```
(N,u,s)=>g=(...L)=>1/L[N-1]?L:g(1/L[1]?u:u+u-L[0]||u+s*(N/2)**.5,...L)

```

Try it online!

Without a calculator in question I need to find one somewhere else

---
Tags: code-golf, arithmetic, statistics
---


title: Get the decimal!

text:
# Question
Title: Get the decimal!
## Task:

Your task is, when given three inputs:

* a numerator `n`
* a denominator `d`
* another integer, `x`

Create a program/function that finds the `x`th digit of the number after the decimal place.

## Specs:

* The range of `n` and `d` is between `1` and `2^31 - 1`, inclusive.
* The range of `x` is between `1` and `10,000,000`, inclusive.
    + You may choose to use 1-based indexing or 0-based indexing for `x`. Please state in your answer which one you're using.
* `n` may be larger than `d`.
* `n`, `d` and `x` are guaranteed to be positive integers (for 1-based index version of `x`, if you choose to use 0-based indexing for `x` then `x` can be `0`).
* You may take inputs in any reasonable way (I.e. any way that is not a standard loophole).

## Rules:

* You must return the exact `x`th digit, not when rounded - so the `15`th digit of `1/6`, for example, is not `7`, but `6`.
* Your program must work for all `x` under 10 million, unless your language doesn't support decimals to 10 million places.

## Example I/O:

*The example input uses 0-based indexing, which means `x` will go from `0` to `9,999,999`. As well as that, the "input" is written as a string with spaces separating the numbers.*

```
1 2 3: 0
5 6 0: 8
5 6 1: 3
1 6 15: 6 (not 7, as it's not rounded)
1 11 2: 0
1 10000 9999999: 0
11 7 1: 7

```

# Answer
> 14 votes
# Python 2, 25 bytes

Port of my Haskell answer, since Python also supports bignums by default. As there, `x` is 1-indexed.

```
lambda n,d,x:n*10**x/d%10

```

Try it online! (borrowing Keerthana Prabhakaran's wrapper.)

# Answer
> 6 votes
## Mathematica 33 Bytes

```
RealDigits[#/#2,10,1,-#3][[1,1]]&

```

1-based indexing.

e.g. 10-millionth digit of Pi right of the decimal point:

```
%[Pi,1,10^7]
7

```

takes about 2 seconds on my old machine.

You can try it online at WolframAlpha (click the equal sign)

# Answer
> 6 votes
# Haskell, 26 bytes

Works for all test cases. Yay bignums!

`(n#d)x` takes `Integer`s and returns an `Integer`. `x` is 1-indexed.

```
(n#d)x=n*10^x`div`d`mod`10

```

Try it online!

# Answer
> 5 votes
# PHP\>=7.1, 40 Bytes

```
<?=bcdiv(($a=$argv)[1],$a[2],$a[3])[-1];

```

bcdiv

Online Version

# Answer
> 4 votes
# Jelly, 7 bytes

```
⁵*×:ƓDṪ

```

Try it online!

A function submission (but also works as a full program). Jelly functions can only take two arguments directly; thus I take the digit to return as the left argument, the numerator as the right argument, and the denominator from standard input (in lieu of using a third argument).

People used to Jelly may be aware that a *full program* can take more than two arguments, but doing so causes you to lose access to the tersest way to write the constant integer 10, which is fairly relevant here. As such, this sort of mixed input feels somewhat like an exploit rather than actual useful golfing; I personally disagree with it, but the rule about allowing this is presently at +40 / -12, so as long as it's in the rules, I may as well exploit it (and pretty much have to to be competitive).

A left argument of 1 refers to the digit immediately after the decimal point (the ".1s digit"), an argument of 2 to the .01s digit, and so on.

## Explanation

```
⁵*×:ƓDṪ
⁵*        10 to the power of {the left argument}
  ×       multiplied by {the right argument}
   :      divided by
    Ɠ                standard input
      Ṫ   take the last
     D                  decimal digit

```

Jelly has arbitrary-precision arithmetic on integers, so by pre-multiplying by a power of 10, we're effectively moving the digit we want to the units position, where it's much easier to extract.

# Answer
> 4 votes
# sed `-r`, 93 ~~131~~ ~~136~~ bytes

```
s/$/,/
:d
s/,.+/,/
:
s/(1+)(1*;\1;1*,)1{10}?/\21/
t
s/1*/&&&&&&&&&&/
ta
:a
s/1,/,/
td
s/.+,//

```

Try it online!

(See output in decimal)

Takes input in unary and outputs in unary, and the program is 1-indexed. Thankfully, this challenge has already prepared me for this one.

The concept is similar, both implement long division. Here, I perform long division `x` times, where `x` is the digit after the decimal place that I have to find. After each iteration, I discard the previous decimal places because they are no longer needed.

While doing division, the program is in the format `dividend;divisor;x,result`.

`s/$/,/` adds this comma, the comma is required to separate the result from everything else

Then follows the main program loop

`:d` label d

* `s/,.+/,/` remove everything after the comma
* `:` empty label
* + `s/(1+)(1*;\1;1*,)1{10}?/\21/` perform division, adding 1 to the result each iteration, whilst simultaneously removing blocks of 10 continuous 1s in the result
* `t` branch to the empty label, in other words, loop until the dividend has been exhausted
* `s/1*/&&&&&&&&&&/` multiply the dividend by 10 to prepare for the next iteration
* `ta` branch to label a
* `:a` label a, this line and the line above are required to make `td` work
* `s/1,/,/` subtract 1 from x

`td` conditional branch to d, this is triggered if there has been a successful substitution since the last conditional branch, since `s/1*/&&&&&&&&&&/` is always successful, `td` will always get triggered, but by introducing branch a, we fix that so that it only depends on the previous substitution

`s/.+,//` finally, remove everything but the result

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

```
->n,d,x{(0..x).map{n=n%d*10};n/d}

```

Try it online!

# Answer
> 3 votes
# REXX, 76 bytes

(Not very short but thought it would make a change to do one in REXX) Rexx is 1-based by defintion.

```
arg n d x
numeric digits x+10
y=n/d
parse var y "." +(x) z
say left(z,1,"0")

```

Explanation:

1. Read input to the numbers
2. Guarantee enough significant digits (default is 9)
3. Calculate
4. Split. Find the decimal point, count forward "x" characters, take the following characters and put into "z"
5. Print out first digit. Pad with 0 to be sure.

Merging 3 and 4 actually makes it longer because of the change in syntax:

```
parse value n/d with "." +x z +1

```

For non-REXXers: Strings and numbers are totally interchangeable in REXX. They are determined by how you act on them. So you can parse a number using sting functions with no conversion. For example

```
"27" + "28"

```

returns 55 and not 2728!

# Answer
> 2 votes
## Batch, 70 bytes

```
@set n=%1
@for /l %%x in (0,1,%3)do @set/an=n%%%2*10
@cmd/cset/an/%2

```

# Answer
> 2 votes
# Assembly Intel x86 cpu language, 50 bytes

```
00000940  53                push ebx
00000941  8B5C240C          mov ebx,[esp+0xc]
00000945  8B4C2410          mov ecx,[esp+0x10]
00000949  31C0              xor eax,eax
0000094B  48                dec eax
0000094C  81C102000000      add ecx,0x2
00000952  721A              jc 0x96e
00000954  81FB00000000      cmp ebx,0x0
0000095A  7412              jz 0x96e
0000095C  8B442408          mov eax,[esp+0x8]
00000960  31D2              xor edx,edx
00000962  F7F3              div ebx
00000964  49                dec ecx
00000965  7407              jz 0x96e
00000967  8D0492            lea eax,[edx+edx*4]
0000096A  01C0              add eax,eax
0000096C  EBF2              jmp short 0x960
0000096E  5B                pop ebx
0000096F  C20C00            ret 0xc

```

traslation in nasm

```
; u32 __stdcall rdiv(u32 a, u32  b, u32 c)
; 8a, 12b, 16c
      align   4
rdiv:                   ; c<0xFFFFFFFE and b!=0
      push    ebx       ; something as for(;a=10*(a%b),c--;);return a/b
      mov     ebx,  dword[esp+  12]
      mov     ecx,  dword[esp+  16]
      xor     eax,  eax
      dec     eax
      add     ecx,  2
      jc      .z
      cmp     ebx,  0
      je      .z
      mov     eax,  dword[esp+  8]
.1:   xor     edx,  edx
      div     ebx
      dec     ecx
      jz      .z
      lea     eax,  [edx+edx*4]
      add     eax,  eax
      jmp     short  .1     ; a=5*a;a+=a=>a=10*a
.z:
      pop     ebx
      ret     12

```

For parameter 'c' the range begin from 0; it would be 0..0xfffffffd. If parameters b=0 or c out of range 0..0xfffffffd it would return -1

# Answer
> 1 votes
# Java 7, ~~146~~ ~~139~~ ~~137~~ ~~133~~ ~~128~~ 122 Bytes

-3 bytes thanks to Erik the Outgolfer, I totally forgot imports didn't have to be on their own line

-4 bytes thanks to Qwerp-Derp for moving n%d to the constructor

-6 bytes thanks Kevin Cruijssen for removing the toString()

I hope this is how the byte count is done for java functions with imports

```
import java.math.*;char a(int n,int d,int x){return (new BigDecimal(n%d).divide(new BigDecimal(d),x+1,1)+"").charAt(x+2);}

```

Uses Java's BigDecimal class to get exact representation of the decimal expansion. Note it's not the fastest running code ever but it does eventually produce the correct output for all test cases. Ungolfed code:

```
import java.math.*;
char a(int n, int d, int x){
    BigDecimal num = new BigDecimal(n%d); // reduce improper fractions
    BigDecimal div = new BigDecimal(d);
    BigDecimal dec = num.divide(div, x+1, 1); // precision of x + 1, round down
    return (dec+"").charAt(x+2); //xth char after decimal
}

```

Try it online!

# Answer
> 1 votes
# Lua, 42 bytes

```
function a(n,x,d)
print((n*10^x/d)%10)
end

```

# Answer
> 1 votes
# C, ~~49~~ 43 bytes

```
f(a,b,i){for(;a=10*(a%b),i--;);return a/b;}

```

'i' argument is 0-indexing. Test code and result

```
main()
{int i;
 for(i=0;i<20;++i)
     printf("%u", f(12,11,i));

 printf("\nf(1,2,3)=%d\n",f(1,2,3));
 printf("f(5,6,0)=%d\n",f(5,6,0));
 printf("f(5,6,1)=%d\n",f(5,6,1));
 printf("f(1,6,15)=%d\n",f(1,6,15));
 printf("f(1,11,2)=%d\n",f(1,11,2));
 printf("f(1,10000,9999999)=%d\n",f(1,10000,9999999));
 printf("f(11,7,1)=%d\n",f(11,7,1));
}

f(1,2,3)=0
f(5,6,0)=8
f(5,6,1)=3
f(1,6,15)=6
f(1,11,2)=0
f(1,10000,9999999)=0
f(11,7,1)=7

```

# Answer
> 1 votes
# F# (.NET Core), 30 bytes

```
let f n d x=n*pown 10I x/d%10I

```

Try it online!

(use 1-based indexing)

# Answer
> 1 votes
## Groovy, 30 bytes

```
{n,d,x->(n*10**x/d as int)%10}

```

x uses 1 based indexing.

Explanation:

```
{n,d,x->    // closure with three arguments, n, d, x
 n*10**x    // multiply n with 10 to the power of x
 /d         // divide by d
 as int     // convert from BigDecimal to int
 )%10       // modulo 10 to get the answer
}

```

# Answer
> 1 votes
## Clojure, 39 bytes

```
#(mod(int(/(*(Math/pow 10 %3)%)%2))10))

```

anonymous function with arguments `n,d,x` where `x` uses one based indexing.

# Answer
> 1 votes
# Vyxal, 6 bytes

```
/$›ḞṪt

```

Try it Online!

I do like the Sympy wrappers vyxal now has. Takes denominator, numerator then index.

## Explained

```
/$›ḞṪt
/      # divide the numerator by the denominator. This is fine because vyxal stores floats as Rationals internally.
 $     # place the index at the top of the stack
  ›Ḟ   # Sympy.evalf(fraction, n=index+1). This avoids rounding issues
    Ṫt # get the second last item

```

# Answer
> 1 votes
# Nibbles, 4 bytes (8 nibbles)

```
/\`p/*^~

```

Input is `x`, `n`, `d`. Uses 1-based indexing.

```
     *      # multiply
      ^~    #   10 to the power of
            #     (implicitly) arg1
            # by
            #   (implicitly) arg2
    /       # and divide this by (implicitly) arg3
  `p        # print the number as a string
 \          # reverse it
/           # and get the first element
            # (by folding across it, each time
            # returning the left-hand of each pair)

```

# Answer
> 1 votes
# Pyt, 7 bytes

```
ᴇ*⇹/1ᴇ%

```

Try it online!

input is `x`,`n`,`d`

```
ᴇ         raises 10 to the x
 *        multiplies by n
  ⇹/      divides by d
    1ᴇ%   modulo 10; implicit print

```

# Answer
> 0 votes
# Python 2, 32 bytes

Uses 0-indexing

```
lambda n,d,x:int(10**-~x*n/d)%10

```

Try it online!

Edit:

Rolled back to original solution as seen in Ørjan Johansen's answer that it works, but I won't golf it any further

# Answer
> 0 votes
# Python 2, ~~50,44,40,~~ 36 bytes

```
lambda n,d,x:(`n*1./d%1`+'0'*x)[x+2]

```

Try it online!

# Answer
> 0 votes
## Ruby, 39 bytes

```
->n,m,o{(n*1.0/m).to_s.split(?.)[1][o]}

```

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

```
(n,d,x)=>`${n/d}`.split`.`[1][x]|0

```

x is 0-based

```
f=
(n,d,x)=>`${n/d}`.split`.`[1][x]|0

console.log(f(1,2,3))
console.log(f(5,6,0))
console.log(f(5,6,1))
console.log(f(1,6,15))
console.log(f(1,11,2))
console.log(f(1,10000,10000000))
console.log(f(11,7,1))
console.log(f(2000,7,0))
```

# Answer
> 0 votes
# Groovy, 55 bytes

```
{n,d,x->z='0'*x;Eval.me("$n.$z/$d.$z").toString()[x-1]}

```

Explained using `1,11,2`:

```
{
    n,d,x->          // I've already lost to Jelly by the end of this line.
    z='0'*x;         // Set z equal to 2 0's.
    Eval.me          // Evaluate as groovy code...
    ("$n.$z/$d.$z")  // 1.00g/11.00g (Automatically set precision using # 0s).
   .toString()[x-1]  // Get 2nd digit of division.
}

```

# Answer
> 0 votes
# Axiom, ~~71 61~~ 76 bytes

```
f(a:NNI,b:PI,n:NNI):NNI==(repeat(a:=10*(a rem b);n=0=>break;n:=n-1);a quo b)

```

n is 0-indexing \[0..M\]. Test code and result

```
(19) ->    f(1,2,3)=0
   (19)  0= 0
(20) ->     f(5,6,0)=8
   (20)  8= 8
(21) ->     f(5,6,1)=3
   (21)  3= 3
(22) ->     f(1,6,15)=6
   (22)  6= 6
(23) ->     f(1,11,2)=0
   (23)  0= 0
(24) ->     f(1,10000,9999999)=0
   (24)  0= 0
(25) ->     f(11,7,1)=7
   (25)  7= 7

```

# Answer
> 0 votes
# JavaScript (Node.js), 23 bytes

```
(a,b,i)=>a*10n**i/b%10n

```

Try it online!

---

# JavaScript (Node.js), 43 bytes, port

```
(a,b,i)=>eval(`for(;a=10*(a%b),i--;)a/b|0`)

```

Try it online!

# JavaScript (Node.js), 51 bytes

```
(n,d,x)=>[...Array(x)].map(_=>[n*=10,u=n/d,n%=d])|u

```

Try it online!

use Array rather than recursive to avoid stackoverflow

# Answer
> 0 votes
# Husk, 9 bytes

```
→d÷⁰*²!İ⁰

```

Try it online!

# Answer
> 0 votes
# Thunno, \\$ 9 \log\_{256}(96) \approx \\$ 7.41 bytes

```
10@*s10%,

```

Attempt This Online! Takes `x` then `n` then `d`.

Port of Ørjan Johansen's Python answer

**Explanation:**

```
10@*s10%,  # Implicit input, x then n then d
10@        # 10**x
   *       # *n
    s      # Swap so d is on top
     10%   # d%10
        ,  # Integer divide
           # Implicit output

```

---
Tags: code-golf, math
---


title: Is this a Jordan matrix?

text:
# Question
Title: Is this a Jordan matrix?
## Background

A **Jordan matrix** is a block-diagonal matrix where each block on the diagonal has the structure of

$$ \begin{bmatrix} \lambda & 1 & 0 & \cdots & 0 \\ 0 & \lambda & 1 & \cdots & 0 \\ \vdots & \vdots & \vdots & \ddots & \vdots \\ 0 & 0 & 0 & \lambda & 1 \\ 0 & 0 & 0 & 0 & \lambda \end{bmatrix} $$

where all values of \\$\lambda\\$ are identical inside each block. (A block diagonal matrix is one that can be divided into blocks, so that the blocks on the main diagonal are square and those out of the main diagonal are all zeros. See examples below.)

The following are some examples of a Jordan matrix:

$$ J\_1=\left\[\begin{array}{c|c|cc} 2 & 0 & 0 & 0 \\ \hline 0 & 0 & 0 & 0 \\ \hline 0 & 0 & 2 & 1 \\ 0 & 0 & 0 & 2 \end{array}\right\]\\ J\_2=\left\[\begin{array}{ccc|cc|cc|ccc} 0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ \hline 0 & 0 & 0 & 3 & 1 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 3 & 0 & 0 & 0 & 0 & 0 \\ \hline 0 & 0 & 0 & 0 & 0 & 3 & 1 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 3 & 0 & 0 & 0 \\ \hline 0 & 0 & 0 & 0 & 0 & 0 & 0 & 7 & 1 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 7 & 1 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 7 \end{array}\right\] $$

The following are more examples of Jordan matrices:

```
[[0]]  // 1x1 matrix is always Jordan

[[0, 0],
 [0, 0]]  // all-zero matrix is also always Jordan

[[3, 0, 0],
 [0, 2, 0],
 [0, 0, 2]]  // diagonal matrix is also Jordan, even if it has duplicates

[[3, 0, 0],
 [0, 2, 1],  // the one between the two 2s is optional
 [0, 0, 2]]  // (if it is a zero, the two are in separate blocks)

[[99,  1,  0,  0],
 [ 0, 99,  1,  0],
 [ 0,  0, 99,  0],
 [ 0,  0,  0,  1]]  // the matrix may contain numbers >= 10

[[1, 0, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 3, 1, 0],  // same diagonal entries may appear separately
 [0, 0, 0, 3, 0],
 [0, 0, 0, 0, 1]]

```

The following are not Jordan:

```
[[0, 0, 0],
 [0, 0, 0],
 [1, 0, 0]]  // has a one where it should be zero

[[2, 0, 0],
 [1, 2, 0],
 [0, 0, 1]]  // 1 is at the wrong side of the diagonal

[[1, 1, 0],
 [0, 2, 0],  // the numbers on the left of and below the
 [0, 0, 2]]  // non-diagonal 1 are not equal

[[99, 99,  0,  0],
 [ 0, 99, 99,  0],
 [ 0,  0, 99,  0],
 [ 0,  0,  0,  1]]  // the matrix may contain numbers >= 10

[[1, 0, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 3, 2, 0],  // all numbers right above the main diagonal
 [0, 0, 0, 3, 0],  // should be either 0 or 1
 [0, 0, 0, 0, 1]]

```

## Challenge

Given a square matrix filled with non-negative integers, determine if it is a Jordan matrix.

Input format is flexible. For output, you can choose to

1. output truthy/falsy using your language's convention (swapping is allowed), or
2. use two distinct, fixed values to represent true (affirmative) or false (negative) respectively.

Standard rules apply. The shortest code in bytes wins.

# Answer
# JavaScript, 58 bytes

```
a=>a.some((r,y)=>r.some((c,x)=>(r/(r=c)==a[x][x])/-y--<c))

```

Try it online!

* When `c==0`
    + `r/(r=c)` is `NaN` or `Infinity`;
    + `(r/(r=c)==a[x][x])` is `false`
    + `(r/(r=c)==a[x][x])/-y--` is `0` or `NaN`
    + `(r/(r=c)==a[x][x])/-y--<c` is false
* When `y==0` (cells on main diagonal) and `c>=1`
    + `(r/(r=c)==a[x][x])/-y--` is `NaN` or `Infinity`
    + `(r/(r=c)==a[x][x])/-y--<c` is false
* When `y==-1` (cells on right side of main diagonal) and `c==1`
    + `r/(r=c)` equals to `r` equals to left cell,
    + `(r/(r=c)==a[x][x])` test if left cell equals to bottom cell
    + `(r/(r=c)==a[x][x])/-y--` is `1` or `0` based on whether left cell equals to bottom cell
    + `(r/(r=c)==a[x][x])/-y--<c` is `true` if left cell not equals to right cell
* When `y==-1` (cells on right side of main diagonal) and `c>=2`
    + `(r/(r=c)==a[x][x])/-y--` is `1` or `0`
    + `(r/(r=c)==a[x][x])/-y--<c` is `true`
* When (`y<-1` or `y>0`) and `c>=1`
    + `(r/(r=c)==a[x][x])/-y--` is a number in range \[-Inf, 1)
    + `(r/(r=c)==a[x][x])/-y--<c` is `true`
> 10 votes

# Answer
# Jelly, ~~14~~ 13 bytes

```
ŒDµḢ=Ɲo@ƑḢ>FẠ

```

Try it online!

*-1 because I actually thought to check if the input can contain negative integers*

```
ŒDµ              Consider the diagonals of the input matrix.
   Ḣ             Pop the main diagonal;
     Ɲ           for each pair of its adjacent elements
    =            are they equal?
                 (Especially note that this results in a list of ones and zeroes,
                 of the same length as the superdiagonal.)
         Ḣ       Pop the superdiagonal;
      o@         are the logical ORs of its elements and the neighbor equalities
        Ƒ        equal to the neighbor equalities?
           F     For every element in the flattened remaining diagonals,
          > Ạ    is the test result strictly greater?

```

Jelly's logical OR is Python's: if the first argument is truthy it is returned, else the second argument is returned. Testing the diagonal equalities' invariance under flipped logical OR with the superdiagonal determines if every element of the superdiagonal is either a 0 anywhere or a 1 "between" two equal elements on the diagonal, since a 0 on the superdiagonal leaves either equality value unchanged, but any non-zero overrides the equality value--passing only if both are 1.
> 7 votes

# Answer
# Rattle, 111 bytes

```
|sI^>s[[PgI#1I#s2=#-#1[^0[^1g2[^0=q]][1g2[^0[^1=q]P=#4<s<=#3-sg0>I~<I~s_3P=#4+<s<=#3sg0>I~<I~<[^~=q]]]]g1]`]`=1

```

Try it Online!

Needless to say, Rattle is not built to handle matrices and this approach is pretty brute-force. However, this code really shows off most of Rattle's features!

# Explanation

```
|                      takes input and parses automatically (Rattle's parser is very
                        powerful and automatically recognises nested lists)
 s                     saves the list to the first memory slot (slot 0)
  I^                   gets the length of the list
    >                  move pointer right
     s                 save length of list to slot 1
      [[ ... ]`]`      nested loop to iterate over array

(inside nested loop)
I won't explain every single command here but the code inside the nested loop is split
 into two parts.
First, the code checks to make sure all values that are not on the diagonal or off
 the diagonal to the right are all zero and all values off the diagonal to the right
 are 1 or 0. If not, it prints a falsy value (0).
Next, it iterates over all values of 1 which appear in the off-diagonal. For each
 value of 1 in this off-diagonal, it ensures the value to the left and below the 1
 are equal. If not, it prints a falsy value (0).
Knowing these conditions have been checked for, a truthy value (1) is printed if a
 falsy value has not already been printed.

```
> 5 votes

# Answer
# Python 3, 69 bytes

```
lambda m,n:re.sub(f"(.)({10**~-n}\\1)*(0%r|$)"%{n},"",m)>""
import re

```

Try it online!

input is a flatened string of the matrix and its size

output `False` for Jordan and `True` for not jordan

#### Edit:

as it wasn't specified when I post this answer, my solution only works for matrix with single digits elements

## How it works:

* the main idea i to substitute every "jordan" sub patern by the empty string and check if the result is the empty string (every subpart of the matrix was jordan)
* `(.)({10**~-n}\\1)*(0%r|$)"%{n}` with for example `n=4` will give the patern `/(.)(1000\1)*(0{4}|$)/`
> 4 votes

# Answer
# , ~~96~~ ~~93~~ ~~83~~ ~~75~~ 67 bytes

```
function(m,k,j=1:k^2%%(k+1),x=m[!j])any(m[j>1],diff(diag(m))&x,x>1)

```

Try it online!

Takes input as matrix and it's size.

Outputs inverted `TRUE/FALSE` values.
> 4 votes

# Answer
# Wolfram Mathematica, ~~150~~ ~~144~~ ~~137~~ 69 bytes

```
With[{m=#,l=Length@#,d=Diagonal},Union@@Join[m~d~#&/@2~Range~l~Join~-Range@l,{If[#2==1,#1,#2]}&~MapThread~{Differences@d@m,m~d~1}]=={0}]&

```

I know... I don't like it either! But this was the shortest code that I could think of, and I'm definitely not an expert. Please take it with a huge grain of salt and enlighten me with your valuable suggestions. Try it online!

**Edit later-** Michael E2 proposed this elegant, much shorter solution: Try it online

```
IdentityMatrix@Length@#==ReverseSort@Abs@First@JordanDecomposition@#&

```

Explanation for the initial code:

```
(* The Diagonal method extracts diagonal vectors from input matrix *)
With[{m=#, l=Length@#, d=Diagonal},
Union@@(
(* Except for the main diagonal and the one above it,
   all other diagonals must be zero: *)
d[m,#]& /@ Complement[Range[-l,l],{0,1}]
(* These diagonals are combined by Union method above *)
)=={0}
&&
(* The Difference of elements of the main diagonal is calculated.
   If an element in the secondary diagonal is 1,
   its corresponding element in the difference diagonal must be zero *)
And@@
MapThread[If[#1==1,#2==0,#1==0]&, {d[#,1], Differences@ d[#]}]]&

```
> 2 votes

# Answer
# Desmos, 90 bytes

```
I=wy+x-w
f(L,w)=\prod_{x=1}^w\prod_{y=1}^w\{L[I]=0,x=y,x=y+1:\{L[I]=1\}\{L[I-1]=L[I+w]\}\}

```

Takes input as the flattened matrix and its width. Returns 1 for truthy and NaN for falsy.

Try it on Desmos!

### Explanation

```
f(L,w)=
  \prod_{x=1}^w\prod_{y=1}^w   # iterate over all x,y in matrix
  \{ # piecewise (case statement)
    L[I]=0, # any 0 is OK; multiply by 1
    x=y,    # any values on main diagonal are OK; multiply by 1
    x=y+1:  # immediately above the main diagonal
      \{L[I]=1\}           # must have value 1 (0s matched L[I]=0) and
      \{L[I-1]=L[I+w]\}    # left and bottom are same
    # fall through: multiply by NaN
  \}

```
> 2 votes

# Answer
# Charcoal, 27 bytes

```
⬤θ⬤ι∨¬λ∨⁼κμ∧⁼⊕κμ⁼λ⁼§ικ§§θμμ

```

Try it online! Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` for Jordon, nothing if not. Explanation:

```
 θ                          Input array
⬤                           Each row satisfies
   ι                        Current row
  ⬤                         Each cell satifies
      λ                     Current cell
     ¬                      Logical Not i.e. is zero
    ∨                       Logical Or
         κ                  Current row index
        ⁼                   Equal to
          μ                 Current column index
       ∨                    Logical Or
              κ             Current row index
             ⊕              Incremented
            ⁼               Equal to
               μ            Current column index
           ∧                Logical And
                 λ          Current value
                ⁼           Equals
                   §ικ      Value to left
                  ⁼         Equals
                      §§θμμ Value below

```

Since the `Equals` operator returns `1` or `0`, the penultimate equality only holds for `1`s where the two adjacent values on the main diagonal are equal or `0`s where the values are unequal, but if the value was `0` we skipped it earlier anyway.
> 1 votes

# Answer
# PARI/GP, 57 bytes

```
m->matrix(#m,,i,j,[1+k=i-j,1-a=m[i,j],m[i,i]-m[j,j]]*a*k)
```

Attempt This Online!

Outputs a zero matrix when the input is a Jordan matrix. In PARI/GP's convention, a matrix is truthy if and only if it contains at least one truthy entry.
> 1 votes

# Answer
# Python 3, 92 bytes

```
def f(m,w,h):
 for i in range(h-1):i*=w;m[i:i+2]=(m[i]==m[i-~w])<m[i+1],
 return any(m[:-1])

```

Attempt This Online!

This is longer than the earlier Python solution, but it supports numbers larger than 9, as required by the challenge. It takes the matrix as a flat list/array of integers in row-major order, and returns False if it's Jordan, True if not.

The loop tests that each triple of diagonal and superdiagonal entries follows the rules, and the diagonals are overwritten with the results. Then `any` checks both that those tests passed and that the rest of the matrix is zero.

This is the first time in my life that I've wanted comparison operators to be left-associative. I almost rewrote the answer in C just for that reason, but I looked it up, and it turns out `<` and `==` have different precedence in C, and `<`'s precedence is higher, which is the opposite of what I need. So much for that.
> 1 votes

# Answer
# Haskell, 91 bytes

```
import Data.Array
j m=and[c==r+1&&v==1&&m!(r,c-1)==m!(r+1,c)|((r,c),v)<-assocs m,v/=0,c/=r]

```

Try it online!
> 0 votes

---
Tags: code-golf, math, decision-problem, matrix, linear-algebra
---


title: NxM List Combination Closest to Target

text:
# Question
Title: NxM List Combination Closest to Target
Given a list of N lists, each containing M positive integers, and a separate list of M positive integers (target values), return a list of N scalars (integers with a value of 0 or more) that correspond to each list in the lists of lists, such that when each value in a list is multiplied by it's scalar, and the values at each index of each list are added together to make one final summed list, the sum of the absolute difference between each value in the summed list and the target list is minimized. If there are multiple possible outputs of equal absolute difference for a given input, output any single answer.

The solution with the fastest algorithm (by running time complexity) wins.

**Examples:**

```
Input:
    Lists:  [[1,2], [2,1]]
    Target: [9,9]

Output:
    [3, 3]

---------- ---------- ----------

Input:
    Lists:  [[3,9,2,1], [7,1,2,3], [2,3,8,1]]
    Target: [60, 70, 50, 60]

Output:
    [6, 5, 4]

---------- ---------- ----------

Input:
    Lists:  [[9, 7, 8], [9, 4, 12]]
    Target: [176, 68, 143]

Output:
    [6, 8]

```

**Example of Answer Corectness Checking:**

```
Input:
        Lists:  [[9, 7, 8], [9, 4, 12]]
        Target: [176, 68, 143]

Output:
    [6, 8]

6 * [9, 7, 8]  = [54, 42, 48]
8 * [9, 4, 12] = [72, 32, 96]

[54, 42, 48] + [72, 42, 96] = [126, 84, 144]

summed difference:
    abs(176 - 126) + abs(68 - 84) + abs(143 - 144)
    = 50 + 16 + 1
    = 67
    (minimize this number)

```

# Answer
> 1 votes
# Python 3, Brute Force Solution

```
from itertools import product
import numpy as np

def abs_difference(totals, target):
    distance = sum(abs(totals - target))
    return distance

def best_combo(array, target):

    # setup, using numpy arrays for optimization
    array = np.array(array)
    target = np.array(target)
    low_difference = sum(target)
    low_combo = None
    n = len(array)

    # figure a limiting scalar for each list
    # aka, the scalar just before a scaled list gets further from the target
    individual_limits = []
    for row in array:
        row_low_difference = sum(target)
        i = 0
        while True:
            i += 1
            totals = i * row
            if abs_difference(totals, target) > row_low_difference:
                break
        individual_limits.append(i)

    # create a range for each limiting scalars
    # and create a generator function for all combinations of the value in these ranges
    # aka combinations of scalars to be multiplied by each row
    ranges = (range(i) for i in individual_limits)
    combos = product(*ranges)

    # iterate over these combos
    # figure out which combination of the rows gets closest to the target
    for combo in combos:
        totals = sum(array * np.array(combo).reshape(n, 1))
        difference = abs_difference(totals, target)
        if difference < low_difference:
            low_combo = combo
            low_difference = difference

    return low_combo

assert best_combo([[1, 2], [2, 1]], [9, 9]) == (3, 3)
assert best_combo([[3, 9, 2, 1], [7, 1, 2, 3], [2, 3, 8, 1]], [60, 70, 50, 60]) == (6, 5, 4)
assert best_combo([[9, 7, 8], [9, 4, 12]], [176, 68, 143]) == (6, 8)

```

# Answer
> 1 votes
# Haskell, O(product target)

```
import Data.List
import Data.Ord

instance Num a=>Num[a]where
 (+)=zipWith(+)
 (-)=zipWith(-)
 (*)=zipWith(*)
 fromInteger=repeat.fromInteger
 abs=map abs
 signum=map signum

closest target vectors=
 minimumBy(comparing$sum.abs.(target-).sum.(vectors*).map fromInteger)$
 sequence$map(enumFromTo 0.succ.maximum.zipWith div target)vectors

```

Try it online!

---
Tags: matrix, fastest-algorithm, linear-algebra, algorithm
---