title: Quine multiple times

text:
# Question
Title: Quine multiple times
Your task is make program that do following:

1. You should take number. (Positive, negative, fraction is possible input)
2. If it is negative, you reverse the quine. and negate that number (Become positive)
3. Then you repeat \<integer part of the input number\> times and print first \<floor(fraction part of the input number\*length)\> from your source program. If it is integer, then the fraction part is zero.

-10% bonus if your program isn't palindrome.

## Example

If your program is "ABCDEFG", then

1.

```
5
ABCDEFGABCDEFGABCDEFGABCDEFGABCDEFG

```

Explanation

> ABCDEFG five times

2.

```
-2
GFEDCBAGFEDCBA

```

Explanation

> GFEDCBA (reversed ABCDEFG) 2 times

3.

```
7.5
ABCDEFGABCDEFGABCDEFGABCDEFGABCDEFGABCDEFGABCDEFGABCDEFGABC

```

Explanation

> ABCDEFG 7 times followed by ABC (first 3(floor(0.5\*7)=floor(3.5)=3) letter on ABCDEFG)

4.

```
-0.3
GF

```

Explanation

> GFEDCBA (reversed ABCDEFG) 0 times followed by GF (first 2(floor(0.3\*7)=floor(2.1)=2) letter on GFEDCBA(reversed ABCDEFG))

5.

```
0
<empty>

```

Explanation:

> \<empty\> here means that your program doesn't output. It is ABCDEFG zero times that is defined as empty string.

# Answer
> 8 votes
## CJam, ~~28~~ 26 bytes * 0.9 = 23.4

Thanks to Sp3000 for saving 2 bytes.

```
{`"_~"+rd_z26*,\g1|@%f=}_~

