title: Play a game of Yahtzee

text:
# Question
Title: Play a game of Yahtzee
In the game Yahtzee, players take turns rolling 5 6-sided dice up to three times per turn, possibly saving dice between rolls, and then selecting a category they wish to use for their roll. This continues until there are no more categories (which happens after 13 turns). Then, players' scores are tallied, and the player with the highest score wins.

The categories are as follows ("sum of dice" means adding up the number of pips on the specified dice):

* **Upper Section**
    + **Aces**: sum of the dice showing 1 pip
    + **Twos**: sum of the dice showing 2 pips
    + **Threes**: sum of the dice showing 3 pips
    + **Fours**: sum of the dice showing 4 pips
    + **Fives**: sum of the dice showing 5 pips
    + **Sixes**: sum of the dice showing 6 pips
* **Lower Section**
    + **Three of a Kind**: 3 dice with same value, score is sum of all dice
    + **Four of a Kind**: 4 dice with same value, score is sum of all dice
    + **Full House**: 3 dice with one value and 2 with another, score is 25
    + **Small Straight**: 4 sequential dice, score is 30
    + **Large Straight**: 5 sequential dice, score is 40
    + **Yahtzee**: all 5 dice with same value, score is 50
    + **Chance**: any combination of dice, score is sum of all dice

There are a few rules about the category choices:

* If a player chooses a category that does not match their roll, they receive a score of 0 for that category.
* If a player earns a score of at least 63 in the upper section, they receive 35 bonus points.
* If a player has rolled a Yahtzee but the Yahtzee category is already taken (by another Yahtzee - filling in 0 for a miss doesn't count), they receive a bonus of 100 points. This bonus is awarded for every Yahtzee after the first.
    + Additionally, the player must still choose to fill in a category. They must choose the upper section category corresponding to their roll (e.g. a roll of 5 6's must be placed in the Sixes category). If the corresponding upper section category has already been used, the Yahtzee may be used for a lower section category (in this case, choosing Full House, Small Straight, or Large Straight awards the normal amount of points rather than 0). If all of the lower section categories are taken, then the Yahtzee may be applied to an unused upper section category, with a score of 0.

## The Challenge

In this challenge, the competitors will play 1000 games of Yahtzee. At the end of each game, the submission(s) that scored the highest will receive 1 point. After all of the games are finished, the submission with the most points will win. If there is a tie, additional games will be played with only the tied submissions until the tie is broken.

## Controller

The complete controller code can be found on this GitHub repository. Here are the public interfaces with which players will be interacting:

```
public interface ScorecardInterface {

    // returns an array of unused categories
    Category[] getFreeCategories();

    // returns the current total score
    int getScore();

    // returns the current Yahtzee bonus
    int getYahtzeeBonus();

    // returns the current Upper Section bonus
    int getUpperBonus();

    // returns the current Upper Section total
    int getUpperScore();

}

```

```
public interface ControllerInterface {

    // returns the player's scorecard (cloned copy, so don't try any funny business)
    ScorecardInterface getScoreCard(Player p);

    // returns the current scores for all players, in no particular order
    // this allows players to compare themselves with the competition,
    //  without allowing them to know exactly who has what score (besides their own score),
    //  which (hopefully) eliminates any avenues for collusion or sabotage
    int[] getScores();

}

```

```
public enum Category {
    ACES,
    TWOS,
    THREES,
    FOURS,
    FIVES,
    SIXES,
    THREE_OF_A_KIND,
    FOUR_OF_A_KIND,
    FULL_HOUSE,
    SMALL_STRAIGHT,
    LARGE_STRAIGHT,
    YAHTZEE,
    CHANCE;

    // determines if the category is part of the upper section
    public boolean isUpper() {
        // implementation
    }

    // determines if the category is part of the lower section
    public boolean isLower() {
        // implementation
    }

    // determines if a given set of dice fits for the category
    public boolean matches(int[] dice) {
        // implementation
    }

    // calculates the score of a set of dice for the category
    public int getScore(int[] dice) {
        // implementation
    }

    // returns all categories that fit the given dice
    public static Category[] getMatchingCategories(int[] dice) {
        // implementation
    }
}

```

```
public class TurnChoice {

    // save the dice with the specified indexes (0-4 inclusive)
    public TurnChoice(int[] diceIndexes) {
        // implementation
    }

    // use the current dice for specified category
    public TurnChoice(Category categoryChosen) {
        // implementation
    }

}

public abstract class Player {

    protected ControllerInterface game;

    public Player(ControllerInterface game) {
        this.game = game;
    }

    public String getName() {
        return this.getClass().getSimpleName();
    }

    // to be implemented by players
    // dice is the current roll (an array of 5 integers in 1-6 inclusive)
    // stage is the current roll stage in the turn (0-2 inclusive)
    public abstract TurnChoice turn(int[] dice, int stage);

}

```

Additionally, there are some utility methods in `Util.java`. They are mainly there to simplify the controller code, but they can be used by players if they desire.

## Rules

* Players are not allowed to interact in any way except using the `Scorecard.getScores` method to see the current scores of all players. This includes colluding with other players or sabotaging other players via manipulating parts of the system that are not part of the public interface.
* If a player makes an illegal move, they will not be allowed to compete in the tournament. Any issues that cause illegal moves must be resolved prior to the running of the tournament.
* If additional submissions are made after the tournament is run, a new tournament will be run with the new submission(s), and the winning submission will be updated accordingly. I make no guarantee of promptness in running the new tournament, however.
* Submissions may not exploit any bugs in the controller code that cause it to deviate from the actual game rules. Point out bugs to me (in a comment and/or in a GitHub issue), and I'll fix them.
* Use of Java's reflection tools is forbidden.
* Any language which runs on the JVM, or can be compiled to Java or JVM bytecode (such as Scala or Jython) can be used, so long as you supply any additional code needed to interface it with Java.

## Final Comments

If there is any utility method you would like me to add to the controller, simply ask in the comments and/or make an issue on GitHub, and I'll add it, assuming it doesn't allow for rule breaking or expose information to which players are not privy. If you want to write it yourself and create a pull request on GitHub, even better!

# Answer
## DummyPlayer

```
package mego.yahtzee;
import java.util.Random;
import java.util.stream.IntStream;
import java.util.stream.Stream;

public class DummyPlayer extends Player {

    public DummyPlayer(ControllerInterface game) {
        super(game);
    }

    @Override
    public TurnChoice turn(int[] dice, int stage) {
        Category[] choices = game.getScoreCard(this).getFreeCategories();
        Category choice = choices[new Random().nextInt(choices.length)];
        if(IntStream.of(dice).allMatch(die -> die == dice[0])) {
            if(Stream.of(choices).filter(c -> c == Category.YAHTZEE).count() > 0) {
                choice = Category.YAHTZEE;
            } else if(Stream.of(choices).filter(c -> c == Util.intToUpperCategory(dice[0])).count() > 0) {
                choice = Util.intToUpperCategory(dice[0]);
            } else {
                choices = Stream.of(game.getScoreCard(this).getFreeCategories()).filter(c -> c.isLower()).toArray(Category[]::new);
                if(choices.length > 0) {
                    choice = choices[new Random().nextInt(choices.length)];
                } else {
                    choices = game.getScoreCard(this).getFreeCategories();
                    choice = choices[new Random().nextInt(choices.length)];
                }
            }
        }
        return new TurnChoice(choice);
    }

}

```

This player is here to serve as a basic outline for how to use the tools present in the Yahtzee controller. It chooses Yahtzee whenever possible, and makes random choices otherwise, while complying with the strict joker rules.
> 4 votes

# Answer
# Aces and Eights

Well, this took a lot longer than I would have liked thanks to how busy I've been lately.

```
package mego.yahtzee;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import static mego.yahtzee.Category.*;

public class AcesAndEights extends Player {
    private Category[] freeCategories, matchingCategories, usableCategories;

    public AcesAndEights(ControllerInterface game) {
        super(game);
    }

    @Override
    public TurnChoice turn(int[] dice, int stage) {
        List<Integer> holdIndices = new java.util.ArrayList<>();

        freeCategories = game.getScoreCard(this).getFreeCategories();

        matchingCategories = Category.getMatchingCategories(dice);
        Arrays.sort(matchingCategories);

        usableCategories = Arrays.stream(freeCategories)
                                 .filter(this::isMatchingCategory)
                                 .toArray(Category[]::new);
        Arrays.sort(usableCategories);

        if (isMatchingCategory(YAHTZEE))
            return doYahtzeeProcess(dice);

        if (isUsableCategory(FULL_HOUSE))
            return new TurnChoice(FULL_HOUSE);

        if (stage == 0 || stage == 1) {
            if (isMatchingCategory(THREE_OF_A_KIND)) {
                int num = 0;
                for (int i : dice) {
                    if (Util.count(Util.boxIntArray(dice), i) >= 3) {
                        num = i;
                        break;
                    }
                }
                for (int k = 0; k < 5; k++) {
                    if (dice[k] == num)
                        holdIndices.add(k);
                }
                return new TurnChoice(toIntArray(holdIndices.toArray(new Integer[0])));
            }

            if (isFreeCategory(LARGE_STRAIGHT) || isFreeCategory(SMALL_STRAIGHT)) {
                if (isUsableCategory(LARGE_STRAIGHT))
                    return new TurnChoice(LARGE_STRAIGHT);

                if (isMatchingCategory(SMALL_STRAIGHT)) {
                    if (!isFreeCategory(LARGE_STRAIGHT))
                        return new TurnChoice(SMALL_STRAIGHT);

                    int[] arr = Arrays.stream(Arrays.copyOf(dice, 5))
                                      .distinct()
                                      .sorted()
                                      .toArray();
                    List<Integer> l = Arrays.asList(Util.boxIntArray(dice));
                    if (Arrays.binarySearch(arr, 1) >= 0 && Arrays.binarySearch(arr, 2) >= 0) {
                        holdIndices.add(l.indexOf(1));
                        holdIndices.add(l.indexOf(2));
                        holdIndices.add(l.indexOf(3));
                        holdIndices.add(l.indexOf(4));
                    }
                    else if (Arrays.binarySearch(arr, 2) >= 0 && Arrays.binarySearch(arr, 3) >= 0) {
                        holdIndices.add(l.indexOf(2));
                        holdIndices.add(l.indexOf(3));
                        holdIndices.add(l.indexOf(4));
                        holdIndices.add(l.indexOf(5));
                    }
                    else {
                        holdIndices.add(l.indexOf(3));
                        holdIndices.add(l.indexOf(4));
                        holdIndices.add(l.indexOf(5));
                        holdIndices.add(l.indexOf(6));
                    }
                    return new TurnChoice(toIntArray(holdIndices.toArray(new Integer[0])));
                }
            }

            if (isFreeCategory(FULL_HOUSE)) {
                int o = 0, t = o;
                for (int k = 1; k <= 6; k++) {
                    if (Util.count(Util.boxIntArray(dice), k) == 2) {
                        if (o < 1)
                            o = k;
                        else
                            t = k;
                    }
                }

                if (o > 0 && t > 0) {
                    for (int k = 0; k < 5; k++) {
                        if (dice[k] == o || dice[k] == t)
                            holdIndices.add(k);
                    }
                    return new TurnChoice(toIntArray(holdIndices.toArray(new Integer[0])));
                }
            }
        }
        else {
            Arrays.sort(freeCategories, Comparator.comparingInt((Category c) -> c.getScore(dice))
                                                  .thenComparingInt(this::getPriority)
                                                  .reversed());
            return new TurnChoice(freeCategories[0]);
        }

        return new TurnChoice(new int[0]);
    }

    private TurnChoice doYahtzeeProcess(int[] dice) {
        if (isUsableCategory(YAHTZEE))
            return new TurnChoice(YAHTZEE);

        Category c = Util.intToUpperCategory(dice[0]);
        if (isUsableCategory(c))
            return new TurnChoice(c);

        Category[] arr = Arrays.stream(freeCategories)
                               .filter(x -> x.isLower())
                               .sorted(Comparator.comparing(this::getPriority)
                                                 .reversed())
                               .toArray(Category[]::new);
        if (arr.length > 0)
            return new TurnChoice(arr[0]);

        Arrays.sort(freeCategories, Comparator.comparingInt(this::getPriority));
        return new TurnChoice(freeCategories[0]);
    }

    private boolean isFreeCategory(Category c) {
        return Arrays.binarySearch(freeCategories, c) >= 0;
    }

    private boolean isMatchingCategory(Category c) {
        return Arrays.binarySearch(matchingCategories, c) >= 0;
    }

    private boolean isUsableCategory(Category c) {
        return Arrays.binarySearch(usableCategories, c) >= 0;
    }

    private int getPriority(Category c) {
        switch (c) {
            case YAHTZEE: return -3;        // 50 points
            case LARGE_STRAIGHT: return -1; // 40 points
            case SMALL_STRAIGHT: return -2; // 30 points
            case FULL_HOUSE: return 10;     // 25 points
            case FOUR_OF_A_KIND: return 9;  // sum
            case THREE_OF_A_KIND: return 8; // sum
            case SIXES: return 7;
            case FIVES: return 6;
            case FOURS: return 5;
            case THREES: return 4;
            case TWOS: return 3;
            case ACES: return 2;
            case CHANCE: return 1;          // sum
        }
        throw new RuntimeException();
    }

    private int[] toIntArray(Integer[] arr) {
        int[] a = new int[arr.length];
        for (int k = 0; k < a.length; k++)
            a[k] = arr[k];
        return a;
    }
}

```

The bot looks for patterns in the dice that could match certain categories and holds the necessary ones. It immediately chooses a high-priority matching category if one's found; otherwise it chooses a category that yields the highest score. Scores nearly 200 points per game on average.
> 1 votes

---
Tags: game, king-of-the-hill
---


title: Find the Wavy Words!

text:
# Question
Title: Find the Wavy Words!
(Note: this is an easier spin-off of my previous challenge Find the Infinity Words!, which is a spin-off of my other previous challenge Find the Swirling Words! :) )

### Definition of a *Wavy Word*:

1. If you connect with curves all the characters of a *Wavy Word* on the alphabet (A-Z) you obtain the path of a wave continuously going toward right or toward left and never changing direction, like in the diagrams below.
2. A *Wavy Word* can be:
    * *Raising* if each consecutive character is at the right (on the alphabet) of the previous one.
    * *Decreasing* if each consecutive character is at the left (on the alphabet) of the previous one.
3. All the even connection must be down, all the odd connections must be up.
4. You can ignore upper/lowercase or consider/convert all to upper case or all to lower case.
5. The input words are only characters in the alphabet range of A-Z, no spaces, no punctuation, or symbols.
6. If a word has double characters, like "SPOON", you must collapse the doubles to one character: "SPOON" \> "SPON" (because if you go from O to O is zero distance).
7. The *Wavy Words* will contain at least 3 distinct characters (even after doubles collapsing).

### Here there are some examples:

### Task:

Write a full program or function that will take a word from standard input and will output if it is a *Wavy Word* or not, and in positive case, output if it is *raising* or *decreasing*. The output can be `True/False/Null`, `2/1/0`, `1/Null/0`, `-1/0/1`, `NO/WR/WD`, etc, you decide how to represent it.

### Test cases:

```
WAVY WORDS:
  ADEPT, BEGIN, BILL, BOSS, BOOST, CHIMP,
  KNOW, SPONGE, SPOON, TROLL, WOLF

ADEPT  > YES > RAISING
BEGIN  > YES > RAISING
BILL   > YES > RAISING
BOSS   > YES > RAISING
BOOST  > YES > RAISING
CHIMP  > YES > RAISING
KNOW   > YES > RAISING
SPONGE > YES > DECREASING
SPOON  > YES > DECREASING
TROLL  > YES > DECREASING
WOLF   > YES > DECREASING

NOT WAVY WORDS:
  WATCH, EARTH, NINON, FOO, BAR, WAVE, SELECTION,
  YES, NO, DEFINITION, WATER, WINE, CODE, AAAHHHH, I, MM, ABCA

```

### Rules:

* Shortest code wins.

### Optional Task:

Find, as a list, as many *Wavy Words* as you can in an English dictionary, and the longest as well. You can take for example as reference the complete list of English words here.

# Answer
> 6 votes
# 05AB1E, ~~11~~ 9 bytes (Thanks to Adnan)

```
Dg2›iÇü‹Ù

```

Try it online!

**Wavy Cases:**

**0** \- Decreasing Wavy

**1** \- Increasing Wavy

**Not Wavy Cases:**

**\[0,1\]** \- Not wavy, initially decreasing, but then has an increase/equality that broke the pattern.

**\[1,0\]** \- Not wavy, initially increasing, but then has a decrease/equality that broke the pattern

**Input String** \- Not possible to be wavy in the first place due to length.

**Explanation:**

```
Dg2›iÇü‹Ù   # Full program

D           # Push 2 copies of input.
 g2›i       # If length is greater than 2.
     Ç      # Push ASCII values for all characters in the string.
      ü     # Push pairwise array.
       ‹    # Vectorize 1 if negative difference, 0 if positive difference.
        Ù   # Uniquify using right most unique values first.
            # Else just print the string back, letting them know it's not valid input.

```

# Answer
> 5 votes
# Jelly, 10 bytes

```
OIṠḟ0µL’aQ

```

**TryItOnline!** or run all test cases

Returns:
`[1]` for wavy increasing
`[-1]` for wavy decreasing
something else otherwise (`[]`, `[0]`, `[-1,1]`, or `[1,-1]`)

(Declared as unnecessary: For a single value for each `OIṠḟ0µL’aQS` (11 bytes) will return `1`, `-1`, and `0` respectively.)

### How?

```
OIṠḟ0µL’aQ - Main link: s
O          - cast to ordinals
 I         - incremental differences
  Ṡ        - sign (-1 for decreasing, 0 for no change, 1 for increasing)
   ḟ0      - filter out zeros
     µ     - monadic chain separation
      L    - length
       ’   - decremented
        a  - and
         Q - unique items

```

# Answer
> 3 votes
# Python 3, ~~77~~ 75 bytes

```
lambda x:(len(set(x))>2)*(list(x)==sorted(x)or(list(x)==sorted(x)[::-1])*2)

```

Assumes all letters are of the same case.

Returns:

* `0` if not wavy
* `1` if forwards wavy
* `2` if backwards wavy

Removed unnecessary spaces thanks @ETHproductions

# Answer
> 3 votes
## Python 2, 54 bytes

```
lambda s:[2<len(set(s))<s[::b]==sorted(s)for b in-1,1]

```

Takes input as a list of characters. Outputs:

```
[False, True] for ascending
[True, False] for descending
[False, False] for neither

```

Checks if the sorted input string equals its original or reverse. Does so by slicing with step sizes of 1 and -1. At the same time, we check whether the word has at least 2 distinct letters.

If "exit with error" can be used an output for the neither case, we can go down to 51 bytes:

```
lambda s:[s,s[::-(len(set(s))>2)]].index(sorted(s))

```

# Answer
> 3 votes
## JavaScript (ES6), ~~84~~ 81 bytes

```
s=>(new Set(t=[...s]).size>2)*(!t.some((c,i)=>c>s[i+1])-!t.some((c,i)=>c<s[i+1]))

```

Assumes the input is all in the same case. Returns `1` for raising wavy, `-1` for decreasing wavy, `0` or `-0` (both are falsy) for not wavy. Edit: Saved 3 bytes thanks to @RobertHickman.

# Answer
> 3 votes
# R, 96 95 bytes

```
function(x,d=diff(rle(utf8ToInt(x))$v))if(any(d>0)&any(d<0)|sum(1|d)<2)3 else`if`(all(d<1),2,1)

```

Returns:

* `1` for wavy and raising
* `2` for wavy and decreasing
* `3` for non-wavy

**Explained**

* `d=diff(rle(utf8ToInt(x))$v)`: Generates a variable `d` by first converting the string into it's `ASCII` values using `utf8ToInt` which conveniently returns a vector. Subsequently perform run length encoding using `rle`. `rle(...)$v` returns the non-repeating values of the sequence (i.e. collapsing all runs). Finally take the difference.
* `if(any(d>0)&any(d<0)|sum(1|d)<2)3`: If at least one of the differences are positive and at least one negative, or if the difference sequence has less than `2` elements (equivalent to the original word having less than 3 characters), the word is non-wavy and return `3`
* `else``if``(all(d<1),2,1)`: Else if all differences are negative, return `2` for wavy and decreasing, else return `1` for wavy and raising.

---

Try all the test cases at R-fiddle (note that it's named such that it can be vectorized for the test cases).

# Answer
> 3 votes
## Javascript (ES6), 84 80 78 bytes

```
i=>new Set(s=[...i]).size>2?[i,s.reverse().join``].indexOf(s.sort().join``):-1

```

Where wavy increasing is 0, decreasing is 1, and -1 is not wavy.

Thanks to @Neil for helping me save 2 bytes.

# Answer
> 2 votes
# Pyth, 12 bytes

```
x*<2lrQ8_BQS

```

Try it online. Test suite.

# Answer
> 2 votes
# PHP, 96 Bytes

```
for(;($t=$argv[1])[++$i];)$s+=$r[]=$t[$i-1]<=>$t[$i];echo(max($r)-min($r)<2)*(0<=>$s)*(1<$s*$s);

```

or 98 Bytes

```
$s=str_split($t=$argv[1]);sort($s);echo(-($t==strrev($j=join($s)))|$t==$j)*!!count_chars($t,3)[2];

```

0 not wavy 1 raising -1 decreasing

# Answer
> 2 votes
# Python 2, ~~53~~ ~~52~~ 50 bytes

Expects input enclosed in quotes, e.g. `"watch"`

As unnamed lambda:

```
lambda s:(sum(map(cmp,s[1:],s))+1)/min(len(s)-1,3)

```

Sums the sign of difference between each letters and integer-divides by `len-1`. If all were `1` (increasing) the sum is `len-1` it displays `1`, similar for decreasing `-1` and for mixed `1`,`-1` the sum is smaller than `len-1` so it displays `0`.

-1 byte for changing `cmp,s[1:],s[:-1])` to `cmp,s[1:],s)+1`

# Answer
> 2 votes
# Ruby, 54 bytes

```
->w{c=w.chars.uniq;c==(s=c.sort)?2:(c==s.reverse)?1:0}

```

Returns `0` if the word is not wavy, `1` if backwards wavy, and `2` if forwards wavy.

# Answer
> 2 votes
# PHP, 100 bytes

```
$n=$m=$l=str_split($argv[1]);sort($n);rsort($m);echo(($n==$l)-($m==$l))*(count(array_unique($l))>2);

```

Returns:

* `-1` for wavy, decreasing.
* `0` for not wavy.
* `1` for wavy, raising.

# Answer
> 2 votes
# Groovy - 56 bytes

```
{d=it[0];c=[0]*3;it.each{a->c[(a<=>d)]=1;d=a};c[1..-1]}
```

Outputs `[1,0]` for raising wavy, `[0,1]` for decreasing wavy, `[0,0]` for single character input or `[1,1]` for non-wavy.

*NOTE:* Assumes input is either a String or a char\[\] and all letters are of the same case.

# Answer
> 1 votes
# C, 164 bytes

```
main(){char s[99];scanf("%s",s);char *c=&s;int p=*c;while(*c^0){if(p>*c){if(c-&s[0]>1)return 0;while(*c^0){if(p<*c)return 0;p=*c;c++;}return 2;}p=*c;c++;}return 1;}

```

Returns 0 if not wawy, 1 if wawy and raising, 2 if decreasing.

# Answer
> 1 votes
## Racket 321 bytes

```
(let*((ld(λ(sl)(for/list((i(sub1(length sl))))(-(list-ref sl(add1 i))(list-ref sl i)))))(l(ld(remove-duplicates(map
(λ(x)(char->integer x))(string->list s)))))(am andmap)(N"Not WAVY")(d displayln))(cond[(<(length l)2)(d N)][(am(λ(x)(>= x 0))l)
(d"YES; RAISING")][(am(λ(x)(<= x 0))l)(d"YES; DECREASING")][else(d N)])))

```

Ungolfed:

```
(define (f s)
  (let*  ((ld (lambda(sl)          ; sub-fn to get differences in list elements
                (for/list ((i (sub1(length sl))))
                  (- (list-ref sl (add1 i))
                     (list-ref sl i) ) )))
          (l (ld
              (remove-duplicates
               (map
                (lambda(x)
                  (char->integer x))
                (string->list s)))))
          (am andmap)
          (N "Not WAVY")
          (d displayln))
    (cond
      [(< (length l) 2)(d N)]
      [(am (lambda(x) (>= x 0)) l) (d "YES; RAISING")]
      [(am (lambda(x) (<= x 0)) l) (d "YES; DECREASING")]
      [else (d N)]
      )))

```

Testing:

```
(f "ADEPT"); > YES > RAISING
(f "BEGIN"); > YES > RAISING
(f "BILL"); > YES > RAISING
(f "BOSS"); > YES > RAISING
(f "BOOST"); > YES > RAISING
(f "CHIMP"); > YES > RAISING
(f "KNOW"); > YES > RAISING
(f "SPONGE"); > YES > DECREASING
(f "SPOON"); > YES > DECREASING
(f "TROLL"); > YES > DECREASING
(f "WOLF"); > YES > DECREASING

(f "WATCH")
(f "EARTH")
(f "NINON")
(f "FOO")
(f "BAR")
(f "WAVE")
(f "SELECTION")

```

Output:

```
YES; RAISING
YES; RAISING
YES; RAISING
YES; RAISING
YES; RAISING
YES; RAISING
YES; RAISING
YES; DECREASING
YES; DECREASING
YES; DECREASING
YES; DECREASING
Not WAVY
Not WAVY
Not WAVY
Not WAVY
Not WAVY
Not WAVY
Not WAVY

```

# Answer
> 1 votes
# Java 7, ~~254~~ 240 bytes

```
import java.util.*;int c(String s){char[]a=s.toCharArray(),x=a.clone();Arrays.sort(x);return s.replaceAll("(.)\\1{1,}","$1").length()<3?0:Arrays.equals(a,x)|Arrays.equals(x,(new StringBuffer(s).reverse()+"").toCharArray())?a[0]>a[1]?1:2:0;}

```

Outputs `0` if the input string isn't wavy, `1` if it's a raising wave, and `2` if it's a decreasing wave.

**Ungolfed & test code:**

Try it here.

```
import java.util.*;
class M{
  static int c(String s){
    char[] a = s.toCharArray(),
           x = a.clone();
    Arrays.sort(x);
    return s.replaceAll("(.)\\1{1,}", "$1").length() < 3
            ? 0
            : Arrays.equals(a, x) | Arrays.equals(x, (new StringBuffer(s).reverse()+"").toCharArray())
               ? a[0] > a[1]
                  ? 1
                  : 2
               : 0;
  }

  public static void main(String[] a){
    System.out.print(c("ADEPT") + ", ");
    System.out.print(c("BEGIN") + ", ");
    System.out.print(c("BILL") + ", ");
    System.out.print(c("BOSS") + ", ");
    System.out.print(c("BOOST") + ", ");
    System.out.print(c("CHIMP") + ", ");
    System.out.println(c("KNOW"));

    System.out.print(c("SPONGE") + ", ");
    System.out.print(c("SPOON") + ", ");
    System.out.print(c("TROLL") + ", ");
    System.out.println(c("WOLF"));

    System.out.print(c("WATCH") + ", ");
    System.out.print(c("EARTH") + ", ");
    System.out.print(c("NINON") + ", ");
    System.out.print(c("FOO") + ", ");
    System.out.print(c("BAR") + ", ");
    System.out.print(c("WAVE") + ", ");
    System.out.print(c("SELECTION") + ", ");
    System.out.print(c("YES") + ", ");
    System.out.print(c("NO") + ", ");
    System.out.print(c("DEFINITION") + ", ");
    System.out.print(c("WATER") + ", ");
    System.out.print(c("WINE") + ", ");
    System.out.print(c("CODE") + ", ");
    System.out.print(c("AAAHHHH") + ", ");
    System.out.print(c("I") + ", ");
    System.out.print(c("MM") + ", ");
    System.out.println(c("ABCA"));
  }
}

```

**Output:**

```
2, 2, 2, 2, 2, 2, 2
1, 1, 1, 1
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0

```

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


title: Animate Adve the Adventurer

text:
# Question
Title: Animate Adve the Adventurer
## The challenge

Your task is to animate Adve the Adventurer moving through a creepy (i.e. Halloween) maze. Adve is a ; he's character fluid, though, so he does not mind being represented by a different character.

To animate Adve, you print out each frame; a frame is the map with his current location in it. Adve moves one space forward every turn and never backtracks. He starts in the first row and ends in the last.

## Input

Any reasonable format like a string with a delimiter or string array. You can assume the input will be a map greater than 3\*3, containing only one possible path. The only characters present will be `#` and .

## Output

The frames.

## Example maze (ok... labyrinth)

Here is a map without Adve in it; the first and last frames are this empty map (this map is 9x15):

```
### #####
##  #####
## ######
##      #
####### #
#   ### #
# # #   #
# #   ###
# #######
#    ####
#### ####
####  ###
##### ###
##### ###
##### ###

```

This is , so shortest code in bytes wins!

The *exact* output for this can be found here (37 frames).

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

# Answer
> 4 votes
## Perl, 84 bytes

*Thanks @Ton Hospel for guiding me to the right direction to golf out around 30 bytes!*

Bytecount includes 82 bytes of code and `-0p` flags.

```
/.*/;say y/A/ /r;s/&(.{@{+}})? /A$1&/s||s/ (.{@{+}})?&/&$1A/s||s/ /&/?redo:y;A&;

```

Note that there are two final spaces, and no final newline (it won't work otherwise).

Takes the maze as input as outputs all the needed frames for Adve to get out of it. Note that Adve is a `&` rather than a , since the latter isn't utf8 (and perl doesn't use utf8 by default). Run it with `-0pE` flags :

```
perl -0pE '/.*/;say y/A/ /r;s/&(.{@{+}})? /A$1&/s||s/ (.{@{+}})?&/&$1A/s||s/ /&/?redo:y;A&;  ' <<< "### #####
##  #####
## ######
##      #
####### #
#   ### #
# # #   #
# #   ###
# #######
#    ####
#### ####
####  ###
##### ###
##### ###"

```

---

*Just for the eyes*, I also made this animated version, that is a little bit longer, but will clear the terminal between each print and sleep 0.15 sec, so it will look like Adve is actually moving :

```
perl -0nE 'system(clear);/.*/;say y/A/ /r;select($,,$,,$,,0.15);s/&(.{@{+}})? /A$1&/s||s/ (.{@{+}})?&/&$1A/s||s/ /&/?redo:say"\e[H",y/A&/  /r' <<< "### #####
##  #####
## ######
##      #
####### #
#   ### #
# # #   #
# #   ###
# #######
#    ####
#### ####
####  ###
##### ###
##### ###"

```

# Answer
> 3 votes
# JavaScript (ES6), 137

(1 byte saved thx @ETHproductions)

```
m=>(o=>{for(p=m.search` `-o,r=[m];[d,o/d,-o/d].some(q=>1/m[d=q,q+=p]?p=q:0);r.push(q.join``))(q=[...m])[p]=0})(d=1+m.search`
`)||[...r,m]

```

*Less golfed*

```
m=>{
  d = o = 1+m.search`\n`; // offset to next row and starting direction
  p = m.search` `-o; // starting position, 1 row above the first
  for( r=[m]; // r is the output array, start with empty maze
       // try moving in 3 directions (no back)
       // if no empty cell found, we have exit the maze
       [d,o/d,-o/d].some(q => 1/m[d=q,q+=p]? p=q : 0);
       r.push(q.join``) // add current frame
     )
     q=[...m], q[p] = 0; // build frame, '0' used to mark Adve position
  return [...r,m] // add last frame with maze empty again
}

```

**Test**

```
F=
m=>(o=>{for(p=m.search` `-o,r=[m];[d,o/d,-o/d].some(q=>1/m[d=q,q+=p]?p=q:0);r.push(q.join``))(q=[...m])[p]=0})(d=1+m.search`\n`)||[...r,m]

function go() {
  var i=I.value,r=F(i),
      frame=x=>(x=r.shift())&&(O.textContent=x,setTimeout(frame,100))
  frame()
}

go()
```

```
#I { width:10em; height: 19em; font-size:10px}
#O { white-space:pre; font-family: monospace; font-size:10px; vertical-align: top; padding: 4px}
```

```
<table><tr><td>
<textarea id=I>### #####
##  #####
## ######
##      #
####### #
#   ### #
# # #   #
# #   ###
# #######
#    ####
#### ####
####  ###
##### ###
##### ###
##### ###
</textarea><button onclick='go()'>go</button></td><td id=O></td></tr></table>
```

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


title: Generate antsy permutations

text:
# Question
Title: Generate antsy permutations
## Introduction

I defined the class of antsy permutations in an earlier challenge. As a reminder, a permutation **p** of the numbers from **0** to **r-1** is antsy, if for every entry **p\[i\]** except the first, there is some earlier entry **p\[i-k\]** such that **p\[i\] == p\[i-k\] ± 1**. As a fun fact, I also stated that for **r ≥ 1**, there are exactly **2r-1** antsy permutations of length **r**. This means that there is a one-to-one correspondence between the antsy permutations of length **r** and the binary vectors of length **r-1**. In this challenge, your task is to implement such a correspondence.

## The task

Your task is to write a program or function that takes in a binary vector of length **1 ≤ n ≤ 99**, and outputs an antsy permutation of length **n + 1**. The permutation can be either 0-based of 1-based (but this must be consistent), and the input and output can be in any reasonable format. Furthermore, different inputs must always give different outputs; other than that, you are free to return whichever antsy permutation you want.

The lowest byte count wins.

## Example

The (0-based) antsy permutations of length 4 are

```
0 1 2 3
1 0 2 3
1 2 0 3
1 2 3 0
2 1 0 3
2 1 3 0
2 3 1 0
3 2 1 0

```

and your program should return one of them for each of the eight bit vectors of length 3:

```
0 0 0
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
1 1 1

```

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

```
ḟẋLṭ+
0;ç/

```

Try it online! or generate all permutations of length 4.

### How it works

```
0;ç/   Main link. Argument: B (bit array)

0;     Prepend a 0 to B.
  ç/   Reduce [0] + B by the helper link.

ḟẋLṭ+  Helper link. Left argument: A (array or 0). Right argument: b (bit)

 ẋ     Repeat A b times, yielding A or [].
ḟ      Filter false; remove the elements of A or [] from A.
  L    Get the length of the resulting array.
       This yield len(A) if b = 0 and 0 if b = 1.
    +  Add b to all elements of A.
   ṭ   Tack; append the result to the left to the result to the right.

```
> 3 votes

# Answer
# Python 2, ~~62~~ 60 bytes

```
x=0,
for n in input():x=[t-n+1for t in x]+[n*len(x)]
print x

```

*Thanks to @xnor for golfing off 2 bytes!*

Test it on Ideone.
> 3 votes

# Answer
## JavaScript (ES6), ~~48~~ ~~47~~ 45 bytes

```
a=>[h=l=0,...a.map(c=>c?--l:++h)].map(e=>e-l)

```

This turned out to be similar to @ETHproductions' method, except I had started by directly calculating the first element and then using the binary vector to determine whether each digit is a new high or a new low. Edit: Saved 1 byte thanks to @ETHproductions. Saved 2 bytes by starting with zero and adjusting afterwards. My previous method turned out to be similar to @Dennis's method, but took 54 bytes:

```
a=>a.reduce((r,b)=>[...r.map(e=>b+e),r.length*!b],[0])

```
> 3 votes

# Answer
## Python, 54 bytes

```
lambda l:[i-i*x+sum(l[i:])for i,x in enumerate([1]+l)]

```

Uses the following procedure:

1. Prepend a 1 to the list.
2. For each 0 entry, write its position in the 0-indexed list.
3. For each entry, write the number of 1's to its right, not counting itself.
4. Add the results of steps 2 and 3 entrywise.

For example, `l=[1,0,1,0]` gives `f(l) == [2,1,3,0,4]`

```
List with prepended 1         1 1 0 1 0

0-indexed position for 0's        2   4
Number of 1's to right        2 1 1 0 0
Sum of above two              2 1 3 0 4

```

Prepending a 0 would also give the same result. The `enumerate` is clunky, I'll see if it can done better recursively.
> 3 votes

# Answer
# JavaScript (ES6), 52 bytes

```
v=>[...v,l=0].map(x=>x?l++:h--,h=v.length).reverse()

```

Test it out:

```
f=v=>[...v,l=0].map(x=>x?l++:h--,h=v.length).reverse()
g=v=>console.log(f((v.match(/[01]/g)||[]).map(x=>+x)))
```

```
<input oninput="g(this.value)" value="010">
```

### Explanation

This takes advantage of the fact that when an antsy permutation is reversed, each item is either 1 more than the maximum of the previous low entries, or 1 less than the minimum of the previous high entries. By denoting a higher item as a `0` and a lower item as a `1`, we can create an exact one-to-one correspondance between the antsy permutations of length **n** and the binary vectors of length **n - 1**.

The best I could do with Dennis' technique is ~~57~~ 51 bytes:

```
v=>v.reduce((x,n)=>[...x.map(i=>i+n),!n*++j],[j=0])
v=>v.map(n=>x=[...x.map(i=>i+n),!n*++j],x=[j=0])&&x

```

xnor's solution is 56 (saved 1 byte thanks to @Neil):

```
l=>[1,...l].map((x,i)=>i*!x+eval(l.slice(i).join`+`||0))

```
> 2 votes

# Answer
# Perl, 33 bytes

Includes +1 for `-p`

Give vector as string without spaces on STDIN:

```
antsy.pl <<< 110

```

`antsy.pl`:

```
#!/usr/bin/perl -p
s%^|.%y/0//+($&?++$a:$b--).$"%eg

```
> 2 votes

# Answer
## Haskell, 40 bytes

```
foldl(\r a->map(+0^a)r++[a*length r])[0]

```

Dennis's Python solution golfs wonderfully in Haskell with `map` and `fold`. It's shorter than my attempts to port my direct entrywise construction:

```
f l=[i*0^x+sum(drop i l)|(i,x)<-zip[0..]$0:l]
f l=[a+c-b*c|(a,c,b)<-zip3(scanr(+)0l)[0..]$0:l]

```
> 0 votes

# Answer
## Batch, 127 bytes

```
@set s=%*
@set/an=h=l=%s: =+%
@for %%b in (%*)do @call:%%b
:0
@echo %n%
@set/an=h+=1
@exit/b
:1
@echo %n%
@set/an=l-=1

```

Takes input as command-line parameters, output is line-separated. (It's possible to input as space-separated on STDIN for no extra cost.)
> 0 votes

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


title: Primes with a twist

text:
# Question
Title: Primes with a twist
Note: this is heavily inspired by *this question*.

# Task:

Your task is to generate the `n`th prime, when each character of your program is repeated `n` times in place.

Let's say your program is:

```
Derp

```

Every character in there is repeated once, so it should output `2`.

When every character is duplicated in place, like so:

```
DDeerrpp

```

This should generate the 2nd prime, which is `3`.

# Specs:

* Your program must accept no input, and output the respective prime.
* Your program must work for all primes, given enough time and memory.
* Leading and trailing newlines are fine.
* The output must be in the default base of the language - if there is no default, any base is fine.

This is , so shortest code in bytes wins.

# Answer
> 22 votes
# Jelly, 13 bytes

```
“Ŀo‘’FQỌµḟ;¹V

```

Try it online! or run the first ten programs.

### Background

Jelly has several different types of string literals; all of them start with a . If the literal contains more than one , a string array is returned, and  separates the strings from each other.

For example, `“abc“def”` yields `['abc', 'def']`.

Depending on the last character of the literal (any of `”«»‘’`, where `«` is currently unimplemented), one can choose between the different types of literals. For , we get the code points in Jelly's code page instead of the corresponding Unicode characters.

For example, `“abc“def‘` yields `[[97, 98, 99], [100, 101, 102]]`.

The literals in the first three programs correspond to the following code point arrays.

```
“Ŀo‘           -> [199, 111]
““ĿĿoo‘        -> [[], [199, 199, 111, 111]]
“““ĿĿĿooo‘     -> [[], [], [199, 199, 199, 111, 111, 111]]

```

### How it works (**n = 3**)

```
“““ĿĿĿooo‘‘‘’’’FFFQQQỌỌỌµµµḟḟḟ;;;¹¹¹VVV  Main link. Implicit argument: 0

“““ĿĿĿooo‘                               Yield the 2D array
                                         [[], [], [199, 199, 199, 111, 111, 111]].
          ‘‘                             Increment twice, yielding
                                         [[], [], [201, 201, 201, 113, 113, 113]].
            ’’’                          Decrement thrice, yielding
                                         [[], [], [198, 198, 198, 110, 110, 110]].
               F                         Flatten, yielding
                                         [198, 198, 198, 110, 110, 110].
                FF                       Twice more. Does nothing.
                  Q                      Unique; yield [198, 110].
                   QQ                    Twice more. Does nothing.
                     Ọ                   Unordinal; convert the Unicode code points
                                         198 and 110 to 'Æ' and 'n'.
                      ỌỌ                 Twice more. Does nothing.
                        µµµ              Begin three monadic chains, all with
                                         argument s := "Æn".
                           ḟ             Filter-false; remove the characters of s
                                         from s, yielding "".
                            ḟḟ           Twice more. Does nothing.
                              ;;;¹       Concatenate with s three times, yielding
                                         "ÆnÆnÆn".
                                  ¹¹     Identity function. Does nothing.
                                    V    Eval the resulting Jelly code, i.e.,
                                         call the next-prime atom thrice, with
                                         initial implicit argument 0.
                                     VV  Eval two more times. This is a no-op
                                         on integers.

```

# Answer
> 22 votes
# GS2 (commit 67fea47), ~~6~~ 3 bytes

```
dnR

```

### How it works

Like most commands, GS2‘s `d` is overloaded. Initially, there's an empty list (the input or the lack thereof) on the stack, so `d` computes its sum. After the first iteration, there's a **0** on the stack, and `d` computes its parity (also **0**). Thus, no matter how many times we repeat `d`, the result will always be a single **0**.

The next part is straightforward. The command `n` pops the top of the stack and pushes the next prime number. Thus, repeating `n` **k** times computes the **k** prime.

Finally, the command simply applies *str* to the top of the stack, which converts a number to its string representation and does no affect strings. Thus, no matter how many times we repeat `R`, the result will be the string representation of the **k** prime.

---
Tags: code-golf, math, primes, source-layout
---


title: Shuffle Up and Deal!

text:
# Question
Title: Shuffle Up and Deal!
It is Friday and I am tired, so let's do a quick one! Take no input, however you should output all thirteen different numbered cards in a standard deck of cards. You should output 2 through Ace (Suit agnostic).

Each card has a top that is denoted with a space  and ten `_` and another space.

The second row from the top is denoted with a `/` and ten spaces  and a `\`

The third row is the same as all the middle-ish rows excepts the character(s) denoting the card value appear two spaces to right (if at the top) or two space to the left (if at the bottom) of the edge.

Each middle-ish row is a simple `|` and ten spaces  and one more `|`

Finally the last line is a `\` and ten `_` and finally a `/`

If the value is multi-digit the overall width by height of the card should not change. (i.e. the 10 will not make the card's sides wider)

King Example:

```
 __________
/          \
| K        |
|          |
|          |
|          |
|          |
|          |
|        K |
\__________/

```

9 Example

```
 __________
/          \
| 9        |
|          |
|          |
|          |
|          |
|          |
|        9 |
\__________/

```

10 Example

```
 __________
/          \
| 10       |
|          |
|          |
|          |
|          |
|          |
|       10 |
\__________/

```

Output them in order from least to greatest (Aces are high!).

This is code-golf so the shortest code wins.

Have fun and have a fun weekend!

# Answer
> 10 votes
## PowerShell v2+, ~~120~~ ~~116~~ ~~114~~ 108 bytes

```
2..10+[char[]]'JQKA'|%{$z=' '*(8-!($_-10));$x='_'*10;$y=' '*10;" $x
/$y\
| $_$z|";,"|$y|"*5;"|$z$_ |
\$x/"}

```

Constructs a range `2..10` and does array concatenation with `char`-array `JQKA`. Feeds that into a loop `|%{...}`. Each iteration, we set `$z` equal to an appropriate number of spaces (based on whether we're at card `10` or not), set `$x` to `10` underscores, and set `$y` to `10` spaces.

Then, we begin our placements. We're going to leverage the default `Write-Output` to insert a newline between pipeline elements, so we just need to get the stuff on the pipeline. Note that in most places, we're using a literal newline rather than closing and reopening our strings to save a couple bytes.

The first is just `$x` with two spaces, then `$y` with two slashes, then the `| $_$z|"` the pipe, a space, the appropriate number of spaces, and another pipe. This forms the top of the cards up to and including the value line.

We have to semicolon here, since the next uses an array. The `,"|$y|"*5` constructs a string-array, with the comma-operator, of the pipe with spaces - on output, each element of this array gets a newline for free.

Then, the `"|$z$_ |` for the bottom value marking, and finally `$x` with slashes for the bottom of the card.

### Output Snippet

```
PS C:\Tools\Scripts\golfing> 2..10+[char[]]'JQKA'|%{$z=' '*(8,7)[$_-eq10];" $(($x='_'*10)) ";"/$(($y=' '*10))\";"| $_$z|";,"|$y|"*5;"|$z$_ |";"\$x/"}
 __________
/          \
| 2        |
|          |
|          |
|          |
|          |
|          |
|        2 |
\__________/
 __________
/          \
| 3        |
|          |
|          |
|          |
|          |
|          |
|        3 |
\__________/
 __________
/          \
| 4        |
...

```

# Answer
> 6 votes
# Python, ~~161~~ ~~160~~ ~~156~~ 149 bytes

*One byte saved by Shebang*

This could use some work but here it is:

```
o=" ";v="_"*10
for x in map(str,range(2,11)+list("JKQA")):print o+v+"\n/",o*9+"\\\n|",x.ljust(8),"|"+("\n|"+o*10+"|")*5+"\n|",o*6+x.ljust(3)+"|\n\\"+v+"/"

```

## Explanation

We make a list of all the ranks in order using `map(str,range(2,11)`. Then we loop through each of the ranks and make a card.

```
print o+"_"*10+"\n/",o*9+"\\\n|",x.ljust(8),"|"+("\n|"+o*10+"|")*5+"\n|",o*6+x.ljust(3)+"|\n\\"+"_"*10+"/"

```

We make the top of the card:

```
o+v+"\n"

```

Then the rank goes on the left:

```
"/",o*9+"\\\n|",x.ljust(8),"|"

```

We use `.ljust` because `10` is two long and all the other ones are one wide.

Then we print the 5 rows in the middle:

```
"|"+("\n|"+o*10+"|")*5+"\n|"

```

and the bottom rank:

```
"\n|",o*6+x.ljust(3)+"|\n"

```

Finally we print the bottom of the card:

```
"\\"+v+"/"

```

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

```
f=
_=>`2345678910JQKA`.replace(/.0?/g,s=>` __________
/          \\
| `+(s+=`   `+s).slice(0,4)+`     |
|     `.repeat(6)+s.slice(-4)+` |
\\__________/
`)
;
document.write('<pre>'+f());
```

# Answer
> 4 votes
# PHP, 233 Bytes

```
foreach([2,3,4,5,6,7,8,9,10,J,Q,K,A]as$k){for($c="",$i=0;$i<10;$i++)$c.=str_pad($i?$i>1&$i<9?"|":($i<2?"/":"\\"):" ",11,$i%9?" ":_).($i?$i>1&$i<9?"|":($i<2?"\\":"/"):" ")."\n";$c[113]=$c[28]=$k;$k>9&&$c[29]=$c[113]=0&$c[112]=1;echo$c;}

```

# Answer
> 4 votes
# Perl, ~~128~~ ~~117~~ 111 bytes

```
map{printf$"."_"x10 ."
/".$"x10 .'\
| %-9s|
'.("|".$"x10 ."|
")x5 ."|%9s |
\\"."_"x10 ."/
",$_,$_}2..10,J,Q,K,A

```

The 6 literal newlines save 1 byte each. **This cannot be run directly from the command line because of the single quotes in lines 2 and 4** in order to save 1 byte by not having to escape a backslash.

Edit: I put Ace at the beginning, but it's supposed to be at the end. It doesn't change the byte count.

Edit 2: -11 bytes: Got rid of some unnecessary statements and added another literal newline. Everything is now output via a single printf.

Edit 3: -5 bytes thanks to @Ton Hospel. But for some reason, I'm getting 111 bytes instead of 112 at home when compared to at work, so I'm going with the byte count my home computer is giving me.

# Answer
> 3 votes
# ///, ~~182~~ 180 bytes

```
/+/_____//*/# |
&//&/@@@@@|# //%/ |
\\\\++\\\/
//$/ ++
\\\/!\\\\
| //#/       //!/#   //@/|!|
/$2*2%$3*3%$4*4%$5*5%$6*6%$7*7%$8*8%$9*9%$10#|
@@@@@|#10 |
\\++\/
$J*J%$K*K%$Q*Q%$A*A%

```

Try it online!

*-2 bytes thanks to m-chrzan*

# Answer
> 3 votes
## Python 3.5, 110 bytes

```
u='_'*10
for c in[*range(2,11),*'JQKA']:print(' %s\n/%%11s\n'%u%'\\'+'| %-6s%2s |\n'*7%(c,*' '*12,c)+'\%s/'%u)

```

Prints

* The top two lines `' %s\n/%%11s\n'%u%'\\'` where `u` is `'_'*10`
* The middle 7 lines `'| %-2s %2s |\n'`, each of which has two string formatting slots. The first and last are filled with the card value, and the rest with spaces for no effect
* The bottom line '\\%s/'%u

Python 3.5's new unpacking features are used in two places. The list of labels `[*range(2,11),*'JQKA']` unpacks the numbers and letters into one list. And, the tuple `(c,*' '*12,c)` unpacks twelve entries of spaces into the center.

# Answer
> 2 votes
## Batch, 236 bytes

```
@echo off
for %%v in (2 3 4 5 6 7 8 9 10 J Q K A)do call:v %%v
exit/b
:v
set s=%1       %1
echo  __________
echo /          \
echo ^| %s:~0,8% ^|
for /l %%l in (1,1,5)do echo ^|          ^|
echo ^| %s:~-8% ^|
echo \__________/

```

I tried golfing this in three different ways but ended up with the same byte count each time...

# Answer
> 2 votes
# Scala, 161 bytes

```
val a=" "*7
val u="_"*10
((2 to 10)++"JQKA")map(_+"")map{x=>val p=" "*(2-x.size)
s" $u \n/$a   \\\n| $x$p$a|\n" + s"|$a   |\n" * 5 + s"|$a$p$x |\n\\$u/\n"}

```

# Answer
> 2 votes
# 05AB1E, ~~71~~ ~~70~~ ~~68~~ ~~66~~ ~~65~~ 64 bytes

Uses CP-1252 encoding.

```
TL¦"JQKA"S«vð'_T×©ððT×…/ÿ\9yg-ð×y"| ÿÿ|"ÂðT×…|ÿ|5×sTÂ‡®…\ÿ/JTä»,

```

Slightly modified link as  doesn't work with `ÿ` on TIO atm.

Try it online!

**Explanation**

`TL¦"JQKA"S«` pushes the list `[2,3,4,5,6,7,8,9,10,J,Q,K,A]`

We then loop over each card value with `v`

`ð'_T×©ð` constructs `" __________ "`
`ðT×…/ÿ\` constructs `"/ \"`
`9yg-ð×y"| ÿÿ|"Â` constructs the 2 rows with card values (the second row is the first reversed)
`ðT×…|ÿ|5×` constructs 5 rows of the form `"| |"`

Then we

```
s     # move the 2nd card value row after the 5 "middle rows"
 TÂ‡  # and replace 1 with 0 and vice versa

```

`®…\ÿ/` constructs the bottom row

```
J       # join everything into 1 string
 Tä     # split into 10 parts
   »,   # merge by newline and print with newline

```

# Answer
> 2 votes
# , 87 bytes

```
i ±_
/± \Ypr|$.Y6P3|r2Lhhr2o\±_/
H8ñy}GP2j6j? _ñ2j$X6jxG"04p/9
rJn.nrQn,nrKn.nrAn.

```

Try it online!

Since this contains some unprintables, here is a hexdump:

```
0000000: 6920 b15f 200a 2fb1 205c 1b59 7072 7c24  i ._ ./. \.Ypr|$
0000010: 2e59 3650 337c 7232 4c68 6872 326f 5cb1  .Y6P3|r2Lhhr2o\.
0000020: 5f2f 0a1b 4838 f179 7d47 5032 6a01 366a  _/..H8.y}GP2j.6j
0000030: 013f 205f f132 6a24 5836 6a78 4722 3034  .? _.2j$X6jxG"04
0000040: 702f 390a 724a 6e2e 6e72 516e 2c6e 724b  p/9.rJn.nrQn,nrK
0000050: 6e2e 6e72 416e 2e                        n.nrAn.

```

# Answer
> 2 votes
# PHP, ~~135~~ ~~131~~ ~~158~~ 134 bytes

Hopefully, I can find a way to shorten this a little more.

```
foreach([2,3,4,5,6,7,8,9,10,J,Q,K,A]as$C)printf(" %'_9s
/%12s| %-8s|%s
|%8s |
\\%'_9s/
",_,'\
',$C,str_repeat('
|         |',5),$C,_);

```

This takes advantage of `printf` to repeat multiple characters and format everything nicely.

---

**Old version:**

Not exactly a piece of beauty, but works!

```
$L=__________;$S='        ';foreach([2,3,4,5,6,7,8,9,10,J,Q,K,A]as$C)echo" $L
/  $S\
| $C".($P=substr($S,$C>9))."|
",str_repeat("|  $S|
",5),"|$P$C |
\\$L/
";

```

---

Thanks to Jörg Hülsermann for detecting a bug and for letting me use part of his code, that reduced it by **4** bytes! And for finding a fatal bug.

# Answer
> 1 votes
# Ruby, 115 bytes

Fairly straightforward use of `printf`.

```
([*(?2.."10")]+%w{J Q K A}).map{|e|printf" #{u=?_*10}
/%11s
| %-9s|
#{(?|+' '*10+"|
")*5}|%9s |
\\#{u}/
",?\\,e,e}

```

# Answer
> 1 votes
## Racket 327 bytes

```
(let*((ms make-string)(p #\space)(e? equal?)(sa string-append)(f(λ(s)(display(sa" "(ms 10 #\_)" \n""/"(ms 10 p)"\\\n""| "s
(ms(if(e? s"10")7 8)p)"|\n"(apply sa(for/list((i 6))"|          |\n"))"| "(ms(if(e? s"10")6 7)p)s" |\n"
"\\"(ms 10 #\_)"/\n")))))(for((i(range 2 11)))(f(number->string i)))(for((i'("J""Q""K""A")))(f i)))

```

Ungolfed:

```
(define (main)
(let* ((ms make-string)
       (e? equal?)
       (sa string-append)
      (f(lambda(s)
  (display
   (sa
    " "
    (ms 10 #\_)
    " \n"
    "/"
    (ms 10 #\space)
    "\\\n"
    "| " s   (ms (if(e? s "10") 7 8) #\space)   "|\n"
    (apply sa (for/list ((i 6)) "|          |\n"))
    "| "  (ms (if(e? s "10") 6 7) #\space)  s " |\n"
    "\\" (ms 10 #\_) "/\n")
   ))))
(for ((i(range 2 11)))
  (f (number->string i)))
(for ((i '("J" "Q" "K" "A")))
  (f i))
))

```

Testing:

```
(main)

```

Output:

```
 __________
/          \
| 2        |
|          |
|          |
|          |
|          |
|          |
|          |
|        2 |
\__________/
 __________
/          \
| 3        |
|          |
|          |
|          |
|          |
|          |
|          |
|        3 |
\__________/
 __________
/          \
| 4        |
|          |
|          |
|          |
|          |
|          |
|          |
|        4 |
\__________/
 __________
/          \
| 5        |
|          |
|          |
|          |
|          |
|          |
|          |
|        5 |
\__________/
 __________
/          \
| 6        |
|          |
|          |
|          |
|          |
|          |
|          |
|        6 |
\__________/
 __________
/          \
| 7        |
|          |
|          |
|          |
|          |
|          |
|          |
|        7 |
\__________/
 __________
/          \
| 8        |
|          |
|          |
|          |
|          |
|          |
|          |
|        8 |
\__________/
 __________
/          \
| 9        |
|          |
|          |
|          |
|          |
|          |
|          |
|        9 |
\__________/
 __________
/          \
| 10       |
|          |
|          |
|          |
|          |
|          |
|          |
|       10 |
\__________/
 __________
/          \
| J        |
|          |
|          |
|          |
|          |
|          |
|          |
|        J |
\__________/
 __________
/          \
| Q        |
|          |
|          |
|          |
|          |
|          |
|          |
|        Q |
\__________/
 __________
/          \
| K        |
|          |
|          |
|          |
|          |
|          |
|          |
|        K |
\__________/
 __________
/          \
| A        |
|          |
|          |
|          |
|          |
|          |
|          |
|        A |
\__________/

```

# Answer
> 1 votes
# Java 7, 287 bytes

```
String c(){String r="",l="__________",c=(" "+l+" \n/s\\\n| z       |\nxxxxxx|       y|\n\\"+l+"/\n").replace("x","|s|\n").replace("s","          ");for(int i=0;i++<13;r+=c.replace("z",i==10?"10":(l=i<2?"A ":i>12?"K ":i>11?"Q ":i>10?"J ":i+" ")).replace("y",i==10?"10 ":" "+l));return r;}

```

Ok, this is ugly and not very efficient, but it works.. That `10` as special case with a space before at the top and after at the bottom position really screws with everyone..

**Ungolfed & test code:**

Try it here.

```
class M{
  static String c(){
    String r = "",
           l = "__________",
           c = (" " + l + " \n/s\\\n| z       |\nxxxxxx|       y|\n\\" + l + "/\n")
                 .replace("x", "|s|\n")
                 .replace("s", "          ");
    for(int i = 0; i++ < 13; r += c
        .replace("z", i == 10
                       ? "10"
                       : (l = i < 2
                               ? "A "
                               : i > 12
                                  ? "K "
                                  : i > 11
                                     ? "Q "
                                     : i > 10
                                        ? "J "
                                        : i+" "))
        .replace("y", i == 10
                       ? "10 "
                       : " "+l));
    return r;
  }

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

```

**Output:**

```
 __________
/          \
| A        |
|          |
|          |
|          |
|          |
|          |
|          |
|        A |
\__________/
 __________
/          \
| 2        |
|          |
|          |
|          |
|          |
|          |
|          |
|        2 |
\__________/
 __________
/          \
| 3        |
|          |
|          |
|          |
|          |
|          |
|          |
|        3 |
\__________/
 __________
/          \
| 4        |
|          |
|          |
|          |
|          |
|          |
|          |
|        4 |
\__________/
 __________
/          \
| 5        |
|          |
|          |
|          |
|          |
|          |
|          |
|        5 |
\__________/
 __________
/          \
| 6        |
|          |
|          |
|          |
|          |
|          |
|          |
|        6 |
\__________/
 __________
/          \
| 7        |
|          |
|          |
|          |
|          |
|          |
|          |
|        7 |
\__________/
 __________
/          \
| 8        |
|          |
|          |
|          |
|          |
|          |
|          |
|        8 |
\__________/
 __________
/          \
| 9        |
|          |
|          |
|          |
|          |
|          |
|          |
|        9 |
\__________/
 __________
/          \
| 10       |
|          |
|          |
|          |
|          |
|          |
|          |
|       10 |
\__________/
 __________
/          \
| J        |
|          |
|          |
|          |
|          |
|          |
|          |
|        J |
\__________/
 __________
/          \
| Q        |
|          |
|          |
|          |
|          |
|          |
|          |
|        Q |
\__________/
 __________
/          \
| K        |
|          |
|          |
|          |
|          |
|          |
|          |
|        K |
\__________/

```

# Answer
> 1 votes
# R, 175 bytes

```
for(x in c(2:10,"J","Q","K","A")){r=c("|"," ",x,rep(" ",9-nchar(x)),"|");cat(" __________ \n/          \\\n",r,"\n",rep("|          |\n",5),rev(r),"\n\\__________/\n",sep="")}

```

A fairly competitive answer in R this time for an ascii-art challenge and should definitely be golfable.

Try it on R-fiddle

**Ungolfed and explained**

```
for(x in c(2:10,"J","Q","K","A")){          # For each card in vector 1,...,10,J,Q,K,A
    r=c("|"," ",x,rep(" ",9-nchar(x)),"|")  # Create variable for 3rd row called "r".
    ;cat(" __________ \n/          \\\n",   # Print: hardcoded top two rows,
    r,"\n",                                 # 3rd row,
    rep("|          |\n",5),                # Repeat middle section 5 times,
    rev(r),                                 # Reversed 3rd row,
    "\n\\__________/\n",                    # Hardcoded bottom row
    sep="")                                 # Set separator to empty string
}

```

The most interesting aspect where a few bytes are saved is the assignment of the third row:

```
r=c("|"," ",x,rep(" ",9-nchar(x)),"|")

```

Because there are `8` spaces in total between the character denoting the card value and the final `|` (except for `10`) we can repeat `9` spaces and subtract the number of characters in the currently printed card.

By storing each character in the `3rd` row as its own element in the string vector `r` we can reverse the vector and reuse it for the `9th` row.

# Answer
> 1 votes
# C#, 385 Bytes

My first ASCII Art challenge - it was fun!

Golfed:

```
string D(){var d=new string[15];for(int i=2;i<15;i++){var a=i>10?new Dictionary<int,string>(){{ 11,"J"},{12,"Q"},{13,"K"},{14,"A"},}[i]:i+"";var r="|          |";d[i]=string.Join("\n",new string[]{" __________",@"/          \",a.Length>1?"| "+a+"       |":"| "+a+"        |",r,r,r,r,r,a.Length>1?"|       " + a +" |" : "|        "+a+" |",@"\__________/"});}return string.Join("\n",d);}

```

Ungolfed:

```
public string D()
{
  var d = new string[15];

  for (int i = 2; i < 15; i++)
  {
    var a = i > 10 ? new Dictionary<int, string>() {
    { 11, "J" },
    { 12, "Q" },
    { 13, "K" },
    { 14, "A" },
    }[i]
      : i+"";

    var r = "|          |";

    d[i] = string.Join("\n", new string[] {
      " __________",
      @"/          \",
      a.Length > 1 ? "| " + a + "       |" : "| " + a + "        |",
      r,
      r,
      r,
      r,
      r,
      a.Length > 1 ? "|       " + a +" |" : "|        " + a +" |",
      @"\__________/"});
  }

  return string.Join("\n", d);
}

```

# Answer
> 1 votes
# Actually, 91 bytes

```
"JQKA"#9⌐2x+`;k' ;'_9u*@++'\' 9u*'/++"| {:<9}|"5'|;' 9u*@++n"|{:>9} |"'/'_9u*'\++kp@'
jf`Mi

```

Try it online!

## Explanation

Part 1: setting up the list of face values:

```
"JQKA"#9⌐2x+`PART 2 CODE`Mi
       9⌐2x                  range(2,11) ([2, 10])
"JQKA"#    +                 extend with ["J", "Q", "K", "A"]
            `PART 2 CODE`M   do Part 2 for each item in list
                          i  flatten resulting list and implicitly print

```

Part 2: creating the cards (newline replaced with `\n` for readability):

```
;k' ;'_9u*@++'\' 9u*'/++"| {:<9}|"5'|;' 9u*@++n"|{:>9} |"'/'_9u*'\++kp@'\njf
;k                                                                            duplicate the face value, push both copies to a list
  ' ;'_9u*@++                                                                 construct the top line
             '\' 9u*'/++                                                      construct the second line
                        "| {:<9}|"                                            create a format string to place the value in a left-aligned 9-width field in the top left of the card, one space away from the edge
                                  5'|;' 9u*@++n                               create 5 copies of the blank middle section
                                               "|{:>9} |"                     like before, but right-align the face value
                                                         '/'_9u*'/++          construct the bottom of the card
                                                                    kp@'\nj   push entire stack to a list, pop the list containing the face values out of that list, and join the rest (the card strings) with newlines
                                                                           f  format the card with the face values

```

---
Tags: code-golf, ascii-art, kolmogorov-complexity, card-games
---


title: Palindromize this string!

text:
# Question
Title: Palindromize this string!
Your task is to palindromize a string as follows:

Take the string.

```
abcde

```

Reverse it.

```
edcba

```

Remove the first letter.

```
dcba

```

Glue it onto the original string.

```
abcdedcba

```

But here's the catch: since this challenge is about palindromes, **your code itself also has to be a palindrome.**

Remember, this is , so the code with the smallest number of bytes wins.

# Answer
> 17 votes
# Python 3, 41 bytes

```
lambda t:t+t[-2::-1]#]1-::2-[t+t:t adbmal

```

Try it here.

# Answer
> 16 votes
# 05AB1E, 1 byte

```
û

```

Try it online!

# Answer
> 15 votes
# Dip, 1 byte

```
B

```

Body must be at least 30 characters; you entered 13.

# Answer
> 14 votes
# Pyth - 13 bytes

It kinda looks like its crying.

```
+Qt_Q " Q_tQ+

```

Try it online here.

# Answer
> 11 votes
# 아희(Aheui), ~~149~~ 137 bytes (47 chars + 2 newlines)

```
붛뱐쎤붇쎡뻐처순의이멓희
빠본땨벌다따토먀의썩속썩의먀토따다벌땨본빠
희멓이의순처뻐쎡붇쎤뱐붛

```

Due to the nature of the Aheui language, the input must end in a double quotation mark (") (gets ignored).

Try it here! (copy and paste the code)

**Bonus (each line is palindromic)**, 131 bytes (42 chars + 5 newlines)

```
밯빪반분반빪밯
쏜발뚝볃뚝발쏜
쏙툼닿뗘닿툼쏙
뽓첡순괆순첡뽓
숙쌱멈긕멈쌱숙
몋희익욥익희몋

```

# Answer
> 4 votes
# APL -- 13 bytes.

```
⊣,¯1↓⌽⍝⌽↓1¯,⊣

```

Explanation:

```
⊣,¯1↓⌽
     ⌽ Reverse the argument.
  ¯1↓  Drop the last character.
⊣,     Concatenate the original to the result.

```

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

```
s=>s+[...s].reverse().slice(1).join("")//)""(nioj.)1(ecils.)(esrever.]s...[+s>=s

```

I tried a smarter solution but it's still longer :/ even abusing `[,...a]=s` didn't seem to save bytes

# Answer
> 3 votes
# J, 17 bytes

```
}:,|.NB. .BN.|,:}

```

Takes the easy way out by using a comment to mirror the code. In J, `NB.` starts a line comment. I do hope to find a method that doesn't involve a comment but the digrams in J probably do make it harder.

Also forms two smileys, `}:` and `:}`.

## Usage

```
   f =: }:,|.NB. .BN.|,:}
   f 'abcde'
abcdedcba

```

## Explanation

Comment part removed since it is just filler.

```
}:,|.  Input: string S
   |.  Reverse S
}:     Curtail, get S with its last char removed
  ,    Join them and return

```

# Answer
> 3 votes
# C#, (~~51~~ 50 + 1)\*2 = ~~104~~ 102 bytes

saved 2 bytes to the use of `.Aggregate()`

```
s=>s+s.Aggregate("",(a,b)=>b+a,s=>s.Substring(1));//;))1(gnirtsbuS.s>=s,a+b>=)b,a(,""(etagerggA.s+s>=s

```

You can capture this lambda with

```
Func<string,string> f = <lambda here>

```

and call it like this

```
f("abcde")

```

# Answer
> 2 votes
## Ruby, 47 bytes

```
->s{s+s.reverse[1..-1]}#}[1-..1]esrever.s+s{s>-

```

# Answer
> 2 votes
# Mathematica, 67 bytes

```
f=#~Join~Rest@Reverse@#//Function;noitcnuF//#@esreveR@tseR~nioJ~#=f

```

Defines a named function `f` that takes a list of characters as input and returns the appropriate palindromized list as output. The bit after the semicolon (is fortunately syntactically valid and) gives a second, way more complicated name to this same function.

It was fun trying to make Mathematica make sense without any brackets!

# Answer
> 2 votes
# Brachylog, 11 bytes

```
:Lc.r
r.cL:

```

Try it online!

### Explanation

```
:Lc.         Input concatenated with a string L results in the Output
   .r(.)     The Output reversed is still the Output

```

The second line is a new predicate declaration that never gets called in that code.

# Answer
> 2 votes
# Actually, ~~14~~ 13 bytes

```
RiXßRkΣkRßXiR

```

Try it online!

**Explanation**

```
R          # reverse input
 i         # flatten
  X        # discard top of stack
   ßR      # push reversed input
     kΣ    # concatenate each
k          # wrap in list
 R         # reverse
  ß        # push input
   X       # discard it
    i      # flatten list to string
     R     # reverse string

```

# Answer
> 2 votes
## Pyke, 1 bytes

```
s

```

Try it here!

Yes, this is the same builtin as the digital root one. This time it takes a sting and turns it into a palindrome. Added with this commit (actually on the same day as the digital root question)

# Answer
> 1 votes
# PHP, 38+39=77 bytes

```
<?=($s=$argv[1]).substr(strrev($s),1);#;)1,)s$(verrts(rtsbus.)]1[vgra$=s$(=?<

```

stupid restriction ... for non-eso languages :)

# Answer
> 1 votes
# WinDbg, ~~142~~ 287 bytes

```
db$t0 L1;.for(r$t1=@$t0;@$p;r$t1=@$t1+1){db$t1 L1};r$t3=@$t1-1;.for(r$t1=@$t1-3;@$t1>=@$t0;r$t1=@$t1-1;r$t3=@$t3+1){m$t1 L1 $t3};eb$t3 0;da$t0;*;0t$ad;0 3t$be;}3t$ 1L 1t$m{)1+3t$@=3t$r;1-1t$@=1t$r;0t$@=>1t$@;3-1t$@=1t$r(rof.;1-1t$@=3t$r;}1L 1t$bd{)1+1t$@=1t$r;p$@;0t$@=1t$r(rof.;1L 0t$bd

```

*+145 bytes to make it a palindrome, nearly missed that requirement...*

Input is passed in via an address in psuedo-register `$t0`. For example:

```
eza 2000000 "abcde"           * Write string "abcde" into memory at 0x02000000
r $t0 = 33554432              * Set $t0 = 0x02000000
* Edit: Something got messed up in my WinDB session, of course r $t0 = 2000000 should work
* not that crazy 33554432.

```

This may be more golfable, for example I feel like there should be an easier way to convert a memory address in a register to the value at that address.

It works by concatenating the chars from the second-to-last to the first to the end of the string.

```
db $t0 L1;                                      * Set $p = memory-at($t0)
.for (r $t1 = @$t0; @$p; r $t1 = @$t1 + 1)      * Set $t1 = $t0 and increment until $p == 0
{
    db $t1 L1                                   * Set $p = memory-at($t1)
};
r $t3 = @$t1 - 1;                               * Point $t3 at end of string

* From the second-to-last char, reverse through the string with $t1 back to the start ($t0)
* and continue to increment $t3 as chars are appended to the string.
.for (r $t1 = @$t1 - 3; @$t1 >= @$t0; r $t1 = @$t1 - 1; r $t3 = @$t3 + 1)
{
    m $t1 L1 $t3                                * Copy char at $t1 to end of string ($t3)
};
eb $t3 0;                                       * Null terminate the new string
da $t0;                                         * Print the palindrome string

* Comment of the previous code in reverse, making the whole thing a palindrome
*;0t$ad;0 3t$be;}3t$ 1L 1t$m{)1+3t$@=3t$r;1-1t$@=1t$r;0t$@=>1t$@;3-1t$@=1t$r(rof.;1-1t$@=3t$r;}1L 1t$bd{)1+1t$@=1t$r;p$@;0t$@=1t$r(rof.;1L 0t$bd

```

Output:

```
0:000> eza 2000000 "abcde"
0:000> r $t0 = 33554432
0:000> db$t0 L1;.for(r$t1=@$t0;@$p;r$t1=@$t1+1){db$t1 L1};r$t3=@$t1-1;.for(r$t1=@$t1-3;@$t1>=@$t0;r$t1=@$t1-1;r$t3=@$t3+1){m$t1 L1 $t3};eb$t3 0;da$t0;*;0t$ad;0 3t$be;}3t$ 1L 1t$m{)1+3t$@=3t$r;1-1t$@=1t$r;0t$@=>1t$@;3-1t$@=1t$r(rof.;1-1t$@=3t$r;}1L 1t$bd{)1+1t$@=1t$r;p$@;0t$@=1t$r(rof.;1L 0t$bd
02000000  61                                               a
02000000  61                                               a
02000001  62                                               b
02000002  63                                               c
02000003  64                                               d
02000004  65                                               e
02000005  00                                               .
02000000  "abcdedcba"

```

# Answer
> 1 votes
# Java 7, 146 bytes

(Enter is added for readibility and not part of the code.)

```
String c(String s){return s+new StringBuffer(s).reverse().substring(1);}/
/};)1(gnirtsbus.)(esrever.)s(reffuBgnirtS wen+s nruter{)s gnirtS(c gnirtS

```

# Answer
> 1 votes
# Java 7, 152 bytes

```
String c(char[]s,int i){return s.length==i+1?s[i]+"":s[i]+c(s,++i)+s[i-1];}//};]1-i[s+)i++,s(c+]i[s:""+]i[s?1+i==htgnel.s nruter{)i tni,s][rahc(c gnirtS

```

# Answer
> 1 votes
# Haskell, ~~46~~ 44 bytes

```
p s=init s++reverse s--s esrever++s tini=s p

```

Try it on Ideone. Saved 2 bytes thanks to Damien.

Straight forward solution. `init` takes everything but the last character of a string (or last element of a list). `--` enables a single line comment.

# Answer
> 1 votes
# R, 107 bytes

This is the boring solution which just uses comments to make it a palindrome.

```
cat(x<-scan(,""),rev(strsplit(x,"")[[1]])[-1],sep="")#)""=pes,]1-[)]]1[[)"",x(tilpsrts(ver,)"",(nacs-<x(tac

```

# R with few comments, 271 bytes

While this code is longer, only 89 of the bytes (33%) are comments, rather than the 50% in the above code. R relies extensively on parentheses for function application, so this was rather difficult.

```
`%q%`=function
(x,y)cat(x,y,sep=e)#
`%p%`=function
(x,y)`if`(length(y),rev(y)[-1],x)#
x=strsplit(scan(,e<-""),e)[[1]]#
n=NULL
e%q%x%p%n
n%p%x%q%e
LLUN=n
#]]1[[)e,)""-<e,(nacs(tilpsrts=x
#)x,]1-[)y(ver,)y(htgnel(`fi`)y,x(
noitcnuf=`%p%`
#)e=pes,y,x(tac)y,x(
noitcnuf=`%q%`

```

# Answer
> 0 votes
# Perl 5, 44 bytes

43 bytes, plus 1 for `-pe` instead of `-e`

```
s#(.*).#$&.reverse$1#e#1$esrever.&$#.)*.(#s

```

# Answer
> 0 votes
# C, 162 bytes

```
f(char*c,char*d){char*e=c;while(*d++=*c++);c-=2;d-=2;do{*d++=*c--;}while(e<=c);}//};)c=<e(elihw};--c*=++d*{od;2=-d;2=-c;)++c*=++d*(elihw;c=e*rahc{)d*rahc,c*rahc(f

```

Ungolfed, unpalindromized:

```
f(char* c,char* d){
 char*e=c;
 while(*d++=*c++);
 c-=2;d-=2;
 do{*d++=*c--;}while(e<=c);
}

```

`c` is is input string, assumes output string `d` has sufficient length.

Usage:

```
int main() {
 char a[] = "abcde";
 char* b=malloc(strlen(a)*2);
 f(a,b);
 printf("%s\n",b);
}

```

# Answer
> 0 votes
# , 16 chars / 20 bytes

```
ï+ïĦ⬮Đ1//1Đ⬮Ħï+ï

```

`Try it here (ES6 browsers only).`

Generated from the interpreter console using this:

```
c.value=`ï+ï${alias(String.prototype,'reverse')}⬮${alias(String.prototype,'slice')}1//1${alias(String.prototype,'slice')}⬮${alias(String.prototype,'reverse')}ï+ï`

```

---
Tags: code-golf, restricted-source, palindrome
---


title: The PPCG Handicap System

text:
# Question
Title: The PPCG Handicap System
As we all know, meta is overflowing with complaints about scoring code-golf between languages (yes, each word is a separate link, and these may be just the tip of the iceberg).

With so much jealousy towards those who actually bothered to look up the Pyth documentation, I thought it would be nice to have a little bit more of a constructive challenge, befitting of a website that specializes in code challenges.

---

The challenge is rather straightforward. As **input**, we have the **language name** and **byte count**. You can take those as function inputs, `stdin` or your languages default input method.

As **output**, we have a **corrected byte count**, i.e., your score with the handicap applied. Respectively, the output should be the function output, `stdout` or your languages default output method. Output will be rounded to integers, because we love tiebreakers.

Using the most ugly, hacked together query (link \- feel free to clean it up), I have managed to create a dataset (zip with .xslx, .ods and .csv) that contains a snapshot of **all** answers to questions. You can use this file (and assume it to be available to your program, e.g., it's in the same folder) or convert this file to another conventional format (`.xls`, `.mat`, `.sav` etc - but it may only contain the original data!). The name should remain `QueryResults.ext` with `ext` the extension of choice.

---

Now for the specifics. For each language, there is a Boilerplate \\$B\\$ and Verbosity \\$V\\$ parameters. Together, they can be used to create a linear model of the language. Let \\$n\\$ be the actual number of bytes, and \\$c\\$ be the corrected score. Using a simple model \\$n=Vc+B\\$, we get for the corrected score:

$$c = \frac{n-B}V$$

Simple enough, right? Now, for determining \\$V\\$ and \\$B\\$. As you might expect, we're going to do some linear regression, or more precise, a least squares weighted linear regression. I'm not going to explain the details on that - if you're not sure how to do that, Wikipedia is your friend, or if you're lucky, your language's documentation.

The data will be as follows. Each data point will be the byte count \\$n\\$ and the question's average bytecount \\$c\\$. To account for votes, the points will be weighted, by their number of votes plus one (to account for 0 votes), let's call that \\$v\\$. Answers with negative votes should be discarded. In simple terms, an answer with 1 vote should count the same as two answers with 0 votes.

This data is then fitted into the aforementioned model \\$n=Vc+B\\$ using weighted linear regression.

---

**For example**, given the data for a given language

$$ \begin{array} \\ n\_1=20, & c\_1=8.2, & v\_1=1 \\ n\_2=25, & c\_2=10.3, & v\_2=2 \\ n\_3=15, & c\_3=5.7, & v\_3=5 \end{array}$$

Now, we compose the relevant matrices and vectors \\$A\\$, \\$y\\$ and \\$W\\$, with our parameters in the vector

$$ A = \left\[\begin{matrix} 1 & c\_1 \\ 1 & c\_2 \\ 1 & c\_3 \\ \end{matrix}\right\] y = \left\[\begin{matrix} n\_1 \\ n\_2 \\ n\_3 \\ \end{matrix}\right\] W = \left\[\begin{matrix} 1 & 0 & 0 \\ 0 & 2 & 0 \\ 0 & 0 & 5 \\ \end{matrix}\right\] x = \left\[\begin{matrix} B \\ V \\ \end{matrix}\right\] $$

we solve the matrix equation (with \\${}^T\\$ denoting the matrix transpose)

$$A^TWAx=A^TWy$$

for \\$x\\$ (and consequently, we get our \\$B\\$ and \\$V\\$ parameter).

---

Your **score** will be the output of your program, when given your own language name and bytecount. So yes, this time even Java and C++ users can win!

**WARNING: The query generates a dataset with a lot of invalid rows due to people using 'cool' header formatting and people tagging their questions as . The download I provided has most of the outliers removed. Do NOT use the CSV provided with the query.**

Happy coding!

# Answer
# Mathematica, 244.719 (245 bytes)

```
f[l_,n_]:=x/.Solve[d=Rest@Import@"QueryResults.csv";LinearModelFit[#.#2/Tr@#&@@{#~Max~-1&/@#4+1,#3}&@@Thread@#&/@{#,#~Cases~{_,l,__}}&/@d~GroupBy~Last/@#[[;;,1,5]],x,x,Weights->Tr/@#[[;;,;;,4]]]&[d~Cases~{_,l,_,v_/;v>=0,_}~GatherBy~Last]@x==n,x]

```

---

**Test case**

```
f["mathematica", n]   (* { .820033 (n + 53.4263) } *)
f["mathematica", 245] (* { 244.719 } *)

```

What about other languages?

```
f["c++", n]           (* { .821181 (n - 79.5437) } *)
f["java", n]          (* { .717579 (n - 56.0858) } *)
f["cjam", n]          (* { 2.21357 (n + 2.73772) } *)
f["pyth", n]          (* { 4.52194 (n - 8.82806) } *)

```

---

## **Alternative model**: \\$\log(c)=\log\left(\frac{n-B}V\right)\\$

One notable feature of code golf (and probably other coding problems) is that the distribution of the lengths of programs tends to be exponential distribution (in contrast to uniform distribution). Hence model \\$\log(n)=\log(Vc+B)\\$ is much more likely to balance the influences between points with large \\$c\\$ and small \\$c\\$.

As we can see in the graphs below, the distribution of points are suitable for fitting in logarithmic scale.

---

**Results of the new model**

```
Language       V       B

Python       1.365   -19.4
Javascript   1.002     1.6
Ruby         0.724     1.7
Perl         1.177   -32.7
C            1.105     1.5
Haskell      1.454   -24.5
Mathematica  1.319   -39.7
PHP          1.799   -62.0
Java         1.642     4.4
C#           1.407     4.5

CJam         0.608   -12.5
Pyth         0.519   -11.4
Golfscript   0.766   -18.0
J            0.863   -21.4
APL          0.744   -17.7
K            0.933   -23.3
Retina       1.322   -37.9
MATL         0.762   -13.3
Jelly        0.965   -23.8

```

We have found two exceptional language - Ruby with \\$V=0.72\\$\` and Retina with \\$V=1.322\\$, and a criterion of being a popular golfing language - having a large negative boilerplate.
> 22 votes

# Answer
# Python3, 765.19 (765) bytes

Probably some room for golfing here. Requires numpy for matrix stuff. Reads from stdin, formatted as follows: \[lang\] \[bytes/n\]. Stops when you send q.

```
import numpy as n,csv
L={};Q={};X={};D=n.dot;f=open('QueryResults.csv',encoding="utf8");R=csv.reader(f);f.readline();Z=list.append;M=n.matrix
for r in R:
 if r[1] not in L:L[r[1]]=[]
 if r[4] not in Q:Q[r[4]]=[]
 Z(L[r[1]],r);Z(Q[r[4]],r)
for l in L:
 b=[];a=[];v=[];t=[]
 for r in L[l]:
  if int(r[3])>-1:
   Z(b,int(r[2]));o=[]
   for q in Q[r[4]]:Z(o,int(q[2]))
   Z(a,sum(o)/len(o));Z(v,int(r[3])+1)
 for k in a:Z(t,[1,k])
 if len(t)<1:continue
 A=M(t);T=A.transpose();W=n.diag(v);y=M(b).reshape((len(b),1));e=D(D(T,W),A)
 if n.linalg.det(e)==0:continue
 i=n.linalg.inv(e);X[l]=D(i,D(D(T,W),y))
p=input()
while(p!="q"):
 S=p.split()
 if S[1]=='n':print("(n-("+str(X[S[0]].item(0))+"))/"+str(X[S[0]].item(1)))
 else:print(str((int(S[1])-X[S[0]].item(0))/X[S[0]].item(1)))
 p=input()

```

### Results

I might have done something wrong at some point; I get different results than the Mathematica answer:

```
python3 808 -> 765.19
python3 n   -> (n-(32.41))/1.01

c++ n        -> (n-(71.86))/1.17
cjam n       -> (n-(-14.09))/0.51
java n       -> (n-(18.08))/1.64
pyth n       -> (n-(1.42))/0.28
jelly n      -> (n-(-4.88))/0.34
golfscript n -> (n-(-0.31))/0.44

```
> 3 votes

---
Tags: code-challenge, statistics
---


title: A day at the Horse Races

text:
# Question
Title: A day at the Horse Races
## Background

Back in the late 90's / first 00's when Flash Web Design was so much cool that noone could live without having a full Flash website, or at least an animated widget, I was hired to develop a "horse races viewer" in Flash/Actionscript, in the shape of an 80's videogame style animation, so the site's visitors could not only read the race results, but they could see it in a moving animation! *WOW! Impressive!*

They provided me a CSV file with all the races details: start and arrival order, horse names, driver names, prizes, etc. My Flash app read that file for each race and displayed the above said animation.

Nowadays the Flash support is significantly declined, so we must revert to **ascii-art**!

## Task

Your task is to create a full program or function that reads the race data in CSV format from standard input and outputs an ascii-art representation of the race as shown in the example below.

**INPUT**

CSV data with 2 fields: 1) start order; 2) arrival time at the Finish in the format `1.13.4` (1 minute, 13 seconds, 4 tenths of second). If the time reports `R` means that the horse is Retreated (didn't finish the race) due to incident, fall or other reason. Note: The arrival time could be the same for 2 or more horses, in this case they share the arrival position.

```
1,1.13.4
2,1.13.0
3,R
4,1.12.7
5,1.11.5
6,1.13.4
7,1.12.1
8,1.17.9

```

**OUTPUT**

For each CSV row, output a racetrack like this:

```
1_|______________4(1.13.0)___________________________

```

The racetrack is composed by:

* `1` which is the horses start order.
* `_|` where `_` is a spacer and the `|` is the finish line.
* 50 x `_` that represents 50 tenths of second.
* `5(1.13.4)` that is the arrival position followed by the arrival time. This must be positioned respecting the time differences between horses. For example: you position the 1st arrived on the Finish line at time `1.11.5`, the second arrives at time `1.12.1`, the difference is `1.12.1 - 1.11.5 = 6` tenths of second, so the second horse should be positioned at the 6th character, and so on. If the time difference is more than 50 tenths of seconds (or 5 seconds) you must position the horse at the end. The same if the horse is `R` (Retreated).

So the whole racetrack for the CSV data above should be:

```
  F=Finish line
1_|____________________________5(1.13.4)_____________
2_|______________4(1.13.0)___________________________
3_|__________________________________________________R
4_|___________3(1.12.7)______________________________
5_1(1.11.5)__________________________________________
6_|____________________________5(1.13.4)_____________
7_|_____2(1.12.1)____________________________________
8_|__________________________________________________6(1.17.9)
  012345678901234567890123456789012345678901234567890

```

There is no need to add `F=Finish line`, and the last line `0123456789...` that is only for explaining purpose.

## Test cases

```
RACE:
1,1.14.9
2,R
3,R
4,1.14.2
5,1.15.2
6,1.15.3
7,1.15.3

RACE:
1,1.13.6
2,1.13.8
3,R,
4,1.15.9
5,1.13.8
6,R,
7,1.14.4
8,1.15.6
9,1.14.1
10,1.13.9
11,1.13.2
12,1.14.3
13,1.15.0

RACE:
1,1.13.4
2,1.13.0
3,R
4,1.12.7
5,1.11.5
6,1.13.4
7,1.12.1
8,1.17.9

RACE:
1,1.17.3
2,1.20.4
3,1.17.0
4,1.18.8
5,1.18.5
6,1.18.4
7,1.18.4
8,1.17.8
9,1.18.3
10,1.18.7
11,R

RACE:
1,1.17.5
2,R
3,1.17.7
4,1.16.9
5,1.16.1
6,1.18.9

RACE:
1,1.12.8
2,1.13.0
3,1.13.2
4,1.12.7
5,1.11.5
6,1.13.0
7,1.12.1
8,1.12.8

```

## Rules

* Shortest code wins.

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

Takes an array of time strings `"1.ss.t"` as input. The start order is implicit.

```
a=>a.map((t,i)=>(u='_',++i>9?'':' ')+i+u+u.repeat(x=(x=t>'9'?50:t.slice(2)*10-s[0].slice(2)*10)>50?50:x,p=s.indexOf(t)+1+`(${t})`).replace(u,'|')+(x<50?p:'')+u.repeat((x=50-p.length-x)>0?x:0)+(x>0?'':t>'9'?t:p),s=a.filter((v,i)=>a.indexOf(v)==i).sort()).join`
`

```

### Demo

```
let f =

a=>a.map((t,i)=>(u='_',++i>9?'':' ')+i+u+u.repeat(x=(x=t>'9'?50:t.slice(2)*10-s[0].slice(2)*10)>50?50:x,p=s.indexOf(t)+1+`(${t})`).replace(u,'|')+(x<50?p:'')+u.repeat((x=50-p.length-x)>0?x:0)+(x>0?'':t>'9'?t:p),s=a.filter((v,i)=>a.indexOf(v)==i).sort()).join`
`

console.log(f([
  "1.13.4",
  "1.13.0",
  "R",
  "1.12.7",
  "1.11.5",
  "1.13.4",
  "1.12.1",
  "1.17.9"
]));

console.log(f([
  "1.13.6",
  "1.13.8",
  "R",
  "1.15.9",
  "1.13.8",
  "R",
  "1.14.4",
  "1.15.6",
  "1.14.1",
  "1.13.9",
  "1.13.2",
  "1.14.3",
  "1.15.0"
]));
```

# Answer
> 1 votes
# Python 2, ~~282~~ ~~272~~ 246 bytes

Similar to Arnauld the input is assumed to be already stripped from the starting number since it is implicit.

```
H=input().split("\n")
T=[float(c[2:])if c[2:]else 99for c in H]
P=[min(int(10*(t-min(T))),50)for t in T]
S=sorted(list(set(T)))
i=0
u="_"
for h,p,t in zip(H,P,T):i+=1;s=S.index(t)+1;print`i`+u+"|"*(s>1)+u*p+[h,"%d(%s)"%(s,h)][t<99]+u*(41-p+(s<2))

```

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


# Question
Title: shortest progam to scan a line and print it using befunge!
well, I'm newly introduced to befunge. it seems to be an amazing language but a bit hard to start with! anyway after about 2 hours of hard work I've created a code which could read a line from stdin and write same line into stdout(I'm using line -1 as buffer in this code):

```
0> :~:a-#v_$$v vg-10:-1< >$>:#,_@
 ^+1p-10\<   >0>\:    #^_^

```

since I'm new to this language I wanted to know if there is a shorter code to do such a thing. I'm currently using Rc/funge-98 v2 interpreter. note that none-trailing whitespaces are counted in your code.

# Answer
since it seems no one could create 7 character program, here is what I did. it works at least with befunge!

## Befunge, 7

```
~:,a`j@

```
> 1 votes

# Answer
# Befunge-98, 4

`~,#@`

Try it online!

It works because `~` acts like `r` when there is no more input (credit to David Holderness for finding this in the funge-98 spec)
> 6 votes

# Answer
## Befunge, 10

```
~:,a`!#@_

```

You were thinking a bit too hard about it I think :)
> 2 votes

---
Tags: code-golf, befunge
---


title: 1, 2, 3, 4, 5, Shaggy

text:
# Question
Title: 1, 2, 3, 4, 5, Shaggy
This is my first code golf exercise for you: Your input is two integers n and k. You can assume n \>= 1 and k \>= 1 You have to output all numbers from 1 to n (inclusively) and replace every element that is a multiple of k or that contains k with "Shaggy".

you can take the input in any convenient form and output it in a human readable form (seperators can be whitespaces, commas or whatever)

Standard loop holes are forbidden. Functions or programs are acceptable. Shortest code in byte wins!

This is different from the "Bzzt"-game, as this takes a variable "Bzzt" parameter, which, for values\>=10, may increase the difficulty in some languages.

**Examples:**

```
Input: 20 6
Output: 1 2 3 4 5 Shaggy 7 8 9 10 11 Shaggy 13 14 15 Shaggy 17 Shaggy 19 20

Input: 21 4
Output: 1 2 3 Shaggy 5 6 7 Shaggy 9 10 11 Shaggy 13 Shaggy 15 Shaggy 17 18 19 Shaggy 21

Input: 212 11
Output: 1 2 3 4 5 6 7 8 9 10 Shaggy 12 13 14 15 16 17 18 19 20 21 Shaggy 23 24 25 26 27 28 29 30 31 32 Shaggy 34 35 36 37 38 39 40 41 42 43 Shaggy 45 46 47 48 49 50 51 52 53 54 Shaggy 56 57 58 59 60 61 62 63 64 65 Shaggy 67 68 69 70 71 72 73 74 75 76 Shaggy 78 79 80 81 82 83 84 85 86 87 Shaggy 89 90 91 92 93 94 95 96 97 98 Shaggy 100 101 102 103 104 105 106 107 108 109 Shaggy Shaggy Shaggy Shaggy Shaggy Shaggy Shaggy Shaggy Shaggy Shaggy 120 Shaggy 122 123 124 125 126 127 128 129 130 131 Shaggy 133 134 135 136 137 138 139 140 141 142 Shaggy 144 145 146 147 148 149 150 151 152 153 Shaggy 155 156 157 158 159 160 161 162 163 164 Shaggy 166 167 168 169 170 171 172 173 174 175 Shaggy 177 178 179 180 181 182 183 184 185 186 Shaggy 188 189 190 191 192 193 194 195 196 197 Shaggy 199 200 201 202 203 204 205 206 207 208 Shaggy 210 Shaggy 212

```

# Answer
# Pyth, ~~25~~ 23 bytes

```
m?|!%dQ}`Q`d"Shaggy"dSE

```

A program that takes input of two newline-separated integers `k, n` and prints a list.

Try it online!

**How it works**

```
m?|!%dQ}`Q`d"Shaggy"dSE  Program. Inputs: Q, E
m                    SE  Map over [1, 2, 3, 4, ..., E] with varaible d:
 ?                         If
    %dQ                    d % Q
   !                       negated is truthy (divisible by H)
  |                        or
        `Q                 str(Q)
       }                   is in
          `d               str(d):
            "Shaggy"         Yield "Shaggy"
                           Else:
                    d        Yield d
                           Implicitly print

```
> 4 votes

# Answer
# Python 2, ~~64~~ 63 bytes

Anonymous function with arguments `n` and `k`, returns the list to output.

```
lambda n,k:[[i,'Shaggy'][i%k<1or`k`in`i`]for i in range(1,n+1)]

```

Alternatively, a function which prints to `STDOUT` for the same bytecount:

```
def f(n,k,i=1):exec"print[i,'Shaggy'][i%k<1or`k`in`i`];i+=1;"*n

```
> 8 votes

# Answer
# SQL (PostgreSQL flavour), 130 ~~136~~ bytes

Done as a prepared statement:

```
prepare p(int,int)as select CASE WHEN i%$2=0or i::char like'%'||$2||'%'THEN'Shaggy'else i::char end from generate_series(1,$1)a(i)

```

This is executed in the following manner

```
execute p(20,6)

```

and the result is output as rows.
> 3 votes

# Answer
# Lua, ~~71~~ 70 Bytes

*Saved a byte thanks to Flp.Tkc*

Getting in before Jelly or Pyth or similar can swoop in and destroy my byte count.

```
a,b=...for i=1,a do print(((i..""):find(b)or i%b<1)and"Shaggy"or i)end

```

## Ungolfed with comments

```
local a,b = ...                         -- Command Line Input
for i=1, a do                           -- For all numbers between 1 and a
    print(                              -- Print with newlines...
            ((i..""):find(b) or i%b<1)  -- if the String version of i contains b, or if the remainder when i is divided by b == 0
            and "Shaggy"                -- then Shaggy
            or i                        -- Else i
        )
end

```
> 2 votes

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

Having already been soundly beaten by @Flp.Tkc I'll just post my ~~74~~ 72 byte recursive solution because it's different and it works and not because it will win (and also because I like recursive functions).

```
def f(a,b,c=1):
 print(c,"Shaggy")[c%b<1or`b`in`c`]
 if c<a:f(a,b,c+1)

```

**Edit**

-2 by removing the unneeded \`\` around the `c` in the print statement

**From comments:**

Call using

```
 f(a,b)

```

c will default to 1 due to the

```
 c=1

```

in the function definition and can then be incremented for the recursive function calls.
> 2 votes

# Answer
# C, 122 bytes

```
f(n,k){int m,i;for(i=1;i<=n;++i){if(i%k){for(m=i;m>0;m/=10)if(m%10==k)goto l;printf("%d ",i);continue;}l:puts("Shaggy");}}

```

Newlines and spaces both act as separators.
> 1 votes

# Answer
# C#, 97 bytes

```
n=>k=>{var r="";for(int i=1;i<=n;i++)r+=i%k>0&&(i+"").IndexOf(k+"")<0?i+" ":"Shaggy ";return r;};

```

Full program with ungolfed method and test cases:

```
using System;

namespace Shaggy
{
    class Program
    {
        static void Main(string[] args)
        {
            Func<int,Func<int,string>>f= n=>k=>
            {
                var r = "";
                for(int i = 1; i <=n ; i++)
                    r += i % k > 0 && (i + "").IndexOf(k + "") < 0 ? i + " " : "Shaggy ";
                return r;
            };

            Console.WriteLine(f(20)(6));
            Console.WriteLine(f(21)(4));
            Console.WriteLine(f(212)(11));
        }
    }
}

```
> 1 votes

# Answer
# C, ~~98~~ 96 bytes

```
n,h[],t[];s(i,j){for(;n<=i;n&&puts(!strstr(t,h)&&n%j?t:"Shaggy"),n++)sprintf(n?t:h,"%d",n?n:j);}

```

Wandbox
> 1 votes

---
Tags: code-golf
---