# Question
Title: Multiply without multiplying, without loops either
Make a function, method, program or routine that will accept two interger parameters (say `x` and `y`) and the total of the two values multiplied. Except straight multiplication is not allowed so you must not simply do something like:

```
int multiply (int x, int y) {
    return x*y;
}

```

Also you must not use a `for ()` loop, like this:

```
int multiply (int x, int y) {
    int z = 0;
    for (int i = 0;i < y; i++){
        z += x;
    }
    return z;
}

```

Everything else is up to you. A winner is you with the most compact solution.

# Answer
> 1 votes
## Ruby, 27 bytes

```
->i,j{(j!=0)?(i/(1.0/j)):0}

```

# Answer
> 3 votes
# Mathematica, 12 bytes

```
Exp@*Tr@*Log

```

Pure function taking a list of numbers (even complex numbers) as input and returning a number. Takes the logarithm of all the numbers in the list, adds them together, and exponentiates the result. Rules of exponents and logarithms ftw! (And because Mathematica calculates `Log[0]` as `-∞` and can subsequently manipulate that symbolically, it arrives at the correct answer if one input number equals `0`.)

# Mathematica, 24 bytes

```
Tr[1^Flatten@Array[,#]]&

```

Pure function taking a list of nonnegative (unfortunately) integers as input and returning their product. Simply creates an array of the appropriate dimensions and counts the number of entries (using `Tr[1^...]` as a golfy shorthand for `Length@...`). Since we don't care what's actually in the array, we can fill it with `Null`s using `Array[,#]`, which doesn't cost any bytes for the first argument.

# Answer
> 0 votes
# Python, ~~48~~ 39 bytes

-9 bytes thanks to @ovs

```
f=lambda x,y,t=0:x and f(x-1,y,t+y)or t

```

Recursively adds `y` to `t`, and returns the sum of `t` when x is 0.

# Answer
> 0 votes
## Ruby, 22 bytes

```
->a,b{eval ?a<<42<<98}

```

Maybe bending the rules? This is no "straight" multiplication.

# Answer
> 0 votes
# Perl, 19 bytes

18 bytes of code + `-p` flag.

```
s/.*/"$&+"x<>.0/ee

```

Try it online!

It takes two numbers (say `m` and `n`) and converts them into `m+m+...+m+0` (n times) and evaluates this string. (the final `+0` is to make sure that if one of the number is `0`, then the result is `0` and not an empty string)

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


# Question
Title: How many Blackjack sequences in that list?
Your task is to find how many distinct Blackjack sequences can be found in an ordered list of 12 cards.

A Blackjack sequence is defined as a sequence of consecutive cards whose sum of points is exactly 21. Points are counted according to the following table:

```
Symbol | Name  | Points     Symbol | Name  | Points
-------+-------+--------    -------+-------+--------
   2   | Two   | 2             9   | Nine  | 9
   3   | Three | 3             T   | Ten   | 10
   4   | Four  | 4             J   | Jack  | 10
   5   | Five  | 5             Q   | Queen | 10
   6   | Six   | 6             K   | King  | 10
   7   | Seven | 7             A   | Ace   | 1 or 11
   8   | Eight | 8

```

### Input

A 12-character string, using the symbols described above. We do not care about the colors of the cards, so they are not provided.

*Example:*

`K6K6JA3Q4389`

### Output

The number of distinct Blackjack sequences that can be found in the input string.

*Example:*

`K6K6JA3Q4389` includes two distinct Blackjack sequences:

* `JA`, with the Ace being counted as 11 points (10 + 11 = 21)
* `A3Q43`, with the Ace being counted as 1 point (1 + 3 + 10 + 4 + 3 = 21)

So the answer would be `2`.

### Rules

* Two Blackjack sequences are considered distinct if they contain different cards or the same cards in different orders. If the exact same sequence appears at different positions in the input list, it must be counted only once.
* The Blackjack sequences may overlap each other.
* Each kind of card may appear up to 12 times in the sequence. (We assume that the cards are picked from at least 3 different decks.)
* If no Blackjack sequence can be found in the input string, you must return `0` or any other falsy value.
* This is code-golf, so the shortest answer in bytes wins. Standard loopholes are forbidden.

### Test cases

The sequences are provided for information purposes, but you're only required to output the number of them.

```
Input        | Output | Distinct sequences
-------------+--------+--------------------------------------------------------
3282486Q3362 | 0      | (none)
58A24JJ6TK67 | 1      | 8A2
Q745Q745Q745 | 1      | Q74
AAAAAAAAAAAA | 1      | AAAAAAAAAAA
T5AQ26T39QK6 | 2      | AQ, 26T3
JQ4A4427464K | 3      | A442, 44274, 7464
Q74Q74Q74Q74 | 3      | Q74, 74Q, 4Q7
37AQKA3A4758 | 7      | 37A, 37AQ, AQ, AQK, QKA, KA, A3A475
TAQA2JA7AJQA | 10     | TA, TAQ, AQ, QA, A2JA7, 2JA7A, JA, AJ, AJQ, JQA
TAJAQAKAT777 | 13     | TA, TAJ, AJ, JA, JAQ, AQ, QA, QAK, AK, KA, KAT, AT, 777

```

# Answer
# Jelly, ~~30~~ 29 bytes

```
1e×5,⁵Ḥ‘
O_48«26%⁴µSeÇ
ẆÇÐfQL

```

**Try It Online!** or check out the **test suite**

### How?

Note that, if we always value an ace as **1** then the only valid sums are **21** and **11**, the latter being acceptable iff an ace appears in the sequence.

```
ẆÇÐfQL - Main link: string
Ẇ      - all non-empty contiguous sublists
  Ðf   - filter keep if...
 Ç     -     last link (2) as a monad ...is truthy
    Q  - unique results
     L - length

O_48«26%⁴µSeÇ - Link 2, isBlackjackSubtring: char array  e.g. ['A','2','8','Q']
O             - cast to ordinal values                        [ 65, 50, 56, 81]
 _48          - subtract 48                                   [ 17,  2,  8, 33]
     26       - 26
    «         - minimum (vectorises)                          [ 17,  2,  8, 26]
        ⁴     - 16
       %      - modulo                                        [  1,  2,  8, 10]
         µ    - monadic chain separation (call the result v)
          S   - sum(v)                                        21
            Ç - last link (1) as a monad link_1(v)            [11,21]
           e  - exists in?                                    1

1e×5,⁵Ḥ‘ - Link 1 validSums: value list (where A is 1, and {T,J,Q,K} are 10)
1e       - 1 exists in? (are there any aces? Yields 1 or 0)
  ×5     - multiply by 5 (5 or 0)
     ⁵   - 10
    ,    - pair ([5,10] or [0,10])
      Ḥ  - double ([10,20] or [0,20])
       ‘ - increment ([11,21] or [1,21])
         -                        ^
         -     note: if no ace is in the sequence it's sum can't be 1 anyway

```
> 6 votes

# Answer
# Python 2, 215 bytes

```
def b(s,a=[],r=range):
 S=map(lambda x:":">x>"1"and int(x)or 10-(x=="A")*9,s)
 for i in r(12):
  for j in r(13):
   if 21in[x*10+sum(S[i:j])for x in r(S[i:j].count(1)+1)]and s[i:j]not in a:a+=s[i:j],
 return len(a)

```

Comments added:

```
def b(s,a=[],r=range):                                      # Define the function b and a list, a, which holds all the blackjack sequences
 S=map(lambda x:":">x>"1"and int(x)or 10-(x=="A")*9,s)      # Set S to the score of each card in b
 for i in r(12):                                            # Loop with i from 0 to 11
  for j in r(13):                                           # Loop with j from 0 to 12
   if 21in[x*10+sum(S[i:j])for x in r(S[i:j].count(1)+1)]\  # If 21 is included in all the possible sums that the scores between i and j in S can be
           and s[i:j]not in a:                              # And that sequence is not already included,
               a+=s[i:j],                                   # Append that sequence to a
 return len(a)                                              # Return the amount of elements in a

```
> 7 votes

# Answer
## JavaScript (ES6), ~~144~~ ~~138~~ ~~129~~ ~~128~~ ~~126~~ 124 bytes

```
g=([c,...s],a=[],q=new Set)=>c?g(s,[...a,[,21]].map(([x,y,A])=>[x+=c,y-=+c||(c<'B'?A=1:10),A,y&&y^10*A||q.add(x)]),q):q.size

```

Old attempt at 128:

```
s=>(q=new Set,f=s=>s?f(s.slice(1))&f(s.slice(0,-1))&[...s].map(c=>t+=-c||~(c<'B'?A=0:9),t=A=21)|t&&t-10*!A?q:q.add(s):q)(s).size

```
> 3 votes

# Answer
## JavaScript (ES6), 123 bytes

```
f=
t=>eval("for(s=new Set,i=0;t[i];i++)for(a=0,b=21,j=i;c=t[j++];b&&b-a*10||s.add(t.slice(i,j)))b-=+c||(c>'A'?10:a=1);s.size")
```

```
<input oninput=o.textContent=/[^2-9TJQKA]/.test(this.value)?'':f(this.value)><pre id=o>
```
> 3 votes

# Answer
# Python, ~~134~~ 130 bytes

```
lambda x:len({x[i:j]for i in range(12)for j in range(13)if sum(min(26,ord(c)-48)%16for c in x[i:j])in([11,21][~('A'in x[i:j]):])})

```

**Try it online!**

### How?

An unnamed function, taking the string of length 12 as `x`.

`x[i:j]` is a slice of the string from the i+1th to the jth character.

Slices are taken such that we have all sublists by traversing from `i=0` to `i=11` with `for i in range(12)`, for each of which we traverse from `j=0` to `j=12` with `for j in range(13)`.

(We only need `j=i+1` and up, but slices with `j<=i` are just empty strings, so we can golf off 4 bytes from `for j in range(i+1,13)`)

These are filtered for those with the correct sum...

Valid sums are 11 and 21 if there is an ace in a slice, or just 21 if not. `'A'in x[i:j]` gives us this information and `~(v)` performs `-1-v`, which we use to slice `[11,21]` \- thus if an ace is in the sequence we get `[11,21][-2:]` and if not we get `[11,21][-1:]`, resulting in `[11,21]` and `[21]` respectively.

The sum itself needs to treat `A` as 1, digits as their values, and `T`, `J`, `Q`, and `K` as 10. This mapping is achieved by first casting to ordinals:
`" 2 3 4 5 6 7 8 9 T J Q K A"` (without the spaces) becomes
`[50, 51, 52, 53, 54, 55, 56, 57, 84, 74, 81, 75, 65]`, subtracting 48 to get
`[ 2, 3, 4, 5, 6, 7, 8, 9, 36, 26, 33, 27, 17]`, taking the `min` with 26 yields
`[ 2, 3, 4, 5, 6, 7, 8, 9, 26, 26, 26, 26, 17]`, and mod (`%`) sixteen those are
`[ 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 1]`, as required for the sum, `sum(...)`.

The filtered results are place into a set with `{...}`, so only the unique results remain and the length, `len(...)` is the count
> 3 votes

# Answer
# 05AB1E, ~~39~~ ~~38~~ 37 bytes

```
'A1:vTy‚ydè})ŒvyO¸y1åiDT+ì}21å})¹ŒÏÙg

```

Try it online!

**Explanation**

