# Question
Title: Find the repetend of the decimal representation!
In this challenge 2 years ago, we found the **period** of a unit fraction (`1/n where n is a natural number`).

Now, your task is to write a program/function to find the **repetend** of a unit fraction.

The **repetend** is the part of the decimal expansion which repeats infinitely, like:

* The decimal representation of `1/6` is `0.16666...`, then the **repetend** is `6`.
* The decimal representation of `1/11` is `0.090909...`, then the repetend is `09`.
* The decimal representation of `1/28` is `0.0357142857142857142857...`, then the repetend is `571428`.

## Specs

* Input in any reasonable format.
* Output the repetend in decimal, **string or list**.
* For `1/7` (`0.142857142857...`), you must output `142857` instead of `428571`.
* For `1/13` (`0.076923076923076923...`), you must output `076923` instead of `76923`.
* No brute force, please.

## Testcases

```
Input    Output
1        0
2        0
3        3
7        142857
13       076923
17       0588235294117647
28       571428
70       142857
98       102040816326530612244897959183673469387755
9899     000101020305081321345590463683200323264976260228305889483786241034447924032730578846348115971310233356904737852308313971108192746742095161127386604707546216789574704515607637135064147893726639054449944438832205273259925244974239822204263056874431760783917567431053641781998181634508536215779371653702394181230427315890493989291847661379937367410849580765733912516415799575714718658450348520052530558642287099707041115264168097787655318719062531568845337912920497019901

```

## Scoring

This is . Shortest solution in bytes win.

No answer would be accepted, because the goal is not to find the language capable of producing the shortest solution, but the shortest solution in each language.

## Leaderboard

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

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

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

# Answer
# Java, 150 bytes:

```
String p(int n){int a=1,p;String r="";for(;n%10<1;n/=10);for(;n%2<1;n/=2)a*=5;for(;n%5<1;n/=5)a*=2;for(p=a%=n;;){p*=10;r+=p/n;if(a==(p%=n))return r;}}

```

### Added whitespace:

```
String p(int n){
    int a=1,p;
    String r="";
    for(;n%10<1;n/=10);
    for(;n%2<1;n/=2)
        a*=5;
    for(;n%5<1;n/=5)
        a*=2;
    for(p=a%=n;;){
        p*=10;
        r+=p/n;
        if(a==(p%=n))
            return r;
    }
}

```

### Ungolfed, full program:

```
import java.util.Scanner;

public class A036275 {
    public static String period(int a,int n){
        if(n%10==0) return period(a,n/10);
        if(n%2==0) return period(a*5,n/2);
        if(n%5==0) return period(a*2,n/5);
        a %= n;
        int pow = a;
        String period = "";
        while(true){
            pow *= 10;
            period += pow/n;
            pow %= n;
            if(pow == a){
                return period;
            }
        }
    }
    public static String period(int n){
        return period(1,n);
    }
    public static void main(String args[]){
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        sc.close();
        System.out.println(period(n));
    }
}

```
> 5 votes

# Answer
# CJam, 26

```
riL{_XW$%A*:X|X@-}g_X#>\f/

```

Try it online

**Explanation:**

The program builds a series of dividends involved in the calculation of the decimal expansion, until it finds a dividend it has seen before. Then it takes all the dividends starting with that one, and divides them by n to get the digits of the repetend.

```
ri       read the input and convert to integer (n)
L        push an empty array (will add the dividends to it)
{…}g     do … while
  _      copy the current array of dividends
  X      push the latest dividend (initially 1 by default)
  W$     copy n from the bottom of the stack
  %A*    calculate X mod n and multiply by 10
  :X     store in X (this is the next dividend)
  |      perform set union with the array of dividends
  X@     push X and bring the old array to the top
  -      set difference; it is empty iff the old array already contained X
          this becomes the do-while loop condition
_X#      duplicate the array of dividends and find the position of X
>        take all dividends from that position
\f/      swap the array with n and divide all dividends by n

```
> 3 votes

# Answer
# Python 3.5, ~~79~~ ~~74~~ ~~73~~ 70 bytes

```
f=lambda n,t=1,q=[],*d:q[(*d,t).index(t):]or f(n,t%n*10,q+[t//n],*d,t)

```

*Saved 3 bytes by keeping track of dividends, an idea I took from @aditsu's CJam answer.*

Test it on repl.it.
> 3 votes

# Answer
# Jelly, ~~12~~ 10 bytes

```
%³×⁵
1ÇÐḶ:

```

*Saved 2 bytes by keeping track of dividends, an idea I took from @aditsu's CJam answer.*

Try it online!

### How it works

```
%³×⁵     Helper link. Argument: d (dividend)

%³       Yield the remainder of the division of d by n.
  ×⁵     Multiply by 10.

1ÇÐḶ:    Main link. Argument: n

1        Yield 1 (initial dividend).
 ÇÐḶ     Apply the helper link until its results are no longer unique.
         Yield the loop, i.e., everything from the first repeated result
         up to and including the last unique one.
    :    Divide each dividend by n.

```
> 2 votes

# Answer
# Perl 6, 37 bytes

```
{(1.FatRat/$_).base-repeating[1]||~0}
~0 max (1.FatRat/*).base-repeating[1]

```

If you don't care that it will only work with denominators that fit into a 64 bit integer you can remove the method call to `.FatRat`.

### Explanation:

```
# return ｢"0"｣ if ｢.base-repeating｣ would return ｢""｣
~0

# ｢&infix<max>｣ returns the numerically largest value
# or it's first value if they are numerically equal
max

(
  # turn 1 into a FatRat so it will work
  # with denominators of arbitrary size
  1.FatRat

  # divided by
  /

  # the input
  *

# get the second value from calling the
# method ｢.base-repeating｣
).base-repeating[1]

```

### Test:

```
#! /usr/bin/env perl6
use v6.c;
use Test;

my &code = ~0 max (1.FatRat/*).base-repeating[1];
# stupid highlighter */
# Perl has never had // or /* */ comments

my @tests = (
  1    => '0',
  2    => '0',
  3    => '3',
  6    => '6',
  7    => '142857',
  11   => '09',
  13   => '076923',
  17   => '0588235294117647',
  28   => '571428',
  70   => '142857',
  98   => '102040816326530612244897959183673469387755',
  9899 => '000101020305081321345590463683200323264976260228305889483786241034447924032730578846348115971310233356904737852308313971108192746742095161127386604707546216789574704515607637135064147893726639054449944438832205273259925244974239822204263056874431760783917567431053641781998181634508536215779371653702394181230427315890493989291847661379937367410849580765733912516415799575714718658450348520052530558642287099707041115264168097787655318719062531568845337912920497019901',
);

plan +@tests;

for @tests -> $_ ( :key($input), :value($expected) ) {
  is code($input), $expected, "1/$input";
}

```

```
1..12
ok 1 - 1/1
ok 2 - 1/2
ok 3 - 1/3
ok 4 - 1/6
ok 5 - 1/7
ok 6 - 1/11
ok 7 - 1/13
ok 8 - 1/17
ok 9 - 1/28
ok 10 - 1/70
ok 11 - 1/98
ok 12 - 1/9899

```
> 2 votes

# Answer
# GameMaker Language, 152 bytes

*Based on Kenny's answer*

```
n=argument0;a=1r=0while(n mod 2<1){a*=5n/=2}while(n mod 5<1){a*=2n/=5}a=a mod n;p=a;while(1){p*=10r=r*10+p/n;r=r mod $5f5e107;p=p mod n;if(a=p)return r}

```
> 1 votes

# Answer
# Java, 122

```
String f(int n){String r="";int x=1,a[]=new
int[n*10];while(a[x]++<1)x=x%n*10;do{r+=x/n;x=x%n*10;}while(a[x]<2);return r;}

```

Similar to my CJam solution.
> 1 votes

# Answer
# Pyth, 63 bytes

```
W!%QT=/QT;J*F+1-PQ,2 5K%*F+1-L7@,2 5PQJ=NKW1=+k/=*NTJIqK=%NJB;k

```

Try it online!

Direct translation of the answer in Java.
> 0 votes

# Answer
# PHP, 169 Bytes

```
$d=$argv[2];$a[]=$n=$argv[1];while($n%$d&&!$t){$n*=10;$r[]=$n/$d^0;$t=in_array($n%=$d,$a);$a[]=$n;}if($t)echo join(array_slice($r,array_search(end($a),$a),count($a)-1));

```
> 0 votes

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


title: Forecast Palindromic Dates

text:
# Question
Title: Forecast Palindromic Dates
Palindromic dates are dates that appear as palindromes: the string of digits can be read the same way backwards as forwards. For the North American date format (MM/DD/YYYY), the next few palindromic dates are:

`02/02/2020`

`12/02/2021`

`03/02/2030`

### The Challenge

Create a function that returns all palindromic dates in a consistent, common date format (of your choosing) that fall within a range of dates (*edit: including the range itself*).

### Rules

* To qualify as a palindrome, only the numeric characters of the date should be checked.
* The date can be in any common format (`MM/DD/YYYY`, `DD-MM-YYYY`), as long as it uses two digits for both the month and day and four for the year, and it uses a character to separate parts of the date. The output must preserve seperating characters (`/`, `-`, etc.). Your function only needs to handle one distinct date format. Please include the format in your answer.
* If there are more than one dates returned, they should be comma or new-line separated.
* Shortest answer wins!

### Example

```
date_palindrome('05/02/2050', '12/12/2060')
>>>['05/02/2050', '06/02/2060']

```

# Answer
# MATL, ~~24~~ 23 bytes

```
YOZ}&:"@23XOtt47>)tP=?8M

```

Accepts input in the form of an array of string `{lower, upper}` where the date format is `'MM/DD/YYYY'`. Output is in the format `MM/DD/YYYY` as well.

**Try it Online**

**Explanation**

```
        % Implicitly grab the two inputs
YO      % Convert to serial date format
Z}      % Push them onto the stack separately
&:      % Create an array from [lower...upper] incrementing 1 day
"       % For each day
  @23XO % Get the string version of the date (mm/dd/yyyy)
  tt    % Duplicate twice
  47>)  % Get the numeric parts
  tP=   % Compare numeric part with the flipped version of the numeric part
  ?8M   % If they are the same push it to the stack
        % Implicitly display stack contents

```
> 8 votes

# Answer
# Python 2, 197 bytes

One byte saved thanks to @cat!

```
from datetime import*
def g(a,b):
 for s in"ab":exec"%s=date(*[int(x)for x in %s.split('-')])"%(s,s)
 for d in range((b-a).days+1):
    x=str(a+timedelta(d));y=x.replace("-","")
    if y==y[::-1]:print x

```

Try it here!

