title: Maximum Maxima!

text:
# Question
Title: Maximum Maxima!
*Inspired by this question and refined by Luis Mendo.*

## Challenge

Given a 2D matrix of integers, each row has a maximum value. One or more elements of each row will be equal to the maximum value of their respective row. Your goal is to determine which column(s) contain the most entries which are equal to their respective row's maximum value as well as the number of row-wise maxima found in these columns.

## Input

* The input will be a non-empty `M` x `N` matrix (`M` \> 0 and `N` \> 0) in whatever form is well-suited to your language of choice.

## Output

* Your program should return the *index* of each column containing the maximum number of row-wise maxima (either as separate values or a list). Either 0- or 1-based indexing can be used (specify in your description).
* Your program should also return the number of maxima that were present in these columns (a single number).
* The order/format of the output is flexible but should be explained in the text accompanying your answer.

## Additional Information

* All entries in the input matrix will be positive integers.
* If the maximum value of a row is shared by multiple elements in that row, all occurrences of that value count towards their columns' total.
* If multiple columns contain the same number of maxima, you should return a list of *all* columns which had this number of maxima.

## An Example

Consider input

```
 7  93
69  35
77  30

```

Row 1 has maxium 93, which occurs only once, namely at column 2. Row 2: occurs at column 1. Row 3: also at column 1. So the winner column is 1, with 2 maxima. Thus the output will be `[1] [2]`. If we change the input to

```
 7  93
69  35
77  77

```

the output will be `[1 2] [2]`, because both columns have 2 maxima.

## Test Cases

```
input                 =>    output ( [1-based index array], [nMaxima] )
----------------------------------------------
 7  93
69  35                =>    [1], [2]
77  30

 7  93
69  35                =>    [1 2], [2]
77  77

1   2   3   4         =>    [4], [2]
5   6   7   8

16   2   3  13
 5  11  10   8        =>    [1  2  4], [1]
 9   7   6  12

 1   1   1   1        =>    [1  2  3  4], [1]

25   6  13  25        =>    [1  4], [1]

1
2
3                     =>    [1], [4]
4

100                   =>    [1], [1]

```

## Scoring

This is , the shortest code in bytes wins. Tiebreaker goes to the earlier answer.

## Leaderboard

Below is a stack snippet for analyzing all entries.

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

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

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

# Answer
> 3 votes
# Jelly, 9 bytes

```
="Ṁ€SµM,Ṁ

```

Input is a 2D list, output is a pair: a list of 1-based indices and the maximal number of maxima.

Try it online! or verify all test cases.

### How it works

```
="Ṁ€SµM,Ṁ  Main link. Argument: M (matrix)

  Ṁ€       Apply maximum to each row.
="         Zipwith equal; compare the entries of the nth row with its maxmium.
    S      Sum; reduce across columns to count the maxima in each row.
     µ     Begin a new, monadic link. Argument: A (list of maxima)
      M    Yield all indices with maximal value.
        Ṁ  Yield the maximum of A.
       ,   Pair the results to both sides.

```

# Answer
> 4 votes
## J, 27 bytes

```
((I.@:=;])>./)@(+/@:=>./"1)

```

This is a monadic verb, used as follows in the case of the second example:

```
   f =: ((I.@:=;])>./)@(+/@:=>./"1)
   m =: 3 2 $ 7 93 69 35 77 77
   f m
+---+-+
|0 1|1|
+---+-+

```

The output consists of two boxes, and uses 0-based indexing. Try it here!

## Explanation

```
((I.@:=;])>./)@(+/@:=>./"1)  Input is m.
(            )@(          )  Composition: apply right hand side, then left hand side.
                     >./"1   Take maximum of each row of m.
                    =        Replace row maxima by 1 and other values by 0,
                +/@:         then take sum (number of maxima) on each column.
                             The result is the array of number of row maxima in each column.
          >./                Compute the maximum of this array
 (     ;])                   and put it in a box with
  I.@:=                      the indices of those entries that are equal to it.

```

# Answer
> 3 votes
# Pyth, ~~20~~ ~~19~~ 17 bytes

1 byte thanks to @Suever.

1 byte thanks to @Jakube.

```
{MC.MhZrSsxLeSdQ8

```

Test suite.

Output is 0-indexed.

Order is reversed.

### All inputs

```
[[7,93],[69,35],[77,30]]
[[7,93],[69,35],[77,77]]
[[1,2,3,4],[5,6,7,8]]
[[16,2,3,13],[5,11,10,8],[9,7,6,12]]
[[1,1,1,1]]
[[25,6,13,25]]
[[1],[2],[3],[4]]
[[100]]

```

### All outputs

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

[[2], [0, 1]]

[[2], [3]]

[[1], [0, 1, 3]]

[[1], [0, 1, 2, 3]]

[[1], [0, 3]]

[[4], [0]]

[[1], [0]]

```

## How it works

```
{MC.MhZrSsxLeSdQ8

               Q   Yield input.
           L       For each array in input (as d):
            eSd      Yield maximum of d.
          x          Yield the 0-indexed indices of the maximum in d.
         s          Flatten.
        S           Sort.
       r         8  Run-length encoding.
                    Now the array is:
                      [number of maxima in column, index of column]
                      for all the columns
   .MhZ             Yield the sub-arrays whose first element is maximum.
                     The first element of each sub-array
                     is "number of maxima in column".
                     Now the array is:
                       [number of maxima in column, index of column]
                       for all the required columns
  C                 Transpose.
                    Now the array is:
                      [[number of maxima in each column],
                       [index of each required column]]
                    Note that every element in the
                    first sub-array is the same.
{M                  Deduplicate each.

```

# Answer
> 3 votes
# MATL, 17 bytes

```
vH3$X>G=XstX>tb=f

```

The first output is the max number of maxima and the second output is the columns in which this occured (1-based indexing).

**Try it Online!**

**Explanation**

```
v       % Vertically concatenate everything on the stack (nothing), yields []
        % Implicitly grab the input
H       % Push the number 2 to the stack
3$X>    % Compute the maximum value of each row (along the second dimension)
G       % Explicitly grab input again
=       % Compare each row of the input to the row-wise max (automatically broadcasts).
Xs      % Sum the number of matches in each column
t       % Duplicate the array
X>      % Determine the max number of maxima in all columns
t       % Duplicate this value
b=f     % Find the index of the columns which had the maximum number of maxima
        % Implicitly display stack contents

```

# Answer
> 3 votes
# MATL, 17 bytes

```
!tvX>!G=5#fFTT#XM

```

Input is a 2D array, with rows separated by semicolons. So the inputs for the test cases are

```
[7 93; 69 35; 77  30]
[7 93; 69 35; 77  77]
[1 2 3 4; 5 6 7 8]
[16 2 3 13; 5 11 10 8; 9 7 6 12]
[1 1 1 1]
[25 6 13 25]
[1; 2; 3; 4]
[100]

```

Output is: first the maximum amount of maxima, then one or more column indices.

**Try it online!**

### Explanation

This uses a different approach from Suever's answer.

First a matrix of logical values (`true` and `false`) is computed, where `true` indicates the presence of a row-maximum. Then the column indices of the `true` values are extracted into a vector. Finally, the mode of that vector is computed (maximum number of maxima), along with all values that are the most frequent (desired column indices).

```
!        % Implicit input. Transpose
tv       % Duplicate. Concatenate vertically. This forces next function (max)
         % to work along columns even if input is a row vector
X>       % Maximum of each column (gives row vector)
!        % Transpose into column vector
G        % Push input again
=        % Test for equality, with broadcast. Gives matrix of true and false
5#f      % Column indices of true values, as a column vector
FTT#XM   % Mode of that vector, and all values that occur maximum number of times
         % Implicit display

```

# Answer
> 3 votes
# CJam, ~~38~~ ~~35~~ 31 bytes

*2 bytes fewer thanks to @FryAmTheEggMan, with help also from @quartata. Thanks also to @Dennis for removing 4 more bytes.*

```
q~_::e>.f=:.+_:e>_@f{=U):Ua*~}p

```

Input is of the form

```
[[7 93] [69 35] [77 77]]

```

Output is an array of 1-based column indices and a number.

**Try it online!**

# Answer
> 3 votes
# Husk, ~~18~~ ~~16~~ ~~19~~ 16 bytes

```
SṠ·e;¥▲mΣTmṠom=▲

```

Try it online!

Probably my best use of combinators in Husk.

-2 bytes from Jo King.

+3 bytes after satisfying first test case.

-3 bytes from Jo King(again!)

## Explanation

```
§eṠoW=▲o;▲mΣTmṠom=▲
             m      map each row to the following:
              Ṡ     hook: Ṡ f g x = f (g x) x
                m=  map each element of the row by equality
                  ▲ to the maximum of the row
            T       transpose the matrix
          mΣ        map each column to its sum
§                   fork: § f g h x = f (g x) (h x)
 e                  create two element list from:
  Ṡ                 hook: Ṡ f g x = f (g x) x
   oW=              indices of elements wich equal
      ▲             maximum, and:
       o;▲          number of maxima

```

# Answer
> 2 votes
## Pyke, 17 bytes

```
FDSeRmq),AsDSe
R%

```

Try it here!

# Answer
> 2 votes
# Python 2, 106 bytes

```
x=map(sum,zip(*[map(max(r).__eq__,r)for r in input()]))
m=max(x);print[i for i,n in enumerate(x)if n==m],m

```

Input is a 2D list of floats, output is a pair: a list of 0-based indices and an integer.

Test it on Ideone.

# Answer
> 2 votes
# Julia, 54 bytes

```
f(x,m=maximum,t=sum(x.==m(x,2),1))=find(t.==m(t)),m(t)

```

Input is a matrix, output is a pair: a list of 1-based indices and the maximal number of maxima.

Try it online!

# Answer
> 2 votes
# 05AB1E, 14 (or 12) bytes

```
εZQ}øOZ©Qƶ0K®‚

