title: The Woz Monitor

text:
# Question
Title: The Woz Monitor
# Challenge

I've recently gotten into 8-bit computers and are fascinated with the workings of them and others alike; thus the objective of this code golf, is to replicate a portion of the Woz Monitor, designed by Steve Wozniak for the Apple I.

You are to store an array of 22 hexadecimal values with a width of two bytes, (min value **$10**, max value **$FF**), and then take in *n*-amount of inputs. (Normally two; languages like Brainfuck might have a hard time).
The inputs will refer to where in the array to start printing from, and where to stop; an input with *defined behaviour* will have their starting value less or equal to the ending value. Your program must then be capable of printing every hexadecimal value between, **and including**, the hexadecimals inputted.

An example of this:

```
Array
00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 10 11 12 13 14 15

Values
FF F4 B6 D7 40 00 00 A4 F0 00 FF 0D 9C 21 65 C4 02 28 90 E7 D6 A5

```

```
input first num:
04
input second num:
14
40 00 00 A4 F0 00 FF 0D 9C 21 65 C4 02 28 90 E7 D6

```

Now the interesting part of this exercise, is that you can use whatever you want to check the bounds of the users input. Person inputs `hello` and your program has undefined behaviour? It quits without notice? They are both valid.

The only rules are:

**1.** You must include the values of the 22 hexadecimal values as part of your program before it starts, (can't ask the user for inputs).
**2.** The output of the hexadecimal values must follow the exact format: `00 FF 00 FF 00` Trailing spaces, tabs or lines are OK. Characters are not.
**3.** The program ***doesn't*** have to ask for the inputs with a message. Leave the "message" blank if you wish. The user must input the hex-bounds however.
**4.** As with the values of the 22 hexadecimals are up to you to decide, you must make a program that actually fetches the values from storage, opposed to ***mimicking*** a program by simply printing values. (such as a list of **$00**'s).
**5.** *n-amount* of inputs, refers to the amount of inputs required for your language of choice to recognise a hexadecimal of two byte-width. **eg. (Brainfuck will require two inputs per hex, making it four for the two).**

Feel free to comment if you need clarification.

**This is code golf, so the shortest answer in the number of bytes is the winner.**

# Leaderboard

Here is a leaderboard generating snippet courtesy of Martin Ender.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```
# Language Name, N bytes

```

where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:

```
# Ruby, <s>104</s> <s>101</s> 96 bytes

```

```
function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/95080/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function getAnswers(){$.ajax({url:answersUrl(page++),method:"get",dataType:"jsonp",crossDomain:true,success:function(e){answers.push.apply(answers,e.items);if(e.has_more)getAnswers();else process()}})}function shouldHaveHeading(e){var t=false;var n=e.body_markdown.split("\n");try{t|=/^#/.test(e.body_markdown);t|=["-","="].indexOf(n[1][0])>-1;t&=LANGUAGE_REG.test(e.body_markdown)}catch(r){}return t}function shouldHaveScore(e){var t=false;try{t|=SIZE_REG.test(e.body_markdown.split("\n")[0])}catch(n){}return t}function getAuthorName(e){return e.owner.display_name}function process(){answers=answers.filter(shouldHaveScore).filter(shouldHaveHeading);answers.sort(function(e,t){var n=+(e.body_markdown.split("\n")[0].match(SIZE_REG)||[Infinity])[0],r=+(t.body_markdown.split("\n")[0].match(SIZE_REG)||[Infinity])[0];return n-r});var e={};var t=0,c=0,p=-1;answers.forEach(function(n){var r=n.body_markdown.split("\n")[0];var i=$("#answer-template").html();var s=r.match(NUMBER_REG)[0];var o=(r.match(SIZE_REG)||[0])[0];var u=r.match(LANGUAGE_REG)[1];var a=getAuthorName(n);t++;c=p==o?c:t;i=i.replace("{{PLACE}}",c+".").replace("{{NAME}}",a).replace("{{LANGUAGE}}",u).replace("{{SIZE}}",o).replace("{{LINK}}",n.share_link);i=$(i);p=o;$("#answers").append(i);e[u]=e[u]||{lang:u,user:a,size:o,link:n.share_link}});var n=[];for(var r in e)if(e.hasOwnProperty(r))n.push(e[r]);n.sort(function(e,t){if(e.lang>t.lang)return 1;if(e.lang<t.lang)return-1;return 0});for(var i=0;i<n.length;++i){var s=$("#language-template").html();var r=n[i];s=s.replace("{{LANGUAGE}}",r.lang).replace("{{NAME}}",r.user).replace("{{SIZE}}",r.size).replace("{{LINK}}",r.link);s=$(s);$("#languages").append(s)}}var QUESTION_ID=49042;var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";var answers=[],page=1;getAnswers();var SIZE_REG=/\d+(?=[^\d&]*(?:<(?:s>[^&]*<\/s>|[^&]+>)[^\d&]*)*$)/;var NUMBER_REG=/\d+/;var LANGUAGE_REG=/^#*\s*([^,]+)/
```

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

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

# Answer
> 3 votes
# Jelly, ~~24~~ 21 bytes

```
w@€ØHḅ⁴
ɠÇµɠÇr@b⁴ịØHK

```

Chosen values: `[00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 1F 10 11 12 13 14 15]`

**TryItOnline**

If the second input is less than the first it outputs the reversed sequence.
Out of bounds behaviour is undefined (e.g. "foo", "14" returns 38 values, most of which are not even in the array and many of which are not length 2)

How?

```
w@€ØHḅ⁴ - Link 1, parse a string as a 1-based hex value e.g. "14"
w@€      - first index (1-based) of each character in
   ØH    - hex digits: "0123456789ABCDEF"                   [2,5]
     ḅ⁴ - convert from base 16                                 37

ɠÇµɠÇr@b⁴ịØHK - Main link
ɠ  ɠ          - read a line from stdin               e.g. "04"  "14"
 Ç  Ç         - call the last link (1) as a monad          21    37
  µ           - monadic chain separation
     r@       - inclusive range, with reversed arguments  [   21,   22,...,   36,   37]
       b⁴     - convert to base 16                        [[1,5],[1,6],...,[2,4],[2,5]]
         ị    - index into
          ØH  - hex digits: "0123456789ABCDEF"            [ "04", "05",..., "13", "14"]
            K - join with spaces

```

# Answer
> 3 votes
## JavaScript (ES6), ~~118~~ ~~115~~ ~~112~~ ~~102~~ ~~82~~ 81 bytes

*Saved 1 byte thanks to ETHproductions*

Chosen values:

```
00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 11 12 13 14 15
-----------------------------------------------------------------
10 10 11 14 10 10 15 15 11 14 10 10 15 15 11 14 10 10 15 15 10 11

```
* Prompts for the lower bound, then for the upper bound (e.g. `0x04` / `0x0f`).
* An invalid lower bound will be interpreted as `0x00` (minimum value).
* An invalid upper bound will be interpreted as `0x15` (maximum value).
* Outputs nothing if the lower bound is greater than the upper bound.

```
alert((1/7+'789').replace(/./g,(v,i)=>i<a|i>b?'':(v|10)+' ',p=prompt,b=p(a=p())))
```

### Previous version (97 bytes)

Generating a pseudo-random list of 'true' hexadecimal values:

```
alert((1/7+'789').replace(/./g,(v,i)=>i<a|i>b?'':(v*7|16).toString(16)+' ',p=prompt,a=p(),b=p()))

```

Sequence:

```
10 10 17 1c 1e 38 33 31 17 1c 1e 38 33 31 17 1c 1e 38 33 31 38 3f

```

# Answer
> 2 votes
# JavaScript (ES6), ~~107 152~~ 137 bytes

```
p=prompt,f=(a=+p(),b=+p(),[x,y,...s]='FFF4B6D7402011A4F0D0FF3D9C2165C4A22890E7D6A5')=>a?f(a-1,b-1,s):x+y+' '+(b?f(a,b-1,s):'');alert(f())

```

```
var
   p=prompt,f=(a=+p(),b=+p(),[x,y,...s]='FFF4B6D7402011A4F0D0FF3D9C2165C4A22890E7D6A5')=>a?f(a-1,b-1,s):x+y+' '+(b?f(a,b-1,s):'');alert(f())
;

//input 0x04 then 0x14 will print 40 to D6
//input 0x00 then 0x00 will print FF
//input 0x13 then 0x17 will print E7 D6 A5 NaN NaN
```

Chosen values:

```
FF F4 B6 D7 40 20 11 A4 F0 D0 FF 3D 9C 21 65 C4 A2 28 90 E7 D6 A5

```

Inputs:

* Input format is `0x14`
* If any input is negative or the 1st input is greater than the 2nd : `InternalError: too much recursion`
* Will print `NaN` for out of bounds.

---

Previous solutions:
152 bytes:

```
i=parseInt,p=prompt,f=(a=i(p()),b=i(p()),[x,y,...s]='FFF4B6D7402011A4F0D0FF3D9C2165C4A22890E7D6A5')=>a?f(a-1,b-1,s):x+y+' '+(b?f(a,b-1,s):'');alert(f())

```

107 bytes, invalid solution (inputs missing):

```
f=(a,b,[x,y,...s]='FFF4B6D7402011A4F0D0FF3D9C2165C4A22890E7D6A5')=>a?f(a-1,b-1,s):x+y+' '+(b?f(a,b-1,s):'')

```

# Answer
> 2 votes
# Python, ~~88~~ ~~87~~ 86 bytes

1 byte save thanks to @JonathanAllan
1 byte save *again* to @JonathanAllan

Also changed the base of the code, much nicer now.

```
a,b=[int(x,16)for x in raw_input().split()];l=[0]*22
while a<=b:print"%02x"%l[a],;a+=1

```

Chosen values: `00` for everything.

Same idea as my C answer. This time however, the code takes a single input from the user, requiring a space between both values, split them, cast them to hex values, and print every hex in the `l` array including and between the two inputted values. Since Python has a magnificent error-catching system, no buffer overflows are present and the code is therefore much more secure. The program is safe from *undefined behaviour* in a sense that it will not execute when a higher value is submitted before a lower value.

This should work on both Python 2.x and 3.x; Please correct me if I am wrong, as I don't have access to both interpreters due to my system not supporting both of them.

# Answer
> 1 votes
# C, ~~176~~ ~~175~~ 161 bytes

1 byte save thanks to @JonathanAllan
Massive help thanks to @Downvoter for saving me **14** bytes!

```
int main(){int a[44]={0};char s[2];scanf("%s",s);int b=(int)strtol(s,0,16);scanf("%s",s);int c=(int)strtol(s,0,16);while(b<=c){printf("%d%d ",a[b],a[b+1]);b++;}}

```

**Try it online!**

Chosen values: `00` for everything.

Un-golfed answer:

```
int main() {
    int a[44] = {0};
    char s[2];
    scanf("%s", s);
    int b = (int) strtol(s, 0, 16);
    scanf("%s", s);
    int c = (int) strtol(s, 0, 16);
    while (b <= c) {
        printf("%d%d ", a[b], a[b+1]);
        b++;
    }
}

```

The trick to this, is taking in two inputs and attempting to convert them to hexadecimal strings and then cast to integers. Since there is no error-checking or anything likewise, *undefined behaviour* is simply throwing errors and breaking the program. The user needs to enter two inputs, however my Eclipse CDT compiler seems to let me input them both on the same line with a space between.

They must be in the correct order, as requesting a bigger value before a smaller value will not run the `while`-loop at all.

The thing is, there is also no buffer-overflow protection, so I can simply request something absurd such as a range from $0 to $FFFF, and I will get everything in my computers memory from the beginning of the allocation of memory for the `a[44]` array, all the way to 65536 values later.

# Answer
> 1 votes
# PHP, ~~106 105 104~~ 96+2 bytes

```
eval($s='for($a=a;$a++<c;)$$a=hexdec($argv[++$i]);while($b<=$c)printf("%02X ",ord($s[$b++]));');

```

or

```
eval($s='for($a=a;$a++<c;)$$a=hexdec($argv[++$i]);');while($b<=$c)printf("%02X ",ord($s[$b++]));

```

Run with `php -nr '<code>' <lowindex> <highindex>`; escape the single quotes in the code.
... or test it online.

`dechex` interpretes input as hexadecimal strings as far as characters are hex digits,
`0` if the input starts with something else.

prints nothing if first value is larger than second.

chosen values:

```
00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 11 12 13 14 15
-----------------------------------------------------------------
66 6F 72 28 24 61 3D 61 3B 24 61 2B 2B 3C 63 3B 29 24 24 61 3D 68

```

(first 22 ascii codes of the executed code)

or

```
for($a=a;$a++<c;)eval($s='$$a=hexdec($argv[++$i]);');while($b<=$c)printf("%02X ",ord($s[$b++]));

```

with these values:

```
00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 11 12 13 14 15
-----------------------------------------------------------------
24 24 61 3D 68 65 78 64 65 63 28 24 61 72 67 76 5B 2B 2B 24 69 5D

```

# Answer
> 1 votes
# Perl, 79 45 41 bytes

"min value $10" - the example has minimum of $00- is that a typo?

Here's a rather boring perl answer in 41 bytes (Was 46 and then I kept seeing spaces, parens I could elide). Takes input in two lines.

```
printf'%02X ',$_ for(4..26)[hex<>..hex<>]

```

The data is a list 04..1A

Before I was being too clever with pack & unpack. Its input bytes are entered at once smushed together, eg "020E' will print the 2nd-14th entries

```
printf'%02X ',$_ for sub{(4..26)[shift..shift]}->(unpack'CC',pack'H4',<>)

```

Might try golfing it more using all 0's, `substr`, and `printf'%*vX'` ... nope that is making my answer longer. 48 characters (using a string of ascii '7', hex 37 as the data)

```
printf'%*vX',' ',substr 7x22,$s=hex<>,1+hex<>-$s

```

# Answer
> 1 votes
# Scala, 45 bytes

```
(_:Int)to(_:Int)map(x=>f"$x%02X")mkString " "

```

Ungolfed:

```
(a:Int,b:Int)=>a.to(b).map(x=>f"$x%02X").mkString(" ")

```

Uses `00` to `FF` as values, but works up to 2147483647.

# Answer
> 1 votes
# C++, ~~98~~ ~~95~~ 93 bytes

```
#include <iostream>
int _[22],a,b;int main(){for(std::cin>>a>>b;b/a++;)printf("%02x ",_[a]);}

```

My chosen values are all 0's

# Answer
> 0 votes
# CJam, 22 bytes

```
{r:~Gb}2*37m!s2/\)<>S*

```

Chosen values:

```
00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 10 11 12 13 14 15
-----------------------------------------------------------------
13 76 37 53 09 12 26 34 50 46 31 59 79 58 15 80 90 24 00 00 00 00

```

Try it online

# Answer
> 0 votes
# GNU sed, 209 + 1(r flag) = 210 bytes

```
1{h
s:.*:,00 FF,01 F4,02 B6,03 D7,04 40,05 00,06 00,07 A4,08 F0,09 00,0A FF,0B 0D,0C 9C,0D 21,0E 65,0F C4,10 02,11 28,12 90,13 E7,14 D6,15 A5:
H;d}
G;s:\n(.*)\n.*(,\1.*):\n\2:
s:(.*)\n(.*,\1 ..).*:\2:
s:,..::g

```

**Try it online!** One leading space is present in the output, I hope it's allowed.

**Run examples:**

```
me@LCARS:/PPCG$ echo -e "06\n0F" | sed -rf table_lookup.sed
 00 A4 F0 00 FF 0D 9C 21 65 C4
me@LCARS:/PPCG$ echo -e "13\n13" | sed -rf table_lookup.sed
 E7

```

**Explanation:** the 22 hexadecimal values stored are the same as the ones from the OP's example

```
value | FF F4 B6 D7 40 00 00 A4 F0 00 FF 0D 9C 21 65 C4 02 28 90 E7 D6 A5
-------------------------------------------------------------------------
index | 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 10 11 12 13 14 15

```

The start and end indexes are read on separate lines. The output is a single line with the table values in that index range (inclusive). *Undefined input will write multiple lines of invalid output.*

```
# store START index in hold space
1{h
# generate the table
s:.*:,INDEX1 VALUE1,INDEX2 VALUE2,°°°:
# append table to hold space and delete pattern space
H;d}
# read END index, append hold space (pattern space format is: END\nSTART\nTABLE)
G
# delete table entries up to, but excluding, the START index (END\nTABLE')
s:\n(.*)\n.*(,\1.*):\n\2:
# delete table entries starting from, but excluding, the END index (TABLE'')
s:(.*)\n(.*,\1 ..).*:\2:
# remove the indexes and print (implicitly) the resulting values
s:,..::g

```

# Answer
> 0 votes
## Apple II 6502 assembly, 75 bytes

Byte code:

```
A9 46 85 36 A9 10 85 37 A0 00 98 20 DA FD A9 A0
20 ED FD C0 42 D0 F3 20 93 FE A2 FC 20 1B FD 9D
04 01 E8 D0 F7 86 31 A9 8D 8D 04 02 20 A7 FF B5
3C 0A 75 3C 95 3C CA 10 F6 A6 3D BD 05 02 20 ED
FD E8 E4 3C D0 F5 99 05 02 C8 60
```

Disassembly:

```
  LDA    #<+
  STA    CSWL
  LDA    #>+
  STA    CSWH    ;redirect stdout
  LDY    #$00
- TYA
  JSR    PRBYTE  ;print number
  LDA    #$A0    ;space
  JSR    COUT    ;print space
  CPY    #$42    ;22*3
  BNE    -
  JSR    SETVID  ;restore stdout
  LDX    #$FC
- JSR    KEYIN   ;fetch a key
  STA    $0104,X ;store to $200+
  INX
  BNE    -       ;four keys
  STX    MODE    ;set internal flags
  LDA    #$8D
  STA    $0204   ;set key delimiter
  JSR    GETNUM  ;convert keys to hex values
- LDA    A1L,X   ;fetch value
  ASL
  ADC    A1L,X   ;multiply by 3
  STA    A1L,X   ;store value
  DEX
  BPL    -       ;both inputs
  LDX    A1H     ;first input
- LDA    $0205,X ;fetch from index
  JSR    COUT    ;print character
  INX
  CPX    A1L
  BNE    -       ;until second input
+ STA    $0205,Y ;fall through to save a byte
  INY
  RTS
```

It forms an array in memory that looks like the output. The chosen values are:

```
00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 11 12 13 14 15
-----------------------------------------------------------------
00 03 06 09 0C 0F 12 15 18 1B 1E 21 24 27 2A 2D 30 33 36 39 3C 3F
```

User presses four keys to set the inputs.

---
Tags: code-golf, array, hexadecimal
---


title: Wanna be an Alchemist

text:
# Question
Title: Wanna be an Alchemist
## Wanna be an Alchemist

I've been watching Full Metal Alchemist these past days and I've been wondering, It is really possible to trans-mutate matter? In the real world, I don't know if it is possible, but in the machine world, we think we "can".

---

**Problem**

Your task is, Given an input of N chemical elements (K, Mg, C, O, etc...), you are going to:

1. Get the first letter of the element
2. Convert that letter into binary
3. Rotate 2 bits to the right
4. Apply Binary Addition
5. If the result is more that 8 bits then get the one's complement of the result and removes the highest bit
6. Output the ASCII (ISO 8859-1) representation of the result

---

**Example**

Given Chemical Elements: `(K, Ca, Mg)`

1. Get the first letter of the element

`K, C, M`

2. Convert that letter into binary

`K => 01001011, C => 01000011, M => 01001101`

3. Rotate 2 bits to the right

`K => 11010010, C => 11010000, M => 01010011`

4. Sum bits

`K => 11010010` \+ `C => 11010000` \+ `M => 01010011` = `111110101`
5. If the result is more that 8 bits then get the one's complement and removes the highest bit

`00001010`

6. Output the ASCII representation of the result. `Result:`

---

**Test Cases**

```
(H, Mn, C) =>  Ê

(I, H, Se) =>  Ç

(K, Ca, Mg) =>

```

---

This is code golf so the shortest answer wins

# Answer
# Perl 5, 44 bytes

```
$n+=257*ord>>2&255}{$_=chr($n>>8?~$n%256:$n)

```

Try it online!
> 1 votes

# Answer
# Python 2, 78 bytes

```
e=sum(ord(e[0])/4+ord(e[0])%4*64for e in input());print chr([e,~e][e>255]%256)

```

Try it online!

-8 bytes thanks to Jonathan Frech
> 2 votes

---
Tags: code-golf, binary, bitwise
---


title: Be as evil as possible

text:
# Question
Title: Be as evil as possible
## Introduction

This is a follow-up of this challenge where you're taking the role of that person's evil twin. Being evil you don't want to maximize your share, but rather be as unfair as possible and you're not going to make it too obvious, that's why you came up with the following scheme:

You're going to tell the others that you want to be as fair as possible like your sibling and thus you're going to split the integer into pieces of equal length. So for each integer you will come up with the right amount of people such that the difference between the largest and the smallest piece is maximal.

For example if you're given the integer `6567` you could leave it as is, split it into two pieces `65,67` or four `6,5,6,7`. This gives you the following maximal differences:

```
6567    -> max() = 0
65,67   -> max(|65-67|) = 2
6,5,6,7 -> max(|6-5|,|6-5|,|6-6|,|6-7|,|5-6|,|5-7|,|6-7|) = 2

```

Since you only want to be evil you don't prefer `67` over `7` and thus you will output either `2` or `4`.

---

Another (less special case); given the integer `121131` you could split it like this:

```
121131      -> max() = 0
121,131     -> max(|121-131|) = 10
12,11,31    -> max(|12-11|,|12-31|,|11-31|) = 20
1,2,1,1,3,1 -> max(…) = 2

```

This time there's only one solution - namely `3` \- since with three people the difference is maximal.

## Challenge

Given an integer determine *any* possible way of being maximally evil and report the **number of people** needed to achieve this.

## Rules

* Input will always be ≥ 1
* Input can be either an integer, list of digits or string
* You don't have to handle invalid inputs

## Testcases

You only need to report the resulting number of people needed, the possible partitions are only for illustration:

```
In -> splits (difference) -> Out
1 -> [1] (0) -> 1
10 -> [1,0] (1) -> 2
11 -> [11] or [1,1] (0) -> 1 or 2
12 -> [1,2] (1) -> 2
42 -> [4,2] (2) -> 2
101 -> [1,0,1] (1) -> 3
2222 -> [2222] or [22,22] or [2,2,2,2] (0) -> 1 or 2 or 4
6567 -> [65,67] or [6,5,6,7] (2) -> 2 or 4
123000 -> [123,000] (123) -> 2
123001 -> [123,001] (122) -> 2
121131 -> [12,11,31] (20) -> 3
294884 -> [294,884] (590) -> 2
192884729 -> [192,884,729] (692) -> 3
123456189012 -> [123456,189012] (65556) -> 2
123457117346 -> [1234,5711,7346] (6112) -> 3

```

# Answer
# Jelly,  ~~16~~  14 bytes

```
Ṁ_Ṃ
sLÆD$ḌÇÞṪL

```

A monadic link taking a list of integers (the digits) and returning an integer.

**Try it online!** or see a test-suite

### How?

```
Ṁ_Ṃ - Link 1, maximal difference: list of numbers
Ṁ   - maximum
  Ṃ - minimum
 _  - subtract

sLÆD$ḌÇÞṪL - Main link: list of numbers, theDigits  e.g. [1,2,3,0,0,1]
    $      - last two links as a monad:
 L         -   length                                    6
  ÆD       -   divisors                                  [1,2,3,6]
s          - split into chunks (vectorises)              [[[1],[2],[3],[0],[0],[1]],[[1,2],[3,0],[0,1]],[[1,2,3],[0,0,1]],[[1,2,3,0,0,1]]]
     Ḍ     - from decimal (vectorises)                   [[1,2,3,0,0,1],[12,30,1],[123,1],[123001]]
       Þ   - sort by:
      Ç    -   call last link (1) as a monad              3             29        122     0
           -                                         ... [[123001],[1,2,3,0,0,1],[12,30,1],[123,1]]
        Ṫ  - tail                                        [123,1]
         L - length                                      2

```
> 5 votes

# Answer
# Pyth, 20 bytes

```
leoeSaM^N2vcRQ*M{yPl

```

**Try it here!**

I no longer use partitions, because it turns out to be longer!!! I ended up splitting into sublists of length equal to the divisors of the length.
> 4 votes

# Answer
# 05AB1E, 12 bytes

```
gDÑΣôDδαà}θ÷

```

Try it online!

### 05AB1E, 12 bytes

```
gDÑΣôàsß-}θ÷

```

Try it online!

### How it works

```
gDÑΣôDδαà}θ÷ | Full program.

g            | Length (count of digits).
 D           | Duplicate (push two copies of the length to the stack).
  Ñ          | Get the divisors (of the top of the stack).
   Σ     }   | Sort by a key function.
--------------------------------------------------------------
    ôDδαà    | Key function #1.
    ô          | Split (the input) into chunks of that size.
     D         | Duplicate.
      δα       | Outer product of absolute difference.
        à      | Get the maximum.
    ôàsß-    | Key function #2 (alternative).
    ô          | Split (the input) into chunks of that size.
     à         | Maximum.
      s        | Swap top two elements.
       ß       | Minimum.
        -      | Subtract.
--------------------------------------------------------------
          θ÷ | Divide the length by the maximum element using the custom sorting.

```

05AB1E is just incredibly terse for this challenge.
> 4 votes

# Answer
# JavaScript (ES6), ~~118~~ 115 bytes

*Saved 3 bytes thanks to @edc65*

Takes input as a string.

```
f=(s,k=l=s.length,m)=>k?f(s,k-1,l%k||(d=Math.max(...a=s.match(eval(`/.{${l/k}}/g`)))-Math.min(...a))<m?m:(r=k,d)):r

```

### Test cases

```
f=(s,k=l=s.length,m)=>k?f(s,k-1,l%k||(d=Math.max(...a=s.match(eval(`/.{${l/k}}/g`)))-Math.min(...a))<m?m:(r=k,d)):r

console.log(f('1')) // [1] (0) -> 1
console.log(f('10')) // [1,0] (1) -> 2
console.log(f('11')) // [11] or [1,1] (0) -> 1 or 2
console.log(f('12')) // [1,2] (1) -> 2
console.log(f('42')) // [4,2] (2) -> 2
console.log(f('101')) // [1,0,1] (1) -> 3
console.log(f('2222')) // [2222] or [22,22] or [2,2,2,2] (0) -> 1 or 2 or 4
console.log(f('6567')) // [65,67] or [6,5,6,7] (2) -> 2 or 4
console.log(f('123000')) // [123,0] (123) -> 2
console.log(f('123001')) // [123,1] (122) -> 2
console.log(f('121131')) // [12,11,31] (20) -> 3
console.log(f('294884')) // [294,884] (590) -> 2
console.log(f('192884729')) // [192,884,729] (692) -> 3
console.log(f('123456189012')) // [123456,189012] (65556) -> 2
console.log(f('123457117346')) // [1234,5711,7346] (6112) -> 3
```
> 4 votes

# Answer
# Python 2, ~~138~~ 132 bytes

```
n=input()
l=len(n)
print len(max([[int(n[l/i*j:][:l/i])for j in range(i)]for i in range(1,l+1)if l%i<1],key=lambda a:max(a)-min(a)))

```

Try it online!
> 1 votes

# Answer
# Haskell, 114 bytes

```
f n|l<-length n=snd$maximum[(a-b,div l i)|i<-[1..l],mod l i<1,a<-i%n,b<-i%n]
i%[]=[]
i%n=read(take i n):i%drop i n

```

Try it online!
> 1 votes

# Answer
# Perl 5, 70 bytes

```
s%.%/A/g;/$/,map$;[$-=$`-$_]=@1,@1for@1=(/.{@{+}}/gc)x!/./g%eg;$_=pop@

```

Try it online!
> 1 votes

# Answer
# Jelly, 20 bytes

```
ŒṖL€E$ÐfḌạþ`ẎṀ$$ÐṀḢL

```

Try it online!
> 0 votes

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


title: Print a quine that contains the input

text:
# Question
Title: Print a quine that contains the input
# Task

You will be given a string in the input consisting only of the characters from `a` to `z`, i.e. the input will match the regex `/^[a-z]*$/`.

Your output should be a complete program in the same language, whose source code contains the input, and is a proper quine.

# Example

Your program would receive the input `abc` and output:

```
...abc...

```

The above should be a complete program in the same language which takes no input and outputs:

```
...abc...

```

i.e. it outputs itself.

# Scoring

This is . Shortest answer in bytes wins.

# References

# Answer
> 7 votes
# Python 3, ~~57~~ 61 bytes

```
lambda x:"s='s=%r;print(s%%s)';print(s%s)".replace('s',x+'x')

```

Takes a basic python 3 quine from here and replaces the variable name with the input.

~~**Note:** As pointed out by Hyper Neutrino in comments, this does not work for reserved keywords like `for`, `if`, etc.~~

Appending a character that none of the reserved keywords ends with such as `'x'` or any number fixes this. (Ørjan Johansen).

# Answer
> 6 votes
# Jelly, 9 bytes

## Generator

```
;“¶Øv”ṾØv

```

Try it online!

### How it works

```
;“¶Øv”ṾØv  Main link. Argument: s (string of letters)

;“¶Øv”     Concatenate s and the string "\nØv".
      Ṿ    Uneval; get its string representation.
           (implicit) Print the previous return value since the next link is an
           otherwise unparsable nilad.
       Øv  Set the return value to "Ṙv".

```

## Quine

If the input is `quine`, the following program is generated.

```
“quine
Øv”Ṙv

```

Try it online!

### How it works

This is the standard Jelly quine. First,

```
“quine
Øv”

```

sets the left argument and the return value to the string `"quine\nØv"`.

Then,  prints a string representation (the code from the previous block) and returns the unaltered string.

Afterwards, `v` takes the left argument and passes it as input to the Jelly program

```
quine
Øv

```

In all Jelly programs, only the *main link* (defined on the last line) is executed, so the first line is ignored entirely.

Finally, `Øv` sets the return value to `"Ṙv"`, which is printed implicitly when the outer program finishes.

# Answer
> 4 votes
# Haskell, 51 bytes

`q` takes a string and returns a string.

```
q s|t<-"main=putStr$fst`mappend`show$"=t++show(t,s)

```

Try it online!

Example output for `putStr$q"test"`:

```
main=putStr$fst`mappend`show$("main=putStr$fst`mappend`show$","test")

```

Try it online!

* Puts the main quine text and the desired string in a tuple.
* Uses `fst` to extract the main text.
* Uses `show` to turn the whole tuple into a string.
* Uses `mappend` to combine the two previous functions. Conveniently `mappend` on two functions gives a function that applies each function to its argument and combines the results with `mappend` for the result type (here string concatenation).

# Answer
> 4 votes
# Underload, 14 bytes

```
(~aSaS(:^)S):^

```

Try it online!

Use as `(test)(~aSaS(:^)S):^` – which is itself a quine.

# How it works

* Underload is a concatenative (stack-based) esoteric language. It doesn't support reading input, so any arguments are put on the stack initially.
* `(test)` and `(~aSaS(:^)S)` are string literals, so place themselves on the stack, with the latter on top.
* `:` duplicates the `(~aSaS(:^)S)` string on top of the stack, then `^` runs its contents as a subprogram.
* `~` swaps the top two elements on the stack, so now `(test)` is uppermost.
* `a` wraps `(test)` in extra parentheses.
* `S` takes the string `((test))` on top of the stack, and prints it without the outer parentheses (which are just literal syntax).
* Now `aS` prints the remaining `(~aSaS(:^)S)` on the stack similarly (with the parentheses).
* At last, `(:^)S` prints the final `:^`.

# Answer
> 4 votes
# Underload, 14 bytes

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

```

Try it online!

A different approach from the other Underload answer; rather than itself being a quine, this constructs a quine. Interestingly, it comes out to the same number of bytes. This is a function that takes its argument from the stack and outputs to standard output.

## Explanation

```
a(aS(:^)S)~*:^
a               Generate a string literal containing the input
 (aS(:^)S)~*    Prepend "aS(:^)S"
            :^  Mockingbird: run the resulting function with itself as argument

```

The resulting function looks like this:

```
aS(:^)S(input)
aS              Print a string literal containing the argument
  (:^)S         Print ":^"
       (input)  Push "input" onto the stack

```

In other words, it prints a string literal containing itself, followed by `:^`. This is clearly a quine (because what was just printed is the same as the code we executed to run it in the first place).

# Answer
> 3 votes
# Python 2, 38 bytes

Though input is only required to support `a-z`, this should work with any single-line input that doesn't contain NUL bytes.

```
s='s=%r;print s%%s#'+input();print s%s

```

**Try it online**

For input `abc` the resulting quine is:

```
s='s=%r;print s%%s#abc';print s%s#abc

```

**Try it online**

# Answer
> 2 votes
# , 9 bytes

```
ñ"qPxÉÑ~j

```

Try it online!

This is a modification of the standard V quine, and I'm proud that this is only one byte longer.

Hexdump:

```
00000000: f122 7150 78c9 d17e 6a                   ."qPx..~j

```

Explanation:

```
ñ           " Record the following commands into register 'q'
 "qP        " Paste register 'q' before all input
    x       " Delete the last character of what we just pasted (this will be a 'ÿ')
     ÉÑ     " Insert 'Ñ' at the beginning of this line
       ~    " Toggle the case of this character
        j   " Move down a line. During playback, this will cancel playback of the current macro,
            " So everything after here is a NOOP

```

Then, the recording implicitly stops and is played back. This will generate the following output:

```
ñ"qPxÉÑ~jHello

```

Since `j` will break playback of the macro, nothing in `Hello` will ever get run.

# Answer
> 1 votes
# RProgN 2, 15 bytes

```
"{']C'.%q[}]C"F

```

## Explained

Using the format

```
{']C'.%q[}]C}

