# Question
Title: Find the tangent of the sum of inverse tangents
# Background

It can be shown that for any integer `k >= 0`, `f(k) = tan(atan(0) + atan(1) + atan(2) + ... + atan(k))` is a rational number.

# Goal

Write a complete program or function which when given `k >= 0`, outputs `f(k)` as a single reduced fraction (the numerator and denominator are coprime).

# Test cases

The first few values are

```
f(0) = (0,1)
f(1) = (1,1)
f(2) = (-3,1)
f(3) = (0,1)
f(4) = (4,1)
f(5) = (-9,19)
f(6) = (105,73)

```

# Rules

* Standard loopholes are forbidden.
* Input and output may be in any convenient format. You may output `f(k)` as a string `numerator/denominator`, as a tuple of two integers, a fraction or rational object, etc. If you output a string, give two integers only, that is, output `3/2` instead of `1 1/2`.
* This is code-golf, the shortest answer (in bytes) wins.

# Answer
# , 11 bytes

```
×C÷@+
R0;ç/

```

Try it online!

Uses the OEIS formula `x(n) = (x(n-1)+n)/(1-n*x(n-1))` with `x(0) = 0`.
> 4 votes

# Answer
# Python 2, ~~76~~ 72 bytes

```
from fractions import*
f=lambda k:Fraction(k and(k+f(k-1))/(1-k*f(k-1)))

```

Use the identity:

```
tan(A + B) = (tan(A) + tan(B)) / (1 - tan(A) * tan(B))

```

We have:

```
f(k) = 0                                    if k = 0
     = (k + f(k - 1)) / (1 - k * f(k - 1))  if k > 0

```

Try it online!

Thanks to Luis Mendo, save 4 bytes.
> 11 votes

# Answer
# Mathematica, 28 bytes

```
Fold[+##/(1-##)&,0,Range@#]&

```

Try it online!

A longer, but more interesting approach (32 bytes):

```
Im@#/Re@#&@Product[1+n I,{n,#}]&

```

Try it online!
> 11 votes

# Answer
# APL (Dyalog), 14 bytes

Requires `⎕FR←1287` (**128** bit **F**loating-point **R**epresentation) for small input. Takes `k` as right argument.

```
1(∧÷,)3○¯3+.○⍳

```

Try it online!

integers one through `k` (zero is not needed as 0 = arctan 0)

`¯3+.○` sum of arcus tangents

`3○` tangent

`1(``)` apply the following tacit function with 1 as left argument and the above as right argument:

the lowest common multiple (of 1 and the right argument); gives the numerator

`÷` divided by

`,` the concatenation (of 1 and the right argument); gives the numerator and the denominator
> 3 votes

# Answer
# Haskell, 52 bytes

This uses the OEIS series expansion:

```
import Data.Ratio
f 0=0%1
f n|p<-f$n-1=(p+n)/(1-n*p)

```

Try it online!

Or a pointfree version:

```
(scanl1(\f n->(f+n)/(1-n*f))[0%1..]!!)

```
> 3 votes

# Answer
## JavaScript (ES6), 80 bytes

```
f=n=>n?([a,b]=f(n-1),g=(a,b)=>a?g(b%a,a):b,c=g(d=b*n+a,e=b-n*a),[d/c,e/c]):[0,1]

```

Returns a \[numerator, denominator\] pair. Explanation: Let `f(n-1) = a/b` then `f(n) = atan(tan(n)+tan(a/b)) = (n+a/b)/(1-n*a/b) = (b*n+a)/(b-n*a)`. It then remains to reduce the fraction to its lowest terms.

Online ES6 Environment
> 2 votes

# Answer
# Casio-Basic, 35 bytes

```
tExpand(tan(sum(seq(tan⁻¹(n),n,0,k

```

tan-1 should be entered as the one on the Trig keyboard; or the -1 can be entered separately from the abc\>Math keyboard. According to the fx-CP400's manual, it's a single two-byte character (764).

Function, 34 bytes for the code, +1 byte to add `k` as an argument.

**Explanation**

`seq(tan-1(n),n,0,k)` generates all the values for `tan-1(n)` from 0 to k.

`sum` adds them all together, then `tan` does the tangent function on them.

`tExpand` will then turn them into a single fraction.
> 1 votes

# Answer
# Pari/GP, 36 bytes

```
n->imag(x=prod(i=0,n,1+i*I))/real(x)

```

Try it online!

Or the same length:

```
n->fold((x,y)->(x+y)/(1-x*y),[0..n])

```

Try it online!
> 1 votes

# Answer
# 05AB1E, ~~33~~ 26 bytes

```
0X)Iƒ©`N*+®`sN*-‚D¿D_i\¤}/

```

Try it online!

**Explanation**

```
0X)                          # initialize stack with [0,1]
   Iƒ                        # for N in range [0 ... input] do:
     ©                       # store a copy of the current pair in the register
      `                      # push the pair separately to the stack
       N*                    # multiply the denominator with N
         +                   # add the numerator
          ®`s                # push the denominator then the numerator to the stack
             N*              # multiply the numerator by N
               -             # subtract it from the denominator
                D¿D          # get 2 copies of the greatest common divisor
                   0Qi  }    # if the gcd equals 0
                      \¤     # replace it with the denominator
                         /   # divide the pair with this number

```
> 1 votes

# Answer
# Octave, 30 bytes

```
format rat
tan(sum(atan(0:k)))

```

Try it online!
> 1 votes

# Answer
# Forth (gforth), 130 bytes

```
: g dup if tuck mod recurse then ;
: f 0 1 rot for 2dup i * + -rot swap i * - next
2dup g + abs over 0< 2* 1+ * >r i / swap r> / ;

```

Try it online!

Uses my own implementation of gcd, and the OEIS formula. Takes `k` from the stack and returns two integers `denom num` on the stack. It took a lot of effort (and bytes) to normalize the fraction.

```
: g ( x y -- gcd 0 )
  dup if tuck mod recurse then
;

: f ( k -- denom num )
  0 1               \ push initial fraction with num=0, denom=1
  rot for           \ ( num denom ) loop from k to 0 inclusive
    2dup i * + -rot \ ( denom*k+num num denom )
    swap i * -      \ ( denom*k+num denom-num*k )
  next
  2dup g + abs      \ ( num denom gcd ) evaluate positive gcd and remove 0
  over 0< 2* 1+ *   \ ( num denom gcd' ) negate gcd if denom < 0
  >r i / swap r> /  \ ( denom/gcd' num/gcd' )
;

```
> 1 votes

# Answer
## Julia 0.6.0 40 bytes

`k->rationalize(tan(sum(x->atan(x),1:k)))`

It's a straightforward implementation of the question. The precision of rationalize can sometimes be weird but works fine 99% of the time.
> 0 votes

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


title: Each step of the Levenshtein distance

text:
# Question
Title: Each step of the Levenshtein distance
In this challenge you will write a program that takes two newline-separated strings, s1 (the first line) and s2 (the second line), as input (STDIN or closest). You can assume that the length of s1 will always be smaller than 30 and bigger than the length of s2. The program should then output each step in the levenshtein distance from s1 to s2.

To clarify what each step in the levenshtein distance means, the program will print n strings, where n is the levenshtein distance between s1 and s2, and the levenshtein distance between two adjacent strings will always be one. The order doesn't matter. The output should be newline-separated and not include s1, only the in-betweens and s2. The program should also run in under one minute on a modern computer.

Examples:

Input:

```
Programming
Codegolf

```

Output:

```
rogramming
Cogramming
Coramming
Coamming
Codmming
Codeming
Codeging
Codegong
Codegolg
Codegolf

```

Input:

```
Questions
Answers

```

Output:

```
uestions
Aestions
Anstions
Ansions
Answons
Answens
Answers

```

Input:

```
Offline
Online

```

Output:

```
Ofline
Online

```

Input:

```
Saturday
Sunday

```

Output:

```
Sturday
Surday
Sunday

```

Here is a link to a python script that prints out the distance and the steps.

Additional rules:

This is code-golf so keep you code short; shortest code wins!

# Answer
> 10 votes
# Haskell, ~~201~~ 194 bytes

```
l=length
g[]n u=map(\_->"")n
g(b:c)[]u=(u++c):g c[]u
g(b:c)n@(o:p)u|b==o=g c p(u++[o])|1<2=((u++o:c):g c p(u++[o]))!((u++c):g c n u)
a!b|l a<l b=a|1<2=b
p[a,n]=g a n""
f=interact$unlines.p.lines

```

Longer than expected. Maybe I can golf it down a little bit ...

Usage example:

```
*Main> f                     -- call via f
Questions                    -- User input
Answers                      -- no newline after second line!
uestions                     -- Output starts here
Aestions
Anstions
Ansions
Answons
Answens
Answers

```

It's a brute force that decides between changing and deleting if the initial characters differ.

# Answer
> 1 votes
# APL (Dyalog 18.0), 66 bytes

```
{⍺<Ö≢⍵:⍺∇⎕←0~⍨0@(⊃(⍸~p)~⍳⊃⌽⍸p←⍵=⍺↑⍨≢⍵)⊢⍵⋄j←⊃⍸⍺≠⍵⋄⍺≢⍵:⍺∇⎕←⍺[j]@j⊢⍵}

```

Try it online!

Works correctly now.

A recursive function submission, done with a lot of input from Adám and Bubbler.

Input is taken as `<s2> f <s1>`.

## Explanation

`⍺<⍥≢⍵:` if the strings have different lengths:

`0@(...)⊢⍵` put a zero at the following index:

first element of:

`(⍸~p)` characters which do not match

`~` without

`⍳⊃⌽⍸p←⍵=⍺↑⍨≢⍵` all indices before last character match

`0~⍨` remove the zero(thereby removing the element)

`⍺∇⎕←` display the result and recurse

`⋄⍺≢⍵:` Otherwise, till the strings match:

`i←⊃⍸⍺≠⍵` find first non-matching element

`⍺[i]@i⊢⍵` and replace the element at that index

`⍺∇⎕←` display the result, and recurse

---
Tags: code-golf, string, restricted-time, edit-distance
---


title: Rectangles in rectangles

text:
# Question
Title: Rectangles in rectangles
This challenge will give you two positive integers `n` and `k` as inputs and have you count the number of rectangles with integer coordinates that can be drawn with vertices touching all four sides of the \\$n \times k\\$ rectangle $$ \\{(x,y) : 0 \leq x \leq n, 0 \leq y \leq k\\}. $$ That is, there should be:

* at least one vertex with an \\$x\\$-coordinate of \\$0\\$,
* at least one vertex with an \\$x\\$-coordinate of \\$n\\$,
* at least one vertex with an \\$y\\$-coordinate of \\$0\\$, and
* at least one vertex with an \\$y\\$-coordinate of \\$k\\$.

### Example

There are \\$a(5,7) = 5\\$ rectangles with integer coordinates touching all four sides of a \\$5 \times 7\\$ rectangle:

### Table

The lower triangle of the (symmetric) table of \\$a(n,k)\\$ for \\$n,k \leq 12\\$ is

```
n\k| 1  2  3  4  5   6   7   8   9  10  11  12
---+----------------------------------------------
 1 | 1  .  .  .  .   .   .   .   .   .   .   .
 2 | 1  2  .  .  .   .   .   .   .   .   .   .
 3 | 1  1  5  .  .   .   .   .   .   .   .   .
 4 | 1  1  1  6  .   .   .   .   .   .   .   .
 5 | 1  1  1  3  9   .   .   .   .   .   .   .
 6 | 1  1  1  1  1  10   .   .   .   .   .   .
 7 | 1  1  1  1  5   1  13   .   .   .   .   .
 8 | 1  1  1  1  1   1   5  14   .   .   .   .
 9 | 1  1  1  1  1   5   1   1  17   .   .   .
10 | 1  1  1  1  1   3   1   3   1  18   .   .
11 | 1  1  1  1  1   1   5   1   5   5  21   .
12 | 1  1  1  1  1   1   1   1   5   1   1  22

```

---

This is a challenge, so the shortest code wins.

# Answer
> 6 votes
# 05AB1E, ~~10~~ 8 bytes

```
LDI-*`¢O

```

Try it online!

**Commented**:

```
          # implicit input: [n, k]
L         # for both values take the [1..x] range
          #   [[1,...,n], [1,...,k]]
 D        # duplicate this list
  I       # push the input [n,k]
   -      # subtract this from the ranges
          #   [[1-n,...,n-n], [1-k,...,k-k]]
          #  =[[-n+1,...,0], [-k+1,...,0]]
    *     # multiply with the ranges
          #   [[1*(-n+1),...,n*0], [1*(-k+1),...,k*0]]
     `    # push all lists of this list on the stack
      ¢   # count the occurences of each value of one list in the other
       O  # sum those counts

```

# Answer
> 14 votes
# Python 2, ~~66~~ 59 bytes

```
lambda n,k:sum(a%n*(n-a%n)==a/n*(k-a/n)for a in range(n*k))

```

Try it online!

Each possible rectangle inside the \\$n \times k\\$-rectangle can be specified by two integers, \\$0 \le a \lt n\\$ and \\$0 \le b \lt k\\$:

To verify a rectangle given \\$a\\$ and \\$b\\$, it suffices to check if one angle is a right angle. To do this I take the dot product of \\$\binom{b}{0}-\binom{0}{a}=\binom{-b}{a}\\$ and \\$\binom{k-b}{n}-\binom{0}{a}=\binom{k-b}{n-a}\\$ to check whether the angle at \\$\binom{0}{a}\\$ is a right angle:

$$ \langle \left( \begin{matrix} -b \\ a \\ \end{matrix}\right), \left(\begin{matrix} k-b \\ n-a \\ \end{matrix} \right) \rangle = 0 \\\Leftrightarrow a\cdot(n-a)-b\cdot(k-b)=0 \\\Leftrightarrow a\cdot(n-a)=b\cdot(k-b) $$

# Answer
> 4 votes
# C (gcc), ~~63~~ 61 bytes

Saved 2 thanks to ceilingcat!!!

```
s;a;f(n,k){for(s=a=n*k;a--;)s-=a%n*(n-a%n)!=a/n*(k-a/n);a=s;}

```

Try it online!

Port of ovs's Python answer.

# Answer
> 4 votes
# Scala, ~~65~~ ~~64~~ ~~60~~ 51 bytes

```
n=>k=>0 to n*k-1 count(a=>a%n*(n-a%n)==a/n*(k-a/n))

```

Try it online!

# Answer
> 3 votes
# JavaScript (ES6),  ~~63 58~~  56 bytes

*Saved 2 bytes thanks to @ovs*

```
(n,y=x=0)=>g=k=>(x=x||++y*k--&&n)&&(y*k==--x*(n-x))+g(k)

```

Try it online!

# Answer
> 3 votes
# Charcoal, 21 bytes

```
ＮθＮηＩΣＥθ№Ｅη×λ⁻ηλ×ι⁻θι

```

Try it online! Link is to verbose version of code. Explanation: Calculates \\$ x(n-x) \\$ for \\$ 0 \le x \< n \\$ and \\$ y(n-y) \\$ for \\$ 0 \le y \< k \\$ and counts the number of times an integer appears in both lists, which corresponds to the parallelogram with coordinates \\$ (x, 0), (0, y), (n - x, 0), (0, k - y) \\$ having 90 degree angles:

```
ＮθＮη

```

Input \\$ n \\$ and \\$ k \\$.

```
ＩΣ

```

Output the total sum of all matches found.

```
Ｅη×λ⁻ηλ

```

Calculate \\$ y(n-y) \\$ for \\$ 0 \le y \< k \\$.

```
Ｅθ№...×ι⁻θι

```

Calculate \\$ x(n-x) \\$ for \\$ 0 \le x \< n \\$ and count how many times each integer appears in the other list.

# Answer
> 3 votes
# Jelly, 8 bytes

```
r1×ḶċⱮ/S

```

A monadic Link accepting a pair of integers which yields the count.

**Try it online!** Or see the test-suite.

### How?

```
r1×ḶċⱮ/S - Link [n,k]
r1       - ([n,k]) inclusive range to 1 = [[n,n-1,...,1],[k,k-1,...,1]]
   Ḷ     - lowered range ([n,k]) = [[0,1,...,n-1],[0,1,...,k-1]]
  ×      - multiply = [[n×0,(n-1)×1,...,1×(n-1)],[k×0,(k-1)×1,...,1×(k-1)]]
      /  - reduce by - i.e.: f(A=[n×0,(n-1)×1,...,1×(n-1)], B=[k×0,(k-1)×1,...,1×(k-1)])
     Ɱ   -   map with - i.e.: [f(A,v) for v in B]
    ċ    -     count occurrences (of v in A)
       S - sum

```

# Answer
> 2 votes
# Retina, 45 bytes

```
\d+
*
L$w`(_+) (_+)
$.`*$1=$.2*$'
m`^(.*)=\1$

```

Try it online! Link includes test suite. Takes space-separated inputs. Explanation:

```
\d+
*

```

Convert the inputs to unary.

```
L$w`(_+) (_+)

```

Match all substrings that contain `_ _`. This corresponds to all pairs of \\$ 0 \le x \< n \\$ and \\$ 0 \le y \< k \\$ which are represented by the unmatched parts at the beginning and end of the string `$`` and `$'` respectively while \\$ n - x \\$ and \\$ k - y \\$ are represented by `$1` and `$2` respectively.

```
$.`*$1=$.2*$'

```

For each pair, list the (unary) products \\$ x (n - x) \\$ and \\$ y (k - y) \\$.

```
m`^(.*)=\1$

```

Count the number of times that they are equal.

# Answer
> 1 votes
# Haskell,~~53~~ 47 bytes

```
a#b=sum[1|x<-[1..a],y<-[1..b],x*(a-x)==y*(b-y)]

```

Try it online!

* Saved 6 thanks to @ovs

We use the expression `x/(b-y)==y/(a-x)` which is converted to `x*(a-x)==y*(b-y)` to avoid modulo checks.

The expression computes the ratio between sides(the second inverted) which has to be the same to be a valid rectangle.

# Answer
> 1 votes
# Perl 5, (`-p` `-Minteger`) 54 bytes

```
/ /;$_=grep$_%$'*($'-$_%$')==$_/$'*($`-$_/$'),1..$`*$'

```

Try it online! Using the same formula, and range product as ovs except the range starts from 1

# Answer
> 1 votes
# Forth (gforth), 72 bytes

```
: f 0e over 0 do dup 0 do
2dup i - i * swap j - j * = s>f f- loop loop ;

```

Try it online!

Yet another port of ovs's Python 2 answer, except that it uses nested loops. Direct loop counters are much cheaper when multiple copies are needed.

Takes `n k` from the main stack and returns the count via the FP stack.

```
: f ( n k -- f:cnt )
  0e               \ setup the initial count
  over 0 do        \ outer loop (j): 0 to n-1
    dup 0 do       \ inner loop (i): 0 to k-1
      2dup         \ ( n k n k )
      i - i * swap \ ( n k i*[k-i] n )
      j - j * =    \ ( n k i*[k-i]==j*[n-j] ) Forth boolean is 0/-1
      s>f f-       \ increment count if equal
    loop
  loop
;

```

# Answer
> 0 votes
# Java 8, 75 bytes

```
n->k->{int r=0,a=n*k;for(;a-->0;)if(a%n*(n-a%n)==a/n*(k-a/n))r++;return r;}

```

Port of *@ovs*' Python 2 answer, so make sure to upvote him!

Try it online.

---
Tags: code-golf, geometry, combinatorics, grid
---


title: Supreme Sum String

text:
# Question
Title: Supreme Sum String
# Supreme Sum String

Given an input string, return the word with the highest sum of each of its unicode characters.

## Rules

* The input should be seperated by whitespace
* The value of each word is based on the sum of each character in the word's UTF-16 code
* The output should be the first word with the highest value (in case of duplicate sums)

## Examples

```
Input: "a b c d e"
Output: "e"

Input: "hello world"
Output: "world"

Input: "this is a test"
Output: "test"

Input: "àà as a test"
Output: "àà"

Input "α ää"
Output: "α"

Input: " 隣隣隣"
Output: "隣隣隣"

Input: "      "
Output: ""

```

This is code golf, so the shortest answer wins! Good luck :)

# Answer
> 1 votes
# Husk, 5 bytes

```
←→kΣw

```

Try it online!

First time using `key-by`. Pretty fitting here.

## Explanation

```
←→kΣw
      w split into words
    k   key on
     Σ  sum of codepoints
 →     take the last(maximum) key
←      return the first in the group

```

# Answer
> 7 votes
# Perl 6, 34 bytes

```
*.words.max(*.encode('utf16').sum)

```

Try it online!

# Answer
> 6 votes
# 05AB1E, 8 bytes

```
ð¡RΣÇO}θ

```

Try it online!

**Explanation**

```
ð¡          # split input on spaces
  R         # reverse the resulting list
   Σ  }     # sort by
    ÇO      # sum of character codes
       θ    # take the last

```

# Answer
> 6 votes
# , ~~77 69 59 58 56~~ 44 bytes

A group effort now.

```
'^'=mapply
sort(-sum^utf8ToInt^scan(,""))[1]

```

Try it online!

Convert to code points, sum each word, negate, (stably) sort, return first element.

Technically the return value is a "named vector" whose value is the sum and name is the winning word, but this seems to follow the rules. If you want to return the winning word as a string, you'd have to spend 7 more bytes and wrap the above in `names()`.

# Answer
> 4 votes
# JavaScript (ES6), 81 bytes

```
s=>s.split` `.map(m=s=>m=[...s].map(c=>t+=c.charCodeAt(),t=0)&&t<=m?m:(r=s,t))&&r

```

Try it online!

# Answer
> 4 votes
# jq, ~~61~~ ~~43~~ ~~57~~ 37 characters

(~~57~~ ~~39~~ ~~53~~ 33 characters code + 4 characters command line options)

```
./" "|reverse|max_by(explode|add)

```

Sample run:

```
bash-4.4$ jq -Rr './" "|reverse|max_by(explode|add)' <<< 'àà as a test'
àà

```

Try it online!

# Answer
> 4 votes
# PowerShell, ~~74~~ 52 bytes

```
(-split$args|sort{$r=0;$_|% t*y|%{$r+=$_};$r}-u)[-1]

```

Try it online!

*Thanks to mazzy for a whopping -22 bytes.*

`-split`s the input `$args` on whitespace, pipes that into `sort` with a particular sorting mechanism `{...}` and the `-u`nique flag.

Here we're taking the current word `$_`, changing it `t`oCharArra`y`, then for each letter we're adding it into our `$r`esult. That turns the string into a number based on its UTF-16 representation.

For once, PowerShell having all strings be UTF-16 in the background is a life-saver!

We then encapsulate those results in `(...)` to transform them into an array and take the last `[-1]` one, i.e., the largest result that's the closest to the start of the sentence. This works because of the `-u`nique flag, i.e., if there's a later element that has the same value, it's discarded. That word is left on the pipeline and output is implicit.

# Answer
> 4 votes
# Pyth, ~~8~~ 7 bytes

```
eosCMNc

```

Test suite

I know there's already a Pyth answer but I feel like this uses a pretty different approach ~~and also it's waaaay shorter~~

Explanation:
```
eosCMNc  | Full code
eosCMNcQ | with implicit variables added
---------+------------------------------------
e        | The last element of
      cQ | the input chopped at whitespace
 o       | sorted by
  s      | the sum of
   CMN   | the Unicode value of each character

```

# Answer
> 3 votes
# Python 3, ~~55~~ 52 bytes

```
lambda s:max(s.split(),key=lambda w:sum(map(ord,w)))

```

Try it online!

* -3 bytes thanks to Gigaflop for pointing out that no argument is needed in the `split` method.

# Answer
> 3 votes
# Jelly, 7 bytes

```
ḲOS$ÐṀḢ

```

Try it online!

```
ḲOS$ÐṀḢ
Ḳ        Split input on spaces
    ÐṀ   Give words that have maximum of:
   $       Monad:
 O           ord(each character)
  S          sum
      Ḣ  First word that gives the max ord-sum.

```

# Answer
> 2 votes
# Japt `-h`, 8 bytes

@Emigna approach

```
¸w ñ_¬xc

```

Try it online!

---

Another Approach

# Japt `-g`, 8 bytes

```
¸ñ@-X¬xc

```

Try it online!

# Answer
> 2 votes
# MATLAB, 57 bytes

```
s=strsplit(input('','s'));[Y I]=max(cellfun(@sum,s));s(I)

```

In my MATLAB R2016a all tests arepassed, except that emojis are not rendered properly. But characters are returned correctly

# Answer
> 2 votes
# Java (JDK), ~~117~~ ~~97~~ 84 bytes

-13 bytes thanks @Nevay. Apparently I didn't know I can also use `var` in Java.

```
s->{var b="";for(var a:s.split(" "))b=a.chars().sum()>b.chars().sum()?a:b;return b;}

```

Try it online!

# Answer
> 1 votes
# Ruby, 45 characters

```
->s{s.split.max_by{|w|w.codepoints.reduce:+}}

```

Sample run:

```
irb(main):001:0> ->s{s.split.max_by{|w|w.codepoints.reduce:+}}['àà as a test']
=> "àà"

```

Try it online!

### Ruby 2.4, 40 characters

```
->s{s.split.max_by{|w|w.codepoints.sum}}

```

(Untested.)

# Answer
> 1 votes
# Pyth, 33 bytes

```
FHmCdmcd)Kczd aYu+GHmCdH0)@KxYeSY

```

Try it online!

There is almost certainly a better way to do this, but I spent too much on it so this will do.

```
FH  #For every array of letters in
  mCd   #the array of arrays of letters [['w', 'o', 'r', 'l', 'd'], ['h', 'e', 'l', 'l', 'o']]
     mcd)   #wrap that in another array [[hello"], ["world"]]
         Kczd   #split input(z) on spaces ["hello", "world"] and assign it to K for later
              aY     #append to list Y... " " silences the prints from the for loop.
                u+GH    #reduce the list of numbers by summing them
                    mCdH    #convert each letter in the array to its int counterpart
                        0)    #the zero for the accumulator and close for loop
                          @K    #get by index the word from K
                            xY   #find the index in Y of that number
                              eSY   #sort Y, get the last (largest) number