```

Outputs in the format `[[1-indexed columns-list], maxima]`.

Try it online or verify all test cases.

If it's allowed to have items `0` in the columns-list which we ignore, it could be 2 bytes less by removing the `0K`:

Try it online or verify all test cases.

**Explanation:**

```
ε               # Map each row in the (implicit) input-matrix:
 Z              #  Get the maximum of the row (without popping)
  Q             #  Check for each value in this row if its equal to the row-maximum
   }ø           # After the map: zip/transpose the matrix; swapping rows/columns
     O          # Take the sum of each inner list (the truthy/falsey values of the columns)
      Z         # Get the maximum column-sum (without popping)
       ©        # Store it in the register (without popping)
        Q       # Check for each column-sum if its equal to this maximum
         ƶ      # Multiply each truthy/falsey value in the list by its 1-based index
          0K    # Remove all 0s
            ®‚  # Pair the resulting list with the maximum we stored in the register
                # (and output the result implicitly)

```

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

```
a=>[m=Math.max(...a=a[0].map((_,i)=>a.map(a=>c+=a[i]==Math.min(...a),c=0)|c)),[...a.keys()].filter(i=>a[i]==m)]

```

Returns an array of two elements; the first is the maximum count of maxima, the second is the array of zero-indexed columns with that count.

# Answer
> 1 votes
# Octave, ~~47~~ 46 bytes

```
@(r){m=max(s=sum(r==max(r,0,2),1)),find(s==m)}

```

This creates an anonymous function that automatically assigns itself to `ans` and can be run using `ans([1 2 3; 4 5 6])`. It returns a two-element cell array where the first element is the maximum number of maxima and the second is the 1-based index of the columns containing these maxima.

**All test cases**

# Answer
> 1 votes
# Python 3, 142 bytes

The algorithm here is basically, go through each row and increase the score of columns that have the max of that row. Then find the max of the scores and find the columns that have that max score and return them. Columns are 1-indexed. I tried one-lining this into a lambda, but with generating the scores column by column it was 153 bytes.

```
def f(r):
    s=[0]*len(r[0]);e=enumerate
    for x in r:
        for i,j in e(x):
            s[i]+=(0,1)[j==max(x)]
    m=max(s);return[i+1for i,j in e(s)if j==m],m

```

---

## Test Cases

```
x=[[7, 93],
[69, 35],
[77, 30]]

print(f(x)) #=>    [[1], 2]

x=[[ 7, 93],
[69, 35],
[77, 77]]

print(f(x)) #=>    [[1 2], 2]

x=[[1,  2,   3,  4],
[5,  6,  7,  8]]

print(f(x)) #=>    [[4], 2]

x=[[16,  2,  3, 13],
 [5, 11, 10,  8],
 [9,  7, 6, 12]]

print(f(x)) #=>    [[1  2  4], 1]

x=[[1,  1,  1,  1]]

print(f(x)) #=>    [[1  2  3  4], 1]

x=[[25,   6,  13,  25]]

print(f(x)) #=>    [[1  4], 1]

x=[[1],
[2],
[3],
[4]]

print(f(x)) #=>    [[1], 4]

x=[[100]]

print(f(x)) #=>    [[1], 1]