```

Test it here.

### Explanation

```
{`"_~"+ e# Generalised quine framework. Leaves the source code on the stack.
  rd    e# Read input and parse as double.
  _z    e# Copy and get absolute value.
  26*   e# Multiply by 26, the length of the quine to get length N of the output.
  ,     e# Get a range [0 1 ... floor(N-1)].
  \g    e# Swap with other copy and computer signum to determine direction of string.
  1|    e# This might be zero though, so take bitwise OR with 1 to avoid an error.
  @%    e# Pull up source string. Reverse it if the signum was -1 (no-op otherwise).
  f=    e# The range we pushed earlier corresponds to the (cyclic) indices of the source
        e# which make up the desired result, so we map each index to the corresponding
        e# character to get the final result.
}_~

```

# Answer
> 5 votes
# Vitsy, 34 * 0.9 = 30.6 Bytes

Thanks to @Sp3000 for pointing out a flaw in my code!

Woo. My Physics teacher reminded me I had power functions to help me with this. Go figure.

```
'r(;Vd3*V2^12/^DvV/1+(rvl1-*\[DO{]
'                                   Start recording as a string - this grabs everything and pushes it to the stack as a string.
 r                                  Reverse the stack order.
  (;                                If the top item is zero, exit the program.
    V                               Grab the input as a final global variable.
     d3*                            Push the character ' to the stack.
        V2^12/^                     Get the absolute value of the input value.
               Dv                   Duplicate and save in a temp variable.
                 V                  Push the global variable to the stack.
                  /                 Divide the top two items - this gets -1 or 1 depending on the polarity of the input.
                   1+(              If it's -1, do the next instruction. Otherwise, don't.
                      r             Reverse the stack
                       v            Push the temporary variable to the stack.
                        l1-*        Multiply by the length of the stack minus 1.
                            \[   ]  Repeat everything in brackets top item of the stack times.
                              DO{   Duplicate an item, pop it off the stack and output it, then move one item over in the stack.

```

# Answer
> 2 votes
# Perl, 104 bytes - 10% = 93.6

```
perl -i-0.3 -e '$_=q{$_="\$_=q{$_};eval";$_=reverse if$^I<0;$n=abs$^I;print+($_ x$n).substr$_,0,y///c*($n-int$n)};eval'

```

102 bytes + 2 bytes for `-i` \- 10% for not being a palindrome. Input is passed as the argument to `-i` (e.g. `-0.3` above).

## How it works

This solution is based on the following quine:

```
$_=q{print"\$_=q{$_};eval"};eval

```

This works as follows. First, set `$_` to the string:

```
print"\$_=q{$_};eval"

```

Next, call `eval`, which works on `$_` by default. This calls `print` with one argument, a string literal:

```
"\$_=q{$_};eval"

```

Since this string is double-quoted, variables are interpolated. After interpolating `$_`, the value of the string is:

```
\$_=q{print"\$_=q{$_};eval"};eval

```

When printed, this outputs:

```
$_=q{print"\$_=q{$_};eval"};eval

```

which is the source code of the program itself.

The nice thing about this quine is that you can embed arbitrary code inside the string to be `eval`'d.

---

Here's a breakdown of the full solution:

```
perl -i-0.3 -e'
    $_=q{                     # string to be eval'd
        $_="\$_=q{$_};eval";  # append beginning and end of quine so the
                              #  entire thing can be reversed if necessary
        $_=reverse if $^I<0;  # reverse if input < 0
        $n=abs $^I;           # set $n to absolute value of input
        print                 # print
            +($_ x $n)        # $_ repeated $n times
            .                 # concatenated with
            substr $_,        # substring of $_
                   0,         # starting at the beginning
                   y///c      # having length x, where x is length of $_
                   *          # multiplied by
                   ($n-int$n) # fractional part of $n
    };
    eval                      # eval $_
'

```

# Answer
> 0 votes
# Mathematica, 139 - 10% = 125.1 bytes

```
StringJoin[Table[s = If[#1 > 0, #1 & , StringReverse][ToString[#0, InputForm]], {Abs[Floor[#1]]}], StringTake[s, Floor[Mod[#1, 1]*139]]] &

```

Note the trailing space. The whitespace, standard notation, etc. are the result of the `ToString[#0, InputForm]`.

# Answer
> 0 votes
## Haskell, 158 * 0.9 = 142.2 bytes

```
c i|i<0=reverse|1<2=id;f i=putStr$take(floor$abs i*158)$cycle$c i$s++show s;s="c i|i<0=reverse|1<2=id;f i=putStr$take(floor$abs i*158)$cycle$c i$s++show s;s="

```

A quine function.

```
*Main> f (-0.3)
"=s;s wohs++s$i c$elcyc$)851*i sba$roolf(ekat$r

*Main> f 1.1
c i|i<0=reverse|1<2=id;f i=putStr$take(floor$abs i*158)$cycle$c i$s++show s;s="c i|i<0=reverse|1<2=id;f i=putStr$take(floor$abs i*158)$cycle$c i$s++show s;s="c i|i<0=reverse

*Main> f 0
              <-- empty

```

# Answer
> 0 votes
# Python 2, 193 bytes - 10% = 173.7

```
x=input();y=int(x);_='x=input();y=int(x);_=%r;_=(_%%_)[::y/abs(y)];x,y=abs(x),abs(y);_=_*y+_[:int(y*(x-y)*193)];print _';_=(_%_)[::y/abs(y)];x,y=abs(x),abs(y);_=_*y+_[:int(y*(x-y)*193)];print _

```

Errors out on `0`, but, ignoring STDERR, you still get empty output.

---
Tags: code-golf, quine
---


title: A Rather Knotty Conundrum

text:
# Question
Title: A Rather Knotty Conundrum
Write a program to draw a 2-D diagram of a knot based on the knot's structure. A knot is exactly what it sounds like: a loop of rope that's tied up. In mathematics, a knot diagram shows where a piece of rope crosses over or under itself to form the knot. Some example knot diagrams are shown below:

There's a break in the line where the rope crosses over itself.

Input: the input describing the knot is an array of integers. A knot where the rope crosses over itself *n* times can be represented as an array of *n* integers, each with a value in the range \[0, n-1\]. Let's call this array *K*.

To get the array describing a knot, number each of the segments 0 through n-1. Segment 0 should lead to segment 1, which should lead to segment 2, which should lead to segment 3, and so on until segment n-1 loops back and leads to segment 0. A segment ends when another segment of rope crosses over it (represented by a break in the line in the diagram). Let's take the simplest knot - the trefoil knot. After we've numbered the segmnents, segment 0 ends when segment 2 crosses over it; segment 1 ends when segment 0 crosses over it; and segment 2 ends when segment 1 crosses over it. Thus, the array describing the knot is \[2, 0, 1\]. In general, segment *x* starts where segment *x-1 mod n* left off, and ends where segment *K\[x\]* crosses over it.

The below image show knot diagrams, with labeled segments and the corresponding arrays that describe the knot.

The top three diagrams are true knots, while the bottom three are loops of rope that cross over themself but aren't actually knotted (but which still have corresponding codes).

Your task is to write a function which takes an array of integers *K* (you could call it something different) that describes a knot (or loop of rope that's not actually knotted), and which produces the corresponding knot diagram, as described in the above examples. If you can, provide an ungolfed version of your code or an explanation, and also provide sample outputs of your code. The same knot can often be represented in multiple different ways, but if the knot diagram your function outputs satisfies has the input as one of it's possible representations, your solution is valid.

This is code-golf, so shortest code in bytes wins. The line representing the rope can have a thickness of 1 pixel, however under and over-crossings must be clearly distinguishable (the size of the break in the rope should be greater than the thickness of the rope by at least a pixel on either side).

I will upvote answers that rely on built-in knot theory capabilities, but the one that's selected in the end can't rely on built-in knot theory capabilities.

**Everything I know about my notation:** I believe that there are sequences of values that don't seem to correspond to any knot or unknot. For example, the sequence \[2, 3, 4, 0, 1\] seems to be impossible to draw.

Aside from that, suppose that you take a crossing and, starting from that crossing, follow the path of the rope in one direction and label every unlabeled crossing that you come across with succesively greater integral values. For alternating knots, there is a simple algorithm to convert my notation into such a labeling, and for alternating knots it's trivial to convert this labeling into a Gauss Code:

```
template<size_t n> array<int, 2*n> LabelAlternatingKnot(array<int, n> end_at)
{
    array<int, n> end_of;
    for(int i=0;i<n;++i) end_of[end_at[i]] = i;
    array<int, 2*n> p;
    for(int& i : p) i = -1;
    int unique = 0;
    for(int i=0;i<n;i++)
    {
        if(p[2*i] < 0)
        {
            p[2*i] = unique;
            p[2*end_of[i] + 1] = unique;
            ++unique;
        }
        if(p[2*i+1] < 0)
        {
            p[2*i+1] = unique;
            p[2*end_at[i]] = unique;
            ++unique;
        }
    }
    return p;
}
template<size_t n> auto GetGaussCode(array<int, n> end_at)
{
    auto crossings = LabelAlternatingKnot(end_at);
    for(int& i : crossings) ++i;
    for(int i=1;i<2*n;i+=2) crossings[i] = -crossings[i];
    return crossings;
}

```

# Answer
# GNU Prolog, ~~622~~ ~~634~~ 668 bytes in code page 850

**Update**: The previous version of the program was sometimes making crossings so tight that they wouldn't render properly, which violates the spec. I've added in some extra code to prevent that.

**Update**: Apparently PPCG rules require extra code to make the program exit and restore the state exactly as it was at the start. This makes the program somewhat longer and adds no algorithmic interest to it, but in the interests of rule compliance, I've changed it.

## Golfed program

Using GNU Prolog because it has a constraint solver syntax that's slightly shorter than portable Prolog's arithmetic syntax, saving a few bytes.

```
y(A,G):-A=1;A= -1;A=G;A is-G.
z(A/B,B,G):-y(A,G),y(B,G),A=\= -B.
v(D,E,G):-E=1,member(_-_,D),p(D);F#=E-1,nth(F,D,M),(M=[_];M=L-S/R,z(L,O,G),J is F+O,nth(J,D,I/U-T/Q),(I=O,Q#=R-1,S=T;K is J+O,R=0,n(S-T-V),y(U,G),U\=O,U=\= -O,I=U,nth(K,D,O/_-V/_))),v(D,F,G).
i([H|K],S):-K=[]->assertz(n(S-H-0));T#=S+1,assertz(n(S-H-T)),i(K,T).
t([],1,_):-!.
t(D,R,G):-S#=R-1,t(E,S,G),H#=G-1,length(F,H),append(F,[[x]|E],D).
s(1,2).
s(-1,1).
s(S,T):-S>1->T=3;T=0.
r(I/O-_,C):-s(I,J),s(O,P),N#=J*4+P+1,nth(N,"│┐┌?└─?┌┘?─┐?┘└│",C).
r([X],C):-X\=y->C=10;C=32.
p([]).
p([H|T]):-r(H,C),put_code(C),!,p(T).
g(4).
g(G):-g(H),G#=H+1.
m(K):-i(K,0),g(G),t(D,G,G),length(D,L),v(D,L,G),abolish(n/1).

```

## Algorithm

This is one of those problems where it's hard to know how to start. It's not obvious how to work out the shape of the knot from the notation given, because it doesn't let you know whether you're meant to bend the line to the left or the right at any given location (and as such, the notation might be ambiguous). My solution was, effectively, to use the old golfing standby: write an incredibly inefficient program which generates all possible outputs and then see if they match the input. (The algorithm used here is slightly more efficient, as Prolog can throw out the occasional dead end, but it doesn't have enough information to improve the computational complexity.)

The output is via terminal art. GNU Prolog seems to want a single byte character set that's consistent with ASCII, but doesn't care which one is used (as it treats characters with the high bit set as opaque). As a result, I used IBM850, which is widely supported and has the line drawing characters we need.

## Output

The program searches all possible knot images, in the order of the size of their bounding box, then exits when it finds the first. Here's what the output looks like for `m([0]).`:

```
 ┌┐
┌│┘
└┘

```

This took 290.528 seconds to run on my computer; the program isn't very efficient. I left it running for two hours on `m([0,1])`, and ended up with this:

```
┌┐┌┐
└─│┘
 └┘

```

## Ungolfed version with comments

Stack Exchange's syntax highlighter seems to have the wrong comment symbol for Prolog, so instead of `%` comments (which Prolog actually uses), this explanation uses `% #` comments (which are of course equivalent due to starting with `%`, but highlight correctly).

```
% # Representation of the drawing is: a list of:
% #     indelta/outdelta-segment/distance  (on path)
% # and [x] or [_]                         (off path; [x] for border).
% # A drawing is valid, and describes a knot, if the following apply
% # (where: d[X] is the Xth element of the drawing,
% #         k[S] is the Sth element of the input,
% #         n[S] is S + 1 modulo the number of sections):
% # d[X]=_/O-S-R, R>1 implies d[X+O]=O/_-S-(R-1)
% # d[X]=_/O-S-0 implies d[X+O]=_/_-k[S]-_
% #                  and d[X+O*2]=O/_-n[S]-_
% # all outdeltas are valid deltas (±1 row/column)

% # not technically necessary, but makes it possible to compile the
% # code (and thus makes the program faster to test):
:- dynamic([n/1]).

% # legal delta combinations:
y(A,G):-A=1;A= -1;              % # legal deltas are 1, -1,
        A=G;A is-G.             % # grid size, minus grid size
z(A/B,B,G):-y(A,G),y(B,G),      % # delta components are valid
            A=\= -B.            % # doesn't U-turn
% # z returns the outdelta for convenience (= byte savings) later on

% # We use v (verify) to verify the first E-1 elements of a drawing D.
% # nth is 1-indexed, so we recurse from length(D)+1 down to 2, with
% # 1 being the trivial base case. After verifying, the grid is printed.
% # This version of the program causes v to exit with success after
% # printing one grid (and uses p to do the work of deciding when that is).
v(D,E,G):-E=1,                  % # base case:
          member(_-_,D),        % # ensure the grid is nonempty
          p(D);                 % # print the grid (and exit)

                                % # otherwise, recursive case:
          F#=E-1,nth(F,D,M),    % # check the last unchecked element
          (
            M=[_];              % # either it's not on the path; or
            M=L-S/R,            % # it's structured correctly, and
            z(L,O,G),           % # it has a valid delta;
            J is F+O,           % # find the outdelta'd element index
            nth(J,D,I/U-T/Q),   % # and the outdelta'd element
            (
              I=O,Q#=R-1,S=T;   % # if not an endpoint, points to next pixel
              K is J+O,         % # else find segment beyond the path:
              R=0,              % # it's an endpoint,
              n(S-T-V),         % # it points to the correct segment,
              y(U,G),           % # ensure we can do NOT comparisons on U
              U\=O,U=\= -O,     % # the line we jump is at right angles
              I=U,              % # the line we jump is straight
              nth(K,D,O/_-V/_)  % # the pixel beyond has a correct indelta,
                                % # and it has the correct segment number
            )
          ),
          v(D,F,G).             % # recurse

% # We use i (init) to set up the k, n tables (k and n are fixed for
% # any run of the program, at least). S is the number of elements that
% # have been removed from K so far (initially 0). To save on characters,
% # we combine k and n into a single predicate n.
i([H|K],S):-K=[]->             % # if this is the last element,
            assertz(n(S-H-0)); % # section 0 comes after S;
            T#=S+1,            % # otherwise, add 1 to S,
            assertz(n(S-H-T)), % # that section comes after S,
            i(K,T).            % # and recurse.

% # We use t (template) to create a template drawing. First argument is
% # the drawing, second argument is the number of rows it has plus 1,
% # third argument is the number of columns it has plus 1.
t([],1,_):-!.
t(D,R,G):-S#=R-1,t(E,S,G),      % # recurse,
          H#=G-1,length(F,H),   % # F is most of this row of the grid
          append(F,[[x]|E],D).  % # form the grid with F + border + E

% # We use s (shrink) to map a coordinate into a value in the range 0, 1, 2, 3.
s(1,2).
s(-1,1).
s(S,T):-S>1->T=3;T=0.
% # We use r (representation) to map a grid cell to a character.
r(I/O-_,C):-s(I,J),s(O,P),N#=J*4+P+1,nth(N,"│┐┌?└─?┌┘?─┐?┘└│",C).
r([X],C):-X\=y->C=10;C=32.
% # We use p (print) to pretty-print a grid.
% # The base case allows us to exit after printing one knot.
p([]).
p([H|T]):-r(H,C),put_code(C),!,p(T).

% # We use g (gridsize) to generate grid sizes.
g(4).
g(G):-g(H),G#=H+1.

% # Main program.
m(K):-i(K,0),                  % # initialize n
      g(G),                    % # try all grid sizes
      t(D,G,G),                % # generate a square knot template, size G
      length(D,L),             % # find its length
      v(D,L,G),                % # verify and print one knot
      % # Technically, this doesn't verify the last element of L, but we know
      % # it's a border/newline, and thus can't be incorrect.
      abolish(n/1).            % # reset n for next run; required by PPCG rules

```
> 22 votes

---
Tags: code-golf, graphical-output, knot-theory
---


title: Kuznetsov's Sequence

text:
# Question
Title: Kuznetsov's Sequence
# Kuznetsov's Sequence

```
(I made the name up, don't bother with Wikipedia or Google)

```

Given any number `n > 0`, let `r` represent the reverse of the number `n`. Iterate until the final result is zero, passing the result of each iteration back into the function using recursion or a methodology of your choice by performing the below operation:

* If `r > n` for that iteration the result is `r % n`.
* If `n > r` for that iteration the result is `n % r`.
* If `n % r = 0` or `r % n = 0`, you terminate iteration.

Take the intermediate result of each execution and store them in an array for the final answer. The initial number `n` is not part of the sequence, nor is `0`; the examples should make everything a little more obvious.

Lets walk through an example where `n=32452345`.

```
54325423 % 32452345 = 21873078 # r > n, uses r % n
87037812 % 21873078 = 21418578 # r > n, uses r % n
87581412 % 21418578 = 1907100  # r > n, uses r % n
1907100 % 17091 = 9999         # n > r, uses n % r
9999 % 9999 = 0                # r % n = n % r = 0, terminated

Result: [21873078, 21418578, 1907100, 9999]

```

Another example `n=12345678`:

```
87654321 % 12345678 = 1234575 # r > n, uses r % n
5754321 % 1234575 = 816021    # r > n, uses r % n
816021 % 120618 = 92313       # n > r, uses n % r
92313 % 31329 = 29655         # n > r, uses n % r
55692 % 29655 = 26037         # r > n, uses r % n
73062 % 26037 = 20988         # r > n, uses r % n
88902 % 20988 = 4950          # r > n, uses r % n
4950 % 594 = 198              # n > r, uses n % r
891 % 198 = 99                # r > n, uses r % n
99 % 99 = 0                   # r % n = n % r = 0, terminated

Result: [1234575, 816021, 92313, 29655, 26037, 20988, 4950, 198, 99]

```

A final example `n=11000`:

```
11000 % 11 = 0 # n % r = 0, terminated

Result: []

```

This is lowest byte-count wins.

# Answer
# 05AB1E, 11 bytes

```
[Â‚{R`%Ð>#,

```

Uses the **CP-1252** encoding. Try it online!
> 4 votes

# Answer
## PowerShell v2+, 89 bytes

```
param($n)for(){$r=-join"$n"["$n".length..0];if(!($n=(($r%$n),($n%$r))[$n-gt$r])){exit}$n}

```

Iterative solution. Lengthy because there's no easy way to reverse an array, so we stringify it and index on it backwards to store into `$r`. Then a pseudo-ternary to pull out the appropriate modulo and re-store into `$n` for the next round. However, if the result is zero, that means the `!($n...)` will be `$true`, so we `exit` instead of `$n`. The numbers are left on the pipeline and (implicitly) returned as an array, but without an encapsulating pipeline or saving the results into a variable, the default `Write-Output` sticks a newline between.

Try it online! (Yes, dead serious.)
PowerShell is now on TIO! You gotta give it a second or two, because PowerShell is a beast to startup, but now you, yes *you*, can verify PowerShell code right in your browser!
> 6 votes

# Answer
# Perl, ~~43~~ 38 + 1 = 39 bytes

Run with the `-n` flag

```
say while$_=($;=reverse)>$_?$;%$_:$_%$

```

Try it online! Includes the two non-empty examples.

### Explanation chart

`-n`: Wraps the entire program in `while(<>){ ... ;}`. This turns the above code into the following line: `while(<>){say while$_=($;=reverse)>$_?$;%$_:$_%$;}`. Notice, a semicolon has been added to the trailing `$`, so it now becomes an instance of the variable `$;`. In the condition of a `while` loop, `<>` automatically reads one line of input and saves it in the `$_` variable. So now let's look at what the interpreter reads inside the outer `while` loop:

```
say while$_=($;=reverse)>$_?$;%$_:$_%$;
[op][mod][         condition          ]     #While is acting as a statement modifier.
                                            #It evaluates the operation as long as the condition is truthy.
            ($;=reverse)>$_?$;%$_:$_%$;     #The meat of the program: a ternary operation
            ($;=reverse)                    #The reverse function takes $_ as a parameter by default, and reverses the value.
                                            #The value returned by reverse is stored in the variable $;
                        >$_                 #A condition asking if $% is greater than $_.  Condition of the ternary operation
                           ?$;%$_           #If true, then return $; modulo $_
                                 :$_%$;     #If false, return $_ modulo $;
         $_=                                #Assign the result of the ternary operation back into $_
                                            #If $_ is non-zero, then the condition is true, and while will evaluate the operation
say                                         #Implicitly takes the $_ variable as parameter, and outputs its contents

```

### Original code, saved for posterity: 43 + 1 = 44 bytes

```
say$_=$%>$_?$%%$_:$_%$%while$_-($%=reverse)

```
> 6 votes

# Answer
# Pyth, ~~13~~ 12 bytes

```
t.u|%F_S,s_`

```

Thanks to @TheBikingViking.

Try it online: Demonstration

My old code:

```
W
W=Q%F_S,s_`

```

Try it online: Demonstration

### Explanation:

```
t.u|%F_S,s_`NNNQ  implicit Ns and Q at the end
               Q  start with N = Q (Q = input number)
        ,         create a pair with the numbers
         s_`N        convert N to string -> reverse-> convert to int
             N       and N
       S          sort
      _           reverse
    %F            fold by modulo
   |          N   or N (if the result is zero use N instead to stop)
 .u               apply this ^ procedure until a value repeats
                  print all intermediate values
 t                except the first one (the original number)

```
> 5 votes

# Answer
# Jelly, ~~15 14~~ 13 bytes

```
,ṚḌṢṚ%/
ÇÇÐ¿Ḋ

```

**TryItOnline**

### How?

```
,ṚḌṢṚ%/ - Link 1, iterative procedure: n
,       - pair n with
 Ṛ      - reverse n
  Ḍ     - undecimal (int of digit list)
   Ṣ    - sort
    Ṛ   - reverse
     %/ - reduce with mod

ÇÇÐ¿Ḋ - Main link: n
  Ð¿  - collect while
 Ç    - last link as a monad is truthy
Ç     -     last link as a monad
    Ḋ - dequeue (remove the input from the head of the resulting list)

```
> 4 votes

# Answer
# Jelly, ~~13~~ 12 bytes

```
,ṚḌṢṚ%/Ṅß$Ṡ¡

```

This is a monadic link/function that prints to STDOUT.

Try it online!

### How it works

```
,ṚḌṢṚ%/Ṅß$Ṡ¡  Monadic link. Argument: n

,Ṛ            Pair n and its reversed digit list.
  Ḍ           Convert the digit list into an integer.
   ṢṚ         Sort and reverse.
     %/       Reduce by modulo. Result: m
          Ṡ¡  Do sign(m) times:
       Ṅß$    Print with a newline and call the link recursively.

```
> 4 votes

# Answer
# Python 2, ~~92~~ ~~87~~ ~~81~~ ~~73~~ 61 bytes

Recursive solution:

```
def f(n):
    r=int(`n`[::-1]);x=min(r%n,n%r)
    if x:print x;f(x)

```

**Try it online**

Iterative solution: (also **61 bytes**)

```
n=input()
while n:r=int(`n`[::-1]);n=min(r%n,n%r);print n/n*n

```

**Try it online**
> 4 votes

# Answer
# MATL, 16 bytes

```
`tVPUhSPZ}\tt]xx

```

Try it online!

### Explanation

```
`         % Do...while
  t       %   Duplicate. Takes input implicitly in the first iteration
  VPU     %   Transform the number at the top of the stack by reversing its digits
  hSPZ}   %   Concatenate the two numbers into an array, sort, reverse, split the
          %   array: this moves the smaller number to the top
  \       %   Modulo
  t       %   Duplicate. The original copy is left on the stack for displaying,
          %   and the duplicate will be used for computing the next number
  t       %   Duplicate. This copy will be used as loop condition: exit if 0
]         % End
xx        % Delete the two zeros at the top. Implicitly display rest of the stack

```
> 3 votes

# Answer
# PHP, 78 bytes

```
function a($n){while(($r=strrev($n))&&($n=$r>$n?$r%$n:$n%$r)!=0){echo$n.' ';}}

```
> 2 votes

# Answer
## Batch, 140 bytes

```
@echo off
set/pn=
:l
set/am=n,l=0
:r
set/al=l*10+m%%10,m/=10
if %m% gtr 0 goto r
set/an=l%%n%%l+n%%l%%n
if %n% gtr 0 echo %n%&goto l

```

Takes input on STDIN and outputs the sequence on separate lines. Batch has conditional statements (which are somewhat verbose) but no conditional expressions so it's easier (despite having to quote the `%`s) to compute `r%n%r` (which is equal to `r%n` if `n<r` or zero if `n>r`) and `n%r%n` (which is equal to `n%r` if `n>r` or zero if `n<r`) and add them together.
> 2 votes

# Answer
## Mathematica, 68 bytes

Thanks to Greg Martin for suggesting I use `FixedPointList` rather than `NestWhileList`:

```
FixedPointList[Mod[(r=IntegerReverse@#)~Max~#,r~Min~#]&,#][[2;;-4]]&

```

The shortest I could get my original solution with `FixedPointList` was 73 bytes:

```
NestWhileList[Mod[(r=IntegerReverse@#)~Max~#,r~Min~#]&,#,#!=0&][[2;;-2]]&

```
> 2 votes

# Answer
# JavaScript, ~~72~~ 70 bytes

```
f=(s,...o)=>(u=s>(z=[...s+''].reverse().join``)?s%z:z%s)?f(u,...o,u):o

console.log(...[32452345, 12345678, 11000].map(x=>f(x)))
```

```
.as-console-wrapper{max-height:100%!important}
```

Edited:

**-2 bytes**: Spread operator waits string concatenation.
> 1 votes

# Answer
# R, ~~126~~ 117 bytes

```
x=scan();while(x){y=sort(c(x,as.double(paste(rev(el(strsplit(c(x,""),""))),collapse=""))));if(x<-y[2]%%y[1])print(x)}

```

Sadly, reversing a number (`as.double(paste(rev(el(strsplit(c(x,""),""))),collapse="")))`) is pretty wordy. Rest is pretty easy. Uses `sort` to indirectly check which is higher.

The rest is straightforward, it keeps looping until `x=0`, and prints all steps.
> 1 votes

# Answer
# C, 87 bytes

```
t;r;f(n){while(t=n){r=0;while(t)r=10*r+t%10,t/=10;n=r>n?r%n:n%r;if(n)printf("%d ",n);}}

```

`t` is temporary for reversing. The inner loop shifts `r` 1 digit to the left and adds the last digit of `t` until it is exhausted. Output is after the first iteration and only if it is non-zero to prevent the first and last item to be displayed.

Ungolfed and usage:

```
t;r;
f(n){
  while (t = n){
    r = 0;
    while (t)
      r = 10*r + t%10,
      t /= 10;
    n = r>n ? r%n : n%r;
    if(n)
      printf("%d ",n);
  }
}

```
> 1 votes

# Answer
# Mathematica, 64 bytes

```
NestWhileList[#2~If[#<=#2,Mod,#0]~#&[IntegerReverse@#,#]&,#,#>0&]&

```

The above code represents a pure function which takes a single input, and returns the kuznetsovs sequence. The really beautiful thing about mathematica is that you can put layer upon layer of pure functions... Allow me to explain the code ;)

Each term in the sequence itself is calculated with the below function, which takes one input and returns the next term.

```
#2~If[#<=#2,Mod,#0]~#&[IntegerReverse@#,#]&

```

The code `IntegerReverse@#` just generates r, the reversed value. The code `#2~If[#<=#2,Mod,#0]~#&` is a function that takes two inputs and either does the mod operation, or reverses the inputs and calls itself again. Another way of writing it is `If[#<=#2, Mod, #0][#2, #]&`, or it could be written as a regular function like this: `k[a_, b_] := If[a <= b, Mod, k][b, a]`
> 0 votes

# Answer
## Racket 180 bytes

```
(let p((n n)(ol'()))(let*((v reverse)(o modulo)
(r(string->number(list->string(v(string->list(number->string n))))))
(m(if(> n r)(o n r)(o r n))))(if(= m 0)(v ol)(p m(cons m ol)))))

```

Ungolfed:

```
(define (f n)
  (let loop ((n n)
             (ol '()))
    (let* ((r (string->number
               (list->string
                (reverse
                 (string->list
                  (number->string n))))))
           (m (if (> n r)
                  (modulo n r)
                  (modulo r n))))
      (if (= m 0)
          (reverse ol)
          (loop m (cons m ol))))))

```

Testing:

```
(f 32452345)
(f 12345678)

```

Ouput:

```
'(21873078 21418578 1907100 9999)
'(1234575 816021 92313 29655 26037 20988 4950 198 99)

```
> 0 votes

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


title: Golfed decimal fractions

text:
# Question
Title: Golfed decimal fractions
Your goal is to write some code that will output the shortest unique decimal sequence for the input fraction. No two fractions with the same denominator may have the same output, although it's possible for fractions with different denominators to have the same representation.

Take **2 integers** as input, the first is the numerator, the second is the denominator.

E.g.:

```
n  d   output
-----  ------
0 13:  0.00
1 13:  0.07
2 13:  0.1
3 13:  0.2
4 13:  0.30
5 13:  0.38

```

etc.

`3/13` is the only fraction with a denominator of 13 that starts with `0.2`, so no further digits are required. `4/13` and `5/13` both start with `0.3`, so another digit is required to distinguish between them.

You may output numbers greater than -1 and less than 1 either with or without a zero before the decimal point, as long as the output is consistent, i.e. `0.5` and `.5` are the same number and are both valid. No other leading zeros are allowed. Trailing zeros must be shown if they are necessary to distinguish the output from another value.

You may not round any numbers away from zero; they must be truncated. There must be no leading or trailing spaces. There may optionally be a single trailing newline.

More test values:

```
   n    d   output
----------  ------
   0    1:   0 (this 0 may not be removed because there's no decimal point)
   5    1:   5
   0    3:   0.0 (or .0)
   4    3:   1.3
   5    3:   1.6
  10    8:   1.2
  11    8:   1.3
  12    8:   1.5
-496  -38:  13.05
 458  -73:  -6.27
  70  106:   0.660 (or .660)
 255  123:   2.07
 256 -123:  -2.081
-257 -123:   2.089
-258  123:  -2.09
 258 -152:  -1.697
-259  152:  -1.70
 260  152:   1.710
 272  195:   1.39
 380  247:   1.538
 455 -455:  -1.000
 -44  891:  -0.049 (or -.049)
 123 1234:   0.099 (or .099)

```

In each case, the output and the denominator are sufficient to uniquely work out the numerator.

# Answer
# Perl, 77 bytes

```
#!perl -p
$%++while/ /<grep{!index$_/$',$\=$`/$'.($`%$'?0:n).0 x$%&'?'x$%}$`-2..$`+2}{

```

Counting the shebang as one, input is taken from stdin.

**Sample Usage**

```
$ echo 0 3 | perl golf-decimals.pl
0.0

$ echo 4 3 | perl golf-decimals.pl
1.3

$ echo 11 8 | perl golf-decimals.pl
1.3

$ echo -496 -38 | perl golf-decimals.pl
13.05

$ echo 458 -73 | perl golf-decimals.pl
-6.27

$ echo -44 891 | perl golf-decimals.pl
-0.049

```
> 1 votes

# Answer
# JavaScript (ES7), ~~118~~ ~~93~~ 90 bytes

```
f=(a,b,i=0)=>(v=(p=n=>((n/b*10**i|0)/10**i).toFixed(i))(a))==p(a+1)|v==p(a-1)?f(a,b,i+1):v

```

I saved 25 bytes, thanks to @Neil.
Saved additional 3 bytes by using recursion.
> 1 votes

# Answer
# Pyth, 37 bytes

```
AQJ+`cGHK*20\0<Jf!}<JTm<+`dKTcRH,tGhG

```

A program that takes input in the form `numerator,denominator` and prints the result.

Test suite

*\[Explanation coming later\]*
> 1 votes

---
Tags: code-golf, number, rational-numbers
---


title: Evaluate the Binomial Coefficient

text:
# Question
Title: Evaluate the Binomial Coefficient
Given two nonnegative integers `n,k` such that `0 <= k <= n`, return the binomial coefficient

```
c(n,k) := (n!) / (k! * (n-k)!)

```

### Test cases

Most languages will probably have a built in function.

```
c(n,0) = c(n,n) = 1 for all n
c(n,1) = c(n,n-1) = n for all n
c(5,3) = 10
c(13,5) = 1287

```

### Related challenges

Catalan Numbers Compute the multinomial coefficient Generate Pascal's triangle m-nomial coefficient

# Answer
> 5 votes
## JavaScript (ES6), 27 bytes

```
f=(n,k)=>k?n*f(n-1,k-1)/k:1

```

# Answer
> 5 votes
# MATL, 2 bytes

```
Xn

```

try it online!

# Answer
> 3 votes
# Jelly, 1 byte

```
c

```

Try it online!

# Answer
> 3 votes
## CJam, 11 bytes

```
l~S*\0e]e!,

```

Try it online!

### Explanation

This uses a trick that (I think) I first used for the Catalan numbers challenge. CJam doesn't have a built-in for this, and computing three factorials is too expensive. But the binomial coefficient `c(n,k)` is the number of ways we can select `k` out of `n` elements. That is, it's equal to the number of permutations of a list of `n` elements where `k` of them have one value and the remaining have another.

```
l~   e# Read and evaluate input. Dumping n and k on the stack.
S*   e# Get a string of k spaces.
\0e] e# Pad to length n with zeros.
e!   e# Get the unique permutations.
,    e# Count the number of such permutations.

```

# Answer
> 2 votes
# Matlab, 8 bytes

There is a builtin for this calculation:

```
nchoosek

```

# Answer
> 2 votes
# Haskell, ~~37~~ 35 bytes

```
n#0=1
0#k=1
n#k=(n-1)#(k-1)*n`div`k

```

# Answer
> 2 votes
# Mathematica, 8 bytes

```
Binomial

```

Yup. Sample usage: `Binomial[13,5]` or `13~Binomial~5` to obtain `1287`.

# Answer
> 2 votes
## Haskell, 34 bytes

```
n#k|k<1||k>=n=1|m<-n-1=m#(k-1)+m#k

```

Usage example: `13#5` -\> `1287`.

A variant with the same size for the `k<1||k>=n`test is `n*k-k*k<1`.

# Answer
> 2 votes
# J, 1 byte

```
!

```

### Usage:

```
   3!5
10
   5!13
1287

```

# Answer
> 1 votes
## Jellyfish, 6 bytes

```
pCi
 i

```

Try it online!

`C` is the built-in for binomial coefficients, the `i`s are replaced with one input each, `p` prints the result.

# Answer
> 1 votes
# Python 2, 33 bytes

```
f=lambda n,k:k<1or n*f(n-1,k-1)/k

```

Note that this will return *True* if **k = 0**, which seems to be allowed by default.

Try it online!

# Answer
> 1 votes
# Pyth, 3 bytes

```
.cF

```

A program that takes input in the form `n,k` and prints the result.

Test

**How it works**

This simply folds `c(n,k)` over the input.

# Answer
> 1 votes
# Actually, 1 byte

Input is of the form `k<newline>n`. Try it online!

# Answer
> 0 votes
# Perl 6, 23 bytes

```
{+combinations $^n,$^p}

```

```
{[*] ($^n...0)Z/1..$^p}

```

( Both are were based on code found at examples.perl6.org, and RosettaCode )

# Answer
> 0 votes
# MATL, 10 bytes

```
:i:&G-:h/p

```

Try it online!

This does the computation manually, without the builtin:

```
:     % Take input n implicitly. Range
      % STACK: [1 2 ... n]
i:    % Take input k. Range
      % STACK: [1 2 ... n], [1 2 ... k]
&G-   % Push n and k again. Subtract
      % STACK: [1 2 ... n], [1 2 ... k], n-k
:     % Range
      % STACK: [1 2 ... n], [1 2 ... k], [1 2 ... n-k]
h     % Concatenate the top two arrays horizontally
      % STACK: [1 2 ... n], [1 2 ... k 1 2 ... n-k]
/     % Element-wise division
      % STACK: [1/1 2/2 ... k/k (k+1)/1 (k+2)2 ... n/(n-k)]
p     % Product of array. Implicitly display
      % STACK: 1/1 * 2/2 * ... * k/k * (k+1)/1 * (k+2)2 * ... * n/(n-k)

```

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


title: Change the Timezone

text:
# Question
Title: Change the Timezone
## Challenge

Given a time and a timezone as input, output the time in that timezone.

## Time

The time will be given in 24 hour format like so:

```
hh:mm

```

Where hh is the two digit hour and mm is the two digit minute. Note that the hour and the minute will always be padded with zeroes like so:

```
06:09

```

All the times given are at UTC+00:00.

*The hours in your output do not have to be padded wih zeroes but your time it must be in 24 hour format*

## Timezone

The timezone will be given in the following format:

```
UTC±hh:mm

```

Where ± is either going to be a + or a - and hh, is the two digit hour and mm is the two digit minute (again, these will be padded with zeroes).

To find the time in that timezone, you either add (if the symbol is +) or subtract (if the symbol is -) the time after the UTC± from the inputted time.

For example, if the input was `24:56` and `UTC-02:50`, you would subtract 2 hours and 50 minutes from 24:56:

```
24:56
02:50 -
-----
22:06

```

The output would be `22:06`.

## Examples

### Chicago

```
Input:  08:50 and UTC-06:00
Output: 02:50

```

### Kathmandu

```
Input:  09:42 and UTC+05:45
Output: 15:27

```

### Samoa

```
Input:  06:42 and UTC+13:00
Output: 19:42

```

### Hawaii

```
Input:  02:40 and UTC-10:00
Output: 16:40

```

Note that this has gone to the previous day.

### Tokyo

```
Input:  17:25 and UTC+09:00
Output: 02:25

```

Note that this has gone to the following day.

## Rules

You must not use any built in date functions or libraries.

Assume all input will be valid times and time offsets.

The timezone will be in the range `UTC-24:00` to `UTC+24:00` inclusive.

In the case of *half past midnight*, the correct representation should be `00:30`, ***not*** `24:30`.

## Winning

The shortest code in bytes wins.

# Answer
> 3 votes
# APL (Dyalog APL), 45 bytes

### Expression

Takes two strings as right argument.

```
24 60⊤∘⍎∘⍕('+-'∩⍕),'/',(0 60⊥2⊃':'⎕VFI ¯5∘↑)¨

```

Try it online!

### Explanation

`24 60⊤` the number-to-base-*a*24*b*60 conversion

of

the evaluation

of

the formatted (i.e. flattened with separating spaces)

`('+-'∩⍕)` intersection of "+-" and the formatted input (this extracts the plus or minus)

`,` followed by

`(`... the following for each of the inputs (the time and the offset)

`0 60⊥` the *a**b*60-to-number conversion of

`2⊃` the second element of

`':'⎕VFI`  the, using colon as field separator, **V**erified and **F**ixed **I**nput of

`¯5∘↑` the last five characters ("hh:mm")

### Step-by-step on "17:25" and "UTC+09:00"

The left-side expression on the right side data, gives the data of the next line.

```
                       '17:25' 'UTC+09:00'
                      /     /   \         \
(...)¨ applies the function train to both inputs
                    /     /       \         \
¯5∘↑               '17:25'         'UTC+09:00'
':'⎕VFI            '17:25'         '09:00'
2⊃            (1 1)(17 25)         (1 1)(9 0)
0 60⊥                17 25         9 0
                      1045         540
                       \  \       / /
This is where ¨ stops, and execution continues on the resulting list
                         \  \   / /
'/',                      1045 540
('+-'∩⍕),             '/' 1045 540
⍕                 '+' '/' 1045 540
⍎                   '+ / 1045 540'
24 60⊤                        1585
                              2 25

```

# Answer
> 3 votes
# C, 109 bytes

```
a,b,c;f(char*t,char*z){for(c=0;z[3];t=z+=3)sscanf(t,"%d:%d",&a,&b),c+=b+a*60;printf("%d:%02d",c/60%24,c%60);}

```

Invoke as follows:

```
int main() { f("17:25", "UTC+09:00"); }

```

# Answer
> 3 votes
## JavaScript (ES6), 101 bytes

```
(t,z,g=s=>+(s[3]+s[7]+s[8])+s.slice(3,6)*60,m=g('UTC+'+t)+g(z)+1440)=>(m/60%24|0)+':'+(m/10%6|0)+m%10

```

Would be 121 bytes if I padded the hours.

# Answer
> 3 votes
# Python 2, 129 bytes

```
def T(t,a):f=[int.__add__,int.__sub__]["-"in a];m=f(int(t[3:5]),int(a[7:9]));print`f(int(t[0:2])+m/60,int(a[4:6]))%24`+":"+`m%60`

```

Call as `T("02:45", "UTC-05:33")`

# Answer
> 2 votes
# Python 2, 84 bytes

```
def f(t,z):i=int;r=60*(i(t[:2])+i(z[3:6]))+i(t[3:])+i(z[3]+z[7:]);print r/60%24,r%60

```

All test cases are at **ideone**

Output format is space separated, with no leading zeros.

# Answer
> 2 votes
# Java 201 bytes

```
String T(String t,String z){return(24+Integer.valueOf(t.substring(0,2))+Integer.valueOf((String)z.subSequence(3,6)))%24+":"+(60+Integer.valueOf(t.substring(3,5))+Integer.valueOf(z.substring(7,9)))%60;}

```

Called as T("12:00", "UTC+02:40")

Unglolfed for the logic,

```
String T(String t, String z) {
    int i = (24 + Integer.valueOf(t.substring(0, 2)) + Integer.valueOf((String) z.subSequence(3, 6))) % 24;
    int j = (60 + Integer.valueOf(t.substring(3, 5)) + Integer.valueOf(z.substring(7, 9))) % 60;
    return i + ":" + j;
}

```

Any help to get it under 200 would be appreciated!

# Answer
> 2 votes
## Javascript (ES6), ~~93~~ 92 bytes

```
t=>((t=eval(t.replace(/.*?(.)?(..):(..)/g,'$1($2*60+$3)+720')))/60%24|0)+':'+(t/10%6|0)+t%10

```

### Test cases

```
let f =
t=>((t=eval(t.replace(/.*?(.)?(..):(..)/g,'$1($2*60+$3)+720')))/60%24|0)+':'+(t/10%6|0)+t%10

console.log(f("08:50 UTC-06:00")); //  2:50
console.log(f("09:42 UTC+05:45")); // 15:27
console.log(f("06:42 UTC+13:00")); // 19:42
console.log(f("02:40 UTC-10:00")); // 16:40
console.log(f("17:25 UTC+09:00")); //  2:25
```

# Answer
> 1 votes
## Ruby, 95 bytes

```
g=->s{"60*"+s.scan(/\d+/).map(&:to_i)*?+}
f=->t,z{r=eval(g[t]+z[3]+g[z]);print r/60%24,?:,r%60}

```

## Usage

```
f[gets,gets]

```

### Inputs(example)

```
08:50
UTC-06:00

```

# Answer
> 0 votes
# C# 214 205 183 Bytes

```
string f(char[]t,char[]u){int s=~(u[3]-45),z=48,m=(t[3]-z)*10+t[4]-z+((u[7]-z)*10+u[8]-z)*s,h=(t[0]-z)*10+t[1]-z+((u[4]-z)*10+u[5]-z)*s+m/60+(m>>8)+24;return$"{h%24}:{(m+60)%60:D2}";}

```

205 byte version

```
string f(string t,string u){Func<string,int>P=int.Parse;var T=t.Split(':');int s=u[3]<45?1:-1,m=P(T[1])+P(u.Substring(7))*s,h=P(T[0])+P($"{u[4]}"+u[5])*s+m/60+(m<0?-1:0)+24;return$"{h%24}:{(m+60)%60:D2}";}

```

Ungolfed

```
string f(char[] t, char[] u)
{
    int s = ~(u[3]-45),
        z = 48,
        m = (t[3] - z) * 10 + t[4] - z + ((u[7] - z) * 10 + u[8] - z) * s,
        h = (t[0] - z) * 10 + t[1] - z + ((u[4] - z) * 10 + u[5] - z) * s + m / 60 + (m>>8) + 24;
    return $"{h % 24}:{(m + 60) % 60:D2}";
}

```

Original 214:

```
string f(string t,string u){Func<string,int>P=int.Parse;var T=t.Split(':');int h=P(T[0]),m=P(T[1]),s=u[3]<45?1:-1;m+=P(u.Substring(7))*s;h+=P($"{u[4]}"+u[5])*s+m/60+(m<0?-1:0)+24;return$"{h%24:D2}:{(m+60)%60:D2}";}

```

# Answer
> 0 votes
# Java ~~156~~ ~~150~~ ~~149~~ ~~147~~ 142 bytes

```
t->z->{Integer H=100,T=H.valueOf(t.replace(":","")),Z=H.valueOf(z.replace(":","").substring(3)),c=(T/H+Z/H+24)*60+T%H+Z%H;return c/60%24+":"+c%60;}

```

## Test cases & ungolfed

```
import java.util.function.BiFunction;

public class Main {
    public static void main(String[] args) {

        BiFunction<String,String,String> f = (t,z)->{
            Integer H = 100, // Hundred, used several times, shorter as variable
                    T = H.valueOf(t.replace(":","")), // as int (HHMM)
                    Z = H.valueOf(z.replaceAll("[UTC:]","")), // as int (-HHMM)
                    c = (T/H + Z/H + 24) * 60 + T%H + Z%H; // transform into minutes
            return c/60%24+":"+c%60;
        };

        test(f, "08:50", "UTC-06:00", "02:50");
        test(f, "09:42", "UTC+05:45", "15:27");
        test(f, "03:42", "UTC-05:45", "21:57");
        test(f, "06:42", "UTC+13:00", "19:42");
        test(f, "02:40", "UTC-10:00", "16:40");
        test(f, "17:25", "UTC+09:00", "02:25");
    }

    private static void test(BiFunction<String,String,String> f, String time, String zone, String expected) {
        // Padding is allowed. Make sure the padding is skipped for the test, then.
        String result = String.format("%2s:%2s", (Object[])f.apply(time, zone).split(":")).replace(" ","0");
        if (result.equals(expected)) {
            System.out.printf("%s + %s: OK%n", time, zone);
        } else {
            System.out.printf("%s + %s: Expected \"%s\", got \"%s\"%n", time, zone, expected, result);
        }

    }
}

```

## Shavings

* 150 -\> 149: `a/H*60+b/H*60` -\> `(a/H+b/H)*60`
* 149 -\> 147: `(T/H+Z/H)*60+1440` -\> `(T/H+Z/H+24)*60`.
* 147 -\> 142: `z.replace(":","").substring(3)` -\> `z.replaceAll("[UTC:]","")`

# Answer
> 0 votes
## CJam, 40 bytes

```
r{':/60b}:F~r3>(\F\~1440,=60b{s2Te[}%':*

```

Try it online! (As a test suite.)

### Explanation

```
r           e# Read first input (time).
{':/60b}:F  e# Define a function F, which splits a string around ':' and
            e# treats the two elements as base-60 digits.
~           e# Run that function on the first input.
r3>         e# Read the second input and discard the 'UTC'.
(           e# Pull off the +-.
\F          e# Apply F to the timezone offset.
\~          e# Execute the + or - on the two amounts of minutes.
1440,=      e# Modulo 1440 to fit everything into the 24-hour format.
60b         e# Obtain base 60 digits again.
{s2Te[}%    e# Convert each digit to a string and pad it to 2 decimal digits.
':*         e# Join them with a ':'.

```

# Answer
> 0 votes
## Retina, 100 bytes

```
:
59$*:,
+`(\d+):
$1,$1
\d+
$*
T`1`0`-.+
^
1440$*
+`10|\D

1{1440}

^(1{60})*(.*)
$#1:$.2
\b\d\b
0$&

```

Try it online!

### Explanation

```
:
59$*:,

```

Replaces each `:` with 59 of them and a comma as a separator.

```
+`(\d+):
$1,$1

```

Repeatedly duplicates the number in front of a `:`. So the first two stages multiply the hour-value by 60.

```
\d+
$*

```

Convert each number to unary.

```
T`1`0`-.+

```

If there's a minus sign in the input, then this transliteration stage turns all the `1`s after it into `0`s. We're basically using `0` as a unary `-1` digit here.

```
^
1440$*

```

Insert 1440 `1`s (i.e. a full day). This is to ensure that the time doesn't get negative.

```
+`10|\D

```

This repeatedly removes all non-digits (i.e. the space, the `UTC`, the `+` or `-`, as well as all the `,` we've inserted) and the `10` combination, thereby cancelling positive and negative digits. This basically subtracts the second number from the first if it's negative, or adds it otherwise.

```
1{1440}

```

Removes 1440 `1`s if possible (basically taking the result modulo 1440 to fit it into a single 24 hours).

```
^(1{60})*(.*)
$#1:$.2

```

Decompose the number into hours and minutes by matching as many chunks of 60 digits as possible (counting the chunks with `$#1`) followed by the remaining digits (whose length is counted with `$.2`).

```
\b\d\b
0$&

```

If there are any single digits in the result, prepend a zero.

---
Tags: code-golf, date
---


title: Sum digits till Square

text:
# Question
Title: Sum digits till Square
Given is any integer x \> 0 and any base y \> 3.

1. Sum all digits of x (if written in the set base).
2. Multiply this by the highest possible digit (is always `base -1`).
3. Repeat until this value is `(y - 1) ^ 2`

Searched is the count of iterations and the steps.

Example 1:

```
x= 739
y= 7
searched: (7 - 1) ^ 2 = 36

based: (b7)2104
sum: (dec)7
mul: (dec)42

based: (b7)60
sum: (dec)6
mul: (dec)36

2 steps needed -> answer is [2, 739, 42, 36] or [739, 42, 36, 2]

```

Example 2:

```
x = 1712
y = 19
s: 324

step1: 1712 -> 360
step2:  360 -> 648
step3:  648 -> 324

3 steps needed -> answer is [3, 1712, 360, 648, 324] or [1712, 360, 648, 324, 3]

```

Special:
In some cases (some combinations with a base of 3) you will not be able to get to `(y - 1) ^ 2` like for `x = 53` and `y = 3`. For this reason `y` needs to be bigger than 3 and you can ignore this.

The count of iterations need to be the first or the last value

This is lowest byte-count wins.

# Answer
> 4 votes
# Jelly, ~~14~~ 13 bytes

-1 byte by printing as it loops ( replacing a chain separation, `µ` and concatenation `;`)

```
Ṅb⁹S×⁹’¤µÐĿL’

```

**TryItOnline!**

### How?

```
Ṅb⁹S×⁹’¤µÐĿL’ - Main link: x, y
        µÐĿ   - loop monadically until results are no longer unique and collect
Ṅ             - print z (initially x), then result of previous loop and return z
  ⁹           -     right argument (y, even though monadic)
 b            -     left to base right
   S          -     sum (the result was a list of base y digits)
       ¤      -     nilad followed by link(s) as a nilad
     ⁹’       -         y decremented
    ×         -     multiply
           L  - length(z)
            ’ - decrement
              - implicit print

```

The alternative 13 byter prints each input to the loop plus a line feed (), and finally implicitly prints the decremented count of the collected results, removing the need for a monadic chain separation (`µ`) and concatenation (`;`).

# Answer
> 4 votes
# Perl 6, 60 bytes

```
{$/=[$^x,*.polymod($^y xx*).sum*($y-1)...($y-1)²];$/-1,|$/}

```

## Expanded:

```
{    # bare block lambda with placeholder parameters ｢$x｣ ｢$y｣

  $/ = [          # store in ｢$/｣ ( so that we don't have to declare it )

    # generate a sequence

    $^x,          # declare first parameter, and seed sequence generator

    # Whatever lambda

    *\            # the parameter to this lambda

    .polymod(     # broken down with a list of moduli

      $^y         # declare second parameter of the outer block lambda
      xx *        # an infinite list of copies of it

    )
    .sum
    *
    ( $y - 1 )

    # end of Whatever lambda

    ...           # repeat until it reaches

    ( $y - 1 )²
  ];

  # returns
  $/ - 1,         # count of values minus one
  |$/             # Slip ｢|｣ the list into the result
}

```

## Usage:

```
# store it in the lexical namespace so that it is easier to understand
my &code = {$/=[$^x,*.polymod($^y xx*).sum*($y-1)...($y-1)²];$/-1,|$/}

say code  739,  7; # (2 739 42 36)
say code 1712, 19; # (3 1712 360 648 324)

```

# Answer
> 4 votes
# C, ~~116~~ 113 bytes

-3 bytes for recalculating square each time

```
s,t,i;f(x,y){s=y-(i=1);while(x-s*s){t=0;++i;printf("%d ",x);while(x)t+=x%y,x/=y;x=t*y-t;}printf("%d %d ",x,i-1);}

```

Ungolfed and usage:

```
s,t,i;
f(x,y){
 s=y-(i=1);
 while(x-s*s){
  t=0;
  ++i;
  printf("%d ",x);
  while(x)
   t+=x%y,    //add the base y digit
   x/=y;      //shift x to the right by base y
  x=t*y-t;
 }
 printf("%d %d ",x,i-1);
}

main(){
 f(739,7);puts("");
 f(1712,19);puts("");
}

```

# Answer
> 4 votes
## JavaScript (ES6), ~~97~~ ~~91~~ ~~84~~ 82 bytes

```
f=(n,b,k=1,c=b-1)=>[n,(s=(B=n=>n%b*c+(n>b&&B(n/b|0)))(n))-c*c?f(s,b,k+1):[s,k]]+''

```

### Test cases

```
f=(n,b,k=1,c=b-1)=>[n,(s=(B=n=>n%b*c+(n>b&&B(n/b|0)))(n))-c*c?f(s,b,k+1):[s,k]]+''

console.log(f(1712, 19))
console.log(f(739, 7))
```

# Answer
> 4 votes
# Jelly, 16 bytes

I guess I'll post this anyway, even though it was beaten while I was writing it, because it's a notably different algorithm and it was interesting to write. (I couldn't figure out how `ÐĿ` parsed from the docs and had to give up on it, despite knowing it would probably lead to a shorter solution than this one.)

```
ṄbS×⁹’¤ß<’¥n⁸$?‘

```

Try it online!

Explanation:

```
ṄbS×⁹’¤ß<’¥n⁸$?‘
Ṅ                 Output {the first argument} and a newline
 b                Convert to base {the second argument}
  S               Sum digits
    ⁹’¤           {the second argument} minus 1, parsed as a group
   ×              Multiply
           n⁸$    {the current value} ≠ {the first argument}, parsed as a group
              ?   If that's true:
       ß          then run the whole program recursively
        <’¥       else run (lambda a,b: (a<b)-1)
               ‘  Increment the result

```

The use of `<’¥` is basically a short way to write a dyad (link with two arguments) that always returns -1 (because we know the answer will never be smaller than the base). Choosing between running that recursively, and the whole program recursively, lets us determine when to stop looping. Then when the stack unwinds at the end of the recursion, we keep incrementing the -1 to determine how many steps there were.

# Answer
> 2 votes
# MATL, ~~25~~ 21 bytes

*4 bytes saved thanks to @Luis*

```
XJx`tJYA!UsJq*tJqU-}@

```

**Try it Online!**

**Explanation**

```
XJ      % Implicitly grab the first input and store in clipboard J
x       % Delete this from the stack
`       % Do...while loop
  t     % Duplicate last element on stack (implicitly grabs second input)
  JYA   % Convert this number to the specified base
  !Us   % Sum the digits
  Jq*   % Multiply by the largest number in this base
  t     % Duplicate this value
  JqU   % Compute (base - 1) ^ 2
  -     % Subtract the two. Evaluates to TRUE if they are not equal
}       % When they are finally equal
@       % Push the number of iterations
        % Implicitly display the stack contents

```

# Answer
> 1 votes
## Mathematica, 80 bytes

```
(s=FixedPointList[x(#2-1)(Plus@@x~IntegerDigits~#2),#];s[[-1]]=Length@s-2;s)&

```

is the private use character `U+F4A1` used to represent `\[Function]`. If the number of steps weren't required in the answer, this could be done in 60 bytes:

```
Most@FixedPointList[x(#2-1)(Plus@@x~IntegerDigits~#2),#]&

```

---
Tags: code-golf, combinatorics, base-conversion
---


title: Optimize ASCII test-tubes

text:
# Question
Title: Optimize ASCII test-tubes
You are given a bunch of ASCII test-tubes, your task is to reduce number of test-tubes used.

Each test tube looks like this:

```
|  |
|  |
|  |
|~~|
|  |
|  |
|  |
|  |
|__|

```

Obviously, `~~` is the water level. Test-tube can be also empty, in which case there are no `~~` characters inside. Single tube can contain up to 8 water level units.

You are given finite number of test tubes with different water levels inside. You have to pour the water in least amount of test-tubes possible, and output the result.

```
|  | |  | |  | |  |         |~~| |  |
|  | |  | |  | |  |         |  | |  |
|  | |~~| |  | |  |         |  | |  |
|~~| |  | |  | |  |         |  | |~~|
|  | |  | |  | |  | ------> |  | |  |
|  | |  | |  | |  |         |  | |  |
|  | |  | |~~| |  |         |  | |  |
|  | |  | |  | |  |         |  | |  |
|__| |__| |__| |__|         |__| |__|

 05 + 06 + 02 + 00  ------>  08 + 05

```

As you can see, test-tubes are separated with single space. Empty tubes should not be shown in output. This is code golf, so code with least number of bytes wins.

Test cases: http://pastebin.com/BC0C0uii

Happy golfing!

# Answer
# Pyth, ~~48~~ ~~45~~ 44 bytes

```
jCssm+_B,*9\|_X+\_*8;ld\~*9;cUs*L/%2w\~_S8 8

```

Try it online.

Prints a single trailing space on every line.
> 4 votes

# Answer
## JavaScript (ES6), ~~159~~ 148 bytes

```
s=>s.replace(/~~|\n/g,c=>1/c?i++:n+=7-i,n=i=-1)&&`012345678`.replace(/./g,i=>`|${g(+i)}| `.repeat(n>>3)+`|${g(~n&7^i)}|
`,g=i=>i?i>7?`__`:`  `:`~~`)

```

Outputs a trailing linefeed. Edit: Saved 11 bytes with some help from @Arnauld.
> 4 votes

# Answer
## Perl, 150 bytes

149 bytes of code + `-n` flag.

```
$l+=9-$.for/~~/g}if($l){$%=($v=$l/8)+($r=$l!=8);say"|~~| "x$v.($@="|  | ")x$r;say$:=$@x$%for$l%8..6;say$@x$v."|~~|"x$r;say$:for 2..$l%8;say"|__| "x$%

```

I won't explain all the code, just a few things:
`$l+=9-$.for/~~/g` counts how much water the is in the input.
The second part of the code prints the output. The idea is to put as many fully filled tubes as possible, and a last one which contains the water that is left (if any). So the algorithm is in 4 parts: prints the first line of water (the top of tubes): `say"|~~| "x$v.($@="| | ")x$r`. Then, print empty parts of tubes until we reach the level of water of the last tube: `say$:=$@x$%for$l%8..6`. Then print the level where the last tube water is: `say$@x$v."|~~|"x$r`. Then, print all the remaining "empty" levels: `say$:for 2..$l%8;`. And finally, print the bottom line: `say"|__| "x$%`.
The variable names make it hard to read (`$%`, `$@`, `$:`) but allows for keywords like `x` and `for` to be written after the variable without a space.

To run it:

```
perl -nE '$l+=9-$.for/~~/g}if($l){$%=($v=$l/8)+($r=$l!=8);say"|~~| "x$v.($@="|  | ")x$r;say$:=$@x$%for$l%8..6;say$@x$v."|~~|"x$r;say$:for 2..$l%8;say"|__| "x$%' <<< "|  | |  | |  | |  |
|  | |  | |  | |  |
|  | |~~| |  | |  |
|~~| |  | |  | |  |
|  | |  | |  | |  |
|  | |  | |  | |  |
|  | |  | |~~| |  |
|  | |  | |  | |  |
|__| |__| |__| |__| "

```

I'm not very satisfied with how long this answer is. I tried to make the best out of my algorithm, but a different approach could probably be shorter. I'll try to work on it soon.
> 3 votes

# Answer
# Befunge, ~~144~~ 138 bytes

```
9>1-00p>~$~2/2%00gv
 |:g00_^#%4~$~$~+*<
$< v01!-g01+*8!!\*!\g00::-1</8+7:<p01-1<9p00+1%8-1:_@#:
_ ~>g!-1+3g:"|",,," |",,:>#^_$55+,10g:#^_@

```

Try it online!

The first two lines process the input, basically ignoring everything except the first character in each tube that might be a level marker. We take the ASCII value of that character, divide by 2 and mod 2 (giving us 1 or 0 depending on whether we're on a level marker or not), multiply that by the row number (counting down from 8, thus giving us the level value for that tube), and add it to a running total.

The output is handled on the second two lines, essentially starting on the far right of the third line. We first calculate the number of tubes by taking the total water level plus 7 divided by 8. Then when iterating over the rows of all the tubes, we calculate the character to display inside a specific tube (*t*, counting down to 0) for a given row (*r*, counting down from 8 to 0) as follows:

```
last_level = (total_water - 1)%8 + 1
level      = last_level*!t + 8*!!t
char_type  = !(level - r) - !r

```

The calculated *char\_type* is -1 for the bottommost row (the base of the tube), 0 for a any other area that isn't a water level, and 1 for the water level. It can thus be used as simple table lookup for the appropriate character to output (you can see this table at the start of line 4).
> 3 votes

# Answer
## Haskell, 186 bytes

```
import Data.Lists
z=[8,7..0]
f x|s<-sum[i*length j-i|(i,j)<-zip z$splitOn"~~"<$>lines x],s>0=unlines$(\i->(#i)=<<(min 8<$>[s,s-8..1]))<$>z|1<2=""
l#i|i==l="|~~| "|i<1="|__| "|1<2="|  | "

```

Usage example:

```
*Main> putStr $ f "|  | |  | |  | |  |\n|  | |  | |  | |  |\n|  | |~~| |  | |  |\n|~~| |  | |  | |  |\n|  | |  | |  | |  |\n|  | |  | |  | |  |\n|  | |  | |~~| |  |\n|  | |  | |  | |  |\n|__| |__| |__| |__|"
|~~| |  |
|  | |  |
|  | |  |
|  | |~~|
|  | |  |
|  | |  |
|  | |  |
|  | |  |
|__| |__|

```

Puts a trailing space on every line. How it works:

```
              lines x      -- split the input string at newlines
      splitOn"~~"<$>       -- split every line on "~~"
    zip z                  -- pair every line with its water level, i.e.
                           -- first line = 8, 2nd = 7 etc.
   [i*length j-i|(i,j)   ] -- for each such pair take the number of "~~" found
                           -- times the level
 s<-sum                    -- and let s be the sum, i.e. the total amount of water

  s>0                      -- if there's any water at all

          [s,s-8..1]       -- make a list water levels starting with s
                           -- down to 1 in steps of 8
       min 8<$>            -- and set each level to 8 if its greater than 8
                           -- now we have the list of water levels for the output
  \i->(#i)=<<(  )<$>z      -- for each number i from 8,7..0 map (#i) to the
                           -- list of output water levels and join the results
unlines                    -- join output lines into a single string (with newlines)

l#i                        -- pick a piece of tube:
                           --  |__|  if l==0
                           --  |~~|  if l==i
                           --  |  |  else

  |1<2=""                  -- if there's no water in the input, return the
                           -- empty string

```

The main pain was the lack of a function that counts how often a substring occurs in a string. There's `count` in `Data.Text`, but importing it leads to a bunch of name conflicts that are way too expensive to resolve.
> 2 votes

# Answer
# Ruby, 139 bytes

(138 bytes of code plus one byte for the `-n`)

```
n||=0;b=gsub(/~~/){n=n+9-$.}[0,5];END{8.times{|i|puts (b*(n/8)).tr(?_,i>0??\ :?~)+(n%8>0?b.tr(?_,(8-i==n%8)??~:?\ ):"")};puts b*((n+7)/8)}

```

Try it online!

A few explanations:

> This program requires the `-n` switch.
>
> **`n`** – water counter.
>
> **`b`** – Template for constructing tubes; equals `"|__| "`
>
> **`i`** – Current line index during tube construction.
>
> **`gsub(/~~/){`****`}`** – This abuses `gsub` to simply count the water level. `gsub` actually expands to `Kernel.gsub`, which is equivalent to `$_.gsub!`. This unnecessarily manipulates the current line (`$_`); however, it allows for a more concise assignment of `b=``[0,5]` instead of `b=$_[0,5]`.
>
> **`n=n+9-$.`** – To measure the water level, the expression uses the pre-defined variable `$.`, which carries the current input line number. This allowed me to lose the explicit loop variable.
>
> **`b=gsub(/~~/){`****`}[0,5]`** – caches the bottom of the leftmost tube as a template. (Feels a little bit like the “Elephant in Cairo” pattern to me because the bottom line wins.)
> Since the bottom of the tube never shows water, the `gsub` won’t replace anything when we’re there; therefore in the end, `b` always equals `"|__| "`.
>
> **`END{`****`}`** – Gets called after the whole input stream has been processed. I use this phase to construct the target tubes.
>
> **`i>0??\ :?~`** – is simply short-hand for `i > 0 ? " " : "~"`.

**Update 1:** Added details on variables, the `gsub` trickery and the `END{``}` phase.

**Update 2:** **(±0 bytes overall)**

* Use `n||=0` instead of `n=n||0` **(-1 byte)**
* Took malus for `-n` **(+1 byte)**
> 1 votes

# Answer
# Python, 261 bytes

```
i=input().split('\n')
t=0
R=range(9)[::-1]
for n in R:t+=i[n].count('~')/2*(8-n)
m=t%8
e=t/8
o=t/8+1
T='|~~| '
b='|  | '
B='|__| '
n='\n'
if m:
 print T*e+b
 for n in R:
    if n==m:print b*e+T
    else:print b*o
 print B*o
elif t<1:1
else:print T*e+(n+b*e)*7+(n+B)*e

```

I feel like there is something I am missing. Also, if a bunch of newlines are accptable for the blank output, I could lose some bytes. Takes input like `'| | | | | |\n| | | | | |\n| | | | | |\n| | | | | |\n| | | | | |\n| | | | | |\n| | | | | |\n| | | | | |\n|__| |__| |__|'`.
> 1 votes

# Answer
# Python 3, 404 bytes

This program creates the full intended output with the water levels both in ASCII and number formats.

```
w,x,y=[],[],[];a,b,s=" ------> ","~","";y=input().split("\n")
for i in [i for i in zip(*y) if "_" in i][::2]:w+=[8-i.index(b)] if b in i else [0]
u=sum(w)
while u:x+=[[8],[u]][u<8];u-=x[-1]
for i,k in enumerate(y):
    s+=k+"%s"%[a," "*9][i!=4]
    for j,l in enumerate(x):
        c=["  ","__"][i==8];s+="|%s| "%(c,b*2)[l==8-i]
    s+="\n"
s+="\n"
for i in w:s+=" %02d  "%i
s+="\b"+a
for i in x:s+=" %02d  "%i
print(s)

```
> 0 votes

---
Tags: code-golf, ascii-art
---


title: Equal out bracket types

text:
# Question
Title: Equal out bracket types
Based on THIS question.

Given a string, replace each bracket `()[]{}<>` with a bracket of the appropriate type so that the brackets match, and the nested brackets cycle as follows:

1. Outermost ones are `()`
2. Directly inside of `()` should be `[]`
3. Directly inside of `[]` should be `{}`
4. Directly inside of `{}` should be `<>`
5. Directly inside of `<>` will be `()` again (cycles)

All non-bracket chars must remain exactly as they are. Open brackets may only be replaced with open brackets of some type, and close brackets with close brackets.

The input will always make this possible. This means its brackets matched correctly if their type is ignored. So, `{ab<)c]` is a valid input, but `ab)(cd` or `ab((cd` are not.

Examples:

```
2#jd {¤>. = 2#jd (¤).
abcdef    = abcdef
(3×5+(4-1)) = (3×5+[4-1])
<<<>><<>><<<<<<>>>>>>> = ([{}][{}][{<([{}])>}])

```

The use of native transforming of input this way (auto syntax of language) is not allowed.

As always: shortest code wins.

# Answer
## JavaScript (ES6), 79 bytes

```
s=>s.replace(/./g,c=>~(p=l.indexOf(c))?l[p&4?--k&3|4:k++&3]:c,l='([{<)]}>',k=0)

```

### Test cases

```
let f =

s=>s.replace(/./g,c=>~(p=l.indexOf(c))?l[p&4?--k&3|4:k++&3]:c,l='([{<)]}>',k=0)

console.log(f("2#jd {¤>."));
console.log(f("abcdef"));
console.log(f("(3×5+(4-1))"));
console.log(f("<<<>><<>><<<<<<>>>>>>>"));
```
> 2 votes

# Answer
# Haskell, 126 bytes

```
b="([{<"
d=")]}>"
y=cycle
(!)=elem
f(e:c)n(x:r)|x!b=y b!!n:f(y d!!n:e:c)(n+1)r|x!d=e:f c(n-1)r|1<3=x:f(e:c)n r
f c n s=s
f" "0

```

Try it on ideone. Usage:

```
*Main> f" "0 "<<<>><<>><<<<<<>>>>>>>"
"([{}][{}][{<([{}])>}])"

```

### Explanation

`f` takes three arguments: A string that works as stack for closing brackets, an int `n` for counting the nesting-depth and the input string.

```
f c n "" = ""                            -- base case for recursion: input string is empty
f (e:c) n (x:r)                          -- for the current char x
   | elem x "([{<" =                     -- check if it is an opening bracket
       (cycle "([{<")!!n :               --   if so, replace it with a bracket of the current nesting depth
           f ((cycle ")]}>")!!n : e : c) --   push the matching closing bracket on the stack
               (n+1) r                   --   increase depth level and check the next char
   | elem x ")]}>" =                     -- if x is a closing bracket
       e :                               --   replace it by the closing bracket from on top of the stack
           f c (n-1) r                   --   decrement depth level and check the next char
   | otherwise     = x : f (e:c) n r     -- otherwise keep x and check the next char

```
> 1 votes

# Answer
# Lex, 132 bytes

```
%{
int i,o[4]={40,91,123,60};
%}
%%
[[({<] {putchar(o[i++&3]);}
[])}>] {putchar(o[--i&3]+2-!(i&3));}
%%
yywrap(){}
main(){yylex();}

```
> 1 votes

# Answer
# Java, 155 bytes

```
a->{String s="([{<)]}>";for(int i=0,j=0,k;i<a.length;i++){k=s.indexOf(a[i]);if(k>3){a[i]=s.charAt(--j%4+4);}else if(k>-1){a[i]=s.charAt(j++%4);}}return a;}

```

Lambda that takes a `char[]` as it's single argument. We loop through the array, storing it's position in our string of brackets (`s`) in a variable (`k`). We check if it's an opening or closing bracket (`s.indexAt()`), and replace it with the appropriate bracket based on it's level of nesting (`s.charAt()`), looping appropriately with `%4`
> 1 votes

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


title: Bob's Passwords

text:
# Question
Title: Bob's Passwords
# Introduction

Bob likes to have different passwords for each website he uses. He wants passwords in a special format so that he can remember. Help him by building a password generator which is as short as possible in code length, because he likes keeping stuff short just like his name.

# Challenge

Build Bob a password generator which takes in four parameters -

* Domain address, (ex : stackexchange.com)
* First name,
* last name,
* Birth date and year.

and outputs a string which has undergone the following transformations.

Every password has a template based on the length ***l*** of the domain name. If ***l*** is prime then the template is of this form -

`[birth-date][domain-name][lastname][birth-year][symbol]`

else it is of this form -

`[symbol][birth-year][firstname][domain-name][birth-date]`.

The symbol field will have values based on the domain type.

```
.com    ->  $$$
.org    ->  &&&
.net    ->  %%%
.edu    ->  +++
.gov    ->  @@@
.mil    ->  >>>
default ->  ~~~

```

Now, he also wants to run a caesar cipher over fields - `[firstname][domain-name][lastname]`.The shift direction is right if *l* is prime else it is left. The shift value is determined by the value of addition of birth date and year.

After the above process, the text cannot be easily remembered so he wants the ciphered text to be pronounceable. To do this he wants to replace every third consecutive consonant with a vowel in alphabetical order (i.e, `aeiou`).

Finally, he wants to delete consecutive occurrences of same letters.

# Example

```
Input  - stackexchange.com bob williams 0894

Output - 08qraicvafyecugjigyoq94$$$.

```

Explanation :

Password template is `[birth-date][domain-name][lastname][birth-year][symbol]`, because the length of domain name `stackexchange` is a prime. Symbol will be `$$$` as domain type is `.com`.

Let's fill those values in the template - `08stackexchangewilliams94$$$`. Now caesar cipher has to be run on fields `[firstname][domain-name][lastname]` (it's just lastname in this case). Shift direction is right because ***l*** is prime and the shift value is `08+94 = 102`.

So, `08stackexchangewilliams94$$$` turns into `08qryaicvafylecugjjgykq94$$$`. Now every third consecutive consonant is replaced with a vowel - `08qraaicvafyeecugjigyoq94$$$` every consecutive ocuurences of same letter is deleted - `08qraicvafyecugjigyoq94$$$`. Don't worry it is pronounceable for Bob.

**Additional info**

* Domain address, first name and last name contain only lowercase alphabets.
* Domain address will always consist of only a second-level and top-level domain, like `stackexchange.com` and not `codegolf.stackexchange.com`. Also, domains like `.co.uk` is not allowed but just `.uk` or `.in` is valid.
* Replacement of vowel in alphabetical order is cyclic. I mean after `u`, `a` is used to replace.
* ASCII range for Caesar cipher is 97 - 122 inclusive.
* You can take input as described here.
* Output has to be a string.
* The format of birth date and year is `dd` and `yy`.So `02` is acceptable and `2` is not.

This is code-golf, so the shortest code in bytes wins. Happy Golfing!

# Answer
> 7 votes
# PowerShell 3+, ~~480~~ ~~476~~ ~~474~~ ~~453~~ ~~450~~ 448 bytes

```
param($d,$f,$l,$b)$s,$t=$d-split'\.'
$m,$y=$b-split'(?<=..)(?=..)'
$v=+$m+$y
$p='1'*$s.Length-match'^(?!(..+)\1+$)..'
$c={-join([char[]]"$input"|%{[char](97..122)[((+$_-97)+((26-$v),$v)[$p])%26]})}
$s=$s|&$c
$f=$f|&$c
$l=$l|&$c
$a=(($a=@{com='$';org='&';net='%';edu='+';gov='@';mil='>'}.$t),'~')[!$a]*3
("`"$(("$a$y$f$s$m","$m$s$l$y$a")[$p]-replace'([^aeiou\d]{3})',"`$('`$1'-replace'[a-z]`$$',('aeiou'[`$i++%5]))")`""|iex)-replace'([a-z])\1+','$1'

```

## Try it online!

**Saved *~~24~~ 26* bytes thanks to TimmyD!**

Wow, this was a crazy one. I don't think I can post a full breakdown of this until later or tomorrow.

Note: all line endings are `\n` (`0x10`), so that I don't have to use `;` and put this all on one line.

### Quick overview:

1. Split the domain into the second level and top level.
2. Split the birthdate into month and year.
3. Calculate the shift value.
4. Determine whether the length of the SLD is prime. ~~Since the segment cannot be longer than 63 characters (see also RFC 1035), I think it was shorter just to hardcode the list of primes :)~~ Using the regex method suggested.
5. Define a scriptblock (anonymous function essentially) to perform the Caesar cipher.
6. Apply the cipher to the SLD, first, and last names
7. Get the symbol with a hashtable and indexing funny business.
8. Finally, a giant mess where I apply the appropriate template, run a replace for the consonant triplets, replacing each one with a subexpression (code) that will replace that section with the appropriate value, then run the resulting string through `Invoke-Expression` (`iex`) to execute the generated emebedded code, then a final replace of consecutive letters with a single letter.

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


title: Replay previous console text

text:
# Question
Title: Replay previous console text
Create a script that, when run from a console, will display the text already in the console, prior to running.

# Challenge

* How will the winner of the challenge will be determined?
> The golf with the shortest length (in bytes) will win.

# Example Input and Output

Input: (Shown is Windows)

```
Microsoft Windows [Version 10.0.14393]
(c) 2016 Microsoft Corporation. All rights reserved.

C:\Users\CSS>dir
 Volume in drive C has no label.
 Volume Serial Number is B0A1-E768

 Directory of C:\Users\CSS

11/30/2016  07:18 PM    <DIR>          .
11/30/2016  07:18 PM    <DIR>          ..
12/01/2016  04:45 PM    <DIR>          .android
10/25/2016  12:41 PM    <DIR>          .atom
11/29/2016  05:52 PM    <DIR>          .dnx
10/27/2016  09:34 PM               148 .gitconfig
11/28/2016  03:02 PM    <DIR>          .MemuHyperv
11/29/2016  05:55 PM    <DIR>          .nuget
12/01/2016  04:42 PM    <DIR>          .oracle_jre_usage
10/26/2016  11:37 PM    <DIR>          .ssh
12/04/2016  06:20 PM    <DIR>          .VirtualBox
11/29/2016  12:56 PM    <DIR>          .vscode
11/28/2016  03:53 PM             8,528 2016-11-28-20-44-28.000-VBoxSVC.exe-2608.log
11/28/2016  05:09 PM    <DIR>          Andy
11/23/2016  10:01 AM    <DIR>          Contacts
12/11/2016  11:16 PM    <DIR>          Desktop
11/30/2016  07:35 PM    <DIR>          Documents
12/11/2016  01:43 AM    <DIR>          Downloads
11/23/2016  10:01 AM    <DIR>          Favorites
11/22/2016  07:23 PM               409 fciv.err
11/22/2016  07:21 PM               266 hi
11/23/2016  10:01 AM    <DIR>          Links
11/22/2016  04:28 PM                15 me.txt
11/28/2016  03:08 PM    <DIR>          Music
10/25/2016  12:44 AM    <DIR>          OneDrive
12/09/2016  05:57 PM    <DIR>          Pictures
11/23/2016  10:01 AM    <DIR>          Saved Games
11/24/2016  08:56 PM               151 search.bat
11/23/2016  10:01 AM    <DIR>          Searches
11/07/2016  11:00 AM                11 t.bat
11/24/2016  08:55 PM                93 update.bat
11/28/2016  03:08 PM    <DIR>          Videos
               8 File(s)          9,621 bytes
              24 Dir(s)  152,887,300,096 bytes free

C:\Users\CSS>

```

---

Output:

**The script must display something like the text above, in the sense that it must display exactly what was in the console before the script was called.**

# Answer
> 1 votes
# MacOS terminal, 84 bytes

```
osascript -e 'tell app "System Events" to keystroke "ac" using command down'
pbpaste

```

Simple select-all then copy-and-paste.

---
Tags: code-golf
---


title: Quine permutation group

text:
# Question
Title: Quine permutation group
Write a program or function which, when run, outputs another program or function which is valid in the same language as the original program, and which itself will output another program or function that has the same properties. You must at one point end up back to your initial program or function.

## Example

Suppose you write program `A`. When run, it outputs program `B`. When you run `B`, it outputs program `C`. When you run `C`, it outputs program `A`, thus completing the circle. `A`, `B` and `C` are all valid in the same language and are all different by at least one character.

## Scoring

Your score is calculated as `<Number of bytes of the initial program>/<number of iterations to get back to the initial program>`

For instance, with the programs `A`, `B` and `C` in the previous example, the number of iterations is `3` (you have to run 3 times to get back to `A`) and the number of bytes is the number of bytes of `A`.

This incentivize both golfing your initial code, and having an initial program that leads to a longer chain.

**The smallest score wins**

# Answer
> 9 votes
# CJam, score → 0

```
{)1e9%"X$~"}0X$~

