title: Will I tip over?

text:
# Question
Title: Will I tip over?
## Overview

Given a 3 line string, figure out if the structure falls to the left, balances, or falls to the right.

## Input structure

You can imagine the structure as metal rod with stuff on top, all being balanced on top of a vertical rod.

```
1  7 4        a
===============
        |

```

The first line is the items. Each item's weight is calculated as the ascii value of the character minus 32. (Characters under 32 aren't considered and spaces weigh 0). Keep in mind that an item's force on the rod is its weight times the distance to the pivot point.

The second line is the rod. Each length of rod weighs 1 unit by itself. This line is exclusively equals signs (`=`).

The third line is the pivot point. This can be placed anywhere, and is represented by a number of spaces followed by a single pipe (`|`) character.

# Examples

Input:

```

=====
  |

```

Output: Balance

Input:

```

=====
   |

```

Output: Falls left

Input:

```
    %
=====
   |

```

Output: Balance (Because `%` weighs enough to counteract the weight of the left side of the rod)

Input:

```
 a    a
=======
   |

```

Output: Falls right (because the `a` on the right is further away from the pivot point)

Input:

```
1  7 4        A
===============
        |

```

Output: Falls left

Input:

```
1  7 4        a
===============
        |

```

Output: Falls right (lower case letters are heavy!)

Input:

```
            $ ~
===============
             |

```

Output: Balance

# Notes

* Trailing whitespace is permitted, leading whitespace is not.
* Your program may output in whatever format you like, as long as there are 3 distinct outputs for left, balance, and right.
* Your program must accept the format shown as input.
* This is so the shortest code in bytes wins

# Answer
> 9 votes
# JavaScript (ES6), ~~116~~ ~~111~~ ~~108~~ 106 bytes

*-5 bytes by summing via `eval(array.join`+`)` instead of `array.reduce()`.*
*-3 bytes by defaulting to `1` instead of `32 - 31`, allowing parentheses to be removed.*
*-2 bytes since pivot point is the length of the last line - 1*

```
(s,[t,r,b]=s.split`
`)=>Math.sign(eval([...r].map((_,i)=>(t.charCodeAt(i)-31||1)*(i-b.length+1)).join`+`))

```

Outputs `-1`, `0`, or `1`, for left, balanced, or right, respectively. Ended up similar to Chas Brown's python answer, so credit goes there.

Can save 4 bytes if the first line is padded to match the length of the rod by using
`(31-t.charCodeAt(i))*(b.length+~i)`.

## Test Snippet

Includes additional output (`Left`/`Balanced`/`Right`) along with the number.

```
f=
(s,[t,r,b]=s.split`
`)=>Math.sign(eval([...r].map((_,i)=>(t.charCodeAt(i)-31||1)*(i-b.length+1)).join`+`))
```

```
<textarea id=I rows=3 cols=20></textarea><br><button onclick="O.value=I.value?`${x=f(I.value)} (${['Left','Balanced','Right'][x+1]})`:''">Run</button> <input id=O disabled>
```

### Another 106 byte method

```
(s,[t,r,b]=s.split`
`)=>Math.sign(eval(r.replace(/./g,(_,i)=>"+"+(t.charCodeAt(i)-31||1)*(i-b.length+1))))

```

Instead of `join`ing an array on `+`s, we create a string of numbers, each prefixed by `+`. The leading `+` gets ignored.

# Answer
> 5 votes
# Python 2, ~~112~~ 110 bytes

```
def f(s):w,b,p=s.split('\n');return cmp(sum((ord((w+' '*-~i)[i])-31)*(i-p.find('|'))for i in range(len(b))),0)

```

Try it online!

EDIT: Finally managed to eliminate the `enumerate` and `rjust` for a measly 2 bytes... meh!

Takes in a string; outputs -1,0, or 1 for falls left, balances, falls right, respectively.

First pass at 112 bytes was:

```
def f(s):w,b,p=s.split('\n');return cmp(sum((ord(c)-31)*(i-p.find('|'))for i,c in enumerate(w.rjust(len(b))),0)

```

# Answer
> 4 votes
# Jelly, 24 bytes

```
ṪO_31
ỴµṪLạÐ€ṪL$×Çṣ0S€IṠ

```

Try it online!

`-1` for falling left, `0` for balancing, `1` for falling right (full program).
`[-1]` for falling left, `[0]` for balancing, `[1]` for falling right (function).

First line must have trailing spaces, last line must not.

Explanation (we start with bottom line):

First of all, we're working with individual lines, so we need to somehow get them. That's a job for . Then, we need to treat the `\n`-split version of the input as if it was the original input, so we use `µ` to make a monadic chain applied to the current value.

Now we begin real work, and our first job would be computing the factors of the weights. Essentially this is a range \[distance from far left to pivot..0..distance from pivot to far right\]. First of all, we have to find the 1-based index of the pivot, which is essentially the length of the last line without trailing spaces. So we pop the last line (pivot line) from our original list with , since we won't need it anymore, and then we take its length with `L`. We then need to take the length of the rod, for which we do the same thing to the now-last line (rod line) with `ṪL$`. Finally, to get the range, we map **|*x* \- *y*|** to \[1..rod length\], where ***x*** is the pivot index and ***y*** is each element of the list we map upon. We do this using `ạÐ€`, where  calculates **|*x* \- *y*|** and `Ð€` makes a range from 1 up to and including the rod length. Now we'll have the range we want.

After that, we have to multiply each integer, representing a piece of the rod, with its corresponding weight. To calculate the weights, we use `Ç`, going to the top line of our code. We take the remaining line with , its charcodes with `O`, and then we calculate ***x* \- 31** using `_31`, ***x*** being each charcode. We then assign space to weight 1 (0 + rod piece = 1), `!` to weight 2 (1 + 1) etc. We're done with the top line, so now `Ç` would return the list of weights, which we multiply with the corresponding integers representing the rod pieces with `×`.