Input and output format is `YYYY-MM-DD`. First intendation level is spaces, second one is tabs.
Nothing too special going on here. Uses some `exec` abuse to convert the input to `date` objects by splitting the date string on `-` and splatting the list into the `date` constructor. Then we just iterate over all dates in their inclusive range and print the ones which are palindromic.
> 6 votes

# Answer
# Bash + GNU utilities, 116 84

Requires 64-bit version of date for the given testcase.

```
set date -uf- +%
jot -w@ - `$@s` 86400|$@F|sed -r 'h
:
s/-|^(.)(.*)\1$/\2/
t
/./d
g'

```

I/O is in `YYYY-MM-DD` format. Input is taken from two lines of stdin, e.g.

```
printf "%s\n" 2050-05-02 2060-12-12 | ./palindate.sh

```

### Explanation

* `set` saves the date command template so it may be accessed using the `$@` parameter
* `date -uf- +%s` converts endpoint dates to number of seconds since the Unix epoch
* `jot` interpolates this to give a list of seconds-from-the-epoch, one per day, each prefixed with `@`
* `date -uf- +%F` formats each list entry as `YYYY-MM-DD`
* `sed` checks for palindromes:
    + `h` save the input line to the hold buffer
    + `:` define "unnamed" label
    + `s/-|^(.)(.*)\1$/\2/` if a dash is found, remove it or if the first and last characters match, remove them
    + `t` if there was a match above, jump back to the unnamed label
    + `/./d` if there are any characters left over, the line is not a palindrome - delete it and continue to the next line
    + `g` if we got here, then no line deletion happened, thus the line must have been a palindrome. Get the line back from the hold buffer and implicitly display it.
> 6 votes

# Answer
## PowerShell v2+, 127 bytes

```
for($a,$b=[datetime[]]$args;$a-le$b){if(($c="{0:yyyyMMdd}"-f$a)-eq-join$c[$c.length..0]){"{0:MM/dd/yyyy}"-f$a}$a=$a.AddDays(1)}

```

Takes input as command-line arguments `$args` in `MM/DD/YYYY` (or similar) format and recasts as a `[datetime]` array, stores them in `$a` and `$b`. That's the setup step of the `for` loop. The conditional is so long as `$a` is less-than-or-equal-to `$b`.

Each iteration, we set `$c` equal to a `-f`ormatted string of `yyyyMMdd` style, based on `$a`. We then compare if that's `-eq`ual to `$c` reversed (using an array-join trick). If so, we output `$a` in the proper format. Either way, we increment `$a` with `.AddDays(1)` to move to the next day.

### Example

```
PS C:\Tools\Scripts\golfing> .\forecast-palindromic-dates.ps1 '06/23/2016' '12/12/2020'
02/02/2020

```
> 5 votes

# Answer
# Julia, 132 bytes

```
f(a,b,t=s->DateTime(s,"mm/dd/y"),g=d->Dates.format(d,"mm/dd/yyyy"))=map(g,filter(d->(r=replace(g(d),"/",""))==reverse(r),t(a):t(b)))

```

This is a function that accepts two strings and returns an array of strings.

Ungolfed:

```
function f(a, b)
    # Define a function to create a DateTime object from a string
    t = s -> DateTime(s, "mm/dd/y")

    # Define a function to create a string from a DateTime object
    g = d -> Dates.format(d, "mm/dd/yyyy")

    # Filter the range a:b to palindromic dates
    p = filter(d -> (r = replace(g(d), "/", "")) == reverse(r), t(a):t(b))

    # Format all dates in the array
    m = map(g, p)

    return m
end

```

Try it online!
> 4 votes

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

```
(s,e)=>{for(r=[],s=Date.parse(s),e=Date.parse(e);s<=e;s+=864e5){d=new Date(s).toJSON().slice(0,10);`${a=d.match(/\d/g)}`==a.reverse()&&r.push(d)}return r}

```

I/O in ISO format. Ungolfed:

```
function date_palindrome(start, end) {
    start = Date.parse(start);
    end = Date.parse(end);
    var result = [];
    while (start <= end) {
        var date = new Date(start).toISOString().slice(0, 10);
        var digits = date.match(/d/g);
        if (digits.join() == digits.reverse.join()) {
            result.push(date);
        }
        start += 24 * 60 * 60 * 1000; // ms
    }
    return result;
}

```
> 3 votes

# Answer
# Java 7, ~~436~~ ~~435~~ 416 bytes *\*sigh..\**

```
import java.text.*;import java.util.*;void c(String...a)throws Exception{DateFormat f=new SimpleDateFormat("dd-MM-yyyy");Calendar s=Calendar.getInstance(),e=Calendar.getInstance();s.setTime(f.parse(a[0]));e.setTime(f.parse(a[1]));for(Date d=s.getTime();s.before(e);s.add(5,1),d=s.getTime()){String o=f.format(d),x=o.replaceAll("\\W|_",""),w="";for(char c:x.toCharArray())w=c+w;if(x.equals(w))System.out.println(o);}}

```

**Input & Output format:** `dd-MM-yyyy`

**Ungolfed & test code:**

Try it here.

```
import java.text.*;
import java.util.*;

class Main{
  static void c(String... a) throws Exception{
    DateFormat f = new SimpleDateFormat("dd-MM-yyyy");
    Calendar s = Calendar.getInstance(),
             e = Calendar.getInstance();
    s.setTime(f.parse(a[0]));
    e.setTime(f.parse(a[1]));
    for(Date d = s.getTime(); s.before(e); s.add(Calendar.DATE, 1), d = s.getTime()){
      String o = f.format(d),
             x = o.replaceAll("\\W|_", ""),
             w = "";
      for(char c : x.toCharArray()){
        w = c + w;
      }
      if(x.equals(w)){
        System.out.println(o);
      }
    }
  }

  public static void main(String[] a){
    try{
      c("05-02-2050", "12-12-2060");
    } catch (Exception e){}
  }
}

```

**Output:**

```
05-02-2050
15-02-2051
25-02-2052
06-02-2060

```
> 2 votes

# Answer
# TSQL, 88 bytes

Using ISO8601 format for date(yyyy-mm-dd)

```
DECLARE @ date='2050-05-02',@t date='2060-12-12'

a:IF stuff(reverse(@),3,1,'')=stuff(@,8,1,'')PRINT @
SET @=dateadd(d,1,@)IF @<=@t GOTO a

```

Fiddle
> 2 votes

# Answer
**Oracle 11: SQL: 246 bytes** (hey, at least I beat Java :P lol )

```
with d as(select to_date('&1','yyyy-mm-dd')s,to_date('&2','yyyy-mm-dd')e from dual),r as(select level-1 l from d connect by level<=e-s+1),x as(select s+l y,to_char(s+l,'yyyymmdd')w from d,r)select to_char(y,'yyyy-mm-dd')from x where w=reverse(w);

```

**Output:**

```
  SQL> with d as(select to_date('&1','yyyy-mm-dd')s,to_date('&2','yyyy-mm-dd')e from dual),r as(select level-1 l from d connect by level<=e-s+1),x as(select s+l y,to_char(s+l,'yyyymmdd')w from d,r)select to_char(y,'yyyy-mm-dd')from x where w=reverse(w);
  Enter value for 1: 2000-01-01
  Enter value for 2: 2021-01-01

  TO_CHAR(Y,
  ----------
  2001-10-02
  2010-01-02
  2011-11-02
  2020-02-02

  SQL>

```

**In readable format:**

```
  with d as (select to_date('&1','yyyy-mm-dd') s,
                    to_date('&2','yyyy-mm-dd') e
              from dual),
        r as (select level-1 l
                from d connect by level <= e-s+1),
        x as (select s+l y, to_char(s+l,'yyyymmdd') w
                from d,r)
  select to_char(y,'yyyy-mm-dd')
    from x
   where w=reverse(w);

```

**Explained:**

```
d: get input for start/end
r: generate rows needed, 1 per day.
x: calculate the actual dates, and convert them to a minimal string.
final: use REVERSE function to verify the palindroms, return in proper format.

```

Learned about the REVERSE function today :)
> 1 votes

# Answer
# C#, ~~97~~ 94 bytes

```
(a,b)=>{for(;a<b;a=a.AddDays(1))if($"{a:yyy}".SequenceEqual($"{a:MMdd}".Reverse()))a.Dump();};

```

C# lambda (`Action`) where inputs are `DateTime` and the output is printed by using the `.Dump()` method (@EvilFonti's trick).

---

# C#, ~~115~~ 112 bytes

```
(a,b)=>{var r="";for(;a<b;a=a.AddDays(1))if($"{a:yyy}".SequenceEqual($"{a:MMdd}".Reverse()))r+=a+",";return r;};

```

C# lambda (`Func`) where inputs are `DateTime` and output is a `string`.

Code:

```
(a,b)=> {
    var r="";
    for(;a<b;a=a.AddDays(1)) {
        if($"{a:yyy}".SequenceEqual($"{a:MMdd}".Reverse()))
            r+=a+",";
    }
    return r;
};

```

---

Try them online!
> 1 votes

# Answer
# VBA, 240 193 bytes

```
Function f(a, b)
Dim j, g()
For i = CDate(a) To CDate(b)
    If Format(i, "yyyy") = StrReverse(Format(i, "mmdd")) Then
        ReDim Preserve g(j)
        g(j) = Format(i, "yyyy-mm-dd")
        j = j + 1
    End If
Next
f = g()
End Function

```

That's it in a comprehensible format. Test case:

```
Sub e()
MsgBox Join(f("5/2/2050", "6/2/2060"), ", ")
End Sub

```

Without that much redundancy:

```
Function f(a,b)
Dim j, g()
For i=CDate(a) To CDate(b)
If Format(i,"yyyy")=StrReverse(Format(i,"mmdd")) Then
ReDim Preserve g(j)
g(j)=Format(i,"yyyy-mm-dd")
j=j+1
End If
Next
f=g()
End Function

```
> 0 votes

# Answer
## Javascript (using external library) (158 bytes)

```
(a,b)=>_.RangeTo(a%1e20,b%1e20,864e5).Select(y=>new Date(y)).Where(x=>z=(_.From(x.toJSON()).Where(y=>!isNaN(y)).Take(8)).SequenceEqual(z.Reverse())).ToArray()

```

Link to lib: https://github.com/mvegh1/Enumerable

Code explanation: Ok, I finally used some actual code golfing here for once. So the inputs a,b are Date objects. Create a range of integers from a to b, where a and b are coerced into integers, and the distance between values in the range is 86400000, i.e the amount of ticks in one day. Map each value in the range to a date object. Filter that range by the predicate that represents palindromic dates. The logic to determine that is simple...cast the JSON string representation of the current date object to a char array using the library and filter out the non-numeric entries, and only take the first 8 values (because the that would be yyyyMMdd) and store that into variable z, then check if z is equivalent to z Reversed. Finally, cast back to native JS array