```

Try it online in the CJam interpreter.

The actual score of this program is obviously positive, but `1e9` can be replaced with `1e99`, `1e999`, `1e9999`, `1e99999`, etc.

The numerator of the score grows *much* slower than the denominator.

### How it works

```
{          }     e# Define a block:
 )               e#   Increment the integer on the stack.
  1e9%           e#   Take the incremented integer modulo 1,000,000,000.
      "X$~"      e#   Push that string.
            0    e# Push 0.
             X$~ e# Copy the block and execute the copy.

                 e# The stack now holds the block, the modified integer and
                 e# the string "X$~", all of which CJam prints before exiting.

```

Executing the code prints `{)1e9%"X$~"}1X$~` which, when executed, prints `{)1e9%"X$~"}2X$~`, etc.

After reaching `{)1e9%"X$~"}999999999X$~`, one more execution yields the original code.

# Answer
> 3 votes
# Javascript ES6, `68/1.8e16` (basically 0)

```
$=_=>`$=${$};$(0)`.replace(eval(`/(${_})\\)/`),x=>++_%9e15+`)`);$(0)

```

Based on my Bling Quine framework:

```
$=_=>`$=${$};$()`

```

Here's the output sequence starting from `$(0)`:

```
$=_=>`$=${$};$(1)`.replace(eval(`/(${_})\\)/`),x=>++_%9e15+`)`);$(0)
$=_=>`$=${$};$(1)`.replace(eval(`/(${_})\\)/`),x=>++_%9e15+`)`);$(1)
$=_=>`$=${$};$(2)`.replace(eval(`/(${_})\\)/`),x=>++_%9e15+`)`);$(1)
$=_=>`$=${$};$(2)`.replace(eval(`/(${_})\\)/`),x=>++_%9e15+`)`);$(2)
$=_=>`$=${$};$(3)`.replace(eval(`/(${_})\\)/`),x=>++_%9e15+`)`);$(2)
$=_=>`$=${$};$(3)`.replace(eval(`/(${_})\\)/`),x=>++_%9e15+`)`);$(3)
$=_=>`$=${$};$(4)`.replace(eval(`/(${_})\\)/`),x=>++_%9e15+`)`);$(3)
...
$=_=>`$=${$};$(8999999999999999)`.replace(eval(`/(${_})\\)/`),x=>++_%9e15+`)`);$(8999999999999999)
$=_=>`$=${$};$(0)`.replace(eval(`/(${_})\\)/`),x=>++_%9e15+`)`);$(8999999999999999)
$=_=>`$=${$};$(0)`.replace(eval(`/(${_})\\)/`),x=>++_%9e15+`)`);$(0)

