# Rotational Average

Given an input integer n >= 10, output the average of all deduplicated rotations of the integer.

For example, for input 123, the rotations are 123 (no rotation), 231 (one rotation) and 312 (two rotations). The average of those is (123 + 231 + 312) / 3 or 222.

As another example, take 4928. The rotations are 4928, 9284, 2849, and 8492. Taking the average of those four numbers equals 6388.25.

For another example, for input 445445, the deduplicated rotations are 445445, 454454, and 544544, so the output is 481481.

For input 777, there is only one deduplicated rotation, so the output is 777.

## Rules

• If applicable, you can assume that the input/output will fit in your language's native Integer type.
• The input and output can be given by any convenient method.
• Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
• Standard loopholes are forbidden.
• This is so all usual golfing rules apply, and the shortest code (in bytes) wins.
• Can we take input as a list of digits? Apr 16, 2018 at 15:19
• @Dennis Sure, that's fine. Go save some bytes. :p Apr 16, 2018 at 15:23
• Do you have an example where the deduplication actually changes the output ? In your 445445 example, each 3 unique rotation happens twice, so leaving them doesn't change the output. Apr 16, 2018 at 15:26
• @Kaldo No, I wasn't able to (manually) come up with one, but that doesn't mean one doesn't exist, so I left the deduplication rules in place. Apr 16, 2018 at 15:28
• @Kaldo Let d be the number of digits of n and k the smallest positive integer such that rotating n k digits to the left reproduces n. Take q and 0 ≤ r < k such that d = qk + r. Rotating n both d and qk digits to the left must yield n, so r = 0. This means each unique rotation occurs q times, so deduplicating the rotations isn't needed to compute the average. Apr 16, 2018 at 15:38

# Python 3, 38 36 bytes

lambda*n:10**len(n)//9*sum(n)/len(n)


Takes the digits as separate arguments. Thanks to @Rod for suggesting Python 3, saving 2 bytes.

Try it online!

• An additional byte could be saved by switching back to Python 2 and taking an array of floats. Apr 16, 2018 at 15:55
• You don't need to take the digits as separate arguments, a regular old list does just fine Apr 16, 2018 at 20:55

# APL (Dyalog), 9 bytes

10⊥≢⍴+/÷≢


A monadic function taking a vector of digits as an argument.

Try it online!

I take the average of the digits +/÷≢, then repeat it by the length of the input ≢⍴, and finally convert from base 10.

Conceptially, I am taking the sum of the rotations (without carrying):

 4  2  9  8
2  9  8  4
9  8  4  2
+8  4  2  9
-----------
23 23 23 23


This is just 4+2+9+8 repeated 4 times. Then converting from base 10 (which does the carrying for me) and dividing by the length. Although I divide by the length earlier on because it is equivilent and saves bytes.

• That's genial :D
– Leo
Apr 17, 2018 at 22:12
• @Leo FWIW the answers that multiply the average by a rep digit are doing essentially the same thing Apr 18, 2018 at 6:38

# Java 10, 1631377672 71 bytes

n->(Math.pow(10,n.size())-1)/9*n.stream().mapToInt(i->i).sum()/n.size()


-36 bytes thanks to @Nevay.
-61 bytes thanks to @OlivierGrégoire by creating a port of @Dennis' Python 3 answer.
-1 bytes by taking the input as a List of digits instead of String.

Explanation:

Try it online.

n->                                 // Method with String parameter and double return-type
(Math.pow(10,n.size())-1)/9       //  Repunits the same length as the input-size
*n.stream().mapToInt(i->i).sum()  //  multiplied by the sum of digits
/n.size()                         //  divided by the input-size