Edit: Shaved 2 bytes by removing unnecessary parens..
> 0 votes

# Answer
# Java, 269 bytes

```
import java.time.LocalDate;void q(String...a)throws Exception{LocalDate s=LocalDate.parse(a[0]);while(!s.isAfter(LocalDate.parse(a[1]))){String d=s.toString().replace("-","");if(d.equals(new StringBuffer(d).reverse().toString()))System.out.println(d);s=s.plusDays(1);}}

```

Ungolfed:

```
import java.io.IOException;
import java.time.LocalDate;

public class UnGolfedPalindromicDates {
    public static void main(String...a) throws IOException {
        LocalDate start = LocalDate.parse(a[0]), end = LocalDate.parse(a[1]);
        while (!start.isAfter(end)) {
            String d = start.toString().replace("-","");
            if (palindrome(d)) System.out.println(d);
            start = start.plusDays(1);
        }
    }

    public static boolean palindrome(String s) {
        return s.equals(new StringBuffer(s).reverse().toString());
    }
}

```
> 0 votes

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


title: Ordering words to fit in a given string

text:
# Question
Title: Ordering words to fit in a given string
Given a string of letters and a set of words, output an ordering of the words so that they can be found in the string by dropping letters that are not needed. Words may occur more than once in the word set. The input string and all words will consist of 1 to 1000 lower case letters each. The letters to be dropped may occur inside words or between words.

Your program or function can accept the letter string and words as lists, a string, or from STDIN, and must output all words in a correct order as a list or string output. If there is more than one correct solution, only output one of them. If there is no possible correct solution, output an empty list or an empty string.

Examples:

```
dogcatfrog cat frog dog
-> dog cat frog

xxcatfixsxhingonxgrapexxxfishingcxat cat grape catfish fishing
-> catfish grape fishing cat

dababbabadbaccbcbaaacdacdbdd aa bb cc dd ba ba ba ab ac da db dc
-> da ab ba ba ba cc bb aa ac dc db dd

flea antelope
->
(no solution)

```

This is code golf. Lowest number of bytes wins.

*Edit: Explained that extra characters can be inside words.*

# Answer
> 5 votes
# Pyth, ~~20~~ 24 bytes

My first attempt on Pyth :)

```
Jcw;FG.ptJI:hJj".*"G0jdG

```

How it works:

```
Jcw;FG.ptJI:hJj".*"G0jdG
Jcw                         assign("J",chop(input()))
    FG.ptJ                  for G in permutations(tail(J)):
          I:hJj".*"G0        if match(head(J),join(".*",G)):
                     jdG      print(join(" ",G))

```

Notes: it takes a long time in the third example (`dababbabadbaccbcbaaacdacdbdd aa bb cc dd ba ba ba ab ac da db dc`).

# Answer
> 5 votes
# Pyth, 10 bytes

```
h@s./Myz.p

```

Demonstration

This program is very much brute force. It first constructs every subset of the input, then every partition of the subsets, then checks for the first one which is a reordering of the word list. No possibilities is handled via erroring with no output to stdout, which is allowed by meta consensus. The error can be removed for 2 extra bytes.

Note that for many of the given test cases, the program will not complete in a reasonable period of time.

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

```
(s,a,t=``,...r)=>a[0]?a.find((w,i)=>(b=[...a],b.splice(i,1),f(s,b,w+t,w,...r)))&&q:~s.search(t.split``.join`.*`)&&(q=r)

```

Accepts a string and an array of words and returns an array of words or `undefined` on failure. Add 2 bytes if it must return the empty string on failure (`?q:```), in which case this alternative version is only 120 bytes and returns the empty string on failure, and can even save 2 bytes if it's allowed to return 0 on failure:

```
(s,a,t=``,...r)=>a[0]?a.reduce((q,w,i)=>q||(b=[...a],b.splice(i,1),f(s,b,w+t,w,...r)),0):~s.search([...t].join`.*`)?r:``

```