```
'A1:                  # replace A with 1 in input

v      }              # for each card
 Ty‚                  # pair 10 and the card
    yd                # check if the card is a digit
      è               # use this to index into the pair, giving 10 for JQK
        )             # wrap in list
                      # we now have a list of cards as numbers in range [1 ... 10]

Œv               }    # for each sublist
  yO¸                 # create a list with the sum of the sublist
     y1åi    }        # if the sublist contain 1
         DT+ì         # add sum+10 to the list
              21å     # check if 21 is in that list
                  )   # wrap in list
                      # we now have a list with 1 where the sublist sums to 21 and
                      # 0 otherwise

¹Œ                    # get sublists of the input
  Ï                   # keep only those which sum to 21
   Ù                  # remove duplicates
    g                 # count the number of lists

```
> 3 votes

# Answer
## JavaScript (ES6), 112 bytes

```
f=(s,x=[k=0])=>s?f(s.slice(1),x,[...s].map(c=>x[t+=+c||10^(c<'B'?a=11:0),b+=c]||t-21&&t-a?0:x[b]=++k,a=b=t=0)):k

```

This code logic is quite similar to the one used in existing JS answers from ETHproductions and Neil. But it's using a basic array to keep track of the encountered Blackjack sequences rather than a `Set`.

### Formatted and commented

```
f = (                     // given:
  s,                      //  - s = list of cards
  x = [k = 0]             //  - x = array of Blackjack sequences
) =>                      //  - k = number of distinct Blackjack sequences
  s ?                     // if s is not empty:
    f(                    //   do a recursive call:
      s.slice(1),         //     starting at the next card in the list
      x,                  //     without re-initializing x[]
      [...s].map(         //   for each card 'c' in the list:
        c => x[           //
          t+ =            //   update the total number of points:
            +c ||         //     using the number of the card (for 2 ... 9)
            10 ^ (        //     or using 10 for all other cards
              c < 'B' ?   //     except the Ace which is
                a = 11    //     counted as 1 point and sets 'a' to 11
              :           //     (which means that a total number of points
                0         //     of 11 will be considered valid from now on)
            ),            //
          b += c          //   update the current sequence 'b'
        ] ||              //   if x[b] was previously stored as a Blackjack sequence
        t - 21 &&         //   or the total number of points is not equal to 21
        t - a ?           //   and not equal to 'a':
          0               //     do nothing
        :                 //   else:
          x[b] = ++k,     //     store the current sequence in x[] and increment k
        a = b = t = 0     //   initialization of all variables used in map()
      )                   //
    )                     //
  :                       // else:
    k                     //   return k

```

### Test cases

```
f=(s,x=[k=0])=>s?f(s.slice(1),x,[...s].map(c=>x[t+=+c||10^(c<'B'?a=11:0),b+=c]||t-21&&t-a?0:x[b]=++k,a=b=t=0)):k

console.log(f('3282486Q3362')) // 0
console.log(f('58A24JJ6TK67')) // 1
console.log(f('Q745Q745Q745')) // 1
console.log(f('AAAAAAAAAAAA')) // 1
console.log(f('T5AQ26T39QK6')) // 2
console.log(f('JQ4A4427464K')) // 3
console.log(f('Q74Q74Q74Q74')) // 3
console.log(f('37AQKA3A4758')) // 7
console.log(f('TAQA2JA7AJQA')) // 10
console.log(f('TAJAQAKAT777')) // 13
```
> 3 votes

# Answer
# 05AB1E, ~~40 39 38 37~~ 36 bytes

-4 Thanks to Emigna

```
Ç<çJŒÙ'@0:[Ž„èµJuS9:S>D1å2‚T*>sOå½]¾

```

Try it online!

```
Ç<ç                                  # decrement characters by 1
   JŒÙ                               # get all unique substrings
      '@0:                           # replace @ (was A) with 0
          [Ž                      ]  # for everything on the stack
            „èµJuS9:                 # replace what was T,J,Q,K with 9
                    S>D              # increment all values
                       1å2‚T*>       # push [11,21] if there was an A, [1,21] otherwise
                              sO     # sum the values of the cards
                                å½   # increment the counter_variable if the sum
                                     # is in the array
                                   ¾ # end loop and push (print) the counter_variable

```

We need to do the decrement -\> substring -\> increment thing so that face cards are represented by a single digit number.
> 2 votes

# Answer
# Bash \+ Unix utilities, ~~145~~ ~~142~~ 141 bytes

```
for n in {9..155}
{ echo ${1:n%12:n/12};}|sort -u|sed 's/\(.\)/+\1/g;s/A/{1,11}/g;s/[J-T]/10/g;s/^/eval echo $[0/;s/$/]/'|sh|grep -c '\<21\>'

```

Try it online!

Test runs:

```
for x in 3282486Q3362 58A24JJ6TK67 Q745Q745Q745 AAAAAAAAAAAA T5AQ26T39QK6 JQ4A4427464K Q74Q74Q74Q74 37AQKA3A4758 TAQA2JA7AJQA TAJAQAKAT777
  do
    echo -n "$x "
    ./21 "$x"
  done

3282486Q3362 0
58A24JJ6TK67 1
Q745Q745Q745 1
AAAAAAAAAAAA 1
T5AQ26T39QK6 2
JQ4A4427464K 3
Q74Q74Q74Q74 3
37AQKA3A4758 7
TAQA2JA7AJQA 10
TAJAQAKAT777 13

```
> 1 votes

# Answer
# PHP, 240 bytes

```
$a=str_split($argv[1]);foreach($a as$k=>$v)$n[$k]=$v=='A'?1:($v==0?10:$v);for($i=0;$i<=$k;$i++){$s=$a[$i];$r=$n[$i];for($j=$i+1;$j<=$k;$j++){$s.=$a[$j];$r+=$n[$j];if ($r==21||($r==11&&stristr($s,'A')))$f[]=$s;}}echo count(array_unique($f));

```

**Ungolfed :**

```
$a = str_split($argv[1]);
foreach ($a as $k=>$v)
    $n[$k] = $v == 'A' ? 1 : ($v == 0 ? 10 : $v);
for ($i=0; $i<=$k; $i++) {
    $s = $a[$i];
    $r = $n[$i];
    for ($j=$i+1; $j<=$k; $j++) {
        $s .= $a[$j];
        $r += $n[$j];
        if ($r == 21 || ($r == 11 && stristr($s,'A')) )
            $f[] = $s;
    }
}
echo count(array_unique($f));

```

**Try it here!**
> 1 votes

---
Tags: code-golf, subsequence, card-games
---


# Question
Title: Draw an asterisk analog clock for hour N
## Challenge:

Create a function or program that will take an input N (a number from 0 - 24) which represents the HOUR.

Output should draw an analog clock out of asterisks showing the hour N.

#

---

## Notes:

•The minute hand must be longer than the hour hand (in terms of number of asterisks used)

•The minute hand must be at least 2 asterisks.

•Noon, 3pm, 6pm, and 9pm will always be orthogonal. Your output for intermediary hours, when arranged by degrees, should be in the same order as the hours of the day. What I mean is at noon the hour hand is 0º and at 3pm the hour hand is 90º so for your output cases of 1pm and 2pm the following must be true: `0pm_deg < 1pm_deg < 2pm_deg < 3pm_deg`. Apart from this rule the actual degree amount can be whatever you decide, obviously it will change depending on font and other native factors.

•The connecting joint between the hour hand and minute hand is a circular/oval unicode character of any kind. `o, O, •, 0, etc.`

---

## Example Input / Output (May vary depending on drawing styles)

```
 N = 3;

 *
 *
 *
 O  *  *

```

---

```
 N = 4;

 *
 *
 *
 O
    *
       *

```

---

```
 N = 5;

 *
 *
 *
 0
  *
   *

```

---

```
 N = 6;

 *
 *
 o
 *

```

---

```
 N = 7;

      *
      *
      *
      •
    *
  *

```

---

```
 N = 0,12,24;

 *
 *
 *
 o

```

---

Example of Differentiating Outputs:

```
 N = 4     VS     N = 5     VS     N = 6

  *                *                *
  *                *                *
  O                O                O
      *              *              *

```

---

This is , so the program with the shortest bytecount wins!

# Answer
> 18 votes
# Javascript (ES6), 105 76 65 bytes

```
F=N=>`  *
ab*12
 9@3
87654`.replace(/\w/g,y=>'0x'+y^N%12?' ':'*')
```

```
<!-- Snippet Demo: -->
N =  <input type="number" min="0" max="24" value="2" id="I" />
<button onclick="console.log(F(I.value))">Run</button>
```
* **-29 bytes:**

+ Reduced size of minute and hour hand to 2 and 1 asterisks respectively. Smaller clock = less bytes :-P
* **-11 bytes:**

+ Changed string comparison to numeric comparison.
    + `y==(N%12).toString(16)?'*':' '` -\> `'0x'+y^N%12?' ':'*'`

## Original with longer hands: (105 94 bytes)

```
F=N=>`    *
a b * 1 2
  ab*12
  99@33
  87654
8 7 6 5 4`.replace(/\w/g,y=>'0x'+y^N%12?' ':'*')
```

```
<!-- Snippet Demo: -->
N =  <input type="number" min="0" max="24" value="2" id="I" />
<button onclick="console.log(F(I.value))">Run</button>
```

# Answer
> 14 votes
## CSS/HTML(JavaScript), 62 + 106 = ~~180~~ 168 bytes

```
pre{position:absolute;left:99px;bottom:99px;transform-origin:50% 80%}
```

```
<input oninput=h.style.transform=`rotate(${this.value*30}deg)`><pre>*
*
o</pre><pre id=h>*

</pre>
```

Edit: Saved 9 bytes thanks to @nderscore.

# Answer
> 9 votes
# Python 2, ~~148~~ ~~140~~ 135 bytes

-8 by deleting some leftover spaces and an unneeded newline.

-5 by changing `(' ','*')` to `' *'`

```
a=input()
b='''    *
a b * 1 2
  ab*12
9 9 o 3 3
  87654
8 7 6 5 4'''
for x in range(1,12):b=b.replace(hex(x)[2],' *'[x==a%12])
print b

```

Try it online!

# Answer
> 5 votes
# C (gcc), 144 bytes

```
#define v ,t
h;t(i){putchar(i>12?i-9:h^i?32:42);}n(i){h=i%12;puts("  *")v(10)v(11)v(h)v(1)v(2)v(19)v(12)v(9)v(57)v(3)v(19)v(8)v(7)v(6)v(5)v(4);}

```

Try it online!

# Answer
> 4 votes
# SmileBASIC, ~~90~~ ~~88~~ 74 bytes

```
INPUT H?("  *"+" "*47)*2;"  o
R=H/1.9LOCATE 2.5+SIN(R)*2,3.5-COS(R)*2?"*

```

Example output:

```
? 5
  *
  *
  o

   *

? 3
  *
  *
  o *

```

# Answer
> 3 votes
# Python 3, ~~86~~ 85 bytes

-1 byte, better clockface (credit DuctrTape, as used in my Jelly answer)

```
def f(h):print(*([c,' *'[h%12+64==ord(c)]][c>'@']for c in'''
K*A
J*B
I0C
HFD
G E'''))

```

**Try it online!**

# Answer
> 3 votes
# Jelly, ~~35 34~~ 33 bytes

```
ị“ tI©’Œ?Ḋ¤µ⁶ẋ13”*⁸¦Ṗ;“**o”ṙ7s5ZY

```

**Try it online!** (`tI©`!) or see all **(0 - 24)**.

### How?