• 151 bytes: n->{var s=new java.util.HashSet();var r=0d;for(int l=n.length(),x;l-->0;)if(s.add(x=new Integer(n=n.substring(1)+n.charAt(0))))r+=x;return r/s.size();}, stream approach with 137 bytes: n->java.util.stream.IntStream.range(0,n.length()).map(i->new Integer(n.substring(i)+n.substring(0,i))).distinct().average().getAsDouble() Apr 16, 2018 at 19:57
• Use orElse(0) instead of getAsDouble(). Apr 17, 2018 at 7:43
• 69 bytes, based on others' solution. Round using (int) for 5 mote bytes, if needed. Apr 17, 2018 at 7:54
• You don't need to cast as a double: Math.pow already takes care of that. That'll spare you 3 bytes. Apr 17, 2018 at 9:56
• @OlivierGrégoire It will give incorrect results if I do that. The cast to int is used so we can integer-divide by 9 and multiply by the sum of digits. Only then it should a double to get the average. If I remove both (int) and *.1 it will for example output 6388.888... instead of 6388.25 for the input 4928. And if I cast the entire thing or just the .pow to an int instead, it will output 6388. Apr 17, 2018 at 11:12

# Husk, 5 bytes

d´MKA


Try it online!

### Explanation

d´MKA
A  Take the average of the digits
´MK   Replace each element of the original list with the average
d      Join the list to get a number


# Husk, 7 bytes

A§modṙŀ


Try it online!

### Explanation

A§modṙŀ
ŀ  Take the range [1..length(input)]
§m  ṙ   Rotate the input by each element of the range
od    Convert each list of digits to a number
A        Take the average of the list

• For a puzzle, there is at least one 5 byte solution Apr 16, 2018 at 16:53
• @H.PWiz I can't figure it out, could you give out a hint? :P
– Leo
Apr 17, 2018 at 12:01
• @Leo There is no ṙ or ŀ, and the first character (on the left) is not A Apr 17, 2018 at 12:21

# R, 8473 64 bytes

function(D,K=sum(D|1))mean(array(D,K+1:0)[1:K,1:K]%*%10^(K:1-1))


Try it online!

Input as list of digits.

Thanks to MickyT for shaving off 11 bytes! 8 bytes shaved by Dennis' proof that deduplication is unnecessary.

• With a slightly different way to rotate the number for 73 Apr 16, 2018 at 21:13
• @MickyT aaahhh clever use of recycling! Apr 17, 2018 at 16:23
• @MickyT array(D,K+1:0) is shorter than matrix(D,K+1,K) by a byte. May 6, 2018 at 21:31

# Vyxal, 3 bytes

Ṗ⌊ṁ


-2 bytes thanks to @lyxal

Try it online!

Explanation

Ṗ   # Permutations
⌊  # Convert each to an integer
ṁ # Mean

• Try it Online! for 4 bytes, because ṅ vectorises when there's sublists Sep 27, 2022 at 14:23
• @Lyxal Oh yeah I just realised that a few days ago, thanks Sep 28, 2022 at 7:13
• Try it Online! for 3 bytes Sep 28, 2022 at 11:02

# 05AB1E, 9 bytes

vÀD}\OIg/


Try it online!

• v with no y, interesting. Apr 17, 2018 at 15:01
• gFÀD})¨Osg/ was where I was thinking. Apr 17, 2018 at 15:02
• Do you know how to use the .æ = pop a compute permutations by function, usage: .æ<FUNC>} command yet? I don't either, but it seems fit to this. Apr 17, 2018 at 15:02
• @MagicOctopusUrn v without y is the shortest solution I could find to perform the rotation g(input) times. I'm checking the .æ, doesn't seem like it's registering <FUNC>} Apr 17, 2018 at 15:56

# Stax, 6 bytes

ñJä⌠╤►


Run and debug it

This program takes a quote-delimited string as input, and expresses the average as a reduced fraction. e.g. 777/1 It's not necessary to de-duplicate the rotations. It never changes the result.

Unpacked, ungolfed, and commented, it looks like this.