(After writing this I noticed that the algorithm is basically the same as @KennyLau's Pyth answer.)

Edited edit: updated after clarification of question, but is now *really* slow on the third test case; I set it off the night before last and this morning I've just noticed that it has actually found the solution, somewhere between 30 and 40 hours later. I was really mean though and fed the solution to it (it works best with the reversed solution, which it will verify instantly).

# Answer
> 1 votes
# Java 7, 256 bytes

```
import java.util.*;String c(String...a){Map s=new HashMap();int j,i=1,l=a[0].length();for(;i<a.length;i++)if((j=a[0].indexOf(a[i]))>-1)s.put(j,s.get(j)!=null?s.get(j)+" "+a[i]:a[i]);a[0]="";for(j=0;j<l;j++)a[0]+=s.get(j)!=null?s.get(j)+" ":"";return a[0];}

```

It should definitely be possible to golf this more by using a different approach, but this will do for now..

**Ungolfed & test code:**

Try it here.

```
import java.util.*;
class M{
  static String c(String... a){
    Map s = new HashMap();
    int j,
        i = 1,
        l = a[0].length();
    for(; i < a.length; i++){
      if((j = a[0].indexOf(a[i])) > -1){
        s.put(j, s.get(j) != null
                  ? s.get(j) + " " + a[i]
                  : a[i]);
      }
    }
    a[0] = "";
    for(j = 0; j < l; j++){
      a[0] += s.get(j) != null
               ? s.get(j) + " "
               : "";
    }
    return a[0];
  }

  public static void main(String[] a){
    System.out.println(c("dogcatfrog", "cat", "frog", "dog"));
    System.out.println(c("xxcatfixsxhingonxgrapexxxfishingcxat", "cat", "grape", "catfish", "fishing"));
    System.out.println(
        c("dababbabadbaccbcbaaacdacdbdd ", "aa", "bb", "cc", "dd", "ba", "ba", "ba", "ab", "ac", "da", "db", "dc"));
    System.out.println(c("flea", "antelope"));
  }
}

```

**Output:**

```
dog cat frog
cat grape fishing
da ab ba ba ba bb db ac cc aa dd

```

# Answer
> 1 votes
# Groovy (44 Bytes)

I can't believe nobody else used regexes for this...

```
{a,b->a.findAll(/${b.join('|')}/).join(" ")}

```

## Explanation

`/${b.join('|')}/` \- Create a regex to find any of the words in a string.
`.findAll(...)` \- Find and collect all occurrences in the string into an array.
`.join(" ")` \- Join the array together with spaces.

Basically, if there aren't any occurrences, the array is empty and returns an empty string implicitly. If it does find occurrences, it returns an array object with the occurrences then flattens it into a string.

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


title: World Time Conversion

text:
# Question
Title: World Time Conversion
# World Time Conversion

### Challenge:

Given an initial clock time in UTC and a list of countries: for each country in the list, output the local time it is in that country based on the initial time. In cases where a country is big enough to have multiple local time zones (like the United States), you may output *any* valid local time for that country, provided you state which time zone you are using (i.e. for United States, EST for Eastern Standard Time). You do not have to worry about daylight savings time.

### Input:

The current time, in UTC, followed by a list of countries. The format of the *input* time can be given in any way (12 or 24 hour, with or without seconds, etc), and the countries can all be on the same line or on new lines after the time, your choice. You may also use any characters to delimit the countries (space, comma, etc.). You may choose to take a list of country -\> timezone in as input, in which case I would prefer a common list be used across all answers, found here. This part can be excluded from your byte count.

### Output:

The local time in each country from the input list. Once again, you may use any characters or newline to delimit the times for each country so long as it is easy to tell one time from another. However, unlike the input, the times must be output in a 12 hour format (so there must be an AM/PM indication). Other than that, you may express the digits in the time in any format (i.e. leading 0's for hours that are single digits, with or without seconds/milliseconds) as long as the character that is used to separate hours and minutes is **different** than the character that is used to separate the different times. I would prefer if a date was not included in the answer since this is a challenge dealing specifically with different times.

### Examples:

Input 1:

```
12:00 AM [United States]

```

Output 1:

```
7:00 PM EST (or any other time zone with the appropriate time)

```

Input 2:

```
12:00 PM [United States, Italy, Russia]

```

Output 2:

```
4:00 AM PST, 2:00 PM, 3:00 PM MSK

```

### Rules:

This is , so shortest code in bytes wins. Standard loopholes are forbidden.

### Common list of country -\> timezone:

```
// Format:  <country>,<UTC offset>,<time-zone abbreviation>
// You may use any alternate format or any other UTC/abbreviation for a country for those that have more than one zone
France,1,CET
United States,-5,EST
Russia,3,MSK
United Kingdom,0,UTC
Australia,10,AEST
Canada,-5,EST
Kingdom of Denmark,1,CET
New Zealand,12,NZST
Brazil,-3,BRT
Mexico,-6,MDT
Indonesia,7,WIST
Kiribati,12,LINT
Chile,-3,CLT
Democratic Republic of the Congo,1,WAT
Ecuador,-5,ECT
Federated States of Micronesia,11,KOST
Kazakhstan,6,ALMT
Kingdom of the Netherlands,1,CET
Mongolia,8,ULAT
Papua New Guinea,10,AEST
Portugal,0,WET
South Africa,2,SAST
Spain,1,CET
Afghanistan,4.5,AFT
Albania,1,CET
Algeria,1,CET
Andorra,1,CET
Angola,1,WAT
Antigua and Barbuda,-4,AST
Argentina,-3,ART
Armenia,4
Austria,1,CET
Azerbaijan,4
Bahamas,-5,EST
Bahrain,3
Bangladesh,6,BDT
Barbados,-4
Belarus,3,FET
Belgium,1,CET
Belize,-6
Benin,1,WAT
Bhutan,6,BTT
Bolivia,-4
Bosnia and Herzegovina,1,CET
Botswana,2,CAT
Brunei,8
Bulgaria,2,EET
Burkina Faso,0,UTC
Burundi,2,CAT
Cambodia,7
Cameroon,1,WAT
Cape Verde,-1,CVT
Central African Republic,1,WAT
Chad,1,WAT
China,8,CST
Colombia,-5
Comoros,3,EAT
Republic of the Congo,1,WAT
Costa Rica,-6
Croatia,1,CET
Cuba,-5
Cyprus,2,EET
Czech Republic,1,CRT
Djibouti,3,EAT
Dominica,-4
Dominican Republic,-4
East Timor,9
Egypt,2,EET
El Salvador,-6
Equatorial Guinea,1,WAT
Eritrea,3,EAT
Estonia,2,EET
Ethiopia,3,EAT
Fiji,12
Finland,2,EET
Gabon,1,WAT
Gambia,0,GMT
Georgia,4
Germany,1,CET
Ghana,0,GMT
Greece,2,EET
Grenada,-4
Guatemala,-6
Guinea,0,GMT
Guinea-Bissau,0,GMT
Guyana,-4
Haiti,-5
Honduras,-6
Hong Kong,8,HKT
Hungary,1,CET
Iceland,0,GMT
India,5.5,IST
Iran,3.5,IRST
Iraq,3
Ireland,0,WET
Israel,2,IST
Italy,1,CET
Ivory Coast,0,GMT
Jamaica,-5
Japan,9,JST
Jordan,2
Kenya,3,EAT
North Korea,8.5,PYT
South Korea,9,KST
Kuwait,3,AST
Kosovo,1
Kyrgyzstan,6
Laos,7
Latvia,2,EET
Lebanon,2,EET
Lesotho,2
Liberia,0,GMT
Libya,2,EET
Liechtenstein,1,CET
Lithuania,2,EET
Luxembourg,1,CET
Macau China,8,CST
Macedonia,1,CET
Madagascar,3,EAT
Malawi,2,CAT
Malaysia,8,MYT
Maldives,5
Mali,0,GMT
Malta,1,CET
Marshall Islands,12
Mauritania,0,GMT
Mauritius,4,MUT
Moldova,2,EET
Monaco,1,CET
Montenegro,1,CET
Morocco,0,WET
Mozambique,2,CAT
Myanmar,6.5,MST
Namibia,1,WAT
Nauru,12
Nepal,5.75,NPT
Nicaragua,-6
Niger,1,WAT
Nigeria,1,WAT
Norway,1,CET
Oman,4
Pakistan,5,PKT
Palau,9
Panama,-5
Paraguay,-4
Peru,-5,PET
Philippines,8,PHT
Poland,1,CET
Qatar,3,AST
Romania,2,EET
Rwanda,2,CAT
Saint Kitts and Nevis,-4
Saint Lucia,-4
Saint Vincent and the Grenadines,-4
Samoa,13
San Marino,1,CET
São Tomé and Príncipe,0,GMT
Saudi Arabia,3,AST
Senegal,0,GMT
Serbia,1,CET
Seychelles,4,SCT
Sierra Leone,0,GMT
Singapore,8,SST
Slovakia,1,CET
Slovenia,1,CET
Solomon Islands,11
Somalia,3,EAT
South Sudan,3,EAT
Sri Lanka,5.5,SLST
Sudan,3,EAT
Suriname,-3
Swaziland,2
Sweden,1,CET
Switzerland,1,CET
Syria,2,EET
Taiwan,8
Tajikistan,5,
Tanzania,3,EAT
Thailand,7,THA
Togo,0,GMT
Tonga,13
Trinidad and Tobago,-4
Tunisia,1,CET
Turkey,2,EET
Turkmenistan,5
Tuvalu,12
Uganda,3,EAT
Ukraine,2,EET
United Arab Emirates,4
Uruguay,-3
Uzbekistan,5,UZT
Vanuatu,11,
Vatican City,1,CET
Venezuela,-4
Vietnam,7,ICT
Yemen,3
Zambia,2,CAT
Zimbabwe,2,CAT

```

# Answer
> 5 votes
## PowerShell v3+, 71 bytes

```
param($a,$b,$x)$b|%{$y=$x[$_];"{0:t} $($y[1])"-f(date $a).AddHours($y[0])}

```

(74 bytes, -3 bytes for input `,$x`, the dictionary of country-\>timezone conversions, equals 71 bytes)

Uses the below dictionary/hashtable for the timezone conversion, which I manually created (with some creative Excel, PowerShell, and Ctrl-H help) based on the Wikipedia link.

```
$x=@{'France'=(1,'CET');'United States'=(-5,'EST');'Russia'=(3,'Moscow');'United Kingdom'=(0,'UTC');'Australia'=(10,'AEST');'Canada'=(-5,'EST');'Kingdom of Denmark'=(1,'CET');'New Zealand'=(12,'NZST');'Brazil'=(-3,'BRT');'Mexico'=(-6,'Zona Centro');'Indonesia'=(7,'WIST');'Kiribati'=(12,'Gilbert');'Chile'=(-3,'CLT');'Democratic Republic of the Congo'=(1,'WAT');'Ecuador'=(-5,'Ecuador Time');'Federated States of Micronesia'=(11,'Kosrae');'Kazakhstan'=(6,'Almaty');'Kingdom of the Netherlands'=(1,'CET');'Mongolia'=(8,'Ulaanbaatar');'Papua New Guinea'=(10,'AEST');'Portugal'=(0,'WET');'South Africa'=(2,'SAST');'Spain'=(1,'CET');'Afghanistan'=(4.5,'Afghanistan');'Albania'=(1,'CET');'Algeria'=(1,'CET');'Andorra'=(1,'CET');'Angola'=(1,'WAT');'Antigua and Barbuda'=(-4,'AST');'Argentina'=(-3,'ART');'Armenia'=(4,'');'Austria'=(1,'CET');'Azerbaijan'=(4,'');'Bahamas'=(-5,'EST');'Bahrain'=(3,'');'Bangladesh'=(6,'BDT');'Barbados'=(-4,'');'Belarus'=(3,'FET');'Belgium'=(1,'CET');'Belize'=(-6,'');'Benin'=(1,'WAT');'Bhutan'=(6,'BTT');'Bolivia'=(-4,'');'Bosnia and Herzegovina'=(1,'CET');'Botswana'=(2,'CAT');'Brunei'=(8,'');'Bulgaria'=(2,'EET');'Burkina Faso'=(0,'UTC');'Burundi'=(2,'CAT');'Cambodia'=(7,'');'Cameroon'=(1,'WAT');'Cape Verde'=(-1,'CVT');'Central African Republic'=(1,'WAT');'Chad'=(1,'WAT');'China'=(8,'Chinese Standard Time');'Colombia'=(-5,'');'Comoros'=(3,'EAT');'Republic of the Congo'=(1,'WAT');'Costa Rica'=(-6,'');'Croatia'=(1,'CET');'Cuba'=(-5,'');'Cyprus'=(2,'EET');'Czech Republic'=(1,'CRT');'Djibouti'=(3,'EAT');'Dominica'=(-4,'');'Dominican Republic'=(-4,'');'East Timor'=(9,'');'Egypt'=(2,'EET');'El Salvador'=(-6,'');'Equatorial Guinea'=(1,'WAT');'Eritrea'=(3,'EAT');'Estonia'=(2,'EET');'Ethiopia'=(3,'EAT');'Fiji'=(12,'');'Finland'=(2,'EET');'Gabon'=(1,'WAT');'Gambia'=(0,'GMT');'Georgia'=(4,'');'Germany'=(1,'CET');'Ghana'=(0,'GMT');'Greece'=(2,'EET');'Grenada'=(-4,'');'Guatemala'=(-6,'');'Guinea'=(0,'GMT');'Guinea-Bissau'=(0,'GMT');'Guyana'=(-4,'');'Haiti'=(-5,'');'Honduras'=(-6,'');'Hong Kong'=(8,'HKT');'Hungary'=(1,'CET');'Iceland'=(0,'GMT');'India'=(5.5,'IST');'Iran'=(3.5,'IRST');'Iraq'=(3,'');'Ireland'=(0,'WET');'Israel'=(2,'IST');'Italy'=(1,'CET');'Ivory Coast'=(0,'GMT');'Jamaica'=(-5,'');'Japan'=(9,'JST');'Jordan'=(2,'');'Kenya'=(3,'EAT');'North Korea'=(8.5,'Pyongyang');'South Korea'=(9,'KST');'Kuwait'=(3,'AST');'Kosovo'=(1,'');'Kyrgyzstan'=(6,'');'Laos'=(7,'');'Latvia'=(2,'EET');'Lebanon'=(2,'EET');'Lesotho'=(2,'');'Liberia'=(0,'GMT');'Libya'=(2,'EET');'Liechtenstein'=(1,'CET');'Lithuania'=(2,'EET');'Luxembourg'=(1,'CET');'Macau (China)'=(8,'Macau');'Macedonia'=(1,'CET');'Madagascar'=(3,'EAT');'Malawi'=(2,'CAT');'Malaysia'=(8,'Malaysia');'Maldives'=(5,'');'Mali'=(0,'GMT');'Malta'=(1,'CET');'Marshall Islands'=(12,'');'Mauritania'=(0,'GMT');'Mauritius'=(4,'Mauritius');'Moldova'=(2,'EET');'Monaco'=(1,'CET');'Montenegro'=(1,'CET');'Morocco'=(0,'WET');'Mozambique'=(2,'CAT');'Myanmar'=(6.5,'MST');'Namibia'=(1,'WAT');'Nauru'=(12,'');'Nepal'=(5.75,'Nepal');'Nicaragua'=(-6,'');'Niger'=(1,'WAT');'Nigeria'=(1,'WAT');'Norway'=(1,'CET');'Oman'=(4,'');'Pakistan'=(5,'PKT');'Palau'=(9,'');'Panama'=(-5,'');'Paraguay'=(-4,'');'Peru'=(-5,'PET');'Philippines'=(8,'PHT');'Poland'=(1,'CET');'Qatar'=(3,'AST');'Romania'=(2,'EET');'Rwanda'=(2,'CAT');'Saint Kitts and Nevis'=(-4,'');'Saint Lucia'=(-4,'');'Saint Vincent and the Grenadines'=(-4,'');'Samoa'=(13,'');'San Marino'=(1,'CET');'São Tomé and Príncipe'=(0,'GMT');'Saudi Arabia'=(3,'AST');'Senegal'=(0,'GMT');'Serbia'=(1,'CET');'Seychelles'=(4,'Seychelles');'Sierra Leone'=(0,'GMT');'Singapore'=(8,'SST');'Slovakia'=(1,'CET');'Slovenia'=(1,'CET');'Solomon Islands'=(11,'');'Somalia'=(3,'EAT');'South Sudan'=(3,'EAT');'Sri Lanka'=(5.5,'SLST');'Sudan'=(3,'EAT');'Suriname'=(-3,'');'Swaziland'=(2,'');'Sweden'=(1,'CET');'Switzerland'=(1,'CET');'Syria'=(2,'EET');'Taiwan'=(8,'');'Tajikistan'=(5,'');'Tanzania'=(3,'EAT');'Thailand'=(7,'THA');'Togo'=(0,'GMT');'Tonga'=(13,'');'Trinidad and Tobago'=(-4,'');'Tunisia'=(1,'CET');'Turkey'=(2,'EET');'Turkmenistan'=(5,'');'Tuvalu'=(12,'');'Uganda'=(3,'EAT');'Ukraine'=(2,'EET');'United Arab Emirates'=(4,'');'Uruguay'=(-3,'');'Uzbekistan'=(5,'Uzbekistan');'Vanuatu'=(11,'');'Vatican City'=(1,'CET');'Venezuela'=(-4,'');'Vietnam'=(7,'Indochina');'Yemen'=(3,'');'Zambia'=(2,'CAT');'Zimbabwe'=(2,'CAT')}

```

Takes input `$a` as a string in 24hr format, `$b` as an explicit array of strings, and the dictionary `$x`. Loops through `$b`, and for each creates a new `Date` based on `$a`, then calls `.AddHours`, indexing into the dictionary to determine how many, and uses the `-f`ormat operator to pull out the correct information.

### Example

```
PS C:\Tools\Scripts\golfing> .\world-time-conversion.ps1 '12:00' @('United States','Italy','Russia','Nepal') $x
7:00 AM EST
1:00 PM CET
3:00 PM Moscow
5:45 PM Nepal

```

# Answer
> 4 votes
# Python 2, ~~154 153 151 148 147 138 134 131 123 121~~ 116 bytes

-4 bytes thanks to @Shebang (missed a div `//` to `/` Py3 -\> Py2 conversion; print time zone using unpacking; use map to replace two `int` casts)

```
def f(t,c,d):
 for x in c:a,b=map(int,t.split(':'));e,z=d[x];v=60*a+b+e;print`v/60%12`+':'+`v%60`,'pa'[v%1440<720],z

```

**repl.it** (I only bothered with a tiny subset of countries, as that's a chore and I'm lazy - but I included Nepal to have a non-standard offset in there & Tuvalu with it's +12:00 one).

Input is `t` the time string in 24 hr format; `c` the list of countries; and `d` a dictionary of country string to tuple of minutes offset and time zone name.

Prints a 12hr format plus time zone for each country split by new lines. Leading zeros are not printed `AM`/`PM` indicator is just `a`/`p` (e.g. 08:06 in Nepal prints as `8:6 a Nepal Time`)

# Answer
> 2 votes
# bash (126 bytes)

```
w(){ cd /u*/sh*/z*
join -o2.2 <(egrep "$2" i*) <(cut -sf1,3 zone.*)|while read z
do TZ=$z date -d"UTC$1" +"%z %r";done|uniq;}
w 12:00PM "United States|Italy|Russia"

```

uses GNU date and file:/usr/share/zoneinfo/{iso3166,zone}.tab

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


# Question
Title: Given a string, Return its Cumulative Delta
*Related*

# Explanation

Given a string such as `DCBA`, convert it to ASCII ordinals, such as `68 67 66 65`. Then, take the differences between each value, eg `67 - 68 = -1, 66 - 67 = -1...` giving `-1 -1 -1` Now as long as there is more than 1 left over value, repeat getting the differences.

For a 3 letter string, your pathway should be similar to

```
A   F   G
65  70  71
-5  -1
-4

```

And for a 5 letter string...

```
B   A   C   E   D   F
66  65  67  69  68  70
1   -2  -2  1   -2
3   0   -3  3
3   3   -6
0   9
-9

```

# The Challenge

Take a string input through any Standard IO Method, and output the value of the cumulative delta as described above.

# Test Cases

```
input: cows
output: 8

input: helloworld
output: 905

input: aaaaaa
output: 0

input: abcdef
output: 0

input: ghfie
output: 20

input: CODEGOLF
output: 185

```

# Rules

* Standard Loopholes Apply
* The input will only consist of ASCII letters that are either all uppercase or all lowercase
* Your code MUST work for both lower and upper case.
* The input will contain at least 2 characters.
* The output may be positive or negative, as long as its absolute value matches the absolute value of the cumulative delta.
* This is marked as , as such, shortest answer in bytes wins!

# Answer
> 6 votes
# Jelly, ~~6~~ 4 bytes

-2 bytes thanks to @Dennis (implement a while loop)

```
OIṖ¿

```

**TryItOnline**
RunAllTestCases

### How?

```
OIṖ¿ - Main link: s
O     - cast to ordinals
  Ṗ¿  - while, ¿, pop last value, Ṗ, evaluates to True:
 I    -     find increments between consecutive values

```

# Answer
> 9 votes
# Python 3, 71 bytes

```
s=input();k=r=0
for c in s:r=ord(c)-r*k/(len(s)-k);k+=1
print(round(r))

```

Test it on Ideone.

### Alternate version, 58 bytes (inexact)

If an approximate result is enough – e.g., **-904.9999999999993 ≈ -905** for input **helloworld** – then the following solution works as well.

```
f=lambda s,k=1:len(s)and-~-len(s)*f(s[1:],k+1)/k+ord(s[0])

```

Test it on Ideone.

### Background

**Proposition** *Let* **f** *be a variadic function that maps the code points* **s0, ⋯, sn** *to their cumulative delta with sign* **(-1)n**, i.e.,

*Then*

**Proof** The statement is clearly true when **n = 0**. Suppose that it holds for **n - 1**, where **n \> 0**.

By the recursive definition of **f** and the hypothesis,

By induction, the statement holds for all non-negative values of **n**.

### How it works

Since

we can rewrite the proposition as follows.

The iterative implementation does precisely this. Numerators are computed by incrementing **k**, denominators by subtracting **k** from the length of the input string **s**, i.e., **n+1**.

Unfortunately, not all fractions will evaluate to integers, so the result is computed using floating point arithmetic and finally rounded to the nearest integer.

The recursive implementation does roughly the same, but it keeps track of the denominator via the auxiliary variable **k** and computes the numerator by subtracting **1** from the length of the remaining string (`~-len(s)`).

# Answer
> 7 votes
# MATL, 5 bytes

```
`dtnq

```

**Try it Online!** or here is a slightly modified version for all test cases.

**Explanation**

```
        % Implicitly grab the input as a string
`       % Do....while loop
    d   % Compute the difference between all consecutive ASCII codes
    tnq % Determine the current length and subtract 1
        % Implicit end of do...while. Evaluate (and consume) stack element and break out
        % of loop if it's 0.
        % Implicit end of loop and display

```

# Answer
> 3 votes
# J, 15 bytes

```
<:@#2&(-/\)3&u:

```

## Usage

```
   f =: <:@#2&(-/\)3&u:
   f 'cows'
8
   f 'helloworld'
_905
   f 'aaaaaa'
0
   f 'abcdef'
0
   f 'ghfie'
_20
   f 'CODEGOLF'
_185

```

## Explanation

```
<:@#2&(-/\)3&u:  Input: string S
           3&u:  Ordinal of each char
   #             Get the length of S
<:@                Decrement it
    2&(   )      Repeat len(s)-1 times on x = ordinal(S)
    2    \         For each pair of values
       -/            Reduce using subtraction
                   Return that as the next value of x
                 Return the final x as the result

```

# Answer
> 2 votes
# Python 2, ~~80~~ 73 bytes

Saving 7 bytes thanks to Dennis.

```
L=map(ord,input())
while L[1:]:L=[x-y for x,y in zip(L,L[1:])]
print L[0]

```

Requires input to be given in quotes, e.g. `"helloworld"`

# Answer
> 2 votes
# 05AB1E, 7 bytes

```
ÇDgG¥}`

```

Try it online!

**Explanation**

```
Ç        # convert to list of ascii codes
 DgG }   # length-1 times do:
    ¥    # take deltas
      `  # pop the single value left in the list and output

```

# Answer
> 1 votes
## Racket 147 bytes

```
(let p((l(map char->integer(string->list s))))(if(= 1(length l))(car l)(p
(for/list((i(range 1(length l))))(-(list-ref l(- i 1))(list-ref l i))))))

```

Ungolfed:

```
(define (f s)
  (let loop ((lst (map char->integer (string->list s))))
    (if (= 1 (length lst))
        (first lst)
        (loop (for/list ((i (range 1 (length lst))))
                (- (list-ref lst (sub1 i))
                   (list-ref lst i))
                )))))

```

Testing:

```
(f "AFG")
(f "BACEDF")
(f "cows")
(f "helloworld")
(f "abcdef")
(f "aaaaaa")
(f "ghfie")
(f "CODEGOLF")

```

Output:

```
-4
-9
8
-905
0
0
-20
-185

```

# Answer
> 1 votes
# RProgN, 17 Bytes

```
►Sb]L1-1\1:[d}P

```

## Explination

```
►                   # Spaceless segment
 Sb                 # Convert the input to a stack, convert the stack of strings to a stack of ordinals.
   ]L               # Push a duplicate of that stack, pop it and push the length in its place
     1-             # Subtract 1 from the length.
       1\1          # Push a one, slide it under the top value, push another one, such that 1 LENGTH 1
          :  }      # For (i=1; i<=LENGTH; i+=1)
           [d       # Pop the iterator, pop the current stack, push the delta stack representing it.
              P     # Pop the top value of the stack, push it to the reg stack, and implicitly print.

```

I used (A version of) this script to test the question itself. I thought I might as well share it.

Try It Online!

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

```
g[x]=x
g x=g$zipWith(-)=<<tail$x
g.map fromEnum

```

Usage example: `g.map fromEnum $ "CODEGOLF"`-\> `185`.

`map fromEnum` turns the string into a list of ascii values. If it has only a single element, return it, else build neighbor differences and check again.

# Answer
> 0 votes
## JavaScript (ES6), 116 bytes

Good that the input is more than 1 char so I can use `s.length` for both Arrays and Strings!

Snippet referenced from Neil's answer on another question :P

```
d=k=>/\d/.test(k)?k:k.charCodeAt(0);r=x=>(a=[...x],a.pop(),a.map((c,i)=>d(c)-d(x[i+1])));f=s=>s.length-1?f(r(s)):s[0]
```

```
<input oninput=o.textContent=this.value&&f(this.value)><pre id=o>
```

# Answer
> 0 votes
# Brain-Flak, 97 bytes

```
([][()]<>){<>([][()]){({}[()]<({}[({})]<>)><>)}{}{}<>([]){({}[()]<({}<>)<>>)}{}<>({}<>[()])}<>

```

Try it online!

This is 97 bytes of code, plus 3 bytes for the `-a` flag, which enables ASCII input.

This would be a lot simpler if we didn't have to worry about the difference between characters sometimes being zero. Instead, we have to muck around with reversing the stack and pushing stack height several times.

Explanation:

```
Push the stack height onto the alternate stack
([][()]<>)

While this stack is non-empty:
{

    Move back
    <>

    Push the height of the stack minus one
    ([][()])

    While true
    {

        Decrement the stack height counter
        ({}[()]

        Move the difference over to the other stack
        <({}[({})]<>)><>)

    }

    Pop the last value and the left-over counter
    {}{}

    Move on to the other stack
    <>

    Move everything back
    ([]){({}[()]<({}<>)<>>)}

    Pop the counter
    {}<>

    Move the step number minus one back
    ({}<>[()])

End
}

Move back one last time
<>

```

# Answer
> 0 votes
## R, 58 bytes

```
x=rev(utf8ToInt(readline()));while(length(x)>1)x=diff(x);x

```

`diff()` in R works differently than the difference defined in this challenge. Therfore we have reverse the vector (using `rev`) prior to taking the difference the first time.

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


title: Randomized Pumpkin Patch

text:
# Question
Title: Randomized Pumpkin Patch
I was walking through a pumpkin patch the other day for a birthday party, and noticed the pumpkin vines making a nifty pattern, with whirls, loops, and offshoots. We're going to simulate that here with some ASCII art.

```
          (())
            \
   p--q      p-----q
  /    \    /       \
(())    b--d       (())

```

### Vine Construction Rules

* There is only one main vine, composed solely of `\ / - p q b d` characters.
* The vine only travels from left to right across the screen. In other words, suppose you were an ant starting at the left-most vine character. As you progress to the next adjacent character on the main vine, you *must* move one column to the right - never to the left.
* When the vine changes direction, one of the `p q b d` characters are required to simulate a loop. The `p` joins vines traveling northeast to east, the `q` for east to southeast, the `b` from southeast to east, and the `d` from east to northeast. Note that the "loop" of the letter connects to the horizontal vine, and the "stem" of the letter connects to the diagonal.
* The beginning of the vine must be one of `p` or `b` (your choice, doesn't have to be random), and starts horizontally. The end of the vine must be one of `q` or `d` (your choice, doesn't have to be random), and must end horizontally.
* Note that loops can be placed immediately adjacent to other loops (e.g., `pd` is a valid substring of the vine), but that may make it more difficult to place the pumpkins later. You may want to always have one of `- / \` immediately after a loop (as I did in my examples), but it's not required.

### Pumpkin Rules

* The pumpkins are composed solely of `(())` (this exact string).
* From the main vine, the pumpkins are attached by offshoots. These offshoots can only be attached to the `p q b d` loops, are precisely one `\` or `/` in length, and attach to the pumpkin so the "end" of the offshoot is in the middle.
* They can connect above or below the main vine.
* The offshoots can connect going to the "left."
* Only one pumpkin can attach per offshoot, and only one offshoot per loop.

### Randomness

* When traveling horizontally, the vine has a 50% chance of continuing horizontally, a 25% chance of turning northeast, and a 25% chance of turning southeast.
* When traveling diagonally, the vine has a 90% chance of turning horizontal and a 10% chance of continuing diagonally.
* There must be sufficient turns to support the input number of pumpkins, though more turns are allowed.
* Once the vine is constructed, pumpkins can be randomly placed at any corner not already occupied by a pumpkin.
* Pumpkins cannot overlap the vine or other pumpkins.

### The Challenge

Given an input number, output a randomized pumpkin patch following the above rules. Executing the code multiple times with the same input should yield different results. All possible pumpkin patches for a given input number should have some (not necessarily equal) non-zero chance of occurring.

### Input

A single integer `n` representing the number of pumpkins in the patch, in any convenient format. For brevity of code, you can assume the input is `0 < n < 256`.

### Output

The resulting pumpkin patch, either printed/displayed to the screen or returned as a string/string-array/etc.

### Rules

* This is so all the usual rules for golfing apply, and the shortest code (in bytes) wins.
* Use our standard definition of "Random."
* Either a full program or function are acceptable.
* Standard loopholes are forbidden.
* Leading and trailing whitespace / newlines are all completely optional.

### Examples

For input `n = 3`, here are some VALID examples of a pumpkin patch following the above rules (separated by blank newlines).

```
          (())
            \
   p--q      p-----q
  /    \    /       \
(())    b--d       (())

(()) (())
  \   /
   b-q (())
      \ /
       b-q

p-----------------------q (())
                       / \ /
                     (()) b-q
                           /
                         (())

```

Here are some INVALID examples for input `n = 3`, with explanations `#`.

```
    (()) (())
     /    /
p---q----q
 \
(())
# The vine continued horizontally after a loop was placed.

(()(())
  \ /
   p---q
        \
       (())
# The pumpkins are both overlapping and sprouting from the same loop.

p----------------q
 \      \         \
(())   (())      (())
# The pumpkin is attached to the middle of the vine, not at a loop.

```

# Answer
> 1 votes
## Python 2, 819 bytes

Takes `n` as input

Always places pumkpins on the 'outside' of corners (randomly left/right)

While the vine is constructed, pumpkins are added, and when enough pumpkins are there, the vine stops.

```
r=lambda:__import__('random').random()
s=1
v=[s]*4
U=[-9]
D=[-9]
i=input()
while len(U)+len(D)<i+2:s=[[0,1][r()<.9],[[0,2][r()<.5],1][r()<.5],[2,1][r()<.9]][s];exec['',[['','U+=[len(v)]'][U[-1]<len(v)-7],'',['','D+=[len(v)]'][D[-1]<len(v)-7]][v[-1]-s+1]][r()<.8];v+=[s]*[1,2][v[-1]!=s]
v+=[1]*5
m=M=s=0
for i in v:s+=i-1;m=[m,s][m>s];M=[M,s][M<s]
R=[[' ']*(M-m+5)for x in v]
m=-m+2
R[2][m]='p'
for x in range(3,len(v)-3):X=v[x-1];R[x][m]='/d p-b q\\'[v[x]*3+X];m+=v[x]-1
R[-3][m]='q'
M=[len(a)-len(a.lstrip())for a in map(''.join,R)]
R=map(list,zip(*R))
B,L,a='-/U'
K="\\"*4
W="""exec("for p in "+a+"[1:]:x=M[p];b=r()<.5;exec('R[x"+B+"1][p'+['+1]=\\""+L+"\\"','-1]=\\""+K+"\\"'][b]);i=p-[0,3][b];l='(';exec('R[x"+B+"2][i]=l;i+=1;'*2+'l=\\")\\";')*2")"""
exec W+";B,a='+D';L,K=K,L;"+W
for x in R:print''.join(map(str,x))

```

### Examples:

`n=4`

```
                (())
                 /
                p---q
 (())          /
   \       p--d
  p-q     /    \
     \   /    (())
      b-d
       \
      (())

```

`n=20`

```
                            (())
                              \
                            p--q
                           /    \
                          /      b--q
           (())     p----d      /    \
  (())       \     /          (())    b-q (())
    \         p---d                      \  \
  p--q       /     \                      b--q
      \     /     (())                   /    \                        (())                                           (())
       b---d                           (())    b-q                       \                                             /
        \                                         \          (())         p-q                                         p---q
       (())                                        \           \         /   \                                       /
                                                    b-----------q     p-d     b-q                            (())p--d
                                                                 \   /       /   \                            / /    \
                                                                  b-d      (())   b-q   (())  (())   p-q     p-d    (())
                                                                   /                 \   /      \   /   \   /
                                                                 (())                 b-q        p-d     b-d
                                                                                \ \      /         \
                                                                                (())b----d         (())
                                                                                /
                                                                                (())

```

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


title: Simulate keystrokes

text:
# Question
Title: Simulate keystrokes
Your job is to simulate a couple of keystrokes that a user types in.

**Input**

A string array or string with a delimiter of your choice (outside the range 32-126) containing at least one 'keystroke'.

This array will only contain two types of string: passive keystrokes (single chars) and commands (chars within brackets `[ ]`).

* Passive keystrokes
    1. ASCII character codes `[32-126]`
* Commands:
    1. `[B]` : backspace (remove last character added if there is one)
    2. `[C]` : copy all of what has already been written
    3. `[D]` : delete all of what has been written
    4. `[P]` : paste what has been copied

**Output**

The string produced by the keystrokes.

**Examples**

```
['H', 'e', 'l', 'l', 'o'] -> 'Hello'
['H', 'e', 'l', 'l', 'o', ' ', '[C]', '[P]'] -> 'Hello Hello '
['[D]', 'D', '[B]'] -> ''
['H', '[C]', 'i', '[P]', '[C]', '[P]'] -> 'HiHHiH'
['e', '[C]', '[B]', 'I', ' ', 'l', 'i', 'k', '[P]', ' ', 'b', '[P]', '[P]', 's', '!'] -> I like bees!
['N', '[P]'] -> 'N'
['#', '5', '0', 'K', '0', '0', '1', '[D]', '#', 'n', 'o', 't'] -> '#not'
['H', 'o', 'w', ' ', '[D]', 'H', 'e', 'y'] -> 'Hey'
['s', 'u', 'd', '[B]', 'p', '[C]', '[D]', 'I', ' ' , 'h', 'a', 'v', 'e', ' ', '[P]', 'p', 'e', 'r', '!'] -> 'I have supper!'

```

**This is , so shortest code in bytes wins!**

# Answer
> 7 votes
# 05AB1E, ~~34~~ ~~33~~ ~~31~~ 27 bytes

Uses CP-1252 encoding.

```
õUvygiyJë"XJ¨DU\"4äyáÇ5%è.V

```

Try it online!

**Explanation**

```
õU                                  # initialize X as the empty string
v                                   # for each y in input
 ygiyJ                              # if len(y) == 1 join y with stack
      ë                             # else
       "XJ¨DU\"                     # push this string
               4ä                   # split into 4 parts (of size [2,1,2,1])
                 yá                 # push only letters of y
                   Ç5%              # mod its ascii code by 5
                      è             # index into the string above with this
                       .V           # evaluate as 05AB1E code

```

The pairs of functions evaluated in the code above are:

```
DU    # [C] -> duplicate and store in X
XJ    # [P] -> push X and join with stack
¨     # [B] -> remove last char of string
\     # [D] -> remove top of stack

```

Saved 4 bytes using the `mod 5` trick from Lynn's CJam answer

# Answer
> 34 votes
# Vim, ~~76, 64, 62~~, 58 keystrokes

*Thanks to Loovjo for saving 7 keystrokes*

---

Did someone say **simulate keystrokes?** Well then, it's a good thing my favorite language to golf in is all *about* simulating keystrokes!

```
:no s :%s/\M[
sB]/<C-v><C-h>
sC]/<C-v><esc>0y$A
sD]/<C-v><esc>"_S
sP]/<C-v><C-r>"
s<bs>\n
S<C-r>"

```

Input comes in this format:

```
h
e
l
l
o

[C]
[P]

```

This is a pretty straightforward answer. It just translates each "command" to the vim keystroke equivalent of that command. Let's take it line by line.

```
:no s :%s/\M[

```

This saves a *ton* of bytes. Vim has a builtin "command line" where you can create mappings, change settings, save files, etc. Here we are creating a mapping. `:no` is short for `:nnoremap` which means "When we are in normal mode, substitute this left hand side for this right hand side." Since we are calling `:%s/` *five different times*, this saves a lot. The `\M` is a nice trick. It means that the following search will be "Very No Magic", which means that the regex `[B]` will match the literal text `[B]` rather than a range containing just a B in it. Since the majority of the substitute commands have a brackets in them, we fill in the first one.

Then, we call five substitute commands. It's worth noting why I called `<C-v>` so many times. Characters like `<esc>`, `<C-v>`, `<C-r>`, etc. are unprintable characters, and must be typed into the command line with a `<C-v>`.

* \[B\]: backspace. This one is pretty easy. Simply substitute each `[B]` with `Ctrl-h`, which is equivalent to backspace in vim.
* \[C\]: copy all of what has already been written. This is translated to `<esc>0y$A`. This means:

```
<esc>      " Escape to normal mode
     0     " Move to the beginning of this line
      y$   " Yank to the end of the line
        A  " Re enter insert mode at the end of this line.

```

We could *almost* simply do `Y` in place of `0y$` which means "yank the whole line", but this also grabs a newline that we don't want.
* \[D\]: delete all of what has been written. This is `<esc>"_S`. As before, `<esc>` exits insert mode so we can run commands. There are some things that are more convenient here. So we do

```
  S         " Delete this whole line and enter insert mode again
"_          " Send it to 'the black hole register'. This is just so that we don't overwrite the main register.

```
* \[P\]: paste what has been copied. This one is also very straightforward. It is just `<C-r>"` which means `Insert the contents of register '"'`. `"` happens to be the main register that 'y' yanks to.

Now that we have translated all of the commands, we must join all the lines together by removing all of the newline characters. Thanks to our mapping, this is just

```
s<bs>\n

```

The `<bs>` is a backspace, (ASCII 0x08) and we need it because of the `[` we filled in.

By now, we have translated the input into vim code, and we just need to run it. So we:

```
S           " Delete this whole line and enter insert mode
 <C-r>"     " Insert the keystrokes of register '"' as if they were typed by the user

```

# Answer
> 9 votes
# CJam, 33 bytes

```
q~{_[`';"];""L~""]:L~"]\1>3b=}%s~

```

Try it online!

## Explanation

```
q~                                  Read an evaluate input list.
  {                          }%     Map over each string in it:
   _                                 Duplicate the string, say S.
    [`';"];""L~""]:L~"]              Replace it the following list:
                                      [repr(S) '; "];" "L~" "]:L~"]
                       \             Bring S on top of the stack.
                        1>           Chop off the first char.
                          3b         Base-3 conversion.
                            =        Modular index into the list.
                               s~   Concatenate and run as CJam code.

```

The “hash function” `1>3b` maps

* single-character strings to **0** (= 0 mod 5),
* `[B]` to **291** (= 1 mod 5),
* `[D]` to **297** (= 2 mod 5),
* `[P]` to **333** (= 3 mod 5),
* `[C]` to **294** (= 4 mod 5).

This value (mod 5) is used as an index into a list of CJam code snippets:

* For single-character strings, say `h`, the snippet `"h"` is returned, which pushes a single-character string to the stack.
* For `[B]`, the snippet `;` is returned, which pops an element.
* For `[D]`, the snippet `];` is returned, which clears the stack.
* For `[P]`, the snippet `L~` is returned, which appends variable `L` onto the stack.
* For `[C]`, the snippet `]:L~` is returned, which stores the current stack in the variable `L`.

These snippets are concatenated and executed; the final stack is printed implicitly by CJam. `L` is initially the empty list, so the copy buffer is initially “empty”.

# Answer
> 7 votes
# JavaScript (ES6), ~~84~~ ~~80~~ ~~77~~ 76 bytes

*Saved 3 bytes thanks to @Neil, 1 more thanks to @edc65*

```
x=>x.reduce((s,[c,z])=>z<'C'?s.slice(0,-1):z<'D'?t=s:z<'P'?"":s+=z?t:c,t="")

```

`.map` is two bytes longer:

```
x=>x.map(([c,z])=>s=z<'C'?s.slice(0,-1):z<'D'?t=s:z<'P'?"":s+=z?t:c,s=t="")&&s

```

### Test snippet

```
f=x=>x.reduce((s,[c,z])=>z<'C'?s.slice(0,-1):z<'D'?t=s:z<'P'?"":s+=z?t:c,t="")

console.log(f(['e', '[C]', '[B]', 'I', ' ', 'l', 'i', 'k', '[P]', ' ', 'b', '[P]', '[P]', 's', '!']))
```

```
<button onclick="console.log(f(I.value.split('\n')))">Run</button>
<br><textarea id=I rows=10>H
e
l
l
o

[C]
[P]</textarea><br>
```

# Answer
> 7 votes
# Python 2, 96 95 93 bytes

```
r=c=""
for o in input():c=[c,r][x=="[C]"];r=[r+c,r[:-1],r,"",r+o][ord(o[1:2]or"E")%5]
print r

```

# Answer
> 7 votes
# Jelly, ~~50 51~~ 48 bytes

```
Ṿ”;;µṭ“Ṗ“ø©“ḣ0“;®”
L>1a2ị$i@“BCDP0”ịÇ
Ç€“⁶Ṗ©”;FV

```

**TryItOnline**
Or all test cases

### How?

```
Ṿ”;;µṭ“Ṗ“ø©“ḣ0“;®” - Link 1, CreateCodeLookupValueList: keystroke
      “Ṗ“ø©“ḣ0“;®” - list of strings, ["Ṗ","ø©","ḣ0"";®"] - these are Jelly code for:
                         Ṗ  : pop (i.e. delete last entry)
                         ø© : niladic separation and copy to register (i.e. copy)
                         ḣ0 : head to 0 (i.e. delete all entries)
                         ;® : concatenate with value of register (i.e. paste)
    µ              - monadic chain separation
Ṿ                  - uneval - make a Jelly code version of the keystroke
                                               e.g. "I" -> "“I”"
 ”;                - string literal ";"                      |
   ;               - concatenate e.g. ";I"                   v
     ṭ             - tack, to make the list ["Ṗ","ø©",";®","“I”"]
                             a keystroke - a command will evaluate to a string like
                             "“[C]”" but wont be accessed)

L>1a2ị$i@“BCDP0”ịÇ - Link 2, ConvertAKeystokeToJellyCodeString: keystroke
L>1                - length greater than 1? (i.e. isCommand?)
      $            - last two links as a monad
   a               - and
    2ị             - index 2 of the keystroke (0 due to and for a passive keystroke)
         “BCDP0”   - Literal string "BCP0"
       i@          - find first matching index of, with reversed arguments
                ị  - index into
                 Ç - call last link (1) as a monad (get code to replace this keystroke)

Ç€“⁶Ṗ©”;FV - Main link: list of keystrokes
Ç€         - call last link (2) as a monad (convert to Jelly code)
  “⁶Ṗ©”    - literal string "⁶Ṗ©" - setup the register with an empty string:
                 ⁶ :literal " ";
                 Ṗ : pop the space to give an empty string;
                 © : places it into the register
       ;   - concatenate (put that at the front)
        F  - flatten list (lists and strings are equivalent in Jelly)
         V - evaluate the string

```

For example

```
The input:
    ['e', '[C]', '[B]', 'I', ' ', 'l', 'i', 'k', '[P]', ' ', 'B', '[P]', '[P]', 's', '!']
Becomes the Jelly code:
    "⁶Ṗ©;“e”ø©Ṗ;“I”;“ ”;“l”;“i”;“k”;®;“ ”;“B”;®;®;“s”;“!”"
Which then evaluates to
    "I like Bees!"

```

\- with a capital `'B'` as a test case, since before I fixed a bug it would have returned `"I likeees!"`

# Answer
> 5 votes
# Perl, ~~53~~ 50 bytes

Includes +1 for `-p`

Give input on STDIN terminated by newlines (the last newline may be left out, so it counts as a string separated by newlines):

```
keystrokes.pl
H
e
[C]
[D]
a
b
[B]
[P]
z
^D

```

gives

```
aHez

```

`keystrokes.pl`:

```
#!/usr/bin/perl -p
$\.=/^.$/?$&:/P/?$a:(/C/?$a=$\:chop($\x=/B/))x0}{

```

Almost caught the Jelly answer but the fiend escaped to 48 bytes...

# Answer
> 4 votes
# Python ~~120 119~~ 116 bytes

```
f=lambda s,r='',c='':f(s[1:],*{'B':(r[:-1],c),'C':(r,r),'D':('',c),'P':(r+c,c),'':(r+s[0],c)}[s[0][1:2]])if s else r

```

**Ideone**

A recursive function with input, `s`, a list of the key-strokes.

Each recursive call updates the return text, `r` and, in the case of a `[C]`, the clipboard, `c` until `s` is empty.

The new values of `r` and `c` are found by indexing into a dictionary, `{...}`, and passed with unpacking, `*`. For the passive keystrokes `s[0][1:2]`will return an empty string and the key `''` will be used instead.

# Answer
> 4 votes
# Haskell, ~~136 133 130~~ 127 bytes

```
k c b(('[':m:_):i)|m<'C'=k c[q|b>"",q<-init b]i|m<'D'=k b b i|m<'P'=k c""i|1<3=k c(b++c)i
k c b(s:i)=k c(b++s)i
k c b[]=b
k""""

```

Try it on Ideone.

**Explanation:** `k` performs a tail recursion over a list of commands. `b` is the buffer in which the string is constructed, `c` saves the copied part.

```
k c b ("[B]":i) = k c (take(length b - 1)b) i -- remove last element of buffer
k c b ("[C]":i) = k b b i                     -- set copy to buffer
k c b ("[D]":i) = k c "" i                    -- clear the buffer
k c b ("[P]":i) = k c (b++c) i                -- append content of copy to the buffer
k c b (s:i)     = k c (b++s) i                -- append char to the buffer
k c b []        = b                           -- command list is empty, return buffer
f = k "" ""                                   -- initialise copy and buffer with empty strings

```

**Edit:** To save some bytes the commands`[B][C][D][P]`are no longer matched exactly but compared: less than `'C'`? -\> `B` and so on. Thanks to @nimi for saving 3 bytes.

# Answer
> 3 votes
# Mathematica, 100 bytes

```
""<>Fold[Switch[#2,"[B]",Most@#~Check~{},"[C]",a=#,"[D]",{},"[P]",#~Join~a,_,Append@##]&,a={};{},#]&

```

Anonymous function. Takes a list of strings as input and returns a string as output. Ignore any messages generated.

# Answer
> 2 votes
# PHP, 131 Bytes

17 Bytes save by @IsmaelMiguel ternary operator

```
<?$c=[];foreach($_GET[a]as$v)($t=$v[1])!=P?$t!=C?$t!=B?$t!=D?$o[]=$v:$o=[]:array_pop($o):$c=$o:$o=array_merge($o,$c);echo join($o);

```

# Answer
> 2 votes
# Java 7, ~~207~~ 203 bytes

```
String c(String[]a){String r="",c=r;for(String s:a){int k=s.length(),l=r.length(),z;if(k>1){z=s.charAt(1);r=z<67?l>0?r.substring(0,l-1):"":z<68?r:z<69?"":z<81?r+c:r+s;c=z==67?r:c;}r+=k<2?s:"";}return r;}

```

This can most definitely be golfed some more, ~~but this is my initial answer. Will edit after I found something to remove those `equals`-checks..~~ replaced with `charAt`, but can probably still be golfed..

**Ungolfed & test code:**

Try it here.

```
class M{
  static String c(final String[] a) {
    String r = "",
           c = r;
    for(String s : a){
      int k = s.length(),
          l = r.length(),
          z;
      if(k > 1){
        z = s.charAt(1);
        r = z < 67
             ? l > 0
                ? r.substring(0, l-1)
                : ""
             : z < 68
                ? r
                : z < 69
                   ? ""
                   : z < 81
                      ? r + c
                      : r + s;
        c = z == 67
             ? r
             : c;
      }
      r += k < 2
            ? s
            : "";
    }
    return r;
  }

  public static void main(String[] a){
    System.out.println(c(new String[]{ "H", "e", "l", "l", "o" }));
    System.out.println(c(new String[]{ "H", "e", "l", "l", "o", " ", "[C]", "[P]" }));
    System.out.println(c(new String[]{ "[D]", "D", "[B]" }));
    System.out.println(c(new String[]{ "H", "[C]", "i", "[P]", "[C]", "[P]" }));
    System.out.println(c(new String[]{ "e", "[C]", "[B]", "I", " ", "l", "i", "k", "[P]", " ", "b", "[P]", "[P]", "s", "!" }));
    System.out.println(c(new String[]{ "N", "[P]" }));
    System.out.println(c(new String[]{ "#", "5", "0", "K", "0", "0", "1", "[D]", "#", "n", "o", "t" }));
    System.out.println(c(new String[]{ "H", "o", "w", " ", "[D]", "H", "e", "y" }));
    System.out.println(c(new String[]{ "s", "u", "d", "[B]", "p", "[C]", "[D]", "I", " ", "h", "a", "v", "e", " ", "[P]", "p", "e", "r", "!" }));
  }
}

```

**Output:**

```
Hello
Hello Hello

HiHHiH
I like bees!
N
#not
Hey
I have supper!

```

# Answer
> 1 votes
# PHP, 108 bytes

```
for(;null!==$s=$argv[++$i];)($g=$s[1])!=B?$g!=C?$g!=D?$o.=$g!=P?$s:$c:$o='':$c=$o:$o=substr($o,0,-1);echo$o;

```

Uses a string based approach rather than an array based one.

Use like:

```
php -r "for(;null!==$s=$argv[++$i];)($g=$s[1])!=B?$g!=C?$g!=D?$o.=$g!=P?$s:$c:$o='':$c=$o:$o=substr($o,0,-1);echo$o;" a b "[C]" "[B]" "[P]" "[C]" "[D]" j "[P]"

```

edit: saved 8 bytes by fiddling the order of the ?:s and making them negative to avoid having to use so many brackets;

# Answer
> 1 votes
# SpecBAS - 216 bytes

```
1 s$,t$="": INPUT a$: DIM b$(SPLIT a$,NOT ",")
2 FOR EACH l$ IN b$()
3 CASE l$
4 WHEN "[B]": s$=s$( TO LEN s$-1)
5 WHEN "[C]": t$=s$
6 WHEN "[D]": s$=""
7 WHEN "[P]": s$=s$+t$
8 OTHERWISE : s$=s$+l$
9 END CASE
10 NEXT l$: ?s$

```

Input is given as a string with commas, which is then turned into array.

# Answer
> 1 votes
# PHP 7.1, ~~95~~ 92 bytes

Note: requires PHP 7.1 for negative string offsets.

```
for(;n|$i=$argv[++$x];)($l=$i[1])?$l^r?$l^s?$l^t?$o.=$c:$o="":$c=$o:$o[-1]="":$o.=$i;echo$o;

```

Without negative string offsets (101 bytes):

```
php -r 'for(;n|$i=$argv[++$x];)($l=$i[1])?$l^r?$l^s?$l^t?$o.=$c:$o="":$c=$o:$o=substr($o,0,-1):$o.=$i;echo$o;' e [C] [B] I ' ' l i k [P] ' ' b [P] [P] s ! 2>/dev/null;echo

```

Run like this:

```
php -nr 'for(;n|$i=$argv[++$x];)($l=$i[1])?$l^r?$l^s?$l^t?$o.=$c:$o="":$c=$o:$o[-1]="":$o.=$i;echo$o;' e [C] [B] I ' ' l i k [P] ' ' b [P] [P] s !;echo
> I like bees!

```

# Explanation

```
for(
  ;
  n|$i=$argv[++$x];   # Iterates over the input until null.
)
  ($l=$i[1])?         # Check if this item is a command, if so set to $l
    $l^r?             # If the command is not B
      $l^s?           # If the command is not C
        $l^t?         # If the command is not D
          $o.=$c      # Then it's P, so paste the clipboard ($c)
        :$o=""        #      It's D, so delete output
      :$c=$o          #      It's C, so copy output to clipboard
    :$o[-1]=""        #      It's B, so remove the last output char
  :$o.=$i;            # No command, add the current item to the output.

echo$o;               # Print the output.

```

# Tweaks

* Saved 3 bytes by combining the output handling with the command handling

# Answer
> 1 votes
# , 49 bytes

```
íÛBÝ/
íÛCÝ/0y$A
íÛDÝ/"_S
íÛPÝ/"
íî
0éiD@"

```

Try it online!

Since this contains unprintable characters, here is a hexdump:

```
0000000: eddb 42dd 2f16 080a eddb 43dd 2f16 1b30  ..B./.....C./..0
0000010: 7924 410a eddb 44dd 2f16 1b22 5f53 0aed  y$A...D./.."_S..
0000020: db50 dd2f 1612 220a edee 0a30 e969 4440  .P./.."....0.iD@
0000030: 22

```

This is just a direct translation of my vim answer so that I could compete with Jelly. Unfortunately, I'm still one byte over, but I'm still working on the last one. :)

I'm more proud of that answer anyway, so if you want a very detailed explanation, read that one instead.

# Answer
> 1 votes
## Actually, 56 bytes

```
''j"'[B]"'XaÆ"'[C]""k;╗i"aÆ"'[P]""╜i"aÆ"'[D]"'éaÆ''+ƒkΣR

```

Try it online!

Explanation:

```
''j"'[B]"'XaÆ"'[C]""k;╗i"aÆ"'[P]""╜i"aÆ"'[D]"'éaÆ''+ƒkΣR
''j                                                       insert an apostrophe between every pair of commands
   "'[B]"'XaÆ"'[C]""k;╗i"aÆ"'[P]""╜i"aÆ"'[D]"'éaÆ         replace:
   "'[B]"'XaÆ                                               "'[B]" with "X"
             "'[C]""k;╗i"aÆ                                 "'[C]" with "k;╗i"
                           "'[P]""╜i"aÆ                     "'[P]" with "╜i"
                                       "'[D]"'éaÆ           "'[D]" with "é"
                                                 ''+      prepend an apostrophe
                                                          now the input has been converted to the equivalent Actually program ("'<character>" pushes the character, "X" removes the last character, "k;╗i" saves the current stack state to a register, and "╜i" pushes the saved stack state)
                                                    ƒ     execute the code
                                                     kΣ   concatenate the characters
                                                       R  reverse the string

```

# Answer
> 1 votes
# Java, 181

```
String v(String[]a){String r="",c=r;for(String s:a){try{int p=s.charAt(1)%5;r=p<1?r+c:p>2?"":p==1?r.length()<2?"":r.split(".$")[0]:r;c=p==2?r:c;}catch(Exception e){r+=s;}}return r;}

```

More readable version:

```
String v(String[]a){
    String r="",c=r;
    for(String s:a){
        try{
            int p=s.charAt(1)%5;
            r= p<1
                 ? r+c
                 : p>2
                    ? ""
                    :p==1
                        ? r.length()<2
                                     ?""
                                     :r.split(".$")[0]
                        :r;
            c=p==2?r:c;
        }catch(Exception e){
            r+=s;
        }
    }return r;
}

```

# Answer
> 1 votes
# MATL, 46 bytes

```
vXKx"@gtnq?2)XJ66=?3L)}J67=?XK}J68=?vx}K]]]]&h

```

Try it online! Or verify all test cases.

### Explanation

```
v                % Push empty array
XK               % Copy to clipboard K. This initiallizes it as empty
x                % Delete
"                % Implicitly input cell array. For each
  @g             % Push current cell's contents
  t              % Duplicate elements
  n              % Number of elements
  q?             % If more then 1
    2)           % Get second char. Copy to clipboard J
    66=?         % If it ss 'B'
      3L)        % Remove last element from string built up to now
    }            % Else
      J67=?      % If it was a 'C'
        XK       % Copy string built up to now into clipboard K
      }          % Else
        J68=?    % If was a 'D'
          vx     % Delete stack. This deletes string built up to now, if any
        }        % Else: it was a 'P'
          K      % Paste from clipboard K
        ]        % End if
      ]          % End if
    ]            % End if
  ]              % End if
  &h             % Horizontally concatenate stack
                 % Implicitly end for
                 % Implicitly display

```

# Answer
> 1 votes
# TCL, 186 bytes

```
proc t w {foreach "B C P N D r Q" [list {[string range $r 0 end-1]} {[set Q $r]} {$r$Q} {$r$g}] break;foreach g $w {eval "set c \$[string index ${g}N 1]";eval "set r \"$c\""};return $r}

```

Nicely formatted:

```
proc t w {
    foreach "B C P N D r Q" [list {[string range $r 0 end-1]} {[set Q $r]} {$r$Q} {$r$g}] break;
    foreach g $w {
        eval "set c \$[string index ${g}N 1]"
        eval "set r \"$c\""
    }
    return $r
}

```

I just wanted to prove I could do this in TCL

# Answer
> 1 votes
# Scala, 158 bytes

```
(i:Seq[String])=>(("","")/:i){case((a,c),k)=>if(k.size<2)(a+k,c)else
if(k=="[B]")(a dropRight 1,c)else
if(k=="[C]")(a,a)else
if(k=="[D]")("",c)else(a+c,c)}._1

```

Ungolfed:

```
(i:Seq[String]) => i.foldLeft(("", "")){
  case ((res,clipboard),key) =>
    if (k.size == 1) (res+key,clipboard)
    else if (k=="[B]") (res dropRight 1, clipboard)
    else if (k=="[C]") (res, res)
    else if (k=="[D]") ("", clipboard)else(acc+clipboard,clipboard)
}._1

```

Solves this problem as a fold with the result and the clipboard as accumulator. Sadly, scala doesn't have a ternary conditional operator, but instead uses `if else` as an expression.

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