title: Parking lot supervisor

text:
# Question
Title: Parking lot supervisor
# Introduction

You are a supervisor of a parking lot and your manager is preparing for shrinking the size to the extreme.

It is a simplified and adapted version of a problem in last year's PAT top-level.

# Challenge

You are asked to calculate how many cars are in the lot at the same time, **at most**.

Standard rules apply. And this is a code-golf so shortest code wins.

First line is the quantity of entries (no more than `100,000`, **your input may not contain this line if you like, for it is only a makeshift to determine where input ends**). The following text contains one entry per line. And each entry includes three numbers:

```
<Car plate number> <Time (seconds) since open> <0(In) | 1(Out)>

```

**Modification 2:** It is OK to use an array of triples as input.

**Modification 3:** You can change the order of numbers in one entry. And you can choose which to use. (see the Remarks section)

The input is guaranteed to be valid, assuming that:

* `Car plate number` is a integer in the range of `10000` ~ `99999`
* `Time` is a integer in the range of `0` ~ `86400`

And

* Entries are **not necessarily** chronologically ordered.
* There is no car before the first second.
* There is **not necessarily** no car after the last second.
* A car would not leave before it gets in.
* `Car plate number` is unique. (but a same car may visit for more than one time)
* So it is impossible for a car to enter the lot when it is already in it.
* A same car wouldn't go in and out at the same `time`.
* A car is considered to be in the lot at the time of in / out.

# Example 1

Input

```
11
97845 36000 1
75487 16500 1
12345 16 0
75486 3300 0
12345 6500 1
97845 32800 0
12345 16400 0
97846 16501 1
97846 16500 0
75486 8800 1
75487 3300 0

```

Output

```
3

```

Explanation

At `16500`, car `12345` and `75487` were in the parking lot.

# Example 2

I made this because I found many code failed on it.

Input (with first line left out)

```
12345 16400 0
12345 16500 1
75487 16500 0
75487 16600 1

```

Output

```
2

```

Explanation

At `16500`, car `12345` and `75487` were in the parking lot.

# Remarks

Actually, not all three are required for the output. At least, you only need plate+time or in/out+time for the result. But the algorithm is slightly different under two circumstances, so the choice of being shorter stays unknown in a certain language. And of course you can use all of three numbers. So I leave them in the challenge.

# Answer
> 7 votes
# Mathematica, 33 bytes

```
-Min@Accumulate[2#2-1&@@@Sort@#]&

```

I had to read the problem statement better to realize that there's a much simpler algorithm that doesn't require the license plate information.

Unnamed function returning an integer; the input format is a list of ordered triples in the form `{time, 0|1, license plate}`. We start by `Sort`ing, which makes the list chronological and also breaks time-ties by sorting `0`s before `1`s; then `2#2-1&@@@` keeps the arrival/departure information and forgets the rest, and also converts `0`s to `-1`s.

`Accumulate` calculates the running totals of that list; the result is a list of the *negatives* of the numbers of cars in the parking lot after every arrival/departure. Then `Min` picks the smallest (most negative) of these and the negative sign is stripped.

# Mathematica, 56 bytes

```
Max[<|#|>~Count~0&/@FoldList[List,{},#3->#2&@@@Sort@#]]&

```

The original submission (the first several comments refer to this submission). Unnamed function returning an integer; the input format is a list of ordered triples in the form `{time, 0|1, license plate}`.

The reason we choose to put the time entry first and the in/out entry second is so that `Sort@#` sorts the list chronologically, and records arrivals before departures if they're simultaneous. After that, `#3->#2&@@@` returns a list of "rules" of the form `license plate -> 0|1`, still sorted chronologically.

Then, `FoldList[List,{},...]` creates a list of all the initial segments of that list of rules. Actually, it really messes up those initial segments; the `k`th initial segment ends up being a list with one rule at depth 2, one rule at depth 3, ..., and one rule at depth `k`+1. (`FoldList[Append,{},...]` would yield the more natural result.) However, `<|#|>` turns each of these initial segments into an "association", which has two desirable effects: first, it completely flattens the nested-list structure we just created; and second, it forces later rules to override earlier rules, which is exactly what we need here—for any car that has left the parking lot, the record of its initial entry is now completely gone (and similarly for cars that re-enter).

So all that's left to do is to `Count` how many `0`s there are in each of these associations, and take the `Max`.

# Answer
> 5 votes
## Haskell, ~~76 63~~ 61 bytes

2 bytes saved by a variation of @nimi's suggestion.

```
f l=maximum$scanl1(+)[(-1)^c|i<-[0..8^6],(_,b,c)<-l,i==2*b+c]

```

Expects the argument as a list of triples in the order given by the problem statement.

For each possible time (and some more), we search first for coming and then for leaving car events and turn them to a list of plus or minus ones. We take the partial sums of this list and then the maximun of these partial sums.

# Answer
> 2 votes
## JavaScript (ES6), ~~83~~~~68~~ 70 bytes

*EDIT: fixed to support the 2nd example*

Takes input as an array of `[in_out, time, plate]` arrays. But the `plate` column is actually ignored.

```
a=>a.sort(([a,b],[c,d])=>b-d||a-c).map(v=>a=(n+=1-v[0]*2)<a?a:n,n=0)|a

```

### Test

```
let f =

a=>a.sort(([a,b],[c,d])=>b-d||a-c).map(v=>a=(n+=1-v[0]*2)<a?a:n,n=0)|a

console.log(f([
  [1, 36000, 97845],
  [1, 16500, 75487],
  [0, 16,    12345],
  [0, 3300,  75486],
  [1, 6500,  12345],
  [0, 32800, 97845],
  [0, 16400, 12345],
  [1, 16501, 97846],
  [0, 16500, 97846],
  [1, 8800,  75486],
  [0, 3300,  75487]
]));

console.log(f([
  [0, 16400, 12345],
  [1, 16500, 12345],
  [0, 16500, 75487],
  [1, 16600, 75487]
]));
```

# Answer
> 2 votes
# PHP 7.1, ~~126~~ 117 bytes

```
for(;$s=file(i)[++$i];)$d[+substr($s,6)][$s[-2]]++;ksort($d);foreach($d as$a){$r=max($r,$n+=$a[0]);$n-=$a[1];}echo$r;

```

takes input from file `i`, ignores first line. Run with `-r`.
Requires a trailing newline in input. Replace `-2` with `-3` for Windows.

**breakdown**

```
# generate 2-dim array; first index=time, second index=0/1 (in/out);
# values=number of cars arriving/leaging; ignore plate number
for(;$s=file(i)[++$i];) # read file line by line (includes trailing newline)
    $d[+substr($s,6)][$s[-2]]++;    # substring to int=>time, last but one character=>1/0
ksort($d);                      # sort array by 1st index (time)
foreach($d as$a)    # loop through array; ignore time
{
    $r=max($r,                      # 2. update maximum count
        $n+=$a[0]                   # 1. add arriving cars to `$n` (current no. of cars)
    );
    $n-=$a[1];                      # 3. remove leaving cars from `$n`
}
echo$r;                         # print result

```

# Answer
> 2 votes
# C, 147 bytes

A complete program, reads input from `stdin`.

```
int r[86402]={},u,i,n,t;g(s,o){for(;s<86401;n<r[s]?n=r[s]:0,++s)r[s+o]+=o?-1:1;}main(){for(n=0;scanf("%d%d%d",&u,&t,&i)==3;g(t,i));printf("%d",n);}

```

Try it on ideone.

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

```
d=>Math.max(...d.sort((a,[b,c])=>a[s=0]-b||a[1]-c).map(e=>s+=1-e[1]*2))

```

This accepts input as an array of entries ordered `[time, inout, plate]`. Unfortunately due to the fact that identical inout times means that both cars are considered in the lot at the moment in time, the sorting algorithm must order `0` prior to `1`, which costed 11 bytes.

## Credits

* I saved 1 byte by moving the shift and multiplication inside the map function completely (thanks Neil).
* I saved another two bytes by using a destructured argument in the sort function (thanks edc65).

## Demo

```
// test the two examples
console.log([[[36000,1],[16500,1],[16,0],[3300,0],[6500,1],[32800,0],[16400,0],[16501,1],[16500,0],[8800,1],[3300,0]],[[16400,0],[16500,1],[16500,0],[16600,1]]].map(
// answer submission
d=>Math.max(...d.sort((a,[b,c])=>a[s=0]-b||a[1]-c).map(e=>s+=1-e[1]*2))
));
```

# Answer
> 2 votes
# Octave , ~~50~~, ~~64~~ 38 bytes

```
@(A)-min(cumsum(sortrows(A)(:,2)*2-1))

```

Same as @Greg Martin 's Mathematica answer

The function gets an array with 3 columns `[time, i/o,plateN]`

previous answer:

```
@(A){[t,O]=A{:};max(cumsum(sparse({++t(!O),t}{2},1,!O*2-1)))}{2}

```

The function only gets two inputs `t`: time and `O`: I/O from first two element of a cell array `A` that contains triple inputs!

A sparse matrix created to count for each recorded time number of existing cars . For it time of out + 1 is considered for car exit and corresponding 1 change to -1 and 0 changed to 1.
Use of sparse here is very important since multiple cars may arrive or leave at the same time.
Then cumulative sum computed representing number of current cars in the lot and max of it is found.

---
Tags: code-golf
---


# Question
Title: Quine that takes as input the name of a language and outputs the same thing implemented in the input language
From Quine central:

Write a quine that takes as input the name of a language and outputs the same thing implemented in the input language.

The source article has something you can work from, but as the author says this is much harder. Obviously you only need to support a limited set of languages. The choice is yours though, as well as the base language.

As a , your score will be the number of languages your program supports; higher is better.

# Answer
> 5 votes
## Ruby

```
require 'json';s=%q[{"ruby":[" %q[","require 'json';s=##;j=JSON.load s;puts j[l=gets.chomp][1].sub('##',j[l][0].delete(' ')+s+j[l][2].delete(' '))"," ]"],"python":["' ''","import json,re;s=##;j=json.loads(s);l=raw_input();print(re.sub('##',j[l][0].replace(' ','')+s+j[l][2].replace(' ',''),j[l][1],1))","' ''"]}];j=JSON.load s;puts j[l=gets.chomp][1].sub('##',j[l][0].delete(' ')+s+j[l][2].delete(' '))

```

## Python

```
import json,re;s='''{"ruby":[" %q[","require 'json';s=##;j=JSON.load s;puts j[l=gets.chomp][1].sub('##',j[l][0].delete(' ')+s+j[l][2].delete(' '))"," ]"],"python":["' ''","import json,re;s=##;j=json.loads(s);l=raw_input();print(re.sub('##',j[l][0].replace(' ','')+s+j[l][2].replace(' ',''),j[l][1],1))","' ''"]}''';j=json.loads(s);l=raw_input();print(re.sub('##',j[l][0].replace(' ','')+s+j[l][2].replace(' ',''),j[l][1],1))

```

Both versions take input on stdin (`ruby` or `python` currently) and generate the output to stdout in either language.

# Answer
> 3 votes
# Turtlèd, Python 2, and Python 3, 3 languages, only competing for bounty

all oneliners follwed by newline

## Turtlèd