```

I would have passed a reduce into another map instead of using the for loop, but I couldn't get that to work.

# Answer
> 1 votes
# Charcoal, 20 bytes

```
≔⪪Ｓ θ≔ＥθΣＥι℅λη§θ⌕η⌈η

```

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

```
≔⪪Ｓ θ

```

Split the input string on spaces and assign to `q`.

```
≔ＥθΣＥι℅λη

```

Calculate the sum of the ordinals of the characters in each word and assign to `h`.

```
§θ⌕η⌈η

```

Find the index of the highest sum and print the word at that index.

# Answer
> 1 votes
# Powershell, 66 bytes

Straightforward. See AdmBorkBork's answer to found a smart using of Powershell.

```
-split$args|%{$s=0
$_|% t*y|%{$s+=$_}
if($s-gt$x){$w=$_;$x=$s}}
$w

```

*Note!* To correct work with unicode, save your script file with `UTF-16` or `UTF8 with BOM` encoding.

Test script:

```
$f = {

-split$args|%{$s=0         # split argument strings by whitespaces, for each word
$_|% t*y|%{$s+=$_}         # let $s is sum of unicode char code
if($s-gt$x){$w=$_;$x=$s}}  # if $s greater then previous one, store word and sum to variables
$w                         # return word from stored variable

}

@(
    ,("a b c d e", "e")

    ,("hello world", "world")

    ,("this is a test", "test")

    ,("àà as a test", "àà")

    ,("α ää", "α")

    ,(" 隣隣隣", "隣隣隣")

    ,("      ", "")
) | % {
    $s,$e=$_
    $r=&$f $s
    "$($r-eq$e): $r"
}

```

Output:

```
True: e
True: world
True: test
True: àà
True: α
True: 隣隣隣
True:

```

---
Tags: code-golf, string, unicode, text-processing
---


title: CUDDLE calculation

text:
# Question
Title: CUDDLE calculation
According to the Wikipedia page on the number 69, it is of note that \\$69^2 = 4761\\$ and \\$69^3 = 328509\\$ together use all decimal digits. The number **69** is in fact the lowest number that satisfies this property.

For a similar reason, \\$32043\\$ is remarkable: \\$32043^2 = 1026753849\\$ uses all decimal digits.

If we're going to keep talking about numbers that are interesting this way, we'll need some notation.

For most integers \\$n\\$, the powers \\$n^2, ..., n^k\\$ will use all ten decimal digits (not counting leading zeroes) at least once for sufficiently large values of \\$k\\$ . If it exists, we'll call the lowest such \\$k\\$ the *CUDDLE* (***CU**mulative **D**ecimal **D**igits, **L**east **E**xponent*) of \\$n\\$.

### Task

Write a program or a function that accepts a single non-negative integer \\$n\\$ as input and calculates and returns its *CUDDLE*.

If \\$n\\$ does not have a *CUDDLE*, you may return anything but a positive integer, including an error or an empty string, as long as your code halts eventually.

### Test cases

Left column is input, right column is output.

```
0
1
2          15
3          10
4          10
5          11
6          12
7           7
8           5
9           6
10
11          7
12          6
13          6
14          7
15          9
16          5
17          7
18          4
19          5
20         15
26          8
60         12
69          3
128         3
150         9
200        15
32043       2
1234567890  3