```
ị“ tI©’Œ?Ḋ¤µ⁶ẋ13”*⁸¦Ṗ;“**o”ṙ7s5ZY - Main link: h
          ¤                       - nilad followed by link(s) as a nilad:
 “ tI©’                           -     base 250 number: 522956007
       Œ?                         - shortest permutation of [1,N] that would be at
                                     that index in a lexicographically sorted
                                     list: [2,3,4,5,6,7,1,12,11,10,9,8,13]
         Ḋ                        - dequeue: [3,4,5,6,7,1,12,11,10,9,8,13]
ị                                 - index into (1-based and modular, so h=2 picks 4,
                                     as does h=14 [as do h=26, h=-10, etc.])
           µ                      - monadic chain separation (call the result j)
            ⁶                     - space character
             ẋ13                  - repeat 13 times
                   ¦              - apply to index...
                  ⁸               - ...left argument (j)
                ”*                -     an asterisk character (replacemes the space
                                         at index j with an asterisk)
                    Ṗ             - pop the last character off the list †
                     ;“**o”       - concatenate "**o"
                           ṙ7     - rotate left by 7 ‡
                             s5   - split into chunks of length 5 (columns)
                               Z  - transpose (get the rows of the clock)
                                Y - join with line feeds
                                  - implicit print

```

Note that `“ tI©’Œ?Ḋ` (permutation at index, dequeued) is a byte save over `“9ȧỤ_ÑḶ’b⁴` (base 16 of), which is a byte save over `“¦þxṙ<ȥ’ḃ13` (bijective base 13 of).

Regarding the pop - we have an extra space in the string, which is where the asterisk for 0, 12, 24 will go to to allow mod-12 indexing of the list of indexes, popping the last character off there is byte-cheaper than doing the concatenation of `“**o”` beforehand and overwriting one of those asterisks.

Regarding the rotation - this is a byte save over constructing a string with the \`“\**o” in the middle (either with it before or after the asterisk placement).

# Answer
> 3 votes
## Haskell, 148 bytes

```
c n=mapM_ putStrLn$(t(n-3)!(t n!(\_->'*')))(map(\x->(2!(\_->x))"     ")"**O  ")
n!f=(\(x,a:y)->x++f a:y).splitAt n
t n=2+truncate(2.5*sin(n*pi/6))

```

Function c is the one that solves the given task

# Answer
> 2 votes
# Bash \+ Unix utilities, 57 bytes

```
tr `dc -e12o$1O%p` \*<<<'B*1
A*2
9O3
864
7 5'|tr 1-9AB \

```

(There's a space after the final backslash.)

Try it online!

Not a very pretty clock, but it meets all the requirements.

# Answer
> 2 votes
# PHP, 71 bytes

1 asterisk hours hand, 2 asterisk minutes hand.

```
$s="  *
  *
  O
";$s[ord(BGHNTSRQPJDE[$argv[1]%12])&31]="*";echo$s;

```

takes input from command line argument; run with `-nr`.

1. define template
2. map hour to position (decode from letter) and set character at position to asterisk
3. print

# Answer
> 1 votes
# 05AB1E, 41 bytes

This is too slow for TIO.

```
14Ýœ•2!&ô÷‰•èv… *@y_2L11+¹12%0‚ìyå+èJ}3ô»

```

For similar code working on TIO try this

Pretty sure this can still be both golfed and sped up.
Explanation coming later.

# Answer
> 1 votes
## Logicode 634 bytes

Couldn't figure out how to input so there is a var a=... for the input at the top of tio link

```
circ v(a)->cond((a&1000)+0)&a->0/a
circ n(a)->cond a&10000->((a&100)+0)|!(a&100)&((a&011)|100)/a
circ y(a)->cond((a&100)+0)&a->a&10011/a
var s=@100000
var m=@101010
var x=y(n(v(a)))
var e=x&1000
var f=(x&100)+0
var t=(x&10)+00
var o=(x&1)+000
circ r(a,b)->cond(a)->b/@a
out s+s+s+s+m
out r(e&t&!o,m)+s+r(o&e&t,m)+s+m+s+r(o&!e&!f&!t,m)+s+r(t&!o&!f&!e,m)
out s+s+r(e&t&!o,m)+r(e&t&o,m)+m+r(o&!t&!f&!e,m)+r(t&!o&!f&!e,m)
out r(e&o&!t,m)+s+r(e&o&!t,m)+s+@110000+s+r(t&o&!f&!e,m)+s+r(t&o&!f&!e,m)
out s+s+r(e&!t&!o,m)+r((f&t&o),m)+r(f&t&!o,m)+r(f&!t&o,m)+r(f&!t&!o,m)
out r(e&!t&!o,m)+s+r(f&t&o,m)+s+r(f&t&!o,m)+s+r(f&o&!t,m)+s+r(f&!t&!o,m)

```

Have given up on golfing this. Could make it shorter at the cost of making the clock look horrible though.

Try it Online

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


title: Grow Till It's 2017

text:
# Question
Title: Grow Till It's 2017
In this challenge you'll be building a program that grows as it traverses through the ages… Until it's 2017.

## Challenge

Whenever this challenge description says “program”, you can also read “function”.

Your submission, when executed, will output a program that is `THE LENGTH OF YOUR SUBMISSION` \+ `1` bytes long.

When *that* program is executed, it will output a program that is `THE LENGTH OF YOUR SUBMISSION` \+ `2` bytes long… and so on.

*However*, when your program has reached a length of 2017 bytes, it must instead output `2017` and exit.

## Rules

* The output of the final program has to be `2017` and only `2017`. It can be a string or an integer, but it must read `2017` and not `2017.0` or `0x7E1` or other such nonsense.
* No standard loopholes.
* ***Only*** your initial program is allowed to require input, which will be added to your bytecount.
So if your initial program is 324 characters long and takes an input of 13 bytes, your total score will be *324 + 13 = 337* *and* the program outputted by it must be ***338*** bytes long.
    + Using command line flags (e.g. `perl -X`) is fine, however – as long as your initial program as well as all generated programs use the *same* flags. Also, they too count towards the total bytecount. Dashes, slashes etc. in front of a command line flag don't count towards the total, so e.g. `perl -X` counts as *one* additional byte.
* If you return a function, it should be an actual function and not a string that, when evaluated, produces a function.
* Improper quines (if your program is a quine) are disallowed.

## Example

> ### Pseudocode, 99 bytes
>
> ```
> IF (PROGRAM LENGTH == 2017)
>   PRINT 2017
> ELSE
>   PRINT (THE SOURCE OF THIS PROGRAM + 1 BYTE PADDING)
>
> ```

Your submission may work differently, as long as it complies with the rules above.

# Answer
> 6 votes
## \*\>\<\>, ~~29~~ ~~28~~ 30 bytes

```
" r::2+l'-':*7-(?ul1-n;Ol?!;ou

```

Try it here! (\*try with 2017 bytes)
\*set delay to 0ms or you might have to wait a long time

This adds an additional  each subsquent run. If it has 2017 bytes and is run, it will output 2017 and stop execution with no other output.

Update: Saved 1 byte by checking if the length is less than 2017 instead of equal

Update 2: Fixed output for +2 bytes

### Explanation

```
" r: 2+                         build quine
    :                           copy extra " "
       l                        push length to stack
        '-':*7-                 push "2018" to stack
               (?u     O        if not length < 2018:
                  l1-n;           output length-1 and exit
                       Ol?!;ou  output entire stack and exit

```

# Answer
> 4 votes
# Python 2.7, 90 bytes

Here's a relatively simple one:

```
p='q';s=r"p+='q';print('p=\''+p+'\';s=r\"'+s+'\";exec s')if len(p)<1929 else'2017'";exec s

```

Try the first iteration here! Try the penultimate iteration here! Try the final iteration here!

Ungolfed:

```
p='q'      # The length of string p is the number of iterations so far.

s=r"p+='q';print('p=\''+p+'\';s=r\"'+s+'\";exec s')if len(p)<1928 else'2017'"

exec s     # s contains the source code, but also contains a line saying "p += 'q'",
           # which makes the byte count longer. When the length of p is 1928 (i.e. when the
           # entire program is 2017 bytes long), 2017 is printed instead.

```

# Answer
> 2 votes
# Microscript II, 38 bytes

```
{v{h}sl+s""+vK#s2017=(2017ph)lp"~"ph}~

```

# Answer
> 1 votes
# \>\<\>, 34 bytes

```
":l' '95**)b*f3++0.1-}'#'r>o<:ln;#

```

Try it online! Note that, in order to test this for smaller values, your value (minus 1) must be able to be generated in 7 bytes.

## Explanation

```
":l' '95**)b*f3++0.1-}'#'r>o<:ln;#
".................................   push this string
 :                                   duplicate
  l                                  push length of stack
   ' '95**                           push 2016
          )                          1, if length > 2016, 0 otherwise
           b*                        multiply by 11
             f3++                    add 18
                 0.                  jump to that character on this line
                                     if the length is sufficiently long, this skips the
                                     next 10 characters, to the 11th (`b` from earlier):
                             :ln;    (if length is > 2016)
                             :         duplicate
                              l        push length
                               n       output as number
                                ;      terminate
                   1-}'#'r>o<        (if length <= 2016)
                   1-                  subtract 1 from the last char, `#`, to get `"`,
                     }                 which is then moved to the bottom
                      '#'              pushes `#` (will be appended)
                         r             reverses the stack
                          >o<          output stack, until error (accepted by default)
                                 #   This is never reached, but is used to generate `"`

```

# Answer
> 1 votes
# C, 197 Bytes

```
#define A ""
char*s="#define A %c %s%c%cchar*s=%c%s%c;%cmain(){printf(sizeof A==1820?%c2017%c:s,34,A,34,10,34,s,34,10,34,34);}";
main(){printf(sizeof A==1820?"2017":s,34,A,34,10,34,s,34,10,34,34);}

```

# Answer
> 1 votes
# Java, 251 Bytes (Eclipse IDE)

```
import java.io.*;class G{public static void main(String[]args) throws Exception{File x=new File("./src/G.java");if(x.length()==2017){System.out.print("2017");}else{PrintWriter y=new PrintWriter(new FileOutputStream(x,1>0));y.print("A");y.close();}}}//

```

This is assuming the project was made in Eclipse, using the convention of `.java` files in the SRC of the working dir. There are other ways to detect where the source is, but I don't think this is against the rules either.

Basically opens the .java source-code, and appends As until 2017 (after a comment). When the file-size of the source reaches a total of 2017 bytes, it will instead print 2017.

# Answer
> 1 votes
# CJam, ~~39~~ ~~33~~ 30 bytes

```
33q:X~