```
@##'@r,r,r-{ +.r_}r{ +.r_}!!-.(3"';m=ord(input()[-1]);_='x=%r;m=ord(input()[-1]);_=%r;print(_.replace(chr(100)+chr(40),chr(100)+chr(40)+chr(114)+chr(97)+chr(119)+chr(95))%%(x,_) if m==50 else _%%(x,_) if m==51 else x.replace(chr(121),chr(39)))';print(_.replace(chr(100)+chr(40),chr(100)+chr(40)+chr(114)+chr(97)+chr(119)+chr(95))%(x,_) if m==50 else _%(x,_) if m==51 else x.replace(chr(121),chr(39)))"367>;++[ d( d)('.)]d<"x='"))(2"';m=ord(raw_input()[-1]);_='x=%r;m=ord(input()[-1]);_=%r;print(_.replace(chr(100)+chr(40),chr(100)+chr(40)+chr(114)+chr(97)+chr(119)+chr(95))%%(x,_) if m==50 else _%%(x,_) if m==51 else x.replace(chr(121),chr(39)))';print(_.replace(chr(100)+chr(40),chr(100)+chr(40)+chr(114)+chr(97)+chr(119)+chr(95))%(x,_) if m==50 else _%(x,_) if m==51 else x.replace(chr(121),chr(39)))"371>;++[ d( d)('.)]d<"x='"))(d' )#'@r,r,r-{ +.r_}r{ +.r_}!!-.(3"';m=ord(input()[-1]);_='x=%r;m=ord(input()[-1]);_=%r;print(_.replace(chr(100)+chr(40),chr(100)+chr(40)+chr(114)+chr(97)+chr(119)+chr(95))%%(x,_) if m==50 else _%%(x,_) if m==51 else x.replace(chr(121),chr(39)))';print(_.replace(chr(100)+chr(40),chr(100)+chr(40)+chr(114)+chr(97)+chr(119)+chr(95))%(x,_) if m==50 else _%(x,_) if m==51 else x.replace(chr(121),chr(39)))"367>;++[ d( d)('.)]d<"x='"))(2"';m=ord(raw_input()[-1]);_='x=%r;m=ord(input()[-1]);_=%r;print(_.replace(chr(100)+chr(40),chr(100)+chr(40)+chr(114)+chr(97)+chr(119)+chr(95))%%(x,_) if m==50 else _%%(x,_) if m==51 else x.replace(chr(121),chr(39)))';print(_.replace(chr(100)+chr(40),chr(100)+chr(40)+chr(114)+chr(97)+chr(119)+chr(95))%(x,_) if m==50 else _%(x,_) if m==51 else x.replace(chr(121),chr(39)))"371>;++[ d( d)('.)]d<"x='"))(d' )

```

Try it online!

## Python 2

```
x='@##y@r,r,r-{ +.r_}r{ +.r_}!!-.(3"y;m=ord(input()[-1]);_=yx=%r;m=ord(input()[-1]);_=%r;print(_.replace(chr(100)+chr(40),chr(100)+chr(40)+chr(114)+chr(97)+chr(119)+chr(95))%%(x,_) if m==50 else _%%(x,_) if m==51 else x.replace(chr(121),chr(39)))y;print(_.replace(chr(100)+chr(40),chr(100)+chr(40)+chr(114)+chr(97)+chr(119)+chr(95))%(x,_) if m==50 else _%(x,_) if m==51 else x.replace(chr(121),chr(39)))"367>;++[ d( d)(y.)]d<"x=y"))(2"y;m=ord(raw_input()[-1]);_=yx=%r;m=ord(input()[-1]);_=%r;print(_.replace(chr(100)+chr(40),chr(100)+chr(40)+chr(114)+chr(97)+chr(119)+chr(95))%%(x,_) if m==50 else _%%(x,_) if m==51 else x.replace(chr(121),chr(39)))y;print(_.replace(chr(100)+chr(40),chr(100)+chr(40)+chr(114)+chr(97)+chr(119)+chr(95))%(x,_) if m==50 else _%(x,_) if m==51 else x.replace(chr(121),chr(39)))"371>;++[ d( d)(y.)]d<"x=y"))(dy )#y@r,r,r-{ +.r_}r{ +.r_}!!-.(3"y;m=ord(input()[-1]);_=yx=%r;m=ord(input()[-1]);_=%r;print(_.replace(chr(100)+chr(40),chr(100)+chr(40)+chr(114)+chr(97)+chr(119)+chr(95))%%(x,_) if m==50 else _%%(x,_) if m==51 else x.replace(chr(121),chr(39)))y;print(_.replace(chr(100)+chr(40),chr(100)+chr(40)+chr(114)+chr(97)+chr(119)+chr(95))%(x,_) if m==50 else _%(x,_) if m==51 else x.replace(chr(121),chr(39)))"367>;++[ d( d)(y.)]d<"x=y"))(2"y;m=ord(raw_input()[-1]);_=yx=%r;m=ord(input()[-1]);_=%r;print(_.replace(chr(100)+chr(40),chr(100)+chr(40)+chr(114)+chr(97)+chr(119)+chr(95))%%(x,_) if m==50 else _%%(x,_) if m==51 else x.replace(chr(121),chr(39)))y;print(_.replace(chr(100)+chr(40),chr(100)+chr(40)+chr(114)+chr(97)+chr(119)+chr(95))%(x,_) if m==50 else _%(x,_) if m==51 else x.replace(chr(121),chr(39)))"371>;++[ d( d)(y.)]d<"x=y"))(dy )';m=ord(raw_input()[-1]);_='x=%r;m=ord(input()[-1]);_=%r;print(_.replace(chr(100)+chr(40),chr(100)+chr(40)+chr(114)+chr(97)+chr(119)+chr(95))%%(x,_) if m==50 else _%%(x,_) if m==51 else x.replace(chr(121),chr(39)))';print(_.replace(chr(100)+chr(40),chr(100)+chr(40)+chr(114)+chr(97)+chr(119)+chr(95))%(x,_) if m==50 else _%(x,_) if m==51 else x.replace(chr(121),chr(39)))

```

Try it online!

## Python 3

```
x='@##y@r,r,r-{ +.r_}r{ +.r_}!!-.(3"y;m=ord(input()[-1]);_=yx=%r;m=ord(input()[-1]);_=%r;print(_.replace(chr(100)+chr(40),chr(100)+chr(40)+chr(114)+chr(97)+chr(119)+chr(95))%%(x,_) if m==50 else _%%(x,_) if m==51 else x.replace(chr(121),chr(39)))y;print(_.replace(chr(100)+chr(40),chr(100)+chr(40)+chr(114)+chr(97)+chr(119)+chr(95))%(x,_) if m==50 else _%(x,_) if m==51 else x.replace(chr(121),chr(39)))"367>;++[ d( d)(y.)]d<"x=y"))(2"y;m=ord(raw_input()[-1]);_=yx=%r;m=ord(input()[-1]);_=%r;print(_.replace(chr(100)+chr(40),chr(100)+chr(40)+chr(114)+chr(97)+chr(119)+chr(95))%%(x,_) if m==50 else _%%(x,_) if m==51 else x.replace(chr(121),chr(39)))y;print(_.replace(chr(100)+chr(40),chr(100)+chr(40)+chr(114)+chr(97)+chr(119)+chr(95))%(x,_) if m==50 else _%(x,_) if m==51 else x.replace(chr(121),chr(39)))"371>;++[ d( d)(y.)]d<"x=y"))(dy )#y@r,r,r-{ +.r_}r{ +.r_}!!-.(3"y;m=ord(input()[-1]);_=yx=%r;m=ord(input()[-1]);_=%r;print(_.replace(chr(100)+chr(40),chr(100)+chr(40)+chr(114)+chr(97)+chr(119)+chr(95))%%(x,_) if m==50 else _%%(x,_) if m==51 else x.replace(chr(121),chr(39)))y;print(_.replace(chr(100)+chr(40),chr(100)+chr(40)+chr(114)+chr(97)+chr(119)+chr(95))%(x,_) if m==50 else _%(x,_) if m==51 else x.replace(chr(121),chr(39)))"367>;++[ d( d)(y.)]d<"x=y"))(2"y;m=ord(raw_input()[-1]);_=yx=%r;m=ord(input()[-1]);_=%r;print(_.replace(chr(100)+chr(40),chr(100)+chr(40)+chr(114)+chr(97)+chr(119)+chr(95))%%(x,_) if m==50 else _%%(x,_) if m==51 else x.replace(chr(121),chr(39)))y;print(_.replace(chr(100)+chr(40),chr(100)+chr(40)+chr(114)+chr(97)+chr(119)+chr(95))%(x,_) if m==50 else _%(x,_) if m==51 else x.replace(chr(121),chr(39)))"371>;++[ d( d)(y.)]d<"x=y"))(dy )';m=ord(input()[-1]);_='x=%r;m=ord(input()[-1]);_=%r;print(_.replace(chr(100)+chr(40),chr(100)+chr(40)+chr(114)+chr(97)+chr(119)+chr(95))%%(x,_) if m==50 else _%%(x,_) if m==51 else x.replace(chr(121),chr(39)))';print(_.replace(chr(100)+chr(40),chr(100)+chr(40)+chr(114)+chr(97)+chr(119)+chr(95))%(x,_) if m==50 else _%(x,_) if m==51 else x.replace(chr(121),chr(39)))

```

Try it online!

## Explanation:

For each language, I took already written quines and modified them a bit.

### Turtlèd first:

Turtlèd includes the standard quine structure. however, should the input end with a 2 or a 3, it appends the end of the python code, either 2 or 3, it includes them both separately, to the quine output, and then goes back to the start and adds `x='`. Otherwise the sourcecode is left and output like a regular quine

Also note it takes input twice `!!.`, because the source contains a newline which feeds to input an empty line.

however, along the way to the start of string, in order to avoid the fact that the string cannot have `'` in it, it changes all the `'` in the main source along the way to `y`. if it did, quote escaping could be annoying, if even possible

this relies on a trick; I could not have written `(''y)`, `(pseudocode:if cell is ', write y)`, because then that y would have been indistinguishable from a '. so, I use the y from the input "Python"! this was a real eureka moment for me.

then, there are the python quinelike things.

### How the python quinelike thing works:

it works like a regular quine, except it also includes the variable x

if it has input Python 3, it works like a regular quine, and uses % formatting to also include the source for Turtlèd.

if it has input Python 2, it replaces `input` in the string with `raw_input`, and does otherwise the exact same thing.

if input is Turtlèd, it replaces the `y`s in the Turtlèd source and prints it.

The two python programs function the same, and take input the same way

---
Tags: code-challenge, quine, rosetta-stone
---


title: Incremental Quine

text:
# Question
Title: Incremental Quine
Your task is to write a program or function that outputs the first character of its source code, then the second, then the third... each time it is run.

For example, if your program was `foo` in language `bar` in file `baz.bar`, then you should get output similar to this:

```
λ bar baz.bar
f
λ bar baz.bar
o
λ bar baz.bar
o

```

Your program can do anything once its done printing its source code in this fashion. You may modify the source code for the file, but remember that the source code to be printed is the *original* source code.

This is a code-golf, so the shortest program in bytes wins.

# Answer
# Jelly, 12 bytes

```
“;⁾vṾ®ȯ©Ḣ”vṾ

```

This is a niladic link. Try it online! (Includes code to call the link twelve times.)

### How it works

```
“;⁾vṾ®ȯ©Ḣ”vṾ  Niladic link.

“;⁾vṾ®ȯ©Ḣ”    Set the left argument and the return value to s =: ';⁾vṾ®ȯ©Ḣ'.
           Ṿ  Uneval; yield r =: '“;⁾vṾ®ȯ©Ḣ”', a string representation of s.
          v   Eval; execute s as a Jelly program with argument r.

 ⁾vV          Yield 'vṾ'.
;             Concatenate r and 'vṾ', yielding q =: '“;⁾vṾ®ȯ©Ḣ”vṾ'.
    ®ȯ        Take the flat logical OR of the register (initially 0) and q.
              This replaces 0 with q in the first run, but it will yield the
              content of the register in subsequent runs.
      ©       Copy the result to the register.
       Ḣ      Head; pop and yield the first character of the register.
              This modifies the string in the register, so it holds one fewer
              character after each call.

```

As an added bonus, since the register will hold an empty string after the twelveth call, it is once again falsy and the link is ready to start over. Calling the link 24 times will output the source code twice, calling it 36 times thrice, etc.
> 6 votes

# Answer
# Javascript - 26 bytes

Defines `f()` that returns the source code character by character.

```
n=0;f=x=>("n=0;f="+f)[n++]

```

Returns undefined after it runs out of characters.

```
n=0;f=x=>("n=0;f="+f)[n++]
for(i=0;i<30;i++){console.log(f())} //test harness
```
> 12 votes

# Answer
# stacked, noncompeting, 34 bytes

```
[tostr ':!' + execCounter # out]:!

```

A variation on the standard quine. This is a full program. This uses `execCounter` to get how many times this program specifically was run. Errors after outputting everything.

Try it here!
> 2 votes

# Answer
# Pip, 31 bytes

```
{Y"{Y (yRsRPy++v)}"(yRsRPy++v)}

```

An anonymous function. Test it on TIO!

### Explanation

Start with this standard Pip quine:

```
Y"Y yRsRPy"yRsRPy
Y"Y yRsRPy"        Yank that string into y
           yRsRPy  In y, replace the space with repr(y)

```

Wrap this in curly braces to make it a function. Now, instead of returning the whole source, we need to index into it. Using a global variable for the index and incrementing it each time will fulfill the "next character each time it's called" requirement. `v` is the best candidate because it is preinitialized to `-1`. Incrementing it the first time gives an index of `0`, next time `1`, etc.