```

# Answer
> 1 votes
# Underload, score of 0 in the limit

```
(a(:^)*(a(S)*):*:*:*:*^S):^

```

Adding another `:*` to the sequence of `:*` will add two bytes to the program, and double the period of the quine. Thus, the score can be made arbitrarily small by adding more copies.

Try it online!

This basically uses the Underload universal quine constructor `(a(:^)**f*S):^`, which is capable of producing a program whose output is any function *f* of the original source code. In this case, the function in question produces a string that outputs its argument in the most naive way (by escaping it and adding a print statement; escape is `a`, add a print statement is `(S)*`); and we run the function in a loop (via `^`) a power of 2 times. (2 to the power of *n* can be written in Underload by using *n* repeats of `:*`.) The result is output like

```
(((((((((((((((((a(:^)*(a(S)*):*:*:*:*^S):^)S)S)S)S)S)S)S)S)S)S)S)S)S)S)S)S

```

which produces, when run,

```
((((((((((((((((a(:^)*(a(S)*):*:*:*:*^S):^)S)S)S)S)S)S)S)S)S)S)S)S)S)S)S

```

and so on until the original program is reached.

---
Tags: code-challenge, quine, code-generation
---


title: Tasteless and other bugs

text:
# Question
Title: Tasteless and other bugs
Some versions of the standard Android calculator app allow you to press a key, like 'sin' and then the 'del' key to make it 'si'. Probably just a bug which they can't be bothered with removing.

The following letters/letter groupings are typable:

```