After that, we split with `ṣ0` on the pivot point, represented by a 0 (since any weight there won't affect the result), resulting in a list of the form \[\[1st weight, 2nd weight...weight just before pivot\], \[weight just after pivot, weight after the one before...last weight\]\]. Those lists represent the sides of the rod, left and right. We now sum each of the lists using `S€` to get the total weights on each side, and use `I` to take the delta, which will be negative if left side is heavier, zero if they're equal-weighted, and positive if right side is heavier. So, to return the final result using this properly to our advantage, we take the sign with .

# Answer
> 4 votes
## Haskell, ~~212~~ 171 bytes (188 if take input as one string)

```
o!p=map(fst)(zip[p-0,p-1..]o)
x#p=sum(zipWith(\c w->(max(fromEnum c-32)0)*w)x(x!p))+sum(x!p)
x?c=length(takeWhile(==c)x)

```

**171 bytes variant**

```
r a b c=signum(take(b?'=')(a++repeat ' ')#(c?' '))

```

**188 bytes variant**

```
x%y=lines x!!y
r i=signum(take(i%1?'=')(i%0++repeat ' ')#(i%2?' '))

```

Explanation

```
o!p=map(fst)(zip[p-0,p-1..]o)        Creates weights coefs list.
                                     o - list, p - pivot position
                                     for list "abcdf" and p=3 (pivot under 'd')
                                     outputs [3,2,1,0,-1]

x#p                                  Calculates total balance
                                     x-list of "objects" on lever, p-pivot place
  sum(zipWith                        sum of zipped lists
   (\c w->(max(fromEnum c-32)0)*w)   weight of ascii "object" times
                                     distance from pivot
    x(x!p))                          x-ascii objects,
                                     (x!p)-distances list(weight coefs)
  +sum(x!p)                          balance of lever ("==") itself

x?c=length(takeWhile(==c)x)          length of list before non c element met
                                     used to find '|' position
                                     and length of "===" lever
                                     before right whitespaces met

r a b c=                             Sums it all up =)
                                     a-ascii objects, b-lever, c-pivot line
   signum(                           1-tips left, 0-balance, -1-tips right
     take(b?'=')(a++repeat ' ')      takes all object on lever
                                     plus whitespaces up to length of the lever
      #                              calculate the balance
       (c?' ')                       determine place of pivot

```

# Answer
> 4 votes
# Python 2, 90 bytes

```
def f(s):L=len(s)/3;print cmp(sum((ord(s[i])-31)*(i-s[-L:].find('|'))for i in range(L)),0)

```

Expects input lines to be padded (with spaces) to the correct length. Outputs `-1` for *falls left*, `0` for *balanced*, and `1` for *falls right*.

**Try it online!**

---

## 94 bytes

For +4 bytes we can have a version which, using a `while` loop, requires *stripped* lines rather than *padded* lines:

```
def f(s):
 i=r=0
 while''<s[i]:r+=(ord(s[i])-31)*(i-s[-3::-1].find('='));i+=1
 print cmp(r,0)

```

**Try it online!**

# Answer
> 2 votes
# Jelly, 30 bytes

```
O_31×J_¥A+\sṪ€µ÷ḢṪ_2Ṡ
ỴṪLç@ỴḢ$

```

Test Suite

Outputs 0 for balanced, 1 for right, and -1 for left.

**How it Works**

```
O_31×J_¥A+\sṪ€µ÷ḢṪ_2Ṡ - helper function. Arguments position of pivot and first line
O                        - char codes of first line
 _31                     - subtract 31 to get weight
    ×                    - elementwise product with:
     J_¥                 - distances from the pivot
        A                - absolute value
         +\              - cumulative sum
           s             - split to get [[...,left weight],...,[..., right + left weight]]
            Ṫ€           - last element of each sublist: [left weight, ... right weight]
              µ÷Ḣ        - get ratio of each element over left weight: ratio n indicates
                              right + left = n × left ===> right = left if n = 2
                 _2      - subtract 2: positive is right>left and negative is right<left
                   Ṡ     - return the sign of this

ỴṪLç@ỴḢ$              - main link. Argument: 3 line string.
   ç@                  - apply helper function with arguments:
Ỵ                        - split by linefeeds
 Ṫ                       - last line
  L                      - length (returns position of pivot)
       $               - and
     Ỵ                   - split by linefeeds
      Ḣ                  - first line

```

# Answer
> 2 votes
## Ruby, 543 bytes

```
def willittip(s)
leftw=0;
rightw=0;
arr=[];
fields=s.split("\n")
pos=fields[2].index("|")
fields[0].split("").each do |i|
arr << i.ord-32
end
arr[pos+1..-1].each_with_index do |x,y|
rightw=rightw+1
if x>0
if pos>0
rightw=rightw+x*(pos-y).abs
else
rightw=rightw+x
end
end
end
arr[0..pos-1].each_with_index do |x,y|
leftw=leftw+1
if x>0
if pos>0
leftw=leftw+x*(pos-y).abs
else
leftw=leftw+x
end
end
end
if leftw==rightw
return "Equal"
elsif leftw<rightw
return "Right"
elsif leftw>rightw
return "Left"
end
end

```

# Answer
> 2 votes
# APL (Dyalog), 43 bytes\*

```
{×(¯31+⎕UCS⊃⍵)+.×(⍳≢⊃⍵)-'|'⍳⍨⊃⌽⍵}⎕TC[2]∘≠⊆⊢

```

Try it online!

`⊆⊢` partition the argument into runs of characters that are

`⎕TC[2]∘≠` different from the **2**nd **T**erminal **C**ontrol character (Linefeed)\**

`{``}` apply the following anonymous function on the list of strings:

`⊃⌽⍵` in the first string of the reversed list (i.e. the last)

`'|'⍳⍨` find the **ɩ**ndex of the pivot point

`(``)-` subtract that from the following list:

`⊃⍵` the first string

its length

all the **ɩ**ndices of that

`(``)+.×` weighted sum with those weights and the following values:

`⊃⍵` the first string

`⎕UCS` code points in the **U**niversal **C**haracter **S**et

`¯31+` add negative thirty-one (32 for the required offset minus one for the rod)

`×` signum of that

---

* For 1 byte per char, use `{×(¯31+⎕UCS↑⍵)+.×(⍳≢↑⍵)-'|'⍳⍨↑⌽⍵}⎕TC[3]∘≠⊂⊢` with `⎕ML←3`. Try it online!
\** `⎕TC` is deprecated and used here only for golfing purposes. In production code, one should use `⎕UCS 10`.

# Answer
> 2 votes
# Haskell (Lambdabot), 142 bytes

```
l=length
g[a,c,b]=splitAt(l b)$a++(' '<$[1..l c-l a])
k e=sum$zipWith((*).(-31+).ord)e[1..]
f=signum.uncurry(-).(k.drop 1.reverse***k).g.lines

```

Try it online!

### Ungolfed version:

```
-- for readability, allows reading top-down/left-right
(.>) = flip (.)

ungolfed =
     lines                                 -- separate out lines into..
  .> (\[a,b,c] ->                          -- a,b,c (first,second,third)
                                           -- ' ' pad the first line & split on pivot
       splitAt (length c) (a ++ replicate (length b - length a) ' ')
     )
  .> (weight.drop 1.reverse *** weight)    -- reverse left half, drop element above pivot & get weight for both
  .> uncurry (-)                           -- subtract right from left
  .> signum                                -- get sign

-- get ord of the character subtract 31 ('=' char from bar),
-- then multiply with scales ([1..]) and sum it all up
weight es = sum $ zipWith (ord .> subtract 31 .> (*)) es [1..]

```

# Answer
> 1 votes
# Python 3, 217 bytes

### Also works in Python 2.7

```
def f(s):i,b,p=s.split('\n');c=p.find('|');l=sum((ord(e)-32)*(c-i.find(e))for e in i[:c])+sum(x for x in range(1,c+1));r=sum((ord(e)-32)*i[c:].find(e)for e in i[c:])+sum(x for x in range(len(b[c:])));return(l>r)-(r>l)

```

***Returns 1 for left-side, -1 for right-side, or zero if balanced.***

## Readable version:

```
def f(s):
    i,b,p = s.split('\n')
    c = p.find('|')

    l = sum((ord(e)-32)*(c-i.find(e))for e in i[:c])+sum(x for x in range(1, c+1))
    r = sum((ord(e)-32)*i[c:].find(e)for e in i[c:])+sum(x for x in range(len(b[c:])))

    return(l>r)-(r>l)

```

# Answer
> 1 votes
# Charcoal, 31 bytes

```
Ａ⁰ξＦＬθＡ⁺ξ×⁻ι⌕ζ|⁻℅§θι³¹ξＩ⁻›ξ⁰‹ξ⁰

```

Try it online! Link is to verbose version of code. Outputs 0 for balance or -1 or 1 for falling left or right. Edit: Changes in Charcoal now mean that `≔ΣＥθ×⁻κ⌕ζ|⁻℅ι³¹ξＩ⁻›ξ⁰‹ξ⁰` works for 24 bytes: Try it online! Link is to verbose version of code. Note: Both answers require padded input, but can be adapted to accept unpadded input at a cost of 3 bytes: `≔⁰ξＦＬη≔⁺ξ×⁻ι⌕ζ|⁻℅§◨θＬηι³¹ξＩ⁻›ξ⁰‹ξ⁰` Try it online! `≔ΣＥ◨θＬη×⁻κ⌕ζ|⁻℅ι³¹ξＩ⁻›ξ⁰‹ξ⁰` Try it online! Links are to verbose version of code.

# Answer
> 1 votes
# C# (.NET Core), ~~127~~ ~~95~~ 90 + 18 = 108 bytes

For this function the first line must be right padded with spaces to be the same length as the rod and the third line must not have trialing spaces. This conditions are allowed (see comments of the question).

```
s=>s.Split('\n')[0].Select((c,i)=>(c-31)*(i-s.Split('\n')[2].Length+1)).Sum().CompareTo(0)

```

Try it online!

Outputs:

-1 for tip left
0 for balance
1 for tip right

# Answer
> 1 votes
# C (gcc), 106 ~~107~~ ~~121~~ ~~123~~ ~~124~~ ~~129~~ ~~131~~ bytes

```
c,b,l,i;f(char*a){l=strlen(a)/3;for(i=b=c=0;32/a[l*2+c];++c);for(;i<l-1;b+=(a[i]-31)*(i++-c));a=b>0?2:!b;}

```

Return 0 for falling left, 1 for balance and 2 for falling right.

Require all three lines to have same length and finish with `\n` to determine the length of string.

Try it online!

# Answer
> 1 votes
# Mathematica, 91 ~~92~~ bytes

```
Sign[(v=(g=ToCharacterCode)@#&@@(d=#~StringSplit~"
")-31).(Range@(l=Length)@v-l@g@Last@d)]&

```

The first line should have the same length with the rod. The third line should contain no trailing spaces.

Return -1, 0, 1 for falling left, balance and falling right.

# Answer
> 1 votes
# PHP, 105 bytes

```
for([$a,$b,$c]=explode("
",$argn);$b[$i];)$w+=(strpos($c,"|")-$i++)*8*(max(1,ord($a[$i])-31));echo$w<=>0;

```

prints `-1`/`0`/`1` for left/balance/right. Run as pipe with `-nR` or try it online.

**breakdown**

```
for([$a,$b,$c]=explode("\n",$argn); # import input
    $b[$i];)                        # loop through bar
    $f+=                                # add to force:
        ($i-strpos($c,"|"))             # distance (<0 if left, >0 if right of pivot)
        *8                              # *8
        *(max(1,ord($a[$i++])-31));     # *weight
echo$f<=>0;                         # print -1 if $f<0, 1 if $f>0, 0 if $f==0

```

# Answer
> 0 votes
# Jelly, 18 bytes

```
ỴµḢO_31×Ẉạ€/$ṣ0§IṠ

```

Try it online!

This started as a golf of Erik's answer (so be sure to go upvote it), but it developed to be different enough, and Erik is no longer active on the site, that I thought posting a separate answer would be fine.

Outputs `[0]` for balanced, `[1]` for tipping right and `[-1]` for tipping left

## How it works

```
ỴµḢO_31×Ẉạ€/$ṣ0§IṠ - Main link. Takes a string S on the left
Ỵ                  - Split S into a list of lines [I, R, P]
 µ                 - Use this list as the arguments
  Ḣ                - Pop and yield I
   O               - Convert to ordinals
    _31            - Subtract 31, mapping space to 1, ! to 2 etc.
            $      - Previous 2 links as a monad f([R, P]):
        Ẉ          -   Get the length of each
           /       -   Reduce by:
          €        -     Convert len(R) to a range and over each element:
         ạ         -       Take the absolute difference with len(P)
       ×           - Multiply these lists together
             ṣ0    - Split at 0, the pivot point
               §   - Sum of each side
                I  - Difference between the sides
                 Ṡ - Sign

```

---
Tags: code-golf, parsing, physics
---


# Question
Title: Your challenge is to make a script that reverses a word then replaces letters
Your task is to make a script *with the shortest byte count*, that reverses a word then replaces each letter with the next letter next in the alphabet.

Examples:

```
input: hi
output: ji

input: hello
output: pmmfi

input: test
output: utfu

```

A few notes:

* Should the letter's value be 27 (`z`+1), assume it is an `a`.
* Symbols, numbers (and any other characters not found in the alphabet) as inputs should error

# Answer
# Python 3, 109 bytes

```
p=input()
print(''.join(chr(ord(c)+1)for c in p[::-1]).replace('{','a').replace('[','A')if p.isalpha()else 0)

```

Try it online!

This is working also for uppercase letters, since also them are included in the alphabet.

Code explanation:

```
p=input()
# takes the input from the prompt

                                                                              if p.isalpha()
# main check: if the string contains all alphabetic characters

              chr(ord(c)+1)for c in p[::-1]
# reverse the word and returns a list of the next characters in the alphabet (ascii value +1)

      ''.join
# creates a string from the list

                                            .replace('{','a').replace('[','A')
# substitutes in the new string the characters '{' (='z' + 1) and '[' (='Z' + 1), to remap 'Z' 'z' to 'A' 'a'

print
# returns the modified word or 0 if a non letter character is present in the input string

```
> 1 votes

# Answer
# Whispers v1, ~~349~~ 343 bytes

```
>> #2
> Input
>> [13]
>> LⁿR
>> Each 20 27
>> Each 4 29 30
> 0
> 65
> 90
> 97
> 122
>> 8…9
>> 10…11
>> [12]
>> Then 14 3
>> Then 3
>> Then 15
>> 7-L
>> ≻L
>> ?L
>> 'L
>> L∈R
>> 2ⁿL
>> LⁱR
>> (1]
>> Each 18 25
>> Each 23 26
>> 1⋅16
>> 1⋅17
>> Each 22 5 28
>> Each 24 6 5
>> Each 19 31
>> Each 4 6 32
>> Each 21 33
>> Output 34

```

Try it online!

In Whispers, the last line is executed first. The other lines are executed when they are referenced in an executing line. Since this program contains many nested operations, I will try to explain it in a bottom-up approach. For better understanding, I will go through the explanation using the example input `HelloWorld`.

**Input:**

2 `>> Input`

Takes the first line of input. Example: `HelloWorld`

**Constants:**

7 `> 0` 8 `> 65` 9 `> 90` 10 `> 97` 11 `> 122`

Simple integers.

12 `>> 8…9`

Returns the set {result of *line 8* .. result of *line 9*}, so we get `{65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90}`.

13 `>> 10…11`

We get `{97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122}`.

14 `>> [12]`

Converts the result of *line 12* into a list. We get `[65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90]`. Since this array occurs several times in this explanation, I will call it `A`.

3 `>> [13]`

`[97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122]`. We call this array `B`.

15 `>> Then 14 3`

```
[A, B]

```

16 `>> Then 3`

```
[B]

```

17 `>> Then 15`

```
[[A, B]]

```

**Functions:**

Functions take an argument `L` and/or an argument `R` from a previously executed line.

4 `>> LⁿR`

Returns the `R`th position of `L`.

18 `>> 7-L`

Takes the result from *line 7*, subtracts it with `L` and returns it. Since the result of *line 7* is `0` *line 18* simply negates its argument.

19 `>> ≻L`

Increments `L`.

20 `>> ?L`

Returns the integer representation of `L`.

21 `>> 'L`

Returns the string representation of `L`.

22 `>> L∈R`

Returns true if `L` is in `R`, else false.

23 `>> 2ⁿL`

Returns the `L`th position of the result of *line 2*. Since *line 2* is our example input `HelloWorld` it will return the `L`th character of this word.

24 `>> LⁱR`

Returns the index of `R` in `L`.

**Variables:**

1 `>> #2`

Returns the length of result of *line 2*. In this example it is `10`.

25 `>> (1]`

Returns the set {1 .. result of *line 1*}, so we get `{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}`.

The `Each` command iterates over the second argument and applies the function given by the first argument. If two arrays are passed, they are zipped.

26 `>> Each 18 25`

```
[-1, -2, -3, -4, -5, -6, -7, -8, -9, -10]

```

27 `>> Each 23 26`

```
dlroWolleH

```

5 `>> Each 20 27`

```
[100, 108, 114, 111, 87, 111, 108, 108, 101, 72]

```

28 `>> 1⋅16`

```
[B, B, B, B, B, B, B, B, B, B]

```

29 `>> 1⋅17`

```
[[A, B], [A, B], [A, B], [A, B], [A, B], [A, B], [A, B], [A, B], [A, B], [A, B]]

```

30 `>> Each 22 5 28`

```
[True, True, True, True, False, True, True, True, True, False]

```

6 `>> Each 4 29 30`

```
[B, B, B, B, A, B, B, B, B, A]

```

31 `>> Each 24 6 5`

```
[3, 11, 17, 14, 22, 14, 11, 11, 4, 7]

```

32 `>> Each 19 31`

```
[4, 12, 18, 15, 23, 15, 12, 12, 5, 8]

```

33 `>> Each 4 6 32`

```
[101, 109, 115, 112, 88, 112, 109, 109, 102, 73]

```

34 `>> Each 21 33`

```
emspXpmmfI

```

**Output:**

35 `>> Output 34`

Outputs the result of *line 34*.

But why the strange order? Because the order is essential. The *lines 1-6* are called several times. So they should better be on a small number line.
> 2 votes

---
Tags: code-golf
---


title: Caesar Shifting

text:
# Question
Title: Caesar Shifting
A Caesar shift is probably something we're all familiar with.

(You might be even doing it as a homework task. If so, please don't copy these answers, your teacher almost certainly doesn't want anything like the answers here.)

Just in case you aren't, a Caesar shift is a very simple form of cipher. It takes a string to be ciphered and an integer. Then for every alphabetical character in the string, perform the following transformation:

1. Work out the character's position in the alphabet (0 based).
2. Add to that number the integer received at the beginning.
3. While the number is bigger than 25, subtract 26 from it.
4. Work out the position of the alphabet it is in.

Leave the rest of the characters unshifted.

Capital letters have to be respected because what is English without capital letters?

Examples:

```
abcdefghijklmnopqrstuvwxyz 1 -> bcdefghijklmnopqrstuvwxyza
Spam spam spam sausage and spam! 13 -> Fcnz fcnz fcnz fnhfntr naq fcnz!
abcdefghijklmnopqrstuvwxyz 52 -> abcdefghijklmnopqrstuvwxyz
abcdefghijklmnopqrstuvwxyz -1 -> zabcdefghijklmnopqrstuvwxy
ABCxyz 3 -> DEFabc

```

## Assumptions

* You may receive any printable ASCII character
* The input number can be negative and will always be bigger than -128 and less then 128 (`-128<x<128`)
* You must be able to encode capital letters and non-capital letters reversibly.
* You must create a full program, not just a function or snippet
* You will get your input from STDIN or closest alternate
* You may choose the format for your input, please state this in your answer
* The characters that need to be shifted are ASCII codepoints `0x41 - 0x5A` and `0x61-0x7A` \- upper and lower case letters

+ Upper case letters should stay upper
    + Lower case letters should stay lower
    + Characters not in this range should be left as they are
* Note for this challenge, you only have to cipher strings, you don't have to be able to solve them automatically (but giving `-x` will reverse the cipher)

Since this is a catalog, languages created after this challenge are allowed to compete. Note that there must be an interpreter so the submission can be tested. It is allowed (and even encouraged) to write this interpreter yourself for a previously unimplemented language. Other than that, all the standard rules of must be obeyed. Submissions in most languages will be scored in bytes in an appropriate preexisting encoding (usually UTF-8).

## Catalog

The Stack Snippet at the bottom of this post generates the catalog from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

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

```
## 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 snippet:

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

```

```
<style>body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; }</style><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="language-list"> <h2>Shortest Solution 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> <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> <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><script>var QUESTION_ID = 67044; var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 32686; var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); else console.log(body); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; lang = jQuery('<a>'+lang+'</a>').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang, user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw > b.lang_raw) return 1; if (a.lang_raw < b.lang_raw) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } }</script>
```

# Answer
> 9 votes
# Pyth, 13 bytes

```
uXGH.<HQrBG1z

```

Test suite

Basically, we start with the two strings we want to caesar shift, the lowercase and uppercase alphabets. The list containing both of these is generated by `rBG1`, bifurcate on uppercase. Then, we reduce over this list, starting with the input string and translating first lowercase, then uppercase letters by the appropriate shift.

# Answer
> 7 votes
# Pyth, 16

```
XXzG.<GQJrG1.<JQ

```

Try it online or run a Test Suite

# Answer
> 5 votes
# Bash + bsd-games package, 21

```
caesar $[($1+130)%26]

```

Builtins FTW! Almost feels like Mathematica. Pyth answers are still shorter though.

Input string read from STDIN and integer from command-line. e.g.:

```
$ ./caesar.sh 13 <<< "Spam spam spam sausage and spam!"
Fcnz fcnz fcnz fnhfntr naq fcnz!
$

```

---

Or if you don't like the builtin:

# Bash + coreutils, 63

```
printf -va %s {a..z}
t=${a:$1%26}${a:0:$1%26}
tr A-Z$a ${t^^}$t

```

# Answer
> 4 votes
# JavaScript (ES6), ~~122~~ ~~118~~ ~~114~~ 111 bytes

```
alert((p=prompt)().replace(/[a-z]/gi,c=>String.fromCharCode((x=c.charCodeAt(),a=x&96,x-a+n+129)%26-~a),n=+p()))

```

*Saved 4 bytes thanks to @Neil!*

## Explanation

First prompt takes the input string. The second is the number to shift each letter by.

```
alert(
  (p=prompt)()              // get input string
    .replace(/[a-z]/gi,c=>  // for each letter
      String.fromCharCode((
        x=c.charCodeAt(),   // x = code of character
        a=x&96,             // a = index of letter a (-1) in same capitalisation
        x-a+n+129)%26-~a    // add N to the letter code and wrap at 26
      ),                    // (+129 is needed to make the % work with negative numbers)
      n=+p()                // get number to shift by
    )
)

```

# Answer
> 3 votes
## CJam, ~~34~~ ~~22~~ ~~21~~ 20 bytes

*Thanks to FryAmTheEggman for saving 1 byte.*

```
l'[,_el^_26/l~fm<ser

```

Test it here.

Input is the string to be shifte on the first line and the shift on the second.

### Explanation

```
l    e# Read the first line of input.
'[,  e# Push a string with all ASCII characters up to and including Z.
_el  e# Duplicate and convert to lower case. This only affects the letters.
^    e# Symmetric set-difference: except for the letters, each character appears in both
     e# sets and will be omitted from the difference, but all the letters will be included.
     e# This gives us "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".
_26/ e# Duplicate and split into chunks of 26 characters, separating lower and upper case.
l~   e# Read the second line of input and evaluate.
fm<  e# Shift each of the two substrings by that many characters to the left.
s    e# Convert to a single string, joining both substrings back together.
     e# On the stack are now the input, the letters in alphabetical order and the letters
     e# in shifted order.
er   e# Character transliteration: replace each occurrence of a letter with the character
     e# at the corresponding position in the shifted string.

```

# Answer
> 2 votes
# Java, 249 Bytes

This is as short as I could get it. Reading from stdin eats a ton of bytes. A solution using command line args is noticeably shorter but, this task specified stdin for input.

Input format is the String first followed by the shift number on a new line.

```
interface C{static void main(String[]a){java.util.Scanner r=new java.util.Scanner(System.in);String s=r.nextLine();int i=(r.nextInt()+26)%26;s.chars().forEach(c->System.out.print((char)(c>64&c<91|c>96&c<123?c<91?65+(c+i-65)%26:97+(c+i-97)%26:c)));}}

```

Using command line Arguments this solution is only 188 bytes. Input is the String as the first argument and the shift as the second.

```
interface C{static void main(String[]a){int i=(Integer.parseInt(a[1])+26)%26;a[0].chars().forEach(c->System.out.print((char)(c>64&c<91|c>96&c<123?c<91?65+(c+i-65)%26:97+(c+i-97)%26:c)));}}

```

# Answer
> 1 votes
## R, 111 bytes

### code

```
n=scan();s=scan(,"");for(l in as.numeric(sapply(s,charToRaw))){v=97;if(l<97)v=65;cat(intToUtf8((l+n-v)%%26+v))}

```

### ungolfed

```
n <- scan()                           # input integer
s <- scan(,"")                        # input string letter by letter
z <- as.numeric(sapply(s,charToRaw))  # get ASCII index of character
for (l in z){                         # loop through chars
  v=97                                # base index of not capitalized chars
  if(l<97)v=65                        # base index of capitalized chars
  cat(intToUtf8((l+n-v)%%26+v))       # paste the char of the shifted index
}

```

This program takes the user input from STDIN, first the integer shifter and then the string, character by character.

# Answer
> 1 votes
## Perl, 81 bytes

(+1 for the `-p` flag)

```
s/[^ ]+ //;$n=$&%26;eval"y/a-zA-Z/".($x=chr(97+$n)."-za-".chr$n+96).uc$x."/"if$n

```

Still working on golfing it down...

Test:

```
llama@llama:...code/perl/ppcg67044caesar$ printf '1 abcdefghijklmnopqrstuvwxyz\n13 Spam spam spam sausage and spam!\n52 abcdefghijklmnopqrstuvwxyz\n-1 abcdefghijklmnopqrstuvwxyz\n3 ABCxyz' | perl -p caesar.pl; echo
bcdefghijklmnopqrstuvwxyza
Fcnz fcnz fcnz fnhfntr naq fcnz!
abcdefghijklmnopqrstuvwxyz
zabcdefghijklmnopqrstuvwxy
DEFabc

```

# Answer
> 1 votes
## Python 2, ~~163~~ 160 bytes

Not sure if I can still golf it down..

```
import sys;k=sys.argv
def f(x,n):r=chr((ord(x.lower())-97+n)%26+97);return(x,[r,r.upper()][x.isupper()])
print''.join(f(x,int(k[2]))[x.isalpha()] for x in k[1])

```

Since it's pretty unreadable, here is an ungolfed version:

```
import sys

def shift(x,n):
    # shift character x by n (all in lowercase)
    r = chr((ord(x.lower())-97+n)%26+97)
    if x.isalpha() and x.islower():
        return r
    elif x.isalpha() and x.isupper():
        return r.upper()
    else:
        return x

# 'map' the function shift to each character of the input
output = ''.join(shift(x,int(sys.argv[2])) for x in sys.argv[1])
print(output)

```

Concerning the input: It expects two arguments, the first must be a string and the second an integer (the shift amount). Examples (file is called `csr.py`):

```
$ python csr.py gnu 9
pwd
$ python csr.py "Spam spam spam sausage and spam\!" 13
Fcnz fcnz fcnz fnhfntr naq fcnz!

```

Note: In the second example an escape character and `""` are needed

# Answer
> 1 votes
# Japt, ~~45~~ 43 bytes

```
Ur"[^\\W_]"_c +V+#¶-(A=Zc <#a?#A:#a)%26+A d

```

Try it online!

# Answer
> 1 votes
## Python 2, ~~118~~ 116 bytes

```
s,n=input()
print''.join([[c,chr((ord(c)-97+n)%26+97)]['`'<c<'{'],chr((ord(c)-65+n)%26+65)]['@'<c<'[']for c in s)

```

# Answer
> 1 votes
## Mathematica, 117 bytes

```
Echo[InputString[]~StringReplace~Thread[Join[a=Alphabet[],b=ToUpperCase@a]->(c=RotateLeft)[a,d=Input[]]~Join~c[b,d]]]

```

Takes the string, followed by a newline, followed by the shifting factor. Might still be golfable...

# Answer
> 1 votes
# Perl 6, 73+1 = 74 bytes

```
$ perl6 -pe 's:g:i/<[a..z]>/{chr ((my$o=ord ~$/)-(my$a=$o+&96+1)+BEGIN get%26)%26+$a}/' # 73+1

```

The first line of input is the number of characters to shift the letters up by.

Usage:

```
$ perl6 -pe 's:g:i/<[a..z]>/{...}/' <<< \
'1
abcdefghijklmnopqrstuvwxyz'
bcdefghijklmnopqrstuvwxyza

```

```
$ perl6 -pe 's:g:i/<[a..z]>/{...}/' <<< \
'13
Spam spam spam sausage and spam!'
Fcnz fcnz fcnz fnhfntr naq fcnz!

```

```
$ perl6 -pe 's:g:i/<[a..z]>/{...}/' <<< \
'52
abcdefghijklmnopqrstuvwxyz'
abcdefghijklmnopqrstuvwxyz

```

```
$ perl6 -pe 's:g:i/<[a..z]>/{...}/' <<< \
'-1
abcdefghijklmnopqrstuvwxyz'
zabcdefghijklmnopqrstuvwxy

```

```
$ perl6 -pe 's:g:i/<[a..z]>/{...}/' <<< \
'3
ABCxyz'
DEFabc

```

```
$ perl6 -pe 's:g:i/<[a..z]>/{...}/' <<< \
'1000000000000000000000000000000000000000
abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ'
mnopqrstuvwxyzabcdefghijkl
MNOPQRSTUVWXYZABCDEFGHIJKL

```

# Answer
> 1 votes
# C++, ~~163~~ ~~154~~ 152 bytes

```
#include<cstdio>
#include<cstdlib>
int main(int x,char**a){for(int c,b,s=atoi(a[1]);1+(c=getchar());putchar(c<b|c>b+26?c:(c+s-b+26)%26+b))b=c<97?65:97;}

```

Usage:

```
$ ./caesar -1 <<< "123 a A z Z aBcDeFgHiKlMnOpQrStUvWxYz"
123 z Z y Y zAbCdEfGhJkLmNoPqRsTuVwXy

```

# Answer
> 0 votes
## k4, 80 bytes

The program accepts the shift number as a command-line argument and reads text from stdin.

Due to a technical constraint, negative shifts must be encoded with an underscore instead of a hyphen-minus. (Without the parser for interpreting this encoding, the solution would be 64 bytes.)

```
% wc -c c.k
80 c.k
% cat c.k
c:{x;,/x{y!(x_y),x#y}'.Q`a`A}
.z.pi:{1@x^c[.q.mod[.*{x^((!).$"_-")x}.z.x]26]x;}
%

```

Here's the examples executed:

```
% echo abcdefghijklmnopqrstuvwxyz|q c.k 1
bcdefghijklmnopqrstuvwxyza
% echo 'Spam spam spam sausage and spam!'|q c.k 13
Fcnz fcnz fcnz fnhfntr naq fcnz!
% echo abcdefghijklmnopqrstuvwxyz|q c.k 52
abcdefghijklmnopqrstuvwxyz
% echo abcdefghijklmnopqrstuvwxyz|q c.k _1
zabcdefghijklmnopqrstuvwxy
% echo ABCxyz|q c.k 3
DEFabc
%

```

And here's a silly little test harness that verifies both encode and decode. (This is `zsh`; for `bash` or `ksh`, change the `for` loop indexing to `((i=0;i<5;i++))`. One-based arrays, ugh....)

```
% a=(abcdefghijklmnopqrstuvwxyz 'Spam spam spam sausage and spam!' abcdefghijklmnopqrstuvwxyz abcdefghijklmnopqrstuvwxyz ABCxyz)
% b=(1 13 52 _1 3)
% c=(bcdefghijklmnopqrstuvwxyza 'Fcnz fcnz fcnz fnhfntr naq fcnz!' abcdefghijklmnopqrstuvwxyz zabcdefghijklmnopqrstuvwxy DEFabc)
% for ((i=1;i<=5;i++))
for> do
for>     r=$(echo "${a[i]}"|q c.k "${b[i]}")
for>     s=$(echo "$r"|if [[ ${b[i]} == _* ]]; then q c.k "${b[i]/_}"; else q c.k "_${b[i]}"; fi)
for>     printf '%s\t%s\n' "$([[ ${c[i]} == $r ]] && echo good || echo bad)" "$([[ ${a[i]} == $s ]] && echo good || echo bad)"
for> done
good    good
good    good
good    good
good    good
good    good
%

```

# Answer
> 0 votes
# Stax, 2 bytes

```
ç'

```

Run and debug it

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


title: Get the closest value to number

text:
# Question
Title: Get the closest value to number
In this code golf, you need to get the closest number from another one in a list.

The output may be the closest number to the input.

Example:

```
value: (Input) 5 --- [1,2,3] --- 3

```

And, the program may work with negative numbers.

Example:

```
value: (Input) 0 --- [-1,3,5] --- -1

value: (Input) 2 --- [1, 5, 3] --- 1 (Because it gives priority to lower numbers)

```

**RULES:**

As mentioned before, it has to work with negative numbers.

If there are two answers (Example: 0 -- \[5,-5\]), the program gives priority to the lowest number. (-5)

This is code golf so the shortest code wins!

# Answer
> 7 votes
# Pyth, 6 bytes

```
haDQSE

```

Test suite

Input in the following form on STDIN:

```
num
array

```

Explanation:

```
haDQSE
          Implicit: Q = eval(input()) (num)
     E    Evaluate input (array)
    S     Sort (smaller values to the front)
 aDQ      Sort by absolute difference with Q.
h         Take the first element of the sorted list, the min.
          Print implicitly.

```

# Answer
> 6 votes
## Ruby, 34 bytes

```
->n,a{a.sort.min_by{|x|(n-x).abs}}

```

```
a.sort       min_by tiebreaks by position in array, so put smaller numbers 1st
.min_by{|x|  select the element which returns the smallest val for predicate...
(n-x).abs}   (absolute) difference between input num and element

```

# Answer
> 5 votes
# Mathematica, 12 bytes

```
Min@*Nearest

```

Built-ins FTW! Buettner's explanation: "Mathematica has a built-in `Nearest` for this, but it returns a list of all tied numbers. Hence, we need to compose it with `Min` to break the tie."

# Answer
> 3 votes
# Pyth, 8 bytes

```
hS.mabQE

```

Explanation

```
         - autoassign Q = eval(input())
  .m   E -   min_values([V for b in eval(input())])
    abQ  -    abs(b-Q)
 S       -  sorted(^)
h        - ^[0]

```

Try it online!

# Answer
> 2 votes
# Jelly, ~~7~~ 6 bytes

```
ạżṛỤḢị

```

Try it online!

### How it works

```
ạżṛỤḢị Main link. Left input: n (number). Right input: A (list)

ạ      Take the asbolute difference of n and the items of A.
  ṛ    Yield the right argument, A.
 ż     Zip the left result with the right one.
       This pairing causes ties in absolute value to be broken by initial value.
   Ụ   Grade up; sort the indices of the resulting list by their associated values.
    Ḣ  Retrieve the first index, which corresponds to the smallest value.
     ị Retrieve the item of A at that index.

```

# Answer
> 2 votes
## JavaScript ES6, ~~64~~ ~~56~~ 54 bytes

```
(i,a)=>a.sort((a,b)=>s(i-a)-s(i-b)||a-b,s=Math.abs)[0]

```

Try it online

Thanks to @Niel for saving two bytes

Test Snippet:

```
f=(i,a)=>a.sort((a,b)=>s(i-a)-s(i-b)||a-b,s=Math.abs)[0];

[
  [5, [1, 2, 3]],
  [2, [3, 5, 1]],
  [2, [1, 3, 5]],
  [0, [-1, 2, 3]],
  [5, [1, 2, 3]]
].map(v=>O.textContent+=JSON.stringify(v)+": "+f.apply(null,v)+"\n")
```

```
<pre id=O></pre>
```

# Answer
> 2 votes
# Jelly, 4 bytes

```
ạÐṂṂ

```

Try it online!

This takes `A` on the left and `n` on the right

I'm guessing the `ÐṂ` builtin didn't exist when Dennis wrote his answer.

## How it works

```
ạÐṂṂ - Main link. Takes A on the left and n on the right
 ÐṂ  - Keep elements of A with a minimal:
ạ    -   Absolute difference with n
   Ṃ - Take the minimum

```

# Answer
> 2 votes
# APL (Dyalog Unicode), ~~17~~ 16 bytes

```
⊢{⌊/⍺/⍨⍵=⌊/⍵}∘|-

```

Try it online!

This is a function which takes a single number as a left argument and a list of numbers as a right argument.

The general structure of this is a fork consisting of:

* the constant right function  returns the list of numbers
* `|-` calculates the absolute value of each difference between a number from the list and the left argument
* and the dfn `{⌊/⍺/⍨⍵=⌊/⍵}` which is called with the results of the other two functions:

```
            ⍝ ⍵: absolute differences (|-)
            ⍝ ⍺: the original list (⊢)
       ⌊/⍵  ⍝ the minimum of the absolute differences
     ⍵=     ⍝ element-wise equal to the absolute differences
  ⍺/⍨       ⍝ select all values from the original list where this is 1
⌊/          ⍝ take the minimum

```

A fully tacit function came out at 17 bytes: `⌊/∘∊((⊢=⌊/)∘|-)⊆⊢`.

---

With some help from Adám, here is a shorter function in the extended variant:

# APL (Dyalog Extended), 12 bytes

```
(⊃⍋⍤|⍤-⊇⊢)∘∧

```

Try it online!

Same arguments as before,  sorts the list ascending and `⊃⍋⍤|⍤-⊇⊢` is applied with the left number and the sorted list as a right argument.

```
     -   ⍝ the difference between the left argument and each list entry of the sorted list
   |     ⍝ take the absolute values
 ⍋       ⍝ the indices that would sort this list (stable)
      ⊇  ⍝ index with these indices into ...
       ⊢ ⍝ ... the sorted list. This resorts the list on the absolute difference
⊃        ⍝ pick the first value

```

# Answer
> 2 votes
# , 37 bytes

```
(x=scan())[order(abs(x-scan()),x)][1]

```

Try it online!

After 4 years, 5 bytes shorter than the previous R answer.

Uses the `order()` function with two arguments, to order first by the closeness to the target value, and then to break ties by the array value. Finally outputs the first element after re-ordering.

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

```
a=input()
print sorted(input(),key=lambda x:abs(a-x))[0]

```

Gets the target number first `a=input()` \- this has to be stored in a variable.

It then sorts the input with the function `lambda x:abs(a-x)` applied (think `map(lambda x:abs(a-x), input())`)

It then takes the minimum value in case of any duplicate values

# Answer
> 1 votes
# MATL, 10 bytes

```
Sti-|4#X<)

```

**Try it online!**

```
S       % implicitly input array, and sort. This ensures smaller numbers have priority
t       % duplicate
i       % input number
-|      % compute array of absolute differences
4#X<    % arg min. If there are several minimizers, the position of the first is returned
)       % index into original array. Implicitly display

```

# Answer
> 1 votes
# Japt `-g`, 4 bytes

```
ÍñaV

```

Try it

```
ÍñaV     :Implicit input of array U and integer V
Í        :Sort U
 ñ       :Sort by
  aV     :  Absolute difference with V
         :Implicit output of first element

```

# Answer
> 1 votes
# Python 3, 41 bytes

```
lambda n,a:min((abs(n-i),i)for i in a)[1]

```

Try it online!

No need to sort, because `min` captures the lowest difference *and* the lowest value.

Also works in Python 2.

# Answer
> 1 votes
# Husk, ~~6~~ 4 bytes

```
◄≠⁰O

```

Try it online!

```
◄           # element that minimizes
 ≠⁰         # difference to arg 1
   O        # applied to sorted elements
            # (implicitly) of arg 2

```

# Answer
> 1 votes
# 05AB1E, 4 bytes

```
{I.x

```

Try it online or verify all test cases.

**Explanation:**

```
{     # Sort the first (implicit) input-list from lowest to highest
  .x  # Pop the list, and push the value closest
 I    # to the second input-integer
      # (after which it is output implicitly as result)

```

This could have been 2 bytes (`.x`) if we were allowed to output the first instead of the lowest value in the list, if more than one is closest: try it online or verify all test cases.

# Answer
> 0 votes
## zsh, ~~75~~ ~~73~~ ~~71~~ ~~70~~ 67 bytes

```
for n in ${@:2};{echo "$[$1-n]    $n"}|tr -d -|sort -n|head -1|cut -f2

```

Expects input as command line arguments.

Note that the four spaces in the `echo` is actually supposed to be a tab, but Stack Exchange converts tabs to spaces in all posts.

Not Bash-compatible because of the `for` syntax.

```
for n in ${@:2};      for each argument except the first...
{echo "$[$1-n]\t$n"}  output the difference from the first argument
                        and then the original number
|tr -d -              poor man's abs()
|sort -n              sort by first num (difference), tiebreaking by second num
                        (original value)
|head -1              take the thing that sorted first
|cut -f2              print field 2 (aka discard the difference)

```

Thanks to dev-null for 2 bytes!

# Answer
> 0 votes
# TeaScript, 10 bytes

```
T#(y-l)a)░

```

TeaScript doesn't support array input so in the console run: `TeaScript("T#y-la)░", [[1, 2, 3], 1], {}, TEASCRIPT_PROPS)` to runthis.

## Explanation

```
T#  // Sort input by...
  (y-l)a // absolute difference with input
)░  // First item in array

```

# Answer
> 0 votes
# R, 42 bytes

```
x=sort(scan());x[which.min(abs(x-scan()))]

```

# Answer
> 0 votes
## Haskell, 38 bytes

```
e#l=snd$minimum$(zip=<<map(abs.(e-)))l

```

Usage example: `2 # [1,5,3]`-\> `1`.

For each element in the input list `l` make a pair of the absolute difference of the element with the input number `e` and the element itself, e.g. `e=2`, `l=[1,5,3]` -\> `[(1,1),(3,5),(1,3)]`. Find the minimum and discard the difference.

# Answer
> 0 votes
# Perl 6, 31 bytes

```
{@^b.sort.sort((*-$^a).abs)[0]}

```

### Usage:

```
my &code = {@^b.sort.sort((*-$^a).abs)[0]}

say code 5, [1,2,3];   # 3
say code 0, [-1,3,5];  # -1
say code 2, [1, 5, 3]; # 1
say code 0, [5,-5];    # -5

```

# Answer
> 0 votes
# Stax, 7 bytes

```
ôXêUe>┤

```

Run and debug it

# Answer
> 0 votes
# PHP, 62 bytes

```
foreach($a as $i){$s[$i]=abs($i-$n);}
asort($s);print key($s);

```

Try it online!

First PHP answer, please help!

*(Define the number and array in header section)*

# Answer
> 0 votes
# T-SQL, 93 Bytes

```
SELECT MIN(B) FROM(SELECT B,abs(B-@v) AS C FROM @A) D WHERE C=(SELECT MIN(abs(B-@v)) FROM @A)

```

Example:

```
DECLARE @A TABLE(B  INT);
DECLARE @v INT = 5;
INSERT INTO @A SELECT * FROM (VALUES(1),(2),(3)) AS A(B);

SELECT MIN(B) -- 3. Finally, select the minimum list value from the rowset
FROM(
        SELECT B,abs(B-@v) AS C -- 1. Get list value along with absolute value of the difference.
        FROM @A
    ) D
WHERE C = (SELECT MIN(abs(B-@v)) -- 2. Filter for the smallest absolute difference.
          FROM @A
          )

```

# Answer
> 0 votes
# C# ~~61~~ 52 bytes

```
int v(int i,int[] a)=>a.Min(x=>(Math.Abs(i-x),x)).x;

```

Or function body only: 29 bytes.

---
Tags: code-golf, math, number, array
---


title: Autogrammatic pairs

text:
# Question
Title: Autogrammatic pairs
For today's task, we have two programs, P and Q, both in the same language. Each of them receives a single-character input.

If P receives character K, P says how many times K appeared in Q. (You can use any output format for P or Q; they need not be the same, the only requirement is that your format can represent any nonnegative integer uniquely). Vice versa: If Q gets K, Q says how many times K was in P.

**Create P and Q,** which must not be identical programs. To further cement this, P and Q must be minimal (remove any amount of characters from either and it doesn't work as required).

Whoever made the combined lengths of P and Q the shortest wins (tiebreak: earlier post). Have fun!

# Answer
# Jelly, 24 bytes

**P**

```
“ṾċḷḤ”Ṿċḷ“”Ḥ

```

**Try it online!**

**Q**

```
“ṾċḷḤ”Ṿċḷ”“Ḥ

```

**Try it online!**

P and Q are very similar, they both contain two of each of the same set of six characters. The only difference is `“”` vs `”“` (empty list vs a single open quote character).

### How?

```
“ṾċḷḤ”Ṿċḷ..Ḥ - Link: character, C
“ṾċḷḤ”       - list of characters = ['Ṿ', 'ċ', 'ḷ', 'Ḥ']
      Ṿ      - un-evaluate Jelly code = ['“', 'Ṿ', 'ċ', 'ḷ', 'Ḥ', '”']
         ..  - either:
             -   “” - empty list = []
             -   ”“ - character literal = '“'
        ḷ    - yield the left argument of this dyadic atom (C)
       ċ     - count occurrences (of C in the un-eval list)
           Ḥ - double

```
> 3 votes

# Answer
# APL (Dyalog Unicode), 29 bytes (SBCS)

## Mutually dependent lambdas

```
P←{≢⍸⍵=⎕CR'Q'}
Q←{≢⍸⍵=⎕CR'P'}

```

Try it online!

`P←`… establish a function with the following definition:

`{``}` dfn; the argument (a character) is :

`⎕CR'``'`**C**haracter **R**epresentation of the function called … (as a character matrix)

`⍵=` 2D mask indicating where the character is equal to elements of that matrix

**ɩ**ndices where true

tally them

## Mutually independent lambdas (35 bytes)

```
P←{≢⍸⍵=⎕CR'P'⋄QQ}
Q←{≢⍸⍵=⎕CR'Q'⋄PP}

```

Try it online!

The only difference from the above is that each function reads its own source, and that each has a dummy statement containing supplemental characters that ensure that they have identical counts of all characters.  is the statement separator, but the second statement will never be reached (it'd cause a vale error anyway) because the function terminates with the value of the first non-assigning statement.
> 4 votes

# Answer
# PowerShell, 63 bytes

Inspired by @Wasif's awesome PowerShell answer

-6 bytes thanks to mazzy!

```
$P={$Q-replace"[^$args]"|% le*}
$Q={$P-replace"[^$args]"|% le*}

```

Try it online!

# PowerShell, Independent Functions, 109 103 93 77 bytes

This version does not require the functions to be in the same file; they are completely independent of one another.

```
$P={"Q$P"-replace"\|P|[^$args]"|% le*}
$Q={"P$Q"-replace"\|Q|[^$args]"|% le*}

```

Try it online!

For either answer, it costs 2 bytes to make the input character case-sensitive.
> 4 votes

# Answer
# PowerShell, ~~128~~ 122 bytes

```
function P($x){cd Function:;(gc Q)-replace"[^$($x)]"|% le*}
function Q($x){(gc $psCommandPath)[0]-replace"[^$($x)]"|% le*}

```

Try it online!

-6 bytes Thanks to mazzy and Zaelin Goodman

Two functions work in different ways.

`P()` will read `Q()`'s source code and count occurrences of the given character.

`Q()` will read the source of the first line in the script (Which is source of function `P()`), and count occurrences of the given character.

I Couldn't be more creative than this solution to follow the rules of the question, otherwise if I made two functions identical, I could save some bytes.
> 3 votes

# Answer
# , version-dependent, ~~110~~ 84 bytes

*Edit: -26 bytes with inspiration from user81655's answer*

*Note: Function-pairs #1 and #2 below depend on the version-dependent output formatting of  functions, and work on my locally-installed  version 3.2.1, but unfortunately not on version 3.5.2 which is installed on TIO. A TIO-compliant (but longer) adjusted version of #1 can be tried here: try it.*

**1: functions that read each other's source code: 84 = 61+23 bytes**

```
p=function(c,x=q)sum(el(gregexpr(c,capture.output(x),f=T))>0)
q=function(c,x=p)p(c,x)

```

**2: functions that read their own source code, but not each other's: 142 = 2x 71 bytes**

```
p=function(c,pr=2,q=1)sum(el(gregexpr(c,capture.output(p),f=T))>pr-q-q)
q=function(c,qr=2,p=1)sum(el(gregexpr(c,capture.output(q),f=T))>qr-p-p)

```

**3: 'proper quine'-like functions that don't read their own source code: 236 = 2x 118 bytes**

```
p=function(c,q=1,p=1)2*sum(el(gregexpr(c,sQuote('function(c,p=1,q=1)2*sum(el(gregexpr(c,sQuote(),f=T))>p-q)'),f=T))>q-p)
q=function(c,p=1,q=1)2*sum(el(gregexpr(c,sQuote('function(c,q=1,p=1)2*sum(el(gregexpr(c,sQuote(),f=T))>q-p)'),f=T))>p-q)

```

---

# , version-dependent, 150 bytes

*New function-pair to comply with the newly-added rule that functions cannot be anagrams of each other*

**4: functions that read their own source code, but not each other's, and are not anagrams of each other: 150 = 2x 75 bytes**

```
p=function(z)sum(el(gregexpr(z,chartr("yz","zy",capture.output(p)),f=T))>0)
q=function(y)sum(el(gregexpr(y,chartr("zy","yz",capture.output(q)),f=T))>0)

```
> 3 votes

# Answer
# JavaScript (V8), 51 bytes

```
p=(k,s='q='+q)=>s.split(k).length-1
q=k=>p(k,'p='+p)

```

Try it online!

Works assuming we're allowed to read the other program (grey area but not explicitly disallowed in the rules).
> 2 votes

# Answer
# Zsh, ~~104 96~~ 56 bytes

```
a=`<$0` b=$1;<<<${#a//[^$b]}

```

```
b=`<$0` a=$1;<<<${#b//[^$a]}

```

~~Try it online! Try it\* online!~~  Try it online!

Both programs are independent (they don't read each other's source). I found the best way to tackle the challenge was to make two self-counting programs with the same character counts. Using assignment to expand the simple `${#${$(<&0)//[^$1]}}` feels cheap, so do take a look at my older programs.

(\*My second attempt hits a fork limit on TIO, so its TIO link uses a modified version that uses the non-forking `echo` instead of `<<<`.)
> 1 votes

# Answer
# Python 3, <sup>~~106~~ ~~100~~</sup> 96 bytes

Saved 10 bytes thanks to Dominic van Essen!!!

```
import inspect
f=lambda c:inspect.getsource(g).count(c)
g=lambda c:inspect.getsource(f).count(c)

```

Try it online!

Two mutually dependent lambdas that simply read each other's source code and return the input character count.
> 1 votes

# Answer
# JavaScript, ~~85~~ 63 bytes

```
p=k=>('q='+p).split(k).length-1
q=k=>('p='+q).split(k).length-1

```

Mutually independent functions (thanks to user81655). Each function reads its own source code since the character counts are the same after the concatenation.

Try it online!
> 0 votes

# Answer
# Charcoal, 40 bytes

```
Ｉ⊗№⁺´”´””yＩ⊗№⁺´´yＳ”Ｓ

```

Try it online!

```
Ｉ⊗№⁺”yＩ⊗№⁺´´yＳ”´”´”Ｓ

```

Try it online!

The first program is simply my answer to Counting characters and the second is a trivial rearrangement.
> 0 votes

---
Tags: code-golf, string, restricted-source, counting
---


title: Is my Diffy game degenerate?

text:
# Question
Title: Is my Diffy game degenerate?
Recently I posted  question about Diffy games which has gone unanswered. Thats fine, the question is really hard, but I would like to make an easier question about Diffy games so that we can get the ball rolling.

---

# How Diffy works

*Copied from Find Diffy Games*

The Diffy game works like as follows: You start with a list of non-negative integers, in this example we will use

```
3 4 5 8

```

Then you take the absolute difference between adjacent numbers

```
 (8)  3   4   5   8
    5   1   1   3

```

Then you repeat. You repeat until you realize you have entered a loop. And then generally the game starts from the beginning again.

```
3 4 5 8
5 1 1 3
2 4 0 2
0 2 4 2
2 2 2 2
0 0 0 0
0 0 0 0

```

Most games end in a string of all zeros, which is considered to be a lose state, but a rare few games get stuck in larger loops.

---

# Task

Given the starting state of a Diffy game determine whether or not the game eventually reaches a state of all zeros. You should output a Truthy or Falsy value for each of the two states. Which corresponds to which does not matter.

The goal is to minimize the number of bytes in your source.

# Answer
> 27 votes
# Pyth, 6 bytes

```
suaV+e

```

Test suite

This program is very suave. 0 (falsy) means all zeroes, anything else (truthy) means not all zeroes.

How it works:

```
suaV+e
suaV+eGGGQ    Variable introduction.
 u       Q    Apply the following function repeatedly to its previous result,
              starting with the input. Stop when a value occurs which has
              occurred before.
  aV          Take the absolute differences between elements at the same indices of
        G     The previous list and
    +eGG      The previous list with its last element prepended.
s             The repeated value is returned. Sum its entries. This is zero (falsy)
              if and only if the entries are all zero.

```

# Answer
> 14 votes
# Mathematica, 52 bytes

```
1>Max@Nest[Abs[#-RotateLeft@#]&,#,Max[1+#]^Tr[1^#]]&

```

Pure function taking a list of nonnegative integers as input and returning `True` or `False`.

`Abs[#-RotateLeft@#]&` is a function that executes one round of the diffy game. (Technically it should be `RotateRight`, but the ultimate answer is unaffected, and hey, free byte.) So `Nest[...,#,R]` executes `R` rounds of the diffy game, and then `1>Max@` detects whether the result is all zeros.

How do we know how many diffy-game rounds `R` to do? If `m` is the largest value in the input, notice that we will never produce an integer larger than `m` no matter how many rounds we do. The total number of lists of length `l` of nonnegative integers all bounded by `m` is `(m+1)^l`. So if we carry out `(m+1)^l` rounds of the diffy game, we are guaranteed to have seen some list twice by then, and thus will be in the periodic part of the game. In particular, the game ends in all zeros if and only if the result of `(m+1)^l` rounds of the game is the all-zeros list. That expression is what `Max[1+#]^Tr[1^#]` computes.

# Answer
> 6 votes
# Jelly, 13 bytes

```
Ṁ‘*L
ṙ1ạ
ÇÑ¡Ṁ

```

Outputs 0 (falsey) if the all zero state will be reached, otherwise a truthy value (a positive integer) is returned.

**Try it online!**

Uses the observation first made by Greg Martin that the numbers within the array may never leave the domain **\[0,m\]** where **m** is the maximal element in the input, so performing **(m+1)l** rounds where **l** is the input's length will suffice.

### How?

```
Ṁ‘*L - Link 1, number of rounds to perform: list a
Ṁ    - maximum of a
 ‘   - incremented
   L - length of a
  *  - exponentiate

ṙ1ạ - Link 2, perform a round: list x
ṙ1  - rotate x left by 1
  ạ - absolute difference (vectorises) with x

ÇÑ¡Ṁ - Main link: list a
  ¡  - repeat:
Ç    -     the last link (2) as a monad
 Ñ   -     the next link (1) as a monad times
   Ṁ - return the maximum of the resulting list

```

# Answer
> 2 votes
# PHP, 144 Bytes

print 0 for all zero and any positive integer value for true

```
<?for($r[]=$_GET[0];!$t;){$e=end($r);$e[]=$e[$c=0];for($n=[];++$c<count($e);)$n[]=abs($e[$c-1]-$e[$c]);$t=in_array($n,$r);$r[]=$n;}echo max($n);

```

Online Version

Expanded

```
for($r[]=$_GET;!$t;){
    $e=end($r);  # copy last array
    $e[]=$e[$c=0]; # add the first item as last item
    for($n=[];++$c<count($e);)$n[]=abs($e[$c-1]-$e[$c]); # make new array
    $t=in_array($n,$r); # is new array in result array
    $r[]=$n; # add the new array
}
echo max($n); # Output max of last array

```

# Answer
> 2 votes
## R (3.3.1), 87 bytes

Returns zero for a game ending in all zeros, and a positive number otherwise.

```
z=scan();sum(Reduce(function(x,y)abs(diff(c(x,x[1]))),rep(list(z),max(z+1)^length(z))))

```

leverages the same fact by Greg Martin and uses the builtin diff to do the diffy-ing

# Answer
> 2 votes
# Jelly, 7 bytes

```
ṙ1ạµÐLẸ

```

Try it online!

Outputs `0` (falsey) if it is degenerate, and `1` (truthy) if not

## How it works

```
ṙ1ạµÐLẸ - Main link. Takes an array A on the left
   µ    - Group the links to the left into a monad f(A):
ṙ1      -   Rotate A one step to the left
  ạ     -   Take the absolute differences with A
    ÐL  - Repeatedly apply f(A) on A until reaching a fixed point
      Ẹ - Yield 0 if all 0s, else 1

```

# Answer
> 1 votes
# JavaScript (ES6), ~~95 92~~ 90 bytes

```
f=(a,b=(Math.max(...a)+1)**(c=a.length))=>b?f(a.map((v,i)=>v-a[++i%c]),b-1):a.every(v=>!v)

```

# Explanation

Recursive function that calls itself as long as the counter (which starts at the maximum value in the list plus one to the power of the length of the list \[`= (max + 1)**length`\]) is not zero. On every call, the counter is decremented, and when it hits zero, all elements in the list are checked against zero. If they all equal zero, the program returns `true`, and `false` otherwise.

# Answer
> 1 votes
# Röda, 80 bytes

```
f l...{x=[{peek a;[_];[a]}()|slide 2|abs _-_];[sum(x)=0]if[x in l]else{x|f*l+x}}

```

Try it online!

Ungolfed:

```
function f(l...) { /* function f, variadic arguments */
    x := [ /* x is a list of */
        { /* duplicate the first element of the stream to the last position */
            peek a /* read the first element of the stream */
            [_]    /* pull all values and push them */
            [a]    /* push a */
        }() |
        slide(2) | /* duplicate every element except first and last */
        abs(_-_)   /* calculate the difference of every pair */
    ]
    /* If we have already encountered x */
    if [ x in l ] do
        return sum(x) = 0 /* Check if x contains only zeroes */
    else
        x | f(*l+x) /* Call f again, with x appended to l */
    done
}

```

# Answer
> 1 votes
# 05AB1E, 13 bytes

Returns **1** if it ends in zeroes and **0** otherwise.

```
Z¹g*F¤¸ì¥Ä}_P

```

Try it online!

**Explanation**

Uses the upper bound of rounds: `max(input)*len(input)` explained by *xnor* in the comment section.

```
Z              # get max(input)
 ¹g            # get length of input
   *           # multiply
    F          # that many times do:
     ¤         # get the last value of the current list (originally input)
      ¸        # wrap it
       ì       # prepend to the list
        ¥      # calculate deltas
         Ä     # calculate absolute values
          }    # end loop
           _   # negate each (turns 0 into 1 and everything else to 0)
            P  # calculate product

```

# Answer
> 1 votes
## J, 22 bytes

Returns `0` (which is effectively `false` in J) for a degenerate game ending in all zeros. Returns `1` (`true`) if the nth iteration contains a non-zero number, where n is equal to the largest integer in the original sequence multiplied by the length of the list. See Greg Martin's answer explaining why this is true.

```
*>./|&(-1&|.)^:(#*>./)

```

Translation:

* What is the sign `*`
* of the greatest value `>./`
* when you iterate the following as many times as `^:( )`
* the length of the list `#` multiplied by `*` the greatest value in the list `>./`:
    + take the absolute value `|&` of
    + the difference between the list `(- )` and
    + the list rotated by one `1&|.`

Examples:

```
   *>./|&(-1&|.)^:(#*>./) 1 1 0
1
   *>./|&(-1&|.)^:(#*>./) 42 42 41
1
   *>./|&(-1&|.)^:(#*>./) 3 4 5 8
0
   *>./|&(-1&|.)^:(#*>./) 0 0 0 0 0 0 0 0 0 0 0 0 0 1 2 1
0

```

# Answer
> 1 votes
# PHP, 123 115

```
for($a=$_GET,$b=[];!in_array($a,$b);){$b[]=$c=$a;$c[]=$c[0];foreach($a as$d=>&$e)$e=abs($e-$c[$d+1]);}echo!max($a);

```

taking input via HTTP get e.g. `?3&4&5&8` saves a few bytes.

Prints 1 if it reaches all zeros or nothing otherwise.

---

```
for($e=$argv,$r=[];!in_array($e,$r);$q=$e[0]){$e[0]=end($e);$r[]=$e;foreach($e as$k=>&$q)$q=abs($q-$e[$k+1]);}echo!max($e);

```

takes the list of arguments via command line. I've got the feeling this can be golfed even further (looking at @Titus).

# Answer
> 1 votes
# Python 3.6, 101 bytes

```
def f(t):
 x={}
 while x.get(t,1):x[t]=0;t=(*(abs(a-b)for a,b in zip(t,t[1:]+t[:1])),)
 return any(t)

```

Takes a tuple of numbers and returns False if it ends in zeros and True if it loops.

# Answer
> 0 votes
## JavaScript (ES6), ~~84~~ 83 bytes

Returns `true` for a game ending in all zeros, `false` otherwise.

```
f=(a,k=a)=>k[b=a.map((n,i)=>Math.abs(n-a[(i||a.length)-1]))]?!+b.join``:f(k[b]=b,k)

```

### Test

```
f=(a,k=a)=>k[b=a.map((n,i)=>Math.abs(n-a[(i||a.length)-1]))]?!+b.join``:f(k[b]=b,k)

console.log(f([3,4,5,8])); // ends in zeros
console.log(f([1,0,1]));   // does not end in zeros
console.log(f([7]));       // ends in zeros
```

---
Tags: code-golf, sequence, arithmetic, game
---


title: Narcissistic loop lengths

text:
# Question
Title: Narcissistic loop lengths
A narcissistic number is a natural number which is equal to the sum of its digits when each digit is taken to the power of the number digits. For example \\$8208 = 8^4 + 2^4 + 0^4 + 8^4\\$, so is narcissistic.

We'll define a function \\$f(x)\\$ as the following, for a natural number \\$x = d\_1d\_2\dots d\_n\\$, where \\$d\_i\\$ is a single digit \\$0\\$ to \\$9\\$ (therefore \\$x\\$ has \\$n\\$ digits):

$$f(x) = \sum\_{i=1}^nd\_i^n$$

In this case, a number is narcissistic if \\$f(x) = x\\$.

However, when we apply \\$f(x)\\$ to a number repeatedly, we find an interesting pattern emerges. For any given \\$x\\$, the sequence either reaches a fixed point (i.e. a narcissistic number), or enters a fixed loop which repeats infinitely. For examples, take the three integers \\$x = 104, 127, 370\\$:

* \\$x = 104\\$: Repeated application of \\$f(x)\\$ leads to the following chain

$$104, 65, 61, 37, 58, 89, 145, 190, 730, 370, 370, ...$$

Here, the loop eventually reaches a fixed point, \\$370\\$.
* \\$x = 127\\$: Repeated application of \\$f(x)\\$ leads to

$$127, 352, 160, 217, 352, 160, 217, ...$$

Here, the triple \\$352, 160, 217\\$ repeats ad infinitum
* \\$x = 370\\$: \\$x\\$ here is already narcissistic, so the chain will just be an endless stream of \\$370\\$s.

These examples document the two possible outcomes for a given \\$x\\$. By treating a fixed point as a loop of length \\$1\\$, we now arrive at the task at hand:

Given a natural number \\$n \> 0\\$, output the length of the loop that arises through repeated application of \\$f(n)\\$.

The above three examples return \\$1\\$, \\$3\\$ and \\$1\\$ respectively. You can assume that all \\$n\\$ eventually enter a loop, which appears to be the case for at least all \\$n \< 10^4\\$. If there exists an \\$n\\$ for which this is false, your program may do anything short of summoning Cthulhu.

This is so the shortest code in bytes wins.

The vast majority of numbers return \\$1\\$. However, these two arrays contain all \\$n \< 1000\\$ which don't, along with what their outputs should be:

```
[ 59,  95, 106, 115, 127, 136, 138, 147, 149, 151, 157, 159, 160, 163, 168, 169, 172, 174, 175, 177, 178, 179, 183, 186, 187, 189, 194, 195, 196, 197, 198, 199, 217, 228, 229, 235, 238, 244, 245, 253, 254, 255, 258, 259, 267, 268, 271, 276, 277, 279, 282, 283, 285, 286, 289, 292, 295, 297, 298, 299, 309, 316, 318, 325, 328, 335, 352, 353, 355, 357, 358, 361, 366, 367, 369, 375, 376, 381, 382, 385, 388, 389, 390, 396, 398, 405, 408, 417, 419, 424, 425, 442, 445, 447, 450, 452, 454, 456, 457, 459, 465, 466, 468, 469, 471, 474, 475, 477, 478, 479, 480, 486, 487, 488, 491, 495, 496, 497, 499, 504, 507, 508, 511, 517, 519, 523, 524, 525, 528, 529, 532, 533, 535, 537, 538, 540, 542, 544, 546, 547, 549, 552, 553, 555, 556, 558, 559, 564, 565, 567, 568, 570, 571, 573, 574, 576, 580, 582, 583, 585, 586, 589, 591, 592, 594, 595, 598, 601, 607, 609, 610, 613, 618, 619, 627, 628, 631, 636, 637, 639, 645, 646, 648, 649, 654, 655, 657, 658, 663, 664, 666, 669, 670, 672, 673, 675, 678, 679, 681, 682, 684, 685, 687, 689, 690, 691, 693, 694, 696, 697, 698, 699, 705, 706, 708, 712, 714, 715, 717, 718, 719, 721, 726, 727, 729, 735, 736, 741, 744, 745, 747, 748, 749, 750, 751, 753, 754, 756, 760, 762, 763, 765, 768, 769, 771, 772, 774, 777, 778, 779, 780, 781, 784, 786, 787, 788, 791, 792, 794, 796, 797, 799, 804, 805, 807, 813, 816, 817, 819, 822, 823, 825, 826, 829, 831, 832, 835, 838, 839, 840, 846, 847, 848, 850, 852, 853, 855, 856, 859, 861, 862, 864, 865, 867, 869, 870, 871, 874, 876, 877, 878, 883, 884, 887, 891, 892, 893, 895, 896, 900, 903, 906, 914, 915, 916, 917, 918, 919, 922, 925, 927, 928, 929, 930, 936, 938, 941, 945, 946, 947, 949, 951, 952, 954, 955, 958, 960, 961, 963, 964, 966, 967, 968, 969, 971, 972, 974, 976, 977, 979, 981, 982, 983, 985, 986, 991, 992, 994, 996, 997, 999]
[  3,   3,   3,   3,   3,   2,  10,  14,  10,   3,  10,  14,   3,   2,  14,  10,   3,  14,  10,   2,  10,   2,  10,  14,  10,  10,  10,  14,  10,   2,  10,  10,   3,  10,   3,   3,   3,   2,   2,   3,   2,  10,  10,  10,  14,  10,   3,  14,  10,  14,  10,   3,  10,  10,  10,   3,  10,  14,  10,  10,  14,   2,  10,   3,   3,   2,   3,   2,  10,  10,  10,   2,  10,  10,  14,  10,  10,  10,   3,  10,  14,   6,  14,  14,   6,  10,  14,  14,  10,   2,   2,   2,   3,  14,  10,   2,   3,  10,   3,  10,  10,  10,  14,  10,  14,  14,   3,  14,  10,  10,  14,  14,  10,  10,  10,  10,  10,  10,  10,  10,  14,  10,   3,  10,  14,   3,   2,  10,  10,  10,   3,   2,  10,  10,  10,  10,   2,   3,  10,   3,  10,  10,  10,  10,  10,  14,   3,  10,  10,  14,  10,  14,  10,  10,   3,  14,  10,  10,  10,  14,  10,  10,  14,  10,  10,   3,  10,   3,   3,  10,   3,   2,  14,  10,  14,  10,   2,  10,  10,  14,  10,  10,  14,  10,  10,  10,  14,  10,  10,  10,  14,  10,   3,  14,  10,  14,   2,  10,  14,  10,  14,  10,   2,   6,  10,  10,  14,  10,  10,  10,   6,   2,  14,   3,  14,   3,  14,  10,   2,  10,   2,   3,  14,  10,  14,  10,  10,  14,  14,   3,  14,  10,  10,  14,  10,  10,   3,  14,   3,  14,  10,  14,   2,  10,   2,  10,  14,   6,  14,  14,  14,  10,  10,   2,  14,  14,   2,  14,  10,  10,  14,   3,  14,  10,  14,  10,  14,  10,  10,  10,   3,  10,  10,  10,  10,   3,  10,  14,   6,  14,  14,  10,  10,  10,  10,  10,  14,  10,  10,  14,  10,  14,  10,   2,   6,  14,  10,  10,   2,  14,  14,  14,  10,  14,  10,  10,   6,  10,   6,  14,  14,  10,  10,  14,  10,   2,  10,  10,   3,  10,  14,  10,  10,  14,  14,   6,  10,  10,  10,  10,  10,  14,  10,  10,   3,  10,  10,  10,  14,  10,  10,  10,   6,   2,   2,  14,  10,  10,  14,   3,  10,  10,   6,  10,   6,  10,  10,  10,   2,   3,  2]

```

Furthermore, this is a program which takes an integer \\$n\\$ and, for each integer \\$1 \le i \le n\\$, generates it's output and the loop that arises.

This is a question over on Math.SE about whether the output ever exceeds \\$14\\$, and if each natural number will eventually go into a loop or not.

# Answer
# Haskell, 85 bytes

```
l=length
k?x|elem x k=l$x:takeWhile(/=x)k|q<-show x=(x:k)?sum[read[k]^l q|k<-q]
([]?)

```

Try it online!

This is frustratingly long for Haskell. We have one main function here. It keeps track of a list `k` of numbers we already visited, appending new numbers to the front. Once we reach a number `x` which is on our list we return one more than the largest prefix not containing `x`.

```
k ? x
  | elem x k
  =
    length (x : takeWhile (/=x) k)
  | otherwise
  =
    (x : k) ? sum [ read [x] ^ length (show x) | k <- show x ]

```
> 10 votes

# Answer
# Python 3, ~~107~~ \\$\cdots\\$ ~~90~~ 84 bytes

Saved a byte thanks to Arnauld!!!

```
f=lambda n,l=[]:n in l and-~l.index(n)or f(str(sum(int(d)**len(n)for d in n)),[n]+l)

```

Try it online!

Expects input as a string.
> 7 votes

# Answer
# Jelly, 12 bytes

I wonder if this is the same as caird's answer (it probably isn't, because the control flow here almost certainly can be simplified by anyone who actually *knows* Jelly, or perhaps even by a good lossless compression utility). This may also be wrong.

```
D*L$S
ÇÐLÇƬL

```

Try it online!
> 6 votes

# Answer
# Raku, ~~67~~ ~~65~~ 64 bytes

```
{{$_-1-.first(:k,.tail)}($_,{sum .comb X**.chars}...{%\{$_}++})}

```

Try it online!

* `$_, { ... } ... { ... }` generates the sequence of numbers, starting with `$_`, the argument to the outer function. The first braces enclose the function that generates successive elements, and the second braces enclose the function that indicates when to stop.
* `sum .comb X** .chars` produces the next number from the preceding one. The `comb` method with no arguments splits strings/numbers into their characters/digits. The `chars` method returns the number of characters/digits in a string/number. The list of digits is cross-exponentiated with the number of digits by the `X**` operator, then summed.
* The ending condition uses an anonymous state hash variable `%`, which stores the number of times each element has been seen so far. The iteration stops when the current number has been seen for a second time.
* That sequence is fed into an inner anonymous function, which is called immediately. (This is a bit shorter than storing the sequence into a variable.) Just like the outer function, this inner function accepts its argument in the `$_` variable.
* `.first(:k, .tail)` finds the index (thanks to the `:k` adverb) of the first element of the sequence which is equal to the final element, returned by `.tail`.
* `$_ - 1 - .first(...)` is the length of the sequence, minus one, minus the first index of the single repeated element, giving the length of the final cycle.
> 6 votes

# Answer
# Wolfram Language (Mathematica), ~~78~~ 73 bytes

-5 thanks to J42161217. His answer is better, so check that out too.

```
#[]//.a_@e___/;a!=e:>a~Tr[#^#2&@@RealDigits@a]~e/.a_@e__:>{e}~Position~a&

```

Try it online!
> 6 votes

# Answer
# Husk, 12 bytes

```
LUṠ-U¡λṁ^L¹d

```

Try it online!

Found a better way to do it by removing the longest unique prefix from the infinite list, and taking the longest unique prefix of that.

# Husk, 14 bytes

```
▼mLUmUṫ¡λṁ^L¹d

```

Try it online!

Basically, we make an infinite list of infinite lists in order to find which one contains the required cycle. Then we take the length of the cycle.

## Explanation

```
▼mLUmUṫ¡λṁ^L¹d
       ¡λ      apply the following to get an infinite list
             d take the digits
          ^L¹  the the power of their length
         ṁ     sum them
      ṫ        get the postfixes of the list
    mU         get the logest unique prefix of each postfix
   U           get the longest unique prefix of that
 mL            Map each cycle to it's lenght
▼              take the minimum

```
> 5 votes

# Answer
# C (gcc), ~~202~~ ... 149 bytes

```
f(l){long a[16]={},i,k=l,n;for(;i=k;a[n++&15]=k){for(l=0;k;k/=10)l++;for(;i;i/=10)k+=__builtin_powi(i%10,l);for(l=16;l--;)if(a[l]==k)return n-l&15;}}

```

Try it online!

## Explained

```
f(l) {
    long a[16] = {}, // Circular buffer of recently seen values
         i,          // Current value, will be initialized to l,
                     //  l will become number of digits in i,
                     //  and will later be used as a loop counter
         k = l,      // Will become f(i)
         n;          // Current index into the circular buffer

    for (; i = k;                     // Loop forever, let i = f(i)
                  a[n++ & 15] = k) {  // Store f(i) in the buffer

        for (l = 0; k; k /= 10)       // Set length to zero, loop over all digits in k (which is equal to i)
            l++;                      // Increment l for each digit
                                      // k is zero after this loop

        for (; i; i /= 10)            // Loop over all digits again
            k += __builtin_powi(i % 10, l); // Add pow(digit, length) to k

        for (l = 16; l--;)            // Check all the values in the buffer
            if (a[l] == k)            // If k matches a value in the buffer
                return n - l & 15;    // Return the distance between k and the match in the buffer
    }
}

```
> 5 votes

# Answer
# Wolfram Language (Mathematica), ~~70~~ 59 bytes

```
Gather@NestList[Tr[#^#2&@@RealDigits@#]&,#,#]~Count~{_,__}&

```

Try it online!

-11 bytes from @att
> 5 votes

# Answer
# Charcoal, 27 bytes

```
ＮθＷ¬№υθ«⊞υθ≔ΣＸ↨θχＬθθ»Ｉ⊕⌕⮌υθ

```

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

```
Ｎθ

```

Input `n`.

```
Ｗ¬№υθ«

```

Repeat until a loop is detected.

```
⊞υθ

```

Save the previous value.

```
≔ΣＸ↨θχＬθθ

```

Compute the next value.

```
»Ｉ⊕⌕⮌υθ

```

Output the number of terms in the loop.
> 4 votes

# Answer
# JavaScript (ES7), 72 bytes

Expects the input number as a string.

```
n=>(g=i=>i-g[[...n].map(d=>t+=d**n.length,t=0)|t]||g(-~i,g[n=t+'']=i))``

```

Try it online!

### Commented

```
n => (                   // n = input number as a string
  g = i =>               // g is a recursive function taking a counter i
    i -                  // subtract from i
    g[                   // lookup in g:
      [...n].map(d =>    //   for each digit d in n:
        t +=             //     add to t:
          d ** n.length, //       d raised to the power of the length of n
        t = 0            //     starting with t = 0
      ) | t              //   end of map(); yield t
    ]                    // end of lookup in g
    ||                   // if the above result is NaN,
    g(                   // do a recursive call:
      -~i,               //   pass i + 1
      g[n = t + ''] = i  //   copy t to n, coerced back to a string
                         //   and set this entry to i in g
    )                    // end of recursive call
)``                      // initial call to g with i zero'ish

```
> 4 votes

# Answer
# Brachylog, 27 bytes

```
{tgjlᵗgᵗz^ᵐ+}ᵃ↖N{¬≠&}↔a↰₄bl

```

Try it online!

```
{tgjlᵗgᵗz^ᵐ+}ᵃ↖N{¬≠&}↔a↰₄bl
{           }ᵃ↖N            repeat the predicate N times
                             and accumulate results
 tg                         last result as list [x]
   jlᵗgᵗ                    [x, [len(x)]]
        z^ᵐ                 each digit ^ length
           +                sum
                {¬≠&}       must have duplicates (not all are different)
                     ↔a     reverse and take prefixes (shortest first)
                       ↰₄   that must have duplicates
                         bl length - 1

```
> 4 votes

# Answer
# MATL, 19 bytes

```
`XIvIFYAtn^syy-]=Pf

```

Try it online! Or plot the sequence from `50` to `170` (it takes about 30 seconds).

### Explanation

```
`         % Do...while
  XI      %   Copy into clipboard I. This implicitly takes input the first time
  v       %   Concatenate stack contents vertically. This attaches the newly computed
          %   term onto the sequence. The first time it does nothing
  I       %   Paste from clipboard I. This pushes the last computed term
  FYA     %   Convert number to vector of decimal digits
  tn^s    %   Duplicate, number of elements, element-wise power, sum. This computes a
          %   new term to extend the sequence
  yy      %   Duplicate top two elements in the stack: sequence so far and new term
  -       %   Element-wise difference. This is truthy if all values are nonzero
]         % End. A new iteration is run if top of the stack is truthy
=         % (The stack contains the computed sequence and a new term that has been
          % found to appears in that sequence) Element-wise equality comparison
P         % Reverse
f         % index of true value. Implicitly display

```
> 4 votes

# Answer
# Jelly, 11 bytes

```
D*L$SƊƬ⁺€ṪL

```

Try it online!

```
D              Take the decimal digits
 *             to the power of
  L            the length of
   $           the list of decimal digits
    S          and sum them.
     Ɗ         For all that,
      Ƭ        iterate until a loop is reached collecting all intermediate results,
        €      then for each of the collected results
       ⁺       iterate again starting from there,
         Ṫ     take the results from the last result,
          L    and get the length of that.

```

Can be even shorter if we take input as a digit list:

# Jelly, 10 bytes

```
*LSDƲƬ⁺€ṪL

```

Try it online!
> 4 votes

# Answer
# Jelly, 11 bytes

Turns out I got the same as Unrelated String.

```
D*L$SƊƬ⁺€ṪL

```

A monadic Link accepting a positive integer which yields a positive integer.

**Try it online!**

### How?

```
D*L$SƊƬ⁺€ṪL - Link: n
      Ƭ     - collect while distinct:
     Ɗ      -   last three links as a monad:
D           -     digits
   $        -     last two links as a monad:
  L         -       length
 *          -       exponentiate
    S       -     sum
        €   - for each:
       ⁺    -   repeat the last link (the collect-while-distinct, above)
         Ṫ  - tail (this will be a single loop)
          L - length

```
> 4 votes

# Answer
# 05AB1E, 15 bytes

```
Δ¤SDgmO©ªÙ}R®k>

```

Try it online!

Takes input as a singleton list containing the integer.

A different approach that comes in at 16 bytes:

```
λSDgmO}ηíεćk}Ù¥н

```

Try it online!

**Commented**:

```
Δ¤SDgmO©ªÙ}R®k>   # implicit input: [x]
Δ         }       # run until the output does not change:
 ¤                #   take the last integer from the list
  S               #   split into digits
   D              #   duplicate
    g             #   take the length of the copy
     m            #   take each digit to the power of the length
      O           #   sum all powers
       ©          #   store this value in the register
        ª         #   and append it to the list
         Ù        #   uniquify the list
                  #   the loop only stops if Ù removed the new element,
                  #   which only happens if it was in the list already
           R      # reverse the (unique) list
            ®     # take the last computed value
             k    # find the 0-based index in the list
              >   # and increment it

λSDgmO}ηíεćk}Ù¥н  # implicit input: x
λ     }           # recursively apply the code to the input
                  #   to generate an infinite list
 SDgmO            # same as above
       η          # take the prefixes
        í         # reverse each prefix
         ε  }     # map over the reversed prefixed
          ć       #   extract the first element
           k      #   find its index in the remaining prefix
                  #   this returns -1 if the prefix was unique
                  # this results in [-1, ..., -1, res-1, res-1, ...]
             Ù    # uniquify => [-1, res-1]
                  # while this list is finite, 05ab1e does not know this
              ¥   # take the differences => [(res-1) - (-1)] = [res]
               н  # take the first element => res

```
> 3 votes

# Answer
# APL (dzaima/APL), ~~30~~ 29 bytes

```
{1⊃⍸⌽(⊢/=⊢){+/(⊢*≢)10⊤⍵}⍡⍵⊢⍵}

```

Try it online!

-1 byte using `⎕IO←0`.

Since the length of the cycle never exceeds \\$n\\$, we can loop n times instead of finding a fixed point, then calculate the length of the cycle.

## Explanation

```
{⊃⍸1↓⌽(⊢/=⊢){+/(⊢*≢)10⊤⍵}⍡⍵⊢⍵}
                          ⊢⍵  input integer n
            {          }⍡⍵    apply the following n times, collecting intermediate results:
                    10⊤⍵       get base 10 digits
                (⊢*≢)          raise to the power of length
             +/                and sum
      (⊢/=⊢)                  bit mask of the locations of the last element
   1↓⌽                        reverse and remove first 1
 ⊃⍸                           first index of the last element

```
> 3 votes

# Answer
# Icon, 99 bytes

```
procedure f(n)
t:=table()
i:=1
until\t[n]do{t[n]:=i
(s:=0)+:=!n^*n&\z
n:=s
i+:=1}
return i-t[n]
end

```

Try it online!
> 2 votes

# Answer
# Red, 125 bytes

```
func[n][m: copy #()i: 1	while[not m/:n][put m n i i: i + 1 s: 0
foreach d k: to""n[s:(-48 + d)**(length? k)+ s]n: s]i - m/:n]

```

Try it online!
> 2 votes

# Answer
# , 40 bytes

*-5 by FrownyFrog!*

```
0(i.~~:@|.)(,*/@~:$1#.&(^#)10#.inv{:)^:_

```

Try it online!

### , 45 bytes

```
[:#.~[:~:&.|.(,1#.&(^#)10#.inv{:)^:(*/@~:)^:_

```

Try it online!

* `…^:_` until result does not change:
* `…^:(*/@~:)` if there is no duplicate in the list:
* `10#.inv{:` digits of the last number …
* `1#.&(^#)` powered by their length, summed
* `,` appended to the list.
* `[:~:&.|.` reverse list, get a bitmask of first occurrences in it, reverse back. So `1 2 3 2 3 -> 3 2 3 2 1 -> 1 1 0 0 1 -> 1 0 0 1 1`.
* `[:#.~` count the trailing 1s with mixed base conversion.
> 2 votes

# Answer
# Scala, 117 bytes

Port of Wheat Wizard's Haskell answer.

```
def>(n:Any,k:Seq[_]=Nil):Any=if(k toSet n)1+k.indexOf(n)else>(s"$n".map(d=>math.pow(d-48,s"$n".size).toInt).sum,n+:k)

```

Try it online!

# Scala, 160 bytes

```
Stream.iterate(_){n=>s"$n".map(d=>math.pow(d-48,s"$n".size).toInt).sum}.scanLeft(Seq[Int]())(_:+_).flatMap(_.tails).find(l=>l.size>1&&l.head==l.last).get.size-1

```

Try it online!

A ridiculously long solution, made worse by the fact that Scala doesn't have `**` like Python and other languages do, and `inits` returns the biggest inits first, so we have to use `scanLeft(Seq[Int]())(_:+_)`.
> 2 votes

# Answer
# , 84 bytes

```
x=scan();while(!(y=match(x,F,0))){F=c(x,F);x=sum((x%/%10^((z=nchar(x)):0)%%10)^z)};y

```

Try it online!

**Commented:**

```
x=scan();                               # get input as x
                                        # F is vector that holds values of f(x) so far
                                        # (initialized by default as zero)
while(!(y=match(x,F,0))){               # if x is present in F, get its matching index as y,
                                        # otherwise set y to zero.
                                        # While !y (x not present in F yet):
 F=c(x,F);                              # prepend F with x
 x=sum((x%/%10^((z=nchar(x)):0)%%10)^z) # update x as f(x):
                                        # sum of decimal digits to the power of # digits
};
y                                       # We exit the while loop when F contains x;
                                        # at this point, y gives the index, which is the
                                        # loop length

```
> 2 votes

# Answer
# K (Kona), 42 bytes

```
--/&{x=*|x}{x~?x}{x,_+/{x^'#x}10_vs*|x}/,:

```

Try it online!
> 1 votes

# Answer
# Jelly, 9 bytes

```
D*L$SƊÐḶL

```

Try it online!

I always wondered why `ÐḶ` and `ÐĿ` both existed until this answer made the exact functionality of `ÐḶ` clear.

## How it works

```
D*L$SƊÐḶL - Main link. Takes an integer n on the left
     Ɗ    - Group the previous 3 links into a monad f(n):
D         -   Convert n to digits, D
   $      -   Group the previous 2 links into a monad g(D):
  L       -     Get the length of D
 *        -     Raise each digit to the power of that length
    S     -   Sum
      ÐḶ  - Repeatedly apply f(n) until a value is repeated. Then, apply f(n)
            to that value until it loops, and return the loop formed
        L - Take the length of the loop

```
> 1 votes

---
Tags: code-golf, math, number-theory, integer
---


title: Generalise perfect numbers

text:
# Question
Title: Generalise perfect numbers
Let \\$\sigma(n)\\$ represent the divisor sum of \\$n\\$ and \\$\sigma^m(n)\\$ represent the repeated application of the divisor function \\$m\\$ times.

Perfect numbers are numbers whose divisor sum equals their double or \\$\sigma(n) = 2n\\$. For example, \\$\sigma(6) = 12 = 2\times6\\$

Superperfect numbers are numbers whose twice iterated divisor sum equals their double. For example, \\$\sigma^2(16) = \sigma(\sigma(16)) = \sigma(31) = 32 = 2\times16\\$

\\$m\\$-superperfect numbers are numbers such that \\$\sigma^m(n) = 2n\\$ for \\$m \ge 1\\$. For \\$m \ge 3\\$, there are no such numbers.

\\$(m,k)\\$-perfect numbers are numbers such that \\$\sigma^m(n) = kn\\$. For example, \\$\sigma^3(12) = 120 = 12\times10\\$, so \\$12\\$ is a \\$(3,10)\\$-perfect number.

You are to choose one of the following three tasks to do:

* Take three positive integers \\$n, m, k\\$ and output the \\$n\\$th \\$(m,k)\\$-perfect number (0 or 1 indexed, your choice)
* Take three positive integers \\$n, m, k\\$ and output the first \\$n\\$ \\$(m,k)\\$-perfect numbers
* Take two positive integers \\$m, k\\$ and output all \\$(m,k)\\$-perfect numbers

You may assume that the inputs will never represent an impossible sequence (e.g. \\$m = 5, k = 2\\$) and that the sequences are all infinite in length. You may take input in any convenient method.

Note that methods that count up starting from either \\$m\\$ or \\$k\\$ are not valid, as they fail for \\$(4,4)\\$-perfect numbers, the smallest of which is \\$2\\$ (credit to Carl Schildkraut for finding this)

This is so the shortest code in bytes wins.

---

## Test cases

This lists the first few outputs\\${}^\*\\$ for example inputs of \\$(m, k)\\$

```
m, k -> out
3, 10 -> 12, 156, 32704, ...
2, 2 -> 2, 4, 16, 64, 4096, 65536, ...
1, 2 -> 6, 28, 496, 8128, ...
4, 48 -> 160, 455, 5920, ...
3, 28 -> 4480, ...
3, 16 -> 294, 6882, ...
1, 4 -> 30240, 32760, ...
4, 4 -> 2, ...

```

\\${}^\*\\$: Aka, the outputs I could get from my generating program without timing out on TIO

# Answer
# PowerShell, 95 92 87 bytes

-8 bytes thanks to mazzy!

This takes two parameters, m and k, and calculates all (m,k) perfect numbers (up to the maximum for a 64-bit signed integer).

```
param($m,$k)for(;$n=++$x){1..$m|%{$a=0;1..$n|%{$a+=$_*!($n%$_)};$n=$a}
,$x*!($a-$k*$x)}

```

Try it online!
> 5 votes

# Answer
# 05AB1E, ~~11~~ 10 bytes

-1 byte thanks to Kevin Cruijssen!

Outputs the infinite sequence given \\$m\\$ and \\$k\\$.

```
∞ʒ¹FÑO}y/Q

```

Try it online!

```
∞            # push an infinite list of positice integers
 ʒ           # iterate over the list and keep y if:
  ¹          # push the first input m
   F  }      # iterate m times:
    ÑO       # take sum O of divisors Ñ
             # sigma^m(y)
       y/    # divide by y
         Q   # is this equal to the second input k?
             # sigma^m(y) / y == k

```
> 5 votes

# Answer
# Jelly, 9 bytes

```
1Æs⁴¡÷¥Ƒ#

```

A full program accepting `k m n` which prints a list representation of the first `n` \\$k\\$-\\$m\\$-generalised-perfect-numbers.

**Try it online!**

### How?

```
1Æs⁴¡÷¥Ƒ# - Main Link: k
1       # - count up from j=1 & find the first (3rd argument, n) truthy results of f(j, k):
       Ƒ  -   is (j) invariant under?:
      ¥   -     last two links as a dyad - g(j, k):
    ¡     -       repeated application...
   ⁴      -         ...number of times: 1st argument, m
 Æs       -         ...action: divisor sum
     ÷    -       divide (by k)

```
> 3 votes

# Answer
# Husk, 14 bytes

```
fS=ö/⁰!²t¡oΣḊN

```

Try it online!

Outputs the infinite sequence of (m \[arg1\], k \[arg2\])-perfect numbers. TIO header gets just the first two terms, to avoid timing-out.

```
             N   # from the sequence N of all integers,
f                # output the elements that are truthy with this function:
         ¡o      # construct an infinite list by repeatedly getting
           ΣḊ    # the sum of divisors;
        t        # discard the first element,
      !²         # and get the element at index given by arg1,
    /⁰           # then divide it by arg2,
 S=ö             # and check whether it's equal to the original number

```
> 3 votes

# Answer
# Wolfram Language (Mathematica), 49 bytes

outputs all (m,k)

```
Do[Nest[Tr@*Divisors,n,#]==n#2&&Print@n,{n,∞}]&

```

Try it online!

-3 bytes from @att
> 2 votes

# Answer
# Python 3, ~~139~~ 123 bytes

```
g=lambda n,m:m and g(n+sum(i*(n%i<1)for i in range(1,n)),m-1)or n
f=lambda m,k,n,x=1:n and f(m,k,n-(g(x,m)==k*x),x+1)or x-1

```

Try it online!

Very direct approach, brute-forces for every number and runs until a result is found.
> 2 votes

# Answer
# Scala `-language:postfixOps`, 80 bytes

```
m=>k=>Stream from 2 filter(n=>(n/:1.to(m))((n,_)=>1 to n filter(n%_<1)sum)==k*n)

```

Try it online!

Outputs all (m, k)-perfect numbers. The flag just saves a couple bytes, but why not use it?

```
m=>k=>                     //Curried arguments
  Stream from 2            //Infinite stream of integers starting at 2
    filter(n=>             //Filter every n in the Stream according to this predicate
      k*n==                  //Check if k * n equals
                              //The iterated divisor sum
        (n/:1.to(m))          //Fold left over the range [1..m] starting with n
                              //We don't actually care about the values in [1..m], it's just to repeatedly find the divisor sum
          ((n,_)=>              //Find the divisor sum of the left argument:
            1 to n               //Range [1..n] of possible divisors
              filter(n%_<1)      //Filter the ones that divide n
              sum                //Sum them
          )
  )

```
> 2 votes

# Answer
# Python 2, 94 bytes

Takes two positive integers \\$ m,k \\$ and outputs all \\$(m,k)\\$-perfect numbers.

```
def f(m,k,n=1):
 s=n;exec"i=t=s\nwhile~-i:i-=1;s+=i>>t%i*t\n"*m
 if s==k*n:print n
 f(m,k,n+1)

```

Try it online!

A straightforward implementation of the problem. The one obfuscation used is the `s+=i>>t%i*t`, which is equivalent to `s+=i*(t%i<1)`, or `if t%i<1:s+=i`.
> 2 votes

# Answer
# Stax, 13 bytes

```
ü╩╔◘8┌╜♀ñêP=e

```

Run and debug it

the divisor sum part takes a lot of space due to two byte builtins.

Outputs the sequence for `m,k` infinitely.
> 2 votes

# Answer
# JavaScript (V8), 119 bytes

```
f=(m,k,i=1)=>((g=x=>(s=[...Array(x+1).keys()].reduce((a,b)=>a+(x%b<1)*b),--t?g(s):s))(i,t=m)==k*i&&print(i),f(m,k,i+1))

```

Try it online!
> 2 votes

# Answer
# JavaScript (ES6), 86 bytes

Expects `(m,k,n)` and returns the \\$n\\$th \\$(m,k)\\$-perfect number (1-indexed).

```
(m,k,n)=>{for(i=0;n;n-=s==i*k)for(M=m,s=++i,d=0;d||(j=d=s,M--);)s+=j%--d?0:d;return i}

```

Try it online!
> 2 votes

# Answer
# Haskell, 76 bytes

```
f m k n=take n[r|r<-[1..],r*k==iterate(\a->sum[x|x<-[1..a],a`mod`x==0])r!!m]

```

Try it online!

* returns first n terms
> 2 votes

# Answer
# Charcoal, 43 bytes

```
ＮθＮηＮζ≔¹εＷ‹ⅉθ«≦⊕ε≔εδＦη≔ΣΦ…·¹δ¬﹪δλδ¿⁼δ×εζ⟦Ｉε

```

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

```
ＮθＮηＮζ

```

Input `n`, `m` and `k`.

```
≔¹ε

```

Initialise the loop at one.

```
Ｗ‹ⅉθ«

```

Repeat until `n` values have been output.

```
≦⊕ε

```

Try the next integer.

```
≔εδ

```

Make a copy of it.

```
Ｆη

```

Repeat `m` times...

```
≔ΣΦ…·¹δ¬﹪δλδ

```

... replace the copy with the sum of its divisors.

```
¿⁼δ×εζ

```

If the result is `k` times the loop counter, ...

```
⟦Ｉε

```

Output the loop counter on its own line.
> 1 votes

# Answer
# Japt, ~~18~~ 16 bytes

```
È*V¥_â x}g[X]}iW

```

Try it

```
Prints nth element 1-indexed

1st input(U) = m
2nd input(V) = k
3rd input(W) = n

@ ... }iW   - return W-th number that satisfy Om(n)==kn
_â x}         - sum of divisors
     g[X]     - repeated U times starting with X
         ¥X*V - ==kn ?

```
> 1 votes

# Answer
# Clojure, 112 bytes

```
#(rest(for[i(range):when(=(* %2 i)(nth(iterate(fn[j](apply + j(for[k(range 1 j):when(=(rem j k)0)]k)))i)%1))]i))

```

Try it online!

Anonymous function that returns an infinite lazy sequence of all \\$(m,k)\\$-perfect numbers.

Test suite extracts \\$n\\$ first members of the sequences, albeit a bit fewer than in the task specification in order to fit within a minute on TIO.
> 1 votes

---
Tags: code-golf, math, sequence, number-theory
---