Pip has cyclical indexing, so once the function prints its last character, it will start over at the beginning.
> 2 votes

# Answer
# Python, 90 bytes

An extension on the standard Python quine (golfing tips welcome):

```
def f(n=0,s='def f(n=0,s=%r):\n while 1:yield(s%%s)[n];n+=1'):
 while 1:yield(s%s)[n];n+=1

```

This is a python generator function, meaning that you iterate over it, and each iteration provides the next character in the source code. When all the characters have been returned, this crashes with `IndexError`.

For testing, simply append this script to the end of the program:

```
source = ''
try:
    # Call generator, add characters to the string
    for char in f():
        source += char
except IndexError:
    # Generator has reached end of source code
    pass

print(source)

```

## Or **try it online!**
> 1 votes

# Answer
# Microscript II, ~~40~~ 33 bytes

A code block literal, the language's closest equivalent to a function:

```
{ss1K+>K>s#<v{o}sl*v!(123v)lKp<o}

```

After running, it puts itself back into `x` to make it easier to invoke again.
> 1 votes

# Answer
## \*\>\<\>, ~~13~~ 21 bytes

```
" r:2+a1Fi1+:1F1+[ro;

```

Creates a file named `\n` to keep track of the index.

This may be able to be golfed more, but nothing immediately jumps out at me ...

### Output

```
$ starfish incrementalquine.sf
"$ starfish incrementalquine.sf
 $ starfish incrementalquine.sf
r$ starfish incrementalquine.sf
:$ starfish incrementalquine.sf
2$ starfish incrementalquine.sf
+$ starfish incrementalquine.sf
a$ starfish incrementalquine.sf
1$ starfish incrementalquine.sf
F$ starfish incrementalquine.sf
i$ starfish incrementalquine.sf
1$ starfish incrementalquine.sf
+$ starfish incrementalquine.sf
:$ starfish incrementalquine.sf
1$ starfish incrementalquine.sf
F$ starfish incrementalquine.sf
1$ starfish incrementalquine.sf
+$ starfish incrementalquine.sf
[$ starfish incrementalquine.sf
r$ starfish incrementalquine.sf
o$ starfish incrementalquine.sf
;$ starfish incrementalquine.sf

```

### Explanation

```
" r:2+                 build the quine
      a1F              open file named "\n"
         i1+:          read input, increment by 1, duplicate
             1F        save incremented input to file
               1+[     increment input, copy that many values to a new stack
                  ro   output the character at the beginning of the new stack
                    ;  end

```

### Cheating Incremental Quine

```
a1Fi1+:0go1F;

```

**Explanation**

```
a1F            open file named "\n"
   i1+         read input and add 1 to it
      :0g      push the value at (input,0) to the stack
         o     output the value
          1F   save the incremented input to the file
            ;  exit

```
> 1 votes

# Answer
# Mathematica, 91 bytes

Comments very welcome; I'm still learning the ropes about what quines are proper quines.

```
(If[!NumberQ[q], q = 0]; StringTake[ToString[#0]<>FromCharacterCode[{91, 93}], {++q}]) & []

```

Defines a function called repeatedly with no arguments. After the 91st call, it throws a big error and returns unevaluated.

There were two issues to overcome: first, I wanted to just use `StringTake[ToString[#0]<>"[]"]`, but `ToString[]` seems to erase the quotation marks; so I had to replace `"[]"` by `FromCharacterCode[{91, 93}]`. Second, Mathematica variables start out uninitialized, so I can't call `++q` before `q` is defined; this is why the initial `If[!NumberQ[q], q = 0]` is needed.

Irrelevant coda: while looking up `NumberQ`, I learned that Mathematica has a function called `TrueQ` ... which, yes, returns `True` if the argument is `True` and `False` if the argument is `False`! (The utility is that it returns `False` on all other arguments as well.)
> 1 votes

# Answer
# Bash (and zsh, ksh), 39-bytes

```
a=`<$0`;pwd>>0;echo ${a:`wc -l<0`-1:1}

```

It prints nothing after once the program is printed out.

Ensure `0` does not exists in the current directory and run:

```
bash iquine.bash

```
> 0 votes

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


title: Fishing for Cube Nets

text:
# Question
Title: Fishing for Cube Nets
Cubes can be made of six squares as sides. But you could also fold three 2x1 rectangles in half and glue them together to form a cube. Now in this challenge you get a set of pieces which are each made from squares, and you have to determine whether you can choose pieces to form a unit cube. Not all of the pieces have to be used, there might be some left over.

## Details

The pieces are given as a string of two different characters or a black and white image or any convenient 2D raster format. In the following I assume the pixels that form the pieces are black, and the background is in white.

Two pixels who share a side are considered to belong to the same piece. The pieces can only be folded along the gridlines that separate the pixels, and they cannot be cut. Each side of the cube has the size of one pixel, and each side of the cube can only be made of a single layer.

The output must be a *truthy* or *falsey* value.

## Testcases

In the following, the spaces  are background and hash symbols `#` represent the pieces.

(more to be added)

### Valid

```
##
 ##
  ##

```

---

```
 #
####
 #

```

---

```
# # # # # # #

```

---

```
# ##
## #

```

### Invalid

```
###
###

```

---

```
#  #
####

```

---

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

```

Run the following snippet for more testcases.

```
document.getElementById("asdfasdf").style.display = "block";
```

```
<div id="asdfasdf" display="none">
<h3>Valid</h3>

    <pre><code>
    ##
     ##
      ##
    </code></pre>

    <hr>

    <pre><code>
     #
    ####
     #
    </code></pre>

    <hr>

    <pre><code>
    # # # # # # #
    </code></pre>

    <hr>

    <pre><code>
    # ##
    ## #
    </code></pre>

    <hr>

    <pre><code>
    #   #
    ###
      #
    </code></pre>

    <h3>Invalid</h3>

    <pre><code>
    ###
    ###
    </code></pre>

    <hr>

    <pre><code>
    #  #
    ####
    </code></pre>

    <hr>

    <pre><code>
    ### ## ####
    </code></pre>

    <hr>

    <pre><code>
    ##  ##  ##  ##
    ##  ##  ##  ##
      ##  ##  ##  ##
      ##  ##  ##  ##
    </code></pre>
  </div>
```

PS: This is a generalization of this challenge

# Answer
> 7 votes
# C, ~~824~~ 803 bytes

```
#define Z return
#define Y char*b
#define N --n
i,j,n,w,h,A,B,C,D,E,F,G,H;char c[9999],*r,*d;x(b)Y;{if(b<c||*b<35)Z;++n;*b^=1;x(b-1);x(b+1);x(b-w);x(b+w);}m(b,p,y)Y,*p;{d=b;if(!y)for(y=-1,--p;1[++p]&31;)d+=w;for(i=0;*p&31?!(*p&16>>i)||b[i]&1:0;++i>4?p+=y,b+=w,i=0:0);Z!(*p&31)?x(d),n:0;}a(b)Y;{for(j=n=0;j<w*h;++j)if(m(c+j,b,1)||m(c+j,b,0))Z n;Z 0;}f(Y){bzero(c,9999);for(h=0,b=strcpy(c,b);r=b,b=strchr(b+1,10);h++,w=b-r);for(A=2,r=1+"@_`^C@|T@^R@XO@XX`|FB@|PP@|DD@PXN@XHX@XPX`PPXL@XHHX@XLDD@XPPX`PPPXH@PXHHH@PPPPP@";*r;r+=A+=r[-1]/96)while(a(r));A=B=C=D=E=F=G=H=0;while(a("PX")||a("XH")) (n-=3)?N?N?N?0:++H:++G:++F:++C;while(a("^")||a("PPPP"))(n-=4)?N?N?0:++H:++G:++E;while(a("P"))N?N?N?N?N?N?0:++H:++G:++F:++D:++B:++A;Z H||(G&&A)||(F&&B+B+A>1)||(E&&A>1)||D>1||C>1||((D||C)*3+B*2+A>5)*(A>1||B>2||A*B);}

```

> *Note: Includes a bug fix (the previous entry falsely identified a tromino and two dominoes as forming a cube).* *In the TIO driver code, there are more test cases and there's now a pass/fail tracker; hexomino test cases were updated with the expected pass/fail value in the label.*

Try it online!

...and before explaining this in detail, it's worth a high level overview.

**Basic Overview**

This algorithm applies a pattern matcher to classify each polyomino it finds with a given pattern as its subset. As polyominoes are matched they are "unmarked", excluding them from pattern matching again. The initial classification given by the matcher is simply a count of the number of tiles in the polyomino.

The matcher is applied first to cull out all polyominoes that cannot be folded onto a cube; the classification of these polyominos is discarded. The match succeeds if these polyominoes appear within higher level ones; therefore, we only care about the smallest subset of "unfoldable" for each class. Shown here along with padded encodings are all such polyominoes (excluding their vertical reflections). The encoding uses bits 4-0 of each character to represent squares on each row:

[^C```] [XHX``] [PPPXH] [XHHX`] [PXN``] [|PP``]
 ####.   ##...   #....   ##...   #....   ###..
 ...##   .#...   #....   .#...   ##...   #....
 .....   ##...   #....   .#...   .###.   #....
 .....   .....   ##...   ##...   .....   .....
 .....   .....   .#...   .....   .....   .....
[|FB``] [XPX``] [PPXL`] [XLDD`] [XPPX`] [|DD``]
 ###..   ##...   #....   ##...   ##...   ###..
 ..##.   #....   #....   .##..   #....   ..#..
 ...#.   ##...   ##...   ..#..   #....   ..#..
 .....   .....   .##..   ..#..   ##...   .....
 .....   .....   .....   .....   .....   .....
[|T```] [^R```] [PXHHH] [XO```] [_````] [PPPPP]
 ###..   ####.   #....   ##...   #####   #....
 #.#..   #..#.   ##...   .####   .....   #....
 .....   .....   .#...   .....   .....   #....
 .....   .....   .#...   .....   .....   #....
 .....   .....   .#...   .....   .....   #....

[XX```]
 ##...
 ##...
 .....
 .....
 .....

Once these polyominoes are culled, we categorize the remaining polyominoes into relevant categories. It's worth noting that in *almost* all cases, one can just find polyominoes that remain (those foldable onto cubes) and simply search for sums of six. There are two exceptions:

* A corner tromino and a line tromino cannot form a cube
* A line tetromino and a domino cannot form a cube

In order to be able to accommodate this restriction we form 8 categories, from A-H: A for monominoes (lone tiles), B for dominoes, C for corner trominoes, D for line trominoes, E for line tetrominoes, F for other tetrominoes, G for pentominoes, and H for hexominoes. Anything not falling into one of these categories is just ignored. Counting polyominoes that fall into each category suffices.

At the end, we just return truthiness or falsiness based on a giant equation and these tabulations.

**Ungolfed with comments**