sin
si
s
cos
co
c
tan
ta
t
ln
l
log
lo
e

```

So, 'tasteless' is typable, because ta-s-t-e-l-e-s-s and so is 'clogs' because 'c-log-s'. However 'got' is not typable, neither is 'an' or 'xyz'.

Write a program that takes a single word (or sequence of letters, only a-z in input) as input and produces output to indicate if a word is typable or not.

Output may be a single character/letter/digit/etc. or it may be larger. All typable words should produce the same output. All non-typable words should also produce the same output.

P.S. Just out of curiosity, is 'tasteless' the longest dictionary word that is typable?

# Answer
> 21 votes
# Perl, ~~47~~ ~~43~~ 41 + 1 = 42 bytes

-4 bytes thanks to @Sunny Pun. -2 bytes thanks to @Brad Gilbert b2gills and @Downgoat

Run with the `-n` flag.

```
say!/^(s(in?)?|co?|t(an?)?|ln?|log?|e)+$/

```

It can definitely be golfed futher, but in the spirit of competition, I'm leaving the mostly-original regex I came up with at the beginning. Returns nothing if true, `1` if false.

Try it online!

I downloaded a dictionary file, and the longest word I found was 11 letters -- `tattletales`

# Answer
> 17 votes
# JavaScript (ES6), 44 bytes

```
s=>/^((si|ta|l)n?|co?|log?|[ste])+$/.test(s)

