title: Two-way Palindromic Closure Generator

text:
# Question
Title: Two-way Palindromic Closure Generator
# Introduction

A palindromic closure of an input string is the shortest palindrome that can be constructed out of the input string where the final palindrome starts with the input string.

For this challenge, we will consider a two-way palindromic closure such that

* **Left Palindromic Closure** of an input string is the shortest palindrome possible that starts with the input string.
* **Right Palindromic Closure** of an input string is the shortest palindrome possible that ends with the input string.
* **Two-way Palindromic Closure** of an input string is the shorter of either of Left or Right Palindromic Closure of the input string.

# Task

Your task is simple. Given a string (consisting only of printable ASCII, new lines and white spaces), output the two-way palindromic closure of that string. In case of tie, either of the left or right palindromic closures are valid output.

You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument, and either printing the result to STDOUT (or closest alternative) or returning it as a string.

You can assume that the input will never be an empty string.

Few examples:

```
<Input>   -> <Output>
"abcdef"  -> "abcdefedcba"  (or "fedcbabcdef")
"abcba"   -> "abcba"
"abcb"    -> "abcba"
"cbca"    -> "acbca"

```

---

*Initial Idea credit goes to VisualMelon, final idea with help from Martin and Zgarb*

*The terms palindromic closure, left-pallindromic closure and right-palindromic closure were first used and defined by this paper.*

# Answer
> 11 votes
# Pyth, ~~22~~ 19

```
hfq_TTsm,+z_d+_dzyz

```

Try it online.

## Explanation

The two-way palindromic closure is either of the form `AX` or `XA`, where `X` is the input string and `A` is a substring of `X`. I actually has to be a contiguous substring of `X`, a prefix for the one form, a suffix for the other form. But I don't care about these defails. A substring (contiguous or not) is all I need in Pyth.

```
                        Implicit: z = raw_input() // Read a string
                 yz     A list with all substrings (contiguous or not) of z
       m                For each of these substrings d, build
        ,                  a pair of two strings:
         +z_d              ( z + inveres(d) ,
             +_dz            inverse(d) + z )
      s                 Sum (put all created pairs into a list)
 fq_TT                  filter elements T, where inverse(T) == T (Palindrom)
h                          Take the first element

```

## Edit

The old version ordered the the strings after filtering by length `.olN...`. Just realized, that `y` returns the substrings ordered by length. So these palindromes are already sorted.

# Answer
> 6 votes
# Clip, 40

```
(sl`f[a=ava}+m[i+v+ixx}Rlxm[i+xvu0ix}Rlx

```

## Example

```
Documents>java -jar Clip4.jar palindrome.clip
abcb
abcba