```
i,j,n,w,h,A,B,C,D,E,F,G,H;char c[9999],*r,*d;
x(b)char*b;{      // recursively unmarks polyomino pointed to by b.
   if(b<c||*b<35)return;
   ++n; *b^=1;    // Tabulates tiles in n as it goes.
   x(b-1);x(b+1);x(b-w);x(b+w); // left/up/down/right
}
m(b,p,y)char*b,*p;{ // pattern match area b with pattern p, direction y.
                    //   y=1 scans down; y=0 scans up.
   d=b; // d tracks a tile in the currently matched pattern for unmarking.
        // Note that all patterns are oriented to where "top-left" is a tile.
   if(!y) // ...when scanning up, move p to the end, set y to -1 to count backward,
          //    and advance d to guarantee it points to a tile (now "bottom-left")
      for(y=-1,--p;1[++p]&31;)d+=w;
   // Match the pattern
   for(i=0;*p&31?!(*p&16>>i)||b[i]&1:0;++i>4?p+=y,b+=w,i=0:0);
   return !(*p&31)   // If it matches...
          ? x(d),n   // ...unmark/count total polyomino tiles and return the count
          : 0;
}
a(b)char*b;{ // Scan for an occurrence of the pattern b.
   for(j=n=0;j<w*h;++j)
      if(m(c+j,b,1)||m(c+j,b,0)) // (short circuit) try down then up
         return n;
   return 0;
}
// This is our function.  The parameter is a string containing the entire area,
// delimited by new lines.  The algorithm assumes that this is a rectangular area.
// '#' is used for tiles; ' ' spaces.
f(char*b) {
   bzero(c,9999); // Init categories, c buffer
   for(h=0,b=strcpy(c,b);r=b,b=strchr(b+1,10);h++,w=b-r); // Find width/height
   // Unmark all polyominoes that contain unfoldable subsets.  This was
   // compacted since the last version as follows.  A tracks
   // the current pattern's length; r[-1], usually terminator for the
   // previous pattern, encodes whether the length increases; and o/c
   // the patterns were sorted by length.
   for(A=2,r=1+"@_`^C@|T@^R@XO@XX`|FB@|PP@|DD@PXN@XHX@XPX`PPXL@XHHX@XLDD@XPPX`PPPXH@PXHHH@PPPPP@";*r;r+=A+=r[-1]/96)
      while(a(r));
   A=B=C=D=E=F=G=H=0;
   // Match corner trominoes now to ensure they go into C.
   while(a("PX")||a("XH"))
      (n-=3)
         ?   --n
             ?   --n
                 ?   --n
                    ?   0 // More than 6 tiles?  Ignore it.
                    : ++H // 6 tiles?  It's an H.
                 : ++G // 5 tiles?  It's a G.
             : ++F // 4 tiles?  It's an F.
        : ++C; // only 3 tiles?  It's a C.
   // Now match line tetrominoes to ensure they go into E.
   while(a("^")||a("PPPP"))
      (n-=4)
         ?   --n
             ?   --n
                 ?   0 // More than 6 tiles?  Ignore it.
                 : ++H // 6 tiles?  It's an H.
             : ++G // 5 tiles?  It's a G.
         : ++E; // only 4 tiles?  It's an E.
   // Find all remaining tetrominoes ("P" is a monomino pattern)
   while(a("P"))
      --n
         ?   --n
             ?   --n
                 ?   --n
                     ?   --n
                         ?   --n
                             ?   0 // More than 6 tiles?  Ignore it.
                             : ++H // 6 tiles?  It's an H.
                         : ++G // 5 tiles? It's a G.
                     : ++F // 4 tiles?  It's an F.
                : ++D // 3 tiles?  It's a D.
            : ++B // 2 tiles?  It's a B.
         : ++A; // only 1 tile? It's an A.
   // Figure out if we can form a cube:
   return H               // Yes if we have a foldable hexomino
      ||(G&&A)            // Yes if we have a foldable pentomino
                          // and a monomino
      ||(F&&B+B+A>1)      // Yes if we have a foldable non-line tetromino
                          // and 2 other tiles (dominoes count twice).
                          // Either one domino or two monominoes will do.
      ||(E&&A>1)          // Yes if we have a foldable line tetromino (E)
                          // and two monominoes (A).  Note we can't make a
                          // cube with a line tetromino and a domino (B).
      ||D>1               // Yes if we have two line trominoes
      ||C>1               // Yes if we have two corner trominoes
      ||((D||C)*3+B*2+A>5)
                          // Any combination of trominoes, dominoes, monominoes>6,
                          // where trominoes are used at most once
                          // (via logical or)...
         * (A>1||B>2||A*B)
                          // ...times this includer/excluder fudge factor
                          // that culls out the one non-working case;
                          // see table:
                          //
                          // Trominos Dominos Monomos Cube  A>1 B>2 A*B
                          //    1        0       3+    yes   Y   N   0
                          //    1        1       1+    yes   Y   N   1
                          //    1        2       0     no    N   N   0
                          //    0+       3       0+    yes   Y   Y   1
      ;
}

```

---
Tags: code-golf, geometry
---


title: <("<) Bird Dancer (>")>

text:
# Question
Title: <("<) Bird Dancer (>")>
Your bird has been itching for some exercise and is sick of being stuck in static positions all the time. Write a program that will show a randomly dancing ascii bird, updating every 100ms\*n or 200ms\*n depending on the dance move. The bird always begins with the dance move `<(")>`.

The program should accept one input which is a number to multiply the sleep interval by (`n >= 0 && n <= 50`).

**100ms Moves**

```
^(")v
v(")^
^(")^
v(")v

```

**200ms Moves**

```
(>")>
<(")>
<("<)

```

## Extra Details

* Randomness doesn't have to be uniform but each dance move should have a reasonable chance of occuring (at least 1 in 60 seems fair, it's OK if the same move occurs twice in a row)
* There should only be one bird displayed at a time, not multiple birds
* Trailing whitespace is allowed (but other trailing characters are not)
* A bird should be displayed *before* the sleep

## Example in Python 3

```
import random, time, sys

birds = """(>")>
<(")>
<("<)
^(")v
v(")^
^(")^
v(")v"""
birds = birds.split()

interval = int(input("Sleep for 100ms*"))
selection = -1

while True:
    if selection == -1:
        selection = 1
    else:
        selection = random.randint(0, len(birds)-1)
    sys.stdout.write('\r'+birds[selection])
    if selection > 2:
        time.sleep(0.1*interval)
    else:
        time.sleep(0.2*interval)

```

## Winning

# Answer
# MATL, 53 bytes

```
xXx`'./U;HbG#3@@!{uu'F'v^<>(")'Za7e 7YrY)D5M3>QG*&XxT

```

Moves are uniformly random.

Below is a sample run with`n = 2`. Or try it at **MATL Online!** (The interpreter is experimental. If it doesn't run initially try pressing "Run" again or refreshing the page).

### Explanation

```
x                   % Take input n and delete it
Xx                  % Clear screen
`                   % Do...while
  './U;HbG#3@@!{uu' %   Push this (compressed) string
  F                 %   Specify source alphabet for decompression
  'v^<>(")'         %   Push target alphabet
  Za                %   Base conversion (decompress)
  7e                %   Reshape as a 7-row char matrix. Each row is a move
  7Yr               %   Push random integer from 1 to 7
  Y)                %   Select that row from the char matrix
  D                 %   Display it
  5M                %   Push the integer again
  3>                %   Does it exceed 3? Gives false (0) or true (1)
  Q                 %   Add 1
  G*                %   Multiply by n
  &Xx               %   Pause that many tenths of a second and clear screen
  T                 %   Push true
                    % End (implicit). Since top of the stack is true, this causes
                    % and infinite loop

```
> 3 votes

# Answer
# Matlab, ~~125~~ 117 bytes

Unfortunately this cannot be displayed in TIO as there is no "streaming" of the output. Here's a gif for an input of `1` instead:

```
t=input('')*.1;a='^(")vv(")^^(")^v(")v(>")><(")><("<)';while 1;n=randi(7);clc;disp(a(n*5-4:n*5));pause(t+t*(n>4));end

```

Thanks @LuisMendo for -8 bytes!
> 6 votes

# Answer
## \*\>\<\>, ~~103~~ 101 bytes

```
<vD[3'(")'
1x<.5
S\:43_C43CdooI:o@:o@:o@Do
R!"^"x"v">
>:2* _"><"92.
x '>)">('u.02S*2:oooooodO<'<("<)'

```

Try it here! (write in `n` on the initial stack or you'll get an error)

I decided to take a stab at my challenge since there were no sub 100 bytes answers. Place `n` on the stack and away you go! This reuses the `(")` characters to save some bytes.

# Explanation

## Initialisation

`<vD[3'(")'`

Here we store `(")` for later usage.

```
<           move the IP left
   [3'(")'  push '(")' to a new stack
  D         move back down to a clean stack
 v          move the IP down into "dance chooser"

```

## Dance chooser

```
1x<.5
 \

```

This is frequently executed to select which type of dance we're going to generate.

```
 x         generate a 100ms dance or a 200ms dance
1  .5      jump to "200ms dance"
 \         mirror IP into "100ms dance"

```

There's a `v` above the `x` and a `<` to the right of it too. These make the `x` get re-executed if it tries to move the IP in the wrong direction.

## Generate 100ms dance

```
S\:1*43_C43CdooI:o@:o@:o@Do

```

Here we generate and output one of the 100ms dance moves.

```
 \                         mirror the IP right
  :                        copy n
   43 C43C                 call "generate '^' or 'v'" twice
     _                     ignored mirror
          do               output a carriage return
            o              output the first hand of the bird
             I:o@:o@:o@D   select, copy, and output '(")'
                        o  output the second hand of the bird
S                          sleep for previous n*100ms
 \                         mirror IP back to "dance chooser"

```

### 43C - Generate "^" or "v"

```
R!"^"x"v">

```

This is a simple function that generates "^" or "v" then returns. It works similarly to the dance chooser where it has instructions around `x` to ensure the IP only moves left or right.

```
     x      generate "^" or "v"
R!"^"    >  push "^" to stack and return
R     "v"   push "v" to stack and return

```

## Generate 200ms dance

This is another that begins with `x`. It'll be separated into two sections: `<(")>` and another `(>")> and <("<)`, because they're two distinct sections and `x` is the only thing they share.

### `<(")>`

```
>:2* _"><"b2.

```

This basically does the beginning of the `generate 100ms dance` routine, but populates the bird hands as `><` instead of a random `^v` combo. It multiplies `n` by two this time as well. This makes it all setup to utilise the `generate 100ms dance` routine to output the entire bird and wait 200ms instead.

```
>              move IP right
 :2*           copy n and do n*2
     _         ignored mirror
      "><"     push "><" to stack
          b2.  jump to "output carriage return" in "generate 100ms dance"

```

### `(>")>` and `<("<)`

```
x '>)">('u.02S*2:oooooodO<'<("<)'

```

This little explanation is about the `(>")>` and `<("<)` generation, though the `x` can send the IP outside of it (explained below).

```
x                                  move to "choose dance", generate (>")>, <("<), or <(")> (previous routine)
  '>)">('                          push '(>")>' to the stack
                          '<("<)'  push '<("<)' to the stack
         u              O<         ensure inner code block is always executed with IP moving left
                      od           output carriage return
                 ooooo             output bird
             S*2:                  sleep for n*200ms
          .02                      jump to "dance chooser"

```
> 5 votes

# Answer
# JavaScript (ES6) + HTML5: ~~118~~ 116 + 8 = 124 bytes

## Javascript: 119 bytes

```
f=n=>{a.innerHTML='(>")>0<(")>0<("<)0^(")v0v(")^0^(")^0v(")v'.split(0)[r=+new Date%7],setTimeout(f,(1+(r<3))*100*n,n)}

```

I'm using the milliseconds since epoch to generate a random-ish number. Theoretically, this would always generate the same (set of) number(s), but a test on my PC gave me a pretty random outcome (most numbers appeared more or less equally). Also using the fact that html elements with an id get added to the global window object in JavaScript, so `document.getElementById()` is not needed.

## HTML: 8 bytes

```
<b id=a>

```

I'm omitting the quotes here and I'm not closing the `b` tag. It's not valid html, but all browsers automatically close the tag anyway. I made it bold because `b` is a one-character HTML element and because my bird's dance deserves being noticed.
> 3 votes

# Answer
# PowerShell, ~~124~~ 117 bytes

(Thanks TimmyD)

```
for(){(-split'^(")v v(")^ ^(")^ v(")v (>")> <(")> <("<)')[($i=0..6|random)];sleep -m((100,200)[$i-gt3]*$args[0]);cls}

```

Try it online! (Not that it will work in TIO...)
> 2 votes

# Answer
# Noodel, noncompeting 67 bytes

```
ʠƘṣḳƑðẉḤż’ṀỴ(EḞ4ĊḌṀY%¤ĠẸG^ḞðxỌð
ḊḢðḞ’ṀḌcṀḌcİ8c¬ððɲḷṛḋʠṡʠạÇƥƥạƥḋʠ⁺µḍ

```

This challenge was very difficult for *Noodel* because it does not have any smart arithmetic or comparative based operators. But after doing this challenge, I think *Noodel* is ready for its first release.

Try it:)

## How It Works