```

I *think* this is the shortest regex possible, but of course I may be wrong.

### Explanation

An obvious first place to start would be a regex that simply includes all options separately:

```
s=>/^(sin|si|s|cos|co|c|tan|ta|t|log|lo|l|ln|e)+$/.test(s)

```

First, we can observe that `cos` can be formed from `co` and `s`, making it unnecessary:

```
s=>/^(sin|si|s|co|c|tan|ta|t|log|lo|l|ln|e)+$/.test(s)

```

Some of these, such as `sin` and `si`, can be combined by making the last letter optional:

```
s=>/^(sin?|s|co?|tan?|t|log?|ln?|e)+$/.test(s)

```

This works because `sin?` matches `si` with or without an `n` on the end, thus covering both `sin` and `si`.

There seems to be a lot of `n?`s as well. What if we put them all together?

```
s=>/^((si|ta|l)n?|s|co?|t|log?|e)+$/.test(s)

```

One more way to golf this would be to combine the remaining single-char options into a character range, but this comes out at the same length:

```
s=>/^((si|ta|l)n?|co?|log?|[ste])+$/.test(s)

```

And that's how you golf a simple regex. I believe this is the shortest possible regex that matches every string correctly, but perhaps not. I will award a **+100 bounty** to anyone who manages to improve upon this regex.

# Answer
> 7 votes
# Pyth, ~~37~~ ~~33~~ ~~29~~ 28 bytes

The code contains an unprintable character, so here is an `xxd` hexdump.

```
00000000: 737d 5173 4d5e 733c 5252 6336 2e22 6174  s}QsM^s<RRc6."at
00000010: 14d0 69ba 76f1 ac59 6422 346c            ..i.v..Yd"4l