```

## Explanation

```
(sl`                                        .- The shortest                     -.
    f[a=ava}                                .- palindrome                       -.
            +                               .- among the following two sets:    -.
             m[i      }Rlx                  .- For each number up to length(x)  -.
                +                           .- combine                          -.
                 v+ix                       .- the last i chars of x, reversed  -.
                     x                      .- and x.                           -.
                          m[i       }Rlx    .- For each number up to length(x)  -.
                             +              .- combine                          -.
                              x             .- x and                            -.
                               vu0ix        .- the first i chars of x, reversed.-.

```

# Answer
> 6 votes
# CJam, 30 bytes

Was really hoping to see a CJam answer by now.. So here it goes :P

```
q:Q,{)QW%/(Q+Q@+s}%{,}${_W%=}=

```

I really hate that `{,}$` block in there, but I get an unordered list of possible palindromes due to the generation algorithm I am using.

**Code explanation**

```
q:Q,{            }%             "Read the input string, store in Q, take length and";
                                "run the code block that many times";
     )QW%                       "Increment the iteration index and Put reversed Q on stack";
         /                      "Split reversed Q into parts of incremented iteration index";
          (Q+                   "Take out the first part and prepend it to Q";
             Q@+s               "Take the rest of the parts and append them to Q";
                   {,}$         "At this point, we have all possible prepended and appended";
                                "sequences of the input string. Sort them by length";
                       {_W%=}=  "Take the first sequence which is a palindrome";

```

Try it online here

# Answer
> 4 votes
## Python 2, ~~115~~ ~~113~~ ~~109~~ ~~105~~ 96 bytes

```
f=lambda x:[x for x in sum([[x[:~i:-1]+x,x+x[i::-1]]for i in range(len(x))],[])if x==x[::-1]][0]

```

Can hopefully golf down further. Bits possibly worthy of note:

* using sum for two list comprehensions in one
* constructing terms in sorted order to avoid the need for min (suggested by @Jakube)

# Answer
> 4 votes
# Mathematica, 96 bytes

There must be a more elegant way than this...

```
""<>#&@@SortBy[r=Reverse;#/.{b___,a__/;r@{a}=={a}}:>{b,r@{b,a}}&/@{r@#,#}&@Characters@#,Length]&

```

This defines an unnamed function which takes a string and returns the result.

The basic idea is to

* Split the string into `Characters`.
* Form an array with this list and its reverse.
* Use pattern matching to find the right palindromic of each of them:

```
{b___,a__/;r@{a}=={a}}:>{b,r@{b,a}}

```

Note that this doesn't actually return a flat list. E.g. for `{a,b,c}` you'd get

```
{a,b,{c,b,a}}

```
* Sort the two results by length.
* Pick the shorter and join it back into a string with `""<>#&@@`.

# Answer
> 2 votes
# Brachylog (2), 6 bytes, language postdates challenge

```
~{↔?a}

```

Try it online!

As usual for Brachylog, this is a function, not a full program.

## Explanation

```
~{↔?a}
~{   }   Find a value that produces {the input} upon doing the following:
  ↔        reversing it;
   ?       asserting that we still have the same value;
    a      and taking either a prefix, or a suffix.

```

As far as I know (it's not my language, but it seems unlikely), `a` wasn't added to Brachylog for this challenge, but it comes in really handy here. We use the "reverse, and assert it hasn't changed" method to assert that the value we find is a palindrome.

As for why this produces the *shortest* palindrome, Prolog's (and hence Brachylog's) evaluation order is heavily influenced by the first thing it evaluates. In this case, that's a "reverse" command, and (like most list operations) it sets an evaluation order that aims to minimize the size of the resulting list. As that's the same as the size of the output, the program happily ends up minimizing exactly the right thing by chance, meaning that I didn't need to add any explicit hints.

# Answer
> 1 votes
# Ruby, 76 + 2 = 78

With command-line flags `-pl` (the `l` may not be needed depending on how you're doing input), run

```
$_=[[$_,r=$_.reverse]*"\0",r+"\0#$_"].min_by{|s|s.sub!(/(.*)\0\1/){$1}.size}

```

Given a string 'abaa', generates the strings 'cbca**0**acbc' and 'acbc**0**cbca', where **0** is the unprintable character with ascii code 0. It then deletes one copy of the longest repeated string framing **0** it finds in each, 'a' in the first and 'cbc' in the second, to get the two closures. It then outputs the shortest result.

The only really weird thing about the golfed code is that it shortens the strings in place while sorting them, which we can get away with because `min_by` only executes the block once per element being compared (both because it's a Schwartzian transform and because there are only two elements to compare).

# Answer
> 1 votes
# Python 3, 107 bytes

---

```
f=lambda a:[i for i in[a[:i:-1]*j+a+a[-1-i::-1]*(1-j)for i in range(len(a))for j in(0,1)]if i==i[::-1]][-1]

```

To test:

```
>>> print("\n".join(map(f, ["abcdef", "abcba", "abcb", "cbca"])))
abcdefedcba
abcba
abcba
acbca

```

# Answer
> 1 votes
# Haskell, 107 bytes

```
import Data.List
r=reverse
f s=snd$minimum[(length x,x)|x<-map(s++)(tails$r s)++map(++s)(inits$r s),x==r x]

```

Test:

```
*Main> mapM_ (putStrLn.f) ["abcdef", "abcba", "abcb", "cbca"]
abcdefedcba
abcba
abcba
acbca

```

# Answer
> 1 votes
# J, ~~66~~ 62 bytes

```
3 :'>({~[:(i.>./)(#%~[-:|.)@>),(<@([,|.@{.~)"#:i.@#"1)y,:|.y'

```

Quite straightforward. The two tricks I use:

The right palindromic closure is the left palindromic closure of the reversed string.

Finding the length of the string with minimum length and palindromity with the expression min(is\_palindrome / length).

```
   f=.3 :'>({~[:(i.>./)(#%~[-:|.)@>),(<@([,|.@{.~)"#:i.@#"1)y,:|.y'

   f 'lama'
lamal

```

Try it online here.

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


title: Rafting Problem (Knapsack variant)

text:
# Question
Title: Rafting Problem (Knapsack variant)
First puzzle from me, suggestions for improvement gladly received!

The scenario is; You work as a manager for a whitewater rafting company. Every morning, you are given a list of bookings, and you have to sort them into raft loads. Write a program or function in your chosen language that does this for you.

Each raft holds a maximum of `n` clients, and each booking is for a group of between 1 and `n` people (inclusive). The following rules must be observed;

* No groups may be split up. If they booked together, they must all be in the same raft.
* The number of rafts must be minimised.
* Subject to the two preceeding rules, the groups must be spread as equally as possible between the rafts.

**Inputs.** The number `n` (you may assume that this is a positive integer), and the size of all the bookings. This may be an array, list or similar data structure if your language supports such things. All of these will be positive integers between 1 and `n`. The order of the bookings is not defined, nor is it important.

**Output.** A list of the booking numbers, grouped into raft loads. The grouping must be indicated unambiguously, such as;

* a list, or array of arrays.
* a comma separated list for each raft. Newline between each raft.

How you implement the third rule is up to you, but this could involve finding the average raft occupancy, and minimising deviations from it as much as possible. Here are some test cases.

```
n  Bookings       Output
6  [2,5]          [5],[2]
4  [1,1,1,1,1]    [1,1,1],[1,1]
6  [2,3,2]        [2,2],[3]
6  [2,3,2,3]      [2,3],[2,3]
6  [2,3,2,3,2]    [2,2,2],[3,3]
12 [10,8,6,4,2]   [10],[8,2],[6,4]
6  [4,4,4]        [4],[4],[4]
12 [12,7,6,6]     [12],[7],[6,6]

```

Standard rules apply, shortest code wins. Have fun!

Edited; A suggested way to define *as equally as possible* for the third rule.

Once the number of rafts `r` has been determined (subject to the second rule), the average occupancy `a` can be calculated by summing over the bookings, and dividing by `r`. For each raft, the deviation from the average occupancy can be found using `d(x) = abs(n(x)-a)`, where `n(x)` is the number of people in each raft and `1 <= x <= r`. For some continuous, single-valued function `f(y)`, which is strictly positive and has a strictly positive first and non-negative second derivatives for all positive `y`, we define a non-negative quantity `F`, as the sum of all the `f(d(x)), 1 <= x <= r`. Any choice of raft allocation that satisfies the first two rules, and where `F` is equal to the global minimum will satisfy the third rule also.

# Answer
# Perl 6, ~~163~~ 158 bytes

```
{[grep $^n>=*.all.sum,map ->\p{|map {p[0,|$_ Z..^|$_,p]},(1..^p).combinations},$^s.permutations].&{.grep: .map(+*).min}.min({.map((*.sum-$s.sum/$_)**2).sum})}

```

Try it online!

### How it works

* ```
map ->\p{|map {p[0,|$_ Z..^|$_,p]},(1..^p).combinations},$^s.permutations
```

Generates all possible partitions of all permutations of the input array.
* ```
grep $^n>=*.all.sum,
```

Filters the ones where no raft is overbooked.
* ```
.&{.grep: .map(+*).min}
```

Filters the ones where the number of rafts is minimal.
* ```
.min({.map((*.sum-$s.sum/$_)**2).sum})}
```

Gets the first one with minimal *∑(nx-a)2*.

*-4 bytes thanks to @Pietu1998*
> 2 votes

# Answer
# Haskell 226 ~~228~~ ~~234~~ ~~268~~ bytes

Naive answer in Haskell

```
import Data.List
o=map
u=sum
p=foldr(\x t->o([x]:)t++[(x:y):r|(y:r)<-t>>=permutations])[[]]
m x=foldl(\[m,n]x->[m+(x-m)/(n+1),n+1])[0,0]x!!0
a!z=abs$u z-a
s t=(length t,u$o((m$o u t)!)t)
a n=head.sortOn s.filter(all$(<=n).u).p

```

Or ungolfed

```
partition' :: [a] -> [[[a]]]
partition' [] = [[]]
partition' (x:xs) = [[x]:ps     | ps <- partition' xs]
                 ++ [(x:p):rest | ps <- partition' xs, (p:rest) <- permutations ps]

-- from Data.Statistics
mean :: [Double] -> Double
mean xs = fst $ foldl (\(m, n) x -> (m+(x-m)/n+1, n+1)) (0, 0) xs

diff :: Double -> [Double] -> Double
diff avg xs = abs $ sum xs - avg

rawScore :: [[Double]] -> Double
rawScore xs = sum . map (diff avg) $ xs where avg = mean . map sum $ xs

score :: [[Double]] -> (Int, Double)
score xs = (length xs, rawScore xs)

-- from Data.Ord
comparing :: (Ord b) => (a -> b) -> a -> a -> Ordering
comparing p x y = compare (p x) (p y)

candidates :: Double -> [Double] -> [[[Double]]]
candidates n xs = filter (all (\ ys -> sum ys <= n)) . partition' $ xs

answer :: Double -> [Double] -> [[Double]]
answer n xs = minimumBy (comparing score) $ candidates n xs

```

With some test cases

```
import Text.PrettyPrint.Boxes

testCases :: [(Double, [Double])]
testCases = [(6 , [2,5])
            ,(4 , [1,1,1,1,1])
            ,(6 , [2,3,2])
            ,(6 , [2,3,2,3])
            ,(6 , [2,3,2,3,2])
            ,(12, [10,8,6,4,2])
            ,(6 , [4,4,4])
            ,(12, [12,7,6,6])]

runTests tests = transpose
                 $ ["n", "Bookings", "Output"]
                 : map (\(n, t) -> [ show . floor $ n
                                   , show . map floor $ t
                                   , show . map (map floor) $ a n t]) tests

test = printBox
     . hsep 3 left . map (vcat top) . map (map text) . runTests $ testCases

```

Where `test` yields

```
n    Bookings       Output
6    [2,5]          [[2],[5]]
4    [1,1,1,1]      [[1,1],[1,1,1]]
6    [2,3,2]        [[2,2],[3]]
6    [2,3,2,3]      [[2,3],[2,3]]
6    [2,3,2,3,2]    [[2,2,2],[3,3]]
12   [10,8,6,4,2]   [[10],[8,2],[6,4]]
6    [4,4,4]        [[4],[4],[4]]
12   [12,7,6,6]     [[12],[7],[6,6]]

```

## Edit

Thanks to @flawr and @nimi for advice.

Squashed `p` a bit.

Shaved off a couple bytes.
> 3 votes

# Answer
# Python3, 224 bytes

```
def p(c):
 if len(c)==1:yield[c];return
 for s in p(c[1:]):
  for n,u in enumerate(s):yield s[:n]+[[c[0]]+u]+s[n+1:]
  yield[[c[0]]]+s
s=sum
r=lambda n,b:min(p(b),key=lambda c:s(abs(s(x)-s(b)/(s(b)//n+1))for x in c))

```

With testcases:

```
tc = [[6,[2,5]],[4,[1,1,1,1,1]],[6,[2,3,2]],[6,[2,3,2,3]],[6,[2,3,2,3,2]],[12,[10,8,6,4,2]],[6,[4,4,4]],[12,[12,7,6,6]]]
for case in tc:
    print(str(case[0]).ljust(3),str(case[1]).ljust(16),"|",r(*case))

```

## How does it work?

The `p` function simply generates all partitions of a given list (all possible ways to divide it up into sublists). `s=sum` simply renames the sum function, so the last line does all the work.

```
r=lambda n,b:min(p(b),key=lambda c:s(abs(s(x)-s(b)/(s(b)//n+1))for x in c))
r=lambda n,b:                                                               Initialize the lambda
                 p(b)                                                       Calculate all possible raft arrangements
                     ,key=lambda c:                                         Map the following lambda onto the list:
                                              s(b)/(s(b)//n+1)              Calculate the ideal average amount of people per raft
                                     abs(s(x)-                )             Calculate how close is the current raft
                                                               for x in c   For each raft in the partition
                                   s(                                    )  Sum it (the sum is a score of how close to ideal the function is),
             min(                                                         ) And find the lowest valued partition.

```

I'm certain that this can be golfed further, especially the `p` function, but I worked on this for hours already, so here you go.
> 0 votes

---
Tags: code-golf, combinatorics
---


title: Calculate Knuth's up arrow notation

text:
# Question
Title: Calculate Knuth's up arrow notation
Inspired by Expand exponentation.

Knuth's up arrow notation is used for big numbers such as Graham's number.

If we look deeper, we can see how it makes big numbers.

One arrow means exponentiation. e.g. 2↑3 equals 2^3 = 8.

Two or more arrows means repeating the instructions of n-1 arrows. e.g. 2↑↑3 equals 2↑2↑2 equals 2^(2^2)=16.

You will be given three integers, n, a, and m. n is the first number, a is the amount of arrows, and m is the second number.

Your code should output the final answer, which is the calculation of `n ↑a m`(↑x means there are x up-arrows, where x is an integer)

# Examples

```
2 1 2 -> 4
2 1 3 -> 8
2 2 3 -> 16
2 3 3 -> 65536

```

# Answer
# APL, 22 bytes

```
{×⍺⍺:(⍺⍺-1)∇∇/⍵/⍺⋄⍺×⍵}

```

This is an operator that takes `a` as its operand (`⍺⍺`), and `n` and `m` as its left and right arguments ( and ).

Explanation:

* `×⍺⍺`: if `⍺⍺` is positive:
    + `⍵/⍺`: replicate   times
    + `(⍺⍺-1)∇∇/`: fold the `⍺⍺-1`-arrow function over the list.
* : otherwise (i.e. if `⍺⍺` is zero):
    + `⍺×⍵`: multiply the arguments
> 2 votes

# Answer
# Java 7, 121 bytes

```
int c(int n,int a,int m){return(int)(a<2?Math.pow(n,m):d(n,a));}double d(int n,int a){return Math.pow(n,a<2?n:d(n,a-1));}

```

**Explanation:**

```
int c(int n, int a, int m){         // Main method with the three integer-parameters as specified by OP's challenge
  return (int)                      // Math.pow returns a double, so we cast it to an integer
          (a < 2 ?                  // if (a == 1):
                   Math.pow(n, m)   //  Use n^m
                 :                  // else (a > 1):
                   d(n, a));        //  Use method d(n, a)
}

double d(int n, int a){             // Method d with two integer-parameters
  return Math.pow(n, a < 2          // n ^ X where
                      ? n           //  X = n    if (a == 1)
                      : d(n, a-1)); //  X = recursive call d(n, a-1)    if (a > 1)
}

// In pseudo-code:
c(n, a, m){
  if a == 1: return n^m
  if a > 1:  return d(n, a);
}
d(n, a){
  if a == 1: return n^n
  if a > 1:  return d(n, a-1);
}

```

**Test code:**

Try it here.

```
class M{
  static int c(int n,int a,int m){return(int)(a<2?Math.pow(n,m):d(n,a));}
  static double d(int n,int a){return Math.pow(n,a<2?n:d(n,a-1));}

  public static void main(String[] a){
    System.out.println(c(2, 1, 2));
    System.out.println(c(2, 1, 3));
    System.out.println(c(2, 2, 3));
    System.out.println(c(2, 3, 3));
  }
}

```

**Output:**

```
4
8
16
65536

```
> 3 votes

# Answer
# JavaScript ES7, 53 44 bytes

```
f=(a,b,c)=>b<2||c<1?a**c:f(a,b-1,f(a,b,c-1))

```

```
f=(a,b,c)=>b<2||c<1?a**c:f(a,b-1,f(a,b,c-1))

console.log(f(2,1,2));
console.log(f(2,1,3));
console.log(f(2,2,3));
console.log(f(2,3,3));
```
> 2 votes

# Answer
## Mathematica, ~~48~~ 40 bytes

```
If[#3>1<#,#0[#0[#-1,##2],#2,#3-1],#2^#]&

```

Order of arguments is `m, n, a` (using the notation from the challenge).
> 2 votes

# Answer
# julia, ~~41~~ 38 bytes

```
f(a,n,b)=b>1< n?f(a,n-1,f(a,n,b-1)):a^b

```

Thanks to @Martin 3 bytes saved.

Try it online!

**a,b** : operands
**n**: number of arrows

Previous answer:

```
f(a,n,b)=n<2||b<1?a^b:f(a,n-1,f(a,n,b-1))

```

Modified formula from Wikipedia

Try it online!
> 0 votes

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


title: Output Keystrokes

text:
# Question
Title: Output Keystrokes
In any programming language, create a program that takes input and animates the text being typed on a keyboard.

The delay between each character should be varying to simulate true typing on a keyboard. The delay shall be `0.1, 0.1, 0.5, 0.1, 0.1, 0.5 ...` seconds, until the last character is printed. The final output shall be left on the screen.

You must overwrite the current line of text you can't have the text be printed on new rows.

Example, the input "Hello, PPCG! Goodbye Earth!" should result in the following animation (note that the sampling rate of the gif-maker was low, so the true result is slightly different):

Since this is code golf, the smallest amount of bytes win.

# Answer
> 8 votes
## C ~~108~~ ~~93~~ ~~89~~ ~~78~~ ~~73~~ 80 bytes

```
f(char *s){for(int i=0;s[i];fflush(0),usleep(100000*(i++%3?1:5)))putchar(s[i]);}

```

Ungolfed version:

```
 void f(char *s)
 {
  for( int i=0;s[i];)
  {
    putchar(s[i]);
    fflush(0);
    usleep(100000*(i++%3?1:5));
 }
}

```

@Kritixi Lithos @Metoniem Thanks for your input! saved some bytes.

Somehow, just `int i` gave me a segmentation error on running, so I initialized it with 0.

# Answer
> 6 votes
# Jelly, 13 bytes

```
115D÷⁵ṁȮœS¥@"

```

This is a monadic link/function. Due to implicit output, it doesn't work as a full program.

### Verification

### How it works

```
115D÷⁵ṁȮœS¥@"  Monadic link. Argument: s (string)

115            Set the return value to 115.
   D           Decimal; yield [1, 1, 5].
    ÷⁵         Divide all three integers by 10.
      ṁ        Mold; repeat the items of [0.1, 0.1, 0.5] as many times as
               necessary to match the length of s.
          ¥@"  Combine the two links to the left into a dyadic chain and apply it
               to each element in s and the corr. element of the last return value.
       Ȯ         Print the left argument of the chain (a character of s) and sleep
                 as many seconds as the right argument indicates (0.1 or 0.5).

```

# Answer
> 6 votes
# MATLAB, 74 bytes

```
c=input('');p=[1,1,5]/10;for i=c;fprintf('%s',i);p=p([2,3,1]);pause(p);end

```

### Explanation:

I used quite a while to make the `fprintf` version shorter than `disp()` with `clc`. The breakthrough was when I found out / remembered that `pause` can take a vector as argument, in which case it will just pick the first value. This makes it possible to leave out a counter.

```
c=input('');    % Take input as 'Hello'
p=[.1,.1,.5];   % The various pause times

for i=c;            % For each of the characters in the input c
  fprintf('%s',i);  % Print the character i, without any trailing newline or whitespace
                    % No need to clear the screen, it will just append the new character
                    % after the existing ones
  pause(p);         % pause for p(1) seconds. If the input to pause is a vector,
                    % then it will choose the first value
  p=p([2,3,1]);     % Shift the pause times
end

```

The shortest I got using `disp` was 81 bytes:

```
c=input('');p=[1,1,5]/10;for i=1:nnz(c),clc;disp(c(1:i));pause(p(mod(i,3)+1));end

```

# Answer
> 4 votes
# , ~~20~~ ~~19~~ 18 bytes

*1 byte saved thanks to @DJMcMayhem*

*saved 1 byte by removing `ò` at the end*

```
òD1gÓulD1gÓulDgÓul

```

Terribly ungolfy, I know, it's just that strict `u`ndo preventing me to use nested loops.

### Explanation

The cursor starts in the beginning of the buffer, which is the first character of the input.

```
ò                      " Start recursion
 D                     " Deletes everything from the cursor's position to the end of line
  1gÓ                  " Sleep for 100ms
     u                 " Undo (now the deletion is reverted)
      l                " Move cursor one to the right
       D1gÓul          " Do it again
             D         " Same as before but...
              gÓ       " Sleep for 500ms this time
                ul     " Then undo and move right
                       " Implicit ò

```

Gif coming soon...

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

```
f=(i,o,n=0)=>i[n]&&(o.data+=i[n],setTimeout(f,++n%3?100:500,i,o,n))
```

```
<form><input id=i><button onclick=f(i.value,o.firstChild)>Go!</button><pre id=o>
```

# Answer
> 4 votes
# MATL, 16 bytes

```
"@&htDTT5hX@)&Xx

```

Try it at MATL Online!

### Explanation

```
"        % Implicitly input string. For each char of it
  @      %   Push current char
  &h     %   Concatenate everything so far into a string
  tD     %   Duplicate and display
  TT5h   %   Push array [1 1 5]
  X@)    %   Get the k-th element modularly, where k is current iteration.
         %   So this gives 1, 1, 5 cyclically
  &Xx    %   Pause for that many tenths of a second and clear screen
         % Implicit end. Implicitly display the final string, again (screen
         % was deleted at the end of the last iteration)

```

# Answer
> 4 votes
# Noodel, 18 bytes

```
ʋ115ṡḶƙÞṡạḌ100.ṡ€ß

```

Try it:)

---

### How it works

```
                   # Input is automatically pushed to the stack.
ʋ                  # Vectorize the string into an array of characters.
 115               # Push on the string literal "115" to be used to create the delays.
    ṡ              # Swap the two items on the stack.

     ḶƙÞṡạḌ100.ṡ€  # The main loop for the animation.
     Ḷ             # Loops the following code based off of the length of the string.
      ƙ            # Push on the current iteration's element of the character array (essentially a foreach).
       Þ           # Pop off of the stack and push to the screen.
        ṡ          # Swap the string "115" and he array of characters (this is done because need array of characters on the top for the loop to know how many times to loop)
         ạ         # Grab the next character in the string "115" (essentially a natural animation cmd that every time called on the same object will access the next item looping)
                   # Also, turns the string into an array of characters.
          Ḍ100.    # Pop the character off and convert to a number then multiply by 100 to get the correct delay. Then delay for that many ms.
               ṡ   # Swap the items again to compensate for the one earlier.
                €  # The end of the loop.

                 ß # Clears the screen such that when implicit popping of the stack occurs it will display the correct output.

```

---

**19 byte** code snippet that loops endlessly.

```
<div id="noodel" cols="30" rows="2" code="ʋ115ṡḷḶƙÞṡạḌ100.ṡ€ß" input='"Hello, PPCG! Goodbye Earth!"'/>
<script src="https://tkellehe.github.io/noodel/release/noodel-2.5.js"></script>
<script src="https://tkellehe.github.io/noodel/ppcg.min.js"></script>
```

# Answer
> 3 votes
# C#, ~~131~~ bytes

Not much to explain. It just takes a string (wrapped in "") as argument and prints each character using the correct delay pattern. After the animation it exits with an `OutOfRangeException` because the loop doesn't stop after it looped over all characters. Since it's an infinite loop, that also means I can use `int Main` instead of `void Main` ;-)

## Golfed

```
class C{static int Main(string[]a){for(int i=0;){System.Console.Write(a[0][i]);System.Threading.Thread.Sleep(i++%3<1?500:100);}}}

```

# Ungolfed

```
class C
{
    static int Main(string[] a)
    {
        for (int i = 0; ;)
        {
            System.Console.Write(a[0][i]);
            System.Threading.Thread.Sleep(i++ % 3 < 1 ? 500 : 100);
        }
    }
}

```

## Edits

* Saved 1 byte by moving incrementing `i` inside of the `Sleep()` method instead of in the `for` loop. (Thanks Maliafo)

# Answer
> 3 votes
# APL, 23 bytes

```
⊢{⍞←⍺⊣⎕DL⍵÷10}¨1 1 5⍴⍨⍴

```

Explanation:

```
               1 1 5⍴⍨⍴  ⍝ repeat the values [1,1,5] to match the input length
⊢                        ⍝ the input itself
 {           }¨          ⍝ pairwise map
      ⎕DL⍵÷10            ⍝ wait ⍵÷10 seconds, where ⍵ is the number
     ⊣                   ⍝ ignore that value, and
  ⍞←⍺                    ⍝ output the character

```

# Answer
> 2 votes
# SmileBASIC, 61 bytes

```
LINPUT S$FOR I=0TO LEN(S$)-1?S$[I];
WAIT 6+24*(I MOD 3>1)NEXT

```

I think the delay calculation could be a lot shorter.

# Answer
> 2 votes
# Python 3, ~~83~~ 75 bytes

```
import time;i=0
for c in input():i+=1;print(end=c);time.sleep(i%3and.1or.5)

```

Try it online!

# Answer
> 2 votes
# Clojure, 81 bytes

```
#(doseq[[c d](map vector %(cycle[100 100 500]))](Thread/sleep d)(print c)(flush))

```

Loops over the input string zipped with a infinite list of `[100 100 500]`.

```
(defn typer [input]
  ; (map vector... is generally how you zip lists in Clojure
  (doseq [[chr delay] (map vector input (cycle [100 100 500]))]
    (Thread/sleep delay)
    (print chr) (flush)))

```

# Answer
> 2 votes
# Bash (+utilities), 32 byte

> Note, this will beep in the process, but who said submissions can not have fancy sound effects !

**Golfed**

```
sed 's/.../&\a\a\a\a/g'|pv -qL10

```

**Demo**

# Answer
> 1 votes
# Powershell, ~~66~~ ~~65~~ 63 Bytes

```
[char[]]$args|%{sleep -m((1,1,5)[++$i%3]*100);Write-Host $_ -N}

```

-1 removed unneeded white space after `-m`

-2 thanks to AdmBorkBork - used `1,1,5` and `*` end result by `100` instead of using `100,100,500`

takes `$args` as a char array, loops through sleeping as specified, `Write-Host` with the `-N`oNewline argument is used to write the chars out on the same line.

Improvements?

* use `[0..99]` instead of `[char[]]` to save 1 byte, but wont work on strings over 100 chars.
* use `100,500` and `[(++$i%3)-gt1]` but make it shorter somehow.
* combine it into a single string and clear between outputs, eliminating the long `Write-Host`

can't find any way to make the last two work, and the first one isn't valid by any particular rule.

# Answer
> 0 votes
# Processing, ~~133~~ 131 bytes

```
int i;void setup(){for(String c:String.join("",args).split(""))p{try{Thread.sleep(i++%3<1?500:100);}catch(Exception e){}print(c);}}

```

*I tried doing `args[0]` and wrapping the argument in `""` instead, but it does not work for some reason.*

Anyways... this is the first time I've written a Processing program that takes arguments. Unlike Java, you don't need to declare the arguments using `String[]args`, but the variable `args` will automatically be initialised to the arguments.

Put it in a file called `sketch_name.pde` under a folder called `sketch_name` (yes, same name for folder and sketch). Call it like:

```
processing-java --sketch=/full/path/to/sketch/folder --run input text here

```

# Answer
> 0 votes
# Perl, 63 bytes

```
foreach(split//,pop){$|=++$i;print;select('','','',$i%3?.1:.5)}

```

# Answer
> 0 votes
# Python 3, 88 Bytes

```
import time;s=''
for x in input():s+=x;time.sleep(.1+.4*(len(s)%3==0));print('\n'*25+s)

```

# Answer
> 0 votes
# Rebol, 65 bytes

```
s: input t:[.1 .1 .5]forall s[prin s/1 wait last append t take t]

```

Ungolfed:

```
s: input
t: [.1 .1 .5]

forall s [
    prin s/1
    wait last append t take t
]

```

# Answer
> 0 votes
# Bash + coreutils, 57 bytes

```
for((;k<${#1};k++)){ echo -n ${1:k:1};sleep .$[2&k%3|1];}

```

# Answer
> 0 votes
# Java 7, ~~151~~ 149 bytes

```
class M{public static void main(String[]a)throws Exception{int n=0;for(String c:a[0].split("")){System.out.print(c);Thread.sleep(n++%3>0?100:500);}}}

```

-2 bytes thanks to *@KritixiLithos* for something I always forget..

**Explanation:**

```
class M{
  public static void main(String[] a) throws Exception{ // throws Exception is required due to the Thread.sleep
    int n = 0;                                          // Initialize counter (and set to 0)
    for(String c : a[0].split("")){                     // Loop over the characters of the input
      System.out.print(c);                              // Print the character
      Thread.sleep(n++ % 3 > 0 ?                        // if (n modulo 3 != 0)
                                 100                    //   Use 100 ms
                               :                        // else (n modulo 3 == 0):
                                 500);                  //   Use 500 ms
    }
  }
}

```

**Usage:**

```
java -jar M.jar "Hello, PPCG! Goodbye Earth!"

```

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


title: Substring Chainification

text:
# Question
Title: Substring Chainification
### Introduction

For this example, let's take the string `Hello, World!` and the array `[3, 2, 3]`. To find the substring chain, we go through the following process:

The first number of the array is `3`, so we get the substring `[0 - 3]`, which is `Hel`. After that, we remove the first `3` characters from the initial string, which leaves us with `lo, World!`.

The second number of the array is `2`, so we get the substring `[0 - 2]` from our new string, which gives us `lo`. The leftover string becomes `, World!`.

The last number is a `3`, which gives us `, W`. The **substring chain** is all of the substrings combined, which gives us:

```
['Hel', 'lo', ', W']

```

For a more visual example:

```
[3, 2, 3], 'Hello, World!'
3 -> Hel
2 ->    lo
3 ->      , W

```

### The task

Given **a *non-empty* string** and **a *non-empty* array** only consisting of **positive integers** (`> 0`), output the **substring chain**. You may assume that the sum of all integers in the array does not exceed the length of the string.

You can also assume that the strings will never contain any newlines.

### Test cases

```
Input: abcdefghijk, [2, 1, 3]
Output: ['ab', 'c', 'def']

Input: Code Golf, [4, 1]
Output: ['Code', ' ']

Input: Ayyy, [3]
Output: ['Ayy']

Input: lexicographically, [2, 2, 2, 7, 4]
Output: ['le', 'xi', 'co', 'graphic', 'ally']

```

This is , so the submission with the smallest number of bytes wins!

# Answer
> 33 votes
# 05AB1E, 1 byte

```
£

```

This is the substring(0,N) command.
Applied on a list this works repeatedly on the remainder on the string.

Try it online!

# Answer
> 12 votes
## Python 2, 42 bytes

```
s,a=input()
for n in a:print s[:n];s=s[n:]

```

Sometimes you just do it the boring way.

# Answer
> 8 votes
# Brachylog, ~~20~~ 13 bytes

```
h@[~c.:la~t?,

```

Try it online!

This is extremely inefficient and times out on TIO for the last test case.

### Explanation

```
Input = [String, List of integers]

h@[            Take a prefix of the string
   ~c.         Take a possible list of strings which when concatenated results in that prefix
      :la      Take the lengths of each element of that list
         ~t?,  This list of lengths is equal to the list of integers of the Input

```

### A slightly more efficient version, 15 bytes

```
t:{~l}a.,?h@[~c
```

# Answer
> 8 votes
# Python 3, 45 bytes

```
f=lambda s,a:f(s[a[0]:print(s[:a.pop(0)])],a)

```

This prints one substring per line and terminates with an error when **a** is exhausted.

Test it on repl.it.

# Answer
> 7 votes
# Python, ~~52~~, 46 bytes

```
f=lambda a,s:a and[s[:a[0]]]+f(a[1:],s[a[0]:])

```

A recursive lambda function.

*Thanks to Dennis for shaving off 6 bytes!*

# Answer
> 7 votes
# Jelly, 6 bytes

```
Jx$ĠịY

```

Try it online!

```
        The implicit working value is the first argument.
Jx$     Given a list L, repeat (x) an element of [1..len(n)] (J)
        as many times as the corresponding value in L.
   Ġ    Group indices by values. This turns [1, 1, 1, 2, 2, 3, 3]
        into [[1, 2, 3], [4, 5], [6, 7]].
    ị   Index into the second argument.
     Y  Join by newlines.

```

# Answer
> 5 votes
## Haskell, 34 bytes

```
s#(a:b)=take a s:drop a s#b
_#_=[]

```

Usage example: `"lexicographically" # [2,2,2,7,4]` -\> `["le","xi","co","graphic","ally"]`

Simple recursion.

Or the boring **29 bytes** solution via built-in:

```
import Data.Lists
splitPlaces

```

# Answer
> 5 votes
# Ruby, 26 bytes

```
->w,a{a.map{|n|w.shift n}}

```

Strings are represented as arrays of characters.

# Answer
> 4 votes
## PowerShell v2+, 46 bytes

```
param($a,$b)$b|%{-join$a[$i..($i+=$_-1)];$i++}

```

Takes input string `$a` and array `$b`, loops over `$b`. Each iteration, does an array slice of `$a` based on `$i` (defaults to `$null`, or `0`) and the current number. Needs to do the `-1` and `$i++` because strings in PowerShell are zero-indexed.

### Examples

(The output here is space-separated, because that's the default stringification method for arrays)

```
PS C:\Tools\Scripts\golfing> @('abcdefghijk',@(2,1,3)),@('Code Golf',@(4,1)),@('Ayyy',@(3)),@('lexicographically',@(2,2,2,7,4))|%{""+$_[0]+" -> "+(.\substring-chainification.ps1 $_[0] $_[1])}
abcdefghijk -> ab c def
Code Golf -> Code
Ayyy -> Ayy
lexicographically -> le xi co graphic ally

```

# Answer
> 4 votes
# Perl, 28 bytes

Includes +1 for `-n`

Run with the input string on STDIN followed by each number on a separate line:

```
(echo "Hello, World!"; echo 3; echo 2; echo 3) | perl -nE 'say for/(??{"."x<>||"^"})/g'

```

Just the code:

```
say for/(??{"."x<>||"^"})/g

```

The 23 bytes version without `||"^"` also sort of works, but prints spurious trailing newlines

`"^"` can be replaced by `$_` if the string does not contain regex meta characters

# Answer
> 3 votes
## JavaScript (ES6), ~~39~~ ~~38~~ 35 bytes

Saved 3 bytes thanks to ETHproductions:

```
s=>a=>a.map(v=>s.slice(t,t+=v),t=0)

```

Example:

```
//Definition
f=
s=>a=>a.map(v=>s.slice(t,t+=v),t=0)

//Call
f('lexicographically')([2, 2, 2, 7, 4]);

//Output
Array [ "le", "xi", "co", "graphic", "ally" ]

```

---

Previous solution:
38 bytes thanks to Huntro:
```
s=>a=>a.map(v=>s.substr(t,v,t+=v),t=0)

```

39 bytes:

```
(s,a)=>a.map(v=>s.substr(t,v,t+=v),t=0)

```

# Answer
> 3 votes
# MATL, 8 bytes

```
ys:)1bY{

```

Try it online!

### Explanation

```
y    % Implicitly take the two inputs: numerical array, string. Duplicate the array
s    % Sum of the array, say n
:    % Range from 1 to n
)    % Take first n characters of the string
1    % Push 1
b    % Bubble up the original copy of the string to the top
Y{   % Split into pieces of lengths given by the numerical array. The pieces are
     % stored in a cell array, which is implicitly displayed, one cell per line

```

# Answer
> 3 votes
## Batch, 74 bytes

```
@set/ps=
@for %%i in (%*)do @call echo %%s:~0,%%i%%&call set s=%%s:~%%i%%

```

I'm beating C? This can't be right! Takes the string on STDIN and the array as command-line arguments.

# Answer
> 3 votes
# Java, 119 Bytes

```
String[] substringChainification(String s, int[] i) {
    String[] r = new String[i.length];
    int j = 0, f = 0;
    for (int t : i)
        r[j++] = s.substring(f, f += t);
    return r;
}

```

**Golfed:**

```
String[]s(String s,int[]i){String[]r=new String[i.length];int j=0,f=0;for(int t:i)r[j++]=s.substring(f,f+=t);return r;}

```

I modified Roman Gräf's answer(https://codegolf.stackexchange.com/a/93992/59935), but i don't have enough rep to comment.

I changed the loop implementation and instead of setting the source string to another substring in every iteration, i just change the indices with which i get the substring.

# Answer
> 2 votes
## Pyke, 10 bytes

```
FQR<
Ki?>Q

```

Try it here!

# Answer
> 2 votes
# sed (82 + 2 for -rn) 84

```
s,^,\n,;:l;N;s,\n\n,\n,;:
s,^([^\n]*)\n(.)([^\n]*\n)1,\1\2\n\3,
t;P;s,^[^\n]*,,;tl

```

The first line of input is the string. Then each line after that is the size of a substring in unary.

Example:

```
$ cat test.txt:
lexicographically
11
11
11
1111111
1111

$ cat hold | sed -rnf sed.txt
le
xi
co
graphic
ally

```

# Answer
> 2 votes
## CJam, 11 bytes

```
lq~{/(ns}/;

```

Try it online!

### Explanation

```
l    e# Read input string.
q~   e# Read array of lengths and eval.
{    e# For each length...
  /  e#   Split the string into chunks of the given size.
  (  e#   Pull off the first chunk.
  n  e#   Print with linefeed.
  s  e#   Flatten the remaining chunks into a single string again.
}/
;    e# Discard any remainder of the input string.

```

# Answer
> 2 votes
# C, 81 bytes

```
i,j;f(s,l,k)char*s;int*l;{for(i=j=0;i<k;){write(1,s+j,l[i]);puts("");j+=l[i++];}}

```

Because `write()` output is not buffered any online compiler will have a hard time outputting this.

**test.c**:

```
i,j;f(s,l,k)char*s;int*l;{for(i=j=0;i<k;){write(1,s+j,l[i]);puts("");j+=l[i++];}}
main(){
    int l[]={3,2,3};
    f("Hello, World!",l,3);
    int ll[]={2,1,3};
    f("abcdefghijk",ll,3);
    int lll[]={4,1};
    f("Code Golf",lll,2);
    int llll[]={3};
    f("Ayyy",llll,1);
    int lllll[]={2,2,2,7,4};
    f("lexicographically",lllll,5);
}

```

Output without piping:

```
Hel
lo
, W
ab
c
def
Code

Ayy
le
xi
co
graphic
ally

```

# Answer
> 2 votes
# PHP, 98 Bytes

```
<?php
$b=$argv[1];foreach(explode(',',$argv[2])as$a){echo(substr($b,0,$a).' ');$b=substr($b,$a);}

```

**Usage:**

```
php chainification.php lexicographically 2,2,2,7,4

```

**Output:**

```
le xi co graphic ally

```

There's probably a better solution with PHP.

# Answer
> 2 votes
# PHP, 82 Bytes

```
<?php for($s=$argv[++$i],$j=-1;$n=$argv[++$i];){for(;$n--;)echo$s[++$j];echo"
";}

```

Takes input as a string and then a list of numbers, output is separated by new lines. e.g.

```
php chainify.php lexicographically 2 2 2 7 4

```

If you're one of those people able to use $argv with -r you can save the 6 bytes used for the opening tag.

# Answer
> 2 votes
# PHP, 63 Bytes

```
<?foreach($_GET[a]as$p){echo" ".substr($_GET[s],$s,$p);$s+=$p;}

```

Output as Array 85 Bytes

```
<?foreach($_GET["a"]as$p){$o[]=substr($_GET["s"],$s,$p);$s+=$p;}echo json_encode($o);

```

# Answer
> 2 votes
# Rebol, 38 bytes

```
func[s b][map-each n b[take/part s n]]

```

# Answer
> 1 votes
# Octave / MATLAB, 31 bytes

```
@(s,a)mat2cell(s(1:sum(a)),1,a)

```

This is an anonymous function with inputs `s`: string; `a`: numerical array.

Try it at Ideone.

### Explanation

This is a port of my MATL answer.

```
s(1:sum(a))        % Take first n characters of string s, where n is the sum of array a
mat2cell(...,1,a)  % Split into pieces of lengths given by a and store in a cell array

```

# Answer
> 1 votes
# Pyth, 7 bytes

```
PcwsM._

```

Takes input separated by newline, with the string unescaped and coming after the array. Try it Online!

Explanation:

```
     ._  Get all prefixes of Q
   sM    Map sum across each of these prefixes (to get the total indices)
 cw      Split the string at these locations
P        Remove the last "remainder" of the string

```

# Answer
> 1 votes
# Java 142 bytes

```
public static String[]substringChain(String s,int[]i){
  String[]r=new String[i.length];
  for(int j=-1;++j<i.length;){
    r[j]=s.substring(0,i[j]);
    s=s.substring(i[j]);
  }
  return b;
}

```

Golfed:

```
String[]s(String s,int[]i){String[]r=new String[i.length];for(int j=-1;++j<i.length;){r[j]=s.substring(0,i[j]);s=s.substring(i[j]);}return b;}

```

# Answer
> 1 votes
# Awk, 36 characters

```
{FIELDWIDTHS=$0;OFS=RS;getline}$1=$1

```

Sample run:

```
bash-4.3$ awk '{FIELDWIDTHS=$0;OFS=RS;getline}$1=$1' <<< $'3 2 3\nHello, World!'
Hel
lo
, W

```

In real life I would use it like this, just no idea how to calculate its score:

```
bash-4.3$ awk -vFIELDWIDTHS='3 2 3' -vOFS='\n' '$1=$1' <<< 'Hello, World!'
Hel
lo
, W

```

# Answer
> 1 votes
# Dyalog APL 16.0, 15 characters (non-competing); 15.0, 17 bytes

### 16.0 solution

```
{⍵⊆⍨(⍴⍵)↑⍺/+\⍺}

```

Dyalog APL 16.0 adds APL2's partition primitive, , with the glyph .

### 15.0 solution:

```
{(-⍺)↑¨(+\⍺)↑¨⊂⍵}

```

TryAPL online!

# Answer
> 1 votes
# Vimscript, ~~79~~ 78 bytes

not very pretty, I'm sure it can be improved...

Takes a vim buffer, then call `echom string(A([2,3]))` to see the output

```
fu A(l)
let r=[]
for i in a:l
exe "norm d".i."l"
let r+=[@"]
endfo
retu r
endf

```

I actually thought of cheating and outputing the *string* `["abc", "def"]`... But I resisted :P

Explanation: Delete (puts in default register) each array items amounts of characters and adds it to the array `r`... A boring answer indeed.

# Answer
> 1 votes
## GNU sed, 55 + 2(rn flags) = 57 bytes

```
1H;1d;G;:;s=.(\n.*)\n(.)=\1\2\n=;t;s=.==;P;s=[^\n]*==;h

```

**Try it online!** (thanks to @Dennis for adding sed)

**Explanation:** The input string should be on the first line and the numbers, in unary, on separate lines after that. A new line is read implicitly at the start of a cycle, running the script each time.

```
1H;1d                       # once: append string to hold space and start new cycle
                            #Initially, the hold space contains an useful '\n'.
G                           # append hold space to pattern space. The pattern space
                            #format will be: 'UNARY\n\nSTRING'.
:;s=.(\n.*)\n(.)=\1\2\n=;t  # iteratively remove a char from the string, as many
                            #times as unary chars, and store it on 2nd pattern line
s=.==;P                     # remove '\n', then print the new top line
s=[^\n]*==;h                # delete up to '\n' and update hold space

```

**Test run:** using a here-document with EOF as the end marker

```
sed -rnf program.sed << EOF
> abcdefghijk
> 00
> 0
> 000
> EOF

```

**Output:**

```
ab
c
def

```

# Answer
> 1 votes
## Ruby, 28 bytes

```
->a,w{a.map{|e|w.slice!0,e}}

```

In case arguments are an array of positive integers and one string.

# Answer
> 1 votes
# Common Lisp, ~~78~~ 76 bytes

Assuming anonymous function is allowed:

```
(lambda(s l)(loop for x in l as y = x then(+ y x)collect(subseq s(- y x)y)))

```

### Usage

```
(funcall #'(lambda(s l)(loop for x in l as y = x then(+ y x)collect(subseq s(- y x)y)))"AbCdefGhijK"'(3 2 3))

```

### Output

```
("AbC" "de" "fGh")

```

-2 bytes by using `as` instead of `and` and changing y definition to fit parentheses between two variables in `(subseq ...)`

# Answer
> 0 votes
**C 474 byte**

```
char**f(char*a,int*b){int  i,j;static char *t[99];for(j=0;j<99;++j)t[j]=0;t[0]=a;for(i=0,j=1;j<99&&a[i]&&b[j-1];++i)if(i>=b[j-1]){t[j++]=a+i;i=0;a=t[j-1];}t[j]=a+i;return j>=99?0:t;}void showResult(char**p, int*b){char *v;int i,j;if(p==0) {printf("NULL"); return;}printf("\'%s\' [", p[0]);for(i=0;b[i];++i)printf("%d%s", b[i], b[i+1]?", ":"");printf("]==[");for(i=0;b[i];++i){printf("\'");for(v=p[i]; v<p[i+1];++v)putchar(*v);printf("\'%s", b[i+1]?", ": "");}printf("]\n");}

```

main

```
main()
{char *test[]={"Hello, World", "abcdefghijk", "Code Golf",
               "Ayyy","lexicographically",0}, **p;
 int  v[80];

 v[0]=3;v[1]=2;v[2]=3;v[3]=0;showResult(f(test[0], v), v);
 v[0]=2;v[1]=1;v[2]=3;v[3]=0;showResult(f(test[1], v), v);
 v[0]=4;v[1]=1;v[2]=0;       showResult(f(test[2], v), v);
 v[0]=3;v[1]=0;              showResult(f(test[3], v), v);
 v[0]=2;v[1]=2;v[2]=2;v[3]=7; v[4]=4; v[5]=0;
                         showResult(f(test[4], v), v);
}
/*
 474
 'Hello, World' [3, 2, 3]==['Hel', 'lo', ', W']
 'abcdefghijk' [2, 1, 3]==['ab', 'c', 'def']
 'Code Golf' [4, 1]==['Code', ' ']
 'Ayyy' [3]==['Ayy']
 'lexicographically' [2, 2, 2, 7, 4]==['le', 'xi', 'co', 'graphic', 'ally']
*/

```

# Answer
> 0 votes
# Java - 143 bytes

```
String[]s(String u,int[]a){String[]k=new String[a.length];for(int i=0;i<k.length;i++){k[i]=u.substring(0,a[i]);u=u.substring(a[i]);}return k;}

```

Ungolfed version:

```
String[] s (String u, int[] a) {
    String[] k = new String[a.length];
    for (int i = 0; i < k.length; i++) {
        k[i] = u.substring(0,a[i]);
        u = u.substring(a[i]);
    }
    return k;
}

```

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


title: Pack sequences of non-negative integers

text:
# Question
Title: Pack sequences of non-negative integers
Let **N** be the set of nonnegative integers, i.e. {0, 1, 2, 3, ...}.

Let c0(**N**) be the set of all infinite sequences in **N** that converge to 0, i.e. { (xn) ∈ **N****N** | xn → 0 as n → ∞}.

c0(**N**) can be equivalently written as the set of all finite sequences of natural numbers, such that there are no trailing zeroes. The infinite sequence of all zeroes (corresponding to a finite sequence of length 0) is an element of c0(**N**).

***Your task*** *is to implement a bijection in your language between **N** and c0(**N**), in as few characters as possible.* This means every number in **N** corresponds to a unique item of c0(**N**), and vice versa. Do this by defining two functions: `f`, going from **N** and c0(**N**); and `g`, the inverse of `f`. *The length in bytes of these two definitions is your score.*

You may use the largest internal integer and list types of your language, even if they aren't bignums or capable of handling infinite length. However, they should theoretically still be able to terminate with the right answer if the language was modified with a suitable bignum or lazy/infinite list type.

Some suggestions for ways to pack are below. Note that these aren't quite solutions yet and could need some tweaking to work; they're mostly to get the blood flowing.

* `f(1463616) = f(2^6 * 3^3 * 5^0 * 7^1 * 11^2) = [6, 3, 0, 1, 2]` \- Factorize the number into primes and read off exponents to get the sequence.
* `f(64971) = f(0b1111110111001011) = [6, 3, 0, 1, 2]` \- Expand the number in binary and use 0 as a separator to read strings of ones, representing the sequence in unary.

---

While this is a and the shortest answer will win, creative and interesting solutions are encouraged and may be subject to a bounty.

# Answer
# GolfScript, 41 bytes

```
{[2base[0]/{,}/]-1%}:f{:|;-1{).f|=!}do}:g

```

### Function “f”

```
[
  2base       # Push the digits of the argument in base 2.
  [0]/        # Split the digits around the 0's. This leaves sequences of 1's.
  {,}/        # Compute the lengths of those sequences.
]-1%          # Reverse the array of the lengths.

```

The binary expansion of any given non-negative integer in its canonical form may have *trailing* 0's, but not *leading* 0's.

Thus, reversing the array is necessary and sufficient to comply with the specification.

### Function “g”

```
:|;           # Save the argument in variable “|” and pop it from the stack.
-1            # Push the integer “-1”.
{             #
  )           # Increment the integer.
  .f|=        # Check whether it is the preimage of “|”.
  !           # If it is not,
}do           # repeat the loop.

```

### Function “g” (alternative)

An alternative, straightforward and efficient implementation of `g` is

```
{[-1%{0\{1}*}/]2base}:g

```

The brute-force approach is *much* slower, but it is four bytes shorter.

```
[
  -1%         # Reverse the order of the integer sequence.
  {           # For each integer “N”,
    0         # push 0,
    \{1}*     # followed by “N” 1's.
  }/          #
]             # Convert this bit sequence into an array.
2base         # Convert the array into an integer.

```

### Example

* `1250` is `10011100010` in base 2.
* The lengths of the sequences of consecutive 1's are `1,0,3,0,0,1,0`.
* Thus, the sequence corresponding to `1250` is `0,1,0,0,3,0,1`.

### Proof of work

```
10000,(;      # Push an array of all integers from 1 to 9999.
{             # For each integer “N”,
  f-1=0=      # if “f(N)” has a trailing zero,
  {0p}*       # print a message.
}/

```

leaves nothing on the stack, so `f` is well-defined.

```
1000,.        # Push the array of all integers from 0 to 999 and duplicate it.
[             #
  {f g}/      # For each integer “N”, push “g(f(N))”.
]=            # Check if the array of the images matches the original array.

```

leaves `1` on the stack (using either definition of `g`).

This means that `g` is a left inverse of `f`, so `f` is injective.

```
[
  1000,.      # Push the array of all integers from 0 to 999 and duplicate it.
  10%-        # Remove the integers with trailing 0's.
  {           # For each integer “N”,
    10base    # push the array of its digits in base 10,
    .0\+.0\+  # and create copies with one and two leading 0's.
  }/          #
].            # Collect all sequences in an array and duplicate it.
[             #
  {g f}/      # For each sequence “S”, push “f(g(S))”.
]=            # Check if the array of the images matches the original array.

```

leaves `1` on the stack (using the second definition of `g`).

This means that `g` is a right inverse of `f`, so `f` is surjective.
> 2 votes

# Answer
# J - 17 char

```
g=:(f=:_ q:>:)inv

```

We implement the prime exponent idea with this bijection—that's what the `_ q:` is doing, getting a list of the exponents of the primes of a number—except we also increment the input number by one before doing so, with `>:`, so that we don't forget 0, who doesn't have its own prime factorization.

For the definition of `g`, it's exactly what it looks like: instead of writing it ourselves, we just tell J to take the inverse of `f`. Arguably this is cheating, or just not interesting, but I think that the ability to do this is what makes J such an interesting language: J can often figure things out for you, allowing you to focus on expressing your solution instead of implementing it.

```
   i. 20
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
   f i. 20  NB. J pads with zeroes on right
0 0 0 0 0 0 0 0
1 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0
2 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0
1 1 0 0 0 0 0 0
0 0 0 1 0 0 0 0
3 0 0 0 0 0 0 0
0 2 0 0 0 0 0 0
1 0 1 0 0 0 0 0
0 0 0 0 1 0 0 0
2 1 0 0 0 0 0 0
0 0 0 0 0 1 0 0
1 0 0 1 0 0 0 0
0 1 1 0 0 0 0 0
4 0 0 0 0 0 0 0
0 0 0 0 0 0 1 0
1 2 0 0 0 0 0 0
0 0 0 0 0 0 0 1
2 0 1 0 0 0 0 0
   g f i. 20
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

```

Proving that this is a bijection is straightforward: the injectivity of this `f` is a well known fact and, if you assume that J's automagical inverse is correct (which it is), then this is trivial.

If you don't want to take it on faith that J knows how to take the inverse of `f`, we can inspect its automatic inverse for `_&q:`:

```
   _&q: b. _1
(p:@i.@# */ .^ ])"1 :.(_&q:)

```

and then check the definition:

```
(p:@i.@# */ .^ ])"1 :.(_&q:)  NB. the alleged inverse of _&q:
                    :.(_&q:)  NB. defining _&q:inv inv to be _&q:
(               )"1           NB. operate on rows of the argument
       #                      NB. length of argument
    i.@                       NB. nonnegative integers less than
 p:@                          NB. n-th prime for each integer n
               ]              NB. the argument again
            .^                NB. pointwise exponentiation
         */                   NB. product

```

and then confirm that J's inverse of `f` gives the decrement of the result of this:

```
   >: b. _1  NB. inverse of increment is decrement
<:
   f b. _1   NB. ([: f g) is one way of writing f composed with g
[: <: (p:@i.@# */ .^ ])"1 :.(_&q:)

```
> 5 votes

# Answer
# Jelly, 7 + 3 = 10 or 11 bytes, language postdates question

```
JÆN*¹P’
‘ÆE

```

Try it online!

Defines an packing function `1Ŀ` and an unpacking function `2Ŀ`. These could be defined in two separate programs, but if you define them both in a single program, you need a newline to separate the definitions. Thus I'm not 100% sure how to count it.

## Explanation

This packs the sequence into a product of primes, which was one of the suggestions in the question.

**Packing**

```
JÆN*¹P’
J         Replace each element of {the input} by its index
 ÆN       Replace each index n by the nth prime number
   *      Raise each element to the power of
    ¹       {the original input}
     P    Take the product of all the elements
      ’   Subtract 1 (so that some sequence maps to 0, making a bijection)

```

**Unpacking**

```
‘ÆE
‘         Add 1 (undo the subtraction earlier)
 ÆE       Output the number of times each prime divides the current value

```

As can be seen, unpacking is very simple here due to the builtin `ÆE`, which is why I selected this format. ~~There's no builtin to do the packing~~, but it has a fairly terse implementation too.

# Jelly, 3 + 3 = 6 or 7 bytes, with some help from @Dennis

OK, apparently there *is* a builtin to do the packing…

```
ÆẸ’
‘ÆE

```

Try it online!

The explanation above still works; it's just that all of `JÆN*¹P` have been replaced by a builtin.
> 2 votes

# Answer
# Python, ~~257~~ 265B

```
from itertools import*
T=lambda i:[list(a)for l in range(i)for a in product(range(i-l+3),repeat=l+1)if a[-1]>0and sum(a)==i-l]
def f(N):
 A,i=[[0]],0
 while len(A)<=N:A+=T(i);i+=1
 return A[N]
def g(t):
 A,i=[[0]],0
 while t not in A:A+=T(i);i+=1
 return A.index(t)

```

To list every sequence, for each integer i, for each length l

```
0 :  1
1 :  2
2 :  0 1
3 :  3
4 :  0 2
5 :  1 1
6 :  0 0 1
7 :  4
8 :  0 3
9 :  1 2
10 :  2 1
11 :  0 0 2
12 :  0 1 1
13 :  1 0 1
14 :  0 0 0 1
15 :  5
16 :  0 4
17 :  1 3
18 :  2 2
19 :  3 1
20 :  0 0 3
21 :  0 1 2
22 :  0 2 1
23 :  1 0 2
24 :  1 1 1
25 :  2 0 1
26 :  0 0 0 2
27 :  0 0 1 1
28 :  0 1 0 1
29 :  1 0 0 1
30 :  0 0 0 0 1

```

so `f(256)=[9]`, and `g([4,2,0,3])=2254`. NB that this is SLOW for large numbers.
> 1 votes

# Answer
# MATL, 8+3 = 11 bytes

## Function f

```
QYF

```

Nice and simple, outputs the exponents of the prime factor decomposition of the input+1, for instance input of 1752922079 gives \[5, 3, 1, 4, 0, 2\]

## Function g

Takes a finite vector of non-negative integers and outputs a single non-negative integer.

```
n:YqG^pq

```

### Explanation

```
n       % find the length of the input
:       % make a range that long
Yq      % use the range to find the first n primes
G       % paste the input vector again
^       % take powers element wise
p       % product of elements
q       % decrement by 1 so 0 is included
        % (implicit) convert to string and display

```

For instance, input \[5, 3, 1, 4, 0, 2\] first pushes the vector \[2, 3, 5, 7, 11, 13\], then combines them into \[32, 27, 5, 2401, 1, 169\] before taking the product, giving 1752922080 and decrementing to give the final answer 1752922079.
> 0 votes

---
Tags: code-golf, number, sequence, open-ended-function
---


title: Reverse Insertion sort

text:
# Question
Title: Reverse Insertion sort
# Objective

Generate the original scrambled list, from the movements that an Insertion Sort would do to sort it. The original list will have all numbers from `0` to `N-1`(inclusive) where `N` is the size of the input.

# Input

A list containing the necessary moves to sort the list. Each value represents the amount of slots displaced by the original (scrambled) number to be in his right position , keep in mind that this process is from the left to the right.
The value at (0-indexed) position `i` in the input list will be between `0` and `i` inclusive.
You don't need to handle invalid inputs, any behaviour is acceptable in this case (crash, infinite loop, etc).

# Output

The scrambled list

### Step-by-step to generate the moves

```
Scrambled List | Moves to sort
[4,0,2,1,3,5]  | [0, , , , , ] #4 stay in place
[**4,**0,2,1,3,5]  | [0,1, , , , ] #0 is moved 1 slot to the left
[**0,4**,2,1,3,5]  | [0,1,1, , , ] #2 is moved 1 slot
[**0,2,4,**1,3,5]  | [0,1,1,2, , ] #1 is moved 2 slot
[**0,1,2,4,**3,5]  | [0,1,1,2,1, ] #3 is moved 1 slot
[**0,1,2,3,4,**5]  | [0,1,1,2,1,0] #5 is in the right place already
[**0,1,2,3,4,5**]

```

So, for the input `[0,1,1,2,1,0]` your program need to output `[4,0,2,1,3,5]`.
Keep in mind that the movements aren't to the position in the (final) sorted list, but in the sorted segment(the bolded section)

# Test Cases

```
[0,0,0] -> [0,1,2]
[0,1,0,1] -> [1,0,3,2]
[0,0,0,0,0,5] -> [1,2,3,4,5,0]
[0,1,2,3] -> [3,2,1,0]
[0,1,1,1] -> [3,0,1,2]
[0,1,1,2,1,0] -> [4,0,2,1,3,5]

```

# Winning

This is , so the shortest answer wins.

# Answer
> 14 votes
# Jelly, 12 bytes

```
L!_UÆ¡$œ?J’U

```

Try it online!

## Explanation

We can basically see the two lists (the input and the output) as encoding an integer; the input encodes an integer in factorial base, and the output encodes an integer as a permutation. Luckily, Jelly has builtins that are already very close to both of these encodings, so it's simply a matter of writing small pieces of code to convert to an integer, then back to the other encoding.

```
L!_UÆ¡$œ?J’U
   U           Reverse {the input}
    Æ¡         and convert from base factorial to integer;
  _   $        subtract that from
L!             the factorial of the length of {the input};
       œ?      then take the nth permutation of
         J     [1,2,...,l], where l is the length of {the input},
          ’    subtract 1 from every elevent,
           U   and reverse it

```

In the case of base factorial, we can observe that the first element of the list must be 0, the second can be 0 or 1, the third must be 0/1/2, and so on. Thus, we have to reverse the input in order to get its elements into the normal writing order for base conversion.

Additionally, for the relative orders of the factorial conversion and the permutation conversion to match up with the operation that insertion sort uses, we need to make two adjustments: reversing the sequence of the permutations, and reversing the order of the output list. Reversing the output list is easy enough, needing only a `U` at the end of the program. To reverse the sequence of permutations, we subtract from the factorial of the input length (this works because the base factorial produces a number in the range 0 to (length!-1), whereas the permutations are numbered by Jelly from 1 to length!, producing an implicit off-by-one that cancels out the off-by-one that you normally get when subtracting a permutation index from a factorial).

# Jelly, 9 bytes, in collaboration with @JonathanAllan

```
UÆ¡Nœ?J’U

```

This version of the program is very similar, but uses a different method of reversing the sequence of permutations; simply negating the input with `N` is enough to make `œ?` treat the order in reverse. Apart from that, it works identically to the previous program.

Try it online!

# Answer
> 6 votes
# Mathematica, 92 bytes

```
Permute[Range[l=Length@#]-1,(c=Cycles@{#}&)@{}©##&@@c[i-0~Range~#[[i]]]~Table~{i,l,1,-1}]&

```

Pure function taking a list of nonnegative integers as input and returning a list of nonnegative integers. The above code contains a `©`, which is incorrect: it's a placeholder for the 3-byte symbol U+F3DE, which Mathematica represents by a circle with a dot in it, and which represents composition of permutations.

`c=Cycles@{#}&` defines a function that converts a list of integers into a `Cycles` object representing a permutation; for example, `c[{3,4}]` is the transposition swapping elements 3 and 4 of a list. `c[i-0~Range~#[[i]]]~Table~{i,l,1,-1}]` takes the input list and generates the permutations necessary to undo the insertion sort. Then `c@{}©##&@@` composes all of these permutations together, starting with the identity permutation `c@{}`. Finally, `Permute[Range[l=Length@#]-1,...]` applies this permutation to the 0-indexed list of appropriate length.

# Answer
> 6 votes
# Python 2, 79 68 bytes

Thanks to Krazor for saving 10 bytes

Thanks to TuukkaX for saving 1 byte

```
a=input();b=range(len(a));print[b.pop(j-a[j])for j in b[::-1]][::-1]

```

Works by generating the moves in reverse

# Answer
> 5 votes
## JavaScript (ES6), ~~69~~ ~~65~~ 63 bytes

```
a=>a.reverse(b=[...a.keys()]).map(o=>+b.splice(~o,1)).reverse()

```

Annoyingly both input and output are in the wrong order. Edit: Saved 4 bytes thanks to @Arnauld. Saved 2 bytes thanks to @ETHproductions.

# Answer
> 3 votes
## JavaScript (ES6), ~~73~~ 71 bytes

*Saved 2 bytes thanks to ETHproductions*

```
m=>(a=m.map((_,i)=>j=i)).map(_=>a.splice(j,0,+a.splice(j-m[j--],1)))&&a

```

### Test cases

```
let f =

m=>(a=m.map((_,i)=>j=i)).map(_=>a.splice(j,0,+a.splice(j-m[j--],1)))&&a

console.log(JSON.stringify(f([0,0,0])));       // -> [0,1,2]
console.log(JSON.stringify(f([0,1,0,1])));     // -> [1,0,3,2]
console.log(JSON.stringify(f([0,0,0,0,0,5]))); // -> [1,2,3,4,5,0]
console.log(JSON.stringify(f([0,1,2,3])));     // -> [3,2,1,0]
console.log(JSON.stringify(f([0,1,1,1])));     // -> [3,0,1,2]
console.log(JSON.stringify(f([0,1,1,2,1,0]))); // -> [4,0,2,1,3,5]
```

# Answer
> 2 votes
# Haskell, 85 bytes

```
f x|n<-length x-1=reverse x#[n,n-1..0]
(n:r)#l=r#(take n l++drop(n+1)l)++[l!!n]
x#l=x

```

Try it online! Example usage: `f [0,1,1,2,1,0]` yields `[4,0,2,1,3,5]`.

`f x` calls the function `#` with list `x` reversed and a list `[length x - 1, length x - 2, ... , 0]`. `(n:r)#l` performs the reverse insertion sort by recursively taking the `n`th element out of `l`, where `l!!n` yields the `n`th element and `take n l++drop(n+1)l` yields the list `l` with the `n`th element removed.

# Answer
> 1 votes
# perl, 61 bytes

```
@o=@p=0..@ARGV-1;splice@o,$_,0,splice@o,$_-pop,1for reverse@p

```

Output ends up in array @o. Example with input array as command line arguments:

```
perl -le'@o=@p=0..@ARGV-1;splice@o,$_,0,splice@o,$_-pop,1for reverse@p;print@o' 0 1 1 2 1 0
402135

```

# Answer
> 1 votes
## Ruby, 49 bytes

```
->l{(w=l.size).times{l.insert(l.shift+w-=1,w)};l}

```

Performs the "reverse insertion" in place inside the list, starting with the largest number.

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


title: Calculate ELO Rating Expected Score

text:
# Question
Title: Calculate ELO Rating Expected Score
Your task is to calculate the expected chance of winning for 2 players in some game, each with their own **ELO Rating**. Player A has ELO Ra and player B has ELO Rb

The expected score for Player A (Ea) is: 1 / (1 + 10(Rb \- Ra) / 400). There is a similar equation for Player B (Eb): 1 / (1 + 10(Ra \- Rb) / 400).

If you want a more copiable version: `1 / (1 + 10^((a-b) / 400))`

Ea \+ Eb should be equal to 1.

Therefore, the score for a player is their expected chance of winning some match, in decimal.

Your program/function should take 2 inputs, Player A's ELO, and Player B's ELO, and print/return their respective chance to win in decimal format. The output *must* add up to one, and you must be accurate to at least 5 decimal places (`0.00000`). After 5 decimal places, you may have inaccurate digits, provided the two outputs still add up to one.

### Examples:

```
1200 2100 -> 0.005591967 0.994408033
1 1 -> 0.5 0.5
60 20 -> 0.557312 0.442688
9999 9998 -> 0.501439 0.498561
9999 1 -> 0.999999 0.000001

```

In the final test case, some answers use scientific exponentiation to represent the value. This is not valid.

You can see in test case 3 here that `0.557312` is not quite accurate, because the `2` should be a `1`, but this is fine because it is after five decimal places and the outputs still add up to one.

This is an example of invalid output:

```
9999 9998 -> 0.5014391117091516, 0.49856088829084844

```

This looks like it satisfies the requirements at first glance, but the numbers add up to `1.00000000000000004` and therefore the output is not valid.

Trailing zeroes in the output is fine.

You may assume a player's ELO will always be greater than 0, and nobody will have an ELO higher than 9999.

The input and output format is flexible, but the input and output must still be in base 10.

As this is , the answer with the lowest byte count will win!

# Answer
> 5 votes
# Jelly, 9 bytes

```
÷400⁵*÷S$

```

Try it online! or View all test cases.

The input is an array `[Ra, Rb]` and the output is an array `[Ea, Eb]`.

## Explanation

```
÷400⁵*÷S$  Input: array [Ra, Rb]
÷400       Divide each by 400, makes [Ra/400, Rb/400]
    ⁵*     Raise 10 to that power, makes [10^(Ra/400), 10^(Rb/400)]
        $  Monadic chain operating on previous result
      ÷      Divide each by
       S     The sum of the whole
           Makes [10^(Ra/400)/(10^(Ra/400) + 10^(Rb/400)),
                  10^(Rb/400)/(10^(Ra/400) + 10^(Rb/400))]
               = [1/(1 + 10^((Rb-Ra)/400)), 1/(1 + 10^((Ra-Rb)/400))]

```

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

```
lambda a,b:[1/(1+10**(x/400))for x in[b-a,a-b]]

```

-8 bytes thanks to @math\_junkie

# Answer
> 3 votes
# MATL, 11 bytes

```
10i400/^ts/

```

Takes input as a list and outputs a list.

```
10       % push number literal
i        % push input
400      % push number literal
/        % divide the list (by 400)
^        % power (10^list, element wise)
t        % duplicate the list
s        % sum the second one
/        % divide by the sum
         % (implicit) convert to string and display

```

# Answer
> 1 votes
# JavaScript (ES7), ~~41~~ 35 bytes

*Saved 6 bytes thanks to @Neil*

```
a=>b=>[b=1/(1+10**((b-a)/400)),1-b]

```

# Answer
> 1 votes
# CJam, 23 bytes

```
XAq~_W%\.m400df/f#:)f/p

```

Some other 23 byte solutions:

```
q~_W%\.m400df{/A\#)W#}p
Aq~_W%\.m400df/f{#)W#}p

```

Try it online!

**Explanation**

```
X                        Push 1
 A                       Push 10
  q~                     Push an eval the input, a list containing 2 numbers
    _W%                  Duplicate the list and reverse it
       \                 Swap top stack elements, so the order of answers matches the input
        .m               Vectorized subtraction: computes Ra - Rb and Rb - Ra
          400d           Push 400.0 (must be a double, otherwise / performs integer division)
              f/         Divide both values by 400
                f#       Raise 10 to the power of both numbers
                  :)     Increment both numbers
                    f/   Divide 1 by both numbers
                      p  Output the list nicely

```

# Answer
> 1 votes
# C, 63 bytes

```
#define M(a,b)1/(1+pow(10,(a-b)/400.)),1/(1+pow(10,(b-a)/400.))

```

Defines a (rather naive) parameterized macro `M`, the shortest working approach I could think of but probably still not the shortest. As such, any golfing suggestions are greatly appreciated.

Anyways, this returns 2 floating point values, `E_b` and `E_a`, respectively.

Try it online!

# Answer
> 0 votes
# SAS Macro Language, 70 bytes

```
%macro e(a,b);data t;p=1/(1+10**((&b-&a)/400));q=1-p;proc print%mend;

```

Output is a SAS data set where variables `p` and `q` are the players' chance of winning. 11 bytes can be saved by removing the `print` procedure.

# Answer
> 0 votes
# C#, 92 bytes

Not the shortest, but it's C#, never the shortest..

# Golfed

```
   static double[]f(int a,double b){b=1/(1+System.Math.Pow(10,(a-b)/400d));return new[]{1-b,b};

```

## Ungolfed

```
static double[] f(int a, double b)
{
    b = 1/(1 + System.Math.Pow(10, (a - b)/400d));
    return new[] {1 - b, b};
}

```

# Answer
> 0 votes
# q, 26 bytes

```
{1%1+10 xexp(y-x;x-y)%400}

```

Example

```
q){1%1+10 xexp(y-x;x-y)%400}[1200;2100]
0.0055919673088347735 0.99440803269116518

```

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


title: In Soviet Russia, code writes you!

text:
# Question
Title: In Soviet Russia, code writes you!
## Input

Two words separated by a space. It is assumed that the first is a verb.

## Output

The "Soviet counterpoint" to the input phrase, in the form of a punchline to an "in Soviet Russia" joke.

```
"break law" --> "In Soviet Russia, law break you!"

```

Accounting for correct grammar is unimportant.

Shortest program wins!

# Answer
# Perl 6, ~~40~~ 37 bytes

~~```
{"In Soviet Russia, {.words[1,0]} you!"}

```~~
```
{~[R,] «you! $_ Russia, Soviet In»}

```

It works because the `« »` "word list quote" recursively splits everything on whitespace.

---

Some other answers require the input words to be passed as two separate arguments. I think that's cheating, but for the record, it would make this solution 34 bytes long (and really boring):

```
{"In Soviet Russia, $^b $^a you!"}

```
> 2 votes

# Answer
# Jelly, 20 bytes

```
“\UṙȦƒĊÑṆ»⁶³ḲṚK“æw}»

```

Try it online!

```
“\UṙȦƒĊÑṆ»⁶³ḲṚK“æw}»
“\UṙȦƒĊÑṆ»                   Set output to 'In Soviet Russia,'
          ⁶                  Set output to ' ' {implicitly printing the previous
                             output}
           ³                 Set output to the input {implicitly printing the
                             previous output}             "breaks law"
            Ḳ                Split {the input} on spaces. ['breaks', 'law']
             Ṛ               Reverse list.                ['law', 'breaks']
              K              Join with spaces.            "law breaks"
               “æw}»         Set output to ' you!' {implicitly printing the
                             previous output}

```

---

Alternatively, if there's no obligation for quotes around the input, it can be done in 19 bytes.

```
“\UṙȦƒĊÑṆ»⁶⁴⁶³“æw}»

```

Try it online!
> 1 votes

# Answer
# Python 3, ~~57~~ 56 bytes

```
print("In Soviet Russia,",*input().split()[::-1],"you!")

```

**Try it online**
> 0 votes

# Answer
# TI-Basic, 68 bytes

```
Input Str1
inString(Str1,"
"IN SOVIET RUSSIA, "+sub(Str1,Ans+1,Str1-Ans)+" "+sub(Str1,1,Ans-1)+" YOU!

```

"Accounting for correct grammar is unimportant." I guess that means I can yell everything ;)
> 0 votes

# Answer
# Gema, 32 characters

```
* *=In Soviet Russia, $2 * you\!

```

Sample run:

```
bash-4.3$ printf 'break law' | gema '* *=In Soviet Russia, $2 * you\!'
In Soviet Russia, law break you!

```
> 0 votes

# Answer
# Jelly, 20 bytes

```
Ḳ“\UṙȦƒĊÑṆ»ṭṚ“©ṠẆ»ṭK

```

Try it online!

More fun with Jelly's compressed strings.

```
Ḳ“\UṙȦƒĊÑṆ»ṭṚ“©ṠẆ»ṭK
Ḳ                     Split {the input} on spaces
           ṭ          Add an additional input to the end:
 “\UṙȦƒĊÑṆ»             "In Soviet Russia," (compressed notation)
            Ṛ         Reverse the list
                  ṭ   Add another additional input to the end:
             “©ṠẆ»      "you!" (compressed notation)
                   K  Join on spaces {and implicitly output}

```
> 0 votes

# Answer
# Retina, ~~39~~ 37 bytes

*Saved 2 bytes thanks to Martin Ender*

```
(.+ )(.+)
In Soviet Russia, $2 $1you!

```

Try it online!
> 0 votes

# Answer
# JAPT 29 Bytes

```
`In soviet rÔëa, {V} {U} y!`

```

input: "drink" "milk"

output: In Soviet Russia, milk drink you

explaination: {U} and {V} are the input variables. it inserts them in the string when running the code.

First code-golf ever. hope it counts!

Try it online!
> 0 votes

# Answer
# 05AB1E, 20 bytes

```
”InË·ž¦,”I#R„€î!)˜ðý

```

Try it online!
> 0 votes

# Answer
# GNU sed, 40 bytes

```
s/(.+ )(.+)/In Soviet Russia, \2 \1you!/

```

Try it online!
> 0 votes

# Answer
# , 29 bytes

```
iIn Soviet Russia, <C-r>b <C-r>a you!

```

Try it online!

Note that `<C-r>` is actually ctrl-r, or ASCII `0x12`, but since that character is unprintable, using the verbose mode to represent it is more convenient.

This is probably about as short as it can get without using compression.
> 0 votes

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


# Question
Title: Smallest multiplier that reveals a factor of a semiprime
Given a semiprime **N**, find the smallest positive integer **m** such that the binary representation of one of the two factors of **N** can be found in the binary representation of **N * m**.

### Example

Let's consider the semiprime **N** = **9799**.

We try different values of **m**, starting at 1:

```
 m |  N * m |   N * m in binary
---+--------+------------------
 1 |   9799 |    10011001000111
 2 |  19598 |   100110010001110
 3 |  29397 |   111001011010101
 4 |  39196 |  1001100100011100
 5 |  48995 |  1011111101100011
 6 |  58794 |  1110010110101010
 7 |  68593 | 10000101111110001
 8 |  78392 | 10011001000111000
 9 |  88191 | 10101100001111111
10 |  97990 | 10111111011000110
11 | 107789 | 11010010100001101

```

We stop here because the binary representation of the last product contains `101001` which is the binary representation of **41**, one of the two factors of **9799** (the other one being **239**).

So the answer would be **11**.

### Rules and notes

* Trying even values of **m** is pointless. They were shown in the above example for the sake of completeness.
* Your program must support any **N** for which **N * m** is within the computing capabilities of your language.
* You are allowed to factorize **N** beforehand rather than trying each possible substring of the binary representation of **N * m** to see if it turns out to be a factor of **N**.
* As proven by MitchellSpector, **m** always exists.
* This is code-golf, so the shortest answer in bytes wins. Standard loopholes are forbidden.

### Test cases

The first column is the input. The second column is the expected output.

```
         N |    m |         N * m |                              N * m in binary | Factor
-----------+------+---------------+----------------------------------------------+-------
         9 |    3 |            27 |                                      [11]011 |      3
        15 |    1 |            15 |                                       [11]11 |      3
        49 |    5 |           245 |                                   [111]10101 |      7
        91 |    1 |            91 |                                    10[1101]1 |     13
       961 |   17 |         16337 |                             [11111]111010001 |     31
      1829 |    5 |          9145 |                             1000[111011]1001 |     59
      9799 |   11 |        107789 |                          1[101001]0100001101 |     41
     19951 |   41 |        817991 |                       1[1000111]101101000111 |     71
    120797 |   27 |       3261519 |                     11000[1110001]0001001111 |    113
   1720861 |  121 |     208224181 |               11000110100[100111111101]10101 |   2557
 444309323 |  743 |  330121826989 |    100110011011100110010[1101010010101011]01 |  54443
 840000701 | 4515 | 3792603165015 | 11011100110000[1000110000111011]000101010111 |  35899
1468255967 |   55 |   80754078185 |      1001011001101010100010[1110001111]01001 |    911

```

# Answer
> 6 votes
# Pyth, 13 bytes

```
ff}.BY.B*TQPQ

```

Demonstration

Explanation:

```
ff}.BY.B*TQPQ
f                Find the first integer >= to 1 where the following is true
 f         PQ    Filter the prime factors of the input
        *TQ      Multiply the input by the outer integer
      .B         Convert to a binary string
   .BY           Convert the prime factor to a binary string
  }              Check whether the factor string is in the multiple string.

```

# Answer
> 6 votes
# 05AB1E, ~~18~~ ~~16~~ 15 bytes

*-2 bytes thanks to Riley!*

*-1 byte thanks to Emigna!*

```
[N¹*b¹Ñ¦¨båOiNq

```

Explanation:

```
[                   # Infinite loop start
 N                  # Push the amount of times we have iterated
  ¹*               # Multiplied by input
    b              # Convert to binary
     ¹Ñ¦¨b         # Calculate the proper divisors of the input in binary excluding one
          åO       # Check if a substring of N * m in binary is in the divisors
            iNq    # If so, print how many times we have iterated and terminate the program

```

Try it online!

# Answer
> 4 votes
# JavaScript (ES6), ~~96~~ ~~95~~ 80 bytes

```
n=>F=m=>(k=p=>p&&(q=1,g=x=>1<x&&x<n&n%x<1|g(x>>1,q*=2))(p)|k(p-q))(n*m)?m:F(-~m)

```

A function which returns a recursive function which uses a recursive function which uses a recursive function. I'm really starting to wonder if the `.toString(2)` route would be shorter...

Assign to a variable e.g. `f=n=>...` and call with an extra pair of parens, `f(9)()`. If that's not allowed (the meta post is at +6/-2), you can use this 83-byte version with standard invocation:

```
f=(n,m)=>(k=p=>p&&(q=1,g=x=>1<x&&x<n&n%x<1|g(x>>1,q*=2))(p)|k(p-q))(n*m)?m:f(n,-~m)

```

Both versions work for all but the last three test cases. You can try these test cases as well by changing `x>>1` to `(x-x%2)/2`.

# Answer
> 3 votes
# Bash \+ Unix utilities, ~~85~~ 84 bytes

```
for((;;m++)){ dc -e2o$[$1*m]n|egrep -q $(dc "-e2o`factor $1`nBEPn")&&break;}
echo $m

```

Try it online!

---

I'll point out also that m always exists for any semiprime n. Here's why:

Write n=pq, where p and q are prime and p \<= q.

Let b the number of digits in the binary representation of n-1. Then, for any k between 0 and n-1 inclusive, p\*(2^b)+k in binary consists of the binary representation of p followed by b additional bits representing k.

So the numbers p\*(2^b)+k for 0 \<= k \<= n-1, when written in binary, all start with the binary representation of p. But these are n consecutive numbers, so one of them must be a multiple of n.

It follows that we have a multiple mn of n whose binary representation starts with the binary representation of p.

Based on this, one can come up with an upper bound for m of 2 sqrt(n). (One can probably get a much tighter upper bound than this.)

# Answer
> 2 votes
## Haskell, 161 bytes

```
import Data.List
(!)=mod
a#b|a!b==0=b|0<1=a#(b+1)
g 0=[]
g n=g(n`div`2)++show(n!2)
(a%b)c|g b`isInfixOf`g(a*c)=c|0<1=a%b$c+1
f n=min(n%(n#2)$1)$n%(n`div`(n#2))$1

```

Straightforward check. Factor first, then search linearly starting at 1 and take the minimum of the value for both factors.

Takes a few seconds for the last testcase (`1468255967`), `ghci` reports `(15.34 secs, 18,610,214,160 bytes)` on my laptop.

# Answer
> 2 votes
## Mathematica, 83 bytes

```
1//.x_/;FreeQ[Fold[#+##&]/@Subsequences@IntegerDigits[x#,2],d_/;1<d<#&&d∣#]:>x+1&

```

# Answer
> 2 votes
# Brachylog (2), 14 bytes

```
ḋḃᵐD∧?:.×ḃs∈D∧

```

Try it online!

There's more than one way to write this in 14 bytes in Brachylog, so I went for the most efficient. As is common for Brachylog submissions, this is a function submission; its input is the semiprime, its output is the multiplier.

## Explanation

```
ḋḃᵐD∧?:.×ḃs∈D∧
ḋ               Prime decomposition (finds the two prime factors)
 ḃᵐ             Convert each factor to binary
   D            Name this value as D
    ∧?          Restart with the user input
      :.×       The output is something that can be multiplied by it
         ḃ      to produce a number which, when expressed in binary
          s     has a substring
           ∈D   that is an element of D
             ∧  (suppress an implicit constraint that D is the output; it isn't)

```

Prolog's and Brachylog's evaluation order is set by the first constraint that can't immediately be deduced from the input. In this program, that's a constraint on the result of a multiplication, so the interpreter will aim to keep the operands of the multiplication as close to 0 as possible. We know one of the operands, and the other is the output, so we find the smallest output we can, which is exactly what we want.

# Answer
> 1 votes
# PowerShell, 136 bytes

```
param($n)$a=2..($n-1)|?{!($n%$_)}|%{[convert]::ToString($_,2)};for(){$b=[convert]::toString(++$m*$n,2);if($a|?{$b-like"*$_*"}){$m;exit}}

```

Try it online!

Very lengthy due to how conversion-to-binary works in PowerShell. :-/

Takes input `$n`, loops through `2` to `$n-1` and pulls out the factors `!($n%$_)`. Sends those into a loop `|%{...}` and `convert`s each of them to a binary (base `2`) string. Stores those binary strings into `$a`.

Then we enter an infinite `for(){...}` loop. Each iteration, we increment `++$m`, multiply that by `$n`, and `convert` that to a binary string, stored into `$b`. Then, `if` that string is regex `-like` any strings in `$a`, we output `$m` and `exit`.

# Answer
> 0 votes
# Perl 6, 66 bytes

```
->\n{first {(n*$_).base(2)~~/@(grep(n%%*,2..^n)».base(2))/},^∞}

```

Regex-based.

Super slow, because it brute-forces the factors of *n* all over again at every regex match position of every number that is tried.

Calculating the factors only once, improves performance but makes it 72 bytes:

```
->\n{my @f=grep(n%%*,2..^n)».base(2);first {(n*$_).base(2)~~/@f/},^∞}

```

---
Tags: code-golf, primes, binary
---


title: Calculate Exponents bit by bit

text:
# Question
Title: Calculate Exponents bit by bit
Your task is to slowly calculate exponentiation, with the following steps:

Given two inputs (in this example, 4 and 8), you must calculate the exponentiation by calculate the equation bit by bit. You would do `4^8`, have a greater base value (4) and a smaller exponent (8). You can do this using more exponentiation and division. You can divide the exponent by a value *X* (provided *X* is a prime divisor of the exponent), and make the base value (*B*) into `B^X`. For example, you can do:

```
4^8 = (4 ^ 2)^(8 / 2) = 16^4

```

I have replaced *X* with 2 in the previous equation.

You can 'simplify' `16^4` further, again with `X = 2`:

```
16^4 = (16 ^ 2)^(4 / 2) = 256^2

```

And then finally calculate a number (again, `X = 2`):

```
256^2 = (256 ^ 2)^(2 / 2) = 65536^1 = 65536

```

Therefore,

```
4^8 = 16^4 = 256^2 = 65536

```

This is the output you should give. The output separator is a little flexible, for example, you can separate the equations by newlines or spaces instead of `=`. Or, you may put them into a list (but you mustn't use a digit or the `^` character as a separator).

As Martin Ender pointed out, the `^` is also flexible. For example, you may use `[A, B]` or `A**B` instead of `A^B` in the output.

*X* may only be prime, which means you cannot use `X = 8` to get straight to the solution, and the values of *X* will only be prime factors of the second input (the exponent).

### Examples:

```
(input) -> (output)
4^8 -> 4^8=16^4=256^2=65536
5^11 -> 5^11=48828125
2^15 -> 2^15=32^3=32768 (2^15=8^5=32768 is also a valid output)

```

Mind that the input format is also flexible (eg you may take `A \n B` or `A B` instead of `A^B`. Obviously, this wouldn't be a problem if you write a function taking two arguments.

In the second example, we go straight to calculation, since `11` is prime and we cannot take any more steps.

You may write a program or a function to solve this, and you may print or return the value, respectively.

As this is , that shortest code wins!

# Answer
> 2 votes
# Jelly, 16 bytes

```
*Uż:Ṫ
ÆfṪ1;×\ç@€

```

**Try it online!**

Input is a single list `[base, exponent]`. The return value of the lower monadic link is a list of lists, as a full program a representation of that list is printed, for example `2^15=8^5=32768^1` is printed as:

```
[[2, 15], [8, 5], [32768, 1]]

```

### How?

```
ÆfṪ1;×\ç@€ - Main link: [base, exponent]            e.g.     [4,12]
Æf         - prime factorization array (vectorises)      [[2,2],[2,2,3]]
  Ṫ        - tail (tailing first costs bytes)                   [2,2,3]
   1;      - 1 concatenated with the result                   [1,2,2,3]
     ×\    - reduce with multiplication  (make factors)       [1,2,4,12]
       ç@€ - call last link (1) as a dyad for €ach with reversed @rguments
           - implicit print if running as a full program

*Uż:Ṫ - Link 1, an entry in the equality: [base, exponent], factor  e.g. [4, 12], 4
*     - exponentiate (vectorises) : [base ^ factor, exponent ^ factor]   [256, 20736]
 U    - upend                                                            [20736, 256]
   :  - integer division: [base // factor, exponent // factor]           [1, 3]
  ż   - zip                                                        [[20736, 1], [256, 3]]
    Ṫ - tail                                                                    [256, 3]
                                               ...i.e at a factor of 4: 4 ^ 12 = 256 ^ 3

```

---

It could be formatted as a grid for 2 bytes by a trailing `µG`, e.g.:

```
    2    15
    8     5
32768     1

```

...or fully formatted, including trimming off the `^1`, for 9, with a trailing `j€”^j”=ṖṖ`, e.g.:

```
2^15=8^5=32768

```

# Answer
> 5 votes
# JavaScript (ES7), 55 bytes

```
f=(a,b,c=2)=>b>1?b%c?f(a,b,c+1):a+['^'+b,f(a**c,b/c)]:a

```

Uses `,` in place of `=` (`2^15,8^5,32768`).

### Test cases

```
f=(a,b,c=2)=>b>1?b%c?f(a,b,c+1):a+['^'+b,f(Math.pow(a,c),b/c)]:a
g=(a,b)=>console.log(`f(${a}, ${b}):`,f(a,b))

g(4,8)
g(5,11)
g(2,15)
```

Note: the snippet uses `Math.pow` instead of `**` for cross-browser compatibility.

# Answer
> 3 votes
# 05AB1E, ~~23~~ ~~22~~ 17 bytes

Saved 5 bytes by noticing the flexible output format.

```
Ò©gƒ²®N¹‚£P`Šm‚Rˆ

```

Try it online!

**Explanation**

Example for `2^15`

```
Ò©                 # calculate primefactors of exponent and store in register
                   # STACK: [3,5]
  g                # length
                   # STACK: 2
   ƒ               # for N in range[0 ... len(primefactors)] do
    ²              # push base
                   # STACK: 2
     ®             # push primefactors
                   # STACK: 2, [3,5]
      N¹‚£         # split into 2 parts where the first is N items long
                   # 1st, 2nd, 3rd iteration: [[], [3, 5]] / [[3], [5]] / [[3, 5], []]
          P        # reduce each by product
                   # STACK 1st iteration: 2, [1,15]
           `       # split list to items on stack
                   # STACK 1st iteration: 2, 1, 15
            Š      # move down the current exponent
                   # STACK 1st iteration: 15, 2, 1
             m     # raise base to the rest of the full exponent
                   # STACK 1st iteration: 15, 2
              ‚    # pair them up
                   # STACK 1st iteration: [15,2]
               R   # reverse the pair
                   # STACK 1st iteration: [2,15]
                ˆ  # store it in global list
                   # print global list at the end of execution

```

# Answer
> 2 votes
# C, ~~125~~ 123 + 4 (`-lm`) = ~~129~~ 127 bytes

```
i;f(n,m)double n;{if(m-1){printf("%.0f^%d=",n,m);for(i=2;i<=m;i++)if(!(m%i))return f(pow(n,i),m/i);}else printf("%.0f",n);}

```

Takes a double and an integer.

Try it online!

# Answer
> 1 votes
## Haskell, 64 bytes

```
a#b|v:_<-[x|x<-[2..b],mod b x<1]=[a,b]:(a^v)#div b v|1<2=[[a^b]]

```

Usage example: `2 # 32` -\> `[[2,32],[4,16],[16,8],[256,4],[65536,2],[4294967296]]`. Try it online!.

How it works:

```
a#b                       -- take input numbers a and b
   |                      -- if
      [x|x<-[2..b]   ]    --  the list of all x drawn from [2..b]
              ,mod b x<1  --  where x divides b
    v:_<-                 --  has at least one element (bind the first to v)
       = [a,b]:           --  the the result is the [a,b] followed by
          (a^v)#div b v   --  a recursive call with parameters (a^v) and (div b v)
   |1<2                   -- else (i.e. no divisors of b)
       = [[a^b]]          --  the result is the singleton list of a singleton list
                          --    of a^b

```

# Answer
> 0 votes
# Bash + GNU utilities, 82

```
echo $1^$2
f=`factor $2|egrep -o "\S+$"`
((m=$2/f,r=$1**f,m-1))&&$0 $r $m||echo $r

```

Recursive shell script. This doesn't seem to work in TIO, but runs fine when saved as a script and executed:

```
$ ./expbit2.sh 4 8
4^8
16^4
256^2
65536
$ ./expbit2.sh 5 11
5^11
48828125
$ ./expbit2.sh 2 15
2^15
32^3
32768
$

```

---
Tags: code-golf, sequence, arithmetic, number-theory, primes
---