```
                                                                     # Note: The input is immediately pushed onto the stack.
ʠ                                                                    # Moves the pointer for the top of the stack down one.
 ƘṣḳƑðẉḤż’ṀỴ(EḞ4ĊḌṀY%¤ĠẸG^ḞðxỌð                                      # Creates a string based off of the key "ƘṣḳƑðẉḤż" and the compressed text "ṀỴ(EḞ4ĊḌṀY%¤ĠẸG^ḞðxỌð" to create "^(")vðv(")^ð^(")^ðv(")vð(>")>ð<(")>ð<("<)" which then gets split by the null character "ð" to create an array of strings which gets pushed to the stack.
                               \n                                    # A new line to separate the literals.
                                 ḊḢðḞ’ṀḌcṀḌcİ8c¬ðð                   # Creates a string based off of the key "ḊḢðḞ" and the compressed text "ṀḌcṀḌcİ8c¬ðð" to create "100ð100ð100ð100ð200ð200ð200" which then gets split the same way as before.
                                                  ɲ                  # Turns each element in the array into a number creating the array of delays.
                                                   ḷ                 # Loops the rest of the code unconditionally.
                                                    ṛ                # Generates a random number from 0 to the length-1 of the array on top of the stack.
                                                     ḋ               # Duplicates the random number.
                                                      ʠ              # Moves the stack pointer down to save one of the random numbers for later.
                                                       ṡ             # Swap the array with the random number such that the array is on top again.
                                                        ʠ            # Moves the stack pointer down such that the random number is on top.
                                                         ạ           # Uses the random number to access the bird array which is now after the random number and pushes the element onto the stack.
                                                          Ç          # Clears the screen and pops the bird and pushes it to the screen.
                                                           ƥƥ        # Moves the stack pointer up two times such that the random number is the top.
                                                             ạ       # Use the random number to access the array with delays and pushes that item onto the stack.
                                                              ƥ      # Moves the stack pointer up in order to have the input on top.
                                                               ḋ     # Duplicates the users input.
                                                                ʠ    # Moves the stack pointer back down in order to have the user input on top followed by the random item from the delay array.
                                                                 ⁺µ  # This command pops two numbers off and multiplies them and pushes the result back on.
                                                                   ḍ # Pops off of the stack and uses that as a delay in milliseconds.

```

---

**64 bytes**

Here is a version that works as a code snippet.

```
ʠƘṣḳƑðẉḤż’ṀỴ(EḞ4ĊḌṀY%¤ĠẸG^ḞðxỌð EAð¶’Ṁ|ṢĿ<h4¶¬ȥḷṛḋʠṡʠạÇƥƥạƥḋʠ⁺µḍ

```

```
<div id="noodel" code="ʠƘṣḳƑðẉḤż’ṀỴ(EḞ4ĊḌṀY%¤ĠẸG^ḞðxỌð EAð¶’Ṁ|ṢĿ<h4¶¬ȥḷṛḋʠṡʠạÇƥƥạƥḋʠ⁺µḍ" input="2" cols="5" rows="3"></div>

<script src="https://tkellehe.github.io/noodel/release/noodel-1.1.js"></script>
<script src="https://tkellehe.github.io/noodel/ppcg.min.js"></script>
```
> 2 votes

# Answer
# Python, 157 bytes

```
import time,random;n,m=5,int(input())
while 1:print('(>")><(")><("<)^(")vv(")^^(")^v(")v'[n:n+5]);time.sleep((.1+(n<15)/10)*m);n=(n+random.randint(1,6)*5)%35

```

I also tried to do it without the chicken ascii art, but that was way longer.

```
import time,random;n,m=5,int(input())
while 1:
  print(['^v'[n%2]+'(")'+'v^'[0<n<3],''.join(map(chr,[40+20*(n>4),62-22*(n>4),34,41+19*(n>5),62-21*(n>5)]))][n>3])
  time.sleep((.1+(n>3)/10)*m);n=(n+random.randint(1,6))%7

```
> 1 votes

# Answer
# Ruby, 97+1 = 98 bytes

+1 byte from the `-n` flag.

```
a=1;loop{puts %w{^(")v <(")> v(")^ (>")> ^(")^ <("<) v(")v}[a];sleep$_.to_i*0.1*(1+a%2);a=rand 7}

```
> 1 votes

# Answer
## Clojure, ~~185~~ 178 bytes

+18 bytes because it wasn't starting with `<(")>`.

-7 bytes by inlining `birds`, and getting rid of the `let`.

```
#(loop[m nil r(or m 1)](print"\r"((clojure.string/split"(>\")> <(\")> <(\"<) ^(\")v v(\")^ ^(\")^ v(\")v"#" ")r))(flush)(Thread/sleep(*(if(> r 2)100 200)%))(recur 1(rand-int 7)))

```

Just splits the birds on spaces, picks a random index from 0-6, displays the chosen bird, then if the chosen index is greater than 2, it waits for 100ms, else 200ms.

Clojure really needs a string `split` method in the core.

Ungolfed:

```
(defn dancing-bird [n]
  (loop [m nil]
    (let [birds (clojure.string/split "(>\")> <(\")> <(\"<) ^(\")v v(\")^ ^(\")^ v(\")v" #" ")
          rand-i (or m 1)]
      (print "\r" (birds rand-i))
      (flush)
      (Thread/sleep (* (if (> r 2) 100 200) n))
      (recur (rand-int 7)))))

```
> 1 votes

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


# Question
Title: Detect ASCII-art windows made of M and S characters
A Window is an ASCII-art square with odd side length of at least 3, with a single character border around the edge as well as vertical and horizontal strokes in the middle:

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

```

An MS Window is a window where the border is made only of the characters `M` and `S`. Your task is to write a program (or function) that takes a string and outputs a truthy value if the input is a valid MS Window, and a falsey value if it is not.

# Specifications

* You may take the input as a newline-separated string or an array of strings representing each line.
* The border of an MS Window may contain a mix of M and S characters, but the inside will always be composed of spaces.
* You can choose to detect only windows with trailing newlines, or only windows without trailing newlines, but not both.

# Test Cases

Truthy:

```
MMM
MMM
MMM

SMSMS
M M S
SMSMM
S S M
SMSMS

MMMMMMM
M  S  M
M  S  M
MSSSSSM
M  S  M
M  S  M
MMMMMMM

```

Falsey:

```
Hello, World!

MMMM
MSSM
MS M
MMMM

MMSMM
M S.M
sSSSS
M S M
MMSMM

MMMMMMM
M  M  M
MMMMMMM
M  M  M
MMMMMMM

MMMMMMM
M M M M
MMMMMMM
M M M M
MMMMMMM
M M M M
MMMMMMM

MMSSMSSMM
M   M   M
S   S   S
S   S  S
MMSSMSSMM
S   S   S
S   S   S
M   M   M
MMSSMSSMM

```

# Answer
> 1 votes
## Pyke, ~~34~~ 31 bytes

```
lei}t\Mcn+it*i\M*+s.XM"QJ\S\M:q

```

Try it here!

```
lei                              -         i = len(input)//2
   }t                            -        (^ * 2) - 1
     \Mc                         -       "M".center(^)
        n+                       -      ^ + "\n"
          it*                    -     ^ * (i-1)
                 +               -    ^ + V
             i\M*                -     "M"*i
                  s              -   palindromise(^)
                   .XM"          -  surround(^, "M")
                               q - ^ == V
                       QJ        -   "\n".join(input)
                         \S\M:   -  ^.replace("S", "M")

```

# Answer
> 8 votes
## Retina, ~~68~~ 67 bytes

Byte count assumes ISO 8859-1 encoding.

```
S
M
^(M((M)*M)\2)((?<-9>¶M((?<9-3> )*(?(3)!)M|\5)\5)*(?(9)!)¶\1)\4$

```

Try it online!

# Answer
> 7 votes
## Grime, ~~39~~ 38 bytes

*Thanks to Zgarb for saving 1 byte.*

```
e`BB/BB/W+ W/+
B=W|B/W\ * W/\ /*
W=[MS

```

Try it online!

I'm not sure whether there's a simpler way to enforce the square aspect ratio of the individual window components than using a recursive nonterminal, but this seems to be working quite well.

### Explanation

It's best to read the program from the bottom up.

```
W=[MS

```