```

### Additional rules

* Your code must work for all inputs up to \\$255\\$.

*Note that this involves dealing with pretty large numbers. \\$20^{15}\\$ is already larger than \\$2^{64}\\$.*
* If you print the result, it may be followed by a linefeed.
* Standard rules apply.

# Answer
# Pyth, 16 bytes

```
hf<9l{=+k^QTtS15

```

Try it online: Demonstration or Test Suite

Like other solutions, I use 15 as an upper limit. I believe that this is also the maximal *CUDDLE*. I tested all numbers up to 10.000.000, and there's no number with a *CUDDLE* greater than 15.

Numbers with a *CUDDLE* \>= 10 are already quite rare. The only numbers with a *CUDDLE* of 15 are the numbers `2*10^k`. There are no numbers with a *CUDDLE* of 14 or 13, the *CUDDLE* 12 only appears for the numbers `6*10^k`, the *CUDDLE* 11 only for `5*10^k`.

So I think this code works perfectly for any natural number.

Prints an error message, if there is no solution.

### Explanation:

```
hf<9l{=+k^QTtS15   implicit: Q = input number
                             k = empty string
            tS15   the list [2, 3, 4, ..., 15]
 f                 filter this list for elements T, which satisfy:
         ^QT          compute Q^T
       +k             k + ^ (converts to string implicitly)
      = k             save the result in k
    l{  k             length of set of k (number of different chars)
  <9                  test if 9 is smaller than ^
h                  print the first number in the filtered list
                   (throws error if empty)

```
> 5 votes

# Answer
## Python 2, 56

```
f=lambda n,i=2,s='L':len(set(s))>10or-~f(n,i+1,s+`n**i`)

```

A recursive solution. Counts up exponents `i` starting from `2` and accumulates the digits of powers `n**i` into the string `s`. When `s` has all ten digits, returns `True`, which equals `1`, and otherwise recurses and adds `1`. This turned out shorter than returning `i`.

Calling the function on a number without a CUDDLE terminates with `Internal error: RangeError: Maximum call stack size exceeded`. Numbers up to `255` that do output never need more than 15 iterations.

Because of Python 2's annoying habit of appending an `L` to large numbers, we actually initialize the digit string to `L` and check if the set size is at least 11. Python 3 saves 2 chars by not needing this, but loses 3 chars on using `str` over backticks. Python 3.5 saves 2 more chars with set unpacking, saving a char over Python 2 in total:

```
f=lambda n,i=2,s='':len({*s})>9or-~f(n,i+1,s+str(n**i))

```
> 7 votes

# Answer
## Ruby, ~~67~~ 65 chars

```
->n{s='';[*2..99].index{|i|(s+="#{n**i}").chars.uniq.size==10}+2}

```

Works near-instantaneously for all the test cases, even the ones \> 255.

Errors for numbers with no CUDDLE.

Explanation:

```
-> n {                         # define function with short lambda syntax
  s = ''                       # the string we are storing the numbers in
  [*2..99]                     # for all numbers from 2 to 99...
    .index {|i|                # find index of the number `i` for which...
      (s+="#{n**i}")           # after appending pow(n,i) to s...
        .chars.uniq.size==10}  # num of uniq chars in s is 10 (each digit)
  + 2                          # add 2, because our index starts from 2
}

```
> 4 votes

# Answer
# CJam, 28 bytes

```
LliG,2>f#{s+_&_}%:,A#)_)s\g*

```

Try it online

This relies on the fact that the CUDDLE (if it exists) is never larger than 15 for the input range, as first observed by @xnor.

There's probably a better way of producing the output for the case where there's no solution. I'll update if I think of anything.

Explanation:

```
L     Push empty string, will be used for accumulating digits.
li    Get input and convert to integer.
G,    Build list of exponents [0 .. 15].
2>    Slice off first two values, to produce [2 .. 15].
f#    Apply power operator with all exponents to input.
{     Start loop over powers.
  s     Convert to string. We care about the digits here.
  +     Concatenate with previously found digits.
  _&    Uniquify using set intersection of digit list with itself.
  _     Copy for continued accumulation in next loop iteration.
}%    End of loop over powers. We'll have an extra copy of the last value here,
      but it does no harm so we just keep it.
:,    Apply length operator to accumulated digit lists.
A#    Find 10 in the list. The search result will correspond to the first power
      that resulted in 10 different accumulated digits. If not found, the result
      will be -1. Note that 0 corresponds to power 2, since that was the first
      power we used. So we need to add 2 to get the result, and check for -1.
)     Increment value. 0 now corresponds to no solution.
_     Copy this value. Will be used as multiplier to create empty string if 0.
)     Increment again, to get the +2 needed for the result.
s     Convert to string.
\     Swap once-incremented value to top, which is 0 for no solution, non-zero
      otherwise.
g     Signum to get 0/1 for no solution vs. solution.
*     Multiply with result string, to get empty string for no solution.

```
> 3 votes

# Answer
## Mathematica, 103 bytes

```
f=(d=DigitCount;x=1;y=d[0];For[n=0,!IntegerQ@Log10[#]&&MemberQ[y,0],++n,x*=#;y+=d[x]];Print[#,"\t",n])&

```

It appears that only powers of 10 would not eventually have CUDDLEs, so they are skipped. Function keeps a list of seen digits and stops when there are no longer zeros in it.

Output:

```
1    0
2    15
3    10
4    10
5    11
6    12
7    7
8    5
9    6
10    0
11    7
12    6
13    6

```
> 2 votes

# Answer
# JavaScript (ES6) 188

Not bad for a language that is limited to 53 bits integers.

Test running the snippet below in a browser that implements EcmaScripts 6, including arrow functions and spread operator (AFAIK Firefox)

```
f=n=>{for(p=1,d=[],v=n=[...n+''].reverse();++p<20;){v.map((a,i)=>n.map((b,j)=>r[j+=i]=a*b+~~r[j]),r=[],c=0),r=r.map(r=>(r+=c,c=r/10|0,d[r%=10]=r));v=c?[...r,c]:r;if(d.join``[9])return p;}}

// Less golfed
U=n=>{
// Arbitrary precision multiplication
  M=(A,B,R=[],c=0)=>
  (
    A.map((a,i)=>B.map((b,j)=>R[j+=i]=a*b+~~R[j])),
    R=R.map(r=>(r+=c,c=r/10|0,r%10)),
    c?[...R,c]:R
  );
  v=n=[...n+''].reverse();
  for(p=1,d=[];++p<20;)
  {
    v=M(n,v)

    v.map(c=>d[c]=c)
    if (d.join``[9])return p
  }
}

// TEST
for(i=o='';++i<300;)o+=i+' : '+f(i)+'\n'
O.innerHTML=o

```

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

# Answer
### PowerShell, 94 bytes

```
param($n,$s='')
2..99|%{$s+=[bigint]::Pow($n,$_);if(($s-split''|sort -U).Count-eq11){$_;break}}

(As a single line)

```

Nothing too clever about it, but piping to `sort -U[nique]` is a neat way to ape Python's `set()` functionality for this kind of use, without explicitly adding items to a hashtable.

```
param($n,$s='')                              # Take command line parameter.
2..99 |%{                                    # Loop from 2 to 99, inclusive.
    $s+=[bigint]::Pow($n,$_)                 # $n^Loopvar, concatenate to string.
    if (($s-split''|sort -U).Count-eq11) {   # Convert to unique-characters-array; count.
        $_;break                             # Print current loopvar and quit.
    }
}                                            # Otherwise, finish (silently).

```

e.g.

```
PS C:\> .\CUDDLE-of-n.ps1 10

PS C:\> .\CUDDLE-of-n.ps1 12
6

PS C:\> .\CUDDLE-of-n.ps1 255
5

```
> 2 votes

# Answer
# gawk 4, 73 + 5 for flags = 78 bytes

```
{for(n=$0;a-1023&&++i<15;j=0)for($0*=n;j++<NF;)a=or(a,2^$j)}$0=i<15?++i:_

```

For every digit `0` bis `9` it encounters in the powers of the input, it sets the bit representing `2^digit` in `a`, until the first 10 digits are found (`a == 1023 == 2^10-1`) or there's been more than 15 iterations.

Has to be called with an empty field seperator and the -M flag for big numbers.

```
echo 17 | awk -M '{for(n=$0;a-1023&&++i<15;j=0)for($0*=n;j++<NF;)a=or(a,2^$j)}$0=i<15?++i:_' FS=

```

Fiddling around with this I found the following sequences for the different CUDDLEs:

```
2: 32043 32286 33144 35172 35337 35757 35853 37176 37905 38772 39147 39336 40545 42744 43902 44016 45567 45624 46587 48852 49314 49353 50706 53976 54918 55446 55524 55581 55626 56532 57321 58413 58455 58554 59403 60984 61575 61866 62679 62961 63051 63129 65634 65637 66105 66276 67677 68763 68781 69513 71433 72621 75759 76047 76182 77346 78072 78453 80361 80445 81222 81945 83919 84648 85353 85743 85803 86073 87639 88623 89079 89145 89355 89523 90144 90153 90198 91248 91605 92214 94695 95154 96702 97779 98055 98802 99066
3: 69 128 203 302 327 366 398 467 542 591 593 598 633 643 669 690 747 759 903 923 943 1016 1018 1027 1028 1043 1086 1112 1182 1194 1199 1233 1278 1280 1282 1328 1336 1364 1396 1419 1459 1463 1467 1472 1475 1484 1499 1508 1509 1519 1563 1569 1599 1602 1603 1618 1631 1633 1634 1659 1669 1687 1701 1712 1721 1737 1746 1767 1774 1778 1780 1791 1804 1837 1844 1869 1889 1895 1899 1903 1919 1921 1936 1956 1958 1960 1962 1973 1984 1985 1991 1994 1996 2003 2017 2019 2030 2033 2053 2075 2123 2126 2134 2157 2158 2159 2168 2175 2183
4: 18 54 59 67 71 84 93 95 97 108 112 115 132 139 144 147 148 152 156 157 159 169 172 174 178 179 180 181 182 184 195 196 213 214 215 216 221 223 227 228 232 234 235 239 241 242 248 265 266 267 270 272 273 279 281 285 287 294 298 299 306 311 312 314 315 316 323 326 329 332 336 338 342 343 353 354 356 361 362 364 365 368 369 379 388 391 393 395 396 397 403 412 413 414 416 419 423 426 431 434 439 442 443 444 448 451 452 453 454 455 457 459 463 466 469 472 473 477 479 482 484 486 489 493 494 496 503 507 508 509 515 517 523
5: 8 16 19 27 28 38 44 47 55 57 61 77 79 80 82 83 86 87 91 92 103 106 113 116 117 118 121 123 125 126 129 131 133 136 138 140 141 142 143 145 146 151 154 158 160 161 165 167 173 175 176 177 183 185 186 187 189 190 191 192 193 197 198 204 207 218 224 226 229 230 231 236 240 243 246 249 253 255 257 258 259 261 263 268 269 271 275 276 277 278 280 282 283 284 286 288 289 292 293 304 309 322 328 331 339 341 344 345 346 347 348 349 352 357 359 367 371 372 373 374 375 377 380 381 384 387 389 402 407 408 409 411 417 418 422 427
6: 9 12 13 22 23 24 33 36 37 39 42 43 45 46 49 51 53 58 62 66 72 73 75 78 81 88 90 94 98 105 107 109 114 119 120 122 127 130 134 137 149 153 155 162 163 164 166 168 170 194 199 206 211 212 217 219 220 222 225 233 237 238 244 247 252 254 256 262 264 274 291 295 296 301 308 317 319 321 324 325 330 333 334 337 351 355 358 360 370 376 378 382 383 385 386 390 394 399 401 404 405 406 415 420 421 424 425 429 430 433 435 438 446 450 460 471 476 478 488 490 498 502 504 506 510 513 514 519 530 539 548 556 578 620 628 631 634 636
7: 7 11 14 17 29 31 32 35 41 48 52 56 63 64 70 74 85 89 96 99 102 104 110 111 135 171 188 201 202 205 208 245 251 290 297 303 305 307 310 313 318 320 335 350 363 392 410 465 475 480 483 485 501 511 518 520 521 560 582 584 595 601 630 640 682 700 736 740 786 798 850 890 952 956 965 975 982 990 999 1002 1005 1011 1020 1040 1054 1100 1110 1171 1219 1313 1331 1350 1379 1414 1447 1468 1601 1707 1710 1735 1748 2001 2010 2020 2050 2080 2450 2510 2534 2641 2745 2900 2914 2955 2970 3030 3050 3070 3100 3130 3136 3180 3193 3200
8: 21 25 26 30 34 65 76 124 209 210 250 260 300 340 505 650 1004 1240 2002 2090 2100 2500 2600 2975 3000 3400 3944 4376 5050 6500 6885 7399 10040 12400 15483 20002 20020 20900 21000 25000 26000 29750 30000 34000 43760 50500 65000 68850 73990
9: 15 68 101 150 1001 1010 1500 10001 10010 10100 15000
10: 3 4 40 400 4000 40000
11: 5 50 500 5000 50000
12: 6 60 600 6000 60000
15: 2 20 200 2000 20000

```
> 1 votes

# Answer
# Jelly, 13 bytes

```
*Ḋ}DFQL
çⱮ⁴i⁵

```

Try it online!

Assumes that the *CUDDLE* of a number is never greater than 16. This is a **14** byte version that only assumes the *CUDDLE* exists (runs forever for \\$n = 0, 1, 10\\$)

## How it works

```
*Ḋ}DFQL - Helper link. Takes n on the left and k on the right
  }     - To k:
 Ḋ      -   Dequeue; Yield [2, 3, ..., k]
*       - Raise each to the power n
   D    - Convert to digits
    F   - Flatten
     Q  - Deduplicate
      L - Length

çⱮ⁴i⁵ - Main link. Takes n on the left
  ⁴   - 16
 Ɱ    - Over each k in [1, 2, ..., 15, 16]:
ç     -   Run the helper link with n on the left and k on the right
    ⁵ - 10
   i  - First index of 10 or yield 0 if not present

```
> 1 votes

# Answer
# 05AB1E, 12 bytes

```
₂L.ΔL¦mS9ÝåP

```

Outputs `-1` if \\$n\\$ does not have a *CUDDLE*.

Try it online or verify all test cases.

**Explanation:**

```
₂L            # Push a list in the range [1,26]
              # (note: 26 is the smallest single-byte builtin integer above 15)
  .Δ          # Find the first integer k in this list which is truthy for:
              # (results in -1 if none were truthy)
    L         #  Push a list in the range [1,k]
     ¦        #  Remove the first item to make the range [2,k]
      m       #  Take the (implicit) input-integer to the power of each of these
       S      #  Convert the list of integers to a flattened list of digits
        9Ý    #  Push a list in the range [0,9]
          å   #  Check for each digit it it's in the flattened list of digits
           P  #  And check if this is truthy for all of them
              # (after which the result is output implicitly)

```

The `S9ÝåP` could also have been `JÙgTQ` for the same byte-count:

```
       J      #  Join the list of integers together to a single string
        Ù     #  Uniquify its characters/digits
         g    #  Pop and push its length
          TQ  #  And check that this length is equal to 10

```
> 0 votes

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


title: Aligning Lines!

text:
# Question
Title: Aligning Lines!
# Aligning Lines!

Given a character and a multiline string, your job is to pad each line of the string so they line up among the given delimiter.

## Examples

**Input:**

```
,
Programming, Puzzles
And, Code golf

```

**Output:**

```
Programming, Puzzles
        And, Code golf

```

# Input

The input will be a multiline string and a character (which you will align among), you may take these in any order / format you wish. The character will appear exactly once per line. Each line of the input may be different in length.

Input can be through function arguments or STDIN.

# Output

The output should be the same string centered. You are allowed one trailing newline and no trailing whitespace.

The output should be padded with the *minimum* amount of spaces. You may not remove any leading whitespace in the input (if it exists).

Output can be from function return or STDOUT.

# Answer
# Pyth, 18 bytes

```
V.z+*d-eSxRz.zxNzN

```
> 6 votes

# Answer
# APL (37)

APL just isn't very good at string processing (or I'm not good at golfing, of course).

```
{⌽∊R,¨' '/⍨¨(⌈/-+)⍺⍳⍨¨⌽¨R←S⊂⍨S=⊃S←⌽⍵}

```

This takes the character as its left argument, and the multiline string as its right argument. It is assumed that the multiline string ends in a linefeed (e.g. `A\nB\nC\n` rather than `A\nB\nC`.) Since I can use "any format \[I\] wish", and this is also the conventional format for text files, I think this is reasonable.

Explanation:

* `S←⌽⍵`: reverse the string, and store it in `S`.
* `R←S⊂⍨S=⊃S`: split `S` on its first character, and store the array of strings in `R`.
* `⍺⍳¨⌽¨R`: reverse each string in `R`, and then find the index of ⍺ (the character) in each string.
* `(⌈/-+)`: subtract each of the indices from the largest index, giving the amount of spaces needed
* `' '/⍨¨`: for each of those values, generate that many spaces
* `R,¨`: add the spaces to each string in `R`.
* : join all the strings together
* : reverse it (to get the original order back)

Example:

```
      NL←⎕UCS 10 ⍝ newline
      test←'Programming, Puzzles',NL,'And, Code golf',NL
      test ⍝ test string
Programming, Puzzles
And, Code golf

      ⍝ run the function
      +X←','{⌽∊R,¨' '/⍨¨(⌈/-+)⍺⍳⍨¨⌽¨R←S⊂⍨S=⊃S←⌽⍵}test
Programming, Puzzles
        And, Code golf

      ⍴X ⍝ result is really a string with newlines, not a matrix
44

```
> 13 votes

# Answer
# CJam, ~~23~~ ~~22~~ 20 bytes

*Thanks to Dennis for saving 2 bytes.*

```
ea_rf#_:e>\fm.{S*\N}

```

This reads the lines from command-line arguments and the character from STDIN.

The online interpreter doesn't support command-line arguments, but you can test an equivalent version here.

## Explanation

```
ea    e# Get the lines from ARGV.
_rf#  e# Duplicate input, read the character and find index of character in each line.
_:e>  e# Duplicate indices and find maximum.
\fm   e# Subtract each index from the maximum index.
.{    e# Apply this block to each pair of line and (max_index - index).
  S*  e#   Get a string with the right amount of spaces.
  \N  e#   Swap spaces with line and push a line feed.
}

```
> 9 votes

# Answer
# Pip, ~~22~~ ~~20~~ 18 + 1 = 19 bytes

```
Y_@?qMgsX(MXy)-y.g

```

Takes strings as command-line arguments and delimiter from STDIN (*idea borrowed from Martin's CJam answer*). Uses `-n` flag to print output values on separate lines.

```
                    g is list of cmdline args; s is space (implicit)
    q               Read the delimiter from stdin
 _@?                Construct a lambda function that takes a string and returns
                       the index of the delimiter in it
     Mg             Map that function to each remaining item in g
Y                   Yank the resulting list of indices into the variable y

         (MXy)-y    Take the max of y minus each element in y
       sX           Space, repeated that many times...
                .g  ... concatenated to each item in g
                    Print, newline-separated (implicit, -n flag)

```

And an example run:

```
C:\Users\dlosc> pip.py -ne Y_@?qMgsX(MXy)-y.g "Programming, Puzzles" "And, Code golf"
,
Programming, Puzzles
        And, Code golf

```
> 9 votes

# Answer
# Pyth, ~~27~~ 24 bytes

```
V.z+.[deSmxdz.z<NJxNz>NJ

```

Updated for the latest Pyth.

Live demo.

## 27-byte version

```
jbm+.[eSmxkz.z<dJxdz\ >dJ.z

```

Live demo.
> 7 votes

# Answer
# JavaScript ES 2015, 113 bytes

```
f=(c,s)=>s.split`
`.map((e,_,a)=>' '.repeat(a.map(j=>j.indexOf(c)).reduce((g,h)=>g>h?g:h)-e.indexOf(c))+e).join`
`

```

Not quite as short as the golfing languages posted so far. Takes input as two function arguments, e.g. `f(',','Programming, Puzzles\nAnd, Code golf')`. The snippet below is ungolfed and includes an easy method to test.

```
f=function(c,s){
  return s
    .split('\n')
    .map(function(e,_,a){
      return ' '.repeat(
        a.map(function(f){
          return f.indexOf(c)
        }).reduce(function(g,h){
          return g>h?g:h
        })-e.indexOf(c)
      )+e
    })
    .join('\n')
}

run=function(){document.getElementById('output').innerHTML=f(document.getElementById('char').value,document.getElementById('string').value)};document.getElementById('run').onclick=run;run()
```

```
<label>Character: <input type="text" id="char" value="," maxlength="1" /></label>
<textarea id="string" rows="4" cols="30" style="display:block">
Programming, Puzzles
And, Code Golf</textarea><button id="run">Run</button><br />
<pre id="output"></pre>
```
> 7 votes

# Answer
# Dyalog APL, ~~22~~ ~~20~~ 16 bytes

-4 thanks to ngn.

APL is actually not so bad at string processing, if allowed to work with arrays. In this challenge, we may chose the most appropriate format, which for APL means a vector of text vectors as left argument, and the delimiter as a scalar right argument. This even handles multiple delimiters per line, and aligns the first one of each line.

```
⊣,¨⍨' '⍴¨⍨⌈.⍳-⍳¨

```

`⊣,¨⍨` prepend each line with

`' '⍴¨⍨` as many spaces as

`⌈.⍳` the rightmost index of the character among the lines

`-` minus

`⍳¨` the index of the character in each line

Try APL online! ( added to print output vertically)

**Bonus?** Works for any number of strings, and delimiters (aligns by left-most).
> 6 votes

# Answer
## Python 3, 85 (IDLE 3.2.2, Windows)

```
c,*s=input().split('\n')
for x in s:print(' '*(max(z.find(c)for z in s)-x.find(c))+x)

```

Pretty straightforward. This finds the position of the character in the string twice: once to find the max (well, once per line), and once to find the offset. I tried combining these but it was longer.

Python 3 is used for the input unpacking. MY IDLE seems to take multiline strings as input.
> 5 votes

# Answer
# Julia, 117 bytes

```
f(c,t)=(s=[split(l,c)for l=split(t,"\n")];join(map(i->lpad(i[1],maximum(map(i->length(i[1]),s))," ")*c*i[2],s),"\n"))

```

Ungolfed:

```
function f(c::String, t::String)
    # Create an array of arrays by splitting on newlines and
    # then on the given delimiter
    s = [split(l, c) for l in split(t, "\n")]

    # Find the maximum length on the left side of the delimiter
    m = maximum(map(i -> length(i[1]), s))

    # Rejoin on the delimiter and pad each line with spaces,
    # and rejoin this with newlines
    join(map(i -> lpad(i[1], m, " ") * d * i[2], s), "\n")
end

```
> 5 votes

# Answer
# Jelly, 12 bytes

```
Ỵ©w€µạṀ⁶ẋż®Y

```

**Try it online!**

Done and golfed with caird coinheringaahing in **J**elly **H**yper **T**raining (JHT), our Jelly practice chat room.

### How it works

The third command line argument (first input) should be the multi-line string, and the character should be the fourth command line argument (second input).

```
Ỵ©w€µạṀ⁶ẋż®Y  ~ Full program.

Ỵ             ~ Split the string by newlines.
 ©            ~ Copy the result to the register.
  w€          ~ Get the index of the first occurrence of the character on each line.
      Ṁ       ~ Take the maximum.
    µạ        ~ And subtract it from each index, taking the absolute value.
       ⁶ẋ     ~ Repeat a space that many times (vectorizes).
         ż®   ~ Interleave with what was stored in the register.
           Y  ~ Join by newlines and print implicitly.

```

I am not sure whether taking input as a list of lines is allowed, so this takes a multiline string as input. If it were allowed:

### 10 bytes

```
w€µạṀ⁶ẋż³Y

```

Try it online!
> 4 votes

# Answer
# Kakoune, 9 bytes

```
s\Q<c-r>"<ret><a-h><a-;>&

```

(`<c-x>` means CTRL+x, `<a-x>` is alt)

Expects the delimited in the "-register, the input in the default buffer and the cursor spanning the entire buffer.

Explanation:

```
s        <ret>             Match the contents of the current selection on the following regex, select every part that matches
 \Q                        Quote, everything after this only matches itself literally (avoiding problems with . etc)
   <c-r>"                  Dump the contents of the "-register (containing the char to align on)
              <a-h>        Select to the beginning of the line for each selection
                   <a-;>   "flip" each selection, so that the anchor is at the end.
                        &  Align everything

```

This might be stretching the allowed input format a bit, so here's a solution which takes the input exactly like the challenge example, in the default buffer, with the cursor at (0, 0):

# Kakoune, 13 bytes

```
xd%s\Q<c-r>"<backspace><ret><a-h><a-;>&

```

This is basically the same solution, with a prelude deleting the delimiter and putting it into the "-register. Note that the newline is also put into the register, which the `<backspace>` deletes.
> 4 votes

# Answer
# C# 4.0, ~~329~~ ~~320~~ 307 bytes

```
using System;class P{static void Main(){Func<char,dynamic>f=(d)=>Console.ReadLine().Split(d);var c=f(' ')[0][0];var m=0;var l=new string[9999][];var z=0;for (l[z]=f(c);l[z].Length==2;l[z]=f(c)){m=Math.Max(l[z][0].Length,m);z++;}for(var i=0;i<z;i++){Console.WriteLine("{0,"+m+"}"+c+"{1}",l[i][0],l[i][1]);}}}

```

Ungolfed version :

```
using System;
class P
{
    static void Main()
    {
        // lamba to to read a line and split on a char, returns an array of
        Func<char,dynamic>f=(d)=>Console.ReadLine().Split(d);
        // read the separator char by taking the first char of the first string
        // in the array
        // use our lambda
        var c=f(' ')[0][0];
        var m=0; // max position where char is found
        var l=new string[9999][]; // hold all input
        var z=0; // count valid entries in l
        // loop until the input doesn't contain an
        // array with 2 elements
        // here we use our lambda agian, twice
        for (l[z]= f(c);l[z].Length==2;l[z] = f(c))
        {
            // calculate max, based on length
            // of first element from the string array
            m=Math.Max(l[z][0].Length,m);
            z++; // increase valid items
        }
        // loop over all valid items
        for(var i=0;i<z;i++)
        {
        // use composite formatting with the padding option
        // use the max to create a format string, when max =4
        // and seperator char is , this will give
        // "{0,4},{1}"
            Console.WriteLine("{0,"+ m +"}"+c+"{1}",l[i][0],l[i][1]);
        }
    }
}

```

It does accept a maximum of 9999 lines ...
> 3 votes

# Answer
# Common Lisp, 101 bytes

```
(lambda(c l)(dolist(x l)(format t"~,,v@a~%"(-(apply'max(mapcar(lambda(x)#1=(position c x))l))#1#)x)))

```

The first parameter is the character, the second is a list of string to be aligned.

Try it online!
> 3 votes

# Answer
# 05AB1E, ~~10~~ 9 (or 5?) bytes

```
U|XδkZαú»

```

Try it online.

If the I/O of the multi-line string could be a list of lines, this would be **5 bytes** instead:

```
δkZαú

```

Try it online.

**Explanation:**

```
U          # Store the first input-character in variable `X`
 |         # Take the other input-lines as a list of strings
   δ       # For each string:
  X k      #  Get the 0-based index of character `X` in this string
     Z     # Push the maximum index (without popping the list itself)
      α    # Take the absolute difference of this maximum with the integer-list
       ú   # Pad each string of the (implicit) input-list (because we've used `|`) with
           # that many leading spaces
        »  # And join the list by newlines
           # (after which it is output implicitly as result)

δ          # For each string in the second (implicit) input-list
 k         #  Get the 0-based index of the first (implicit) input-character
  Zαú      # Same as above
           # (after which the list of strings it output implicitly as result)

```
> 3 votes

# Answer
## Matlab / Octave, 106 bytes

Function that uses three separate arguments for character, string, string; and gives result in stdout:

```
function f(c,s,t)
p=find(s==c)-find(t==c);disp([repmat(32,1,max(-p,0)) s]),disp([repmat(32,1,max(p,0)) t])

```

Example in Matlab:

```
>> f(',', 'Programming, Puzzles', 'And, Code golf')
Programming, Puzzles
        And, Code golf

```

Or try it online with Octave interpreter.
> 2 votes

# Answer
# Julia, 80 bytes

```
f(c,s)=(t=split(s,'
');u=[search(i,c)for i=t];join([" "].^(maxabs(u)-u).*t,'
'))

```

Ungolfed:

```
function f(c,s)
  # converts multiline string to array of single-line strings
  t=split(s,'\n')

  # creates array of positions of delimiter
  u=[search(i,c)for i=t]

  # Appends appropriate number of spaces to each line
  # (uses elementwise operations to achieve this result)
  v=[" "].^(maxabs(u)-u).*t

  # Recombines array of strings to multiline string and returns
  return join(v,'\n')
end

```
> 2 votes

# Answer
# JavaScript (ES6), 105

Using template strings, the 2 newlines are significant and counted.

Test running the snippet in any EcmaScript 6 compatible browser (that is FireFox. Chrome does not support default parameters)

```
f=(s,c,p=(s=s.split`
`).map(r=>m<(v=r.indexOf(c))?m=v:v,m=0))=>s.map((r,i)=>' '.repeat(m-p[i])+r).join`
`

// Ungolfed
f=(s,c)=>{
  s=s.split('\n')
  p=s.map(r=>r.indexOf(c))
  m=Math.max(...p)
  s=s.map((r,i)=>' '.repeat(m-p[i])+r)
  return s.join('\n')
}

// TEST
out=x=>O.innerHTML+=x+'\n'

out(f(`Programming, Puzzles
And, Code golf`,','))
```

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

# Answer
# Python 2, 93 bytes

```
def f(x,y,z):
 p=y.index(x)-z.index(x)
 if p<0:y=" "*abs(p)+y
 else:z=" "*p+z
 print y+'\n'+z

```

Called like so:

```
f(',','Programming, Puzzles','And, Code Golf')

```
> 2 votes

# Answer
# Ruby, 74 bytes

```
l=lambda{|d,s|s.each{|e|puts ' '*(s.map{|f|f.index(d)}.max-e.index(d))+e}}

```

and call it like

```
l.call ',',['Programming, Puzzles','And, Code golf']

```
> 2 votes

# Answer
## R, 68 bytes

```
function(c,x,y,r=regexpr)cat(x,"\n",rep(" ",r(c,x)-r(c,y)),y,sep="")

```

Unnamed function that takes `3` inputs; `c` which is the character to align, `x` is the first string and `y` the second string.

In R, the function `regexpr` returns the position of a given pattern in a string. The solution works by applying `regexpr` on both strings and repeating white spaces amounting to the difference and subsequently just print both inputs separated by a newline.
> 2 votes

# Answer
# Japt `-R`, 13 bytes

```
·mqV Õvù ÕmqV

```

Try it

```
·mqV Õvù ÕmqV     :Implicit input of string U & delimiter V
·                 :Split U on newlines
 m                :Map
  qV              :  Split on V
     Õ            :Transpose
      v           :Modify first element
       ù          :  Left pad with spaces to the length of the longest
         Õ        :Transpose
          m       :Map
           qV     :  Join with V
                  :Implicit output joined with newlines

```
> 2 votes

# Answer
# C#, 191

As a function. Roughly a porting of my JS answer.

```
using System.Linq;string f(string s,char c){var q=s.Split('\n');int m=0,v;Array.ForEach(q,x=>m=m<(v=x.IndexOf(c))?v:m);return String.Join("\n",q.Select(x=>new String(' ',m-x.IndexOf(c))+x));}

```
> 1 votes

# Answer
# Python 2, ~~67~~ 66 bytes

```
def a(d,l):
 i=l[0].index(d)
 for e in l:print' '*(i-e.index(d))+e

```

Called with:

```
a(',', ['Programming, Puzzles', 'And, Code golf'])

```
> 1 votes

# Answer
## Moonscript, 138 bytes

```
(n)=>
 i=0
 @='
'..@
 l=[b-a for a,b in @gmatch "
().-()"..n]
 m=math.max unpack l
 (@gsub '
',(a)->
  i=i+1
  a..(' ')\rep m-l[i])\sub(2)

```

This returns a function which takes 2 arguments. The first is the string, the second is the character to align on. These arguments are the implicit argument @, and n.

First, I append a new line to the string, to make processing easier.

```
@='
'..@

```

Now, I generate a list of the positions of every alignment character, using `gmatch`. Next, I replace the newline before every line with the correct number of spaces, then trim the newline I added at the beginning.
> 1 votes

# Answer
# Lua, 169 bytes

```
function a(d,t)m={}for k,v in pairs(t)do m[#m+1]=string.find(v,d)end o=math.max(unpack(m))for k,v in pairs(t)do print(string.rep(" ",o-(string.find(v,d)or 0))..v)end end

```

Not as short as other answers but this is my first one :D
> 1 votes

# Answer
# Retina, 71 bytes

```
+`^((.)(.*¶)*)((.)*\2.*¶)((?<-5>.)*(?(5)\2|(.)\2).*)
$1$#7$* $4$#5$* $6

```

Try it online! Note: This leaves the alignment character in the output; it can be deleted at a cost of 4 bytes. If only two strings need to be aligned, then for 52 bytes:

```
^(.)¶((.)*\1.*¶)((?<-3>.)*(.)*\1.*)
$#5$* $2$#3$* $4

```

Explanation:

```
^(.)¶

```

This matches the alignment character.

```
((.)*\1.*¶)

```

This matches the first line and also keeps track of how many characters there were before the alignment character. (.NET keeps a match stack for each variable, in this case, `$3`.)

```
((?<-3>.)*(.)*\1.*)

```

This matches the second line, trying to account for as many characters as we found on the first line. `?<-3>` causes the match to pop the stack for each character, until it is empty, at which point the match fails, and the `(.)*` then matches the remaining characters before the alignment character. At this point we have the following variables:

* `$1` contains the alignment character
* `$2` contains the first line
* `$3` contains a stack whose length is the first line prefix minus the second line prefix
* `$4` contains the second line
* `$5` contains a stack whose length is the second line prefix minus the first line prefix

`$#5$*` then prefixes the necessary number of spaces to make the first line align with the second, and vice versa for `$#3$*`.

Similar logic applies to the main answer, except here we have to find two lines which don't align so that we can align them (this is where the `?(5)` comes in) and then repeat the alignment over all the lines until they are all equally aligned.
> 1 votes

# Answer
# Perl 5 `-MList::Util=max`, ~~69~~ 64 bytes

```
$l=max map{/$d/xg;pos}($d,@a)=<>;say map{/$d/x;$"x($l-pos).$_}@a

```

Try it online!
> 1 votes

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


title: Align a list of numbers

text:
# Question
Title: Align a list of numbers
Perhaps something like this is here already, but I couldn't find it.

It is not the same as Aligning Lines!.

## Example:

### Input:

```
98.6
$2,750.17
-$23
-86
3,120,487.19

```

### Output:

```
       98.6
   $2,750.17
     -$23
      -86
3,120,487.19

```

Note that `.6` isn't right-padded to `.60` or `.6` .

## Input:

* A list/array of strings (or lines from stdin), each one containing a number, without leading or trailing whitespace
* Some may begin with begin with a negative sign (`-`), and/or a currency symbol (`$`), in that order
* Some may contain a decimal mark (`.`)
* Digits before the decimal mark will sometimes be grouped into threes and separated by commas

## Output:

* A list/array (or stdout)
* Each entry is left padded with spaces so that the actual or implied decimal marks align
* No trailing whitespace

This is , so shortest code wins.

---

## Update:

This first attempt has turned into a valuable learning experience: **always use the sandbox**.

* My first version was overly complicated, and I trimmed it down a lot before actually posting.
* I simplified it again in response to the quite valid comments that soon arrived.
* Unfortunately, the resulting question ended up too simple (effectively a duplicate of the question that I said wasn't), with most of the description of the input becoming irrelevant.
* Somewhere in there I managed to lose the original intent, which was to process only what are valid numbers while leaving other strings alone. (The idea came from a function in an existing program that does just that, its purpose being to turn all strings into something that will look good if everything is printed left-justified.)

When posing a problem, take more time to think it through, and as I said: **always use the sandbox**.

# Answer
# 05AB1E, ~~19~~ ~~18~~ ~~15~~ 10 bytes

Code:

```
'.©«®δkZαú

```

Try it online! Explanation:

```
'.©«             # append . to each element
    ®δk          # Find index of . for all elements
       Z         # Get the largest
        α        # Get the absolute difference between the indices
         ú       # Pad by that much

```
> 8 votes

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

Anonymous tacit prefix function taking and returning a list of strings.

```
⊢,¨⍨' '⍴¨⍨∘(⌈/-⊢)⍳¨∘'.'

```

Try it online!

the strings

`,¨⍨` each prepended with

`' '` space

`⍴⍨¨`**r**eshaped to each of the shapes

`∘(``)` of:

`⌈/` the maximum (lit. larger-value reduction)

`-` minus

the values of

`⍳¨` the index (1+length if not found) in each

of:

`'.'` a decimal mark
> 5 votes

# Answer
# Retina, 12 bytes

```
mP^`^[^.\n]+

```

Try it online! Explanation:

```
m`^[^.\n]+

```

Match up to the first `.` or the end of each line.

```
P^`

```

Pad matches on the left with spaces to the same length.
> 4 votes

# Answer
# Kakoune, 11 bytes

```
s^[^\n.]+<ret>&

```

(`<ret>` is the return key)

This solution assumes the input is in the default buffer, and the entire buffer being selected. `%` can be prepended to the solution if the entire buffer is not selected.

Explanation:

```
s        <ret>      Search for this regex in the current selection, reduce the selection to the matches
 ^[^\n.]+           The regex to search for, it matches every line until the end or a decimal point
               &    Align all selections

```
> 4 votes

# Answer
# , 29 27 bytes

```
((,~#&' ')&.>>./-])i.&'.'&>

```

Try it online!

*-2 thanks to xash*

Inspired by Adam's APL answer.
> 3 votes

# Answer
# , 61 bytes

```
function(n)paste0(strrep(" ",max(x<-regexpr("\\.|$",n))-x),n)

```

Try it online!

```
function(n)						# function:
	paste0(						# concatenate
	       strrep(" ",				# " " repeated this many times:
			   max(				# (the max of
			       x<-regexpr("\\.|$",n)	# the position of the first "." OR the end of the line
				)-x)			# minus the position of the first "." OR the end of the line)
		,n)					# with n
							# and return

```
> 2 votes

# Answer
# Japt, 14 bytes

I/O as an array.

```
®q.ÃÕvù Õ®f q.

```

Try it

```
®q.ÃÕvù Õ®f q.     :Implicit input of array
®                  :Map
 q.                :  Split on "."
   Ã               :End map
    Õ              :Transpose
     v             :Modify first element
      ù            :  Left pad with spaces to the length of the longest
        Õ          :Transpose
         ®         :Map
          f        :  Filter ('Cause transposing arrays fills gaps with null)
            q.     :  Join with "."

```
> 2 votes

# Answer
# Ruby 2.7, 54 bytes

```
->s{s.map{|e|' '*-((e=~r=/\.|$/)-s.map{_1=~r}.max)+e}}

```

Try it online!

TIO uses an older version of Ruby, so `_1` is replaced with `|c|c` for 2 extra bytes.
> 2 votes

# Answer
# Husk, 24 bytes

```
mṠ+(R' ≠▲m₂¹₂
?€'.o→L€'.

```

Try it online!

Now corrected.

## Explanation

```
Function ₂: location of dot in string if exists, else length - 1
?€'.o→L€'.

Main function:
mṠ+(R' ≠▲m₂¹₂
m             map each string to the following:
            ₂ take current dot position
        ▲m₂¹  take the highest dot position
       ≠      and take absolute difference with it
    R'        repeat space that many times
 Ṡ+(          prepend this to the string

```
> 1 votes

# Answer
# Perl 5 `-00pa` `-MList::Util+max`, 54 bytes

```
s~^[^.
]+~$"x(max(map{/\.|$/;"@-"}@F)-length$&).$&~mge

```

Try it online!
> 1 votes

# Answer
# Python 3, 63 bytes

```
lambda a:[(max(map(len,a))-(s+'.').find('.'))*' '+s for s in a]

```

Try it online!

Pad decimals to the length of the longest string in the input array. This results in leading whitespace.

---

# Python 3, 80 bytes

```
lambda a:[(max((s+'.').find('.')for s in a)-(s+'.').find('.'))*' '+s for s in a]

```

Try it online!

If leading whitespace were not allowed.
> 1 votes

# Answer
# JavaScript (Node.js), ~~105~~ ~~91~~ 76 bytes

-14 bytes thanks to Giuseppe's answer
-15 bytes thanks to Shaggy!!

```
a=>a.map((w,i)=>''.padEnd(Math.max(...b=a.map(s=>s.search(/\.|$/)))-b[i])+w)

```

Try it online!
> 0 votes

# Answer
# Wolfram Language (Mathematica), 82 bytes

```
""<>{" "~Table~#,#2}&~MapThread~{Max[x=#&@@@StringLength@StringSplit[#,"."]]-x,#}&

```

Try it online!
> 0 votes

# Answer
# C, ~~163~~ ~~141~~ 137 bytes

```
#define f(k)for(char**j=i;*j;++j){char*c=strchr(*j,46);u=c?c-*j:strlen(*j);k;}
u,v;a(char**i){f(v=v>u?v:u)f(printf("%*s%s\n",v-u,"",*j))}

```

Try it online!

Sadly C isn't the best at strings. Requires a null entry after the last passed in strung to denote end of array.
> 0 votes

# Answer
# Red, 132 bytes

```
func[b][m: 0 foreach s b[m: max m index? any[find s"."tail s]]forall
b[t: tail b/1 pad/left b/1 m - 1 + offset? any[find b/1"."t]t]]

```

Try it online!
> 0 votes

# Answer
# Charcoal, 25 bytes

```
ＷＳ⊞υ⮌⪪ι.←⮌Ｅυ⮌⊟ι↘→Ｅυ∧ι⁺.⊟ι

```

Try it online! Link is to verbose version of code. Input list needs to be newline-terminated. Assumes a maximum of one `.` in each element. Explanation:

```
ＷＳ

```

Loop through each element of the input list.

```
⊞υ⮌⪪ι.

```

Reverse split each of them on `.`, so that the part to be padded is the last part of the split.

```
←⮌Ｅυ⮌⊟ι

```

Extract the parts to be padded, reverse them, reverse the whole list, and then print the result upside-down. This is almost the same as printing them in order, except that the output is now right-aligned rather than left-aligned.

Move the cursor so that the decimal portions can be printed.

```
→Ｅυ∧ι⁺.⊟ι

```

For each element, print its decimal portion if any, otherwise skip that line (actually by printing an empty array, but fortunately that has the same output as an empty string.)
> 0 votes

# Answer
# Factor, 159 bytes

```
: f ( b -- b ) dup dup
[ 46 suffix 46 swap index ] map
[ [ [ length ] map ] dip [ - ] 2map ] keep
0 [ max ] reduce [ + ] curry map
32 [ pad-head ] curry 2map ;

```

Try it online!

As if my Red solution wasn't long enough :)

# Factor, 200 bytes

```
: f ( b -- b ) [ "."split ] map
[ [ first ] map ] [ [ rest concat ] map ] bi
[ dup [ length ] [ max ] map-reduce
32 [ pad-head ] 2curry map ] dip zip
[ dup last { } = [ concat ] [ "."join ] if ] map ;

```

Try it online!

Here I wanted to try a different approach: I split all strings at ".", find the longest integer part and pad all such parts with as many spaces, then zip and join (or concat in case of empty fractional part) with ".".
> 0 votes

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


# Question
Title: Print the nth Fibonacci number containing the nth Fibonacci number!
# Challenge

You must write a program that takes a positive integer `n` as input, and outputs the `n`th Fibonacci number (shortened as Fib# throughout) that contains the `n`th Fib# as a subtring. For the purposes of this challenge, the Fibonacci sequence begins with a `1`.

Here are some examples that you can use as test cases, or as examples to clarify the challenge (for the latter, please leave a comment down below explaining what you find unclear).

```
n=1
Fib#s: 1
       ^1 1st Fib# that contains a 1 (1st Fib#)
Output: 1

n=2
Fib#s: 1, 1
       ^1 ^2 2nd Fib# that contains a 1 (2nd Fib#)
Output: 1

n=3
Fib#s: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233
             ^1              ^2                   ^3 3rd Fib# that contains a 2 (3rd Fib#)
Output: 233

n=4
Output: 233

n=5
Output: 6765

n=6
Output: 28657

n=7
Output: 1304969544928657

n=8
Output: 14472334024676221

n=9
Output: 23416728348467685

n=10
Fib#s: 1, ..., 34, 55, 89, ..., 63245986, 102334155, 165580141, ..., 2880067194370816120, 4660046610375530309
                   ^1                     ^2         ^3                                   ^10 10th Fib# that contains a 55 (10th Fib#)
Output: 4660046610375530309

```

---

As always, this is , so go for the lowest byte count possible.

If something is confusing/unclear, please leave a comment.

(This challenge is based off another challenge I posted: Print the nth prime that contains n)

# Answer
> 12 votes
# Haskell, ~~85~~ 84 bytes

EDIT:

* -1 byte: Laikoni shortened `l`.
* Typo (`x>=s` for `x<=s`) in explanation.

`f` takes an `Int` and returns a `String`.

```
l=0:scanl(+)1l
m=show<$>l
f n|x<-m!!n=[y|y<-x:m,or[x<=s|s<-scanr(:)""y,x++":">s]]!!n

```

Try it online!

# How it works

* `l` is the infinite list of Fibonacci numbers, defined recursively as the partial sums of `0:1:l`. It starts with `0` because lists are 0-indexed. `m` is the same list converted to strings.
* In `f`:
    + `n` is the input number, and `x` is the (string of the) `n`th Fibonacci number.
    + In the outer list comprehension, `y` is a Fibonacci number tested for whether it contains `x` as a substring. The passing `y`s are collected in the list and indexed with the final `!!n` to give the output. An extra `x` is prepended to the tests to save two bytes over using `!!(n-1)` at the end.
    + To avoid counting `y`s several times, the tests of each `y` are wrapped in `or` and another list comprehension.
    + In the inner list comprehension, `s` iterates through the suffixes of `y`.
    + To test whether `x` is a prefix of `s`, we check whether `x<=s` and `x++":">s`. (`":"` is somewhat arbitrary but needs to be larger than any numeral.)

# Answer
> 10 votes
# Jelly, ~~15~~ 14 bytes

1 byte thanks to Jonathan Allan.

```
0µ³,ÆḞẇ/µ³#ÆḞṪ

```

Try it online!

# Answer
> 5 votes
# Python 2, 99 86 bytes

* Ørjan Johansen Saved 7 bytes: starting with `b=i=x=-1 a=1` and dropping the `x and`
* Ørjan Johansen again saved 3 bytes: `f and n==2` to `f*(n>2)`
* Felipe Nardi Batista saved 9 bytes: economic swap `a,b=a+b,a` shorthand `f-=str(x)in str(a)`, squeezed `(n<2)*f`
* ovs saved 13 bytes: transition from python 3 to python 2.

```
f=n=input()
b=i=x=-1
a=1
while(n>2)*f:i+=1;a,b=a+b,a;x=[x,a][i==n];f-=`x`in`a`
print a

```

Try it online!

Explanation:

```
f=n=int(input())                 # f is number of required numbers

b=i=x=-1                         # i is index(counter) set at -1
                                 # In Two-sided fibonacci, fib(-1) is 1
                                 # and b(fib before it) i.e. fib(-2) is -1
                                 # Taking advantage of all -1 values, x is
                                 # also set to -1 so that the `if str(...`
                                 # portion does not execute until x is set a
                                 # value(i.e. the nth fibonacci) since there
                                 # is no way -1 will be found in the number
                                 # (ALL HAIL to Orjan's Genius Idea of using
                                 # two-sided fibonacci)

a=1                              # fib(-1) is 1

while(n>2)*f:                    # no need to perform this loop for n=1 and
                                 # n=2 and must stop when f is 0

 i+=1                            # increment counter

 b,a=a,a+b                       # this might be very familiar (fibonacci
                                 # thing ;))

 x=[x,a][i==n]                   # If we have found (`i==n`) the nth
                                 # fibonacci set x to it

 f-=`x`in`a`                     # the number with required substring is
                                 # found, decrease value of f

print a                          # print required value

```

# Python 3, 126 120 113 112 110 101 99 bytes

```
f=n=int(input())
b=i=x=-1
a=1
while(n>2)*f:i+=1;a,b=a+b,a;x=[x,a][i==n];f-=str(x)in str(a)
print(a)

```

Try it online!

# Answer
> 4 votes
# Java, ~~118~~ 111 bytes

```
i->{long n=i,p=0,q,c=1;for(;--n>0;p=c,c+=q)q=p;for(n=c;i>0;q=p,p=c,c+=q)if((""+c).contains(""+n))--i;return p;}

```

I keep thinking it should be possible not to duplicate the Fibonacci bit, but all my efforts somehow result in more bytes.

Thanks to Kevin for improvements... guess it shows this was my first attempt at golfing :)

# Answer
> 2 votes
# Perl 6, 45 bytes

```
{my@f=0,1,*+*...*;@f.grep(/$(@f[$_])/)[$_-1]}

```

`$_` is the argument to the function; `@f` is the Fibonacci sequence, lazily generated.

# Answer
> 2 votes
# JavaScript (ES6), ~~96~~ ~~93~~ ~~92~~ ~~90~~ 86 bytes

0-indexed, with the 0th number in the sequence being `1`. Craps out at `14`.

```
f=(n,x=1,y=1)=>n?f(n-1,y,x+y):x+""
g=(n,x=y=0)=>x>n?f(y-1):g(n,x+!!f(y++).match(f(n)))

```
* ~~2~~ 6 bytes saved thanks to Arnauld

---

## Try it

```
f=(n,x=1,y=1)=>n?f(n-1,y,x+y):x+""
g=(n,x=y=0)=>x>n?f(y-1):g(n,x+!!f(y++).match(f(n)))
oninput=_=>o.innerText=(v=+i.value)<14?`f(${v}) = ${f(v)}\ng(${v}) = `+g(v):"Does not compute!"
o.innerText=`f(0) = ${f(i.value=0)}\ng(0) = `+g(0)
```

```
<input id=i min=0 type=number><pre id=o>
```

---

## Explanation

Updated version to follow, when I get a minute.

```
f=...                   :Just the standard, recursive JS function for generating the nth Fibonacci number
g=(...)=>               :Recursive function with the following parameters.
n                       :  The input integer.
x=0                     :  Used to count the number of matches we've found.
y=0                     :  Incremented on each pass and used to generate the yth Fibonacci number.
x>n?                    :If the count of matches is greater than the input then
f(y-1)                  :    Output the y-1th Fibonacci number.
:                       :Else
g(...)                  :    Call the function again, with the following arguments.
n                       :      The input integer.
x+                      :      The total number of matches so far incremented by the result of...
RegExp(f(n)).test(f(y)) :        A RegEx test checking if the yth Fibonacci number, cast to a string, contains the nth Fibonacci number.
                        :        (returns true or false which are cast to 1 and 0 by the addition operator)
y+1                     :      The loop counter incremented by 1

```

# Answer
> 2 votes
# Charcoal, 65 bytes

```
ＡＩθνＡνφＡ±¹βＡβιＡβξＡ¹αＷ∧›ν²φ«Ａ⁺ι¹ιＡ⁺αβχＡαβＡχαＡ⎇⁼ιναξξＡ⁻φ›№ＩαＩξ⁰φ»Ｉα

```

Try it online! Link to verbose code for explanation.

# Answer
> 1 votes
# Mathematica, 85 bytes

```
(i=ToString;f=Fibonacci;For[n=t=0,t<#,If[i@f@n++~StringContainsQ~i@f@#,t++]];f[n-1])&

```

**input**

> \[10\]

*-4 bytes from @JungHwan Min*

**output**

> 4660046610375530309

# Answer
> 1 votes
# R, ~~77~~ 72 bytes

```
F=gmp::fibnum;i=0;d=n=scan();while(n)if(grepl(F(d),F(i<-i+1)))n=n-1;F(i)

```

This makes use of the `gmp` library for the Fibonacci number. Fairly straight foward implementation of the question.

```
F=gmp::fibnum;          # Alias Fibonacci function to F
i=0;                    # intitalise counter
d=n=scan();             # get n assign to d as well
while(n)               # loop while n
  if(grepl(F(d),F(i<-i+1)))  # use grepl to determine if Fib of input is in Fib# and increment i
     n=n-1;             # decrement n
F(i)                  # output result

```

Some tests

```
> F=gmp::fibnum;i=0;d=n=scan();while(n)if(grepl(F(d),F(i<-i+1)))n=n-1;F(i)
1: 2
2:
Read 1 item
Big Integer ('bigz') :
[1] 1
> F=gmp::fibnum;i=0;d=n=scan();while(n)if(grepl(F(d),F(i<-i+1)))n=n-1;F(i)
1: 3
2:
Read 1 item
Big Integer ('bigz') :
[1] 233
> F=gmp::fibnum;i=0;d=n=scan();while(n)if(grepl(F(d),F(i<-i+1)))n=n-1;F(i)
1: 10
2:
Read 1 item
Big Integer ('bigz') :
[1] 4660046610375530309
> F=gmp::fibnum;i=0;d=n=scan();while(n)if(grepl(F(d),F(i<-i+1)))n=n-1;F(i)
1: 15
2:
Read 1 item
Big Integer ('bigz') :
[1] 1387277127804783827114186103186246392258450358171783690079918032136025225954602593712568353

```

# Answer
> 1 votes
# PHP, 96 bytes

```
for($f=[0,1];$s<$a=$argn;$s+=$f[$a]&&strstr($f[$i],"$f[$a]")?:0)$f[]=$f[$i]+$f[++$i];echo$f[$i];

```

Try it online!

# Answer
> 1 votes
# 05AB1E, ~~11~~ 9 bytes

```
µNÅfDIÅfå

```

-2 bytes thanks to *@ovs*.

Try it online or verify the first 10 test cases.

**Explanation:**

```
µ          # Loop until the counter_variable is equal to the (implicit) input:
           # (the counter_variable is 0 by default)
 N         #  Push the loop index
  Åf       #  Pop and push the index'th Fibonacci number
    D      #  Duplicate it
     IÅf   #  Get the input'th Fibonacci number
        å  #  Check that the index'th Fibonacci nr contains the input'th Fibonacci nr
           #  (if this is truthy, implicitly increase the counter_variable by 1)
           # (after the loop, the top of the stack - the last index'th Fibonacci number
           #  we've duplicated - is output implicitly as result)

```

# Answer
> 1 votes
# Husk, ~~15~~ 13 bytes

```
!fȯ€d!¹İfQdİf

```

Try it online!

```
!⁰fȯ€od!⁰İfQdİf
!⁰                  # get the input-th element of
  f          İf     # fibonacci numbers that satisfy:
   ȯ€      Qd       # one of the subsets of their digits is
     od             # the digits of
       !⁰           # the input-th element of
         İf         # the fibonacci series

```

# Answer
> 1 votes
# Jelly, 11 bytes

```
1,ÆḞw/ɗ#ÆḞṪ

```

Try it online!

Heartbroken. This is a **9** byte version that unfortunately fails for \\$n = 2\\$ which otherwise, I'm really proud of due to the weird chain rules and the byte saves.

## How they work

```
1,ÆḞw/ɗ#ÆḞṪ - Main link. Takes n on the left
      ɗ     - Group the previous three links into a dyad f(k, n):
 ,          -   Pair; [k, n]
  ÆḞ        -   n'th Fib; [fib(k), fib(n)]
     /      -   Run the previous dyad over the list
                with fib(k) on the left and fib(n) on the right:
    w       -     Index of fib(n) in fib(k)'s digits or 0

1      #    - Count up k = 1, 2, 3, ..., until n integers return
              true for f(k, n) and return those k
        ÆḞ  - n'th Fib for each
          Ṫ - Return the last value

```

And the version that fails for \\$n = 2\\$:

```
ÆḞw¥#ÆḞ⁺Ṫ - Main link. Takes n on the left
     ÆḞ   - Yield the n'th Fibonacci number, x
   ¥      - Group the previous 2 links together as a dyad f(k, x):
ÆḞ        -   k'th Fibonacci number
  w       -   Index of x in fib(k)'s digits else 0
    #     - Count up k = n, n+1, n+2, ... until n integers return true
            for f(k, x) and return those k
       ⁺  - Redo the previous link (ÆḞ), yielding the k'th Fibonacci
            number for each k returned by #
        Ṫ - Take the last k

```

# Answer
> 0 votes
## Clojure, 99 bytes

```
(def s(lazy-cat[0 1](map +(rest s)s)))#(nth(filter(fn[i](.contains(str i)(str(nth s %))))s)(dec %))

```

A basic solution, uses an infinite sequence of Fibonacci numbers `s`.

# Answer
> 0 votes
# C#, 35 bytes

```
int u=1,b=1;for(;b<n;){b+=u;u=b-u;}

```

**Try it**

```
int n=int.Parse(t2.Text);int u=1,b=1;for(;b<n;){b+=u;u=b-u;t.Text+=b.ToString()+" ";}if(b==n){t.Text+="true";}

```

# Answer
> 0 votes
# NewStack, 14 bytes

```
N∞ ḟᵢﬁ 'ﬁf Ṗf⁻

```

## The breakdown:

```
N∞              Add all natural numbers to the stack
   ḟᵢ           Define new function will value of input
     ﬁ          Get the n'th Fibonacci number for ever element n
       'ﬁf      Remove all elements that don't contain the (input)'th Fibonacci number
           Ṗf⁻  Print the (input-1)'th element

```

**In English:** *(with example of an input of 3)*

`N∞`: Make a list of the natural numbers `[1,2,3,4,5,6...]`

`ḟᵢ`: Store the input in the variable `f` `[1,2,3,4,5,6...]`

: Convert the list to Fibonacci numbers `[1,1,2,3,5,8...]`

`'ﬁf`: Keep all elements that contain the `f`th Fibonacci number `[2,21,233...]`

`Ṗf⁻`: Print the `f-1`th element (-1 due to 0-based indexing) `233`

# Answer
> 0 votes
# Japt, ~~16~~ ~~15~~ 12 bytes

Would be 11 bytes but for a bug in Japt.

```
@µX¦skN}f!gM

```

Try it

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


title: *Language name* is awesome!

text:
# Question
Title: *Language name* is awesome!
Write a program in any language that reads input from stdin and outputs a slightly modified output to stdout. The program should borrow some characters from the input and output as large of a prefix as possible of `*language-name* is awesome!` followed by a newline and then what's left of the input.

* The input does not contain any uppercase characters.
* If the first character of the language name is not present in the string, only the newline character should be borrowed.
* If there's no newline character in the input, output the input unmodified.
* It does not matter which of the available characters you borrow.

I'm using `\n`as the newline character (`0x0a`) to save space when writing. The real program should only care about the real newline character, not the `\n` string.

Example: python.
input: `abcdefghijklmnopqrstuvwxyz\n0123456789`
output: `python\nabcdefgijklmqrsuvwxz0123456789`
Since the input does not have any spaces, we cannot continue even though we have enough characters for the next word: `is`.

Example: C.
input: `i don't see anything!`
output: `i don't see anything!`
C was not found in the string, so no modification was possible. Also, no newline character is present.

Example: C++.
input: `i don't\nsee anything!`
output: `\ni don'tsee anything!`
C was not found in the string, so no modification was possible.

Example: Obj-C.
input: `objectively, clojure is amazing.\nq.e.d.`
output: `obj\nectively, clojure is amazing.q.e.d.`
The input contains enough characters to write `obj` but the `-` is missing.

Byte count of your source code minus the byte count of your languages' name, utf-8 encoded (if possible), is your score; lowest wins!

# Answer
# Pyth, 37 bytes

```
.-Jjb.zpef!.-TJ+,kb+Rb._"pyth is awesome!

```

The source code is **41 bytes** long. Try it online.

### How it works

```
  Jjb.z                                      Save all user input in J.
                      ._"pyth is awesome!    Compute all prefixes that string:
                                               ["p", "py", ... ]
                   +Rb                       Append a linefeed to each prefix.
               +,kb                          Concatenate ["", "\n"] with the result.
         f                                   Filter the resulting array; for each T:
           .-TJ                                Perform bagwise difference between T
                                               and J (respects multiplicities).
         !                                     Take the logical NOT.
                                             Keep T if ! returned True, i.e., if J
                                             contains all of T's characters.
        e                                    Retrieve the last, longest match.
       p                                     Print it.
.-J                                          Remove its characters from J.
                                             (implicit) Print the result.

```
> 4 votes

# Answer
## Python, 186 - 6 = 180

```
import sys
a=sys.stdin.read()
s="python is awesome!"
r=''
if'\n'not in a:print a;exit()
a=a.replace('\n','',1)
for c in s:
 if c in a:a,r=a.replace(c,'',1),r+c
 else:break
print r+'\n'+a

```

Try it online
> 2 votes

# Answer
## Python, 146 bytes

```
import sys
r=sys.stdin.read();y='\npython is awesome!';a=''
for i in y:
    if i in r:a+=i
    else:break
print a[1:]+'\n'+''.join(b for b in r if not b in a)

```
> 1 votes

# Answer
# Ceylon, 235 - 6 = 229

`void a(){variable value i="";variable value r="\nceylon is awesome!";while(exists l=process.readLine()){i=i+"\n"+l;}i=i.rest;for(j->c in r.indexed){if(c in i){i=i.replaceLast(c.string,"");}else{r=r[0:j];break;}}print(r.rest+r[0:1]+i);}`

Here is a formatted and commented version:

```
void a() {
    // our target string, with the \n shuffled to the start.
    variable value r = "\nceylon is awesome!";

    // read the whole input line by line
    // (there doesn't seem a way to do this shorter :-/)
    variable value i = "";
    while (exists l = process.readLine()) {
        i = i + "\n" + l;
    }
    // remove first \n:
    i = i.rest;
    for (j->c in r.indexed) {
        if (c in i) {
            // remove some occurence of c
            i = i.replaceLast(c.string, "");
        } else {
            // stop the loop, and take the part of `r` processed so far.
            r = r[0:j];
            break;
        }
    }
    // reshuffle first \n in r to its end.
    // This will result in the empty string if r is empty, i.e. no \n was found.
    print(r.rest + r[0:1] + i);
}

```

It uses `replaceLast` instead of `replaceFirst` because it is shorter.

Some example inputs and outputs in the same format as in the question:

* `abcdefghijklmnopqrstuvwxyz\n0123456789``ceylon\nabdfghijkmpqrstuvwxz0123456789`
* `i don't see anything!``i don't see anything!`
* `i don't\nsee anything!``\ni don't see anything!`
* `objectively, closure is amazing.\nq.e.d.``ceylon is a\nobjectivel, sureiamzng.\q..d.`
> 1 votes

# Answer
# Jelly, 23 - 5 = 18 bytes

```
“£İþ¬Ɠ¥ỊḊ»
¢œ-ƤṆ€×¢Ṅœ-@

```

Try it online!

This uses the Jelly encoding. Insisting on UTf-8 encoding has the same byte count, it just means I need to make a hexdump of the bytes.

## How it works

```
“£İþ¬Ɠ¥ỊḊ» - Helper link. Compressed string "jelly is awesome"

¢œ-ƤṆ€×¢Ṅœ-@ - Main link. Takes S on the left
¢            - Yield "jelly is awesome"
   Ƥ         - Over each prefix of "jelly is awesome":
 œ-          -   For each character in the prefix, remove it exactly once
                  if it is in the input
                  This results in an empty list if the entire prefix is in
                  the input else a non-empty list
     €       - Over each:
    Ṇ        -   Logical NOT. This yields 1 for an empty list, else 0
       ¢     - Yield "jelly is awesome"
      ×      - For each character, keep it if the left argument is 1
        Ṅ    - Print the kept characters with a trailing newline
         œ-@ - Remove exactly one occurrence of each of the kept characters
               from the input and output that

```
> 1 votes

# Answer
# JavaScript (ES6) 90 (100-10)

As a function returning the requested ouput. It's difficult to implement with I/O, as the usual substitute for STDIN is `prompt()`, that does not accept a newline inside the input string.

As a function with real output (using `alert`) the byte count is 107

```
f=s=>alert(([...`
javascript is awesome`].every(c=>(z=s.replace(c,''))!=s&&(s=z,q?o+=c:q=c),q=o=''),o+q+z))

```

Test running the snippet below in an EcmaScript 6 compliant browser (implementing spread operator and arrow function - I use FireFox)

```
f=s=>([...`
javascript is awesome`].every(c=>(z=s.replace(c,''))!=s&&(s=z,q?o+=c:q=c),q=o=''),o+q+z)

function test()
{
  O.innerHTML=f(I.value)
}

test()
```

```
#I {width: 80%}
```

```
<textarea id=I>
objectively, clojure is amazing.
q.e.d.</textarea><button onclick="test()">-></button>
<pre id=O></pre>
```
> 0 votes

# Answer
# JavaScript (ES7), ~~101~~ 107 - 10 = 97

It was shorter before, and even worked on all four test cases, but apparently I missed a rule, so....

```
x=>(i=r=q='',[for(c of`
javascript is awesome`)(y=x.replace(c,''),i||y==x?i=1:(c<' '?q=c:r+=c,x=y))],r+q+x)

```

Works properly in Firefox 42. This originally started out at 119 bytes, but a trick from @edc65's answer helped to shorten it a great deal. I think there's still some room for improvement. As always, suggestions welcome!
> 0 votes

# Answer
# Perl, 72 - 4 = 68 bytes

Includes 2 switches.

```
perl -0pe 'for$c("\nperl is awesome!"=~/./gs){s/$c//?$p.=$c:last}s/^/$p\n/;s/\n//'

```

*Explanation*: For every character in the string `"\nperl is awesome"`, remove the corresponding character from the input string (`$_`) till we find a character not present in `$_`. The matching characters are stored in `$p` which is prefixed to `$_` which is then printed.

The `-0` switch reads in the complete input rather than line-by-line and the `-p` switch makes reading input and print the output implicit.
> 0 votes

---
Tags: code-golf
---


# Question
Title: Calculate the bounded cumulative sum of a vector
The cumulative sum of a vector is calculated by simply taking the sum of all previous elements. For instance:

```
vec =     [1  1  1 -1 -1 -1 -1 -1  1  1  1  1 -1]
cum_vec = [1  2  3  2  1  0 -1 -2 -1  0  1  2  1]

```

Now, impose an upper and a lower limit, meaning that you stop increasing the cumulative sum if it's at the upper limit, and stop decreasing the cumulative sum if it's at the lower limit. A simple example:

```
upper_lim = 2
lower_lim = -1
vec =     [1  1  1 -1 -1 -1 -1 -1  1  1  1  1 -1]
cum_vec = [1  2  2  1  0 -1 -1 -1  0  1  2  2  1]

```

The input vector consists of integers, not necessarily only `1` and `-1`, both positive and negative. Assume that `upper_lim >= lower_lim`. If the first element of the vector is outside the boundary, jump directly to the boundary (see last example).

Write a function that takes a vector of integers as input, and two integers that represent the upper and lower limits. Output the bounded cumulative vector, as defined above. The input can be as either function arguments or from STDIN.

Standard code golf rules apply.

Examples:

```
upper_lim = 6
lower_lim = -2
vec =     [1  4  3 -10  3  2  2  5 -4]
cum_vec = [1  5  6  -2  1  3  5  6  2]

upper_lim = 100
lower_lim = -100
vec =     [1  1  1  1  1  1]
cum_vec = [1  2  3  4  5  6]

upper_lim = 5
lower_lim = 0
vec =     [10 -4 -3  2]
cum_vec = [5   1  0  2]

upper_lim = 0
lower_lim = 0
vec =     [3  5 -2  1]
cum_vec = [0  0  0  0]

upper_lim = 10
lower_lim = 5
vec =     [1  4  6]
cum_vec = [5  9 10]
           |
           Note, jumped to 5, because 5 is the lower bound.

```

# Answer
# Pyth, 14 bytes

```
t.u@S+Q+NY1vwZ

```

Try it online: Demonstration or Test Suite

### Explanation

```
t.u@S+Q+NY1vwZ  implicit: Q = first input list [upper_lim, lower_lim]
 .u        vwZ  for each number Y in the next input list, update N = 0 with:
       +NY         N + Y
     +Q            append this to Q
    S              sort this list
   @      1        take the middle element
                .u returns a list with all intermediate values of N
t                  remove the first value, print the rest

```
> 5 votes

# Answer
# CJam, ~~16~~ 15 bytes

```
l~f{\T++$1=:T}`

```

Try it online

This takes the list as first argument, and the pair of upper/lower limit as a second 2-element list. Example input:

```
[1 4 3 -10 3 2 2 5 -4] [6 -2]

```

The latest version saves 1 byte by sorting the 3 values, and taking the middle value, instead of using a max and min operation. This was also used in Jakube's solution, as well as suggested by Martin.

Explanation:

```
l~    Get and parse input. This leaves the value and bounds lists on the stack.
f{    Apply block with value (the bounds list).
  \     Swap new value to top.
  T     Get previous value from variable T (which is default initialized to 0).
  +     Add new value and previous value.
  +     Append new value to bounds list, producing a 3 value list.
  $     Sort it...
  1=    And take the middle value.
  :T    Store in variable T for next iteration.
}     End of apply loop.
`     Convert list to string.

```
> 5 votes

# Answer
# JavaScript (ES6), 43 bytes

```
(l,u,v,p=0)=>v.map(c=>p=(p+=c)<l?l:p>u?u:p)

```

Defines an anonymous function that takes input in the format `lower bound, upper bound, vector (as JS Array)`. I don't know if it could be any shorter, but I'll try. Suggestions welcome!
> 4 votes

# Answer
# Haskell, 37 bytes

```
u#l=tail.scanl(((min u.max l).).(+))0

```

Usage example: `6 # (-2) $ [1,4,3,-10,3,2,2,5,-4]` -\> `[1,5,6,-2,1,3,5,6,2]`.

Start the sum with `0` to fix initial values out of bounds. Take the `tail` to remove it from the final result.
> 4 votes

# Answer
## R, 61 bytes

```
function(x,l,u,s=0)sapply(x,function(i)s<<-min(u,max(l,s+i)))

```

`sapply` is the function to apply a function to every element of a vector (here `x`) but it is usually done in a context where all the evaluations are independent and without side-effect. Here, however, I use the `<<-` operator to make an assignment in the parent/calling environment of `sapply` so that the cumulative sum `s` can be stored outside the iterative evaluations. This is very bad practice...
> 4 votes

# Answer
# Julia, ~~44~~ ~~42~~ 38 bytes

```
f(x,l,u,s=0)=[s=clamp(s+i,l,u)for i=x]

```

This creates a function `f` that accepts an array and two integers and returns an array.

Ungolfed:

```
function f(v::Array, u::Int, l::Int, s::Int = 0)
    # The parameter s is the cumulative sum, which begins
    # at 0

    # For each element i of v, define s to be s+i if
    # l ≤ s+i ≤ u, l if s+i < l, or u if s+i > u
    x = [s = clamp(s + i, l, u) for i = v]

    return x
end

```

Saved 2 bytes by using ETHproductions' idea of including the cumulative sum as a function parameter and 1 bytes thanks to Glen O.
> 3 votes

# Answer
# Mathematica, 46 bytes

```
Rest@FoldList[{a,b}Min[a+b,#2]~Max~#3,0,#]&

```

The funny character is U+F4A1 for `\[Function]`. If the first element can be assumed to be in the range, I could save 7 bytes.
> 3 votes

# Answer
# Python 2, 67 Bytes

```
lambda u,l,v:reduce(lambda x,y:x+[max(min(x[-1]+y,u),l)],v,[0])[1:]

```
> 3 votes

# Answer
## Minkolang 0.9, 30 bytes

```
0I3-[2g+d0c`,3&x0cd1c`3&x1cdN]

```

This, as a function, assumes the stack has been pre-initialized to `high, low, vector`. The full program is below (**37 bytes**) and takes input as `high, low, vector`.

```
(n$I$)0I4-[2g+d0c`,3&x0cd1c`3&x1cdN].

```

Try it here.

### Explanation

```
(n$I$)                                   Read in integers from input until empty
      0                                  Initialize cumulative sum
       I4-[                        ]     Loop over vector
           2g+                           Get the next partial sum
              d0c`,3&x0c                 If too high, replace with high
                        d1c`3&x1cd       If too low, replace with low
                                  N      Output as integer
                                    .    Stop

```
> 2 votes

# Answer
# APL, ~~29~~ ~~27~~ 18 bytes

As Dennis pointed out in chat, `\` (expand) works from left to right, but applies the function being expanded with from right to left. So we can't just do `1↓(⎕⌈⎕⌊+)\0,⎕`. We work around this by taking the `,\` of the array, and then processing each subarray separately using `/` (fold).

```
1↓(⎕⌈⎕⌊+)/¨⌽¨,\0,⎕

```

Input in the order `array, upper bound, lower bound`.
> 1 votes

# Answer
### C 98 bytes

It's long, but it works

```
#define P printf(
void c(*v,n,u,l,s,c){P"[");while(c++<n)s+=*v++,s=s<u?s>l?s:l:u,P"%d ",s);P"]");}

```

### Usage example

```
#define P printf(
void c(*v,n,u,l,s,c) {
    P"[");
    while(c++<n)
        s+=*v++,s=s<u?s>l?s:l:u,P"%d ",s);
    P"]");
}

int main() {
    int vec[9] = {1, 4, 3, -10, 3, 2, 2, 5, -4};
    int upper = 6, lower = -2, count = 9;
    c(vec, count, upper, lower, 0, 0);
}

```

The output would be

```
[1 5 6 -2 1 3 5 6 2 ]

```
> 1 votes

# Answer
# K (oK), 12 bytes

```
{0(x&y|+)\z}

```

Try it online!

Similar to lirtosiast's APL answer, but with some simplifications. Uses `0` as the seed for a scan over `z`.
> 1 votes

# Answer
# Jelly, 9 bytes

```
Ż+«⁴»⁵ʋ\Ḋ

```

Try it online!

We can remove the first and last bytes if not for the `[1, 4, 6]` test case. This is a full program which takes the arguments on the command line in the order `vec upper_limit lower_limit`

## How it works

```
Ż+«⁴»⁵ʋ\Ḋ - Main link. Takes a list V on the left
            And integers U and L on the command line
Ż         - Prepend a 0 to V
      ʋ   - Group the previous 4 links together into a dyad f(x, y):
 +        -   x + y
   ⁴      -   U
  «       -   min(x+y, U)
     ⁵    -   V
    »     -   max(min(x+y, U), L)
       \  - Cumulative reduce V by f(x, y)
        Ḋ - Remove the leading 0

```
> 0 votes

# Answer
# Japt, 11 bytes

```
å@VwWmX+Y}T

```

Try it
> 0 votes

---
Tags: code-golf, arithmetic, array
---