```

with the input

```
2017:N=N{33')X+`":X~"+}?

```

Try it online!

This is functionally equivalent to my previous version, except that it avoids the need to write and escape the quotes. The previous version:

```
33"2017:N=N{33')X+`\":X~\"+}?":X~

```

Which outputs

```
33")2017:N=N{33')X+`\":X~\"+}?":X~

```

which outputs

```
33"))2017:N=N{33')X+`\":X~\"+}?":X~

```

and so on. Finally, the program

```
33"))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))2017:N=N{33')X+`\":X~\"+}?":X~

```

Outputs `2017`.

**How it works**

```
33      Push 33
  q     Read the input: 2017:N=N{33')X+`":X~"+}?
   :X   Store it in variable X
     ~  Eval it

```

But what does the code in the input actually do?

```
 2017:N                      Push 2017 and store it in N
       =                     Check if the other number (33 on first run) equals 2017
        N                     If it does, push 2017
         {                    Else, execute this block:
          33                   Push 33
            ')                 Push the ) character
              X                Push X
               +               Concatenate with ')
                `              String representation (wraps it in quotes, escapes quotes inside)
                 ":X~"       Push the string ":X~"
                      +      Concatenate
                       }?    (end of block)

```

If the first number of the program isn't equal to 2017, then it will output a program in which that number is incremented one more time than it was this time. If it does equal 2017 (i.e. it's been incremented 1984 times), then simply push 2017 and terminate. The first number starts out as 33 (the length of the code); every increment increases the code length by 1 AND that number by 1, so when 33 has been incremented enough to become 2017, the code will also be 2017 bytes long.

# Answer
> 1 votes
# Python 2, ~~217~~ ~~167~~ 78 bytes

Note that there should be a trailing newline. I used similar concepts to what Calconym used, so thanks for the inspiration!

```
p='q';s='p+=p[0];print"p=%r;s=%r;exec s"%(p,s)if len(p)<1941else 2017';exec s

```

**Try it online**

Try at 2016; Try at 2017

---

**Previous Version:**

This program uses the `inspect` module to get the current line number. Then, it prints itself but with an extra line after the import, which changes the line number for the next program. There should also be a trailing newline here.

```
from inspect import*
n=stack()[0][2];s='from inspect import*%sn=stack()[0][2];s=%r;print(s%%(chr(10)*n,s))if n<1852else 2017';print(s%(chr(10)*n,s))if n<1852else 2017

```

Try it online

# Answer
> 0 votes
# JavaScript, ~~98~~ 83 bytes

That was quite a challenge… Guess that's what I get for requiring actual functions to be returned and not just the function's source.

## Original function

```
function x(){return "3".length>1933?2017:Function(`return ${x}`.replace(/3/,33))()}

```

I'm using `function` instead of `=>` here because the latter doesn't support named functions, just assigning anonymous functions to a variable.

## First iteration

Running the above in your browser console returns a function that, when cast to a string, looks like:

```
function x(){return "33".length>1933?2017:Function(`return ${x}`.replace(/3/,33))()}

```

## Getting to 2017

Since every function returns a new function, you can call the original function / its result 1934 times to get *2017*.

```
console.log((
function x(){return "3".length>1933?2017:Function(`return ${x}`.replace(/3/,33))()}
)()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()
)
```

Tested with Firefox.

---
Tags: sequence, quine, code-generation, code-golf
---


# Question
Title: Help the grandparents find their password
Here's a scenario: A grandmother and grandfather forget what their GMail password is. They know the word, but can't remember which letters are capitals. The challenge is to take a word given and print(stdout) every combination of capital letters possible, essentially "brute-forcing" but only on a given string.

## Example:

`and` would output

```
and
anD
aNd
aND
And
AnD
ANd
AND

```

## Example:

`ea!` would output

```
ea!
Ea!
EA!
eA!

```

## Rules

* ASCII characters only
* Input doesn't have to be lowercase
* The order is not important
* Non-alphabetic chars are left alone
* Standard Loopholes apply.
* Any form of input is allowed
* Repetition is ***NOT*** allowed

## Leaderboard Snippet:

```
function answersUrl(a){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+a+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(a,b){return"https://api.stackexchange.com/2.2/answers/"+b.join(";")+"/comments?page="+a+"&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(a){answers.push.apply(answers,a.items),answers_hash=[],answer_ids=[],a.items.forEach(function(a){a.comments=[];var b=+a.share_link.match(/\d+/);answer_ids.push(b),answers_hash[b]=a}),a.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(a){a.items.forEach(function(a){a.owner.user_id===OVERRIDE_USER&&answers_hash[a.post_id].comments.push(a)}),a.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(a){return a.owner.display_name}function process(){var a=[];answers.forEach(function(b){var c=b.body;b.comments.forEach(function(a){OVERRIDE_REG.test(a.body)&&(c="<h1>"+a.body.replace(OVERRIDE_REG,"")+"</h1>")});var d=c.match(SCORE_REG);d&&a.push({user:getAuthorName(b),size:+d[2],language:d[1],link:b.share_link})}),a.sort(function(a,b){var c=a.size,d=b.size;return c-d});var b={},c=1,d=null,e=1;a.forEach(function(a){a.size!=d&&(e=c),d=a.size,++c;var f=jQuery("#answer-template").html();f=f.replace("{{PLACE}}",e+".").replace("{{NAME}}",a.user).replace("{{LANGUAGE}}",a.language).replace("{{SIZE}}",a.size).replace("{{LINK}}",a.link),f=jQuery(f),jQuery("#answers").append(f);var g=a.language;/<a/.test(g)&&(g=jQuery(g).text()),b[g]=b[g]||{lang:a.language,user:a.user,size:a.size,link:a.link}});var f=[];for(var g in b)b.hasOwnProperty(g)&&f.push(b[g]);f.sort(function(a,b){return a.lang>b.lang?1:a.lang<b.lang?-1:0});for(var h=0;h<f.length;++h){var i=jQuery("#language-template").html(),g=f[h];i=i.replace("{{LANGUAGE}}",g.lang).replace("{{NAME}}",g.user).replace("{{SIZE}}",g.size).replace("{{LINK}}",g.link),i=jQuery(i),jQuery("#languages").append(i)}}var QUESTION_ID=110455,OVERRIDE_USER=8478,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; font-family: sans-serif}#answer-list,#language-list{padding: 10px; width: 290px; float: left}table thead{font-weight: 700}table td{padding: 5px; margin: 0}table tr:nth-child(even){background: #eee}
```

```
<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
> 8 votes
# Jelly, 7 bytes

```
żŒsŒpQY

```

Try it online!

### How it works

```
żŒsŒpQY Main link. Argument: s (string)

 Œs     Yield s with swapped case.
ż       Zip s with the result, creating an array of character pairs.
   Œp   Take the Cartesian product.
      Y Join, separating by linefeeds.
     Q  Unique; deduplicate the result.

```

# Answer
> 8 votes
# Bash + GNU utils, 38

```
eval echo `sed 's/[a-z]/{\l&,\u&}/gi'`

```

Try it online.

The sed expression replaces every letter with `{<LOWER>,<UPPER>}`, where `<LOWER>` and `<UPPER>` are respectively the lower- and upper- case versions of that letter. These are bash brace expansions which are then expanded - the `eval` ensures this is the last expansion to happen.

# Answer
> 4 votes
# MATL, ~~13~~ 12 bytes

```
!tYohZ}&Z*Xu

```

Try it online!

Same idea as Dennis, only less neat, with Luis Mendo's suggestion.

# Answer
> 2 votes
## JavaScript (ES6), ~~99~~ 97 bytes

Returns a space-separated list of words.

```
f=(s,i)=>--i<1?'':s.replace(/[a-z]/gi,c=>c[`to${i&n?'Upp':'Low'}erCase`](n*=2),n=1)+' '+f(s,i||n)

```

### Test cases

```
f=(s,i)=>--i<1?'':s.replace(/[a-z]/gi,c=>c[`to${i&n?'Upp':'Low'}erCase`](n*=2),n=1)+' '+f(s,i||n)

console.log(f("and"))
console.log(f("ea!"))
```

# Answer
> 2 votes
# PHP, ~~115~~ ~~101~~ ~~99~~ ~~102~~ 101 bytes

saved 14 bytes thanks @user63956.

```
function f($b,$a="
"){$b&a?f($c=substr($b,1),$a.$d=$b[0])|ctype_alpha($d^=" ")&&f($c,$a.$d):print$a;}

```

recursive function, prints the results with a leading newline

**breadown**

```
function f($b,$a="\n")                          // $b=remaining input, $a= prepared output
{
    // while $b is not empty
    $b&a        # this is not a typo!
        // recurse with $d(=first char of $b) appended to $a
        ?f($c=substr($b,1),$a.$d=$b[0])
        // if $d is letter, recurse with $d (case toggled) appended to $a
            |ctype_alpha($d)&&f($c,$a.$d^=" ")
    // if $b is empty, print $a
    :print$a;
}

```

# Answer
> 0 votes
# Bash \+ Unix utilities, 95 bytes (non-recursive)

```
s=${1,,}$'
'
s[1]=${s^^}
for((n=${#s};z<n*2**n;)){ echo -n "${s[z/n>>z%n&1]:z++%n:1}";}|sort -u

```

Try it online!

*Note: This solution and the recursive solution below both require bash 4; the ${x,,} and ${x^^} constructs weren't available in bash 3.*

This is quite a bit longer than @DigitalTrauma's solution, but I think it works on all strings, even if they have special characters in them. For example, with input

```
{a,b}

```

this program outputs

```
{A,B}
{A,b}
{a,B}
{a,b}

```

as it should. (@DigitalTrauma's solution, although very ingenious, doesn't work for this input and other similar inputs.)

---

---

# Bash \+ Unix utilities, 88 bytes (recursive)

```
[ "$1" ]&&(c=${1:0:1};sed "h;s/^/${c,,}/;p;g;s/^/${c^^}/"<<<`$0 "${1:1}"`|sort -u)||echo

```

This recursive solution works on input `{a,b}` but it has problems with other special characters, for example, input `a/b`.

# Answer
> 0 votes
## JavaScript (Firefox 30-57), 92 bytes

```
f=([c,...a])=>c?[for(l of new Set([c.toLowerCase(),c.toUpperCase()]))for(r of f(a))l+r]:['']

```

Accepts a string or array of characters and returns an array of strings.

# Answer
> 0 votes
## C ~~247~~ 229 bytes

```
i,n,j,k,l;f(char *s){l=strlen(s);for(i=0;i<l;i++)s[i]=tolower(s[i]);int v[l];for(i=0;i<pow(2,l);i++){n=i,k=0;for(;n;k++){v[k]=n;n/=2;}for(j=0;j<l;j++){v[j]%=2;if(v[j])s[j]=toupper(s[j]);else s[j]=tolower(s[j]);}printf("%s ",s);}}

```

Ungolfed version:

```
void f(char *s)
{
  int i,num,k,l=strlen(s);
  for(int i=0;i<l;i++)
     s[i]=tolower(s[i]);

   int v[l];

   for(i=0;i<pow(2,l);i++)
   {
      num=i,k=0;
      for(;num;k++)
      {
         v[k]=num;
         num/=2;
      }

      for(int j=0;j<l;j++)
      {
        v[j]%=2;
        if(v[j])
         s[j]=toupper(s[j]);
        else
         s[j]=tolower(s[j]);

      }
      printf("%s \n",s);

   }
}

```

Explanation:

* Accept the character string, convert the string to lowercase.
* Declare integer array of length equal to that of the string.
* Store the numbers from 0 to `2^strlen(s)`in binary form in an `int` array.( For a 3 byte string: 000,001,010...111)
* Depending on if a bit at a position is set or, toggle the case.
* Output the string for every possible combination.

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


# Question
Title: Create a "hacker typer" program that renders its own source code
If you are unfamiliar with hacker typer, see hackertyper.net. In short, it is a program that outputs one chunk of a code base per keystroke for comedic effect. BUT, the hackertyper.net version is far too easy to implement. It simply outputs three characters at a time from an *arbitrary* piece of code. For this challenge, a program must output its own source code, and print one *space delimited* chunk of code per keystroke.

## Details

* One cannot hard code a file name for the program; it must determine its name dynamically. If the program compiles to an executable, it may append the standard file extension to the name of the executable (excluding the .exe if using Windows) and assume that the source file is within the executable's directory. For example, if a C executable is named "hacker", it should pull its source code from a file named "hacker.c" in its same directory. If a compiled program has an extension, it should be dropped before determining the name of its source code ("typer.exe" -\> "typer.cs").
* Programs must contain at least 5 spaces, with at least one character between each space. This means that the smallest possible size for this challenge is 9 bytes. The spaces do not have to be crucial to the functioning of the program.
* Any formatting (indentation, new lines, etc.) must be maintained in the output. This formatting may either be printed with the code that proceeds it or follows it, what matters is that the formatting be maintained.
* Avoid using comments to satisfy the 5 space requirement unless there is no other way to implement the spaces in your language of choice.

**EDIT**: New lines can be used in place of, or in addition to, spaces as chunk separators.

# Answer
> 13 votes
### bash, 51 58

```
for w in $(<$0);do read -sn 1;printf -- "$w ";done

```

# Answer
> 22 votes
### HTML & JavaScript, 123

```
<head></head><body onload="s=(a=document.all)[i=0].innerHTML" onkeyup="a[2].textContent += s.split(/(?= )/)[i++%6]"></body>

```

This works similarly to hacker typer, but with its own source code. Let me know if I've misunderstood the rules.

And here's a styled version (170 characters):

```
<head></head>
<body style="background:#000;color:lime" onload="s=(a=document.all)[i=0].innerHTML" onkeyup="a[3].textContent+=s.split(/(?=\s)/)[i++%6]">
<pre></pre></body>

```

I've made a **demo**. It's modified because JS Bin adds a lot of extra code, but the general idea is the same.

# Answer
> 12 votes
# Perl + Term::ReadKey, 56 bytes

```
use
Term'ReadKey;ReadMode
4;open
0;ReadKey,print
for
<0>

```

Thanks to ThisSuitIsBlackNot for the original inspiration, and to primo for suggesting `open 0` and `<0>`.

Note that the newline after `for` is actually unnecessary, except that I need to include one extra newline *somewhere* to bring the whitespace count up to the specified minimum of five.

Also note that, like ThisSuitIsBlackNot's submission, this program requires the Term::ReadKey module from CPAN. On Debian / Ubuntu Linux, this module, if not already present, can be easily installed with the command `sudo apt-get install libterm-readkey-perl`.

Also, to save a few characters, this program does not restore the input mode to normal on exit, so you may find yourself unable to see what you're typing afterwards. Executing the shell command `stty sane` or `reset` should fix that. This issue could be fixed, at the cost of 10 extra bytes, with:

```
use
Term'ReadKey;ReadMode
4;open
0;ReadKey,print
for<0>;ReadMode
0

```

---

## Bonus: Pure quine, 81 bytes

```
$_=q{use
Term'ReadKey;ReadMode
4;ReadKey,say
for
split$/,
"\$_=q{$_};eval"};eval

```

Again, the newline after the comma is only needed to meet the five whitespace minimum.

Unlike the 56-byte program above, this version doesn't actually need to read its own source code, since it's based on a quine — specifically, on this quine:

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

```

The nice thing about this quine is that it can easily carry an arbitrary "payload" within the `q{ }` block, without having to repeat it. While it can't quite beat `<0>` in shortness, it does get pretty close.

Note: This program uses the Perl 5.10+ `say` feature, and thus needs to be invoked with the `-M5.010` (or `-E`) command line switch. Per established consensus on meta, such switches used to enable modern language features do not count as extra characters. The shortest solution I can find without `say` is 83 bytes:

```
$_=q{use
Term'ReadKey;ReadMode
4;ReadKey,print
for
split/^/,
"\$_=q{$_};eval"};eval

```

Both of these can also be made more terminal-friendly by (joining the last two lines and) inserting:

```
;ReadMode
0

```

before the last `}`.

# Answer
> 5 votes
# Python 3 - 124 bytes - 7 spaces

---

Code:

```
from curses import*
s=initscr();noecho()
for x in open(__file__).read().split(" "):s.getch();s.addstr(x+" ")
echo();endwin()

```

Ungolfed:

```
from curses import*
# init curses
screen=initscr()
noecho()
# split code into spaces
code = open(__file__).read().split(" ")
for x in code:
    # wait for keypress
    screen.getch()
    # print a bit
    screen.addstr(x+" ")
# deactivate curses
echo()
endwin()

```

Styled version:

```
from curses import*
s=initscr();noecho();start_color();init_pair(2,COLOR_GREEN,COLOR_BLACK)
for x in open(__file__).read().split(" "):s.getch();s.addstr(x+" ",color_pair(2))
echo();endwin()

```

# Answer
> 4 votes
# Ruby, 85, 71

```
require"io/console";f=File.open __FILE__;loop{STDIN.raw &:getc;print f.read(3)||exit}

```

Too bad that `IO#raw` is not part of the standard library.

### Improvement

```
require"io/console";24.times{|q|STDIN.raw &:getc;$><<IO.read($0,3,q*3)}

```

This one eliminates the call to Kernel#exit and uses global variables to shorten the code.

# Answer
> 4 votes
# Befunge - 21

```
~ $ g , 1 +:54*`#@_:0

```

I'm fairly pleased with this, as I just found out about Befunge. If you don't mind "typing" into a popup window, you can run it here or here until I find a better online interpreter.

# Answer
> 2 votes
## Python 3 - 299

```
a="""from curses import*
s=initscr()
raw()
noecho()
for x in e:
 s.getch()
 s.addstr(x+' ')
nocbreak()
echo()
endwin()
""";b="""e=(a+'a=#%s#;b=#%s#;%s'%(a,b,b.replace('#','""''"',4))+'exec(a)').split(' ')
""";e=('a="""%s""";b="""%s""";%s'%(a,b,b.replace('#','""''"',4))+'exec(a)').split(' ')
exec(a)

```

Its a quine. Shortened from 507 by using `exec` and moving some statements around.

# Answer
> 2 votes
## Powershell, 89

```
(gc $MyInvocation.MyCommand.Path).split(" ")|%{$l+="$_ ";write-host "$l";read-host ;cls}

```

# Answer
> 2 votes
# C - 136 135 132 bytes (Windows only)

```
*fopen();**v;b[ 1<<20];main(p,q){v=q; strcpy(b,*v);strcat(b,".c") ;for(*v=fopen(b,"r");~fscanf(*v,"%s",b);printf("%s ",b))getch();}

```

Note: there is a space at the end of the program, which probably won't show up.

I can't guarantee this program will work on a single computer other than my own as it is awesomely hacky. Things would have been a lot simpler back when everyone only had 32-bit machines. Then I would not need to worry about `sizeof(int*)` being 8 (which it definitely is; I printed it out to make sure) while `sizeof(int)` is 4.

Happily, the name of the executable is stored in the first string in argv.  ~~However, putting a pointer as an argument to a function means that I have to explicitly specify the type of ALL the arguments to the function--meaning I would have to type `int` twice--a huge waste of characters.~~  Fortunately I found a workaround. I had the second argument to main, `q`, be just another int. Then assigning `q` to a variable of type `int**` somehow managed to grab all the necessary bytes from the stack.

I was unsuccessful in finding any such tricks to interpret the return type of `fopen` as a pointer without declaring the function.

Edit: Noticed I should use `~fscanf(*v,"%s",b)` instead of `fscanf(*v,"%s",b)>0` since the return is -1 when EOF is reached.

# Answer
> 2 votes
# C, 211 186 bytes

My solution in C using the curses library. It may be longer than the other C solution, but it is a quine. Although not required by the question, it's still pretty nice. It also works quite nicely:

```
#define R(x)#x
#define T(x)R(x)
#define S(p)char*s="#define R(x)#x\n#define T(x)R(x)\n#define S(p)"p"\nS(T(S(p)))";main(){initscr();noecho();while(*s)if(~getch())addch(*s++);}
S(T(S(p)))

```

A more readable version with some comments and stuff:

```
#define R(x)#x /* macros to convert the source code in S into a C-string */
#define T(x)R(x)
#define S(p) char*s="#define R(x)#x\n" \
                    "#define T(x)R(x)\n" \
                    "#define S(p) " p "\n" \
                    "S(T(S(p)))";\
    main(){\
        initscr();\
        noecho(); /* don't echo input */ \
        while(*s)\
            if(~getch()) /*true if character has been typed */ \
                addch(*s++);\
}
S(T(S(p)))

```

compile with:

```
gcc -o h h.c -lncurses

```

# Answer
> 1 votes
# Perl - 87 bytes

```
#!/usr/bin/perl -040
use Term::ReadKey;open F,$0;ReadMode 3;print''.<F>while ReadKey 0

```

I didn't see anything in the rules about what to do once the file has been read to the end, so it simply sits waiting for input after printing the last chunk.

# Answer
> 1 votes
node.js with LiveScript:

```
#!/usr/local/bin/lsc
console.log <| require \fs .readFileSync __filename, encoding: \utf8

```

asynchronous version:

```
#!/usr/local/bin/lsc
require \fs .readFile __filename, encoding: \utf8, -> console.log &1

```

# Answer
> 1 votes
# Cobra - 147

```
class P
    def main
        while 1,for a in File.readLines(CobraCore.exePath[:-4]+'.cobra'),print if('[Console.readKey]'and (Console.cursorLeft=0)<1,a,'')*

```

`CobraCore.exePath` is so useful!

# Answer
> 1 votes
# Javascript ES6, 154

**Firefox 154**:

```
(a= (i=1,b="(a= "+a+")()",s="") => {window.onkeydown=()=>{clear();i=b.indexOf(" ",i+1),d=b.slice(0,i<0?b.length:i);console.log(s+d);if(i<0){i=0,s+=d}}})()

```

**Chrome 175**:

```
( a= function (i,s){b="( a= "+a+")()";c=console,window.onkeydown=function(){c.clear();s=s||"",i=b.indexOf(" ",i+1),d=b.slice(0,i<0?b.length:i);c.log(s+d);if(i<0){i=0,s+=d}}})()

```

**Both 274**:

```
( a= function (i,s){b="( a= "+a+")()";c=console,window.onkeydown=function(){(clear)?clear():c.clear?c.clear():0;s=s||"",i=b.indexOf(" ",i+1),d=b.slice(0,i<0?b.length:i);c.log(s+d);if(i<0){i=0,s+=d}}})()

```

**Ungolfed** (chrome):

```
( a= function (i,s){        // starting index | undefined, output string
    b="( a= "+a+")()";      // get a string representation of the function
    c=console,
    window.onkeydown=function(){    // on each key down event
        c.clear();                  // clear the output
        s=s||"";
        i=b.indexOf(" ",i+1);       // get the index of next space
        d=b.slice(0,i<0?b.length:i);// get the string part wanted
        c.log(s+d);                 // print the string
        if(i<0){
            i=0,                    // reset counters
            s+=d                    // adding the string to the main output
        }
    }
})()

```

Has two versions, because Chrome does not handle arrow function and the console is not cleared with the same method

The Firefox one work with firebug, it seem that the default developer console can't be cleared from a script.

# Answer
> 1 votes
## C, 248 characters

**True quine**

Only works in unix, in windows it would be implemented using \_getch.

```
main(){char *p="main(){char *p=\"%s\",s[400];sprintf(s,p,p);system(\"stty raw\");for(p=s;*p!=0;putchar(*p++))getchar();system(\"stty cooked\");}",s[400];sprintf(s,p,p);system("stty raw");for(p=s;*p!=0;putchar(*p++))getchar();system("stty cooked");}

```

# Answer
> 0 votes
# Groovy - 379

```
import java.nio.file.*
Path p = Paths.get(System.getProperty("user.dir"))
DirectoryStream<Path> f = Files.newDirectoryStream(p,"*.groovy")
try{for(e in f){read(e.toAbsolutePath().toString())}}
catch(Exception e){ }
finally{f.close()}

void read(String x){
    def s = new File(x).text
    for(e in s.replace("%n"," %n").split(" "))
        print e + " "
    Thread.sleep(200)
}

```

Since there is no `getch()` or equivalent in Java and Java-esque languages like Groovy... basically my code doesn't handle keypresses. That's all :D

# Answer
> 0 votes
# HTML and Javascript, 232 bytes

```
<body><script>var n=0;var f=function (){document.onkeypress=function(){document.body.innerHTML+=("<body><script>var n=0;var f="+f.toString()+"f()</script></body>").split(" ")[n]+" ";n++;}};f()</script></body>

```

The traditional Javascript quine, but modified.

JSFiddle here.

# Answer
> 0 votes
# SmileBASIC, ~~79~~ 75 bytes

```
LOAD"PRG1:"+PRGNAME$()
PRGEDIT 1
@L
IF BUTTON(2)THEN?PRGGET$();
WAIT
GOTO@L

```

~~It's very easy to get a specific LINE of a program in SmileBASIC, so I just put the spaces before each line break.~~ I thought I was so clever, putting the spaces before each line break, but apparently we're allowed to use line breaks instead of spaces...

Explanation:

```
LOAD "PRG1:"+PRGNAME$() 'load the code into slot 1 so we can easily read 1 line at a time
PRGEDIT 1 'Edit slot 1
@LOOP
IF BUTTON(2) THEN 'When a button is pressed...
                   PRINT PRGGET$(); 'get a line of code and print it
WAIT 'delay so we don't detect the same press multiple times in a single frame.
GOTO @LOOP

```

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


title: Find the numbers and calculate output

text:
# Question
Title: Find the numbers and calculate output
# Objective

Given an input list of `6` distinct digits, find 3 numbers `a`, `b` and `c` such that `a × b = c`, with `a` having 2 digits, `b` having 1 digit and `c` having 3 digits. In a more visual way, your program must arrange those 6 digits in the boxes of this image:

If more than one solution exists, you may output any of them.

# Input

6 distinct digits. You may take them in any reasonable way for your language.

# Output

The 3 numbers `a`, `b` and `c`. The output format is relatively free, as long as the 3 numbers are separated and are always printed in the same order (but not necessarily in the order `a, b, c`).

# Test Cases

```
1, 2, 3, 4, 5, 6 -> 54,3,162
2, 3, 4, 5, 6, 7 -> 57,6,342 or 52,7,364

```

# Scoring

The shortest code in bytes wins.

# Answer
> 8 votes
## JavaScript (ES6), ~~90~~ 88 bytes

Takes input as an array of 6 digits. Returns a string describing a possible solution (such as `'54*3==162'`) or exits with a 'too much recursion' error if (and only if) there's no solution.

```
f=(a,k=1)=>eval(s='01*2==345'.replace(/\d/g,n=>a[n],a.sort(_=>(k=k*2%3779)&2)))?s:f(a,k)

```

### How it works

This is a deterministic algorithm.

The primes `P=2` and `Q=3779` were chosen in such a way that the sort callback `(k = k * P % Q) & 2` is guaranteed to generate all 720 possible permutations of the input array over time. More precisely, all permutations are covered after 2798 sorts -- which should be within the recursion limit of all browsers.

We inject each permutation in the expression `01*2==345` by mapping the digits to the corresponding entries in the array.

We evaluate this expression and do recursive calls until it's true.

### Test

```
f=(a,k=1)=>eval(s='01*2==345'.replace(/\d/g,n=>a[n],a.sort(_=>(k=k*2%3779)&2)))?s:f(a,k)

console.log(f([1,2,3,4,5,6])); // 54*3==162
console.log(f([2,3,4,5,6,7])); // 52*7==364
console.log(f([1,2,3,4,6,7])); // 73*2==146
```

# Answer
> 8 votes
# Brachylog (2), 10 bytes

```
p~c₃o.k×~t

```

Try it online!

Far too slow to run in a reasonable length of time (the Brachylog interpreter spends a long time doing multiplications on empty strings, 4-digit numbers, negative numbers etc. using a very slow constraint solver). The TIO link uses an input with only 3 digits (this program can handle input with any number of digits). This is a function whose input is a number containing all the digits required (e.g. `234567`) – the lack of duplicates in the input means that you can always just put any `0` at the end to avoid a leading zero – and whose output is a list in the order `[b, a, c]` (e.g. `[6, 57, 342]`).

## Explanation

```
p~c₃o.k×~t
p           Permute the digits of the input
 ~c₃        Split them into three groups
    o       Sort the three groups
     .      to produce the output, which must have the following property:
      k     all but the last group
       ×    when multiplied together
        ~t  produces the last group

```

So where did the requirement on the groups to be 2, 1, and 3 digits go? Well, we know there are 6 digits in the input, and the groups are in sorted orders. The only possible sizes they can have, therefore, are \[1, 1, 4\], \[1, 2, 3\], or \[2, 2, 2\]. The first case is impossible (you can't multiply two 1-digit numbers to produce a 4-digit number, as 9×9 is only 81), as is the last case (you can't multiply two 2-digit numbers to produce a 2-digit number, as even 10×10 produces 100). Thus, the return values `[b, a, c]` must be 1, 2, and 3 digits long in that order, so `a` is 2 digits, `b` is 1 digit, and `c` is 3 digits, as requested.

# Answer
> 6 votes
# Brachylog, 17 bytes

```
p~c[Ċ,I,Ṫ]cᵐ.k×~t

```

Try it online!

### Explanation

```
p                   Try a permutation of the Input
 ~c[Ċ,I,Ṫ]          Deconcatenate it; the result must be a list of the form [[_,_],_,[_,_,_]]
          cᵐ.       Output is the list of integers you get when mapping concatenate on the
                      previous list
             k×~t   The first two ints of the Output, when multiplied, result in the third
                      int of the Output

```

# Answer
> 3 votes
# 05AB1E, ~~15~~ 13 bytes

Saved two bytes thanks to *Emigna*!

```
œJvy3L£Â`*Qi,

```

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

Explanation:

```
œ                 # Get all permutations of the input
 J                # Join them to get the numbers
  vy              # For each element in the list..
    3L            #   Push the list [1, 2, 3]
      £           #   Pops a and pushes [a[0:1], a[1:3], a[3:6]]
       Â`         #   Bifurcate and flatten
         *        #   Multiply the top two elements in the stack
          Qi      #   If equal to the third element..
            ,     #     Print the array

```

# Answer
> 3 votes
# Bash + coreutils, 70

```
for((b=1;b;));{
a=`shuf -ze $@`
b=${a:0:2}*${a:2:1}-${a:3:3}
}
echo $b

```

No particularly easy way to generate all the permutations. Instead randomly generate permutations and calculate until we find a good one.

Output is in the form `A*B-C` \- i.e. the expression that will evaluate to zero when we have the correct permutation.

Try it online.

# Answer
> 2 votes
# CJam, 23 bytes

```
qm!{3/)2/+:i}%{(\:*=}=p

```

Try it online!

# Answer
> 2 votes
# Python 2, 105 bytes

```
lambda s:[(x[0],x[1:3],x[3:])for x in permutations(s)if eval('%s*%s%s==%s%s%s'%x)]
from itertools import*

```

Try it online!

# 88 bytes solution with a more *flexible* output

```
lambda s:[x for x in permutations(s)if eval('%s*%s%s==%s%s%s'%x)]
from itertools import*

```

Try it online!
where the output would be \['6', '5', '7', '3', '4', '2'\] instead '6', '57', '342'

# Answer
> 2 votes
# PHP, 110 bytes

It'll get there... eventually...

```
<?$v=$argv;unset($v[0]);do shuffle($v)&[$a,$b,$c,$d,$e,$f]=$v;while("$a$b"*$c!="$d$e$f");echo"$a$b $c $d$e$f";

```

Ungolfed:

```
<?
$v=$argv;
unset($v[0]);
do
  shuffle($v);
  [$a,$b,$c,$d,$e,$f]=$v;
while("$a$b"*$c!="$d$e$f");
echo"$a$b $c $d$e$f";

```

# Answer
> 2 votes
# PHP, 77 bytes

```
for(;;)eval(strtr('0.*1-"428"||die("0.,1,428");',1/7,str_shuffle($argv[1])));

```

Takes input as a string.

# Answer
> 2 votes
# Pip, 18 bytes

17 bytes of code, +1 for `-S` flag.

```
$/_=1FI_^@3,5MPMa

```

Takes input as a string of digits via command-line argument. Output is in the order c, b, a. Try it online!

This code outputs *all* solutions if multiple exist. If it is required to output only *one* solution, then add three bytes and wrap the program in `(...0)`.

### Explanation

```
                   a is 1st cmdline arg (implicit)
              PMa  Compute all permutations of a
             M     To each, map this function:
          3,5       Range(3,5)--contains values 3 and 4
       _^@          Split the function argument at those indices
                    This transforms a string like 342657 into a list [342; 6; 57]
     FI            Now filter the list of split permutations on this function:
$/_                 Fold on division: takes 1st element and divides it by the rest
   =1               Compare the quotient with 1
                    This keeps only the permutations where the first number is the product
                    of the other two
                   Autoprint the list (implicit), with each sublist on a separate line
                   and space-separated (-S flag)

```

# Answer
> 2 votes
## Ruby, 60 bytes

```
->x{x.permutation{|a|(eval a="%d%d*%d==%d%d%d"%a)&&puts(a)}}

```

Prints all solutions as "a\*b==c"

### Example:

```
->x{x.permutation{|a|(eval a="%d%d*%d==%d%d%d"%a)&&puts(a)}}[[1,2,3,4,5,6]]
54*3==162

->x{x.permutation{|a|(eval a="%d%d*%d==%d%d%d"%a)&&puts(a)}}[[2,3,4,5,6,7]]
52*7==364
57*6==342

```

# Answer
> 1 votes
# ES6 (Javascript), ~~85~~, ~~82~~, 79 bytes

Accepts an array of digits (strings), returns a 3-element array `[A,B,C]` =\> `C=A*B`

**Golfed**

```
R=(w,[a,b,c,d,e,f]=w)=>f*(d+=e)^(a+=b+c)?R(w.sort(_=>Math.random()-.5)):[a,d,f]

```

EDITS:

* Saved 3 more bytes by reusing `d` and `a`, and getting rid of `==` (Thanks @Arnauld !)
* Saved 3 bytes using destructuring assignment

**Try It !**

```
R=(w,[a,b,c,d,e,f]=w)=>f*(d+=e)^(a+=b+c)?R(w.sort(_=>Math.random()-.5)):[a,d,f];

function generate(A) {
   console.log(R([...A]));
}
```

```
<input type="text" id="A" value="123456"/><button onclick="generate(A.value)">GENERATE</button>
```

# Answer
> 1 votes
## Batch, 305 bytes

```
@echo off
set/pd=
for /l %%i in (0,1,719)do set n=%%i&call:c
exit/b
:c
set t=%d%
set s=
for /l %%j in (6,-1,1)do set/ap=n%%%%j,n/=%%j&call:l
set s=%s:~0,2%*%s:~2,1%-%s:~3%
set/an=%s%
if %n%==0 echo %s%
exit/b
:l
call set u=%%t:~%p%%%
call set s=%%s%%%%u:~,1%%
call set t=%%t:~,%p%%%%%u:~1%%

```

Takes input on STDIN as a string `[1-9]{6}` and outputs all solutions in `dd*d-ddd` format. Batch isn't very good at string manipulation so generating the 720 permutations is a little awkward.

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


title: Imitate an ordering

text:
# Question
Title: Imitate an ordering
Given two lists of numbers, a *source* and a *pattern*, reorder the source to match the relative ordering of the pattern. Any two entries of the reordered source should compare the same way as the entries at those same positions of the pattern.

For example, the input

```
s = [-5, 9, 4, 13, 11, -6, 0]
p = [7, -4, 1, -8, 4, -3, 12]

```

should produce the result

```
    [11, -5, 4, -6, 9, 0, 13]

```

Comparing the first and last positions, the result has `11<13`, which matches `7<12` in the pattern.

**Input:** Two equal-length non-empty lists of integers. Each list will have no repeats. It's up to you whether the source or pattern is given first.

**Output:** A list that rearranges the source numbers to have the same relative ordering as the pattern numbers.

**Leaderboard:**

```
var QUESTION_ID=62587,OVERRIDE_USER=20260;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/62587/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://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
## CJam, 12 10 bytes

```
{_$f#\$f=}

```

This is an anonymous function, which takes `s p` on the stack and leaves the result on the stack. Online demo

With thanks to Martin Büttner for 2 bytes.

### Dissection

```
{         e# Define an anonymous function
  _$f#    e# Use a copy of the pattern to map each element to its sort index
  \$      e# Sort the source
  f=      e# Map each sort index to the corresponding source element
}

```
> 10 votes

# Answer
# J, 9 bytes

```
/:^:2~/:~

```

This is a dyadic verb that takes **p** and **s** as left and right arguments. Try it online with J.js.

### Test run

```
   7 _4 1 _8 4 _3 12 (/:^:2~/:~) _5 9 4 13 11 _6 0
11 _5 4 _6 9 0 13

```

### How this works

Say we defined assigned the left and right input from the example via

```
p =: 7 _4 1 _8 4 _3 12
s =: _5 9 4 13 11 _6 0

```

Then:

* The train `/:^:2~/:~` is a hook of the verbs `/:^:2~` and `/:~`, so calling

```
p (/:^:2~/:~) s

```

executes

```
p /:^:2~ /:~ s

```
* The adverb `~` in `/:~` is *reflexive*, since `/:` is used monadically. Thus, calling

```
/:~ s

```

executes

```
s /: s

```
* The adverb `~` in `/:^:2~` is *passive*, since the verb `/:^:2` is used dyadically. Thus, calling

```
p /:^:2~ y

```

executes

```
y /:^:2 p

```
* The adverb `^:` is *power*. Thus, calling

```
y /:^:2 p

```

executes

```
y /: y /: p

```

Putting it all together, calling

```
p (/:^:2~/:~) s

```

executes

```
(s /: s) /: (s /: s) /: p

```

### How *that* works

Dyadic `/:` is *grade up using*, i.e., `x /:y` returns the elements of **x**, sorted according to the corresponding values of `y`.

* `s /: s` simply sorts the elements of **s**.
* `(s /: s) /: p` sorts the (sorted) elements of **s** according to the corresponding values of **p**.
* Grading up twice essentially computes the ordinals of its right argument.

Thus, `(s /: s) /: (s /: s) /: p` sorts the (sorted) elements of **s**, imitating the order of the elements of **p**.
> 10 votes

# Answer
# Mathematica, ~~32~~ 27 bytes

```
Sort@#~Permute~Ordering@#2&

```

Example usage:

```
Sort@#~Permute~Ordering@#2 &[{-5, 9, 4, 13, 11, -6, 0}, {7, -4, 1, -8, 4, -3, 12}]
(* {11, -5, 4, -6, 9, 0, 13} *)

```

Previous attempt:

```
Sort[#][[Ordering@Ordering@#2]]&

```
> 9 votes

# Answer
## J, 17 bytes

```
(A.^:_1/:~)~A.@/:

```

This evaluates to a dyadic (meaning binary) verb. It can be evoked as follows:

```
  _5 9 4 13 11 _6 0 ((A.^:_1/:~)~A.@/:) 7 _4 1 _8 4 _3 12
11 _5 4 _6 9 0 13

```

## Explanation

This may not be the shortest possible J solution, but it's a novel approach.

```
                   Left input is x, right input is y.
            A.@/:  The index of the permutation P that sorts y. /: gives the
                   permutation itself, and A. gives its index in the sorted
                   list of all its permutations.
       /:~         x sorted in ascending order. We are applying the x-sorting
                   permutation to x itself.
(A.^:_1   )~       The inverse of the permutation P applied to the sorted
                   version of x. Since P maps y to its sorted version, its
                   inverse maps the sorted version to y, and thus sorted x to
                   the correct output.

```
> 7 votes

# Answer
# Pyth, 10 bytes

```
@LSvzxLSQQ

```

Try it online: Demonstration

### Explanation

```
@LSvzxLSQQ implicit: z = first input line as string
                     Q = second input line evaluated
       SQ  sorted(Q)
     xLSQQ find the index for each element of Q in sorted(Q)
  Svz      sorted(evaluated z)
@LSvz      take the element in ^ for each index

```
> 6 votes

# Answer
# Pyth, 7 bytes

```
XQSQSvz

```

This is a full program that expects string representations of **s** and **p** on two lines. Try it online.

### How it works

```
           Store the first line of input (rep. of s) in z.
           Evaluate the second line of input and store the result (p) in Q.
  SQ       Sort the elements of p.
    Svz    Evaluate the repr. of s and sort its elements.
XQ         Perform transliteration on p.
           This replaces the lowest element of p with the lowest element of s, etc.

```
> 6 votes

# Answer
# Mathematica ~~56 43 30~~ 29 bytes

```
o=Ordering;Sort[#][[o@o@#2]]&

```

`Ordering@#2` returns the order of numbers in the pattern. `Ordering@Ordering@#2` gives the positions that the sorted elements in the source should occupy.

`Sort[#][[o@o@#2]]&` returns the source in the required positions, namely, those that have the same relative ordering as the pattern list.

**Testing**

```
o=Ordering;Sort[#][[o@o@#2]]&[{-5, 9, 4, 13, 11, -6, 0}, {7, -4, 1, -8, 4, -3, 12}]

```

> {11, -5, 4, -6, 9, 0, 13}
> 5 votes

# Answer
# Python 2, 51

```
lambda s,p,a=sorted:[a(s)[a(p).index(x)]for x in p]

```
> 5 votes

# Answer
# CJam, 8 bytes

```
{_$@$er}

```

This is an anonymous functions that expects **s** and **p** (topmost) on the stack and pushes the reordered **s** in return. Try it online in the CJam interpreter.

### How it works

```
_      e# Push a copy of p.
 $     e# Sort it.
  @    e# Rotate s on top of p and the sorted p.
   $   e# Sort s.
    er e# Perform transliteration.
       e# This replaces the lowest element of p with the lowest element of s, etc.

```
> 5 votes

# Answer
## J, 13 bytes

```
/:@/:@[{/:~@]

```

I'm still having trouble wrapping my head around J's verb composition, so I feel like some of those `@` and `[]` might be unnecessary. If some more experienced J user could let me know if this can be compressed, that would be great. :)

The verb can be used as follows:

```
   7 _4 1 _8 4 _3 12 (/:@/:@[{/:~@]) _5 9 4 13 11 _6 0
11 _5 4 _6 9 0 13

```

### Explanation

```
/:@/:@[{/:~@] NB. Left input is the pattern, right input is the source.
        /:~@] NB. Sort the source.
/:@/:@[       NB. Compute the ordering of the ordering of the pattern.
       {      NB. Use those as indices into the sorted source.

```
> 4 votes

# Answer
## Python 2, 48

```
lambda*l:map(dict(zip(*map(sorted,l))).get,l[0])

```

A big glob of functions. This uses the element translation approach of many other answers using a dictionary.

The starred input `*l` expects the patterns and source in that order, and turns them into a list `l`.

Mapping `sorted` sorts both lists, and `dict(zip(_))` turns a pair of lists into a dictionary with keys from the first list matched with values in the second, in ascending order. So, the result is that that `i`-th largest element of the pattern is matched with the `i`-th largest element of the source.

Finally, we transform the pattern (`l[0]`) via this dictionary by mapping its `.get` method.
> 4 votes

# Answer
# Bash + coreutils, 55

```
nl $2|sort -nk2|paste <(sort -n $1) -|sort -nk2|cut -f1

```

Input is taken as two filenames, for the source and pattern respectively:

```
$ ./imitord.sh source.txt pattern.txt
11
-5
4
-6
9
0
13
$

```
> 3 votes

# Answer
## R, 38 bytes

```
function(s,p)sort(s)[match(p,sort(p))]

```
> 3 votes

# Answer
# Ruby, 51 bytes

```
->s,p{s.map{|x|s.sort[p.sort.index(p[s.index x])]}}

```
> 3 votes

# Answer
## APL, ~~17~~ 12 bytes

```
{⍺[⍋⍺][⍋⍋⍵]}

```

Thanks to @Dennis, this is now very elegant.

Here's a nice 14-byte solution that doesn't use double indexing:

```
{⍺[(⍋⍋⍺)⍳⍋⍋⍵]}

```

Unfortunately, we can't index arrays from within trains in APL.
> 3 votes

# Answer
# TeaScript, 15 bytes

```
ys¡m™x[yi(l)])

```

This takes input as an array. The interpreter is currently down because I'm putting up the fancy new interpreter

### Explanation

```
y      // Second input
 s¡    // Sort it = s()
m™     // Map over it = m(#
  x[      // Num in first input at index...
    yi(l) // Current char's index in y
  ]
)

```
> 2 votes

# Answer
## Haskell, 65 bytes

```
import Data.List
s#p=[sort s!!i|b<-p,(i,e)<-zip[0..]$sort p,b==e]

```

Usage example: `[-5,9,4,13,11,-6,0] # [7,-4,1,-8,4,-3,12]` -\> `[11,-5,4,-6,9,0,13]`.

How it works:

```
           b<-p                              -- for every b in p
               ,(i,e)<-zip[0..]$sort p       -- walk through the sorted list of p
                                             -- paired with it's index ->
                                             -- (index,element) or (i,e)
                                      ,b==e  -- for those cases where b equals e
 sort s!!i                                   -- take the i-th element from the
                                             -- sorted list s

```
> 2 votes

# Answer
## R, 37 bytes

```
function(s,p,o=order)s[o(s)][o(o(p))]

```
> 2 votes

# Answer
# Jelly, 6 bytes, language postdates challenge

```
Œ¿œ?Ṣ}

```

Try it online!

This takes the pattern, followed by the source, as two separate arguments.

## Explanation

```
Œ¿œ?Ṣ}
Œ¿      Generate an integer that describes the order of {the first input}
  œ?    Use that integer to reorder
    Ṣ}  the sorted version of the second {input}

```
> 2 votes

# Answer
## Haskell, 56 bytes

```
import Data.List
p%s=[sort s!!(length$filter(<x)p)|x<-p]

```

Defines a binary function `%`. Each entry in `p` is transformed to the entry of `s` with the same order statistic, i.e. relative rank in its list. The order statistic of `x` in `p` is found by counting the elements smaller than it (`sort p!!x` produces an annoying `Maybe`). The result is indexed into `sort s`.

A `zip/lookup` solution is the same length, except it gives `Just` numbers.

```
import Data.List
p%s=[lookup x$zip(sort p)(sort s)|x<-p]

```
> 1 votes

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


# Question
Title: Change the Code, Change the Sequence: Robbers
*This is a challenge. For the cops thread, go here.*

This challenge involves two OEIS sequences chosen by the cops -- **S1**, **S2** -- and how well those sequences can be golfed and obfuscated.

The cops are constructing code **A** that produces **S1** and giving a number **X** that they claim is the best Levenshtein distance possible (in characters) to create **B** that produces **S2**.

### The Robbers' Challenge

To crack a particular cop's submission, robbers must come up with a program **C** in the same language (and version) as that answer that produces S2(n) and is **Y** character changes away from **A** (with `Y <= X`). Robbers do not necessarily need to find the exact same **B** code that the cop (secretly) produced. The robbers' submissions must adhere to the same 0-index or 1-index as specified by the cop's submission.

If you manage this, post an answer with the solution, linking to the cop's answer, and leave a comment on the cop's answer linking back to yours.

Each cop answer can only be cracked once, and of course, you're not allowed to crack your own answer. If the cop's answer turns out to be invalid before or after being cracked, it is not counted towards the robber's score.

### Winning and Scoring

Robbers are scored by `(X - Y)*5 + 5` for each of their cracks, and the robber with the overall highest score wins.

### Further Rules

* You must not use any built-ins for hashing, encryption, or random number generation (even if you seed the random number generator to a fixed value).
* Either programs or functions are allowed, but the code must not be a snippet and you must not assume a REPL environment.
* You may take input and give output in any convenient format. The input/output methods must be the same for both sequences.
* The definitive calculator for the Levenshtein distance for this challenge is this one on Planet Calc.
* In addition to being a CnR challenge, this is so all usual golfing rules apply.

# Answer
> 7 votes
# Pyke, Levenshtein distance of 1, A036487, A135628 \- score 5

Crack of an entry by muddyfish

```
wX*e

```

Try it here!

The original code, `X*e`, squares the input, `X`, multiplies that by the input `*`, and halves then floors the result, `e`.

The trick is that `'X'` is 56 in the base 96 representation of `w`, so `wX` yields 56, multiply that by the input then floor and halve and you get 28 times the input as needed.

# Answer
> 4 votes
# Brain-Flak, 28 bytes, Distance of 4, A002817, A090809

```
(({(({})[()])}{}){{({}[()])}{}})

```

This answer was discovered with the help of a brute-forcer, which generated 35,000 possible programs (Lot's of them were imbalanced, and thus invalid brain-flak code, but I rolled with the bug and found the answer anyway). This was around the 20 thousandth program tested, and it took around an hour to find (though I don't know exactly how long since I was away when it finished).

I kind of didn't want to post this answer yet, since I don't yet have a full understanding of how this program works. However, the answer is about to be safe so I don't want it to expire. I hope to update this answer more once I fully understand it, as well as posting the code I used to find this answer. But for now, I'll just post a partial explanation.

```
#Push the sum of:
(

    #The (n-1)th triangular number, and the range [1, n] (The range doesn't count towards the sum I believe)
    ({(({})[()])}{})

    #Triangulate every number on the stack
    {{({}[()])}{}}

)

```

This makes sense because OEIS states:

> For n\>0, the terms of this sequence are related to A000124 by a(n) = sum( i\*A000124(i), i=0..n-1 ). \[Bruno Berselli, Dec 20 2013\]

And A000124 are the triangular numbers + 1. However, I don't know exactly what the forumla is, so I can't fully explain how this works.

# Answer
> 3 votes
# Perl 6, 19 bytes, X = 1, A000045 → A000035

```
{(0,1,*+<*...*)[$_]}

```

`+>` in place of `+<` would also work.

Try it online!

### How it works

infix ... is quite useful for simple recursive sequences. The `(0,1,*+*...*)` part of the original code, which is a shorthand for

```
(0, 1, -> $x, $y { $x + $y } ... *)

```

specifies a sequence that begins with **0** and **1**, then adds items by computing the sum of the former two items of the sequence.

In contrast, `(0,1,*+<*...*)` uses left bit-shift (`+>`, right bit-shift would also work) to construct the parity sequence. Since shifting **1** zero units to the left is **1**, and shifting **0** one unit to the left is **0**, we get the desired alternating patterns of ones and zeroes.

# Answer
> 2 votes
# Perl 6, 10 bytes, distance 1 - score 5

Crack of an entry by smls

```
*[0]o 1***

```

Becomes:

```
*[0]o 1*+*

```

Try It Online!

# Answer
> 2 votes
# Perl 6, distance 2, smls

Original:

```
+(*%%2)

```

Crack:

```
+(*+0%2)

```

Try it online!

# Answer
> 2 votes
# WolframAlpha, Distance 1, Greg Martin, A002378, A000537

```
(sum1to#of n^1)^2&

```

**How it works**

I realized that interestingly, (n\*(n+1)/2)^2 is a formula for the second sequence. Since sum(1 to n) is equivalent to n\*(n+1)/2, I just had to switch the * to a ^.

# Answer
> 2 votes
## Brain-Flak, 20 bytes, DJMcMayhem

```
({({})({}[()])()}{})

```

Try it online!

Added a `({})` at the beginning of the loop to double the value in each iteration.

# Answer
> 1 votes
# JavaScript, Distance 4, LliwTelracs

Original:

```
f=x=>{return x?2*x-1+f(x-1):0}

```

Crack:

```
f=x=>{return x?2*(-0+f(x-1)):1}

```

Try it online!

# Answer
> 1 votes
## JavaScript(ES6), Distance 1, Advancid

Original:

```
as=function(){ return 2*2**((11)*-1*~arguments[0]/11-(4-(as+[]).length%89))-(as+[]).length%7}

```

Crack:

```
as=function(){ return 0*2**((11)*-1*~arguments[0]/11-(4-(as+[]).length%89))-(as+[]).length%7}

```

Try it online!

or

```
as=function(){ return 2*1**((11)*-1*~arguments[0]/11-(4-(as+[]).length%89))-(as+[]).length%7}

```

Try it Online!

Somehow I was able to get it to behave differently between TIO and repl.it (absolutely no clue why 2\*1^... would be equal to 0 as according to repl.it)

# Answer
> 1 votes
# Javascript, 41 bytes, Distance of 3, A061313, A004526

```
f=x=>{return x>>1;0?x%2?f(x+1)+1:f(x/2)+1:0}

```

Try it online!

# Answer
> 1 votes
## Java, Distance 4, Peech, A094683, A000290

Original:

```
int x{double r=1;for(int i=0;i<42;i++)r=r/2+n/r/2;int k=(int)((int)n*(float)n/Math.pow(n,(Math.sin(n)*Math.sin(n)+Math.cos(n)*Math.cos(n))/2));return n%4%2==(int)Math.log10(Math.E)/Math.log((double)'H'-'@')?(int)r:k;}

```

Crack:

```
int x{double r=1;for(int i=0;i<42;i++)r=r/2+n/r/2;int k=(int)((int)n*(float)n/Math.pow(n,(Math.sin(n)*Math.sin(n)+Math.cos(n)*Math.cos(n))/2));return n%4%1==(int)Math.log10(Math.E)/Math.log((double)'H'-'@')?(int)n*n:k;}
                                                                                ^                                                         ^^^

```

returns n\*n

# Answer
> 1 votes
# Javascript, Advancid, distance of 2, A059841 and A000004

Only leaving the code behind the TIO link because it seems to be breaking the site.

Thanks to @nderscore, whose code I used to decrypt the initial code

There was some redundant code such as using !!\[\]+\[\]+\[\] instead of !!\[\]+\[\].

The addition of !+\[\]-(!+\[\]) (+1-1) initially prevented decryption.

Try it Online

# Answer
> 1 votes
# Pyke, Levenshtein distance of 2, A008788, A007526

```
'SS^

```

Try it here!

### How it works

This does mixed base conversion.

`'S` grabs the input **n** and applies, pushing **\[1, ..., n\]** on the stack. The next `S` takes input **n** and pushes the same array once more. `'` seems to cause the next command to be applied to the previous top on the stack; I'm a little fuzzy on the details.

Finally, `^` applies mixed base conversion, so **\[1, ..., n\] \[1, ..., n\]** `f` computes
**a(n) := \[1\]n + n + (n)(n-1)... + \[n!\]1** where the brackets indicate the place value and the number to their right the digit.

Now, **a(n) = (1 + (1)(n-1) + (n-1)(n-2)(n-3) + ... + (n-1)!)n = n(a(n) + 1)**, which is the same recursive formula that defines **a(n)** in \[A007526\]. Since an empty sum is zero, **a(0) = 0** and the base case matches as well.

---
Tags: code-golf, sequence, cops-and-robbers
---


title: Make a picture into a sliding puzzle

text:
# Question
Title: Make a picture into a sliding puzzle
## Summary

The goal of this challenge is to create an undone image-version of a 15-puzzle / sliding puzzle also called taquin in french.

## Details:

Given an input composed of:

* an image,
* an integer `n`,
* an other integer `r`,

your program, or function, or anything else that fits, must output the same image (*i.e.* same size and format) as the input, but that underwent the following process:

1. divide the image into  rectangles,
2. remove one of those rectangles, randomly,
3. move a random number of contiguous rectangles from the *line/column* affected by point (2.) so the hole created is filled and another one is generated in this line/column. This number can be `0` if the blank is in a corner or an edge.

Repeat (3.) `r` times.

**Clarifications:**

* If you moved rectangles from the line in step (3.), you must move rectangles from the column the in the next repetition,
* if you moved rectangles left-to-right in a line-step, they must be moved right-to-left in the next line-step, same for top-to-bottom and bottom-to-top concerning columns,
* you may assume that `n` will be chosen so it divides the lengths of the sides of the picture.

**A last point:**

An animated `.gif` showing the whole process are very welcomed.

I propose to use the following picture (which is `1024x768`), with `n=16` and `r=100` as a model, you can use **any other picture** (as long as it's relevant and complies with SE's rules, of course).

Note that standards loopholes policies apply.

This is , so the shorter submission wins !

Since an example was requested, here is one, made "by hand", with `n=4` and `r=1`

**Steps 1 and 2**

**Step 3** : line-wise, 2 rectangles to the left

# Answer
# Mathematica, 246 bytes

```
ImageAssemble@(n=Nest)[k=RandomInteger;q=Reverse;({t,r}=1~k~2;q[o=n[q/@#&,#,r]&@*(n[#&,#,t]&)])[o@#/.{a___,b:_~RepeatedNull~k[Position[o@#,i][[1,2]]-1],i,c___}:>{a,i,b,c}]&,MapAt[(i=#~ImageAdd~1)&,#~ImagePartition~Scaled[1/#2],{1,#2}~k~2],#3]&

```

Anonymous function. Contains U+F3C7, corresponding to Mathematica's `Transpose` operator. This function takes an `Image` object and returns an `Image` object.

Sample Animation, with `n=16` and `r=100`

After 5000 iterations:

*(click image for larger version)*

## Explanation

### Initialization

```
n=Nest

```

Store the `Nest` function (repeating operation) in `n`.

```
k=RandomInteger;q=Reverse;

```

Store the `RandomInteger` function in `k`, and `Reverse` function in `q`.

### Splitting the image

```
#~ImagePartition~Scaled[1/#2]

```

Partition the input image into (second input)^2 tiles.

```
{1,#2}~k~2

```

Generate two `RandomInteger`s between 1 and the second input. This selects a random tile.

```
MapAt[(i=#~ImageAdd~1)&, ..., {1,#2}~k~2]

```

Make that tile white. Store it in `i`.

### Moving Tiles

```
{t,r}=1~k~2

```

Generate two random integers from 0 to 1, and store them in `t` and `r`, respectively. This randomly selects direction.

```
o=n[q/@#&,#,r]&@*(n[#&,#,t]&)

```

Define function `o`: the composition of

1. a function transposing the input `t` times.
2. a function reversing each row `r` times.

```
o@#
```

Apply `o` to the input.

```
Position[o@#,i][[1,2]]

```

Find the column of `i` (white image).

```
k[ ... -1]

```

Subtract one and find a random integer between 0 and that number. This randomly chooses how many tiles to move.

```
o@#/.{a___,b:_~RepeatedNull~ ... ,i,c___}:>{a,i,b,c}

```

When the said number of tiles occur before an `i` (white image), switch their places.

```
(... q[o= ... ])[ ... ]

```

Reverse the `o` function and apply that to the result of above operation. This un-reverses and un-transposes the image.

### Looping and Image Assembly

```
(n=Nest)[ ... ,#3]

```

Repeat the above process (third input) times.

```
ImageAssemble@

```

Put the images together.
> 10 votes

---
Tags: code-golf, image-processing, sliding-puzzle
---