This simply defines a nonterminal (which you can think of as a subroutine that matches a rectangle) `W` which matches either an `M` or an `S` (there's an implicit `]` at the end of the line).

```
B=W|B/W\ * W/\ /*

```

This defines a non-terminal `B` which matches about a quarter of the output, i.e. one window panel with the left and top border. Something like this:

```
MSM
S
M

```

To ensure that this window panel is square, we define `B` recursively. It's either a window character `W`, or it's `B/W\ * W/\ /*` which adds one layer to the right and to the bottom. To see how it does this, let's remove some syntactic sugar:

```
(B/W[ ]*)(W/[ ]/*)

```

This is the same, because horizontal concatenation can be written either `AB` or `A B`, but the latter has lower precedence than the vertical concatenation `/` while for the former has higher. So `B/W[ ]*` is a `B` with a window character and a row of spaces below. And then we horizontally append `W/[ ]/*` which is a window character with a column of spaces.

Finally, we assemble these nonterminals into the final window shape:

```
BB/BB/W+ W/+

```

That's four window panels `B` followed by a row of window characters and a column of window characters. Note that we make no explicit assertion that the four window panels are the same size, but if they aren't it's impossible to concatenate them into rectangle.

Finally the `e`` at the beginning is simply a configuration which tells Grime to check that the entire input can be matched by this pattern (and it prints `0` or `1` accordingly).

# Answer
> 5 votes
# Perl, ~~124~~ ~~123~~ ~~119~~ ~~95~~ ~~93~~ 84

The following Perl script reads one candidate MS Window from the standard input. It then exits with a zero exit status if the candidate is an MS Window and with a non-zero exit status if it isn't.

It works by generating two regular expressions, one for the top, middle and bottom line and one for every other line, and checking the input against them.

Thanks, @Dada. And again.

```
map{$s=$"x(($.-3)/2);$m="[MS]";($c++%($#a/2)?/^$m$s$m$s$m$/:/^${m}{$.}$/)||die}@a=<>

```

# Answer
> 5 votes
## JavaScript (ES6), ~~115~~ 113 bytes

```
a=>(l=a.length)&a.every((b,i)=>b.length==l&b.every((c,j)=>(i&&l+~i-i&&l+~i&&j&&l+~j-j&&l+~j?/ /:/[MS]/).test(c)))

```

Takes input as a an array of arrays of characters (add 5 bytes for an array of strings) and returns `1` or `0`. After verifying that the height is odd, every row is checked to ensure the array is square, and every character is verified to be one of the character(s) that we expect in that particular position. Edit: Saved 2 bytes thanks to @PatrickRoberts.

# Answer
> 2 votes
# Mathematica, 166 bytes

```
Union[(l=Length)/@data]=={d=l@#}&&{"M","S"}~(s=SubsetQ)~(u=Union@*Flatten)@{#&@@(p={#,(t=#~TakeDrop~{1,-1,d/2-.5}&)/@#2}&@@t@#),p[[2,All,1]]}&&{" "}~s~u@p[[2,All,2]]&

```

Unnamed function taking a list of lists of characters as input and returning `True` or `False`. Here's a less golfy version:

```
(t = TakeDrop[#1, {1, -1, d/2 - 0.5}] &;
Union[Length /@ data] == {d = Length[#1]}
  &&
(p = ({#1, t /@ #2} &) @@ t[#1];
SubsetQ[{"M", "S"}, Union[Flatten[{p[[1]], p[[2, All, 1]]}]]]
  &&
SubsetQ[{" "}, Union[Flatten[p[[2, All, 2]]]]])) &

```

The first line defines the function `t`, which separates a list of length `d` into two parts, the first of which is the first, middle, and last entries of the list, and the second of which is all the rest. The second line checks whether the input is a square array in the first place. The fourth line uses `t` twice, once on the input itself and once on all\* of the strings in the input, to separate the characters that are supposed to be `"M"` or `"S"` from the characters that are supposed to be spaces; then the fifth and seventh lines check whether they really are what they're supposed to be.

# Answer
> 2 votes
## JavaScript (ES6), ~~108~~ 106 bytes

Input: array of strings / Output: `0` or `1`

```
s=>s.reduce((p,r,y)=>p&&r.length==w&(y==w>>1|++y%w<2?/^[MS]+$/:/^[MS]( *)[MS]\1[MS]$/).test(r),w=s.length)

```

### Test cases

```
let f =

s=>s.reduce((p,r,y)=>p&&r.length==w&(y==w>>1|++y%w<2?/^[MS]+$/:/^[MS]( *)[MS]\1[MS]$/).test(r),w=s.length)

console.log('Testing truthy test cases...');

console.log(f([
  'MMM',
  'MMM',
  'MMM'
]));

console.log(f([
  'SMSMS',
  'M M M',
  'SMSMS',
  'M M M',
  'SMSMS'
]));

console.log(f([
  'MMMMMMM',
  'M  S  M',
  'M  S  M',
  'MSSSSSM',
  'M  S  M',
  'M  S  M',
  'MMMMMMM'
]));

console.log('Testing falsy test cases...');

console.log(f([
  'Hello, World!'
]));

console.log(f([
  'MMMM',
  'MSSM',
  'MS M',
  'MMMM'
]));

console.log(f([
  'MMSMM',
  'M S.M',
  'sSSSS',
  'M S M',
  'MMSMM'
]));

console.log(f([
  'MMMMMMM',
  'M  M  M',
  'MMMMMMM',
  'M  M  M',
  'MMMMMMM'
]));

console.log(f([
  'MMMMMMM',
  'M M M M',
  'MMMMMMM',
  'M M M M',
  'MMMMMMM',
  'M M M M',
  'MMMMMMM'
]));
```

# Answer
> 2 votes
# JavaScript (ES6), ~~140~~ ~~138~~ ~~141~~ 140 bytes

I know this isn't a winning byte count (although thanks to Patrick Roberts for -3, and I realised it threw false positives for 1 instead of M/S: +3), but I did it a slightly different way, I'm new to this, and it was fun...

Accepts an array of strings, one for each line and returns true or false. Newline added for clarity (not included in byte count).

```
f=t=>t.every((e,i)=>e.split`S`.join`M`==[...p=[b='M'.repeat(s=t.length),
...Array(z=-1+s/2|0).fill([...'MMM'].join(' '.repeat(z)))],...p,b][i])

```

Instead of checking input against a generalised pattern, I construct an 'M' window of the same size, replace S with M on input, and compare the two.

## Ungolfed

```
f = t => t.every( // function returns true iff every entry in t
                  // returns true below
  (e, i) => e.split`S`.join`M` // replace all S with M
                                 // to compare to mask
  == [ // construct a window of the same size made of Ms and
       // spaces, compare each row
      ...p = [ // p = repeated vertical panel (bar above pane)
               // which will be repeated
              b = 'M'.repeat(s = t.length),
                  // b = bar of Ms as long as the input array
              ...Array(z = -1 + s/2|0).fill([...'MMM'].join(' '.repeat(z)))],
              // z = pane size; create enough pane rows with
              // Ms and enough spaces
      ...p, // repeat the panel once more
      b][i] // finish with a bar
)

console.log(f(["111","111","111"]))

console.log(f(["MMMMM","M S M","MSSSM","M S M","MSSSM"]))
```

## Test cases

```
f=t=>t.every((e,i)=>e.split`S`.join`M`==[...p=[b='M'.repeat(s=t.length),
...Array(z=-1+s/2|0).fill([...'MMM'].join(' '.repeat(z)))],...p,b][i])

truthy=`MMM
MMM
MMM

SMSMS
M M M
SMSMS
M M M
SMSMS

MMMMMMM
M  S  M
M  S  M
MSSSSSM
M  S  M
M  S  M
MMMMMMM`.split('\n\n')

falsey=`Hello, World!

MMMM
MSSM
MS M
MMMM

MMSMM
M S.M
sSSSS
M S M
MMSMM

MMMMMMM
M  M  M
MMMMMMM
M  M  M
MMMMMMM

MMMMMMM
M M M M
MMMMMMM
M M M M
MMMMMMM
M M M M
MMMMMMM`.split('\n\n')

truthy.forEach(test=>{
  console.log(test,f(test.split('\n')))
})

falsey.forEach(test=>{
  console.log(test,f(test.split('\n')))
})
```

# Answer
> 1 votes
# JavaScript (ES6), ~~109~~ ~~107~~ ~~106~~ ~~105~~ 99 bytes

```
s=>!s.split`S`.join`M`.search(`^((M{${r=s.search`
`}})(
(M( {${w=(r-3)/2}})M\\5M
){${w}}))\\1\\2$`)

```

**Edit**: Whoa, Arnauld saved me 6 bytes by changing `s.split`\n`.length` to `s.search`\n``! Thanks!

This takes a single multiline string and constructs a `RegExp`-based validation using the length of the input string. Returns `true` or `false`. Assumes a valid window ~~has~~ *does not have* a trailing newline.

# Demo

```
f=s=>!s.split`S`.join`M`.search(`^((M{${r=s.search`
`}})(
(M( {${w=(r-3)/2}})M\\5M
){${w}}))\\1\\2$`);
`MMM
MMM
MMM

SMSMS
M M M
SMSMS
M M M
SMSMS

MMMMMMM
M  S  M
M  S  M
MSSSSSM
M  S  M
M  S  M
MMMMMMM

Hello, World!

MMMM
MSSM
MS M
MMMM

MMSMM
M S.M
sSSSS
M S M
MMSMM

MMMMMMM
M  M  M
MMMMMMM
M  M  M
MMMMMMM

MMMMMMM
M M M M
MMMMMMM
M M M M
MMMMMMM
M M M M
MMMMMMM`.split`

`.forEach(test=>{console.log(test,f(test));});
```

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


title: Kids shuffling cards

text:
# Question
Title: Kids shuffling cards
Shuffling a deck of cards is hard for kids, so they must figure out ways to get a reasonable well shuffled deck as simply as possible.

One way to do this that gives reasonably good results is:

1. Take the top card out and insert it a random place in the deck
2. Take the bottom card out and insert it in a random place in the deck
3. Continue until you believe it's good enough.

Note that you shall never insert a card in the top or bottom spot, it should be placed somewhere *in* the deck.

---

Instead of shuffling cards, we'll shuffle alphanumerical characters: `0-9`, `A-J`, `a-j`, `q-z` and `Q-Z`.

Start with the string shown below and shuffle the characters the way it's described above. You can choose if you want to continue shuffling infinitely or shuffle the cards 100 rounds (100 cards from the top and 100 cards from the bottom).

```
0123456789abcdefghijqrstuvwxyzABCDEFGHIJQRSTUVWXYZ

```

The challenge is to display the characters being shuffled. Each "shuffle" (take out and insert card) shall take between 0.25 and 0.35 seconds.

The gif below shows an example output:

---

This is so the shortest code in bytes wins.

---

<sub>*"Why don't you have `a-t` instead of `a-j`, `q-z`?"* Because this shall illustrate suits of cards, not just characters. And yes, there are 5 suits.</sub>

---

Note: I have decided to stop using the check mark on -challenges. Relevant meta posts here and here.

# Answer
## JavaScript (ES6), ~~192~~ ~~188~~ 185 bytes

```
document.write('<pre id=o>')
s='ABCDEFGHIJQRSTUVWXYZ'
a=[0,...123456789+s.toLowerCase()+s]
setInterval('o.innerText=a.join``;a.splice(Math.random(s^=1)*48+1,0,s?a.pop():a.shift())',250)
```

Edit: Saved 4 bytes thanks to @L.Serné. Saved 3 bytes thanks to @Arnauld.
> 5 votes

# Answer
# MATL, ~~62~~ ~~58~~ 56 bytes

*2 Bytes saved thanks to @Luis*

```
4Y2'A':'J'tk'Q':'Z'tk&h`48YrQJh&)@o?l&)wb}wO&)]&htD3&XxT

```

This version will run indefinitely. Try the online demo at MATL Online, an experimental online interpreter that supports dynamic output. This will run for 30 seconds (a hard limit imposed by the online version) if it isn't killed first.

**Explanation**

```
4Y2     % Predefined literal for the characters '0'...'9'
'A':'J' % Create an array of the characters 'A'...'J'
tk      % Duplicate and make lowercase
'Q':'Z' % Create an array of the characters 'Q'...'Z'
tk      % Duplicate and make lowercase
&h      % Horizontally concatenate everything
`       % Do...while loop
  48YrQ % Determine a random integer between 2 and 49
  Jh&)  % Split the string at the selected location
  @o?   % If this is an odd time through the loop
    l&) % Grab the first character
    wb  % Move it to the middle of the stack of three strings
  }     % Else...
    wO&)% Grab the last character and move it to the middle of the stack
  ]     % End of if statment
  &h    % Horizontally concatenate all strings on the stack
  tD    % Duplicate and display the current string
  3&Xx  % Pause for 0.3 seconds and clear the display
  T     % Push a literal TRUE to the stack to make this an infinite loop
        % Implicit end of while loop

```
> 4 votes

# Answer
## Python 3, ~~199~~ ~~196~~ ~~192~~ 186 bytes

Saved 4 bytes thanks to TuukkaX, and 6 bytes thanks to FlipTack!

```
import time,random
s="abcdefghijqrstuvwxyz";s="0123456789"+s+s.upper()
f=0
while 1:print(end="\r"+s);time.sleep(.3);s,e=s[1^f:50-f],s[f and-1];i=random.randint(1,49);s=s[:i]+e+s[i:];f^=1

```

Uses Python 3's `print` function to suppress newline, shorter than Python 2's `sys.stdout.write`.

Uses a flip-flop variable to switch between moving the top and the bottom cards.

Ungolfed:

```
from random import randint
from time import sleep

string = "abcdefghijqrstuvwxyz"
string = "0123456789" + string + string.upper()
flip_flop = 0
while True:
    print("\r"+string,end="")
    sleep(0.3)
    string,char = string[not flip_flop:50-flip_flop], string[flip_flop and -1]
    position = randint(1,49)
    string = string[:position] + char + string[position:]
    f = not f

```
> 4 votes

# Answer
## Perl, 117 bytes

```
@F=(0..9,a..j,"q"..z,A..J,Q..Z);{print"\r",@F;splice@F,++$|+rand(@F-2),0,++$v%2?shift@F:pop@F;select$,,$,,$,,.3;redo}

```

To run it:

```
perl -e '@F=(0..9,a..j,"q"..z,A..J,Q..Z);{print"\r",@F;splice@F,++$|+rand(@F-2),0,++$v%2?shift@F:pop@F;select$,,$,,$,,.3;redo}'

```

Explanations:
-`@F=(0..9,a..j,"q"..z,A..J,Q..Z)` creates the initial deck, and stores it in `@F`.
-`{...;redo}` executes `...` forever.
-`splice@F,++$|+rand(@F-2),0,++$v%2?shift@F:pop@F` alternatively remove the first/last element from the deck and insert in at a random position (while incrementing `$|`, so the prints aren't buffered),
\- `print"\r",@F` prints the deck,
\- `select$,,$,,$,,.3` sleeps for 0.3 seconds (Perl's `sleep` can't sleep for less than 1 second),
> 4 votes

# Answer
## C, ~~290~~ 285 bytes

```
#include<stdio.h>
#include<time.h>
#define S(s,a,b){int p=rand()%48+1;clock_t c=clock()+300;while(c>clock());int x=d[s];for(int i=s;i a p;)d[i b]=d[i];d[p]=x;printf(d);}
main(){char d[]="0123456789abcdefghijqrstuvwxyzABCDEFGHIJQRSTUVWXYZ\r";srand(time(0));for(;;){S(0,<,++)S(49,>,--)}}

```

Ungolfed:

```
#include<stdio.h> // variadic(printf) functions without a valid prototype = UB
#include<time.h>  // required for the implementation-defined clock_t type
// note that <stdlib.h> isnt required for srand()/rand() because they are
//  validly declared implicitly
#define S(s,a,b) // macro function
{
    int p=rand()%48+1;     // get a random position within the array
    clock_t c=clock()+300; // get the time 300 milliseconds from now
    while(c>clock());      // wait for that time
    int x=d[s];            // save the s'th character in a tempvar
    for(int i=s;i a p;)    // shift everything in the array from p
        d[i b]=d[i];       // a determines the comparison: </>
                           // b determines the operation: ++/--
    d[p]=x;                // put the tempvar in its new position
    printf(d);             // print the modified string
} // note: the \r at the end makes it so the next printf overwrites it

main() // main entry point
{      // deck to shuffle below
    char d[]="0123456789abcdefghijqrstuvwxyzABCDEFGHIJQRSTUVWXYZ\r";
    srand(time(0)); // seed the random number generator
    for(;;)         // infinite loop
    {
        S(0,<,++)   // shuffle from the start of the deck
        S(49,>,--)  // shuffle from the end of the deck
    }
}

```
> 3 votes

# Answer
# Ruby (138 119 Bytes)

```
f=0;a=[*0..9,*?a..?j,*?q..?z,*?A..?J,*?Q..?Z];loop{$><<a*''+?\r;a.insert(rand(48),f>0? a.shift : a.pop);f^=1;sleep 0.3}

```

Not as short as @PaulPrestidge but at least I understand it.. Also great to learn that ruby is like a endless tunnel of awesome!
> 2 votes

# Answer
# Swift, 288 bytes

```
import Darwin
var o=Array("0123456789abcdefghijqrstuvwxyzABCDEFGHIJQRSTUVWXYZ".characters)
while true{
print(String(o),terminator:"\r")
fflush(__stdoutp);{o.insert(o.removeLast(),at:$0())
o.insert(o.removeFirst(),at:$0()+1)}({Int(arc4random_uniform(UInt32(o.count-1)))})
usleep(300000)
}

```

Golfing in Swift is always a challenge, as one of its selling points is expressiveness.
> 2 votes

# Answer
# Noodel, noncompeting 41 bytes

```
"Q…Z"A…J"q…z"a…j"0…9⁵⁺ḷçṛ47⁺1ɱɲOṃḃɲ49ḅṙḍq

```

Try it:)

### How It Works

```
"Q…Z"A…J"q…z"a…j"0…9⁵⁺                    # Creates the string literal to be shuffled.
                      ḷçṛ47⁺1ɱɲO      ṙḍq # The main "infinite" loop that applies the animation.
                                ṃḃɲ49ḅ    # Sub-loop that acts like an if-statement that only runs every odd iteration of the loop.

"Q…Z                                      # Pushes the string literal "QRSTUVWXYZ".
    "A…J                                  # Pushes the string literal "ABCDEFGHIJ".
        "q…z                              # Pushes the string literal "qrstuvwxyz".
            "a…j                          # Pushes the string literal "abcdefghij".
                "0…9                      # Pushes the string literal "0123456789".
                    ⁵⁺                    # Add the five strings on the stack to make one string.
                      ḷ                   # Unconditionally loop the following code.
                       ç                  # Copy what is on the top of the stack, clear the screen, and then print the copy.
                        ṛ47               # Create a random integer from 0 to 47.
                           ⁺1             # Increment the number to get 1 - 48 such that will not be the top or bottom of the deck.
                             ɱ            # Push the number of times that the unconditional loop has ran.
                              ɲO          # Consume the counter and push on zero if is even and one if is odd.
                                ṃ         # Conditional loop that only passes if the top of the stack is truthy (if the counter is odd).
                                 ḃ        # Throws away the top of the stack.
                                  ɲ49     # Pushes the literal 49 in order to represent the top of the deck.
                                     ḅ    # Ends the conditional loop.
                                      ṙ   # Relocate an element in the string by using the two numbers on the stack (either 0 or 49 to the random number).
                                       ḍq # Delay for a quarter of second. (End of unconditional loop)

```

```
<div id="noodel" code='"Q…Z"A…J"q…z"a…j"0…9⁵⁺ḷçṛ47⁺1ɱɲOṃḃɲ49ḅṙḍq' input="" cols="50" rows="2"></div>

<script src="https://tkellehe.github.io/noodel/release/noodel-0.0.js"></script>
<script src="https://tkellehe.github.io/noodel/ppcg.min.js"></script>
```
> 1 votes

# Answer
# Ruby, ~~111~~ 101 characters

```
s=[*0..9,*?a..?j,*?q..?z,*?A..?J,*?Q..?Z,?\r]*''
loop{$><<s;s[1+rand(48),0]=s.slice!$.^=-2;sleep 0.3}

```

Loops infinitely.
> 1 votes

# Answer
# bash, 170 bytes

```
r(){((r=RANDOM%48+1));echo -n $c^;sleep .3;}
c=0123456789abcdefghijqrstuvwxyzABCDEFGHIJQRSTUVWXYZ
while r
do
c=${c:1:r}${c:0:1}${c:r+1}
r
c=${c:0:r}${c:49}${c:r:-1}
done

```

here '^' (on the first line) represents `ctrl-m`: entered on the command-line as `ctrl-v` `enter` or in an editor according to how your editor works (assuming your editor works)
> 0 votes

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


title: Smallest Multiple to "Palindromize"

text:
# Question
Title: Smallest Multiple to "Palindromize"
# Goal:

Given any non-zero natural number `a`, find the smallest non-zero natural number `b` such that `a•b` is palindromic, e.g. it reads the same forwards and backwards. Input `a` through any reasonable means (STDIN, function argument, etc.), And output `b` through any reasonable means (STDOUT, function return value.)

# Notes:

* Input will not always have a solution (multiples of 10), so you must create an error, or display -1/0
* Input validation is not necessary, assume `a` is a natural number.
* Standard loopholes apply (Hardcoding, using a language created after this challenge)

# Examples:

```
a=34, b=8 (272)
a=628, b=78 (48984)
a=15, b=35 (525)
a=33, b=1 (33)
a=20, (Error, -1, or 0)

```

# Answer
# Pyth, ~~10~~ 9 bytes

```
&eQf_I`*Q

```

Try it online.

### Explanation

```
&eQf_I`*QT    Implicitly append T, and take input in Q.
 eQ           Calculate input mod 10.
&             Logical and, only evaluate the following if result ≠ 0.
   f          Starting from 1, find the first integer T for which...
      `       ...the string representation of...
       *QT    ...input multiplied by T...
    _I        ...is equal to its reverse.

```
> 5 votes

# Answer
## Ruby, 51 bytes

```
->a{(1..a%10/0.0).find{|b|(c="#{a*b}")==c.reverse}}

```

### Explanation

```
        a%10/0.0 # -> NaN for multiples of 10, Infinity otherwise

```
> 2 votes

# Answer
# 05AB1E, 11 bytes

```
T%            # input mod 10
  0›          # is greater than 0
    µ         # repeat the following until counter reaches that number (0 or 1)
     ¹N*      # input * iteration
        ÂQ    # is equal to its reverse
          ½   # if true, increase counter
              # implicitly output last iteration (or 0)

```

Try it online!
> 2 votes

# Answer
# C, ~~108~~ 101 bytes

*Thanks to @nmjcman101 for 7 bytes!*

```
m,o;f(n){for(o=0;n;)o=o*10+n%10,n/=10;return o;}g(n){m=-1;if(n%10)for(m=1;n*m!=f(n*m);m++);return m;}

```

Is C the only language here with no built-in reversing/checking palindrome function?

Try it online!
> 2 votes

# Answer
## Java, 113 bytes

```
i->{int j=1;for(String a;!new StringBuilder(a=String.valueOf(i*j)).reverse().toString().equals(a);)j++;return j;}

```
> 1 votes

# Answer
# Python 2, ~~78~~ ~~66~~ 60 bytes

```
def f(a):
 b=a%10!=0
 while `a*b`!=`a*b`[::-1]:b+=1
 print b

```

Try it online
> 1 votes

# Answer
## QBIC, 29 bytes

```
:{c=a*q~!c$=_f!c$||_Xq\q=q+1

```

Explanation:

```
:      Get cmd line param as number 'a'
{      DO
c=a*q  multiply 'a' by 'q' and assign to 'c', which is 1 at the start of a QBIC program
~      IF
!c$    'c' cast to string
=      equals
_f!c$| 'c' cast to string, the reversed
|      THEN
_Xq    Quit, printing 'q'
\q=q+1 ELSE increment q and rerun
       DO Loop is auto-closed by QBIC, as is the IF

```

Eventually, 'q' will overflow and throw an error on an unsolvable 'a'.
> 1 votes

# Answer
## Mathematica, 43 bytes

```
If[10∣#,0,#//.x_/;!PalindromeQ@x:>x+#]/#&

```

### Explanation

```
If[10∣#,0,...]/#&

```

If the input is a multiple of 10, return 0 (divided by the input).

```
#//....

```

Otherwise, repeatedly apply the following substitution to the input.

```
x_/;!PalindromeQ@x

```

Match a value which is not a palindrome.

```
...:>x+#

```

And replace that value with itself plus the input. This repeated substitution therefore searches through consecutive multiples of the input until it finds a palindrome.

```
.../#

```

Finally, to figure out `b` we simply divide the result by the input again.
> 0 votes

# Answer
# Haskell, ~~67~~ 66 bytes

```
f a|a`mod`10==0=0|1>0=[b|b<-[1..],show(a*b)==reverse(show$a*b)]!!0

```

Returns 0 if `a` is a multiple of 10. Will check from 1 to infinity for `b` if the textual reverse of `a*b` is the same as `a*b`.
> 0 votes

# Answer
## Python 2, 68 bytes

```
x,y=input(),1
if not x%10:x+''
while `x*y`!=`y*x`[::-1]:y+=1
print y

```

Outputs an error if input is a multiple of 10.
> 0 votes

---
Tags: code-golf, math, number, sequence, palindrome
---


title: KeyPad Code to Text!

text:
# Question
Title: KeyPad Code to Text!
Given a String and an Array as input, your task is to output the text the input String will print when typed on a typical Mobile Keypad. In a Mobile Keypad, a letter is typed by pressing a button n times, where n is the position of where the letter is at on the button's label. So, `22` should output `b`.

---

# Rules

* The Helper Array will contain the Character Map (`[" ",".,!","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"]`). This will be given to save you some bytes.
* The `#` symbol will toggle case. Initial Case will be lower. So `2#3` should output `aD`.
* The `0` will add a space. So, `202` should output `a a`.
* There will be a space () in the input String to start a new letter that is on the same numeric button. For Example to type `aa`, the input String will be `2 2`.
* It is guranteed that the input String will always be a valid KeyPad Code.

---

# Input

You can take input in whatever way your language supports.

---

# Output

You can output the result in any way you want. Function `return` is also allowed.

---

# Test Cases

```
#4440555#666888330#999#66688111 -> "I Love You!"
#6#33777 7779990#222#4477744477778627777111 -> "Merry Christmas!"
#44#27 79990#66#3390#999#332777111 -> "Happy New Year!"

```

---

This is , so the shortest code in bytes wins!

# Answer
> 4 votes
# Pyth - 31 bytes

The new key thing cost me too much.

```
ss.emr!FZk@@QsedthdfndeTrb8cz\#

```

Test Suite.

# Answer
> 3 votes
# JavaScript, ~~105~~ 99 bytes

```
f=
(s,a)=>s.replace(/#| ?((.)\2*)/g,(m,n,d)=>d?(l=a[d][n.length-1],x?l:l.toUpperCase()):(x=!x,''),x=1)

a=['  ','.,!','abc','def','ghi','jkl','mno','pqrs','tuv','wxyz']

F=s=>console.log( f(s,a) )
F('#4440555#666888330#999#66688111')
F('#6#33777 7779990#222#4477744477778627777111');
F('#44#27 79990#66#3390#999#332777111');
```
* 6 bytes off thanks @Neil.

# Answer
> 2 votes
# Perl 6,  ~~119~~  97 bytes

map based solution 119 bytes

```
->$_,\a{my$u=0;[~] map {/'#'/??{$u+^=1;|()}()!!(&lc,&uc)[$u](a[.substr(0,1)].substr(.chars-1,1))},.comb(/(\d)$0*|'#'/)}

```

Try it

substitution based solution 97 bytes

```
->$_,\a{my$u=0;S:g/(\d)$0*|./{$0??(&lc,&uc)[$u](a[$0].substr($/.chars-1,1))!!($u+^=$/eq'#')x 0}/}

```

Try it

## Expanded:

```
->     # pointy block lambda

  $_,  # input string
  \a   # helper array

{

  my $u = 0;

  S                        # substitute (implicit against ｢$_｣)
  :global
  /

    | (\d) $0*             # digit followed by same digit
    | .                    # everything else

  /{

    $0                     # is ｢$0｣ set (digit)

    ??                     # if so then
        (&lc,&uc)[$u](     # call either ｢lc｣ or ｢uc｣

          a[$0]            # get the value from the input array
          .substr(         # select the correct character
            $/.chars - 1,
            1
          )

        )

    !!
        (
          $u +^= $/ eq '#' # numeric xor $u if ｢#｣ was matched
        ) x 0              # string repeated zero times (empty string)

  }/
}

```

# Answer
> 2 votes
# JavaScript ES6 - 124 bytes

Golfed:

```
f=h=>a=>(o=c="")+a.match(/#|(.)\1*/g).forEach(e=>e==" "?0:e=="#"?c=!c:(n=h[e[0]][e.length-1])*(o+=c?n.toUpperCase():n))?o:0;

```

```
f=h=>a=>(o=c="")+a.match(/#|(.)\1*/g).forEach(e=>e==" "?0:e=="#"?c=!c:(n=h[e[0]][e.length-1])*(o+=c?n.toUpperCase():n))?o:0;

console.log(f(["  ",".,!","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"])("#4440555#666888330#999#66688111"));
console.log(f(["  ",".,!","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"])("#6#33777 7779990#222#4477744477778627777111"));
console.log(f(["  ",".,!","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"])("#44#27 79990#66#3390999332777111"));
```

Ungolfed:

```
f=(a,h)=>{
    //out string
    o="";
    //uppercase or lowercase (initialized as "" and then inverted in golfed version)
    c=0;
    //split it into array of instructions, which are sets of repeated characters, or # solely alone
    a.match(/#|(.)\1*/g).forEach((e)=>{
        e==" "?0:
            e=="#" ? (c=!c) : ( ()=>{ //lambda added because two statements ungolfed, multiplied in the golfed version
                    n=h[e[0]][e.length-1];
                    o+=c?n.toUpperCase():n;
                })()
    })
    return o;
}

```

# Answer
> 1 votes
# JavaScript, 301 bytes

```
(a,b)=>{u="l";p=[];r="";a.split``.map((c,i)=>p.push(c!=a[i-1]?" "+c:c));p.join``.trim().replace('   ', ' ').split` `.map(l=>{if(l=="#"){u=(u=="l"?b.forEach((y,j)=>b[j]=y.toUpperCase())||"u":b.forEach((y,j)=>b[j]=y.toLowerCase())||"l")}else{if(l!="  "){r+=b[+l[0]][l.length-1]}else{r+=" "}}});return r}

```

```
f=(a,b)=>{u="l";p=[];r="";a.split``.map((c,i)=>p.push(c!=a[i-1]?" "+c:c));p.join``.trim().replace('   ', ' ').split` `.map(l=>{if(l=="#"){u=(u=="l"?b.forEach((y,j)=>b[j]=y.toUpperCase())||"u":b.forEach((y,j)=>b[j]=y.toLowerCase())||"l")}else{if(l!="  "){r+=b[+l[0]][l.length-1]}else{r+=" "}}});return r}

console.log(f("#4440555#666888330#999#66688111 ",["  ",".,!","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"]));
console.log(f("#6#33777 7779990#222#4477744477778627777111",["  ",".,!","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"]));
console.log(f("#44#27 79990#66#3390#999#332777111",["  ",".,!","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"]));
```

I know this is very long, but this is the best I can.

# Answer
> 1 votes
# , 60 bytes

```
Í /|
Í¨ä©¨±*©/½a[submatch(1)][len(submatch(2))]
Í|
ò/#
g~$x

```

(There's an unprintable `½<Ctrl+r>a`)

Try it online!

### Explain

```

Í /|                                          #Replace all " " with "|"
Í¨ä©¨±*©                                      #Replace all (\d)(\1*)
        /½                                    #With =
          ^Ra                                 #(Inserts the passed array)
             [submatch(1)][len(submatch(2))]  #Index into the array
Í|                                            #Replace all "|" with "" (second ò implied)
ò   ò                                         #Recursively (until breaking)
 /#                                           #Go to the next #
g~$                                           #Toggle case until the of the line
   x                                          #Delete current char (#)

```

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


title: Sharing (characters) is Caring!

text:
# Question
Title: Sharing (characters) is Caring!
# Overview

Consider the following task:

> Given a positive integer **n \> 0**, output its integer square root. The integer square root of a number **n** is the largest value of **x** where **x2 ≤ n**, usually expressed with the formula `floor(sqrt(n))`.
>
> Examples: `25 -> 5`, `24 -> 4`, `40 -> 6`, `1 -> 1`.

This task is easy enough on its own. However, in this challenge, your task is to solve this in *as many languages as possible* using a set of only *25 characters.*

# Example

First, you need to pick a *set* (no duplicates) of 25 bytes. It may look something like this (note the leading space):

```
 ()*-.05:=>Mabdhilmnqrst|

```

Your challenge is then to, using only characters in this set, construct a solution to the problem in as many *text based* (sorry, Piet) languages as possible. You can use characters as many times as necessary, but you must not use characters outside the set.

The solutions can be either *full programs* or *functions*, but not snippets. For example, using this set of characters, I could do:

```
M -> (int) Math.sqrt(M)    // Java (lambda expression)
M => Math.sqrt(M)|0        // Javascript (unnamed function)
lambda M: int(M**.5)       // Python (lambda function)

```

As I've used 3 languages, this would give me a score of **3**.

Please also include the set of bytes you are using in your answer.

## Rules

* This is a challenge - your score is the number of languages your submission includes. The highest score wins. Standard loopholes apply.
* For this challenge, a 'language' counts as a distinctly different programming language - multiple versions of the same language (Python 2, Python 3, etc) are banned.
* Programs only need to work for inputs within the language's standard integer range.
* Programs with the exact same source code (polyglots) are not allowed.
* To be more specific, it is a set of *bytes*, not characters - so you can use the 05AB1E `£` and the Jelly `ɱ` as the same character (because they have the same codepoint).

Please don't feel as though you have to beat all other solutions - if you have an interesting answer, post it!

# Answer
# 20 languages

Using `()-#*.05;=>^Vefikloqrst` (24 characters) so far:

```
let f l=floor(l**0.5);;       OCaml
let f l=floor(l**0.5)         F#
f(l)=floor(l^.5)              Julia
f(o)=floor(o^.5)              PARI/GP
s^+>5 0>5 0*.5l               Pyth
(* **.5).floor                Perl 6
floor.(**0.5)                 Haskell
flr.(tt ^.5)                  Wonder
l=>l**.5^0                    JavaScript
l->l**.5^0                    Cheddar
.5^5*5f                       Pyke
(isqrt)                       Maple
ri.5#i                        CJam
isqrt                         Common Lisp
0.5^k                         MATL
*.5^0                         Jelly
*.^0                          M
t0^                           05AB1E
q f                           Japt
r#                            Pushy
V-                            gs2

```
> 37 votes

# Answer
# 10 languages

Character set of 19 characters (in **CP-1252**):

```
,-/12@QUVX^fkmt¬÷␊␍

```

Where  represents a *line feed* and the  represents a *carriage return*.

(Script for checking the characters)

### Jelly, 2 bytes

```
Æ½

```

Try it online!

### 05AB1E, 2 bytes

```
t1X-^

```

Try it online!

### GS2, 2 bytes

```
V-

```

Try it online!

### Jolf, 3 bytes

```
mfU

```

Try it here! (works best on Firefox)

### Japt, 2 bytes

```
¬f

```

Try it here!

### MATL, 3 bytes

```
X^k

```

Try it online!

### Pyke, 3 bytes

```
,1f

```

Try it here!

### Pyth, 6 bytes

```
/@Q2t2

```

Try it here!

### Oasis, 6 bytes

```
1␊2/m1÷

```

Try it online!

### 2sable, 9 bytes

```
t1X-XX--^

```

Try it online!
> 8 votes

# Answer
# 5 languages

Gonna add more languages soon.

### Character set (22 bytes):

```
s^Q.5=>*|0√Lrdmlab :/1

```

### Pyth

```
s^Q.5

```

### Javascript

```
Q=>Q**.5|0

```

### Actually

```
√L

```

### CJam

```
rdmQ

```

### Python

```
lambda Q:Q**.5//1

```
> 6 votes

# Answer
# 5 languages

```
[].,+<>{}()0134879

```

18 characters.

I'm trying not to use any alphabet characters...

**Brainfuck, Brainfuck++, Brainfuck-ng, Braintrust, ...**

```
,[[>++++++[<++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++]>[+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>++++++++++<]>[+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++<+>]<<<[+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>>+<<]],]>>>>>>>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++[<<<<<[+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>+>+<<]>[+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++<+>]<<+[+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++<<+>>>>+<<]>>[+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++<<+>>]<<<<[>>[<+>>>+<<+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++]<[>+<+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++]<+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++]>>>>>>>>+<<<<[>>>+<<[+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>+>[+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++]<<]>>[+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>+<]<[+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++<+>]<+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++<+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++]>[+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++]>>>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++]<<<<<<+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++<++++++++++>[+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++<+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++[<+<<]<[+[+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>+<]<+<<]>>>>>]<<<[<++++++[+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>++++++++<]>.[+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++]]++++++[+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>++++++++<]>.

```

Doesn't work for over `224` because `256` (= (sqrt(225)+1)^2) overflows.

Replaced all `-`s with `+`s to use one less character. (e.g. `-` -\> 255 `+`s)

*Original Program*

```
,[[>++++++[<-------->-]>[->++++++++++<]>[-<+>]<<<[->>+<<]],]>>>>>>>-[<<<<<[->+>+<<]>[-<+>]<<+[-<<+>>>>+<<]>>[-<<+>>]<<<<[>>[<+>>>+<<-]<[>+<-]<-]>>>>>>>>+<<<<[>>>+<<[->+>[-]<<]>>[->+<]<[-<+>]<-<-]>[-]>>>-]<<<<<<-<++++++++++>[-<-[<+<<]<[+[->+<]<+<<]>>>>>]<<<[<++++++[->++++++++<]>.[-]]++++++[->++++++++<]>.

```

**Brain-Flak**

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

```

@WheatWizard's code. Thanks for the permission!

**Brain-Flueue**

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

```

Another @WheatWizard's code.

**Numberwang**

```
[encoded data, 7402 characters]

```

**Spoon**

```
00101100010000100010111111001000110000000000000000000000000100000011010001000000101111111111011001101000100000011101000110110110110010000001001010110110011001100101100011010010010010010010010000001000110110110110110010000001010101011011001101000100000011101000110110111001000000110111010010010010101101100110100100010000001101110100100011011011011011001000100100010001110100100101011011000001101100100010101100000110110000011010010010010010010010010101101101101100100010010010101101100100000010101000100000001101101100110100100010000001010110011011001000000111010001101100001100000110100010000000110100100100000011011011011011011011000011111111111101000100000011000001000111011011001101100100100100000010101100110111011011001101001001001001000110110110110010001111111100100000010111111110110011010001010001000000011001111111100100000010111111110110011010001010

```

Per meta consensus, this code should be okay, even though no interpreters are currently available.
> 6 votes

# Answer
# 5 languages

Using `()*/12 dlinpqrstu` and newline (18 characters) so far.

### Common Lisp

```
isqrt

```

A built-in function.

### QBasic

```
input q
print int(sqr(q))

```

### Python 3

```
print(int(int(input())**(1/2)))

```

Python 3 used for floating-point division without decimal points.

### Pip

```
q**/2//1

```

Unnecessarily golfy to show off the unary inversion operator `/`. Takes input from stdin. Try it online!

### tinylisp

```
(d sqrt (q((n nsqr input) (i (l input nsqr) (s n 1) (sqrt (s n (s 1 2)) (s 2 (s (s (s 1 n) n) nsqr)) input)))))
(q((input)(sqrt 1 1 input)))

```

`sqrt` is a helper function whose arguments are: the current guess `n`, `n` squared, and the `input` number. If `input` is less than `nsqr`, we've gone too far, so return `n` minus 1; otherwise, recurse, adding 1 to `n` and adding `n + n + 1` to `nsqr`. (The math is a bit complicated because tinylisp only has subtraction built in.) The second line defines our actual function, which takes a single `input` and returns the result of `sqrt` with `n` starting at 1.
> 4 votes

# Answer
# 6 languages

Using `retun flosq(agm1)\,i` and extended codepoints `B1` and `BC` for 22 bytes so far.

**GameMaker Language**

```
return floor(sqrt(argument1))

```

**Pyke**

```
,1f

```

**Julia**

```
isqrt

```

**Maple**

```
(isqrt)

```

**Stuck**

```
i\

```

**TI-Basic (hex dump)**

```
B1 BC 72

```

Note that 0x72 is `r` in ASCII.
> 3 votes

# Answer
# 7 languages

`24` chars:

```
limQi->(nt)Mah.sqr_ ?;:\

```

### CJam

```
limQ
li       e#Read Int
  mQ     e#Integer square root

```

### Java

```
i->(int)Math.sqrt(i)

```

### Chaincode

```
q_
q  #sQuare root
 _ #floor

```

### Math++

```
_sqrt ?

```

### Grin

```
;q:

```

### Stuck

```
i\)

```

### Unilinear

```
iMivMiMs
i            Read input
 Mi          Convert to int
    v        Square root
    Mi       Convert to int
      Ms     Convert to String

```

### R

```
sqrt

```

## Costs too much bytes

### Python

```
lambda i:int(i**.5)

```
> 1 votes

---
Tags: code-challenge, number, arithmetic, number-theory, rosetta-stone
---