:)  get all character rotations
{em convert strings back to integers
:V  mean - integer inputs means result will be rational


Run this one

# Jelly, 6 5 bytes

ṙJḌÆm


Try it online!

### How it works

ṙJḌÆm  Main link. Argument: A (digit array)

J     Yield the indices of A, i.e., [1, ..., len(A)].
ṙ      Rotate A 1, ..., and len(A) units to the left, yielding a 2D array.
Ḍ    Convert each rotation from decimal to integer.
Æm  Take the arithmetic mean.


# Perl 6, 15 bytes

{.sum/$_*1 x$_}


Try it online!

The average is the digit average applied to each decimal position, so digit average times 111.... 1 x $_ produces a string of 1s which get coerced to strings by the multiply. Takes a list of digits as input. A sequence would require a .cache before the sum, and a number or string input would need a .comb. # Perl 5-lpF, 24 22 bytes #!/usr/bin/perl -lpF$_=1x@F/s/./+$&/g*eval  Try it online! Doing it as a list of digits is only 1 byte shorter and feels like cheating: #!/usr/bin/perl -p$;+=$_}{$_=1x$./$.*$ Try it online! • what's usrt? :P Apr 17, 2018 at 1:40 • @ASCII-only Wait,you don't have your executables in the /usrt directory ? Anyways, fixed. Thanks Apr 17, 2018 at 6:49 # Ruby, 60 bytes ->n{a=b=c=0.0;a,b,c,n=a+n%10,b*10+1,c+1,n/10while n>0;a*b/c}  Try it online! # Wolfram Language (Mathematica), 22 bytes FromDigits[0#+Mean@#]&  Try it online! # Ruby, 33 bytes ->n{10**(k=n.size)/9*n.sum*1.0/k}  Try it online! A port of Dennis's Python 3 answer ### Here's my lame attempt (74 bytes) ->s{a=(1..s.size).map{|i|s.chars.rotate(i).join.to_i}|[];a.sum*1.0/a.size}  Try it online! # JavaScript (Node.js), 43 bytes x=>eval(x.join+)*'1'.repeat(n=x.length)/n  Try it online! Can we take input as a list of digits? – Dennis♦ 7 mins ago @Dennis Sure, that's fine. Go save some bytes. :p – AdmBorkBork 3 mins ago # Japt, 8 bytes Takes input as an array of single digit strings. xpUÊ)÷UÊ  Try it ## Explanation  :Implicit input of array U pUÊ :Repeat each string length of U times x ) :Reduce by addition ÷UÊ :Divide by the length of U  # APL (Dyalog Unicode), 21 14 bytesSBCS +/≢÷⍨⍳∘≢(⍎⌽)¨⊂  Try it online! Tacit prefix function. Takes input as a string. Thanks to Adám for an enlightening 7 byte save. ### How? +/≢÷⍨⍳∘≢(⍎⌽)¨⊂ ⍝ Main fn, example argument '123' ⊂ ⍝ Enclose the argument (turns it into a scalar) ¨ ⍝ Use each of the left arguments to ( ⌽) ⍝ Rotate, then ⍎ ⍝ Convert strings into numbers ⍳∘≢ ⍝ Tally (≢) the argument, then index (⍳) from 1. ⍝ Returns 1 2 3 for a 3 digit argument, and rotates the argument 1, 2, then 3 times. ⍨ ⍝ Use the result as left argument for ÷ ⍝ Divide ≢ ⍝ By the number of rotations +/ ⍝ And sum the results  • :| still can't get used to APL comments Apr 17, 2018 at 1:40 # Python 2, 83 77 bytes def f(a):b={int(a[i:]+a[:i])for i in range(len(a))};print sum(b)/len(b)  EDIT: -6 bytes thanks to @ovs • Apr 17, 2018 at 1:32 # Charcoal, 11 bytes Ｉ∕×ΣθＩ⭆θ1Ｌθ  Try it online! Link is to verbose version of code. Explanation:  θ θ θ Input as a string Σ Sum of digits ⭆ 1 Replace each character with the literal 1 Ｉ Cast to integer × Multiply Ｌ Length ∕ Divide Ｉ Cast to string Implicitly print  # J, 10 bytes 10#.#$+/%#


This is a port of H.PWiz's great APL solution to J.

Takes a list of digits as an argument.

## Explanation:

+/%# the average of the digits (divide % the sum of the digits +/ by their number #)

#\$creates a list of copies of the average according to the number of digits

10#. convert form base 10

Try it online!

# Pari/GP, 34 bytes

Takes input as a list of digits.

n->fromdigits([vecsum(n)|x<-n])/#n


Try it online!

## C++, 218 208 bytes

-10 bytes thanks to Zacharý

#include<set>
#include<cmath>
float a(int m){std::set<int>a;int n=m,t,c=0;for(;n>0;n/=10)++c;for(;n<c;++n){a.insert(m);t=m%10;m=m/10+std::pow(10.f,c-1)*t;}int s=0;for(int v:a){s+=v;}return float(s)/a.size();}


And, to test :

int main() {
printf("%f\n%f\n%f\n%f\n",a(123),a(4928),a(445445),a(777));
}

• You don't need spaces between #include and <, and you can remove the {} around both ++c; and s+=v;. You might be able to move the int s=0 to the beginning with your other variables. May 10, 2018 at 19:08
• Also, I don't think you need the n=0 in the second for loop, as it should have reached 0 by then. m/=10;m+=std::pow(10.f,c-1)*t; => m=m/10+std::pow(10.f,c-1)*t. And wouldn't using int instead of auto work? May 10, 2018 at 19:12
• You can still move int s=0; with your other variables, and do you need the braces around the s+=v;? May 23, 2018 at 12:37
• 168 bytes Jun 16, 2018 at 0:21
• n>0 => n might work. Jun 30, 2018 at 21:25

# 05AB1E, 3 bytes

œÅA


Port of @tybocopperkettle's Vyxal answer, so make sure to upvote him/her as well!

Explanation:

œ    # Get all permutations of the (implicit) input
#  e.g. 123 → ["123","132","213","231","312","321"]
ÅA  # Take the average of this list
#  → 222.0
# (which is output implicitly as result)


# ThunnoE, $$\ 9 \log_{256}(96) \approx \$$ 7.41 bytes

DLzP.ZDAA


Attempt This Online!

Port of Vyxal.

#### Explanation

DLzP.ZDAA  # Implicit input. The E flag keeps it as a string.
DL         # Duplicate and get the length of the input string.
zP       # Permutations of the input with the same length.
.ZD    # Converted to integers from lists of characters.
AA  # Get the average of this list of integers.
# Implicit output.


# TI-Basic, 10 bytes

mean(Ans)int(1/9₁₀^(dim(Ans


Takes input in Ans as a list. Port of Dennis's Python 3 answer.

# Pyth, 12 bytes

csms.<zdlzlz


Probably improvable.

c         lz     Divide by the length of the input:
s               Reduce by +
m     lz       Map over d = [0 ... the length of the input]:
s.<zd         Shift the input d characters to the left and cast to int


Try it here!

• There's a built-in average function o. If you do that and do I/O as lists of digits, you can get it down to 8 bytes.
– user48543
Apr 16, 2018 at 15:30
• Ah, I was taking "If applicable, you can assume that the input/output will fit in your language's native Integer type." to mean that it had to be an integer if taken in as Q.
– RK.
Apr 16, 2018 at 16:21

# J, 23 Bytes

(+/%#)".~.(|."0 1~i.@#)


Takes input as a string

### Explanation

          (|."0 1~i.@#)  | All rotations
~.               | Deduplicate
".                 | Convert each to int
(+/%#)                   | Average


# Matlab, 65 bytes

c=num2str(n);l=nnz(c);mean(str2num(c(mod((1:l)+(0:l-1)'-1,l)+1)))


Gonna work on this, pretty sure it can be done better.

## Clojure, 139 bytes

#(let[n(count %)G(set(apply map list(for[i(range n)](take n(drop i(cycle %))))))](/(apply +(for[g G](read-string(apply str g))))(count G)))


Quite sub-optimal language features for converting sequences of characters to integers.

# dc, 37 bytes

This is a full program, reading input and printing the output:

?1sd[O~rzsadO<x+ldO*1+sd]dsxxOkld*la/p


It works by separating the number into its digits, and multiplying the mean of the digits by the appropriate length repdigit (which is built up in d as we go).

?                               # read input
1sd                            # initialize d=1
[                   ]dsxx   # define and execute recursive macro x:
O~r                        #   remainder and quotient of /10
zsa                     #   a = number of digits
dO<x                 #   recurse if needed
+ldO*1+sd        #   increment repdigit d
Ok         # after executing x, set precision
ld*la/   # multiply by repdigit; divide by a
p  # print the result