```

where `%q` is the qouted input, builds a quine of the flavour

```
{']C'."Some Text"[}]C

```

which is a standard RProgN2 quine, `{']C'.}]C` That, before finished, appends and destroys the inputted string.

Try it online!

# Answer
> 1 votes
## Retina, 14 bytes

Byte count assumes ISO 8859-1 encoding.

```
\(\`^
¶\(*S1`|

```

Try it online!

For input `x`, this outputs:

```

\(*S1`|x
\(*S1`|x

```

### Explanation

The output is a minor modification of the standard quine. We simply use the regex `|x` instead of the empty regex. Since the `|` still allows (and prioritises) and empty match, the functionality itself is not affected, and since `x` will only ever contain letters, it's guaranteed to be valid regex syntax itself.

Printing this actually uses a technique which is similar to the quine itself. To avoid the duplication of the quine, we insert `¶\(*S1`|` only once into the beginning of the string. That's exactly half the source code. To print it twice without a linefeed, we use the configuration `\(\`, which wraps the entire program in a group and makes both the stage itself as well as the group containing it print the result without a linefeed.

# Answer
> 1 votes
## Japt, 14 bytes

```
"\"iQ ²ª`"+U ²

```

Test it online! For an input of `abc`, outputs

```
"iQ ²ª`abc"iQ ²ª`abc

```

which outputs itself. Test it online!

### Explanation

This is an extension of the standard payload-capable Japt quine:

```
"iQ ²"iQ ²

"iQ ²"      // Take this string.  iQ ²
      iQ    // Insert a quote.    "iQ ²
         ²  // Repeat this twice. "iQ ²"iQ ²
            // Implicit: output result of last expression

```

The only difference is that we append `ª`abc` at the end, which in JavaScript is basically `||"abc"`. Since the result of the first part is always a non-empty string (truthy), the `||` never gets run.

There are several alternative versions of the same length:

```
"iQ ²ª`abc"iQ ²ª`abc   quine||"abc"
"iQ ²ª$abc"iQ ²ª$abc   quine||abc
"iQ ²ª{abc"iQ ²ª{abc   quine||function(){ ... }
"iQ ²ªXabc"iQ ²ªXabc   quine||X.a(...) (X could be any uppercase letter or digit)
"iQ ²//abc"iQ ²//abc   quine//abc      (// is a comment in JS/Japt)
"iQ ²;[abc"iQ ²;[abc   quine;          (unmatched [ causes a parsing error)

```

# Answer
> 0 votes
# CJam, ~~16~~ 14 bytes

```
"`_~"q`';++`_~

```

Try it online!

**How it works**

```
"`_~"           e# Push "`_~"
     q`         e# Push a string representation of the input (input wrapped in quotes)
       ';       e# Push a semicolon
         ++     e# Concatenate all this together
           `    e# Get the string representation of the resulting string
            _~  e# Duplicate it and eval it (pushing the original string on the stack again)

```

Which outputs something like `"`_~\"test\";"`_~"test";`.

# Answer
> 0 votes
# JavaScript, 21 bytes

```
$=_=>`$=${$}/*${_}*/`

```

# Answer
> 0 votes
## Perl 5, 35 bytes

```
$_=q{say"\$_=q{$_};eval"#}.<>;eval

```

Try it online!

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


title: Cross-Alphabetic Characters

text:
# Question
Title: Cross-Alphabetic Characters
## Background

I saw this very interesting Venn Diagram on wikipedia: https://simple.wikipedia.org/wiki/Alphabet#/media/File:Venn\_diagram\_gr\_la\_ru.svg

It shows the letters (physical shapes) in different alphabets that are common between Russian, Greek and Latin alphabets.

## The Challenge

Given an input string of characters from any of the three scripts shown (i.e capitalised Greek, Cyrillic or Latin letters), output a percentage of the string that matches each language. Repeated letters count every time.

For example, `FFLURS` is all latin-only characters, so the output is `FFLURS is 100% Latin, 0% Cyrillic and 0% Greek`.

By contrast, `TOX BEAM PHP` is formed completely of characters that appear in all three languages, so the output is `TOX BEAM PHP is 100% Cyrillic, 100% Greek and 100% Latin`.

# Lookup Tables

The Venn diagram is the source of the letters below:

**Latin Only:**

```
J,G,S,D,Q,U,V,W,F,L,R

```

**Latin and Cyrillic:**

```
C, С

```

**Latin and Greek:**

```
I,Ι, N,Ν, Z,Ζ

```

**Greek and Cyrillic**

```
Φ,Ф, Π,П, Γ,Г, Λ,Л

```

**All three:**

```
A,B,E,O,M,K,T,X,Y,H,P (and equivalents in greek and cyrillic), (space)

```

**The rest** ...are Greek-only or Cyrillic-only.

**IMPORTANT NOTE**

Unicode defines (for example) "A" in (at least) three separate ways - one for each language. **Whichever is used in the input (&#0391, &#0410 or &#0041), the program should understand it as matching all three languages.** So, `A` (Latin), `Α` (Greek Alpha) and `А` (Cyrillic) should all give `100% Cyrillic, 100% Greek and 100% Latin` as the answer.

## Input Format

Any string containing exclusively `А-Я`, `Α-Ω`, `A-Z` and  (space). These characters can be repeated multiple times within the string.

## Output Format

The output can be in any format, provided the function produces consistent results. I would *like* to see output in the format I show in my examples (`FFLURS is 100% Latin, 0% Cyrillic and 0% Greek`), but in order to make the challenge more open to anyone I'm happy to accept arrays/strings of percentages/ratios:

`[100,0,0]`,

`100 0 0`

`[1.0 0.0 0.0]`

as long as it's always clear which number is which language - so the output should be consistent.

## Some more test cases

`CINEMATICS` -\> `CINEMATICS is 100% Latin, 70% Greek and 60% Cyrillic`

`ЩJЩFЩLΞRΞVΞW` -\> `ЩJЩFЩLΞRΞVΞW is 50% Latin, 25% Cyrillic and 25% Greek`

-\>  `is 100% Cyrillic, 100% Greek and 100% Latin`

`ΨΩTESTINGЯЮ` -\> `ΨΩTESTINGЯЮ is 63.6% Greek, 63.6% Latin and 45.5% Cyrillic`

## Winning Criteria

Usual rules and exclusions apply; shortest answer (bytes) wins.

(sandbox link: https://codegolf.meta.stackexchange.com/a/14984/62289)

For the avoidance of doubt, the only Unicode characters valid in the input are:

* 0020, 0041-005A (Latin alphabet)
* 0020, 0391-03A9 (Greek alphabet)
* 0020, 0401, 0410-042F (Cyrillic alphabet)

But as shown in the lookup tables, characters may be cross-alphabetic.

Adding Jonathan Allan's table from the comments:

```
                                                 Latin  Greek  Cyrillic
U+0020     Space                                 1      1      1
U+0041  A  Latin capital letter A                1      1      1
U+0042  B  Latin capital letter B                1      1      1
U+0043  C  Latin capital letter C                1      0      1
U+0044  D  Latin capital letter D                1      0      0
U+0045  E  Latin capital letter E                1      1      1
U+0046  F  Latin capital letter F                1      0      0
U+0047  G  Latin capital letter G                1      0      0
U+0048  H  Latin capital letter H                1      1      1
U+0049  I  Latin capital letter I                1      1      0
U+004A  J  Latin capital letter J                1      0      0
U+004B  K  Latin capital letter K                1      1      1
U+004C  L  Latin capital letter L                1      0      0
U+004D  M  Latin capital letter M                1      1      1
U+004E  N  Latin capital letter N                1      1      0
U+004F  O  Latin capital letter O                1      1      1
U+0050  P  Latin capital letter P                1      1      1
U+0051  Q  Latin capital letter Q                1      0      0
U+0052  R  Latin capital letter R                1      0      0
U+0053  S  Latin capital letter S                1      0      0
U+0054  T  Latin capital letter T                1      1      1
U+0055  U  Latin capital letter U                1      0      0
U+0056  V  Latin capital letter V                1      0      0
U+0057  W  Latin capital letter W                1      0      0
U+0058  X  Latin capital letter X                1      1      1
U+0059  Y  Latin capital letter Y                1      1      1
U+005A  Z  Latin capital letter Z                1      1      0

U+0391  Α  Greek capital letter Alpha            1      1      1
U+0392  Β  Greek capital letter Beta             1      1      1
U+0393  Γ  Greek capital letter Gamma            0      1      1
U+0394  Δ  Greek capital letter Delta            0      1      0
U+0395  Ε  Greek capital letter Epsilon          1      1      1
U+0396  Ζ  Greek capital letter Zeta             1      1      0
U+0397  Η  Greek capital letter Eta              1      1      1
U+0398  Θ  Greek capital letter Theta            0      1      0
U+0399  Ι  Greek capital letter Iota             1      1      0
U+039A  Κ  Greek capital letter Kappa            1      1      1
U+039B  Λ  Greek capital letter Lambda           0      1      1
U+039C  Μ  Greek capital letter Mu               1      1      1
U+039D  Ν  Greek capital letter Nu               1      1      0
U+039E  Ξ  Greek capital letter Xi               0      1      0
U+039F  Ο  Greek capital letter Omicron          1      1      1
U+03A0  Π  Greek capital letter Pi               0      1      1
U+03A1  Ρ  Greek capital letter Rho              1      1      1

U+03A3  Σ  Greek capital letter Sigma            0      1      0
U+03A4  Τ  Greek capital letter Tau              1      1      1
U+03A5  Υ  Greek capital letter Upsilon          1      1      1
U+03A6  Φ  Greek capital letter Phi              0      1      1
U+03A7  Χ  Greek capital letter Chi              1      1      1
U+03A8  Ψ  Greek capital letter Psi              0      1      0
U+03A9  Ω  Greek capital letter Omega            0      1      0

U+0401  Ё  Cyrillic capital letter Io            0      0      1

U+0410  А  Cyrillic capital letter A             1      1      1
U+0411  Б  Cyrillic capital letter Be            0      0      1
U+0412  В  Cyrillic capital letter Ve            1      1      1
U+0413  Г  Cyrillic capital letter Ghe           0      1      1
U+0414  Д  Cyrillic capital letter De            0      0      1
U+0415  Е  Cyrillic capital letter Ie            1      1      1
U+0416  Ж  Cyrillic capital letter Zhe           0      0      1
U+0417  З  Cyrillic capital letter Ze            0      0      1
U+0418  И  Cyrillic capital letter I             0      0      1
U+0419  Й  Cyrillic capital letter Short I       0      0      1
U+041A  К  Cyrillic capital letter Ka            1      1      1
U+041B  Л  Cyrillic capital letter El            0      1      1
U+041C  М  Cyrillic capital letter Em            1      1      1
U+041D  Н  Cyrillic capital letter En            1      1      1
U+041E  О  Cyrillic capital letter O             1      1      1
U+041F  П  Cyrillic capital letter Pe            0      1      1
U+0420  Р  Cyrillic capital letter Er            1      1      1
U+0421  С  Cyrillic capital letter Es            1      0      1
U+0422  Т  Cyrillic capital letter Te            1      1      1
U+0423  У  Cyrillic capital letter U             1      1      1
U+0424  Ф  Cyrillic capital letter Ef            0      1      1
U+0425  Х  Cyrillic capital letter Ha            1      1      1
U+0426  Ц  Cyrillic capital letter Tse           0      0      1
U+0427  Ч  Cyrillic capital letter Che           0      0      1
U+0428  Ш  Cyrillic capital letter Sha           0      0      1
U+0429  Щ  Cyrillic capital letter Shcha         0      0      1
U+042A  Ъ  Cyrillic capital letter hard sign     0      0      1
U+042B  Ы  Cyrillic capital letter Yeru          0      0      1
U+042C  Ь  Cyrillic capital letter soft sign     0      0      1
U+042D  Э  Cyrillic capital letter E             0      0      1
U+042E  Ю  Cyrillic capital letter Yu            0      0      1
U+042F  Я  Cyrillic capital letter Ya            0      0      1

```

# Answer
> 4 votes
# Jelly, 56 bytes

A hash may well be shorter.

```
O:⁹:2;ON©œị“ŒḂI4ƥƒⱮıtɱN¦“¤COṙṚ¹`“ÑṂḄẈɼ]ġÐ’b4¤+4Bṙ®Ḣµ€S÷L

```

A monadic link returning a list of ratio amounts in the order English, Greek, Russian.

**Try it online!**
...or see a fully formatted output (including the implied rounding to one decimal place)

### How?

We wish to have code which translates each possible character to a triple of ones and zeros representing whether they belong to each of the alphabets (much like the table in the question where `C` is `1 0 1`). Once that is done we can sum across these and divide by the length to yield the ratios (between zero and one inclusive) - this is just `S÷L` (seen at the right of the code).

For any given character We know that if the ordinal is less than 256 it counts as English, if it is greater than 1024 it counts as Russian, and that if it is in-between 256 and 1024 it counts as Greek. As such taking the ordinal and integer dividing by 256 and then integer dividing the result by two yields `0` for the space and Latin characters (count as English), `1` for Hellenic (count as Greek), and `2` for Cyrillic (count as Russian). This is just `O:⁹:2` in Jelly (seen at the left of the code).

If we rotate the triples of bits such that the natural alphabet bit\* is the most significant then we can encode the lower two bits (as values between zero and three inclusive) in a look-up table with three rows and then rotate right by the numbers found above.

When we do this there are two things worthy of note - 1. Jelly has a rotate-left-by atom not a rotate-right-by one; 2. the Hellenic row of the look-up table would start with a zero (since `Ξ` is only Greek), thwarting a simple base-4 encoding (since leading zeros are not encodable). To alleviate (1) we can rotate-left by the negated value and to alleviate (2) we can encode our rows in reverse and index into them with the negative amount. This way we can negate both the row and column index with a single byte (`N`) as such our row and column indices may be calculated with `O:⁹:2;ON`.

Note that Jelly now has a multi-dimensional indexing atom, `œị`.

The table is formed from three large numbers which, once converted to base four, give the lower bits required for Cyrillic, Greek and Latin(+Space) respectively. They are of minimal length such that modular indexing by the negated ordinal values is possible - 47, 25, and 30 respectively (the `.`s are at unused indexes):

```
1: 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 3 1 3 3 2 3 1 3 3 3 1 3 0 0 0 0 3 0 1 3 0 3 0 0 0 0 0 0
   . . . . . . . . . Я Ю Э Ь Ы Ъ Щ Ш Ч Ц Х Ф У Т С Р П О Н М Л К Й И З Ж Е Д Г В Б А Ё . . . . .

2: 3 2 3 1 0 3 1 3 0 2 3 3 0 0 3 2 3 3 0 0 3 2 3 0 1
   Μ Λ Κ Ι Θ Η Ζ Ε Δ Γ Β Α Ω Ψ Χ Φ Υ Τ Σ . Ρ Π Ο Ξ Ν

3: 3 3 0 0 0 3 0 0 0 3 3 2 3 0 3 0 2 3 0 0 3 0 1 3 3 0 0 3 0 2
   Y X W V U T S R Q P O N M L K J I H G F E D C B A . .   . Z

```

As an example consider the character Φ at Unicode point U+03A6 (which should yield `[0,1,1]`) it has an ordinal value of (3×16²+10×16+6 =) 934. (`O:⁹:2` means 934//256//2 =) 1 identifying it as part of the Hellenic block. The `;O` concatenates the ordinal giving us `[1,934]` and the `N` then negates both values giving us `[-1,-934]`. Since Jelly indexing is both 1-based and modular and there are three rows the `-1` references the second of the three rows (row 2 in the above code-block), since the middle row has a length of 25 the `-934` references the (-934%25 =) 16th entry in that row, which is `2`. The code then adds four (the most significant bit) giving us `6` which converted to binary is `[1,1,0]`. The code then rotates this left by each of `[-1,-934]` and takes the head (i.e. the rotation left by -1, a rotation right by 1) yielding `[0,1,1]` as required.

* English for space since it's grouped with the Latin characters

---

**Commented code**

```
O:⁹:2;ON©œị“...“...“...’b4¤+4Bṙ®Ḣµ€S÷L - Link: list of characters        e.g.: "СЯ"
                                 µ€    - for €ach character:                С       Я
O                                      -   cast to ordinal               1057    1071
  ⁹                                    -   literal 256
 :                                     -   integer division                 4       4
   :2                                  -   integer divide by 2              2       2
      O                                -   cast to ordinal               1057    1071
     ;                                 -   concatenate                  [2,1057] [2,1071]
       N                               -   negate                     [-2,-1057] [-2,-1071]
        ©                              -   copy to register for later
                          ¤            -   nilad followed by link(s) as a nilad:
           “...“...“...’               -     list of integers encoded in base 250 = [4951760157204492290900832256, 1043285073970097, 1081712651052809266]
                        b4             -     convert to base 4                    = [[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,1,3,3,2,3,1,3,3,3,1,3,0,0,0,0,3,0,1,3,0,3,0,0,0,0,0,0],[3,2,3,1,0,3,1,3,0,2,3,3,0,0,3,2,3,3,0,0,3,2,3,0,1],[3,3,0,0,0,3,0,0,0,3,3,2,3,0,3,0,2,3,0,0,3,0,1,3,3,0,0,3,0,2]]
         œị                            -   index into                       2       0                   ^--[-2,-1071]   [-2,-1057]--^
                           +4          -   add four                         6       4
                             B         -   convert to binary             [1,1,0] [1,0,0]
                               ®       -   recall from register       [-2,-1057] [-2,-1071]
                              ṙ        -   rotate left         [[1,0,1],[0,1,1]] [[0,0,1],[1,0,0]]
                                Ḣ      -   head                          [1,0,1] [0,0,1]
                                   S   - sum                                 [1,0,2]
                                     L - length                                 2
                                    ÷  - divide                            [0.5,0,1]
                                       -   i.e.: 50.0% Latin, 0% Greek, 100% Russian

```

# Answer
> 5 votes
# JavaScript (ES6), ~~197~~ 179 bytes

Returns an array of 3 ratios in \[0..1\].

```
s=>[...s].map(_=>(x='b;C6cC6%c>b^[<$]_3--_c_acC-----$+aKHbKK[`H`H]'[(p=s[a='charCodeAt'](l++)%202%116%89)>>1][a]()-36,x/=p&1||8,L+=x/4&1,G+=x/2&1,C+=x&1),l=L=G=C=0)&&[L/l,G/l,C/l]

```

Try it online!

### How?

We use the (rather inefficient) hash function `% 202 % 116 % 89` to transform each character code into an index in \[0..88\]. The corresponding lookup table consists of 3-bit entries where bit #2 = Latin, bit #1 = Greek and bit #0 = Cyrillic. Using decimal digits, this gives:

```
76273722773722017732767267300071731711117377737577371111111111000775474476474767744474447

```

We append an extra `1` to get en even number of entries and encode this bit stream with printable ASCII characters in the range \[37..99\] (`%` to `c`), with 6 bits of payload data per character.

This leads to the following string:

```
b;C6cC6%c>b^[<$]_3--_c_acC-----$+aKHbKK[`H`H]

```

The offset was chosen to avoid characters such as `\` that would have required escaping.

# Answer
> 3 votes
# Ruby, 165 bytes

```
->s{(0..2).map{|x|s.chars.map{|c|o=c.ord;(o<33?7:"ĝ]ē¯]÷W59WUė½ñĝĕ×ßoĝėÏė55#{?!*15}"[o-[913,1040,65][y=o>>7<=>7]].ord+226>>3*-~y)[x]*1.0}.sum/s.size}}

```

Try it online!

**Edit:** Significantly golfed the code, and most importantly, squeezed 3 translation sequences into one UTF-8 string. The original longer code is kept below for better readability and explanation of the logic.

### Ruby, 211 bytes

```
->s{(0..2).map{|x|s.chars.map{|x|o=x.ord;o<33?7:o<91?"77517117317173771117111773"[o-65]:o<938?"7762737237673276702776722"[o-913]:"74764744444767776757767#{?4*15}"[o-1040]}.inject(0.0){|y,z|y+=z.to_i[x]}/s.size}}

```

Try it online!

May not be the most efficient approach, but does the job. Uses a translation table for each alphabet with character occurrence in different scripts encoded by the bits of the number (in the order: Latin, Greek, Russian). The output is an array of percentages in the same order.

To fix the outlier `Ё` case I extended the Russian-only block of 4-s from 10 positions at the end of the alphabet to 15. This way, `Ё` gets picked correctly with negative index (and we are not required to handle lowercase letters than correspond to these extra indices).

# Answer
> 1 votes
# Retina 0.8.2, 230 bytes

```
.+
$&¶$&¶$&¶$&
T`ΓΔΘΛΞΠΣΦΨΩЁБГДЖ-ЙЛПФЦ-Я`_`.+(?=¶.+¶.+$)
T`CDFGJ\LQRSUVWЁБДЖ-ЙС-Я`_`.+(?=¶.+$)
T`DFGIJ\LNQRSUVWZΔΖΘΙΝΞΣΨΩ`_`.+$
¶(.*)
¶$.1$*
1
100$*
.
1
(1+)¶(\1)*1*¶(\1)*1*¶(\1)*1*
$#2 $#3 $#4

```

Try it online! Link includes test cases. Note: Output is in % truncated down to an integer, because increasing the precision made the script too slow and it timed out on TIO.

---
Tags: code-golf, unicode, statistics
---


title: Race for the Steward Badge

text:
# Question
Title: Race for the Steward Badge
### Backstory

If you visit the Steward Badge Page, you will see no one has received one of these badges from PPCG yet. However, there are two users: **DJMcMayhem** & **Martin Ender**, that are only a few reviews away from this badge!

### Challenge

Your challenge is to write a program or function that when run outputs DJMcMayhem's review count from the Low Quality reviews & Martin Ender's review count from First Posts reviews.

Your code needs to be dynamic so you should not hard-code the values of the current count. You should actually go and fetch the counts from those pages.

Your output should be the user's name and the count, with some delimiter in between each value, and there is no input.

### Examples

```
DJMcMayhem, Count] [Martin Ender, Count]

DJMcMayhem, Count, Martin Ender, Count

DJMcMayhem Count Martin Ender Count

DJMcMayhem
Count
Martin Ender
Count

etc.....

```

No extraneous info is allowed.

### Rules

Standard loopholes are not allowed.

This is , so the shortest code in bytes for each language wins!

Sandbox post

# Answer
# Red, 259 bytes

```
c:"https://codegolf.stackexchange.com/review/"t: copy c
d:"low-quality-posts/stats"e:"first-posts/stats"
f: func[s q][parse find s q[thru{-count">^M^/}any" "copy n to" "(print[q n])]]
f read to-url append c d"DJMcMayhem"
f read to-url append t e"Martin Ender"

```

Try it online!

Unfortunately doesn't work in TIO - results in timeout, although works normally in Red console.
> 1 votes

---
Tags: code-golf, internet, stack-exchange-api
---


title: Fastest to find the joint

text:
# Question
Title: Fastest to find the joint
The input is an array (or space-separated string, as you wish), zero-indexed, consisting of one strictly increasing array and one strictly decreasing array (in this order, not other vice versa), each having a length of 2 at least. Example is:

```
-10 -2 4 18 38 46 28 19 10

```

The goal is to write the fastest algorithm to find the joint of two sorted arrays.

In other words, the output is the index of the greatest element. In the provided case the output should be `5`.

The input is guaranteed not to contain repeating numbers.

It's obvious that this can be solved with `O(n)` with ease, so please provide more interesting faster answers :)

---

Other test cases (first line is input, second is output):

```
0 1 4 3
2

```

---

```
1 10 9 8 7 6 5 4 3 1
1

```

---

```
1 3 4 6 7 8 0 -10 -20
5

```

---

```
1 3 5 3 1
2

```

---

You could also accept the length of the array as additional input, if needed

# Answer
# C (gcc)

```
int find_joint(int *array, int length) {
	int left_bound = 0, right_bound = length - 1, joint = length / 2;

	while (array[joint-1] > array[joint] || array[joint] < array[joint+1]) {
		if (array[joint-1] < array[joint])
			left_bound = joint + 2;
		else
			right_bound = joint - 2;

		joint = left_bound + (right_bound - left_bound) / 2;
	}

	return joint;
}

```

Try it online!
> 3 votes

# Answer
# JavaScript (ES6), O(log n)

Now assuming that accessing `Array.length` is always **O(1)** (as suggested by @12Me21 and @ETHproductions) and therefore not requiring the length to be passed as input anymore.

Returns a string describing the result (index + number of iterations).

```
f = (a, n = 1, min = 0, max = a.length - 1) => {
  let res = x => `Found index ${x} in ${n} iteration(s)`,
      mid;

  return (
    // only one slot left?
    max == min ? res(max) :

    // only two slots left?
    max == min + 1 ? res(a[max] > a[min] ? max : min) :

    // is the middle slot greater than its two neighbors?
    a[mid = min + max >> 1] > a[mid + 1] && a[mid] > a[mid - 1] ? res(mid) :

    // recursive call required
    a[mid] > a[mid + 1] ?
      f(a, n + 1, min, mid - 1)
    :
      f(a, n + 1, mid + 1, max)
  );
}

```

Try it online!
> 2 votes

# Answer
## JavaScript (ES7)

```
function find_join(a, l) {
    p = 1.25 ** .5 - .5;
    n = 1;
    i = 0;
    j = l * p + .5 | 0;
    k = j * p + .5 | 0;
    x = a[j];
    y = a[k];
    while (l > 2) {
        n++;
        if (x > y) {
            l = j;
            j = k;
            k = j * p + .5 | 0;
            x = y;
            y = a[i + k];
        } else {
            i += k;
            l -= k;
            k = j - k;
            j = l * p + .5 | 0;
            y = x;
            x = a[i + j];
        }
    }
    return [n, a.indexOf(Math.max(...a.slice(i, i + l)), i)];
}

```

I was too lazy to write out the full `l < 3` case.

This algorithm optimises the number of accesses of the array `a`. In practice this is not very useful, since the binary search always tests consecutive elements, which is not likely to be much slower than testing a single element.
> 0 votes

---
Tags: array, fastest-algorithm
---


title: Abstract Rewriting Challenge (Cops)

text:
# Question
Title: Abstract Rewriting Challenge (Cops)
This is a somewhat -like challenge. This is the cops' thread; the robbers' thread is here.

# Cops

Your task is to define an abstract rewriting system in which the reachability of one word from another is difficult to determine. You will prepare the following things:

1. A set of symbols, called the alphabet. (You may use any Unicode characters for these, but please don't use whitespace, or symbols that are hard to distinguish from each other.)
2. A *source string* composed of symbols from your alphabet.
3. A *target string* composed of symbols from your alphabet.
4. A set of rewrite rules using characters from your alphabet. (See below for the definition of a rewrite rule.)
5. A proof showing whether your source string can be converted into your target string by successive application of your rewrite rules. This proof might consist of an actual sequence of rewrite steps, or a mathematical proof that such a sequence must exist, or a mathematical proof that such a sequence does not exist.

You will post the first four of these, keeping the proof secret; the robbers will try to crack your answer by providing their own proof that your target string can or can not be reached from your source string. If your submission is not cracked within **two weeks**, you may mark it as safe and edit in your proof.

Submissions will be scored according to the number of characters in their rewrite rules and their source and target strings, as detailed below. The winner will be the uncracked submission with the lowest score.

**What is a rewrite rule?**

A rewrite rule is simply a pair of strings in your alphabet. (Either of these strings may be empty.) An application of a rewrite rule consists of finding a substring that is equal to the first string in the pair, and replacing it with the second.

An example should make this clear:

Suppose alphabet is `A`, `B` and `C`; the source string is "`A`"; the target string is "`C`" and the rewrite rules are

```
A:B
B:BB
B:A
AA:C

```

then the target string is reachable in the following way:

```
A
B   (using rule 1)
BB  (using rule 2)
AB  (using rule 3)
AA  (using rule 3)
C   (using rule 4)

```

**Scoring**

Your score will be

* the length of your source string,
* plus the length of your target string,
* plus the length of all the strings included in your rewrite rules,
* plus one extra point for each rewrite rule.

If you write your rewrite rules with a colon separator as above, this is just the total length of all the rewrite rules (including the separator), plus the lengths of the source and target strings. A lower score is better. The number of distinct characters in your alphabet will be used to break ties, with fewer being better.

## Bounty

I'd like to see answers that really go for low scores. I will award **200 rep** to the first answer that scores less than 100 points in this challenge and doesn't get cracked.

# Answer
> 10 votes
## 326 points - Cracked by jimmy23013

The level is Picokosmos #13 by Aymeric du Peloux (with a trivial modification). I tried to find a tasteful level that could be implemented with "boxes" and "walls" being the same character. For this level it was possible by making the central choke point two columns wide rather than one.

The rules/initial/target strings could be golfed a bit more, but this is just for fun.

Initial string:

```
___##___####_____##_#_#_##_#_!####______##_#####__####_#_######__###__

```

Target string:

```
___##___####_____##_#_#_##_#_#####____!__#_#####__####_#_######__###__

```

Rules:

```
_wW:!
_<:<_
Vv_:!
V_:_V
R:>>>>>>>>>>>>>
V#:#V
#w<:w#
>v_:_v
_wX:#
_!:!_
!:wLW_
L:<<<<<<<<<<<<<
#W:W#
!#_:_!#
_w<:w_
#<:<#
!:_VRv
>v#:#v
Uv_:#
_W:W_
_X:X_
>#:#>
#X:X#
U_:_U
Vv#:!URv
#wW:wLX!
>_:_>
!_:_!
_#!:#!_
U#:#U

```

# Answer
> 8 votes
# 171 points, cracked by HyperNeutrino

Source: `YAAAT`

Target: `VW626206555675126212043640270477001760465526277571600601`

Rules:

```
T:AAAAAT
T:BBU
U:BU
U:ZW
AB:BCA
CB:BC
AZ:Z
CZ:ZC
YB:Y
YZ:V
V:VD
DCC:CD
DCW:W+
DW:W_
___:0
__+:1
_+_:2
_++:3
+__:4
+_+:5
++_:6
+++:7

```

Just something obvious to do. The actual sequence of rewrite steps probably won't fit in an SE answer.

# Answer
> 7 votes
## 33 points, cracked by user71546

A simple one to start off.

Source: `xnor`
Target: `xor`
Rewrite rules:

```
x:xn
no:oon
nr:r
ooooooooooo:

```

The last rule takes 11 o's to the empty string.

# Answer
> 5 votes
# 139 points (safe-ish)

I intended this answer to be cracked, and user202729 basically solved it in the comments, but nobody posted an answer in the robbers' thread, so I'm marking it "safe-ish" and including my proof below.

(These things are evidently much easier to make than they are to crack. Nobody has tried to go for a really low score yet though, and there might be more fun to be had at that end of things, if this challenge ever takes off.)

---

Here's a self answer. It's potentially very hard, but should be easy if you work out where it came from.

alphabet: `ABCDEⒶⒷⒸⒹⒺⒻ⬛⚪←→`

source: `←A→`

target: `←→`

Rules: (whitespace is not significant)

```
← : ←⬛
→ : ⬛→
A⬛ : ⚪B
A⚪ : ⚪Ⓑ
⬛Ⓐ : E⚪
⚪Ⓐ : Ⓔ⚪
B⬛ : ⚪C
B⚪ : ⚪Ⓒ
Ⓑ⬛ :
Ⓑ⚪ : ⚪Ⓕ
⬛C : D⚪
⚪C : Ⓓ⚪
Ⓒ⬛ : ⬛B
Ⓒ⚪ : ⬛Ⓑ
D⬛ : ⚪E
D⚪ : ⚪Ⓔ
⬛Ⓓ : C⬛
⚪Ⓓ : Ⓒ⬛
⬛E : A⚪
⚪E : Ⓐ⚪
Ⓔ⬛ : ⬛D
Ⓔ⚪ : ⬛Ⓓ
Ⓕ⬛ : ⚪C
Ⓕ⚪ : ⚪Ⓒ
⬛ :
⚪ :
⬛ :
⚪ :

```

---

Here is an ASCII version, in case that unicode doesn't display well for everyone.

---

## Proof

This is equivalent to the current best contender for a six state busy beaver. A busy beaver is a Turing machine that halts after a really long time. Because of this, the source string `←A→` can indeed be transformed into the target string `←→`, but only after more than `7*10^36534` steps, which would take vastly longer than the age of the universe for any physical implementation.

The Turing machine's tape is represented by the symbols  (0) and  (1). The rules

```
← : ←⬛
→ : ⬛→

```

mean that the ends of the tape can always be extended with more zeros. If the head of the Turing machine ever gets near one end of the tape we can just apply one of these rules, which allows us to pretend that the tape is infinite, and starts out filled with all zeros. (The symbols  and  are never created or destroyed, so they're always at the ends of the tape.)

The Turing machine's head is represented with the symbols `ABCDEⒶⒷⒸⒹⒺⒻ` and . `A` means the head is in state `A` and the symbol under the head is a  (0), whereas Ⓐ means it's in state `A` and the symbol under it is a  (1). This is continued for the other states, with the circled letter representing a 1 underneath the head and the uncircled version representing a 0. (There is no symbol `F` because it happens that the head never ends up in state `F` with a 1 underneath it.)

The state  is the halting state. It has the special rules

```
⬛ :
⚪ :
⬛ :
⚪ :

```

If the halting state is ever reached we can repeatedly apply these rules to "suck in" all of the tape (including any extra zeros that arose from extending the tape more than necessary), leaving us in the state `←→`. Therefore the reachability problem boils down to whether the state  will ever be reached.

The remaining rules are the transition rules for the Turing machine. For example, the rules

```
A⬛ : ⚪B
A⚪ : ⚪Ⓑ

```

can be read as "if the machine is in state A and there is a zero under the head, then write a 1, change to state B and move right." Moving right takes two rules, because the tape cell to the right might contain a , in which case the machine should go into state `B`, or the cell might contain a , in which case it should go into state , since there is a  underneath it.

Similarly,

```
⬛Ⓓ : C⬛
⚪Ⓓ : Ⓒ⬛

```

means "if the machine is in state D and there is a 1 under the head, then write a 0, change to state C and move left."

The Turing machine used was discovered by Pavel Kropitz in 2010. Although it's often mentioned in the context of busy beavers, its actual transition table is a little tricky to track down, but it can be found for example here. It can be written as

```
    0   1

A   1RB 1LE
B   1RC 1RF
C   1LD 0RB
D   1RE 0LC
E   1LA 0RD
F   1RH 1RC

```

which can be read as "if the machine is in state A and there is a zero under the head, then write a 1, change to state B and move right," and so on. It should be straightforward, if laborious, to check that each entry of this table corresponds to a pair of rules as described above.

The only exception is the rule `1RH` that occurs when the machine is in state F over a 0, because it seemed fairly pointless to make the machine write a 1 and move to the right when it could just halt immediately as soon as it ever enters state F over a 0. So I changed the rule that would have been

```
Ⓑ⬛ : ⚪F

```

into

```
Ⓑ⬛ :

```

This is why there is no symbol `F` in the alphabet. (There are some other 'golfs' I could have made, but I didn't want to obscure it too much.)

That's basically it. The target string is reachable from the source string, but only after a ridiculous number of steps.

One more fun fact: if I had used

`←A⚪⚪→`

as the starting point instead, then it would take not `7*10^36534` steps to halt, but `10^10^10^10^18705352` steps, which is a very big number indeed.

# Answer
> 4 votes
# 287 points, safe

Source: `YAAT`

Target:

```
VW644507203420630255035757474755142053542246325217734264734527745236024300376212053464720055350477167345032015327021403167165534313137253235506613164473217702550435776242713

```

Rules:

```
T:AAAAAT
T:BBU
U:BU
U:ZW
AB:BCA
CB:BC
AZ:Z
CZ:ZC
YB:Y
YZ:V
V:VD
DCC:CD
DCW:W+
DW:W_
___:0
__+:1
_+_:2
_++:3
+__:4
+_+:5
++_:6
+++:7

```

I found that openssl is much easier to use than gpg for this purpose.

---

See HyperNeutrino's crack to the weaker version. In this case, The number of `C`s is:

```
22030661124527021657244569669713986649562044939414344827127551659400215941242670121250289039666163853124410625741840610262419007778597078437731811349579211

```

And the prime factors are:

```
220040395270643587721928041668579651570457474080109642875632513424514300377757
100120985046540745657156603717368093083538096517411033964934953688222272684423

```

The first number mod 5 = 2, so it is possible to get the final string.

# Answer
> 3 votes
# 48 points, cracked by bb94

Alphabet: `abc`
Source: `cbaabaabc`
Target: `cbacbcabc`
Rewrite rules:

```
ab:ba
bc:cb
ca:ac
ab:cc
bc:aa
ca:bb
```

# Answer
> 2 votes
# 402 points

Alphabet: `abcdefghijklmnopqrstu`
Source: `abcdoi`
Target: `ioabcdnnnnnnnnnnnnnnnnnn`
Rewrite rules:

```
ab:ba
ba:ab
ac:ca
ca:ac
ad:da
da:ad
bc:cb
cb:bc
bd:db
db:bd
cd:dc
dc:cd
na:an
nb:bn
nc:cn
nd:dn
nm:mn
nj:jn
aoi:eag
boi:ebg
coi:ecg
doi:edg
ae:ha
be:hb
ce:hc
de:hd
ioa:kam
iob:kbm
ioc:kcm
iod:kdm
ma:aj
mb:bj
mc:cj
md:dj
dg:rdnnnnnnnnnn
cg:qcnnnnn
bg:pbnn
ag:fan
cr:fc
br:fb
ar:fa
bq:fb
aq:fa
ap:fa
er:io
eq:io
ep:io
ef:io
hf:io
kd:dunnnnnnnnnn
kc:ctnnnnn
kb:bsnn
ka:aln
uc:cl
ub:bl
ua:al
tb:bl
ta:al
sa:al
um:oi
tm:oi
sm:oi
lm:oi
lj:oi
:n
```

The last rule allows you to create as many `n`s as you need.

Ugly as it seems, it's actually quite nice, one way or another...

# Answer
> 2 votes
# 1337 Points

Definitely not competitive, and took way too long to create (I hope I made no mistake).

Hint:

> try to understand the source string before looking at the rules

Alphabet: `ABEILRSTabcdefijlr`

Source: `SIbbbbbbbdbffacebbfadbdbeecddfaeebddcefaddbdbeeecddaaaaadfaeeebdddcefbbfadbdbdbeeecdddfaeeebdddcefaddbdbeeecddaaaadfaeeebdddcefbfadbdbdbeeecdddfaeeebdddcbdbffacebfadbdbeecddfaeebddceeefadddbdbeeeecddddfaeeeebddddceefaddbdbeeecdddfaeeebdddceefadadbefadfacdbeecddfaeebddcefaeeefaddbdbeeecdddfaeeebdddcceecdfaeeaddceecefaeadcbefadfacecdfaebdceeeeefadddddbdbeeeeeecddddddfaeeeeeebddddddceeefaddaeecdddbdbffacebfadbdbeecddfaeebddceeefadddbdbeeeecddddfaeeeebddddceefaddbdbeeecdddfaeeebdddceefadadbefadfacdbeecddfaeebddcefaeeefaddbdbeeecdddfaeeebdddcceecdfaeeaddceecefaeadcbefadfacecdfaebdcefaefaeeebdddcdcefaceeaaaceefacdffacebdceeeeefadddddbdbeeeeeecddddddfaeeeeeebddddddceeefaddaeecdddbdbffacebfadbdbeecddfaeebddceeefadddbdbeeeecddddfaeeeebddddceefaddbdbeeecdddfaeeebdddceefadadbefadfacdbeecddfaeebddcefaeeefaddbdbeeecdddfaeeebdddcceecdfaeeaddceecefaeadcbefadfacecdfaebdcefaefaeeebdddcdcefaceeaaaaceefacdffacebdcecefacE`

Target: `SE`

Rewrite rules:

```
Ab:bA
bA:Ab
Aa:aA
aA:Aa
Ad:dA
dA:Ad
Ae:eA
eA:Ae
Af:fA
fA:Af
Ac:cA
cA:Ac
IA:AI
AI:IA
Bb:bB
bB:Bb
Ba:aB
aB:Ba
Bd:dB
eB:Be
Be:eB
dB:Bd
Bf:fB
fB:Bf
Bc:cB
cB:Bc
E:BE
S:SB
Ib:AbI
AIa:aI
IdB:dBI
BIe:eIB
AIf:AfI
BIfB:BfiLB
Lb:bL
La:aL
Le:eL
Ld:dL
Lf:fL
Lc:cL
ib:bi
ia:ai
ie:ei
id:di
if:fil
lb:bl
la:al
le:el
ld:dl
lf:fl
lc:cl
icl:ci
icL:cI
Ic:jRc
bj:jb
aj:ja
dj:jd
ej:je
br:rb
ar:ra
dr:rd
er:re
fr:rf
cr:rc
bR:Rb
aR:Ra
dR:Rd
eR:Re
fR:Rf
cR:Rc
cj:jrc
fjr:jf
fjR:If
I:T
TB:T
BT:T
bT:T
aT:T
dT:T
eT:T
fT:T
cT:T
T:

```

# Answer
> 2 votes
> Note that I made some mistakes initially, so the score was changed. Nevertheless, the idea is the same. I hope there are no more mistakes now.

---

# 154 Points

Alphabet: `P.!xABC[{mD<`
Source: `[x!P.P...P..P.P....P..P.P.....P.P....P......P.P..P...P.P...Pm` (61 characters)
Target: `{CCCCC<` (there are 5 `C`s, so 7 characters)

Rules:

```
P.  →  .PP
!.  →  !
x   →  AxB
x   →
AB  →  BAC
CB  →  BC
CA  →  AC
[B  →  [
[A  →  {
{A  →  {
!   →  !m
mP  →  PmD
Dm  →  mD
DP  →  PD
!P  →  ?
?P  →  ?
!m  →  <
<m  →  <
C<D →  <

```

There are 19 rules, total number of characters = 67.

# Answer
> 1 votes
# 106 points - cracked by HyperNeutrino

Alphabet: `ABCDEFGHIJ`

Source: `FIABCJAGJDEHHID`

Target: `F`

Rewrite Rules:

```
B:DCIE
A:IFBA
D:EEFJ
C:GFIC
E:HBJG
F:FEBG
G:HFCJ
H:DIGB
I:FCAH
J:BHEA

EJGI:FF
FFF:J
FF:E
EE:D
DDEA:FI
I:F

```

---

Okay, HyperNeutrino has proved that this is unsolvable. However, there is another solution to this.

---

Take:

```
I E C D H G J A F B
1 2 3 4 5 6 7 8 9 10

```

The value of the source is even. The value of the target is odd. If we take each side, total the value, and take the value to mod 2, the values stay the same. Therefore, this cannot be achieved.

---
Tags: cops-and-robbers, repeated-transformation, grammars
---


title: Exploding Cats!

text:
# Question
Title: Exploding Cats!
# Challenge

You will be making a program/function that takes a string input of length `n`, and:

1. Puts the `kth` char at the center of the space, where `k = (n+1)/2`. This will be the location of your ground zero.
2. Puts the rest of the non-whitespace chars randomly arranged around ground zero. The Pythagorean distance from the char must not exceed `n`.
3. Outputs the result.

**If you need clarifications, see the example below.**

---

## Rules

* Standard loopholes apply!
* I/O must be in the form of a string.
* Input will always be odd to ensure that you have a central char to put at ground zero.
* Every valid output should occur with a non-zero probability.

This is ; shortest code in bytes wins!

---

## Example

Input: `qwert`

The boundaries of the explosion emanating from ground zero (x's mark valid places for the rest of the chars to be):

```
     x
  xxxxxxx
 xxxxxxxxx
 xxxxxxxxx
 xxxxxxxxx
xxxxxexxxxx
 xxxxxxxxx
 xxxxxxxxx
 xxxxxxxxx
  xxxxxxx
     x

```

Example output:

```
       t
     r

q    e

      w

```

# Answer
> 1 votes
# APL (Dyalog Classic), ~~68~~ ~~66~~ ~~65~~ ~~63~~ 62 bytes

```
{⍵@(n⊣¨¨@(⊢≡¨⌽)i[n?≢i←⍸(××n≥*∘.5)+.×¨⍨n-⍳s])⊢''⍴⍨s←2⍴1+2×n←≢⍵}

```

Try it online!

`{ }` anonymous function with argument

`n←≢⍵` variable `n` is the length

`s←2⍴1+2×n` variable `s` is the shape of the result: 2n+1 by 2n+1

`''⍴⍨s` create a square of spaces with that shape

`A@I⊢B` puts elements `A` at (pairs of) indices `I` in matrix `B`

`+.×¨⍨n-⍳s` squared distances from the centre of the matrix

`(××n≥*∘.5)` boolean matrix indicating where those distances are non-zero and `≤n`

coordinate pairs for the 1s in the boolean matrix

`i[n?≢i← ... ]` choose n of them randomly (no duplicates)

`n⊣¨¨@(⊢≡¨⌽)` change the central one to `n n`

`⍵@( ... )⊢ ...` put the chars from the argument at the given indices in the matrix of spaces

# Answer
> 3 votes
# JavaScript (ES6), 211  ~~216 220~~

**Edit** 1 byte saved thx @usandfriends

```
s=>[...s].map((c,i)=>{for(R=_=>Math.random()*h-l|0;x=R(y=R()),!(i-(l/2|0)?x|y&&x*x+y*y<=l*l&g[y+=l][x+=l]<'!':x=y=l););z=[...g[y]],z[x]=c,g[y]=z.join``},l=s.length,g=Array(h=l-~l).fill(' '.repeat(h)))&&g.join`
`

```

**Test**

```
f=s=>[...s].map((c,i)=>{for(R=_=>Math.random()*h-l|0;x=R(y=R()),!(i-(l/2|0)?x|y&&x*x+y*y<=l*l&g[y+=l][x+=l]<'!':x=y=l););z=[...g[y]],z[x]=c,g[y]=z.join``},l=s.length,g=Array(h=l-~l).fill(' '.repeat(h)))&&g.join`
`

// Less golfed
U=s=>(
  l=s.length,
  h=l-~l, // l+l+1
  g=Array(h).fill(' '.repeat(h)),
  [...s].map((c,i)=>{
    for(R=_=>Math.random()*h-l|0;
        x=R(y=R()), // set x,y to a random value in range -l ... l
        !(i - (l/2|0) // check if at mid point of input string
          ? x|y && // if not, check x and y must not be both 0
            x*x + y*y <= l*l &  // then check position inside the circle of ray L
            g[y+=l][x+=l] < '!' // then add offset L and check if position is not already used
          : x=y=l // if at midpoint in input string, x and y have fixed value L
         );
       ); // loop until valid position found
    z = [...g[y]];  // modify string at current position: convert to array ...
    z[x] = c;       // ... set element ...
    g[y] = z.join`` // ... back to string
  }),
  g.join`\n`
)

setInterval(_=>O.textContent=(f(I.value)),1000)
```

```
Word <input id=I value='qwert'><pre id=O></pre>
```

# Answer
> 2 votes
# Ruby, ~~211~~ ~~207~~ ~~203~~ 196 characters

Thanks to edc65 for 4 characters

```
->(x){x=x.chars
o,b,c=x.size
l=o*2+1
a=Array.new(l){Array.new l,' '}
a[o][o]=x.delete_at o/2
a[b][c]=x.pop if a[b=rand(l)][c=rand(l)]==' '&&(b-o)**2+(c-o)**2<=o*o while x[0]
a.map(&:join).join $/}

```

Explanation:

`->(x){...}` define an anonymous function that takes in an argument `x`

`x=x.chars` transform `x` from a string into an array of one-character strings

`o,b,c=x.size` store the length of the input in `o` for later use. `b` and `c` simply need to be initialized to *something*, so save 2 characters by attaching to a previous assignment.

`l=o*2+1` this is the length/width of the field where all characters could possibly go, also the diameter of the explosion circle.

`Array.new(l){Array.new l,' '}` make an `l`x`l` sized 2D array of space characters.

`a[o][o]=x.delete_at o/2` sets the center of the array to the center of the values of `x` (the input), while deleting that value from `x`

`... while x[0]` run the block (in this case, the code before `while` because it is inline) over and over until `x` is empty. In ruby, accessing an index that does not exist returns `nil`, which is a falsey value.

`a[b=rand(l)][c=rand(l)]==' '` Assign `b` and `c` to random values where 0 \<= *n* \< `l`. Then check if the spot at `b`,`c` is empty (aka is set to space character)

`(b-o)**2+(c-o)**2<=o*o` Pythagorean distance check. `o` is the length of the input. `**` is ruby's exponentiation operator, and `val<=o*o` is shorter than `val**0.5<=o`.

`a[b][c]=x.pop` delete the last value from `x`. Set the position `a`,`b` to that value in array `a`

`a[b][c]=x.pop if a[b=rand(l)][c=rand(l)]==' '&&(b-o)**2+(c-o)**2<=o*o while x[0]` Set a random position to the last value if that position is free and is within the explosion radius; keep doing this until we run out of characters to place.

`$/` is set to the operating system's newline. It's also shorter than `"\n"`

`a.map(&:join).join $/` Map all the arrays in `a` to a single-string version of themselves (eg `['a','b','c']` -\> `'abc'`). Take that new array and join it with newlines. Implicit return.

# Answer
> 1 votes
# Python 3, 286 bytes

```
import random as r
i=input()
l=len(i)
a=range(-l,l+1)
g=[(y,x)for y in a for x in a]
p=[(y,x)for y,x in g if abs(x+y*1j)<=l and x|y]
m=i[l//2]
d=[*i.replace(m,"",1).center(len(p))]
r.shuffle(d)
o=""
for c in g:
	o+=m if c==(0,0)else d.pop()if c in p else" "
	if c[1]==l:o+="\n"
print(o)

```

Trying it online is an option.

Whoops, stumbled onto this due to recent activity, didn't notice it was over two years old somehow until I spent a good while on this. Well, two answers is kind of sad, so this is probably a good idea to post anyway. I'm sure there are dozens of ways to improve on this—didn't notice until just now that input is always odd, which would've been helpful to know.

## Explanation

`i=input()` is input, of course, `l=len(i)` is saving the length of the string because it's used quite a few times.

`a=range(-l,l+1)` — a quick tool to create an iterator ranging the available distances away from the origin both ways along one dimension.

`g=[(y,x)for y in a for x in a]` builds a list of tuple coordinates that makes up the entire final grid.

`p=[(y,x)for y,x in g if abs(x+y*1j)<=l and x|y]` creates a subset of the list containing only the coordinates that non-center letters can possibly land on.

`m=i[l//2]` establishes the center character.

`d=[*i.replace(m,"",1).center(len(p))]` — the center character's taken out, leaving us with the other debris. The `center()` function is very nice here, because it allows us to pad out the line (with by default a space) until it's a certain number of characters long. Here, that's the number of spaces the letters can land on, thus mirroring the distribution we need.

`r.shuffle(d)` naturally shuffles said distribution to be actually... distributed.

The loop, `for c in g: o+=m if c==(0,0)else d.pop()if c in p else" "`, looks over the entire square of feasible tiles, regardless of anything possibly landing on it or not, and as necessary, adds a character to our output string `o`. Characters are popped out of our sample of debris so that they only appear once.

`if c[1]==l:o+="\n"` — Adds line breaks as well. Returns.

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


title: What is my exponential potential?

text:
# Question
Title: What is my exponential potential?
We'll define the ***N****-exponential potential* of a positive integer **M** as the count of prefixes of **MN** that are perfect **N**-powers.

The prefixes of an integer are all the contiguous subsequences of digits that start with the first one, interpreted as numbers in base 10. For example, the prefixes of **2744** are **2**, **27**, **274** and **2744**.

A prefix **P** is a perfect **N**-power if there exists an integer **K** such that **KN = P**. For example, **81** is a perfect **4**-power because **34 = 81**.

---

Given two strictly positive integers **M** and **N**, compute the **N**-exponential potential of **M** according to the definition above.

For instance, the **2**-exponential potential of **13** is **3** because **132** is **169**, and **1**, **16** and **169** are all perfect squares.

## Test cases

Naturally, the outputs will nearly always be pretty small because powers are... well... exponentially growing functions and having multiple perfect-power prefixes is rather rare.

```
M, N     -> Output

8499, 2  -> 1
4,    10 -> 2
5,    9  -> 2
6,    9  -> 2
13,   2  -> 3

```

# Answer
> 10 votes
# Brachylog, 12 bytes

```
{^a₀.&b~b^}ᶜ

```

Try it online!

## Explanation

```
{^a₀.&b~b^}ᶜ
{         }ᶜ  Count the number of ways the following can succeed:
  a₀            A prefix of
 ^                the first {input} to the power of the second {input}
    .&          produces the same output with the same input as
       ~b         any number
         ^        to the power of
      b           all inputs but the first (i.e. the second input)

```

# Answer
> 6 votes
# Jelly, 10 bytes

```
*DḌƤÆE%Ḅċ0

```

Try it online!

### How it works

```
*DḌƤÆE%Ḅċ0  Main link. Left argument: m. Right argument: n.

*           Compute m**n.
 D          Generate its decimal digits.
  ḌƤ        Convert prefixes back to integers.
    ÆE      Get the exponents of each prefix's prime factorization.
      %     Take all exponents modulo n.
            For a perfect n-th power, all moduli will be 0.
       Ḅ    Convert from binary to integer, mapping (only) arrays of 0's to 0.
        ċ0  Count the zeroes.

```

# Answer
> 3 votes
# Haskell, 56 bytes

```
0%n=0
x%n=sum[1|t<-[1..x],t^n==x]+div x 10%n
m#n=(m^n)%n

```

Try it online!

Extracts the prefixes arithmetically by repeated `\x->div x 10`. I tried expressing the last line point-free but didn't find a shorter expression.

# Answer
> 2 votes
# 05AB1E, 8 bytes

```
mηÓ¹%O0¢

```

Try it online!

Uses Dennis's Jelly 10-byte algorithm. Inputs are in reversed order.

# Answer
> 2 votes
# Perl 5, 38 bytes

```
#!/usr/bin/perl -p
/ /;$_=grep/^${\++$n**$'}/,($`**$')x$`

```

Try it online!

# Answer
> 1 votes
## Haskell, 73 bytes

```
m#n=sum[1|c<-scanl(\s c->s++[c])"0"$show$m^n,any(==read c)$map(^n)[1..m]]

```

Try it online!

# Answer
> 1 votes
# Java (OpenJDK 9), 105 bytes

```
m->n->{int c=1,k=m;for(;--k>0;)if((""+(int)Math.pow(m,n)).matches((int)Math.pow(k,n)+".*"))c++;return c;}

```

Try it online!

## Credits

# Answer
> 1 votes
# Perl 6, 40 bytes

```
{1+(^$^m X**$^n).grep({$m**$n~~/^$^p/})}

```

Try it online!

# Answer
> 0 votes
# Jelly, 14 bytes

```
*DḌƤ*İ}ær⁵%1¬S

```

Try it online! or see the **test suite**

## How it works

```
*DḌƤ*İ}ær⁵%1¬S - Main link. Arguments: n, m (integers)  e.g. 13, 2
*              - Power. Raise x to the power y               169
 D             - Convert to a list of digits                 [1 6 9]
   Ƥ           - Convert each Ƥrefix
  Ḍ            - Back to an integer                          [1 16 169]
     İ         - Calculate the İnverse of
      }        - The right argument                          0.5
    *          - Raise each element to that power            [1 4 13]
       ær⁵     - Round each to 10 ** -10                     [1 4 13]
               - to remove precision errors
          %1   - Take the decimal part of each               [0 0 0]
            ¬  - Logical NOT each                            [1 1 1]
             S - Sum                                         3

```

# Answer
> 0 votes
# Python 2, ~~83~~ ~~71~~ 70 bytes

```
n,m=input();s=n**m;k=0
while s:k+=round(s**(1./m))**m==s;s/=10
print k

```

Try it online!

Thx for 1 from ovs.

# Answer
> 0 votes
# APL (Dyalog), 31 bytes

```
{+/o=⌊o←(÷⍵)*⍨10⊥¨,\10⊥⍣¯1⊢⍺*⍵}

```

Try it online!

# Answer
> 0 votes
# Haskell, 83 bytes

```
import Data.List
m#n=sum[1|x<-read<$>(tail$inits$show(m^n)),x`elem`((^n)<$>[1..m])]

```

Try it online!

# Answer
> 0 votes
# Ruby, 60 bytes

```
->m,n{c=1;s=m**n;c+=(0..m).count{|j|j**n==s}while 0<s/=10;c}

```

a lot of it is to deal with floating point errors

Try it online!

# Answer
> 0 votes
# Kotlin, 89 bytes

```
m,n->1+(1..m-1).count{"${Math.pow(m+0.0,n)}".startsWith("${Math.pow(it+0.0,n).toInt()}")}

```

Try it online!

In the test cases, passed in n as double values (2.0, 10.0, 9.0) so that I don't have to convert to double when calling Math.pow().

# Answer
> 0 votes
# Jelly, 9 bytes

```
*DḌƤœ&*€L

```

Try it online!

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


title: Sequentially Divisible

text:
# Question
Title: Sequentially Divisible
Sometimes to fall asleep, I'll count as high as I can, whilst skipping numbers that are not square-free. I get a little thrill when I get to skip over several numbers in a row - for example, `48,49,50` are all NOT square-free (48 is divisible by 2^2, 49 by 7^2, and 50 by 5^2).

This led me to wondering about the earliest example of adjacent numbers divisible by some arbitrary sequence of divisors.

## Input

Input is an ordered list `a = [a_0, a_1, ...]` of strictly positive integers containing at least 1 element.

## Output

Output is the smallest positive integer `n` with the property that `a_0` divides `n`, `a_1` divides `n+1`, and more generally `a_k` divides `n+k`. If no such `n` exists, the function/program's behavior is not defined.

## Test Cases

```
[15] -> 15
[3,4,5] -> 3
[5,4,3] -> 55
[2,3,5,7] -> 158
[4,9,25,49] -> 29348
[11,7,5,3,2] -> 1518

```

## Scoring

This is ; shortest result (per language) wins bragging rights. The usual loopholes are excluded.

# Answer
# Wolfram Language (Mathematica), 51 bytes

```
Mod[ChineseRemainder[1-Range@Length@#,#],LCM@@#,1]&

```

Try it online!
> 8 votes

# Answer
# Husk, 7 bytes

```
VδΛ¦⁰ṫN

```

Try it online!

## Explanation

```
VδΛ¦⁰ṫN  Input is a list x.
      N  The list [1,2,3...
     ṫ   Tails: [[1,2,3...],[2,3,4...],[3,4,5...]...
V        Index of first tail y satisfying this:
  Λ       Every element
    ⁰     of x
   ¦      divides
 δ        the corresponding element of y.

```
> 6 votes

# Answer
# JavaScript, ~~42~~ 40 bytes

Will throw a recursion error if there is no solution (or the solution is too big).

```
a=>(g=y=>a.some(x=>y++%x)?g(++n):n)(n=1)

```

Saved 2 bytes with a pointer from Rick Hitchcock

---

## Try it

Enter a comma separated list of numbers.

```
o.innerText=(f=
a=>(g=y=>a.some(x=>y++%x)?g(++n):n)(n=1)
)(i.value=[5,4,3]);oninput=_=>o.innerText=f(i.value.split`,`.map(eval))
```

```
<input id=i><pre id=o>
```
> 5 votes

# Answer
# MATL, 11 bytes

```
`Gf@q+G\a}@

```

Try it online!

```
`           % Do ....
 Gf         %   Convert input to [1,2,...,]
   @q+      %   Add current iteration index minus one, to get [n, n+1, ....]
      G\    %   Elementwise mod([n,n+1,...],[a_0,a_1,...])
        a   % ...while any of the modular remainders is nonzero.
         }  % Finally:
          @ %   Output the iteration index.

```

Not exactly optimized for speed... the largest testcase takes a full minute using MATL, and approximately 0.03s on MATLAB. There is a small possibility MATL has a bit more overhead.
> 5 votes

# Answer
# Python 3, 62 bytes

```
f=lambda x,n=1:all(j%k<1for j,k in enumerate(x,n))or-~f(x,n+1)

```

Try it online!
> 4 votes

# Answer
# Pyth, 11 bytes

```
f!s.e%+kTbQ

```

Try it online!

---

```
f!s.e%+kTbQ         Full program - inputs list from stdin and outputs to stdout
f                   First number T such that
   .e     Q         The enumerated mapping over the Input Q
      +kT           by the function (elem_value+T)
     %   b          mod (elem_index)
 !s                 has a false sum, i.e. has all elements 0

```
> 3 votes

# Answer
# Clean, 61 bytes

```
import StdEnv
$l=hd[n\\n<-[1..]|and[i/e*e==i\\i<-[n..]&e<-l]]

```

Try it online!
> 3 votes

# Answer
# Haskell, ~~45~~ 44 bytes

```
f a=[n|n<-[1..],1>sum(zipWith mod[n..]a)]!!0

```

Try it online!

*Edit: -1 byte thanks to nimi!*
> 3 votes

# Answer
# 05AB1E, 9 bytes

```
Xµā<N+sÖP

```

Try it online!

**Explanation**

```
Xµ          # loop until counter equals 1
  ā         # push range [1 ... len(input)]
   <        # decrement
    N+      # add current iteration index N (starts at 1)
      sÖ    # elementwise evenly divisible by
        P   # product
            # if true, increase counter
            # output N

```
> 3 votes

# Answer
# , 23 bytes

```
[:I.0=]+/@:|"1#]\[:i.*/

```

Try it online!
> 2 votes

# Answer
# , 51 bytes

```
function(l){while(any((F+1:sum(l|1))%%l))F=F+1
F+1}

```

Try it online!

The use of `any` throws `k` warnings about implicit conversion to `logical`, where `k` is the return value.
> 2 votes

# Answer
# APL (Dyalog Unicode), ~~24 23~~ 22 bytes

```
{∨/×⍺|⍵+⍳⍴⍺:⍺∇⍵+1⋄⍵}∘1

```

Try it online!

Technically, this is a tacit function. I had to make it so since the only input allowed is the list of integers. Uses `⎕IO←0` (0-indexing)

It's worth noting that the function times out if `n` doesn't exist.

Thanks to @ngn and @H.PWiz for 1 byte each.

### How?

```
{∨/×⍺|⍵+⍳≢⍺:⍺∇⍵+1⋄⍵}∘1 ⍝ Main function. ⍺=input; ⍵=1.
{                   }∘1 ⍝ Using 1 as right argument and input as left argument:
           :            ⍝ If
        ⍳≢⍺             ⍝ The range [0..length(⍺)]
      ⍵+                ⍝ +⍵ (this generates the vector ⍵+0, ⍵+1,..., ⍵+length(⍺))
    ⍺|                  ⍝ Modulo ⍺
   ×                    ⍝ Signum; returns 1 for positive integers, ¯1 for negative and 0 for 0.
 ∨/                     ⍝ Logical OR reduction. Yields falsy iff the elements of the previous vector are all falsy.
            ⍺∇⍵+1       ⍝ Call the function recursively with ⍵+1.
                 ⋄⍵     ⍝ Else return ⍵.

```
> 2 votes

# Answer
# Perl 6, 34 bytes

```
->\a{first {all ($_..*)Z%%a},^∞}

```

Try it online!
> 2 votes

# Answer
# Perl 5, 49 + 2 (`-pa`) = 51 bytes

```
$i=!++$\;($\+$i)%$_&&last,$i++for@F;$i<@F&&redo}{

```

Try it online!
> 1 votes

# Answer
# Japt, 10 bytes

Will eventually output `undefined` if no solution exists, if it doesn't crash your browser first.

```
@e_X°vZÃ}a

```

Try it

---

## Explanation

```
               :Implicit input of array U
@       }a     :Loop and output the first integer X that returns true.
 e_    Ã       :For every element Z in U
   X°          :X, postfix increcemnted
     vZ        :Is it divisible by Z?

```
> 1 votes

# Answer
# Ruby, 48 bytes

```
->l{1+(1..1/0.0).find{|x|l.all?{|y|(x+=1)%y<1}}}

```

Try it online!
> 1 votes

# Answer
# Python 2, 80 bytes

```
def f(l,n=1):
 while n:
	n+=1
	if all((n+i)%v<1for i,v in enumerate(l)):return n

```

Try it online!
> 1 votes

# Answer
# Ruby, ~~47 46 43~~ 42 bytes

```
->a{(1..).find{|i|a.all?{|v|i%v<1&&i+=1}}}

```

Try it online!

NB: the `(1..)` syntax is only supported in ruby 2.6, for the moment TIO only supports 2.5 so the link is to an older version (43 bytes).
> 1 votes

# Answer
# PowerShell, ~~65~~ 62 bytes

```
for(){$o=1;$i=++$j;$args[0]|%{$o*=!($i++%$_)};if($o){$j;exit}}

```

Try it online!

PowerShell doesn't have the equivalent of an `any` or `some` or the like, so we need a slightly different approach.

This takes input `$args[0]` as an array, then enters an infinite `for` loop. Each iteration we set `$o` to be `1` (explained later), and set `$i` to be `++$j`. The incrementing `$j` keeps tabs on what the first number of the proposed solution is, while the `$i` will increment over the rest of the proposed solution.

We then send each element of the input `$args[0]` into a `ForEach-Object` loop. Inside the inner loop, we Boolean-multiply into `$o` the result of a calculation. This will make it so that if the calculation fails for a value, the `$o` will turn to `0`. The calculation is `!($i++%$_)`, or the Boolean-not of the modulo operation. Since any nonzero value is truthy in PowerShell, this turns any remainders into a falsey value, thus turning `$o` into `0`.

Outside the inner loop, `if` `$o` is nonzero, we've found an incrementing solution that works, so we output `$j` and `exit`.
> 1 votes

# Answer
# Standard ML (MLton), 96 bytes

```
open List;fun$n% =if all hd(tabulate(length%,fn i=>[1>(n+i)mod nth(%,i)]))then n else$(n+1)%;$1;

```

Try it online!

### Ungolfed:

```
open List
fun f n l =
    if all (fn x=>x)
           (tabulate ( length l
                     , fn i => (n+i) mod nth(l,i) = 0))
    then n
    else f (n+1) l
val g = f 1

```

Try it online! Starting with `n=1`, the function `f` increments `n` until the `all`-condition is fulfilled, in which case `n` is returned.

`tabulate(m,g)` with some integer `m` and function `g` builds the list `[g 0, g 1, ..., g m]`. In our condition `tabulate` is called with the length of the input list `l` and a function which checks whether the `i`th element of `l` divides `n+i`. This yields a list of booleans, so `all` with the identity function `fn x=>x` checks whether all elements are true.

I found a nice golfing trick to shorten the identity function in this case by four bytes: Instead of the lambda `(fn x=>x)`, the build-in function `hd` is used, which returns the first element of a list, and the resulting bools in `tabulate` are wrapped in `[` and `]` to create singleton lists.
> 1 votes

# Answer
# tinylisp, 108 bytes

```
(load library
(d ?(q((L N)(i L(i(mod N(h L))0(?(t L)(inc N)))1
(d S(q((L N)(i(? L N)N(S L(inc N
(q((L)(S L 1

```

The last line is an unnamed lambda function that takes a list and returns an integer. Try it online!

### Ungolfed

```
(load library)

(comment Function to check a candidate n)
(def sequentially-divisible?
 (lambda (divisors start-num)
  (if divisors
   (if (divides? (head divisors) start-num)
    (sequentially-divisible? (tail divisors) (inc start-num))
    0)
   1)))

(comment Function to check successive candidates for n until one works)
(def search
 (lambda (divisors start-num)
  (if (sequentially-divisible? divisors start-num)
   start-num
   (search divisors (inc start-num)))))

(comment Solution function: search for candidates for n starting from 1)
(def f
 (lambda (divisors)
  (search divisors 1)))

```
> 1 votes

# Answer
# Julia 0.6, 79 bytes

```
f(s,l=length(s),n=s[])=(while !all(mod.(collect(0:l-1).+n,s).==0);n+=s[];end;n)

```

Try it online!

Inputs without valid solutiosn will cause infinite looping... :)
> 1 votes

# Answer
# Python 2, 78 bytes

```
def f(a,c=0):
 while [j for i,j in enumerate(a) if(c+i)%j<1]!=a:c+=1
 return c

```

EDIT: -26 thanks to @Chas Brown
> 1 votes

# Answer
# Java 8, ~~82~~ 75 bytes

```
a->{for(int r=1,i,f;;r++){i=f=0;for(int b:a)f+=(r+i++)%b;if(f<1)return r;}}

```

**Explanation:**

Try it online.

```
a->{                 // Method with integer-array parameter and integer return-type
  for(int r=1,       //  Return-integer, starting at 1
          i,         //  Index-integer
          f;         //  Flag-integer
      ;r++){         //  Loop indefinitely, increasing `r` by 1 after every iteration
    i=f=0;           //   Reset both `i` and `f` to 0
    for(int b:a)     //   Inner loop over the input-array
      f+=(r+i++)%b;  //    Increase the flag-integer by `r+i` modulo the current item
    if(f<1)          //   If the flag-integer is still 0 at the end of the inner loop
      return r;}}    //    Return `r` as result

```
> 0 votes

# Answer
# Jelly, 10 bytes

```
1Ḷ+$ọ¥Ạ¥1#

```

Try it online!
> 0 votes

# Answer
# APL NARS, 140 bytes, 70 chars

```
r←f w;i;k
i←r←1⊃,w⋄k←¯1+⍴w⋄→0×⍳k=0
A:→0×⍳0=+/(1↓w)∣(k⍴r)+⍳k⋄r+←i⋄→A

```

test

```
  f 15
15
  f 3 4 5
3
  f 5 4 3
55
  f 2 3 5 7
158
  f 4 9 25 49
29348
  f 11 7 5 3 2
1518

```
> 0 votes

---
Tags: code-golf
---