```

# Answer
> 1 votes
## Clojure, 150 bytes

```
(fn[M](let[F(dissoc(frequencies(mapcat(fn[r](map-indexed #(if(=(apply max r)%2)%)r))M))nil)m(apply max(vals F))][(map first(filter #(#{m}(% 1))F))m]))

```

Man that is long, I've got a feeling this could be simplified a lot. At least it produces the correct output.

```
[(f [[ 7  93][69  35][77  30]])
 (f [[ 7  93][69  35][77  77]])
 (f [[16   2   3  13][5  11  10   8][9   7   6  12]])]

[[(0) 2] [(1 0) 2] [(0 1 3) 1]]

```

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


title: Digit sum of powers in bases

text:
# Question
Title: Digit sum of powers in bases
You should write a program or function which outputs or returns the sum of the digits in base `b` representation of the first `n` natural power of `a` in ascending order.

Example for `a = 2`, `b = 3` and `n = 4`

```
The base10 numbers are 2^0, 2^1, 2^2 and 2^3.
Their base3 representations are 1, 2, 11, 22.
The digit sums are 1, 2, 2, 4.
The sorted digit sums are 1, 2, 2, 4 which is the result.

```

## Input

* 3 integers `a > 1`, `b > 1` and`n > 0`

## Output

* A list of integers

## Examples

Input =\> Output

```
2 5 10 => 1 2 4 4 4 4 4 4 8 8
3 2 20 => 1 2 2 3 4 5 6 6 6 8 9 10 11 11 13 14 14 14 15 17
5 6 1 => 1
6 6 11 => 1 1 1 1 1 1 1 1 1 1 1
6 8 20 => 1 6 6 8 8 8 13 13 15 20 22 22 22 27 29 34 34 34 36 41
8 2 10 => 1 1 1 1 1 1 1 1 1 1
15 17 18 => 1 15 17 31 31 33 49 49 63 65 81 95 95 95 95 113 127 129

```

This is code-golf so shortest code wins.

# Answer
> 4 votes
# Pyth, 11

```
Smsj^vzdQvw

```

Note that this requires the inputs separated by newlines in the order a,b,n.

Try it online here

Pyth has built-ins that do each step for us. We `m`ap over each value from `0` to `n-1`, raising `a` to that power. Then we use `j` to convert each of these numbers to base `b`. We `s`um the resulting lists, and the final list of numbers is `S`orted.

The input is read in the order `z`, `Q` then `w`. `z` and `w` have to be `eval`ed in order to be used as numbers.

# Answer
> 6 votes
# CJam, 13 bytes

```
q~,f#\fb::+$p

```

I think this can be improved, but lets get this started.

The input is in the following order : `b a n`

Example input:

```
3 2 4

```

Output:

```
[1 2 2 4]

```

**Code expansion**:

```
q~             "Read the input and parse it. Now we have on stack, b a and n"
  ,            "Get an array from 0 to n-1";
   f#          "Get all the powers of a present in the array, i.e. 0 to n-1";
     \         "Swap the array of a^i and bring the base on top";
      fb       "For each number in the array, convert it into its base representation array";
        ::+    "Calculate the sum of each of the sub arrays in the bigger array";
           $p  "Sort and print the sum of digits of base representation of n powers of a";

```

Try it online here

# Answer
> 3 votes
# JavaScript (ES6) 170 ~~175 196 98 100~~

**Edit** New version, handles bigger numbers using digits array. Score *almost* doubled :-(

Multiplying digit by digit is more difficult, summing the digits is simpler.

```
F=(a,b,n)=>
  (t=>{
    for(r=t;--n;r[n]=s)
      for(k=1,y=t,z=a;z;z=z/b|0)
        t=[...t.map(v=>(v=c+(k?w*~~y[i++]+v:w*v),s+=d=v%b,c=v/b|0,d),
           w=z%b,s=c=0,i=--k),c]
  })([1])||r.sort((a,b)=>a-b)

```

*Less golfed*

```
F=(a, b, n) =>
{
  var r=[1]; // power 0 in position 0

  for(w=[]; w.push(a%b),a=a/b|0; ); // a in base b

  for(t = [1]; --n; )
  {
    // calc next power, meanwhile compute digits sum
    y=[...t]
    k=1
    w.map(w=>
      (t=[...t.map(v=>(
        v = c + (k?w*~~y[i++]+v:w*v),
        d = v % b, // current digit
        s += d, // digits sum
        c = (v-d)/b, // carry
        d)
       ,s=c=0,i=--k),c]
      )
    );
    r[n] = s // store sum in result array (positions n-1..1)
  }
  return r.sort((a,b)=>a-b) // sort result in numeric order
}

```

**My first attempt** using `doubles`, fails for big numbers. JS doubles have 52 mantissa bits when for instance 15^14 needs 55 bits.

```
F=(a,b,n,r=[1])=>(x=>{for(;--n;r[n]=s)for(t=x*=a,s=0;t;t=(t-d)/b)s+=d=t%b})(1)
||r.sort((a,b)=>a-b)

```

*Less golfed*

```
F=(a, b, n) =>
{
  var r=[1]; // power 0 in position 0
  for(x = 1; --n; )
  {
    x *= a; // calc next power starting at 1
    for(t = x, s = 0; t; t = (t-d) / b) // loop to find digits
    {
      d = t % b;
      s += d;
    }
    r[n] = s // store sum in result array (positions n-1..1)
  }
  return r.sort((a,b)=>a-b) // sort result in numeric order
}

```

**Test** In Firefox/FireBug console

```
;[[2,5,10],[3,2,20],[5,6,1],[6,6,11],[6,8,20],[8,2,10],[15,17,18]]
.forEach(t=>console.log(...t,F(...t)))

```

> 2 5 10 \[1, 2, 4, 4, 4, 4, 4, 4, 8, 8\]
> 3 2 20 \[1, 2, 2, 3, 4, 5, 6, 6, 6, 8, 9, 10, 11, 11, 13, 14, 14, 14, 15, 17\]
> 5 6 1 \[1\]
> 6 6 11 \[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1\]
> 6 8 20 \[1, 6, 6, 8, 8, 8, 13, 13, 15, 20, 22, 22, 22, 27, 29, 34, 34, 34, 36, 41\]
> 8 2 10 \[1, 1, 1, 1, 1, 1, 1, 1, 1, 1\]
> 15 17 18 \[1, 15, 17, 31, 31, 33, 49, 49, 63, 65, 81, 95, 95, 95, 95, 113, 127, 129\]

# Answer
> 3 votes
# A purely mathematical equation on the Cartesian Plane, written in LaTeX: Unknown size, incomplete

Demonstrated here: https://www.desmos.com/calculator/svpkyarzxh

`a`, `b`, and `n` are adjustable inputs.

To avoid spaghetti code, it's split into two functions, although it could be condensed.

```
f\left(x\right)=\floor \left(x-\left(b-1\right)\sum _{i=1}^{\log _bx}\floor \left(xb^{-i}\right)\right)
y=f\left(a^{\floor \left(x\right)}\right)\left\{0<x\le n\right\}

```

I'm not sure how to put the values in an adjustable list or sort the list without using an actual programming language. However, the fact that this equation allows you to put it on a programmable graphing calculator and figure out the rest from there. I know it can be done in TI-BASIC, but I'm too busy to put an example here.

# Answer
> 2 votes
# Mathematica, ~~43~~ 41 bytes

```
Sort[Tr/@IntegerDigits[#^Range@#3/#,#2]]&

```

Very straightforward and apart from the slight abuse of `Tr` very readable. This is an unnamed function which is called with the three parameters in order.

Example outputs:

```
f=Sort[Tr/@IntegerDigits[#^Range@#3/#,#2]]&
f[2, 5, 10]
(* {1, 2, 4, 4, 4, 4, 4, 4, 8, 8} *)
f[3, 2, 20]
(* {1, 2, 2, 3, 4, 5, 6, 6, 6, 8, 9, 10, 11, 11, 13, 14, 14, 14, 15, 17} *)
f[5, 6, 1]
(* {1} *)
f[6, 6, 11]
(* {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1} *)
f[6, 8, 20]
(* {1, 6, 6, 8, 8, 8, 13, 13, 15, 20, 22, 22, 22, 27, 29, 34, 34, 34, 36, 41} *)
f[8, 2, 10]
(* {1, 1, 1, 1, 1, 1, 1, 1, 1, 1} *)
f[15, 17, 18]
(* {1, 15, 17, 31, 31, 33, 49, 49, 63, 65, 81, 95, 95, 95, 95, 113, 127, 129} *)

```

Two bytes saved thanks to alephalpha.

# Answer
> 1 votes
## J - 19

```
/:~+/"1#.inv`(^i.)/

```

Takes numbers in that order: b a c

Usage example (x stands for extended precision):

```
   /:~+/"1#.inv`(^i.)/ 5 2 10
1 2 4 4 4 4 4 4 8 8
   /:~+/"1#.inv`(^i.)/ 17 15x 18
1 15 17 31 31 33 49 49 63 65 81 95 95 95 95 113 127 129

```

# Answer
> 1 votes
# APL (Dyalog Unicode), ~~29~~ 24 bytes

```
{(⊂∘⍋⌷⊢)+⌿⍵(⊥⍣¯1)∊*∘⍳/⍺}

```

-5 bytes from Jo King.

Takes inputs as `a n` function `b`.

Try it online!

```
{(⊂∘⍋⌷⊢)+⌿(⊃⌽⍵)(⊥⍣¯1)(⊃⍵)*⍳⍺}

```

Takes inputs as `n` function `a b`

Thanks to Jo King for helping me fix this answer.

Try it online!

## Explanation

```
{(⊂∘⍋⌷⊢)+⌿(⊃⌽⍵)(⊥⍣¯1)(⊃⍵)*⍳⍺} ⍺ → n, ⍵ → [a,b]
                          ⍳⍺  range (1..n)
                     (⊃⍵)*    a to the power of the range
          (⊃⌽⍵)               take b from reverse of ⍵
               (⊥⍣¯1)         inverse encode(decode) using b till it reaches zero
        +⌿                    reduce with addition along non-leading axis
                              i.e: sum the columns
 (⊂∘⍋⌷⊢)                      tacit fn:
    ⍋                         Get indices for ascending order
     ⌷                        Get elements at those indices
      ⊢                       From the right arg
  ⊂                           Enclose it

```

# Answer
> 0 votes
# Haskell, 79 bytes

```
import Data.Digits
import Data.List
f a b n=sort$map(sum.digits b.(a^))[0..n-1]

```

Usage: `f 6 8 20`, output: `[1,6,6,8,8,8,13,13,15,20,22,22,22,27,29,34,34,34,36,41]`

This is a typical Haskell function: straight forward, same as ungolfed version but the `import`s ruin the golf score: for every element e of the list from `0` to `n-1` calculate `a^e`, convert to a list of base `b` digits and `sum` it. `Sort` the resulting list.

# Answer
> 0 votes
# Jelly, 7 bytes

```
Ḷ*@b⁵§Ṣ

```

Try it online!

Takes input as 3 command line arguments, \\$n\\$, \\$a\\$ then \\$b\\$.

## How it works

```
Ḷ*@b⁵§Ṣ - Main link. n on the left, a on the right and b as the 3rd argument
Ḷ       - Range [0, 1, ..., n-1]
 *@     - Take a to the power of each [1, a, ..., a^(n-1)]
    ⁵   - Yield b
   b    - Convert each power to base b
     §  - Take the digit sums of each
      Ṣ - Sort the digit sums

```

# Answer
> 0 votes
# Husk, 13 bytes

```
OmoΣB²`z^R¹⁴ŀ

```

Try it online!

## Explanation

```
OmoΣB²`z^R¹⁴ŀ
            ŀ range from 0..n-1
         R¹⁴  a replicated n times
      `z^     zip both with power
 moΣB²        convert each power to base n, and sum digits
O             Sort in ascending order

```

---
Tags: code-golf, math, number, base-conversion
---


title: All about basic binary

text:
# Question
Title: All about basic binary
Please excuse the punny title.

This is a question is inspired by A Curious Property of 82000. In it, the author points out that the number 82000 is binary in base 2, 3, 4, and 5. The post then poses the question "is there a number that is binary in bases 2, 3, 4, 5, and 6"? (For those curious, I've checked values up to 10^1,000,000 and so far the answer is no.)

This got me thinking: given a number, what bases *is* it binary in?

Our curious number, 82000, is actually binary in six bases:

```
Base 2 = 10100000001010000
Base 3 = 11011111001
Base 4 = 110001100
Base 5 = 10111000
Base 81999 = 11
Base 82000 = 10

```

Not all numbers will have binary bases that are sequential. Consider the number 83521. It's binary in bases 2, 17, 289, 83520, and 83521.

Your challenge is to determine and display which bases a number is binary in.

# Rules

* A number is considered "binary" in a given base if its representation in that base consists of only zeroes and ones. `110110` is a binary value, while `12345` is not, `A380F` is definitely not.
* Your number will be provided on standard input. It will be an integer value between 2 and 2^32-1 inclusive and will be provided in base-10 format.
* In ascending order, display each base greater than one that the number is binary in. Each base should be on its own line. If you include the binary value in that base (see the bonus scoring below), separate the base and the binary value with a space. Only output to standard out will be judged, standard error and other sources will be ignored.

# Scoring

Your score is your program's size in bytes. The lower the score, the better.

**Bonus**:
If your program also outputs the binary values in the found bases, multiply your score by 0.75
Your displayed binary value should have no extra punctuation, no extraneous zeroes, no decimal point, just zeroes and ones.

# Examples

Input:

```
82000

```

Output (receives bonus):

```
2 10100000001010000
3 11011111001
4 110001100
5 10111000
81999 11
82000 10

```

Input:

```
1234321

```

Output (no bonus):

```
2
1111
1234320
1234321

```

# Answer
> 14 votes
# Pyth, ~~14~~ 13

```
jbf!-jQTU2tSQ

```

Thanks to Jakube for pointing out the new `S` function.

Try it here.

The online version is too slow to do `1234321`. This simply converts the input to each base from 2 to itself and discards the results that contain values other than 0 and 1.

### Explanation:

```
                           : Q=eval(input) (implicit)
jb                         : join on newlines the list...
  f!                       : filter away nonempty values (impliticly named T)
    -jQTU2                 : sewtise difference of number converted to base and range(2)
     jQT                   : convert Q to base T
        U2                 : range(2)
          tSQ              : over the range [2 Q+1)

```

---

In addition, this is a (~~not well golfed~~ now well golfed, again thanks to Jakube) bonus version (20 * .75 = 15):

```
VQI!-JjQK+2NU2pdKjkJ

```

Try it here

# Answer
> 10 votes
# Julia, ~~72~~ 70 bytes

It's actually longer with the bonus, so no bonus here.

```
n=int(readline());for j=2:n all(i->i∈0:1,digits(n,j))&&println(j)end

```

This reads a line from STDIN, converts it to an integer, and prints the result. Despite being a brute force method, the input 1234321 took less than 1 second for me.

Ungolfed + explanation:

```
# Read n from STDIN and convert to integer
n = int(readline())

# For every potential base from 2 to n
for j = 2:n
    # If all digits of n in base j are 0 or 1
    if all(i -> i ∈ 0:1, digits(n, j))
        # Print the base on its own line
        println(j)
    end
end

```

Examples:

```
julia> n=int(readline());for j=2:n all(i->i∈0:1,digits(n,j))&&println(j)end
1234321
2
1111
1234320
1234321

julia> n=int(readline());for j=2:n all(i->i∈0:1,digits(n,j))&&println(j)end
82000
2
3
4
5
81999
82000

```

**NOTE**: If input can be taken as a function argument rather than from STDIN (awaiting confirmation from the OP), the solution is 55 bytes.

# Answer
> 7 votes
# CJam, 20 bytes (or 27 bytes * 0.75 = 20.25)

Here is the no bonus version, 20 bytes:

```
ri:X,2f+{X\b2,-!},N*

```

Try this here.

Just for fun, here is the bonus version, 27 bytes:

```
ri:X{X\)b2,-!},1>{)SX2$bN}/

```

Try it online here

# Answer
> 7 votes
# Python 2, ~~88 86~~ 80

Fairly straightforward, no bonus. Python is nice and lenient with global variables.

```
N=input();g=lambda n:n<1or(n%b<2)*g(n/b)
for b in range(2,N+1):
 if g(N):print b

```

Best I've managed to get for the bonus is 118\*.75 = **87.75**:

```
N=input();g=lambda n:0**n*" "or" "*(n%b<2)and(g(n/b)+`n%b`)*(g(n/b)>'')
for b in range(2,N+1):
 if g(N):print`b`+g(N)

```

# Answer
> 7 votes
# Mathematica, 59 bytes

```
Print/@Select[1+Range[n=Input[]],Max@IntegerDigits[n,#]<2&]

```

Ugh... `IntegerDigits` D:

There isn't really much to explain about the code... 12 bytes are wasted by the requirement for using STDIN and STDOUT.

I don't think I can claim the bonus. The best I've got is 84 bytes (which yields a score over 60):

```
Print@@@Select[{b=#+1," ",##&@@n~IntegerDigits~b}&/@Range[n=Input[]],Max@##3<2&@@#&]

```

# Answer
> 4 votes
# Python 2, 90 * 0.75 = 67.5

```
n=input();b=1
while b<n:
 b+=1;s="";c=k=n
 while k:s=`k%b`+s;c*=k%b<2;k/=b
 if c:print b,s

```

Pretty straightforward iterative approach.

Without the bonus, this is 73 bytes:

```
n=input();b=1
while b<n:
 b+=1;c=k=n
 while k:c*=k%b<2;k/=b
 if c:print b

```

# Answer
> 4 votes
# SQL (PostgreSQL), ~~247.5~~ ~~255~~ 230.25 (307 * .75)

Since SQL is known to be wonderful at these sorts of challenges, I thought I better put one together :) The bonus was really worthwhile for this one.
It should comply with spec, but I have no easy way to test the COPY I FROM STDIN.
**Edit** Fixed order. Changed the way column R is handled to use an array.

```
CREATE TABLE IF NOT EXISTS I(I INT);TRUNCATE TABLE I;COPY I FROM STDIN;WITH RECURSIVE R AS(SELECT n,I/n I,ARRAY[I%n] R FROM generate_series(2,(SELECT I FROM I))g(n),(SELECT I FROM I)I(I)UNION ALL SELECT n,I/n,I%n||R FROM R WHERE I>0)SELECT n||' '||array_to_string(R,'')FROM R WHERE 2>ALL(R)and i=0ORDER BY n

```

As a test I just used straight inserts into the `I` table. Test run expanded and commented.

```
-- Create the table to accept the input from the copy command
CREATE TABLE IF NOT EXISTS I(I INT);
-- Make sure that it is empty
TRUNCATE TABLE I;
-- Popoulate it with a value from STDIN
--COPY I FROM STDIN;
INSERT INTO I VALUES(82000); -- Testing
--Using a recursive CTE query
WITH RECURSIVE R AS (
    -- Recursive anchor
    SELECT n,                -- base for the row
       I/n I,                -- integer division
       ARRAY[I%n] R   -- put mod value in an array
    FROM generate_series(2,(SELECT I FROM I))g(n), -- series for the bases
         (SELECT I FROM I)I(I) -- Cross joined with I,  saves a few characters
    UNION ALL
    -- for each row from r recursively repeat the division and mod until i is 0
    SELECT n,
        I/n,
        I%n||R -- Append mod to beginning of the array
    FROM R WHERE I>0
    )
-- return from r where i=0 and r has 1's and 0's only
SELECT n||' '||array_to_string(R,'')
FROM R
WHERE 2 > ALL(R)and i=0
ORDER BY n -- Ensure correct order

```

> 2 10100000001010000
> 3 11011111001
> 4 110001100
> 5 10111000
> 81999 11
> 82000 10

# Answer
> 3 votes
# Haskell 109\*0.75 = 81.75 bytes

```
0#x=[]
n#x=n`mod`x:div n x#x
f n=[show x++' ':(n#x>>=show)|x<-[2..n+1],all(<2)$n#x]
p=interact$unlines.f.read

```

Usage example (note: binary values are lsb first):

```
p 82000

2 00001010000000101
3 10011111011
4 001100011
5 00011101
81999 11
82000 01

```

Without input/output restrictions, i.e input via function argument, output in native format via REPL):

### Haskell, 67\*0.75 = 50.25 bytes

```
0#x=[]
n#x=n`mod`x:div n x#x
f n=[(x,n#x)|x<-[2..n+1],all(<2)$n#x]

```

Returns a list of (base,value) pairs. The values are lsb first, e.g. (newlines/spaces added for better display):

```
 f 82000
 [ (2,[0,0,0,0,1,0,1,0,0,0,0,0,0,0,1,0,1]),
   (3,[1,0,0,1,1,1,1,1,0,1,1]),
   (4,[0,0,1,1,0,0,0,1,1]),
   (5,[0,0,0,1,1,1,0,1]),
   (81999,[1,1]),
   (82000,[0,1]) ]

```

# Answer
> 2 votes
# Java, ~~181~~ ~~155.25(207 * .75)~~ 151.5(202 * .75) bytes

```
class I{public static void main(String[]a){a:for(long b=new java.util.Scanner(System.in).nextLong(),c,d=1;d++<b;){String e="";for(c=b;c>0;e=c%d+e,c/=d)if(c%d>1)continue a;System.out.println(d+" "+e);}}}

```

**Expanded with explanation:**

```
class I {
    public static void main(String[]a){
        a:for(long b=new java.util.Scanner(System.in).nextLong(),c,d=1; //b = input(), d = base
              d++<b;) {                                           //For all bases in range(2,b+1)
            String e="";
            for(c = b;c > 0; e = c % d + e,c /= d)                //Test all digits of base-d of b
                           //e = c % d + e                        //Append digits to string
                if (c % d > 1)                                    //Reject base if the digit is greater than 1
                    continue a;
            System.out.println(d+" "+e);                          //Print base and digits.
        }
    }
}

```

**Original (without bonus):**

```
class I{public static void main(String[]a){long b=new java.util.Scanner(System.in).nextLong(),c,d=1;a:for(;d++<b;){c=b;while(c>0){if(c%d>1)continue a;c/=d;}System.out.println(d);}}}

```

3.75 bytes thanks to Ypnypn :)

# Answer
> 2 votes
# R, 111

Probably a lot of room to improve this at the moment

```
i=scan();b=2:i;R=i%%b;I=rep(i,i-1);while(any(I<-I%/%b))R=cbind(I%%b,R);for(x in b)if(all(R[x-1,]<2))cat(x,'\n')

```

Runs with warnings

```
> i=scan();b=2:i;R=i%%b;I=rep(i,i-1);while(any(I<-I%/%b))R=cbind(I%%b,R);for(x in b)if(all(R[x-1,]<2))cat(x,'\n')
1: 82000
2:
Read 1 item
There were 17 warnings (use warnings() to see them)
2
3
4
5
81999
82000
>

```

# Answer
> 2 votes
# R, ~~94~~ ~~83~~ 79

```
n=scan();cat((2:n)[!sapply(2:n,function(x){while(n&n%%x<2)n=n%/%x;n})],sep="\n")

```

Usage:

```
> n=scan();cat((2:n)[!sapply(2:n,function(x){while(n&n%%x<2)n=n%/%x;n})],sep="\n")
1: 82000
2:
Read 1 item
2
3
4
5
81999
82000
> n=scan();cat((2:n)[!sapply(2:n,function(x){while(n&n%%x<2)n=n%/%x;n})],sep="\n")
1: 1234321
2:
Read 1 item
2
1111
1234320
1234321

```

The core of the function is `!sapply(2:n,function(x){while(n&n%%x<2)n=n%/%x;n})` which, for each base x from 2 to n, keep the quotient n/x as long as the remainder is either 0 and 1. It then outputs the result (which is 0 if all remainders were either 1 or 0) and negates it (0 negates to TRUE, everything else negates to FALSE). Thanks to function scope, there is no need to make a dummy variable for n. The resulting vector of booleans is then used to index `2:n` and therefore outputs only the bases for which it worked.

# Answer
> 2 votes
# Jelly, 9 bytes

```
³bṀỊµÐfḊY

```

Try it online!

Done alongside caird coinheringaahing in chat.

## How it works

```
³bṀỊµÐfḊY    Full program.

     Ðf      Filter the implicitly generated range [1, input].
    µ        Starts a new monadic chain.
³b           Convert the input to the base of the current number, as a list.
  Ṁ          Maximum.
   Ị         Insignificant. Checks if abs(Z) ≤ 1.
       Ḋ     Dequeue; Removes the first element of the list (to drop base 1).
        Y    Join by newlines.

```

# Answer
> 2 votes
# APL (Dyalog Extended), 28 bytes, 28 * 0.75 = 21

```
{{⍵⌿⍨∧/2>↑2⌷⍉⍵}(⍪,⊤∘⍵¨)1↓⍳⍵}

```

`1↓⍳⍵` all numbers from 2 to ⍵

`(⍪,⊤∘⍵¨)` each number with the representation of ⍵ in that base

`{⍵⌿⍨∧/2>↑2⌷⍉⍵}` dfn to filter

`↑2⌷⍉⍵` 2nd column as a matrix

`2>` is 2 greater than?

`∧/` boolean and

`⍵⌿⍨` replicate Try it online!

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

```
Input N
For(B,2,N
If prod(seq(BfPart(iPart(N/B^X)/B),X,0,log(N)/log(B))<2
Disp B
End

```

## Explanation

* Input N
* For every B from 2 to N
    + If N is just 0 and 1 in base B
        - Display B
* End loop

## The complicated part

The second line works as follows:

* For every X from 0 to logB N
* B × fPart(iPart(N / BX) / B) is the Nth digit in base B, counting backwards
* Consider this as a list
* For each element, if the digit is less than 2, yield 1 (true), else 0 (false)
* Take the product: 1 iff all elements are 1

## Note

The program runs significantly faster if a closing parenthesis `)` is placed at the end of the second line. See here for more about this.

# Answer
> 1 votes
# TI-BASIC, ~~31~~ 29

```
For(B,2,Ans
If 2>round(Bmax(fPart(Ans/B^randIntNoRep(1,32
Disp B
End

```

This is probably optimal for TI-BASIC.

Explanation:

`randIntNoRep(1,32)` returns a random permutation of the numbers from 1 to 32 (All we need is those numbers in some order; TI-BASIC doesn't have anything like APL's iota command). 32 elements is enough because the smallest possible base is 2 and the largest number is 2^32-1. `B^randIntNoRep(1,31)` raises that list to the Bth power, which results in the list containing all of `B^1,B^2,...,B^32` (in some order).

Then the input (in the `Ans`wer variable, which is input to in the form `[number]:[program name]`) is divided by that number. If your input is 42 and the base is 2, the result will be the list `21,10.5,5.25,...,42/32,42/64,[lots of numbers less than 1/2]`, again in some order.

Taking the fractional part and multiplying the number by your base gives the digit at that position in the base-b representation. If all digits are less than 2, then the greatest digit will be less than 2.

As Ypnypn stated, a closing parenthesis on the `For` statement speeds this up due to a parser bug.

31-\>31: Saved a byte but fixed rounding errors which added the byte again.

31-\>29: Saved two bytes by using `RandIntNoRep()` instead of `cumSum(binomcdf())`.

# Answer
> 0 votes
## Javascript, ES6, ~~118\*.75 = 88.5~~ 110\*.75 = 82.5

```
f=x=>{res={};for(b=2;b<=x;++b)if(!+(res[b]=(c=x=>x%b<2?x?c(x/b|0)+""+x%b:"":"*")(x)))delete res[b];return res}

```

Previous version:

```
f=x=>{res={};for(q=2;q<=x;++q)if(!+(res[q]=(c=(x,b)=>x%b<2?x?c(x/b|0,b)+""+x%b:"":"*")(x,q)))delete res[q];return res}

```

Check:

```
f(82000)
Object { 2: "10100000001010000", 3: "11011111001", 4: "110001100", 5: "10111000", 81999: "11", 82000: "10" }

```

# Answer
> 0 votes
# JavaScript (*ES6*) 65

68 bytes for a function with a parameter and console output.

```
f=n=>{s=n=>n%b>1||b<n&&s(n/b|0);for(b=1;b++<n;)s(n)||console.log(b)}

```

65 bytes with I/O via popup

```
n=prompt(s=n=>n%b>1||b<n&&s(n/b|0));for(b=1;b++<n;)s(n)||alert(b)

```

Claiming the bonus: 88\*0.75 =\> 66

```
n=prompt(s=n=>n%b>1?9:(b<=n?s(n/b|0):'')+n%b);for(b=1;b++<n;)s(n)<'9'&&alert(b+' '+s(n))

```

# Answer
> 0 votes
## Mathematica, 76 * 0.75 = 57

```
n=Input[];G=#~IntegerDigits~b&;If[Max@G@n<2,Print[b," ",Row@G@n]]~Do~{b,2,n}

```

Initially forgot about the input requirements... Fortunately, those didn't add too much extra.

# Answer
> 0 votes
# Ruby, 44 bytes

```
->n{(2..n).select{|i|n.digits(i)-[0,1]==[]}}

```

Try it online!

# Answer
> 0 votes
# Perl 5, 63 bytes

```
map{$t=$n;1while($f=$t%$_<2)&&($t=int$t/$_);say if$f}2..($n=<>)

```

Try it online!

No bonus on this because it scores very slightly better than my version with the bonus:

# Perl 5, 85 bytes * 0.75 = 63.75

```
map{my$r;$t=$n;$r=$/.$r while($/=$t%$_)<2&&($t=int$t/$_);say"$_ 1$r"if$/<2}2..($n=<>)

```

Try it online!

# Answer
> 0 votes
# Husk, ~~11~~ 10 bytes

```
¶tfoΛε`B¹ḣ

```

Try it online!

-1 byte from Zgarb.

## Explanation

```
¶tfoΛ<2`B¹ḣ
          ḣ list from 1..n
  f         filter based on the result of the following
   o        composition of 2 functions
       `B¹  the input in base n as digits
    Λ<2     are all digits < 2?
 t          remove first element
¶           join with newlines

```

# Answer
> 0 votes
# Japt `-R`, 11 bytes

```
õ2 f@ìX e§1

```

Try it

```
õ2 f@ìX e§1     :Implicit input of integer U
õ2              :Range [2,U]
   f            :Filter by
    @           :Passing each X through the following fuction
     ìX         :  Convert U to base X digit array
        e       :  All
         §1     :    <=1
                :Implicit output, joined with newlines

```

---
Tags: code-golf, math, number, base-conversion
---


title: Golf a string twister

text:
# Question
Title: Golf a string twister
## How strings are twisted

The twisting algorithm is very simple. Each column is shifted down by its index (col 0 moves down 0, col 1 moves 1, ...). The column shift wraps to the top. It works like this:

```
aaaa
bbbb
cccc

```

Becomes:

```
a
ba
cba
----
 cba
  cb
   c

```

With everything under the line wrapping to the top. Real example:

```
Original:
\\\\\\\\\\\\
............
............
............

Twisted:
\...\...\...
.\...\...\..
..\...\...\.
...\...\...\

```

## Input

Input is either an array of strings, or a multi-line string. All lines have the same length.

## Output

The twisted string, multi-line output to std-out (or closest alternative).

## Examples:

(`>` denotes input, trailing space is important)

```
>Hello, world!
>I am another
>string to be
>twisted!

Hwrmoe oo br!
Ieii ,dttr e
s lsna !ohl
ttaltgnw  ed

>\\\\\\\\\\\\
>............
>............
>............

\...\...\...
.\...\...\..
..\...\...\.
...\...\...\

>abcdefg
>.......

a.c.e.g
.b.d.f.

>abcdefghij
>..........
>..........

a..d..g..j
.b..e..h..
..c..f..i.

>\\\\.....././
>...../.......
>........././.
>..../.^\\....

\.........../
.\....^..../.
..\../.\../..
...\/...\/...

>cdeab
>deabc
>eabcd
>abcde

cbbbb
ddccc
eeedd
aaaae

>aeimquy37
>bfjnrvz48
>cgkosw159
>dhlptx260

ahknqx147
beloru258
cfipsvy69
dgjmtwz30

>abcdefghi
>jklmnopqr
>stuvwxyz1
>234567890

a3ume7yqi
jb4vnf8zr
skc5wog91
2tld6xph0

```

# Answer
# Japt, 4 bytes

```
yÈéY

```

Try it here
> 3 votes

# Answer
# Pyth, 11

```
jC.>R~hZC.z

```

Try it here

```
jC.>R~hZC.z    ##  implicit: .z = list of input split by lines
        C.z    ##  transpose .z to get columns
  .>R~hZ       ##  shift each column by it's index
               ##  equivalent to .e.>bk
jC             ##  transpose back and join by newlines

```
> 7 votes

# Answer
# APL (Dyalog), 7 bytes

```
⊖⊖⊖⍨⍬⍋⍉

```

Requires `⎕io←0`

Try it online!

`⍬⍋⍉` gets the range from 0 to the number of columns
reverses vertically
`⊖⊖⍨⍬⍋⍉` rotate (vertically) the (vertically) reversed input by `0,1..`
reverse that, and return it.
> 7 votes

# Answer
## Retina, ~~111~~ ~~101~~ ~~92~~ 87 bytes

Byte count assumes ISO 8859-1 encoding.

```
(?<=((.))*)(?=(?<1>.*¶)*.*(?<=(?=(?<-2>.)*(.))(?<-1>.+¶)*.*(.(?<=^(?<-1>¶?.+)*))*)).
$3

```

Woo, solved it in a single regex substitution. :) (Chances are, there's a shorter solution by using several, but where's the fun in that...)

Try it online!

### Explanation

This requires some basic knowledge of balancing groups. In short, .NET's regex flavour allows you to capture multiple times with a single group, pushing all captures onto a stack. That stack can also be popped from, which allows us to use it for counting things inside the regex.

```
(?<=((.))*)

```

This pushes one capture onto both groups `1` and `2` for each character in front of the match (in the current line). That is, it counts the horizontal position of the match.

The rest is in a lookahead:

```
(?=(?<1>.*¶)*.* [...] )

```

We match each line and *also* push it onto group `1`, such that group `1` is now the sum of the horizontal and vertical position (where the latter is counted *from the bottom*). This essentially labels the diagonals of the grid with increasing values starting from the bottom left corner. That `.*` then just moves the engine's cursor to the end of the string.

We now switch into a lookbehind, which is matched from right to left in .NET:

```
(?<= [...] (.(?<=^(?<-1>¶?.+)*))*)

```

This will repeatedly pop exactly `H` captures from group `1` (where `H` is the height of the input). The purpose of that is to take the group modulo `H`. Afterwards, group `1` contains the row (counted from the bottom) from which to pick the new character in the current column.

```
(?=(?<-2>.)*(.))(?<-1>.+¶)*.*

```

Another lookbehind, again starting from the right. `(?<-1>.+¶)*.+` now uses group `1` to find the row from which to pick the new character and then the lookahead finds the correct column using group `2`.

The desired character is captured into group `3` and written back by the substitution.
> 6 votes

# Answer
## CJam, 13 bytes

```
qN/zee::m>zN*

```

Test it here.

### Explanation

```
q    e# Read all input.
N/   e# Split into lines.
z    e# Transpose to get an array of columns.
ee   e# Enumerate, pairing each column with its index.
::m> e# Map: fold: rotate (cyclically shifting each column by its index).
z    e# Transpose again.
N*   e# Join with linefeeds.

```
> 4 votes

# Answer
# TeaScript, 10 bytes

```
xHl@C(r╢tD

```

Thanks to TeaScript 3's extremely concise syntax, this is *really* short :D

Would be 1-byte shorter if Sigma loop weren't buggy

Try it online

## Explanation

```
      // Implicit, x = input
xH    // Transpose input
l@    // Loop
 C(r╢   // Cycle column by index
        // `╢` exits loop
t    // Transpose
D    // Join on \n

```
> 4 votes

# Answer
# Python 3, 164 bytes

Not the best answer by a long shot, but the first in Python...

```
s=list(zip(*open(0).readlines()))[:-1]
r=[[s[i][(j-i)%len(s[i])] for j in range(len(s[i]))] for i in range(len(s))]
print('\n'.join([''.join(l) for l in zip(*r)]))

```
> 3 votes

# Answer
# MATLAB, ~~92~~ 36 bytes

```
s=bsxfun(@circshift,s,0:size(s,2)-1)

```

Assuming that the input string `s` is already in the form of a 2D char array/ matrix, e.g.

```
s = ['abcdefg';'.......'];
s = ['\\\\.....././';'...../.......';'........././.';'..../.^\\....'];

```

Explanation: iterate through the columns of the matrix. For each column perform a circular shift of its elements by the number of characters that equals the column index (-1 because of MATLAB indexing).
> 3 votes

# Answer
# Brachylog, 5 bytes

```
iᵇ↻₎ᵐ

```

Try it online!

Gets input as an array of columns (which seems to be within the question's specifications).

`iᵇ` \- For each element in the array, pair it with its (0-based) index
\- map this predicate to each element of the result:
`↻₎` \- permute (the column) circularly by the amount specified as the last element (the index)

Easily extended to a version that accepts a single multiline string:

### 13 bytes

```
ṇẹ\iᵇ↻₎ᵐ\cᵐ~ṇ

```

Try it online!
> 3 votes

# Answer
# Brachylog, 96 bytes

```
$\:0{h_.|[M:I]hh:I{bh0,?h.|[C:I]h$)D,I-1=:Dr:2&.}C,I+1=J,Mb:J:1&:[C]rc.}$\{hA,[A]:"~s
"w,?b:3&;}

```

This expects a list of character codes strings as input and no output, e.g. `brachylog_main([`aaaa`,`bbbb`,`cccc`],_).`

That's one ridiculously long answer, and there's probably a much shorter way to do it.

### Explanation

```
§ Main Predicate

$\:0{}$\{}                            § Create a list containing the transposed input and 0
                                      § Call sub-predicate 1 with this list as input
                                      § Transpose its output and pass it as input to
                                      § sub-predicate 3

§ Sub-predicate 1

h_.                                   § If the matrix is empty, output is empty list
   |                                  § Else
    [M:I]hh:I{}C,                     § Input is [M,I], call sub-predicate 2 with the first
                                      § line of M and I as input. Its output is C.
                 I+1=J,Mb:J:1&        § Call sub-predicate 1 with M minus the first line
                                      § and I+1 as input
                              :[C]rc. § Its output is appended after C, which is then
                                      § unified with the output of sub-predicate 1.

§ Sub-predicate 2

bh0,?h.                               § If the second element of the input list is 0,
                                      § output is the first element of the input
       |                              § Else
        [C:I]                         § Input is [C,I]
             h$)D,                    § Perform a circular permutation of C from left to
                                      § right (e.g. [a,b,c] => [c,a,b]) and unify it with D
                  I-1=:Dr:2&.         § Call sub-predicate 2 with D and I-1 as input, unify
                                      § its output with sub-predicate 2's output

§ Sub-predicate 3

hA,[A]:"~s\n"w,                       § Write the first line of the input as a char codes
                                      § string followed by a new line

               ?b:3&;                 § Call sub-predicate 3 with input minus the first
                                      § line. If it fails (empty input), terminate

```
> 2 votes

# Answer
# MATL, 18 ~~21~~ bytes

```
Zy2):"G@Z)@qYS]N$h

```

Input is of the form

```
['Hello, world!'; 'I am another '; 'string to be '; 'twisted!']

```

**Try it online!**

**How it works**:

```
Zy       % implicitly take input: 2D char array. Get its size
2)       % second element from size vector: number of columns, say n
:        % create vector [1,2,...,n]
"        % for each element k in that vector
  G      %   push input
  @      %   push k
  Z)     %   k-th column from input
  @qYS   %   circularly shift k-1 positions
]        % end for loop
N$h      % concatenate all stack contents horizontally
         % implicitly display

```
> 2 votes

# Answer
# JavaScript, ~~92~~ 89 bytes

3 bytes off thanks @Neil.

```
s=>(z=s.split`
`).map((m,i)=>m.replace(/./g,(n,j)=>z[((l=z.length)*j+i-j)%l][j])).join`
`

```

```
f=s=>
    (z=s.split`\n`).map((m,i)=>
        m.replace(/./g,(n,j)=>
            z[((l=z.length)*j+i-j)%l][j]
        )
    ).join`\n`

Input.value = `abcdefghij
..........
..........`
```

```
textarea{display:block;width:250px;height:75px;}
```

```
<textarea id='Input'></textarea>
<button id='Run' onClick='Output.value=f(Input.value);'>Run</button>
<textarea id='Output'></textarea>
```
> 2 votes

# Answer
# Python 2, 115 bytes

```
lambda s:'\n'.join("".join(s)for s in zip(*[k[-i%len(k):]+k[:-i%len(k)]for i,k in enumerate(zip(*s.split('\n')))]))

```

Thanks to the wonder of `zip` managed to get this down to one line. See it in action here.
> 2 votes

# Answer
# F#, 105 bytes

My first stab at it (only a `\n` character is required):

```
let m x y=(x%y+y)%y
let f(a:string[])=Array.mapi(fun i x->String.mapi(fun j _->a.[m(i-j)a.Length].[j])x)a

```

Usage:

```
f [| @"\\\\\\\\\\\\"
     "............"
     "............"
     "............" |]

```
> 1 votes

# Answer
# JavaScript (ES6), 73 bytes

```
t=>t.replace(/./g,(_,i)=>t[(i+s*l-i%l*l)%s],l=t.search`
`+1,s=t.length+1)

```

## Explanation

```
t=>
  t.replace(/./g,(_,i)=> // replace each character at index i
    t[                   // get the character at index:
      (i                 // start at i
        +s*l             // add s*l to ensure the result is always positive for %s
        -i%l*l           // move the index upwards the num of chars from start of the line
      )%s                // shift the index into the the range of s
    ],
    l=t.search`
`+1,                     // l = line length
    s=t.length+1         // s = input grid length (+1 for the missing newline at the end)
  )

```

## Test

```
var solution = t=>t.replace(/./g,(_,i)=>t[(i+s*l-i%l*l)%s],l=t.search`
`+1,s=t.length+1)
```

```
<textarea id="input" rows="5" cols="40">\\\\.....././
...../.......
........././.
..../.^\\....</textarea><br>
<button onclick="result.textContent=solution(input.value)">Go</button>
<pre id="result"></pre>
```
> 1 votes

# Answer
# Japt, 29 bytes

```
Uy £XsV=(Y*Xl -Y %Xl)+X¯V}R y

```

Test it online!

### How it works

```
Uy        // Transpose rows and columns in the input string.
£     }R  // Map each item X and index Y in the result, split at newlines, to:
Y*Xl -Y   //  Take Y times X.length and subtract Y.
%Xl)      //  Modulate the result by X.length.
XsV=      //  Set V to the result of this, and slice off the first V chars of X.
+X¯V      //  Concatenate this with the first V chars of X.
y         // Transpose the result again.
          // Implicit: output last expression

```
> 1 votes

# Answer
# Haskell, 81 bytes

```
let t=transpose in t.snd.mapAccumR(\c l -> 1+c,take(length l)(drop c$cycle l))0.t

```

reimplementation of the CJam example, though the reverse, map and enumerate is part of the mapAccumR, the snd removes the accumulator since we don't need it anymore, the reversal is just a side effect of the right fold.
> 1 votes

# Answer
## Haskell, 65 bytes

```
g l@("":_)=l;g l|t<-tail<$>l=zipWith(:)(head<$>l)$g$last t:init t

```

Usage example: `g ["1111","2222","3333"]` -\> `["1321","2132","3213"]`.
> 1 votes

# Answer
# MATL, 9 bytes

```
"@X@qYS&h

```

Try it online!

Pretty similar in core to Luis Mendo's existing MATL answer, but shorter by using features that were probably not in the language at that point: 1. `"` iterates through a matrix's columns automatically now, so no costly business of constructing column indices and indexing into them (this is the biggie), 2. `&h` as a shorthand way of saying `N$h`, and 3. implicit loop end if `]` is not specified.

Alternately, for the same bytecount:

```
tsn:ql&YS

```

Try it on MATL Online

```
      &YS   % circularly shift the matrix
     l      % across rows (i.e. shift each column) by the amounts
            %  given by this array:
tsn         % duplicate input, get the sum of each column, get the
            %  number of elements in that (which is the number of columns)
   :q       % construct range 1 to ncols, then decrement to start at 0
            % (implicit output)

```
> 1 votes

# Answer
# Husk, 10 bytes

```
Tzṙm→İ-T'

```

Try it online!

(there's a space at the end.)

## Explanation

```
Tzṙm→İ-T'
       T'  transpose, padding with spaces
 zṙ        zip and rotate each column by
     İ-    negative integers
   m→      each incremented
T          transposed back

```
> 1 votes

# Answer
# C (clang), 114 bytes

Works in GCC under MinGW. TIO's GCC gets confused by using `strlen` in the init expression of the first for loop.

```
f(L,n)char**L;{for(int l=strlen(*L),i=0,j,c;i<n;i++)for(j=c=0;j<=l;j++,c=c?c-1:n-1)putchar(l^j?L[(c+i)%n][j]:10);}

```

Try it online!
> 0 votes

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


title: Twisting Sentences

text:
# Question
Title: Twisting Sentences
## Rules

The program should receive a string/array of words as input. For each word in the string/array, it will reconstruct the word by taking characters in alternating fashion from the front and back of the word.

12345 678 9 -\> 15243 687 9.

It will then rearrange the words in an alternating fashion between the earliest and the latest occurring word in the string.

15243 687 9 -\> 15243 9 687

Finally, it will reconstruct the string by placing the spaces, tabs and newlines at the indexes where they were initially located before outputting the result.

12345 678 9-\> 15243 687 9 -\> 15243 9 687 -\> 15243 968 7

Output should be the same datatype as the input.

Standard Loopholes are forbidden

## Examples

> Input:
> The quick brown fox jumps over the lazy dog.
> Output:
> Teh d.ogq kucil yaz bnrwo tehf xoo rvej supm
>
> Input:
> The quick brown fox jumps
> over the lazy dog.
> Output:
> Teh d.ogq kucil yaz bnrwo
> tehf xoo rvej supm
>
> Input:
> Aflack
> Output:
> Akfcla

This is so shortest code wins

# Answer
> 3 votes
# Jelly, ~~15 14~~  8 bytes

A **whopping** 6 byte save from **Dennis** (by moving the flatten and mould inside link 1 there is no need to split into two and head, and a flatten is there already so they become one!)

```
żṚFṁ
Ç€Ç

```

(from the two lines: `żṚFœs2Ḣ`, and `Ç€ÇFṁ⁸`)

**Try it online!**

Takes an array of words and returns an array of new words. (The Footer at TIO calls this and joins the array with spaces so it prints out nicely.)

*Note - handling a single string, splitting on tabs spaces and newlines, then reassembling was actually proving rather tricky; once I saw that a list of words was an option things got a lot easier!*

### How?

```
Ç€Ç - Main link: list of words
Ç€  - call the last link (1) as a monad for €ach word
  Ç - call the last link (1) as a monad for the result

żṚFṁ - Link 1: Do a twist: list (here, a list of words or characters)
                            e.g. input = [A,B,C,D,E,F,G]
ż    - zip the list with                 [A,    B,    C,    D,    E,    F,    G]
 Ṛ   - the reverse of the list             [G,    F,    E,    D,    C,    B,    A]
                                        [[A,G],[B,F],[C,E],[D,D],[E,C],[F,B],[G,A]]
  F  - flatten into a single list        [A,G,  B,F,  C,E,  D,D,  E,C,  F,B,  G,A]
                                         [A,G,B,F,C,E,D,D,E,C,F,B,G,A]
   ṁ - mould like the input list         [A,G,B,F,C,E,D]

```

# Answer
> 2 votes
## JavaScript (ES6), 89 bytes

Takes and outputs an array of words.

```
a=>a.map(w=>(F=([a,...b])=>a?a+(b.pop()||'')+F(b):'')(a.map(F)).slice(p,p+=w.length),p=0)

```

**Test**

```
let f =

a=>a.map(w=>(F=([a,...b])=>a?a+(b.pop()||'')+F(b):'')(a.map(F)).slice(p,p+=w.length),p=0)

console.log(
  JSON.stringify(
    f(["The","quick","brown","fox","jumps","over","the","lazy","dog."])
  )
);
```

### String version, 112 bytes

Takes and outputs a string.

```
s=>s.replace(/\S+/g,w=>(F=([a,...b])=>a?a+(b.pop()||'')+F(b):'')(s.split(/\s/).map(F)).slice(p,p+=w.length),p=0)

```

**Test**

```
let f =

s=>s.replace(/\S+/g,w=>(F=([a,...b])=>a?a+(b.pop()||'')+F(b):'')(s.split(/\s/).map(F)).slice(p,p+=w.length),p=0)

console.log(f(`The quick brown fox jumps over the lazy dog.`))

console.log(f(`The quick brown fox jumps
over the lazy dog.`))

console.log(f(`Aflack`))
```

# Answer
> 2 votes
# Perl, 77 bytes

74 bytes of code + 3 bytes for `-0pa` flags.

```
map{s/.\K/chop/ge,s/../chop/reg}@F;s/\S/($r||=$F[$i++].pop@F)=~s%.%%,$&/ge

```

Try it online!

Saved 8 bytes thanks to an old @Ton Hospel's post where I "stole" `s/../chop/reg`. (I previously had `$c=y///c/2,s/.{$c}$//`)

# Answer
> 0 votes
# Perl 6, 84 bytes

```
{my &t={(|(.shift,.pop)xx*)[^$_]}
map({|t [.comb]},t [$_]).rotor($_».chars)».join}

```

Inputs and outputs a list of words.

### How it works

Inside the lambda, I defined another lambda to perform the "*taking characters in alternating fashion from the front and back*" twisting:

```
my &t={                        }   # Lambda, assigned to a variable.
          .shift,.pop              # Remove an element from the front an back,
                      xx*          # an infinite number of times,
        |(           )             # and make sure this infinite list is flattened.
                          [^$_]    # Take as many elements as the input had elements.

```

This works because the `xx` operator is more like a macro than a function, in that it provides magic lazy evaluation.

Then in the main lambda:

```
                   [$_]                          # Create a fresh array from the input,
                 t                               # and twist it (destructively).
map({          },                                # For each element (i.e. word):
      t [.comb]                                  #   Split it into characters and twist them,
     |                                           #   and slip them into the outer list.
                        .rotor($_».chars)        # Partition this flat list of characters,
                               $_».chars         # using the original word lengths.
                                         ».join  # Turn each sub-list into a word.

```

---

# Perl 6, 87 bytes

```
{my &t={(|(.shift,.pop)xx*)[^$_]}
my @a=map {|t [.comb]},t [.words];S:g/\S/{@a.shift}/}

```

This is a variation of the above, which inputs and outputs a string – preserving different whitespace characters.

# Answer
> 0 votes
# Haskell, ~~115 95 93 98~~ 95 bytes

```
f(a:b)=a:f(reverse b)
f e=e
a!(y:z)|elem y" \t\n"=y:a!z|b:c<-a=b:c!z
a!z=z
(!)=<<(f=<<).f.words

```

Call with `(!)=<<(f=<<).f.words $ "some string"`. Try it online!

Thanks to @nimi for pointing out that I misread the challenge earlier.

The function `f` performs the twisting on a list, so it can be used on strings (list of chars) and a list of strings. `a!b` inserts the whitespace of string `b` into string `a`.

`(!)=<<(f=<<).f.words` is equivalent to `\s0 -> (concatMap f . f . words $ s0) ! s0`:

```
            s0 = "The quick brown fox jumps\nover the lazy dog."
      words s0 = ["The","quick","brown","fox","jumps","over","the","lazy","dog."] = s1
          f s1 = ["The","dog.","quick","lazy","brown","the","fox","over","jumps"] = s2
concatMap f s2 = "Tehd.ogqkucilyazbnrwotehfxoorvejsupm"                           = s3
       s3 ! s0 = "Teh d.ogq kucil yaz bnrwo\ntehf xoo rvej supm"

```

# Answer
> 0 votes
# Husk, 14 bytes

```
UΣSze↔mȯUΣSze↔

```

Try it online!

This doesn't work with a reusable function since a function can only support one type of arguments.

---
Tags: code-golf, string, permutations
---


title: Size up a number

text:
# Question
Title: Size up a number
# Intro

Given a whole number \\$\< 100,\\$ extend/shorten the english representation of the number to have as many characters as it's value.

Sandbox

# Rules

Take the number \\$n\\$, and get it in words from this dictionary. You may take this dictionary in any way you prefer. (a list, read from link, command line arg, STDIN, variable, so on.)

Here's the file as a JSON Array. (Courtesy of Lyxal)

Then, do the following with the string:

* If the string's length is lower than the number, repeat some of its characters in place until the length matches the number.
* The first and last characters should not be repeated, and the numbers of repetitions of the other characters should differ by at most one (so you can repeat some of them 5 times and others 6 times, for example; it doesn't matter which ones exactly).
* If the string's length is greater than the number, remove any of its characters except the first and last to make the length match the number. **1 and 0 are exceptions, since they are too small.**
* The order of the letters in the string must be maintained.
* Example:

```
50 → f[ift]y → 3 letters must be duplicated 16 times
61 → s[ixtyon]e → 5 letters must be duplicated 10 times, 1 character must be duplicated 9 times

```

## Step by step run-through

Taking 11 as an example,

(formatted as `word → length`)

```
eleven → 6
 ^
elleven → 7
   ^
elleeven → 8
     ^
elleevven → 9
       ^
elleevveen → 10
  ^
ellleevveen → 11 (end)

```

## Examples

```
2 → to
3 → the or tre or tee
4 → four
5 → fiive or fivve
7 → seevven or sevveen or seeveen
10 → teeeeeeeen

Special cases:
0 → (Any null value/no output)
1 → o

```

## Winning Criteria

This is . Shortest code in each language wins.

## ~~LoTM Bounty~~ Claimed by Dominic Van Essen!

The first Husk answer to this question will get a +50 rep bounty from me on top of Zgarb's bounty, if it satisfies the criteria put up here in the **Additional Efforts** part.

# Answer
> 9 votes
# , ~~(110 105 96)~~ ~~96~~ 95 bytes

*Hopefully answering the correct question now...*

```
function(n,a)cat(substring(b<-a[n+1],r<-sort(c(1,l<-nchar(b),rep(3:l-1,n))[1:n]*!!n),r),sep='')

```

Try it online!

Doh! Read the question, stupid!

Ok, first (several) attempts were not answering the correct question, because I didn't read the challenge properly and didn't notice that the first+last characters shouldn't be repeated. Coincidentally, though, the near-complete-rewrite came out at the same number of bytes!

**How?** Ungolfed code:

```
size_up=
function(n,a){              # n is number, a is array of text strings
  b=a[n+1]                  # get the text string for this number
  l=nchar(b)                # get the number of characters
  r=sort(                   # r = sort the indices of characters to output:
      c(1,l,                # we need index 1 and the last index (l)...
        rep(2:(l-1),n))     # then plenty of repeats of 2..(l-1) ...
      [1:n])                # and, from this, we'll use the first n.
  if(n)                     # only output anything if n>0 ...
    cat(substring(b,r,r),sep='')
                            # ...in which case concatenate the indexed
}                           # characters of the text string b.

```

# Answer
> 7 votes
# Husk, ~~28~~ ~~27~~ ~~25~~ ~~22~~ 21 bytes

*Edit: -2 bytes thanks to Zgarb, -3 more bytes thanks to Jo King, and then -1 more byte thanks again to Zgarb (those last 4 bytes took a while to work-through and understand; I've added an explanation but it isn't easy for Husk newbies like me...)*

```
SṀ!(O↑¹:1S:ȯ*¹…2←L)!→

```

Try it online!

My first Husk answer, inspired by the 'language of the month'.
Port of the approach in my R answer.
I'm pretty happy just to figure-out how to write a working program (hooray!), so it's almost-certainly not as golfy as it could be...

**How?** (commented after Zgarb & Jo King's golfs: it's quite complicated now...):

First of all, we'll put-in all the implicit arguments (as superscripts  and `²`):

```
SṀ!(O↑²:1S:ȯ*²…2←L)!→²⁰

```

Now the commented code:

```
S                               # S is a 'hook' combinator to recycle argument x: Sfgx == fx(gx)
 Ṁ!                             # f is M! = map the list-index function across a list of indexes, with the list to index given by argument x
   (O↑²:1S:ȯ*²…2←L)             # g is (O↑²:1S:ȯ*²…2←L) = function to generate the list of indexes from argument x (see below)
                   !→²⁰         # x is !→²⁰ = the text name of the number (for instance, "twenty"; see below)

                                # Explanation of g:
         S                      # S 'hook' combinator again, so Sfgy here == fy(gy)
          :                     # f is : = prefix with y
           ȯ                    # g is given by ȯ*²…2←
                                # ȯ is 3-function combinator: ȯfgh == single function fgh
                ←               #   subtract 1
              …2                #   and construct a series from 2..this value,
            *²                  #   and repeat this series n times, with n given by argument 2 (first given program argument);
                                #   so ȯ*²…2← is the function that repeats 2..x, n times, for argument y
                 L              # y is the length of the argument x
                                # So: up to here, we have :Lx *²…2←Lx
       :1                       # Now prefix with 1...
     ↑²                         # then select the first n elements, with n given by argument 2 (first given program argument)...
    O                           # and sort the result.  This is the list of indexes from x.

                                # Explanation of x:
                   !  ⁰         # element of argument 1 (second given), indexed by...
                    →²          # argument 2 (first given) +1

```

# Answer
> 7 votes
# Haskell, 59 bytes

```
d!n|h:t<-d!!n=take n$h:[t!!div(i*length t-i)(n-1)|i<-[1..]]

```

Try it online!

Usage: `["zero","one",...]!n`.

For example, for input `11`, it will output an `'e'` followed by `"leven"` indexed at: $$ \left\lfloor\frac{4}{10}\right\rfloor, \left\lfloor\frac{8}{10}\right\rfloor, \dots, \left\lfloor\frac{40}{10}\right\rfloor $$ which is `"lleevvveen"`. (Intuitively, the formula stretches the indices \[0..4\] of `"leven"` to \[0..10\].)

`take n$` is used to support the 0 case (otherwise the output is `"z"`), but it also lets us write `[1..]` instead of `[1..n-1]`, so the net cost is only 4 bytes rather than 7.

# Answer
> 6 votes
# Jelly, 20 bytes

```
ị©L⁸,_2œs/Ẉ⁸>Ø.¤j®x"

```

A dyadic Link accepting the number on the left and the list of number-names on the right (in Jelly index order), which yields a list of characters.

**Try it online!** Or see all 100.

### How?

```
ị©L⁸,_2œs/Ẉ⁸>Ø.¤j®x" - Link: N, Words
ị                    - (N) index into (Words) -> the word
 ©                   - copy for later
  L                  - length
   ⁸                 - chain's left argument -> N
    ,                - pair -> [N, length(Word)]
     _2              - subtract two -> [N-2, length(Word)-2]
         /           - reduce using:
       œs            -   split (implicit range [1..N-2]) into (length(Word)-2)
                         approximately equal parts
          Ẉ          - length of each -> sizes (call this [s1, s2, ...])
               ¤     - nilad followed by link(s) as a nilad:
           ⁸         -   chain's left argument -> N
             Ø.      -   bits -> [0,1]
            >        -   greater than? -> [N>0, N>1]
                j    - join -> [N>0, s1, s2, ..., N>1]
                 ®   - recall from earlier -> the word
                   " - zip with:
                  x  -   repeat

```

# Answer
> 6 votes
# , 40 39 bytes

```
[{.[(]#~1:0 _1}2+/@}.($[:}:@}.@=#\))>@{

```

Try it online!

# Answer
> 5 votes
# Python 3, 98 bytes

```
def f(n,a):x,*s,y=a[n];l=len(s);d=n-2;a[0]=(x+"".join(s[i]*(d//l+(i<d%l))for i in range(l))+y)[:n]

```

Try it online!

-8 bytes thanks to ovs
-2 bytes thanks to pxeger

(-9 bytes between the two because one of the saved bytes overlaps between the two optimizations)

-9 more bytes thanks to ovs

# Answer
> 5 votes
# JavaScript (ES6),  ~~78~~  73 bytes

Expects `(n)(dictionary)`. Returns an empty string for zero.

```
n=>d=>(s=d[n--],g=k=>k<n?s[~k?k/~-n*(s.length-2)+1|0||2:0]+g(k+1):'')(-1)

```

Try it online!

# Answer
> 5 votes
# K (oK), ~~50~~ ~~46~~ 40 bytes

-4 bytes thanks to ovs

-6 bytes thanks to coltim

```
{x#,/(1,(+/'(-2+#y@x;0N)#2_x#1),1)#'y@x}

```

Try it online!

# Answer
> 4 votes
# Rust, 203 bytes

```
|i,a|if i<2{a[i].truncate(i)}else
if let[f,m@..,l]=&*a[i].clone(){let mut v:Vec<_>=(0..m.len()).cycle().take(i-2).collect();v.sort();a[i]=v.iter().map(|&j|m[j]).collect();a[i].insert(0,*f);a[i].push(*l)}

```

Try it online

A closure of type `fn(usize,&mut [Vec<char>])`. The result is written in `a[i]`.

# Answer
> 4 votes
# APL (Dyalog Unicode), ~~39~~ ~~37~~ 36 bytes

-2 bytes thanks to Razetime!
-1 byte thanks to Jo King!

Assumes `⎕IO←0`.

```
⊃∘⌷{⍵↑⍺/⍨1,⍨1,(⍵-2)(⌊÷+|⍨>∘⍳⊢)≢2↓⍺}⊣

```

Try it online!

**Explanation**

This function takes the dictionary as the right argument and the integer as the left argument.

`⊃∘⌷` is a function that gets the word at the left index in the right dictionary.
is the left identity function.
The inner function `{ ... }` is then called with the word as a left argument  and the integer as a right argument .

`≢2↓⍺` is the length of the word without the first two characters (`a`).
`⍵-2` is just the integer input minus `2` (`b`).

With these two arguments the function `⌊÷+|⍨>∘⍳⊢` is called:
`⍳⊢` creates an index vector `0 1 ... a-1`.
`|⍨` calculates `b mod a`.
`>` compares this to the index vector, which results in a boolean vector with `b mod a` `1`'s and `a - b mod a` `0`'s.
`⌊÷` is the floor of `b÷a`.
`+` adds this to the boolean vector.

`1,` prepends a `1`, `1,⍨` appends a `1`.
`⍺/v` selects as many items from the word x, as indicated in `v`. Example: `1 3 2 2 2 1/'eleven'≡'ellleevveen'`. This is commuted () here to avoid brackets.
`⍵↑` then takes the required number of characters. This is required for `0` and `1`.

# Answer
> 3 votes
# Charcoal, 29 bytes

```
ＮθＦ⊕θＳηＦθ§η∧ι⊖÷×⊕⁻ιθ⁻²Ｌη∨⁻²θ¹

```

Try it online! Link is to verbose version of code. Takes input as the number and then the dictionary. Removing the `Ｆ⊕θＳη` results in a program that resizes the second line to the length given on the first line. Annoyingly, `2` was the hardest number to process, since both the first and last character are edge cases. Explanation:

```
Ｎθ

```

Input `n`.

```
Ｆ⊕θＳη

```

Read in the dictionary up until and including the entry for `n`.

```
Ｆθ

```

Loop over `n` characters. (`⭆θ` also works.)

```
§η

```

Output the character of the dictionary word given by the computed index.

```
∧ι

```

For the first character of the output the computed index is always `0`.

```
⊖÷×⊕⁻ιθ⁻²Ｌη∨⁻²θ¹

```

Otherwise scale the distance to the end of the string from `0..n-2` to `0..l-2` (where `l` is the length of the dictionary word), rounded up. Note that this results in `0/0` for `n=2`, so the denominator is coerced to `1` in this case. Example for `n=5, five`:

```
i=0 o=0
i=1 o=3-ceil((4-1)*(4-2)/(5-2))=3-ceil(3*2/3)=3-2=1
i=2 o=3-ceil((4-2)*(4-2)/(5-2))=3-ceil(2*2/3)=3-2=1
i=3 o=3-ceil((4-3)*(4-2)/(5-2))=3-ceil(1*2/3)=3-1=2
i=4 o=3-ceil((4-4)*(4-2)/(5-2))=3-ceil(0*2/3)=3-0=3

```

Therefore the output indices are `0, 1, 1, 2, 3` resulting in `fiive`. (In actual fact the calculations are done using negative indices, so the actual indices are `0, -3, -3, -2, -1`, which means that they are actually rounded down, rather then up.)

# Answer
> 3 votes
# Perl 5, 77 bytes

```
sub{@w=@{$d[$n=pop]};$h=$n<4?2:(@w-2)/($n-2);join'',@w[map.99+$h*$_,0..$n-1]}

```

Try it online!

# Answer
> 3 votes
# Scala, 93 bytes

```
i=>a=>{val f+:m:+l=a(i);(f+:Seq.fill(i)(m.indices).flatten.take(i-2).sorted.map(m):+l)take i}

```

Try it online!

Defines a function of type `Int=>Seq[Seq[Char]]=>Seq[Char]`.

## Explanation:

```
i => a => {                  // define a curried lambda function with two arguments
  val f+:m:+l = a(i)         // destructure the string to extract the first and last letter
  (                          // return...
    f +:                     // the first letter prepended to
      Seq.fill(i)(m.indices) // the numbers from 0 to i-2, all repeated i times
                             // for "seven", this is 7 instances of [0,1,2]
      .flatten               // flatten this list
      .take(i-2)             // take the first i-2  numbers from the list
      .sorted                // sort them
      .map(m)                // and use them as indices for the middle part of the string
    :+l                      // append l
  )
  take i                     // to handle 0 and 1, take i letters from the result
}

```

# Answer
> 2 votes
# 05AB1E, 20 bytes

```
èā¨¨₂и¾šηε{®ª}0šδè¹ù

```

Takes the list of words as additional second input.
Outputs as a list of characters.

Try it online or verify all \\$\[0,99\]\\$ test cases.

**Explanation:**

```
è                  # Index the (implicit) input-integer into the (implicit) string-list
 ā                 # Push a list in the range [1,string-length] (without popping)
  ¨¨               # Remove the last two values to make the range [1,length-2]
    ₂и             # Repeat this list 26 times: [1,2,3] → [1,2,3,1,2,3,1,2,3,...]
      ¾š           # Prepend a 0 to this list
        η          # Take all prefixes
         ε         # Map each prefix-list to:
          {        #  Sort the list
           ®ª      #  And append a -1
         }0š       # After the map: prepend a 0 to the list of lists
             δ     # Map over each list:
              è    #  Index it in the string that's still on the stack
                   #  (modulair 0-based, so the -1 indexes into the last character)
               ¹ù  # Keep the list of characters of a length equal to the first input
                   # (after which the result is output implicitly as result)

```

If outputting a lazy infinite result is allowed, the `₂и` could be `Þ` instead for -1 byte: try it online.

# Answer
> 1 votes
# Factor, 201 bytes

```
: s ( n d -- s ) dupd 2dup nth length 2 - pick 1 - 1 max dup [ / ] dip swap
<repetition> dup first [ + ] accumulate [ 1 + >integer ] map nip [ nth ] dip
dupd swap nths [ 1 head ] dip append swap head ;

```

Try it online!

# Answer
> 1 votes
# Japt, 25 bytes

```
gV
_uUÊ-2 Ä}hV[0UÊÉ] Í®gU

```

Try it

```
Input :
 U = dictionary
 V = number

gV          - get element from dictionary

hV[0UÊÉ]    - build a list of V indexes,
              starting with [0 , last idx]
              and calling the following function on last element to generate next items.
_uUÊ-2 Ä}   - returns number modulo( literal length -2) + 1

Example : 11 - eleven
[0,5] -> 5%4+1
[0,5,2] -> 2%4+1
[0,5,2,3]
[0,5,2,3,4,1,..]

Í®gU         - sort and maps to literal

-P flag to join result

```

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