```

Try it online.

~~Extremely~~ Astronomically inefficient. The time and space complexity is ~~O(16n)~~ O(24n).

### Explanation

First, a `Q` is implicitly appended.

```
s}QsM^s<RRc6."…"4lQ     Implicit: Q = input
            ."…"        Generate "logsincostanlnee"
          c6            Split in 6 parts: ["log", "sin", "cos", "tan", "ln", "ee"]
         R      4       For each n from 0 to 3
       <R               Take the first n chars from each string
      s                 Flatten the results
                 lQ     Get length of input
     ^                  Take that Cartesian power of the list
   sM                   Join each resulting list
 }Q                     Check if the input is found
s                       Cast to integer

```

# Answer
> 6 votes
# Jelly, ~~32~~ ~~31~~ ~~30~~ ~~28~~ 26 bytes

```
ŒṖw@€€“¡Ṡ[ẈKœịḲ-¢ȧ?-»’%3ḌẠ

```

Outputs **0** if the word is typeable, **1** if not. *Thanks to @JonathanAllan for golfing off 1 byte!*

Try it online!

### How it works

```
ŒṖw@€€“¡Ṡ[ẈKœịḲ-¢ȧ?-»’%3ḌẠ  Main link. Argument: s (string of lowercase letters)

ŒṖ                          Yield all partitions of s.
      “¡Ṡ[ẈKœịḲ-¢ȧ?-»       Yield "sine  logcostanln". Every third character
                            marks the start of a typeable word.
  w@€€                      Find the indices of all substrings in the partitions
                            in the string to the right (1-based, 0 if not found).
                     ’      Decrement. "Good" indices are now multiples of 3.
                      %3    Modulo 3. "Good" indices are mapped to 0, "bad"
                            indices are mapped to 1 or 2.
                        Ḍ   Convert from decimal to integer. A partition will
                            yield 0 iff all indices are "good".
                         Ạ  All; yield 0 if one or more integers are falsy (0), 1
                            if all integers are truthy (non-zero).

```

# Answer
> 6 votes
# Brachylog, 33 bytes

*Fixed a bug thanks to @Synoli.*

```
~c:1a
,"sincostanloglneeee"@6e@[?

```

Try it online!

Outputs `true.` if typeable or `false.` otherwise.

### Explanation

We try deconcatenations of the input until we find one for which all strings that we concatenate are a prefix of one of `["sin", "cos", "tan", "log", "lne", "eee]`.

```
~c                          A list of strings which when concatenated results in the Input
  :1a                       All strings of this list satisfy the predicate below:

,"sincostanloglneeee"@5           The list ["sin", "cos", "tan", "log", "lne", "eee"]
                       e          Take one element of that list
                        @[?       The input is a prefix of that element

```

# Answer
> 4 votes
# Perl 6,  ~~60 50~~  44 bytes

first attempt (*60*)

```
put +?(get~~/^<{<sin cos tan ln log e>».&{|m:ex/^.+/}}>*$/)

```

translation of the Perl 5 answer (*50*)

```
put +?(get~~/^[s[in?]?|co?|t[an?]?|ln?|log?|e]*$/)

```

using `-n` switch (*43+1*)

```
put +?/^[s[in?]?|co?|t[an?]?|ln?|log?|e]*$/

```

The first `?` converts the result to Boolean, and the first `+` converts that to a number (`1` for `True`, `0` for `False`)

# Answer
> 2 votes
# Wonder, 41 bytes

```
!.(mstr"^(s|t|co?|(l|ta|si)n?|log?|e)+$")

```

Usage:

```
(!.(mstr"^(s|t|co?|(l|ta|si)n?|log?|e)+$")) "tasteless"

```

Totally misunderstood the question before, but now it's all fixed. Outputs `F` for match and `T` for no match.

## Noncompeting, 35 bytes

```
!.`^(s|t|co?|(l|ta|si)n?|log?|e)+$`

```

Usage:

```
(!.`^(s|t|co?|(l|ta|si)n?|log?|e)+$`) "tasteless"

```

This makes use of applicable regexes, which was implemented after this challenge.

# Answer
> 2 votes
## Mathematica, 101 bytes

```
If[StringMatchQ[#,("sin"|"si"|"s"|"cos"|"co"|"c"|"tan"|"ta"|"t"|"ln"|"l"|"log"|"lo"|"e")..],"T","F"]&

```

It seems that the hard parts of this challenge are coming up with the shortest regex and choosing the most concise language to match the regex. I don't have anything to contribute to the former, and Mathematica isn't good candidate for the latter since you have to use `StringMatchQ` and `RegularExpression`. What I can do is answer your P.S.: is "tasteless" the longest word that you can type?

```
In[1]:= f=StringMatchQ[#,("sin"|"si"|"s"|"cos"|"co"|"c"|"tan"|"ta"|"t"|"ln"|"l"|"log"|"lo"|"e")..]&;

In[2]:= Select[EntityList@"Word",f@#[[2,1]]&][[All,2,1]]//SortBy[StringLength]//DeleteDuplicates
Out[2]= {c,e,l,s,t,cc,cl,el,et,lo,si,sl,ta,te,ccc,col,cos,cot,eel,ell,eta,etc,lee,let,log,lot,sec,see,set,sic,sin,sit,tae,tan,tat,tec,tee,cell,clog,clot,coco,cole,colt,coss,cost,cote,else,less,loco,loge,loll,lose,loss,lota,sect,seel,sell,sess,seta,sett,sill,silo,silt,sine,sise,siss,site,sloe,slog,slot,stet,taco,tact,tael,talc,tale,tall,tect,tell,test,cello,close,cosec,costa,cotan,eccle,elect,elsin,ettle,loess,lotte,secle,setee,since,sleet,stale,stall,state,steel,stele,tasse,taste,tatee,teest,telco,testa,tetel,tsine,cellco,closet,coleta,collet,coltan,cosine,cosset,costal,ecesis,estate,lessee,scelet,select,sellee,sestet,settee,settle,siesta,silole,stacte,stance,stasis,tallet,tallot,taslet,tassel,tasset,tattle,tectal,teetan,tellee,testee,tsetse,celesta,cessile,cocotte,collect,costate,ecolect,ectasis,electee,sessile,sinless,sitelet,statant,tassell,tastant,testate,coestate,colessee,colocolo,cosiness,costless,electant,lossless,sceletal,siletane,statelet,tactless,tallness,telltale,telocoel,coelostat,sissiness,stateless,tasteless,tattletale}

```

So "tattletale" seems to be the longest by one character.

# Answer
> 2 votes
# Processing, 223 bytes

```
int d(String b){for(String p:"tan0log0sin0cos0ln0e".split("0"))if(p.startsWith(b))return 1;return 0;}

int l(String p){String b="";int t=1;for(char c:p.toCharArray()){b+=c;if(d(b)<1){b=c+"";t=d(b);}if(t<1)return t;}return t;}

```

Finally decided to do an answer without regex. To call the function, use `l("tasteless");`. Returns `0` for false and `1` for true.

### Expanded code with explanation

```
int d(String b){
  for(String p:"tan0log0sin0cos0ln0e".split("0"))
    if(p.startsWith(b))
      return 1;
  return 0;
}
//main function
int l(String p){
  String b="";
  int t=1;
  for(char c:p.toCharArray()){
    b+=c;
    if(d(b)<1){
      b=c+"";
      t=d(b);
    }
    if(t<1)return t;
  }
  return t;
}

```

Basically, we iterate over the given string, building up `b` char by char. We check using `d()` if any of the `tan`,`log`,... start with `b`. If it does, then it is valid. Else, we check if the char at that position is valid and we reset `b`. Now if it is invalid, `0` will be returned, or else it will still be valid. At the end, if the program hasn't already returned something, then return `1`.

# Answer
> 2 votes
# Scala, 49 bytes

```
s=>s.matches("(s(in?)?|co?|t(an?)?|ln?|log?|e)+")

```

Returns true if the given string matches the regex, false otherwise.

# Answer
> 2 votes
# Python 3, 154 bytes

```
r=1;i=input()
while r:
 r=0
 for s in'sin,cos,tan,log,ln,co,lo,si,ta,s,c,t,l,e'.split(','):
  if i.startswith(s):r=i=i.replace(s,'',1);break
print(i=='')

```

Try it online!

# Answer
> 2 votes
# Python 3, ~~149~~ 130 bytes

```
i=input()
for a in 'tan,sin,cos,log,si,co,ta,lo,lo,ln,s,c,t,l,e'.split(','):
    if a in i:
        i=i.replace(a,"")
print(not i)

```

edit #1: shaved 19 bytes using @Henke solution

# Answer
> 0 votes
# PHP, 60 bytes

```
<?=preg_match("#^((si|ta|l)n?|co?|log?|s|e|t)+$#",$argv[1]);

```

regex stolen from ETHproductions:
takes input from command line argument; prints `1` for typable, `0` for not typeable.

**older versions, ~~75~~ ~~73~~ 69 bytes**

```
<?=!preg_replace("#co|log|ln|lo|sin|si|tan|ta|[celst]#","",$argv[1]);

```

replaces all possible words with empty string, returns the result, negates.

```
<?=!preg_split("#co|log|ln|lo|sin|si|tan|ta|[celst]#",$argv[1],-1,1);

```

splits input by regex matches. Flag `1` stands for `PREG_SPLIT_NO_EMPTY` and tells `preg_split` to only return non-empty results. If input is typable, `preg_split` will only have empty results, so it will return an empty array, which is falsy. `!` negates the result.

Both versions take input from command line argument
and print `1` if result is empty (input is typable), else nothing.

Notes:
Packing the regex using `?` does not work here; it renders the expressions ungreedy; probably due to backtracking. And the order of the alternatives is important: `ta` has to stand before `t` or the engine will stop matching when it finds `t`.

I found a quantifier cheat sheet, thought `??` or `?+` might help; but they did not work for me.

# Answer
> 0 votes
## Python 2, 124 bytes

```
f=lambda w:any(f(w[len(s):])if w[:len(s)]==s else 0for s in'sin,cos,tan,log,ln,co,lo,si,ta,s,c,t,l,e'.split(','))if w else 1

```

# Answer
> 0 votes
# Java 8, 55 bytes

```
s->return s.matches("^((si|ta|l)n?|co?|log?|[ste])+$");

```

Disclamer: *I used ETHproductions' regex because it was many bytes shorter than mine.* Full credit on the Regex to him. What I did was add 24 bytes to make it a Java function.

Returns `false` if the word did not fit into the Regex, else `true`.

---
Tags: code-golf, string, decision-problem
---


title: Plotting the Cornu spiral

text:
# Question
Title: Plotting the Cornu spiral
The Cornu Spiral can be calculated using Feynman's method for path integrals of light propagation. We will approximate this integral using the following discretisation.

Consider a mirror as in this image, where `S` is the light source and `P` the point where we collect light. We assume the light bounces in a straight ray from `S` to each point in the mirror and then to point `P`. We divide the mirror into `N` segments, in this example 13, labelled `A` to `M`, so that the path length of the light is `R=SN+NP`, where `SN` is the distance from `S` to mirror segment `N`, and similar for `P`. (*Note that in the image the distance of points `S` and `P` to the mirror has been shortened a lot, for visual purposes. The block `Q` is rather irrelevant, and placed purely to ensure reflection via the mirror, and avoid direct light from `S` to `P`.*)

For a given wave number `k` the phasor of a ray of light can be calculated as `exp(i k R)`, where `i` is the imaginary unit. Plotting all these phasors head to tail from the left mirror segment to the right leads to the Cornu spiral. For 13 elements and the values described below this gives:

For large `N`, i.e. a lot of mirror segments, the spiral approaches the "true" Cornu spiral. See this image using various values for `N`:

**Challenge**

For a given `N` let `x(n)` be the *x*-coordinate centre of the *n*-th mirror segment (`n = 0,1,2,...,N`):

```
x(n) := n/N-0.5

```

Let `SN(n)` be the distance of `S = (-1/2, 1000)` to the n-th mirror segment:

```
SN(n) := sqrt((x(n)-(-1/2))^2 + 1000^2)

```

and similarly

```
NP(n) := sqrt((x(n)-1/2)^2 + 1000^2)

```

So the total distance travelled by the *n*-th light ray is

```
R(n) := SN(n) + NP(n)

```

Then we define the phasor (a complex number) of the light ray going through the *n*-th mirror segment as

```
P(n) = exp(i * 1e6 * R(n))

```

We now consider the cumulative sums (as an approximation to an integral)

```
C(n) = P(0)+P(1)+...+P(n)

```

The goal is now plotting a piecewise linear curve through the points `(C(0), C(1), ..., C(n))`, where the imaginary part of `C(n)` should be plotted against its real part.

The **input** should be the number of elements `N`, which has a minimum of 100 and a maximum of at least 1 million elements (more is of course allowed).

The **output** should be a plot or image in any format of at least 400×400 pixels, or using vector graphics. The colour of the line, axes scale etc are unimportant, as long as the shape is visible.

Since this is code-golf, the shortest code in bytes wins.

*Please note that this is not an actual Cornu spiral, but an approximation to it. The initial path integral has been approximated using the Fresnel approximation, and the mirror is both not of infinite length and not containing an infinite number of segments, as well as mentioned it is not normalised by the amplitudes of the individual rays.*

# Answer
# MATL, ~~29~~ ~~26~~ 25 bytes

*Thanks to @Adriaan for 3 bytes off!*

```
Q:qG/q1e3YytP+1e6j*ZeYsXG

```

Here's an example with input ~~`365`~~ `366`... because today is MATL's first birthday! (and 2016 is a leap year; thanks to @MadPhysicist for the correction).

Or try it in **MATL online!** (experimental compiler; refresh the page if it doesn't work).

### Explanation

```
Q:q    % Input N implicitly. Push range [0 1 ... N] (row vector)
G/     % Divide by N, element-wise
q      % Subtract 1. This gives NP projected onto the x axis for each mirror element
1e3    % Push 1000. This is NP projected onto the y axis
Yy     % Hypotenuse function: computes distance NP
tP     % Duplicate, reverse. By symmetry, this is the distance SN
+      % Add. This is distance SNP for each mirror element (row vector)
1e6j   % Push 1e6*1i
*      % Multiply
Ze     % Exponential
Ys     % Cumulative sum
XG     % Plot in the complex plane

```
> 20 votes

# Answer
# MATLAB, ~~88 84~~ 81 79 bytes

```
g=@(x)hypot(1e3,x);h=@(x)plot(cumsum(exp(1e6i*(g(x)+g(1-x)))));f=@(N)h(0:1/N:1)

```

Thanks @LuisMendo for -3 bytes, and @Adriaan for -2 bytes!

The function `g` is the distance function we use in `SN` and `NP`, and `h` does the rest of the calculation plus plotting. `f` the actual function we want and it produces the vector we need.

This is the output for `N=1111`
> 14 votes

# Answer
# GeoGebra, 107 bytes

```
1
1E6
InputBox[a]
Polyline[Sequence[Sum[Sequence[e^(i*b(((k/a)^2+b)^.5+((k/a-1)^2+b)^.5)),k,0,a],l],l,1,a]]

```

Each line is entered separately into the input bar. Input is taken from an input box.

Here is a gif of the execution:

**How it works**

Entering `1` and `1E6` implicitly assigns the values to `a` and `b` respectively. Next, the `InputBox[a]` command creates an input box and associates it with `a`.

The inner `Sequence` command iterates over integer values of `k` from `0` to `a` inclusive. For each value of `k`, the required distance is calculated using the expression `((k/a)^2+b)^.5+((k/a-1)^2+b)^.5)`. This is then multiplied by `i*b`, where `i` is the imaginary unit, and `e` is raised to the result. This yields a list of complex numbers.

After this, the outer `Sequence` performs the cumlative summation by iterating over integer values of `l` from `1` to `a` inclusive. For each value of `l`, the first `l` elements of the list are summed using the `Sum` command, again yielding a list of complex numbers.

GeoGebra treats the complex number `a + bi` as the point `(a, b)`. Hence, the complex numbers can be plotted using the `Polyline` command, which joins all the points in the complex number list with straight line segments.
> 12 votes

# Answer
## R, 102 82 80 bytes

Edit: scrapped the function for calculating the distance

Edit2: Noticed a nearly identical answer by @Plannapus (oh well)

Edit3: Saved 2 bytes thanks to @Plannapus as well

```
N=scan();x=1:N/N;plot(cumsum(exp((sqrt(x^2+1e6)+sqrt((x-1)^2+1e6))*1e6i)),t="l")

```

For `N=1000` we get:
> 6 votes

# Answer
# R, ~~86~~ ~~83~~ 81 bytes

```
plot(cumsum(exp(1e6i*((1e6+(0:(N<-scan())/N)^2)^.5+(1e6+(0:N/N-1)^2)^.5))),t="l")

```

Thanks @JarkoDubbeldam for the extra 3 bytes.

For N=1000:
> 5 votes

# Answer
## Mathematica 89 Bytes (87 chars)

```
Graphics[Line[ReIm/@Tr/@Table[E^(I*10^6*Tr[√(10^6+(-{0,1}+j/#)^2)]),{i,0,#},{j,0,i}]]]&

```

Usage:

```
%@100

```

yields
> 1 votes

---
Tags: code-golf, graphical-output
---