text
stringlengths 180
608k
|
---|
[Question]
[
**This question already has answers here**:
[Polynomial Interpolation](/questions/1729/polynomial-interpolation)
(3 answers)
Closed 10 years ago.
Given a set of space-delimited integers, you've gotta either return a function that can generate that sequence, or return "There isn't any such function".
Sample input:
```
"1 11 41 79"
- x^3+x^2-1
"12 38 78"
- 7x^2 + 5x
```
The operations that the functions can contain are: +-/\* and exponentiation.
If anyone has any other ideas LMK. As this is a code-golf, the shortest code will win.
[Answer]
## Python 256 bytes
```
a=raw_input().split();r=range(len(a));m=[[(i+1.)**p for p in r]+[int(a[i])]for i in r]
for j in r:s=m[j];m=[map(lambda a,b:a-b*(i[j]-(i==s))/s[j],i,s)for i in m]
while~j:
c=m[j][-1]
if c:print('%+.15g'%c)[s>c>0:j>=c*c==1or 18]+('x^%d'%j)[:j*j],;s=0
j-=1
```
Sets up a system of linear equations, matrix style, and then uses Gaussian elimination to solve. Quite a few bytes are spent pretty-printing the output. Non-integer solutions are displayed to 15 digits of accuracy.
As every sequence of *n* real numbers can be generated by a polynomial of order no more than *n-1*, the "function does not exist" case is not handled.
Sample usage:
```
$ echo 1 11 41 79 | python find-poly.py
-2x^3 +22x^2 -42x +23
$ echo 1 11 35 79 | python find-poly.py
x^3 +x^2 -1
$ echo 12 38 78 | python find-poly.py
7x^2 +5x
$ echo 43 12 -5 19 57 | python find-poly.py
-2.25x^4 +27x^3 -98.75x^2 +110x +7
```
[Answer]
There was no restriction in using any specific library, so here is a solution in Python using Sympy
**Python 2.x: 71 Characters**
```
from sympy import*
print interpolate(map(int,raw_input().split()),abc.x)
```
] |
[Question]
[
I assume everyone here is familiar with the Caesar Cipher that shifts letters to a certain index. <https://en.wikipedia.org/wiki/Caesar_cipher> for those who still needs introduction.
But, we can all agree that plain Caesar is unfun and way too easy. So here's a version that also shifts characters around. This version first applies a cyclic position shift of a given amount to the string, for each character in the string separated with punctuations (space counts as character in this context, positive index means to the right).
For example, `Hello world` with shift +3 becomes `rldHello wo`.
`Hello! World` becomes `lloHe!rld Wo` with the same shift however because the ! separated the string.
After that, your program applies the Caesar cipher to the shifted text, and outputs the result. (easy enough)
The first example becomes `uogKhoor zr` after the Caesar cipher of +3.
The second example becomes `iilEb!oia Tl` after a Caesar shift of -3 (or +23 in alphabets)
As seen above, the index of the two shifts may or may not be equal.
**Task**
Write a encode and decode program or function (or whatever your language of choice calls them), they may or may not be the same one. It must implement the aforementioned rules of double shifting, and the decode function must successfully reverse it.
**Conditions**
Your program must at the very least function on ASCII characters, ASCII 0-9 (48-57, inclusive), A to Z (65-90), a to z (97-122) and Space (32) counts as characters in this context, with every other ASCII character counting as punctuation and breaking up the string.
Bonus points to those whose program functions on your language of choice's codebase. Since non-ASCII language contain special characters the "punctuation" rule is omitted in this use case. You only need to implement the cyclic shift and then the Caesar shift on your language's codebase.
`¡¢£¤` in Jelly becomes `©¤¥¦` with a position shift of +1 and Caesar shift of -253.
**You may assume:**
The index input are integers. It may be negative or zero.
If only one number is provided, encode both shifts with that number.
If no number is provided, perform whatever default shifts your heart desire (except 0 and 0, that is boring).
**Edit: Due to overwhelming demand, you may assume that there will be at least one number provided. Code that has defaults would still be preferred but no extra scoring.**
The input string is in ASCII. Or in your language's codebase if you decide to input that to your program.
**Scoring**
Of course programs that successfully include their codebase will be prioritized. Include the shifted version of your program in your answer to reflect this.
The other criteria is lowest byte wins. This counts both the encoder and decoder. List the sum and respective length separately please.
**Test cases**
```
+3 -5 "Hello,world" becomes "ggjCz,mgyrj"
+10 "Implement a Caesar Cipher with a Digit Shift" becomes "sqsd Crspd Swzvowoxd k Mkockb mszrob gsdr k N"
-2 -11 "Caesar cipher, also known as Caesar's cipher, the shift cipher, Caesar's code or Caesar shift."
becomes "thpg rxewtgRp,ahd zcdlc ph Rpthpg p'rxewtgh ,wt hwxui rxewtg i,pthpg'h rdst dg Rpthpg hwxui R."
```
PS. Of course I am aware that the two shifts can be carried out in any order and produce the same result, it is just my way of visualizing things. Plus, the first input means position shift index.
PPS. If the test cases are wrong I apologize, I am not a good coder.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 23 (12+11) [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
Uses the [05AB1E encoding](https://github.com/Adriandmen/05AB1E/wiki/Codepage) for the Caesar-shifting.
**Encoder:**
```
žĆDII(._kI+è
```
Input order as `string`, `shift`, (optional `Caesar-shift`). I/O of the strings as character-list.
[Try it online](https://tio.run/##yy9OTMpM/f//6L4jbS6enhp68dme2odX/P8freShpKOUCsQ5UJwPxCBYDmUXQcVTlGK5jLl0TQE) or [try it online with debug step-by-step lines and single shift-input](https://tio.run/##yy9OTMpM/f9fyTk/JbUgMT3VSkHJ/ui@I222LlxKnnkFpSUKxRmZaSWpKSAJF09PDb14W5BMSmZyarFCZp5CMpLGbKCUY0oKRAtQsiQ1PbUIJOGpDdGUWgESzUfRdHiFzv//0UoeSjpKqUCcA8X5QAyC5VB2EVQ8RSmWyxgA).
**Decoder:**
```
žĆDIkI-èI._
```
Input order as `string`, (optional `Caesar-shift`), `shift`. I/O of the strings as character-list.
[Try it online](https://tio.run/##yy9OTMpM/f//6L4jbS6e2Z66h1d46sX//x@tlKuko6CUDiLiQYQziEiAi4GJLBChDiKKINxYLl1TLmMA) or [try it online with debug step-by-step lines and single shift-input](https://tio.run/##yy9OTMpM/f9fyTk/JbUgMT3VSkHJ/ui@I222LlxKnnkpmcmpxQr5aQrFJUWZeem6mXkFpSUgJZ7ZtlxKwaVJJUWJySUKxRmZaSVAyZLU9NQisLSuLVh7aoUCUDRfIRnJ9MMrQFpBOsAq9eJ1/v@PVipV0lHKB@J0IPYG4gwoH4SLgFgfiKvA7FguYwA).
**Explanation:**
```
# ENCODER:
žĆ # Push the 05AB1E codepage
D # Duplicate it
I # Push the first character-list input
I # Push the second shift integer
( # Negate it
._ # Shift the character-list that many times towards the left
k # Get the index of each character in the duplicated codepage
I # Push the second shift input again or the optional third Caesar-shift input
+ # Add it to each index
è # And index it into the 05AB1E codepage
# (after which the resulting character-list is output implicitly as result)
# DECODER:
žĆ # Push the 05AB1E codepage
D # Duplicate it
I # Push the first character-list input
k # Get the index of each in the duplicated codepage
I # Push the optional Caesar-shift or shift integer
- # Subtract it from each index
è # Index it into the 05AB1E codepage
I # Push the second/third shift integer
._ # And rotate the character-list that many times towards the left
# (after which the resulting character-list is output implicitly as result)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), (8 + 11 = 19?) 11 + 14 = 25 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
Uses the code-page, no punctuation option
19 + 6 = 25 bytes handling the `only 1 number option` by taking a list of numbers as one of the two arguments.
**[Encoder +](https://tio.run/##y0rNyan8/9/g4e7uwzO8dB7unHloaSWQfNS44@GORf///4821jE0iP2vlAFUmK9Qnl@Uk6KoBAA "Jelly – Try It Online"):** (`Shift(s), plaintext`)
```
0ịØJ,ṙ¥yṙ⁸Ḣ
```
**[Decoder +](https://tio.run/##y0rNyan8/9/g4e5uv8MzvHQe7px5aGklkHzUuMPv0JKHOxb9//8/2ljH0CD2v1JZpdahnZU1ZXnaRfllSgA "Jelly – Try It Online"):** (`Shift(s), cyphertext`)
```
0ịNØJ,ṙ¥yṙ⁸N¤Ḣ
```
These Links build on the below programs:
**[Encoder](https://tio.run/##y0rNyan8///wDC@dhztnHlpaCSQfNW79//@/ocF/pQygbL5CeX5RToqi0n9jAA "Jelly – Try It Online"):** (`Caesar shift, plaintext, Cyclic shift`)
```
ØJ,ṙ¥yṙ⁵
```
**[Decoder](https://tio.run/##y0rNyan8/9/v8AwvnYc7Zx5aWgkkHzVu9Tu05P///4YG/5XKKrUO7aysKcvTLsovU/pvDAA "Jelly – Try It Online"):** (`Caesar shift, cyphertext, Cyclic shift`)
```
NØJ,ṙ¥yṙ⁵N¤
```
# How?
### Encoder
```
ØJ,ṙ¥yṙ⁵ - Main Link: Caesar shift, plaintext
ØJ - code-page characters
¥ - last two links as a dyad:
ṙ - rotate (code-page) left by (Caesar shift)
, - (code-page) pair with (that)
y - (plaintext) translated using (that mapping)
⁵ - get program's 3rd argument (Cyclic shift)
ṙ - rotate (translated) left by (Cyclic shift)
- implicit print
```
### Decoder
```
NØJ,ṙ¥yṙ⁵N¤ - Main Link: Caesar shift, cyphertext
N - (Caesar shift) negated
ØJ - code-page characters
¥ - last two links as a dyad:
ṙ - rotate (code-page) left by (negated Caesar shift)
, - pair
y - (cyphertext) translated using (that mapping)
¤ - nilad followed by link(s) as a nilad:
⁵ - get program's 3rd argument (Cyclic shift)
N - negated
ṙ - rotate (translated) left by (negated Cyclic shift)
- implicit print
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jellylanguage/wiki), ~~[25](https://tio.run/##y0rNyan8///hzpmHth6e4ZX5aOM67UeNWx/u7gbyuIDCh3c8atziB5eMh0sC9bQc3viocSeIXv7/v1JuXn5Bdo7Sf6P/hgYA)~~ 23 [bytes](https://github.com/DennisMitchell/jellylanguage/wiki/Code-page) (10 + 13)
```
ØJiⱮṙ+⁵ịØJ
ØJiⱮṙN}¥_⁵ịØJ
```
**Encoder**:
```
Ɱ For each character on the input string
i get its index on
ØJ the Jelly code page.
ṙ Then rotate the list we get by as much as the cyclic shift input
+⁵ and add to each number as much as the Caesar shift input.
ị Finally use those numbers to index
ØJ on Jelly's code page again.
```
**Decoder**:
```
Ɱ For each character on the input string
i get its index on
ØJ the Jelly code page.
ṙ Then rotate the list of indices
N}¥ by the symmetric of the cyclic shift input.
_⁵ Then subtract from each number as much as the Caesar shift input.
ị Finally use those numbers to index
ØJ on Jelly's code page again.
```
@Jonathan saved me 2 bytes! Kudos to him :D
Inputs are the string to encode, the shift corresponding to the "rotation" of the string and the shift corresponding to the Caesar encoding. I am encoding the whole Jelly codepage.
You can [try the encoder](https://tio.run/##y0rNyan8///wDK/MRxvXPdw5U/tR49aHu7uBAv///1fKAErnK5TnF@WkKCr9N/5vaAAA) or [the decoder](https://tio.run/##y0rNyan8///wDK/MRxvXPdw506/20NL4R41bH@7uBgr@//9fqaxS69DOypqyPO2i/DKl/8b/DQ0A). You can also [check the encoder and decoder are the inverse of one another](https://tio.run/##y0rNyan8///wDK/MRxvXPdw5U/tR49aHu7uBAlwIQb/aQ0vj4RL/H@5sObzxUeNOEL38/3@lxKTklNQ0pf9G/w0NAA) (swap the order of the encoder/decoder to verify they are the inverses on both sides).
[Answer]
# [PHP](https://php.net/), 398 bytes
```
function e($z,$x,$y=null){$y=is_null($y)?$x:$y;for($i=0,$o=preg_split('/([^A-Za-z0-9 ])/',$z,0,2);$i<count($o);$o[$i]=$s,$i+=2)for($s=substr(($s=$o[$i]).$s.$s,($l=strlen($s))-$x,$l),$j=0;$j<strlen($s);$j++)if(($c=$s[$j])!=' ')$s[$j]=(chr(ctype_digit($c)?(ord($c)+$y-38)%10+48:(ord($c)+$y-($p=ctype_lower($c)?97:65)+26)%26+$p));return join($o);}function d($z,$x,$y=null){return e($z,-$x,-($y?:$x));}
```
[Try it online!](https://tio.run/##jVDfa9swEH7fX3GDK5aw3DpOm7V2hAljZYNCA31b8IJnK7EyYxnJXuOO/u2eHAe37Gmgh@/u@3Gnq4u6X8Z1UUO/a6uskaoCQfCF4ZFhx6u2LOkfC6TZDphgR2M8hthFO6UJSu4zVLzWYr81dSkb4lyRzY@V9z31XnzvDhJ65TAb57OARiiXmWqrhqCyhdqgTDgahtLlAT3lGW7an6bRZICjgl6isY8RLLllSlFZjlJvWLCkDA/cj/CwfKNs5bpU7mxGZuM3eEjoR@6AQ8eCk6zQJGu6Wmxzubc7Y0ZjonQ@ABc7b35LL2a@e30bvu8SrPnoKtWz0CfX3adwcUPdYEEvgoWLNaWRFk2rKzgoWZ3@@TrdNf/3rmfp6d7Df@yILg7xaFNee5EVClAAtzxgqve/N7OEnVEwoXkClMH663r75fEh@jC6cuvKrUv8v55PMyAGZ716enIghPvVt4eo7z@nwqQaMlkXQjNIS6PgV6WeK0gNjKRjJropBJhC7pqp8yZRuQClz41RdTkL5uz6ZtF7wV8 "PHP – Try It Online")
Submitted as two functions:
* Encode: `e( $string, $index_shift, [ $caesar_shift ] ) : string`
* Decode: `d( $string, $index_shift, [ $caesar_shift ] ) : string`
Yes, this is not very golfed yet, but I thought it would be helpful to post to verify my assumptions about this challenge, while waiting for answers to my questions to the OP above.
Still unclear to me is:
1. Case of inputs `+1 "Z" == "A"`, `+1 "z" == "a"`, `+1 "9" == "0"`?
2. *Only* UTF-8 / ASCII languages are required to implement the "punctuation delimiter" rule?
3. Verify output with posted test cases, which as I've pointed out, I believe the second two are incorrect.
[Answer]
First version, a bit verbose yet, I'll try to optimize:
* "fully cyclic caesar" (`9`+1 becomes `0`, `z`+1 becomes `a`, `Z`+1 becomes `A`)
* breaks on anything not a space or char (`a-z A-Z 0-1`) (I think your last example is wrong, it breaks on the last `'`, which is intended)
* default values if missing: 1 / 1 (same value for both, could be up to 9 without extra byte)
* originally planned to use PHP's char increment, convenient way to loop over alpha values (`$c='Z';$c++;` makes `'AA'`), but decrement is not implemented (so no negative values or decoding)!
* should be prioritized IMO because it supports its own codebase, UTF-8 ;)
**ENCODER + DECODER = TOTAL**
# [PHP](https://php.net/), 430 + 71 = 501 bytes
```
function a($a,$b='',$c=''){$b!==''?:$b=$c;$c!==''?:$c=$b;$t="/([^a-zA-Z0-9 ]+)/";preg_match_all($t,$a,$s);$r=preg_split($t,$a);for($i=0;null!==$d=$r[$i];$i++){if($j=strlen($d)){$n=-$b%$j;$d=substr($d,$n).substr($d,0,$n);for(;$j--;){if(' '!=$e=$d[$j]){$n=($t=ctype_digit($e))?10:26;$f=$c%$n+$e=ord($e);$d[$j]=chr($t&$f>57|$f>122|$e<91&$f>90?$f-$n:($t&$f<48|!$t&$f<65|$e>96&$f<97?$f+$n:$f));}}}$r[$i]=$d.$s[1][$i];}return join($r);}function b($a,$b='',$c=''){return a($a,$b!==''?-$b:'',$c!==''?-$c:'');}
```
[Try it online!](https://tio.run/##dZFhk5owEIa/91dEZ6@SAVRsz6vGnHPTf1HLORCCxHKBSWJv2tPfTheQ88NNv4TdfZ@82WXrom422xrP/KSFU5UmiQdJACmfTAIQeNI3SEccg@0aqyAYiCEVHFIGjo9n3u45Cf8@hT/m4YrEPp2NWW3kYf@SOFHsk7L0wAWtr6UMDO80W5fK9XXK8sp4oPic6VNZoj9kHMwOVMxA@T59U7kHR26dKaX2IKPYleYhpHdwZMjaU4oaCgFoOr1l8zbvzBkcw5B1RhMyGXGQ@MYOjnHnhG1w4f7Ucp@pQ9uVpHQbzdeLJYMch74D7eONymStxPqbXBT4iPsM@eP9wxnPaLE4g9ysora0mm8hD0Gve2Tz9dt51EfLe6QeV8s2Xj0g5SMFOaXscrn0U2NvU7C7KO5@wcVIdzKaHCuFwxvk3reVftjWlb2usV8V/qh1RwypwBRtGimKioylFlUms1kmuy95Va4gtlC5I4k5nF6kdpYAhr93i5jMruGXeP1Tj9mnzgPQg7dvtkoUBwMdDCydjm80do38f6Gm@Z5ImxgiVF1IE5CktBX5patXnMuSXpzYd9kV8truULkhOBCpzLXQU9MmXDRhFP0D "PHP – Try It Online")
**BONUS - Encoder with line breaks and comments:** (not updated)
```
$a=$argv; //arguments short alias
$b=$a[2]?$a[2]:$a[3]; //argument 1 defaults to 2 if missing
$c=$a[3]?$a[3]:($b?$b:$b=1); //argument 2 defaults to 1 or both default to "1"
$t="/([^a-zA-Z0-9 ]+)/"; //breaking on anything not alpha or digit or space
preg_match_all($t,$a[1],$s); //saving breaking chars for later
$r=preg_split($t,$a[1]); //splitting at breaks
for($i=0;null!==$d=$r[$i];){ //for any non null split
if($j=strlen($d)){ //if it has a length
$n=-$b%$j; //modulo for shifting
$d=substr($d,$n).substr($d,0,$n); //the shifting
for(;$j--;){ //for every char
if(' '!=$e=$d[$j]){ //which is not a space
$n=($t=ctype_digit($e))?10:26; //char code range depending if digit or alpha
$f=$c%$n+$e=ord($e); //new char code and save current one
$d[$j]=chr($t&$f>57|$f>122|$e<91&$f>90?$f-$n:($t&$f<48|!$t&$f<65|$e>96&$f<97?$f+$n:$f)); //applying char code $f or using range $n to calculate if out
}
}
}
echo$d.$s[1][$i++]; //display current split with breaking chars
}
```
**BONUS 2 - shifted version of the program with -2 / -11:**
```
crixdc puj($p,$q='',$r=''){$q!==''?:$q=$r;$r!==''?:$r=$q;$i="/([^p-oP-O9-8 ]+)/";tveg_irwbp_apa($i,$p,$h);$g=tveg_axihe($i,$p);gud($x=9;aacj!==$s=$g[$x];$x++){xu($y=gatchi($s)){$c=-$q%$y;$s=qhighj($s,$c).qhighj($s,9,$c);gud(;$y--;){xu(' '!=$t=$s[$y]){$c=($i=netri_vxisx($t))?09:15;$u=$r%$c+$t=sdg($t);$s[$y]=grw($i&$u>46|$u>101|$t<80&$u>89?$u-$c:($i&$u<37|!$i&$u<54|$t>85&$u<86?$u+$c:$u));}}}$g[$x]=$s.$h[0][$x];}ijgc ydxcgt($g);}crixdc quj($p,$q='',$r=''){ijgc pgt($p,$q!==''?-$q:'',$r!==''?-$r:'');}
```
EDIT: saved 10 bytes by refactoring to remove brackets + replaced `''!==` by `''!=` + replaced logical operators `||`/`&&` by bitwise `|`/`&`
EDIT2: saved 1 byte by using `$l=strlen(` in for declaration instead of `''!=` and reusing it after, but +4 bytes correcting a bug for `$f<65` picking numbers, changed to `!$t&$f<65`
EDIT3: fixed bug of prematurely breaking first loop when string begins by a punctuation, forces new `if` to prevent division by zero, but uses split length `$j` to shorten second loop declaration
EDIT4: improved with a function and advices from 640KB but didn't want to go too far while questions not resolved and didn't want to end with same code - gave up default values when both arguments miss, supports now zero shifting
] |
[Question]
[
## Background
Malbolge is truly intriguing language. But programs written in it are also extraordinairly huge (and in some cases, unpostable on PPCG).
Your challenge (shall you accept it) is, to compress and decompress given normalized Malbolge program. Devise your own lossless algorithm. You may compress your data further using an existing algorithm afterwards, but you must cite the algorithm used. You may use dictionaries.
## Input
On the input, there will be given (in most cases very long) string, containing only following characters: `i</*jpov`. Example data:
```
iooooooooooooooooooooovoooioooipooooo<ooooooooooivojo<<<<<oio*ioooooooooooooooopiooooooooooooooooooo/jpooooooooooo
```
[Example](https://raw.githubusercontent.com/KrzysztofSzewczyk/codegolf-submissions/master/h0.mn) bigger chunk of data, 86 kilobytes big.
## Output
Well, not very much to say about it, output depends on the algorithm.
## Rules:
* Input taken by your program, compressed, and then decompressed, shall be identical.
* Submissions are scored by the following formula: \$ \frac{Compressed}{Original} \times 100\% \$, applied to the example 86 kilobytes big chunk.
* If a submission abuses the fact that only one example chunk is provided (eg. by hardcoding it), I reserve right to add more example chunks.
* Standard loopholes are forbidden, I/O rules apply.
Note: 7zip with PPMd algorithm manages to compress the code with 2,95% score.
[Answer]
# Score with test 1: 38.6%, Score with test 2: 4.9%
# Compressor
## [Jelly](https://github.com/DennisMitchell/jelly), 97 bytes
```
ṡ2ṢŒɠżQƊ1ị>ɗƇ3NÞḣ8Ṫ€,‘ɼ$€Ẏœṣ;@W}ɗjƭƒ
7©ṛ⁸“i</*jpov”iⱮ’Ç31¡
“i</*jpov”iⱮḅ8b256,ÇĖF€LÞḢL;L};÷/$ʋ,ḷɗ
```
[Try it online!](https://tio.run/##7V1LiyTHEb7rZyw6NQuLJGwLdjE6@bQYdNLd4MMkgszTgg@CtcAsWOCDDFoLP7Ckk41t8Ek7sk4a78L4X/T8kXFPd3W98hXPrJ6uGCGpujIzKrPyyy8jIjOy3C8//vhXt7fby6/e3V5@/frz67@@/v7DN799Z/ufz356/fLNi/d@fvWX7atv3t9e/v3m0388vHn@h@vv395dbb/73evfby@/efzBR59cv3Rv/vnm87d@8sPftpd/vPn1q5vnf7p48mjjgn928/zPFzf//tfN8y@vXrz3zg9fvRWnbV/95v1fvPujHz@8evHfL362k/307pFfP3389JPHV98@evt/nz3cvvr2@uXt1Ytd4u3tgwuf@nu2@/cu5SLsfz4ZUi6eeeef3P3tMmyi0iEl75ELo18PHmYeKvrM7J9zh/8E77riftNd7h7cXd5V4Xh3/2t@d38Z3FCH/m53ub8eMmzGP0Ylupxhkrrxfvzseeqx5uF4Nxze79390P3/INQdCvc1GvKN7m98VLfajU0yC@DW3SsbVyNZXbcJmY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TTa@1XSe1iloPAxumlscGmenFPHj0hczZmutrNPCBTmGOnJKbNtCea8QQDI2KWxK1n5qzQAsFDpxU4epa54tVn1anWoUgVg0FKAzRvGSE09PE1OCoTBqBKaXAaTfT1C2@DS3xwPcVBVNgLhpjmjHelNzScxeeFxA0LOSncYUk5f52FnkaBjqupTs@4zHGTUo0Y9rb07DM257I4eQ8fIBxJVQWchwJ5mzcj0zKn@IKOeZN0b/yzFPy2/nw4z2wHlEpBa5eewmN@GUASV6mnJMPigt6KeAfOUjVEfGhzOpH2ql@o8dK5zUZrlwVMPHDrYj3YqrkNQ8VIVcNaKMPArlbLAEGMQwB5iwsLBGm1omZkE2euaq0YQBED3oWfxcNZzR3UKYaNC84w@1NCncsB5RzfV1QcWSQiio/I9KhASOKG4NgFUyUNlQqAOZxYCzGBgGQxAgKBdmKzpoH4mOZwezEYI1OV9rSmBjQwpf4PNGcQQUQlAVLbJgcMxVr7Zta4YSpiQbKCImRdolzR6Y9AqLAhhFwOhExdYpKAF49gsgTmYjaJWCJIDfcGCRBArmkaEJhI4YGRwUvn6m3CQxBnPHUCTVGLVcyGYsNwWqFAHm1KQsdnq/S/t0UZvBVxTOEwz/9ZJQEvIHYaNgjEPGEVHAds1cjBB6yf4xRFzfRH6H0IUkhiQUz@A5GDr5XKsIAmGRroI0tCxhXXl2UTCIcbafgElD5s7gF8FxLFGm@h9Ib3CzBIZZwcUI5IaRtkyKUxIPL3T7BBNeGidxskvWoeLTSiEr/ZoUgX8m6dAxacODDNGtFEhttgKBQGi983KkNyus8DMUT32p679VkpO8WJThuQaq@RZ8LBoDnz8x8riPVrFCmI38rTxcWJ38aC4w2wRxXV5YUahfdwH6GhDQMbmG9TmP4WZha9v1M9pQmqoZqhAogwbgkVUESGoomaycGlDbwIRmTSgVGHTBXCxw2N1W9lTITHLYvBJwgwTiZjEpnipGSbZA3bhakZRgFkoG2laefB/ "Jelly – Try It Online")
# Decompressor
## [Jelly](https://github.com/DennisMitchell/jelly), 44 bytes
```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a3Vqnmdr//esyTZs5znLprjD1943qMGHHaRZ3crnAcHT4T9ysbsMTf/nPchUXBmoctrmpbbj@@l6YCMIz@rFCbMvOHS1c2TN3Yi2XV7ST/8C "Jelly – Try It Online")
## Explanation
Uses two different methods and picks the one with the shortest output.
Method 1: Convert the input from base 8 to base 256
Method 2: Repeatedly finds the 8 most common sublists of length 2 and replaces them with an integer between 8 and 255. The dictionary is stored at the beginning of the output.
The first byte of the output indicates the method used.
Input to compressor is a string of Malbolge. Output is a list of integers between 0 and 255. This could easily be encoded in Jelly’s code page if preferred. Input and output to/from decompressor mirror the compressor.
[Answer]
## Retina, 47.25%
**I know this is currently uninteresting, but this is still a WIP.**
Cheap algorithm to compress Malbolge programs.
```
ooooooooo
a
oooooooo
b
ooooooo
c
oooooo
d
ooooo
e
oooo
f
ooo
g
j\*
h
jah
k
```
Decompressor:
```
a
ooooooooo
b
oooooooo
c
ooooooo
d
oooooo
e
ooooo
f
oooo
g
ooo
h
j\*
k
jah
```
## Explanation
This simply shortens the source by replacing the o's, after noticing that there are too many o's in the Malbolge program. [Try compressor online!](https://tio.run/##7V3bkuMmEH33p/gt7/spedkkm2RIVVClUvn9yYwt68bt9A15TE@qsrKAFojDobuh0T8//n37@/tP7@/x8Xf5flkuf3lcXn6dry6/3S8uP27/Xn7//OfyxyX8fL38eQnf/7z89f7@Fgt/nwlv0@3y2@bufzHEb59/HxmuSeGpKC73F8L9f1MMc/F4nS8/Hjxfflbhcff263j3djmFtQ7L3fnydr1muG5/bErMOadd6jXG7bOPqY@aT4@7U7g/OIY5e5iFhnvhpUZrvs39a0zq1rpxzWYBbn2@sm01stUN16lQcC756Mhp16@P4ov4uM/w8Xt@PJhvrt8Cmyn/tEflF2lxKjx1qqXPGVaQToenTdtXFvcZjm27vcJCljnPZjRMtWZtHrh/A0mzsunrcHk8bdPK5Wlxn/Ao/WhGJimuY3YRvLaq2IxNL@3F5qSm9@8pYfsjbca2IpnSufu36@0PQhs2rzcjNXv/Prx2P@uI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7PVobkcZ0RZo7otT9x7TeSs4uXPGVI7rFK3gUP8@bA@39MzN8jla8g9iBPmjVO7CkeFHdkW0RxX16YUWgf9wEutCEgk@cb1OE/hZmFr2/E72lCaqjZUIF4GSYEi6giQlBFs8nCpQ29CURk0oBSRZ4ugJsdBqvbyt4KidkWg08S2TCR8ElMipeYYeK9YBeuZgQFZAtlIU0r89n/ZrMvZlesn4rPy8OyWG@L1faPzWq3PKweDqv94flluV/tH9/Pivqv2q23h4f5f@rwogmfPxXrx2PMa/GxeF1tHxohj3baf60/7Za7v@qAf7@Y3Wp@imxe@br@9LxdblZPxcOL2VS71X5vdnUxVu3TY1Oe@nFjts918v279WG12T@cS9P8XdKuPtcFaDNa5Wj@WpnHdPYrHtqYNv2yftwdTi3y8WMn@1Mx/82Wdkzz2RRbcyg2y8PL1@LwdVWY3fr39Xb5Or@KPDXHl/n3S7Xff/jH3398b9rMKsEvr@/f/fq3H3O7CR9//h8) using standard Python libraries serves as a baseline for other advanced approaches.
Here is the outcomes for common compression algorithms.
```
Test case 0
Library Score
gzip 50.000%
bz2 64.912%
lzma 87.719%
Test case 1
Library Score
gzip 3.908%
bz2 2.968%
lzma 3.826%
PPMd 3.161%
```
NOTE: The PPMd algorithm score is obtained manually using 7zip to compress Test Case 1 into a zip file using a dictionary size of 16M and word size of 16 on Windows.
[Answer]
# [///](https://esolangs.org/wiki////), 0.00116%
[Compressor (large test case)](https://tio.run/##7V15d9vGtf//fQpRiUwtMYeiKGthqcWUImuXuy@nr/tidAHadN@OLLdu0jZ9raW2ahKncZSmcdKmlRVFcmP3nUPYyTnOOTh6X8FfJO/eOwOuADEDDEjHhC2CwOzL7/7uvTMA@MTXP/fEV7/0xHvvsf9i8GeY4h975ypcmsagZRmD7N4VvKBwZx@TWYY5aFqGBRHODQwYZM4BfDsH71w1JQ/MeYOXypxDXvU7V5033HiowDk0oSJnHxK8SWW7/yHatJxDagVEGxZkvMGcIypOhPKcJoYfYzgGYZSJwZUzqAdTGewEe8HT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TOSNyo0LbZKgsChdlPvAydt@t0QHMEvvYn2PoNyFmPl0Rl6Nxj1fkueLmnOdSf/@iy5z3a9ayg6o087VnjVL2LR4k7El8kxn15zYwS7sd9JBfaFCCT6Bulm/9i0CzR7Y3g9zQpWqiJoyLzlGEbwaLVEAlhiiYuS1TaiE@BaFEaslSRqAvJzQ5T1bbV@1ZIlW0xeSWROCY6nklsK16CHBPfF@zKmxktC0g8lEHdtPLee/8P "/// – Try It Online")
[Decompressor (large test case)](https://tio.run/##jVprVxvX1f7eX6HBlgeBrSMJgQSqBFgimIsQ7v2yeknbtPE07Uyb9u29CxPiOG7dC6KtkhjXNokTEjexwBiI7XQtjR2v5ax1Fu9f0B/J@zx7zwicT2@MzpyZ2fucfb@cyYsvPPvi88@9@Omn5nMGf@F9E94by9td2yrb1tcCe9du2ebPbHPIbvt2267ZvfqT1THberIafkj4e@Zc@De7Njg6Ge7YVnf5Jduq29bBA9u2G91Xrwliv232sInzobG7FdcFcPfiZfyFb6U4WV7hI9t0cTNuN/xj4b5/LGebGeLsGzwd@2H6ZLj3ZHXese3wLqiw29lyBYjAS@lauNHNibQnSLknq3Y3Hy2vILnx0jPceHfMNvkWc9sCHACIt2vG@NS23LJwZJsAOHiQ7i4v21ZlLMdXea42752oEOGuqfnHKmPhJoBOkh5s211ag6Qa2e5Scwz3KeyCF0uvYyOi7Jizg6N2xx8I73iRmG2zv94T1Fheyb54mdB3TOLxum0X42Hn4StJuxG@XQy3j0PiKrjcuG2nD7YIv23sfqYYvmP3B7vLL2dmD@53l674yRn8Jex@uGVb89DP8nK@Tugt05dQyL7Ewf1Tdq0vbI87YKlaPw4CGrq8cNo2iRm7s9iH3@AwxuTBfbsd6GShe/HqpN1fCG/bFmFvm/AD2YXm0l0@b5tZV9RuW@OO3TgBwo/bZl7NplklygdG17Abie7FS7IgNjh6wwu0/76uM2/bRHvfLC6ErWDGW@zzkqeTMx7@ina/zwv/IxxEUvyPKZ4uynrhNdDjZsNbJ23zeGwb0LdL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ZAC48LEKYtccUgaZ@0HPToQ6BbprsCBu@DEM5MkXMSHfU/e3O1hdJndMBPH/GoixbTx2GthI9vUDL1Bpt7mmrIp73xsIAgEEludH/5nPhfc//fT/AA "/// – Try It Online")
[Compressor (small test case)](https://tio.run/##jVnpchvHtf5/nwKgBA1AmmgABEmQMEBSAEVxAUllXyqLkzgxJ05mEifOnqIoW5adODchmIRe5EiGN9qObYimSNmSb9W0aFXJVV28r6AX8f2@cxqg7MqPKxE9Pd2nu8@@9Dz26EOPPfLwY59@av7L4C@M/D9z5zJeo3AwjsNBc3eTLzLuugSLw2gwisMYE@4aBwaN28XT7d65HP0/G@Pe112N29Oj71x27/fmcYDbi3CQ6wLguuzd@4/pKHZ7ggWmwxgLrxm3L9v5UV0ZcfyA4xziVMThfg/nECo0R6RCYaJjoOgzUOaIO@GsLjADkoPYJDZHN4nbnmAB6DVzdEs45K67a3c37266Xf74n09idDzS/39g/nfjPhKNaxPn2LgtGSWbt4/PBjahcTdEQMZ15HxOyXTXuB3OHB2QAGJh7j19hTBbroPfXuw6YB52vnfpGT1zG91n2e32/mPgJQ60MbvHHTbO4/XoGslSBm9hc9LSFnFg3wMAbSgrZMEF9Ek/uk9wuBO5rYg4@MM3nhSxQEx8uSgrY5PyaJh0nyozwKM9NZ89fBuMbHuNEBROKEF7x2Ay0VMVHC6qclLYEZlMnyhu5reKjvvHG58SasCpQJQMe2R1ZNfkhLoUyBj6zHbHuHU@i82BeUAZkjHD3A0SzAu1oSko/vumKB2KpeT1woygA16SnWVZ77ZSZpQbwJbGZAPgMC47bpkKnnFoJlSKlOGksDY0Vd0HtNSEBB5SJ@a30mZKj4XwpgU6NjN83gB90JaB0Jzm6zbWNvTAjmkK0VDfWe779BWc1s669kiP1jME3EmbOUFsdyJjznLFzQEzr7LeMgvSicyiYEHVW1Lmtk3Lq4FZloNJ/Ap6GWj/qjAhHjfnhKDztWItB8zJ9KW06zZnCX4@KJJnl55FOz2CGSqB@YLy9MC1AVEq1hrTmC6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/DVCci7gvmqkxFzhWa5wrN9hIMq8dI8rvealyiwIjK8YtZtU1HfoJwu6alU@WFR7rUGzBwHfAuaXjYYdYW/EGfV8Dnqkc3ie9SUj1WK5qoUROp9a1BlJJyi5pBXrjD3UF00Ur8lHZaKiRDNSp2OfdnPiu0PC8hdMOjIH8dmy9tapeWmiBbAVg37eaOoSNytXmedymgRKnwJGUAD854x0leWo3tvmN9mampybjYWJFgFvos@xZ9luFDBZNElRXEO6LuatBWN3JMXXDQRL0c@j6oArYTaH8pChdZZlIn1qBvUfU/UZw4qKx2jTxm7ykOcpo8GrSQEcfnCeMgdb/7eMSQ3bCClV7Cxucdr00gfVNok9mEAmWItJHBoHHVy6AsK0IirzIEmQS4Am1hgiLOWL6agJ@KQI0khqgRtyMmJ84W/YsJtiDsgb@W5N7ocoeuogx21lkywf8atXBitwxTRWJOWnsIBPnk@aWOOSNmgsSCYbgaf6PuR@0LDSJBEpCpf79BsUoyTX5ROycuLIatFa/uH86Nf7JEoHquM4Kdzxntwvuo9PtQF2zBzseXx9@xDUf5LmeOU@MQKJzg51zUkCzwIpyy4YfyDwhA94EaUAOlhdBpGIKcvHq1rlQnVskLdkvhzx9iQBT/wvCQx6Qo5qkYZHAvSfPLhEdlsyfcVIUQtugyO7o@X1Y1ZlETQryo@EOa4CBfrUJYxfQ5/vqQFhYbstlGMtn/zCB1Twoi8YryqH/BFS3/AqvPSe9P6RqYP7FIIXsND2zvHBvXhfPIIwZaeDPZTfbdLt@aTHP5zabd5T2QdbxleoQ6AnYISLPZhVZAC48LEKYtccUgaZ@0HPToQ6BbptsCBu@DEM5MkXMSHfU/e3O1hdJrdMBPE/DcTYNh47DWwk@/qBF6i021xTVsW97w0EgQACy/Oj/8xnzjmO/wu7898@cTmz5yTF@Z988v8 "/// – Try It Online")
Explanation: simple dictionary-based approach. The decompressor performs the same substitions as the compressor, but in reverse order. Note that both these programs take input by concatenating it into the source, as is usual for ///.
] |
[Question]
[
Define `f(a,b) := a if b=1; a^f(a,b-1) if b>1` ([Tetration](https://en.wikipedia.org/wiki/Tetration), where `^` means power) for positive integers `a` and `b`, given four positive integers `a,b,c,d`, compare `f(a,b)` and `f(c,d)`.
Your program should output three constant values to mean "greater", "less" and "equal".
Samples:
```
a b c d f(a,b) output f(c,d)
3 2 2 3 27 > 16
4 2 2 4 256 < 65536
4 1 2 2 4 = 4
```
Lowest time complexity to `max{a,b,c,d}` win, with tie-breaker code length(the shorter the better) and then answer time(the earlier the better).
## Complexity assumption
* Your code should handle `a,b,c,d` up to 100, and your algorithm should handle all legal input
* You can assume integer calculations (that your language directly support) in `O((a+b+c+d)^k)` cost `O(1)` time if can be done in O(1) for 2k bit numbers if k bit computing can be done in O(1)
* For example, both plus(`+`) and multiply(`*`) can be done in O(1) for 2k bit numbers if k bit computing for both can be done in O(1), so both satisy the requirement. It's fine if multiply can't be done without plus, or even if both can't be done without each other.
* Float calculations in `O(log(a+b+c+d))` bit precision in `±2^O((a+b+c+d)^k)`, takes `O(1)`, with same requirements like integer calculations.
[Answer]
# [Java (JDK 10)](http://jdk.java.net/), 295 bytes
```
int f(Long a,long b,long c,long d){return a>c?-f(c,d,a,b):a<c?b>d?d==1?(a==2&((b==2&c==4)|(b==3&c==16)))|(a==3&b==2&c==27)?0:1:b-d>1?1:f(t(a,b),1,c,d):-1:a<2?0:a.signum(b-d);}long t(long a,long b){long t=1;for(;b-->0;)t=p(a,t);return t;}long p(long a,long b){long p=1;for(;b-->0;)p*=a;return p;}
```
[Try it online!](https://tio.run/##bVFNb9swDL33VxAdUkiDbEROsAH2FAO7FehOPQY5yJ@TF8uGzXQYUv/2jJKSrigGw6Qe@fhIUZ1@0VFX/bqYfhwmhI5w3Gv8GX837aPFuq2n7K486nmGH9pYON8BjKfiaEqYUSO5l8FU0FOOPeNkbLs/gJ7amXsqhKoeFNj6tweMZz5xHByX2FjPOBMh8AHOG5HQt1nELbD1ge37gHShxeMl6HnTDBMLwoBpUOZvws9/Zqz7eDhhPNKkeLSsjxuG@/VBAO6lt4m3mwO/jul6uP/9bbHGidBgGamAEeBcd2v0sU3D7lcVfAIyiszKruy9MKIT/zYSI6NAaOmaXZxgw57oJqCFuxAUwZXBVfw81XiaLOhdmUcNK0UltCh4qr@VebGr8kopmTOtVPLAWOFcqdSWv7rzxp3lF84Jagdv@eQrz9epTIuo2slcprQc5lRp3dSAp5Ek/YQoOp5Na089IybPFj8T@s2/zcvPIapk5l4lK6Jot844qpEkkWfX@fFaPf63evxQPX5W@lY5ZstlufwF "Java (JDK 10) – Try It Online")
Codes:
* `1` if `a^^b > c^^d`
* `-1` if `a^^b < c^^d`
* `0` is `a^^b == c^^d`
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~30~~ 19 bytes[SBCS](https://en.wikipedia.org/wiki/SBCS)
```
{f←*/⍴⍨⋄×(f/⍺)-f/⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///vzrtUdsELf1HvVse9a541N1yeLpGGpC3S1MXRG2t/Z@uAFSgAFZWDRSwNbQCygIVAkktEKujHSiqa1iLRS8X16O@qSDdxgpGCulAbAwTMIEKmCAEDMECRv8B "APL (Dyalog Unicode) – Try It Online") Thanks to @ngn for saving 11 bytes by defining tetration in a much clever and shorter way:
```
f ← */⍴⍨ ⍝ Define f to be the tetration function
⍨ ⍝ Taking a on the right and b on the left,
⍴ ⍝ creating an array of b occurrences of the number a
*/ ⍝ and then building the tower of exponentials.
```
Now if I have a vector with two integers, `f/` applies the function to those two integers, e.g. `f/ 2 4` gives `65536` and `f/ 4 2` gives `256`. We need this in our main function:
```
{f←*/⍴⍨⋄×(f/⍺)-f/⍵} ⍝ Dyadic function (g) expecting two vectors of 2 integers, e.g. 4 2 g 2 4
{f←*/⍴⍨ } ⍝ Define the auxiliar function as above
{ ⋄ } ⍝ and then:
{ f/⍵} ⍝ Apply aux function to the right vector of integers
{ (f/⍺) } ⍝ Apply aux function to the left vector of integers
{ - } ⍝ Subtract the two values and finally
{ × } ⍝ get the sign of that difference.
```
This means my function returns 1 if the left integers give a larger value, 0 if they are the same or ¯1 if the left integers give a smaller value.
My original submission had a recursive definition of tetration:
```
{f←{⍵=1:⍺⋄⍺*⍺∇⍵-1}⋄×(f/⍺)-f/⍵}
```
with tetration as:
```
{ } ⍝ Dyadic function expecting 2 integers
{⍵=1:⍺ } ⍝ If the right argument is 1, return the left argument;
{ ⋄ } ⍝ otherwise (separate previous statement from the next one)
{ ⍺* } ⍝ Take the left argument to the power of
{ ⍺∇⍵-1} ⍝ the recursive call of this function with same left argument and decremented right argument.
```
[Answer]
## Haskell, 46 bytes
```
a#1=a
a#b=a^a#(b-1)
(a!b)c d=compare(a#b)(c#d)
```
Prints `GT` for `>`, `LT` for `<` and `EQ`for `=`.
[Try it online!](https://tio.run/##Vck7DoMwEAXA3qd4lil2ixQ2dJGvEunZRgLxFcn9nUQ00M4MfE/9PNdK5yOfdCnyRSfp4dUIbdKMEvO27Dx6@bVKdkXrwnFFRNkMsB/j@kEDaW1QBLRX607r7ub/FuoX "Haskell – Try It Online")
] |
[Question]
[
**Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Update the question so it focuses on one problem only by [editing this post](/posts/95705/edit).
Closed 7 years ago.
[Improve this question](/posts/95705/edit)
This is going to be relatively quick...
## Challenge
Given a lower-case word as input, calculate the Pearson's Correlation Coefficient between the letter position of the word (nth letter within the word, x), and the letter position within the alphabet (nth letter of the alphabet, y).
## Background
Pearson's Correlation Coefficient is worked out for data sets x and y, as:
[](https://i.stack.imgur.com/3XX0Z.gif)
where **x** and **y** are the respective data sets as explained above (and further below), and **n** is the length of the string.
## Examples
```
Input: forty
Output: 0.964406804
```
**Explanation:**
```
Letters: f o r t y
Alphabet Number (y): 6 15 18 20 25
Letter Position (x): 1 2 3 4 5
Length of word (n): 5
```
Correlation coefficient is worked out from the above formula.
```
Input: bells
Output: 0.971793199
```
**Explanation:**
```
Letters: b e l l s
Alphabet Number (y): 2 5 12 12 19
Letter Position (x): 1 2 3 4 5
Length of word (n): 5
```
Correlation coefficient is once again worked out from the above formula.
## Rules
1. Input must provide the word as a lower-case alphabetic string with no spaces (assumed input). The delivery of this string is entirely up to you (file, STDIN, function, array, carrier pigeon, etc.)
2. Output is in the form of a numeric that will, by the formula, provide r, such that -1 <= r <= 1. Delivery of the output, once again, is entirely up to you.
3. [No silly loop holes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default?s=3%7C0.7643)
4. This is not code-golf, as I'm sure there will be many languages that may have native statistical functions. Instead, this will be a popularity contest, so most votes wins here, so make your entry count... I'll be throwing in a bounty for the most creative answer that attracts my attention a little later down the line...
Any questions/comments?
[Answer]
## R, 63 bytes
```
s=strsplit(scan(,""),"")[[1]];cor(match(s,letters),1:length(s))
```
**Ungolfed :**
```
#Takes the input and splits it, letters by letters
s=strsplit(
scan(,""),
"")[[1]];
#Finds the positions of each letters in the lowercase alphabet, and correlates them with
#their position in the word
cor(
match(s,letters),
1:length(s)
)
```
[Answer]
# Python
That's a lot of traversals, let's do all we need to do in one pass for efficiency.
Since `y` will be `[1,2,...,len(x)]` we can calculate it's sum and sum of squares using the formulas for triangle and square pyramid numbers respectively.
...and there's really no need for two square roots since the two are multiplied we can just square the product.
```
def p(l):
y = sx = sxy = sx2 = 0
for c in l:
y += 1
x = ord(c) - 96
sx += x
sxy += x * y
sx2 += x * x
sy = y * (y + 1) / 2
sy2 = sy * (2 * y + 1) / 3
return (n * sxy - sx * sy ) / ((n * sx2 - sx * sx) * (n * sy2 - sy * sy)) ** .5
```
[Answer]
# Python 3
Simply uses the formula in the challenge. Doesn't use any libraries like `numpy` and friends.
```
from math import sqrt
def correlation_coefficient(word):
alphabet = 'abcdefghijklmnopqrstuvwxyz'
x = list(range(len(word)))
y = list(map(alphabet.index, word))
n = len(word)
top = n * sum(a*b for a, b in zip(x, y)) - sum(x) * sum(y)
bottom = (sqrt(n * sum(a ** 2 for a in x) - sum(x) ** 2)
* sqrt(n * sum(a ** 2 for a in y) - sum(y) ** 2))
r = top / bottom
return r
```
[Ideone it!](http://ideone.com/gY3QV7)
] |
[Question]
[
**This question already has answers here**:
[Polynomial Interpolation](/questions/1729/polynomial-interpolation)
(3 answers)
Closed 7 years ago.
For this challenge, **when given a list of (x,y) points your submission needs to output a polynomial function that goes through all of them**.
For example, if your points were `[(0,0), (2,5)]`, you could return `y = 2.5*x` or `y = x + 1/4x^2`.
* All points passed in will consist only of integers
* Two points will never have the same `y` value
* Your function be of the form `y = a*x^n + ... b*x^m`. Reducing of terms is allowed.
* Constants (the exponent and coefficient) can either be in decimal or fractional form. Decimals should be accurate to at least 3 decimal places
* You should be able to handle an arbitrary number of points
* Output must be a string starting with "y=". Whitespace anywhere in the string is fine.
# Test cases
Note, the given output is not the only valid output, just one of the possibilities.
```
(1,4) -> y=x+3
(0,0), (1,8) -> y=8x
(0,6), (-1,90) -> y=-84x+6
(6,4), (70,4), (-1,-6) -> y=−10/497x^2+760/497x−316/71
(4,5), (5,6), (6,7) -> y=x+1
(20,1), (-20,1), (0,5), (10, 4), (11,12), (17,4), (2,4) -> y=488137/10424165400x^6−643187/473825700x^5−87561839/10424165400x^4+550999039/1042416540x^3−21590713027/5212082700x^2+300110420/52120827x+5
```
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so make your answers as short as possible in your favorite language!
[Answer]
# [MATL](https://github.com/lmendo/MATL), 38 bytes
```
ynq3$ZQ'y=' '%+fx^%i'btn:qP&vYDh1J3-h)
```
Inputs are an array with the *x* values and an array with the *y* values.
[**Try it online!**](http://matl.tryitonline.net/#code=eW5xMyRaUSd5PScgJyUrZnheJWknYnRuOnFQJnZZRGgxSjMtaCk&input=WzYgNzAgLTFdCls0IDQgLTZd)
```
y % Inplicitly take the two inputs, and push another copy of the first
nq % Get its length minus 1. This is the required polynomial degree.
3$ZQ % Coefficients of polynomial fitted to those data (`polyfit`)
'y=' % Push this string
'%+fx^%i' % Push format string for `sprintf`
b % Bubble up the polynomial coefficients to the top of the stack
tn:qP % Duplicate and produce [n n-1 ... 0] where n is the polynomial degree.
% These are the exponents
&v % Concatenate vertically. This gives a 2D array with the coefficients in
% the first row and the exponents in the second
YD % Apply `sprintf` to this array with previous format string. The array
% is read in column-major order: down, then across
h % Concatenate 'y=' and formatted string representing the polynomial
1J3-h) % The string ends in '...x^0'. Remove last three chars to delete this.
% Implicitly display
```
[Answer]
# Python2 + sympy, 61 58 bytes
```
from sympy import*;print interpolate(input("y="),var("x"))
```
[Answer]
# Matlab (with Symbolic Toolbox), 52 bytes
Using builtins for calculating an interpolation polynomial, and then converting it to a symbolc expression for pretty printing and back to a string for the actual output. This function takes two lists of coordinates, e.g. `[6,70,-1]` and `[4,4,-6]` for the fourth test case.
```
@(x,y)['y=',char(poly2sym(polyfit(x,y,numel(x)-1)))]
```
] |
[Question]
[
There is a parade marching through a city! There are 3 main groups of marchers: the (B)and, Poster (C)arriers, and (F)lag Holders. Also, every (P)oliceman in the whole city is on duty.
Flag holders (F) can march anywhere in the parade, but two flag holders cannot march next to each other, unless three or more flag holders are together.
The band (B) has to be together. The poster carriers (C) all have to be behind the band (either together, or in two groups).
Given the number of flag holders, poster carriers, band members, and policemen separated by your choice of delimiter, print one line for every possible configuration, organized in alphabetical order.
Test case 1:
```
Input:
2 2 2 0
Output:
CCFBBF
CFCBBF
CFCFBB
FCCBBF
FCCFBB
FCFCBB
```
Test case 2:
```
Input:
3 3 3 0
Output:
CCCBBBFFF
CCCFFFBBB
CCFCFBBBF
CCFFFCBBB
CFCCFBBBF
CFCFCBBBF
CFFFCCBBB
FCCCFBBBF
FCCFCBBBF
FCFCCBBBF
FCFCFCBBB
FFFCCCBBB
```
Test case 3:
```
Input:
2 2 2 1
Output:
CCBBFPF
CCFBBFP
CCFBBPF
CCFPBBF
CCFPFBB
CCPFBBF
CFCBBFP
CFCBBPF
CFCFBBP
CFCFPBB
CFCPBBF
CFCPFBB
CFPCBBF
CFPCFBB
CFPFCBB
CPCFBBF
CPFCBBF
CPFCFBB
FCCBBFP
FCCBBPF
FCCFBBP
FCCFPBB
FCCPBBF
FCCPFBB
FCFCBBP
FCFCPBB
FCFPCBB
FCPCBBF
FCPCFBB
FCPFCBB
FPCCBBF
FPCCFBB
FPCFCBB
FPFCCBB
PCCFBBF
PCFCBBF
PCFCFBB
PFCCBBF
PFCCFBB
PFCFCBB
```
This is code-golf, so the shortest source code in bytes wins.
\*Note: It doesn't count if it takes longer than 3 seconds to run each test case. I won't use integers more than 20.
[Answer]
# Pyth, 56 bytes
```
jf&!},2\FrT8!:T"B.*C|C([^C]+C+){2}|B[^B]+B"0{S.ps*V"FCBP
```
[Try it online!](http://pyth.herokuapp.com/?code=jf%26%21%7D%2C2%5CFrT8%21%3AT%22B.%2aC%7CC%28%5B%5EC%5D%2BC%2B%29%7B2%7D%7CB%5B%5EB%5D%2BB%220%7BS.ps%2aV%22FCBP&input=2%2C2%2C2%2C7&debug=0)
[Answer]
## CJam, 49 bytes
```
l~"BCFP".*(a\s+m!:s{_"FP"-W%_$=\e`[2'F]e=!&},_&N*
```
[Try it online!](http://cjam.aditsu.net/#code=l~%22BCFP%22.*(a%5Cs%2Bm!%3As%7B_%22FP%22-W%25_%24%3D%5Ce%60%5B2'F%5De%3D!%26%7D%2C_%26N*&input=%5B2%202%202%201%5D)
Input format is `[B C F P]`.
] |
[Question]
[
**Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Update the question so it focuses on one problem only by [editing this post](/posts/48077/edit).
Closed 8 years ago.
[Improve this question](/posts/48077/edit)
**Introduction**
Elite was the first space trading video game, written and developed by David Braben and Ian Bell and published by Acornsoft for the BBC Micro and Acorn Electron computers in in September of 1984.

The Elite universe contains eight galaxies, each with 256 planets to explore. Due to the limited capabilities of 8-bit computers at the time, these worlds were procedurally generated. A single seed number is run through a fixed algorithm the appropriate number of times and creates a sequence of numbers determining each planet's complete composition (position in the galaxy, prices of commodities, and name and local details; text strings are chosen numerically from a lookup table and assembled to produce unique descriptions, such as a planet with "carnivorous arts graduates"). This means that no extra memory is needed to store the characteristics of each planet, yet each is unique and has fixed properties. Read more about this here: [Elite random number generator](http://wiki.alioth.net/index.php/Random_number_generator)

**Challenge**
Like the Elite game did, write a script which can procedurally generate a list of 8 galaxies each of which contains 256 planets. (You need to generate a total of 2048 planet names).
The 8 galaxy names can be defined before hand or procedurally generated. This is your choice.
**Output**
* Please post your script here and perhaps use [paste bin](http://pastebin.com/) or an equivalent to host your output.
**Rules**
* At a minimum your script must generate 2048 planet names and 8 galaxy names.
* Each 256 planets should be nested within the array of a galaxy.
* This is a popularity-contest! Try to make your code clever, interesting, slick or retro.
* This is not code-golf. As such, readable code is appreciated. Still, try to keep size low remember the original programmers only had 32Kb or memory to work within for the whole game.
* Repeats of planet names of more than 3 in a row is not allowed and a single planet name must not appear more than 5 times in the total 2048 planets.
* Input is optional and not required.
* [Standard Loopholes apply](http://meta.codegolf.stackexchange.com/questions/1061/standard-loopholes-which-are-no-longer-funny).
**How to get kudos**
* If your script also generates economy, government, tech level, population, gross productivity, average radius and comments about each planet.
* If your planet names look organic (doesn't have to be in English) but for example 'Lave' looks better and is easier to read than 'Esdqzfjp'.
* If your planet names don't contain profanity such "Arse". I only mention this because the original programmers had to do this.
* If you do this challenge in BBC Basic.
[Answer]
# Java
I just though I would start out this contest with something :). The names are organic and are generated on the fly. Run with any arguments to use interactive mode.
```
import java.io.PrintStream;
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
public class Main {
private final static int[][] frequencies = new int[][]{ //Generated with names from http://www.minorplanetcenter.net/iau/lists/MPNames.html
{96, 323, 512, 445, 222, 113, 407, 249, 514, 134, 740, 1287, 975, 3188, 212, 235, 13, 2131, 997, 909, 501, 398, 226, 50, 355, 165, 3223},
{626, 61, 8, 8, 877, 3, 3, 28, 322, 5, 7, 114, 9, 8, 425, 4, 0, 396, 44, 6, 260, 0, 7, 0, 51, 3, 40},
{607, 4, 129, 16, 287, 9, 14, 1728, 248, 4, 364, 139, 9, 8, 518, 7, 18, 99, 27, 41, 94, 2, 0, 0, 49, 42, 102},
{842, 49, 13, 46, 784, 17, 38, 45, 425, 18, 21, 65, 56, 31, 503, 10, 2, 224, 90, 70, 169, 13, 50, 0, 86, 37, 421},
{326, 203, 264, 375, 284, 128, 231, 143, 513, 67, 261, 1436, 399, 1874, 159, 179, 9, 2873, 940, 680, 206, 402, 180, 64, 317, 125, 1527},
{161, 7, 3, 1, 246, 170, 6, 6, 128, 5, 2, 61, 16, 5, 122, 3, 0, 253, 16, 28, 105, 3, 3, 0, 4, 0, 122},
{596, 16, 27, 27, 595, 8, 62, 150, 250, 17, 16, 134, 32, 100, 319, 11, 6, 272, 53, 28, 258, 3, 18, 10, 46, 18, 507},
{1360, 24, 33, 16, 1001, 2, 9, 14, 1219, 9, 55, 123, 93, 204, 683, 8, 0, 178, 55, 88, 383, 21, 50, 0, 96, 0, 453},
{1104, 148, 802, 362, 646, 85, 333, 97, 47, 160, 477, 789, 486, 2022, 309, 149, 15, 501, 1007, 614, 137, 142, 65, 43, 146, 147, 1598},
{309, 5, 6, 13, 183, 1, 2, 2, 224, 1, 15, 2, 4, 11, 354, 1, 0, 3, 15, 6, 132, 2, 0, 0, 8, 2, 103},
{1094, 15, 10, 9, 614, 6, 7, 166, 718, 9, 39, 133, 32, 36, 737, 9, 0, 137, 92, 20, 343, 17, 25, 1, 153, 2, 494},
{1219, 105, 66, 280, 1319, 87, 73, 55, 1259, 17, 77, 1034, 142, 35, 622, 80, 4, 38, 209, 146, 271, 67, 21, 0, 224, 33, 612},
{1790, 139, 135, 14, 591, 6, 6, 21, 859, 9, 16, 16, 120, 23, 599, 121, 5, 24, 87, 11, 252, 3, 12, 0, 78, 7, 249},
{1139, 159, 291, 744, 1103, 55, 881, 124, 1014, 72, 298, 80, 108, 519, 735, 52, 12, 110, 543, 495, 140, 27, 59, 10, 203, 120, 2308},
{72, 299, 215, 258, 167, 138, 150, 288, 124, 62, 282, 824, 456, 1643, 200, 199, 5, 1054, 815, 457, 408, 698, 201, 26, 145, 96, 1181},
{517, 9, 5, 2, 474, 17, 3, 204, 263, 0, 16, 95, 10, 6, 311, 131, 0, 147, 45, 34, 87, 0, 1, 0, 24, 2, 66},
{1, 0, 0, 0, 1, 0, 0, 0, 30, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 116, 2, 1, 0, 0, 0, 5},
{1518, 162, 175, 366, 1113, 44, 325, 86, 1469, 18, 204, 176, 211, 294, 1196, 58, 11, 294, 331, 505, 439, 57, 37, 4, 311, 44, 1349},
{904, 66, 452, 26, 770, 22, 17, 935, 522, 13, 439, 132, 109, 56, 570, 131, 10, 28, 442, 932, 437, 46, 44, 0, 68, 50, 1616},
{1009, 24, 60, 13, 1026, 20, 21, 607, 618, 29, 47, 74, 52, 35, 862, 12, 0, 399, 365, 481, 180, 18, 30, 1, 90, 125, 657},
{164, 191, 273, 207, 233, 51, 186, 75, 170, 55, 238, 344, 292, 555, 55, 72, 5, 694, 672, 274, 13, 35, 23, 32, 76, 82, 421},
{535, 3, 4, 4, 441, 0, 10, 3, 577, 1, 16, 28, 1, 12, 153, 4, 0, 26, 91, 4, 12, 1, 0, 0, 30, 1, 475},
{516, 5, 2, 5, 289, 4, 2, 43, 290, 0, 17, 32, 11, 26, 109, 2, 0, 25, 57, 1, 33, 0, 1, 0, 13, 0, 49},
{35, 2, 7, 2, 25, 2, 2, 3, 63, 1, 3, 5, 0, 0, 9, 1, 0, 4, 3, 5, 26, 1, 3, 0, 0, 0, 82},
{557, 38, 55, 46, 138, 22, 26, 31, 72, 18, 44, 126, 75, 143, 238, 31, 1, 81, 108, 57, 214, 9, 27, 9, 6, 8, 706},
{241, 12, 4, 22, 196, 0, 8, 146, 142, 0, 17, 11, 16, 15, 87, 2, 1, 11, 23, 11, 122, 10, 13, 0, 19, 49, 206},
{1282, 1246, 1014, 818, 540, 466, 757, 928, 351, 680, 1207, 835, 1479, 552, 375, 957, 40, 795, 1710, 952, 150, 455, 435, 34, 288, 226, 0}
};
private final static int MIN_NAME_LENGTH = 4;
private final static String INFO = "Type \"galaxy x\" to change galaxy. Type a number to get the name of that planet. Type \"exit\" or any invalid input to exit.";
private final static Scanner in = new Scanner(System.in);
private final static PrintStream out = System.out;
public static void main(String[] args) throws Exception {
if (args.length == 0){
long seed = hash(System.nanoTime());
for (int i = 0; i < 8; i++){
long galaxySeed = (hash(i) ^ seed) + 1;
out.println("Galaxy " + generateName(new Random(galaxySeed)));
for (int j = 0; j < 256; j++){
long planetSeed = (hash(j) ^ galaxySeed) + 1;
out.println(generateName(new Random(planetSeed)));
}
}
return;
}
out.println(INFO);
out.println("Seed?");
long seed = hash(in.nextLong());
out.println("Galaxy?");
long galaxySeed = hash(in.nextInt()) ^ seed;
in.nextLine();//Get rid of rest of line.
String galaxyName = generateName(new Random(galaxySeed));
out.println("The name of your galaxy is " + galaxyName + ".");
while (true){
String input = in.nextLine().trim().toLowerCase();
try {
if (input.startsWith("galaxy")) {
int galaxy = Integer.parseInt(input.substring(6).trim());
galaxySeed = (hash(galaxy) ^ seed) + 1;
galaxyName = generateName(new Random(galaxySeed));
out.println("The name of your galaxy is " + galaxyName + ".");
} else if (input.startsWith("exit")){
return;
} else {
int planet = Integer.parseInt(input);
long planetSeed = (hash(planet) ^ galaxySeed) + 1;
String planetName = generateName(new Random(planetSeed));
out.println("The name of your planet is " + planetName + ".");
}
} catch (Exception e){
return;
}
}
}
private static String generateName(Random rand) {
int previousChar = randomIndex(frequencies[26], rand);
String name = "" + (char)(previousChar + 'A');
for (;;){
int[] frequency = frequencies[previousChar].clone();
frequency[26] *= Math.max(name.length() - (MIN_NAME_LENGTH - 1), 0) ; //Hack, reduces name lengths.
int nextChar = randomIndex(frequency, rand);
if (nextChar == 26){
return name;
}
previousChar = nextChar;
name += (char) (nextChar + 'a');
}
}
private static int randomIndex(int[] frequencies, Random rand) {
int total = Arrays.stream(frequencies).sum();
int n = rand.nextInt(total);
int i = 0;
for (int frequency : frequencies){
n -= frequency;
if (n < 0){
return i;
}
i++;
}
throw new IllegalStateException();
}
private static long hash(long i) {
return (int) ((131111L*i)^i^(1973*i)%7919); //http://stackoverflow.com/a/9640543/4230423
}
}
```
It uses the same code to generate galaxy names as planet names. Here are some example names:
```
Kanipeso
Danlerg
Deigaji
Kanialu
Fulla
Tirr
Smanger
Anikuraba
Dotia
```
For full output of 8 galaxies [look here](http://pastebin.com/qZqTFE1L).
] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
This question does not appear to be about code golf or coding challenges within the scope defined in the [help center](https://codegolf.stackexchange.com/help/on-topic).
Closed 9 years ago.
[Improve this question](/posts/45157/edit)
We've all seen the famous painting of Marilyn Monroe created by Andy Warhol.

Let's try to replicate that effect with the usual suspects.
Your task is to write a program/programs that do as many as possible of the following tasks:
1. With one image as the input, generate four color palettes from that image and print a 4x4 grid with different "Warhol'd" color variants of that image.
2. With two images as input, generate two color palettes from each image and print a Warhol'd grid of the first image.
3. With four images as input, generate one color palette from each image and print a Warhol'd grid of the first image.
Of course, it would be cheating to hardcode palettes you like the best, **so your program has to determine a set of colors that is both distinct and aesthetically pleasing.** Warhol used five distinct colors in each panel, so five is your goal as well.
Here are some photos that you could use to showcase your program:
[](http://upload.wikimedia.org/wikipedia/commons/thumb/0/0d/Great_Wave_off_Kanagawa2.jpg/800px-Great_Wave_off_Kanagawa2.jpg)
[](http://upload.wikimedia.org/wikipedia/commons/thumb/e/ed/Underwater_World.jpg/800px-Underwater_World.jpg)
[](https://i.stack.imgur.com/xPAwA.png)
[](http://upload.wikimedia.org/wikipedia/commons/thumb/e/ea/Van_Gogh_-_Starry_Night_-_Google_Art_Project.jpg/757px-Van_Gogh_-_Starry_Night_-_Google_Art_Project.jpg)
[](https://i.stack.imgur.com/y2VZJ.png)
[](http://upload.wikimedia.org/wikipedia/commons/thumb/2/2a/Brown_bear_%28Ursus_arctos_arctos%29_running.jpg/796px-Brown_bear_%28Ursus_arctos_arctos%29_running.jpg)
[](http://upload.wikimedia.org/wikipedia/en/e/e8/Escher_Waterfall.jpg)
[](https://i.stack.imgur.com/fCTEl.png)
[](http://commons.wikimedia.org/wiki/File:Crab_Nebula.jpg)
[](http://upload.wikimedia.org/wikipedia/commons/thumb/c/cc/Grant_Wood_-_American_Gothic_-_Google_Art_Project.jpg/497px-Grant_Wood_-_American_Gothic_-_Google_Art_Project.jpg)
[](http://upload.wikimedia.org/wikipedia/commons/thumb/e/ec/Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg/402px-Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg)
[](http://upload.wikimedia.org/wikipedia/en/thumb/f/f4/The_Scream.jpg/475px-The_Scream.jpg)
Try to achieve a wide range of palette colorings and of course make them as aesthetically pleasing as possible.
This is a popularity contest, so the answer with the most net votes wins.
(Formatting largely copied from [Paint by Numbers](https://codegolf.stackexchange.com/questions/42217/paint-by-numbers), which was a partial inspiration for this challenge as was [American Gothic in the palette of Mona Lisa: Rearrange the pixels](https://codegolf.stackexchange.com/questions/33172/american-gothic-in-the-palette-of-mona-lisa-rearrange-the-pixels))
[Answer]
# Mathematica
```
namedColors = {Red, Green, Blue, Black, White, Gray, Cyan, Magenta, Yellow, Brown, Orange, Pink, Purple};
myRules =
Table[Rule[namedColors[[i]], RandomChoice[namedColors]], {j, 4}, {i,
Length[namedColors]}];
myImages = {--images here--};
Grid@Table[ColorQuantize[ColorReplace[myImages[[i]], myRules[[j]]],5],
{i, Length[myImages]}, {j, 4}]
```

] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win.
Closed 6 years ago.
[Improve this question](/posts/8357/edit)
## The challenge
The program must return a valid sequence of numbers into some rules
## Rules
* `x` is the size of the sequence;
* `x` cannot be less than `4` or greater than `9` (Thanks David Carraher);
* Digits of the sentence can't repeat, each one must appear once;
* All digits between `1` to `x` must be in the sequence;
* A valid sequence never begins nor ends with `1` or `x`;
* Into the sequence, numbers can never appear "together";
## Examples
If `x=4`:
`2413` valid
`3142` valid
`1423` not valid, because begins with `1` and `23` are "together".
`2134` not valid, because ends with `x` and `34` are "together".
Still don't get it?
Other example:
If `x=8`:
`28375146` valid, because don't start with `1` nor `x`(8), don't end with `1` nor `x`, and no numbers are "together"(no numbers touches, no numbers are the next or previous)
Sorry, I really don't know how to explain the last rule. Hope the example make it understandable.
## Additional Information
* `x` does not need to be an input, you can show the outputs for `x=4` and `x=9` working;
* Since **any language will be accepted** and, I don't know how all of them work, I will ask you people to help me with this;
* The winner will be the one who got more up-votes in 1 week, so please, vote the answer you find the best; I will mark it as the Correct one;
Good, luck. =)
[Answer]
## GolfScript (17 16 chars)
Assuming input on stdin and output on stdout.
```
~:^),(;{-2\^%?}$
```
Almost alphanumeric-free...
[Answer]
# Mathematica 38
This simply returns the digits less than or equal to `x`, in the order in which they appear below.
```
Row@Select[{2, 9, 6, 4, 7, 1, 8, 5, 3},#<x+1&]
```
The results from 4 through 9:

[Answer]
May I try to answer my own challenge?
## Javascript (35 chars)
```
a="1";for(i=x;i>1;i--)a=i%2?a+i:i+a
```
Outputs
```
document.write(a);
4 => 2413
5 => 24153
6 => 246153
7 => 2461753
8 => 24681753
9 => 246819753
```
[Answer]
# Haskell 78
```
a 4=[3,1,4,2]
a x=let b=filter even [1..x]++filter odd[1..x]in tail b++[b!!0]
```
This defines a function `a` that takes one parameter, the desired length of the sequence. This function returns a list of numbers in that sequence. I believe this works for `x >= 4`
This can probably be golfed further (I don't have that much experience in haskell)
### Example (in ghci)
```
ghci> a 4
[3,1,4,2]
ghci> a 9
[4,6,8,1,3,5,7,9,2]
```
# Haskell 25
This version is from before a rule change that now requires that every digit from 1 to x be used exactly once in the sequence
This should work for any sequence of length > 2 (even though the rules only required 4 <= x <= 9)
```
putStrLn$take x$cycle"02"
```
### Input
The number of digits in the sequence is stored in x.
### Output
x = 6 :: Int
```
020202
```
x = 4 :: Int
```
0202
```
[Answer]
# PHP, 64
If I understand the rules correctly, this should work:
`for($i=1;$i<=$x;$i++)echo($x%2?2*$i%$x+1:2*$i-($x+1)*($i>$x/2));`
If x is odd, this simply cycles through multiples of 2 % x + 1 to produce sequences like 357924681. If x is even, this does the same, but halfway through subtracts 1+x because 2i%x+1 would otherwise never produce even values.
[Answer]
## GolfScript, ~~22~~ 20 chars
```
~.1|,.+2%(;(@.1&,~;\
```
Outputs the following sequences for the inputs `4` through `9`:
```
2413
41352
246135
4613572
24681357
468135792
```
For even inputs, just `~),.+2%(;` would suffice. I'm not too happy with the kluge for handling odd input values; there's got to be a more efficient way to do it.
**Edit:** Saved two chars by changing the output for odd inputs a bit and playing silly stack manipulation tricks. Still not too happy with the length.
[Answer]
Python, 37
```
range(3,x+1,2)+[1]+range(4,x+1,2)+[2])
```
<http://ideone.com/xK40m>
[Answer]
# Perl 96 chars (obsolete solution since the new rules)
For what I can understand from the rules, we can assume that X is predefined.
Then this solution should work :
```
for(2x$x..9x$x){if(!/^$x/+/$x$/+/1$/){$L=0;map{$d=$L-$_;abs$d>1||next;$L=$_}split//;print;exit}}
```
which is 96 characters long, although the algorithm is very naive.
It gives the following solutions :
```
2
30
240
2402
24020
240202
2402020
24020202
240202020
```
Thus, it seems obvious than there is room to a much simpler program which directly computes a solution of this form...
---
The following program outputs **all** valid sequences with any given length X (takes X in STDIN)
```
$x=<>;$b=10**$x;for($b/10..$b-1){if(!/^$x/+/$x$/+/1$/){$L=0;map{$d=$L-$_;abs$d>1||next;$L=$_}split//;print"$_
"}}
```
If you want to output ALL possible solutions (for any X), then the program becomes (102 chars) :
```
for(;;){$x=length$_++;if(!/^$x/+/$x$/+/1$/){$L=0;map{$d=$L-$_;abs$d>1||next;$L=$_}split//;print"$_
"}}
```
[Answer]
## Python,30:
```
' 3579'[:(1+x)/2]+'1468'[:x/2]+'2'
```
<http://ideone.com/3csRh>
] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
This site is for programming contests and challenges. **General programming questions** are off-topic here. You may be able to get help on [Stack Overflow](http://stackoverflow.com/about).
Closed 1 year ago.
[Improve this question](/posts/3568/edit)
Here's a problem to which I don't know the answer. Suppose you have an ordered list of integers with an operator in between each consecutive pair. Let's restrict ourselves to three operations that are closed over the integers, namely addition, multiplication and subtraction. Is there a good way to find the order we should perform the operations such that the expression evaluates to the maximum value?
For example, given the input `5 * 5 - 3 + 8 * -2` the correct order is to first perform the addition leading to `5 * 5 - 11 * -2`, then perform the last multiplication leading to `5 * 5 - -22`, then perform the subtraction leading to `5 * 27`, then perform the final multiplication giving `135`, which is maximal.
The question is: does there exist a reasonably efficient way to find this answer? I can see some tricks that might help a little, but I can also see some roadblocks.
Here's a program in python that computes the solution in the dumb recursive O(2^n) fashion. It might be helpful to check answers.
```
def find_max(x):
if len(x) == 1:
return x[0]
y = [find_max(contract(x, i)) for i in xrange(len(x)//2)]
return max(y)
def contract(x, i):
return x[:2*i] + [do_op(*x[2*i:2*i + 3])] + x[2*i + 3:]
def do_op(left, op, right):
return {"+": left + right, "-": left - right, "*": left * right}[op]
init = [int(x) if i%2 == 0 else x for i,x in enumerate(raw_input().split())]
print find_max(init)
```
Usage: `python findmax.py < in.txt` where `in.txt` contains a sequence like `4 * -3 + 6 - 2 * 10`.
Is there a significantly faster way?
[Answer]
## Haskell, *O*(n3)
```
import Data.Array
data Op = Plus | Minus | Times
exampleTerms :: [Integer]
exampleTerms = [5, 5, 3, 8, -2]
exampleOps :: [Op]
exampleOps = [Times, Minus, Plus, Times]
main = print $ maximalOrder exampleTerms exampleOps
type MinMax = (Integer, Integer)
-- Given an operator and minimal/maximal values for left- and right-hand sides,
-- compute the minimal/maximal value of the expressions joined together with this operator.
combine :: Op -> MinMax -> MinMax -> MinMax
combine Plus (lmin, lmax) (rmin, rmax) = (lmin + rmin, lmax + rmax)
combine Minus (lmin, lmax) (rmin, rmax) = (lmin - rmax, lmax - rmin)
combine Times (lmin, lmax) (rmin, rmax) = (minimum ps, maximum ps)
where ps = [lmin * rmin, lmin * rmax, lmax * rmin, lmax * rmax]
maximalOrder :: [Integer] -> [Op] -> Integer
maximalOrder [] _ = error "maximalOrder: No terms"
maximalOrder terms ops
| length terms /= length ops + 1 = error "maximalOrder: Mismatched terms/ops lists."
maximalOrder terms ops = snd $ minMax 0 (termCount - 1) where
termCount :: Int
termCount = length terms
termsA :: Array Int Integer
termsA = array (0, termCount-1) $ zip [0..] terms
opsA :: Array Int Op
opsA = array (0, termCount-2) $ zip [0..] ops
dp :: Array (Int, Int) MinMax
dp = array ((0,0), (termCount-1,termCount-1))
[((start, end), minMax start end)
| start <- [0..termCount-1], end <- [start..termCount-1]]
minMax :: Int -> Int -> MinMax
minMax start end
| start == end =
let x = termsA ! start
in (x,x)
| otherwise =
let xs = [combine (opsA ! i) (dp ! (start,i)) (dp ! (i+1,end)) | i <- [start..end-1]]
in (minimum (map fst xs), maximum (map snd xs))
```
This computes the minimal and maximal values of every substring in the expression, by going through each intervening operator and finding the minimal/maximal result of treating that operator as the root of the expression. It collects these results into the overall minimal and maximal values for this substring.
This algorithm runs in O(n3) time and uses O(n2) space. Finding the minimal/maximal value of an expression string, once its substrings have been visited, takes O(*len*), where *len* is the length of the substring. The minimal/maximal value of every substring needs to be computed:
```
1..5
1..4 2..5
1..3 2..4 3..5
1..2 2..3 3..4 4..5
1..1 2..2 3..3 4..4 5..5
```
In this case, it takes 5\*1 + 4\*2 + 3\*3 + 2\*4 + 1\*5. In general, the number of operations grows in a cubic fashion.
At the heart of the algorithm is the `combine` function, which takes an operator and the minimal/maximal values of each of its operands, and produces the minimal/maximal results.
To maximize the result:
* If adding two numbers, maximize both arguments.
* If subtracting two numbers, maximize the left argument and minimize the right argument.
* If multiplying two numbers, try the following:
+ Maximize both arguments. This gives us the maximal result when multiplying two positive numbers.
+ Minimize both arguments. This gives us the maximal result when multiplying two negative numbers, since a [negative times a negative equals a positive](http://www.youtube.com/watch?v=2k_jS1zVLWw).
+ Minimize the left argument and maximize the right argument, or vice versa. We'd rather multiply two positives or two negatives and get a positive result, but if we have to multiply a positive and a negative and get a negative result, we want it to be as close to zero as possible. To do so, we minimize the positive number and maximize the negative number.
] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** [Update the question](/posts/2539/edit) so it's [on-topic](/help/on-topic) for Code Golf Stack Exchange.
Closed 12 years ago.
[Improve this question](/posts/2539/edit)
A software vendor friend of mine wants to clamp down the development environment by limiting access to the software's source code to only Remote Desktop access, disallowing any digital communication including clipboard, printer, network shares, and internet access from that environment.
The reasoning is that they are contractually obligated to provide a company-standard-issue development environment to an overseas partner and there is a concern of theft.
I want to convince them that this is a futile effort and vain burden on good developers since the otherwise unsupervised access to the source code will provide ample opportunity to steal the data. No matter how many firewall rules and group policies are in place, one channel remains that cannot be removed - the screen.
Assuming the development environment has Visual Studio 2010, data compression software, and other common development environment tools, what is the slickest way to use the Remote Desktop screen to steal the data? Keep in mind any limitations of the screen refresh rate.
Candidate approach: a monochrome bitmap of the screen can hold over 200KB of an archive of such source code. Without error correction, that's just over 500 screenshots of monochrome data for 100MB of compressed source code. The data must be encoded, decoded, and I'm entirely too lazy to save 500 screenshots into paint. Existing free software can be involved, but not installed on the environment.
Other ideas? Implementations?
[Answer]
Use [FRAPS](http://www.fraps.com/) to capture video from your local machine. Then you can flash stuff up on the remote desktop at up to the frame rate and it will all get recorded to a local video file.
I don't see a way to sync to exactly to the frame rate, so you'll need some error detection to make sure you're not getting data mid-draw. Here's a simple scheme using text and a python script:
```
framerate = 30 # fps of viewer
numlines = 24 # lines of text you can see at once
import sys,time,md5,base64
lineno = 0
while 1:
lines = 'chunk starting at line %d\n' % lineno
for i in xrange(numlines - 2):
lines += sys.stdin.readline()
lineno += 1
print 'md5:', base64.encodestring(md5.new(lines).digest()),
print lines
time.sleep(1.0/framerate)
```
Run this script in the RemoteDesktop window and pipe in the text you wish to capture. When it is done, OCR each frame of your FRAPS output (that's the hard part, I'm not sure what you'd use for that). Throw away any duplicate frames and frames where the md5 isn't right.
You probably want to base64 encode your input, as OCR doesn't do well with nonprinting characters like tabs and spaces.
] |
[Question]
[
Modern hardware can perform multiplication very fast in a constant latency of 3~4 cycles. But some tiny chips for embedded environments sometimes lack hardware multiplication, which has to be emulated by a series of instructions.
### Goal
You are given a primitive CPU with a set of basic operations. Your job is to implement unsigned multiplication of two 8-bit numbers, each in register `c` and `d`, after which the result will be stored in registers `a` and `b`, `a` storing the lower bits and `b` storing the higher bits. You don't have to preserve the input in `c` and `d`.
### Spec
The machine has 26 8-bit registers from `a` to `z`, whose initial value is `0`. You are allowed to use all of them freely to implement this operation.
There are no "jumps" or branching instructions, but there are flags conditionally set according to the last operation.
* ZF : zero flag; set if the result is zero
* CF : carry flag; set if the result is "wrapped" for addition/subtraction; set if a bit was "carried out" for shift/rotation
There is no memory access.
### Score
The total sum of latency cycles plus the number of registers used will be your score, the lower the better.
### Available Instructions
`instr r0 r1/imm (2)` means `instr` takes two register operands, of which the second one can be an 8-bit immediate operand, and this instruction takes 2 cycles to complete.
All operations except `mov`, `swp`, `setX`, and `mskX` sets the zero flag accordingly.
* `mov r0 r1/imm (1)` : `r0 = r1`
* `swp r0 r1 (2)` : `r0 = r1`, `r1 = r0`
* `sswp r0 (2)` : swap the low 4 bits and the high 4 bits
* `setz/setnz/setc/setnc r0 (1)` : set `r0` to `1` if the specified flag was set, and `0` otherwise ; `z -> ZF, nz -> not ZF, c -> CF, nc -> not CF`
* `mskz/msknz/mskc/msknc r0 (1)` : set `r0` to `0xff` if the specified flag was set, and `0` otherwise
* `add r0 r1/imm (2)` : `r0 = r0 + r1`; CF affected
* `sub r0 r1/imm (2)` : `r0 = r0 - r1`; CF affected
* `adc r0 r1/imm (3)` : `r0 = r0 + r1 + CF`; CF affected
* `sbb r0 r1/imm (3)` : `r0 = r0 - r1 - CF`; CF affected
* `and r0 r1/imm (2)` : `r0 = r0 & r1`
* `or r0 r1/imm (2)` : `r0 = r0 | r1`
* `xor r0 r1/imm (2)` : `r0 = r0 ^ r1`
* `shr r0 (1)` : bitshift right once shifting in a zero; CF is the old least significant bit (LSB)
* `shl r0 (1)` : bitshift left once shifting in a zero; CF is the old most significant bit (MSB)
* `ror r0 (1)` : rotate right; bitshift right once shifting in the LSB; CF is the old LSB
* `rol r0 (1)` : rotate left; bitshift left once shifting in the MSB; CF is the old MSB
* `rcr r0 (2)` : rotate right with carry; bitshift right once shifting in the CF; the new CF is the old LSB
* `rcl r0 (2)` : rotate left with carry; bitshift left once shifting in the CF; the new CF is the old MSB
* `not r0 (2)` : bitwise not
* `neg r0 (2)` : two's complement negation; same as `not r0; add r0 1`; `CF = not ZF`
---
[Here](https://godbolt.org/z/faP5ajor3), you can test your code that is translated to x86 assembly. Write your code below the label `mulb:`. I also added a working implementation ported from the work of @l4m2.
The tester has some limitations, though. It only supports 15 registers from `a` to `o`, and you have to write `shr a, 1` instead of `shr a` etc. because of NASM syntax.
[This is a scoring program written by @tsh.](https://tio.run/##rVhtc9s2DP6eX4F2vUhqHPml29qzY/d2WXrXu63trduXuu4iS4yjViZ1FFU7Tby/ngGkaEmO3dhuvvjEFzx4AIIA6M/B1yALZZyqYy4idhsKninIRC5DBn14r2TMJ74MZue3PXiXBDh7hYsQ4ma4ZJLdnvtZEofMbXu9gwMjrhf7BYqvxB9ixuRpkDHX87M0iZXb/Cg/8psh/Y6anj8NUtdNYs4aEPOIzT3oD8C9PgDg@bRr5uAI2g2cUWyuuqA300h8YTwzY1@ylBi6zeFPvZH/tNkAxyFwFV6ixtlRc@I1Dhae51/EiWJSayRNWtggVY2YTgMeZWgIEZmKr124hvAqTFgXmYBkky4omRPnKZJ0UQxnW3qoDcDdgg9la4QQONeDBSyIczZLK1CdAqqUl@1CfFjINwxQe0RIw@K7YdFHJfAdZC44K6HvsHJd@30IrXnrwoOTE/jZg5uVlQsUHQxwpUfC/odXKLtE6fehVVJg6lvdT/dQKPBeQhu6dRy@G9CjzUjhzoxO1zMKd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W4W4VKnqP5d0kA7o9HCH03XMm2aI4xEJnr6yU1jLcPwBx0emTI38zyLmrtNwPFMPiuKUU4KdyICO2MVzQs/iL1bJOPudjfNJjTclTmvdNaA2uAgwXhrwwX7Cgs6kxtuWnIL7tcXQrMFUTJua9bwTOjRPZGrTkZ3u2Gy25FhxvFvs13@aGfkNda8eb1auCKoavL0Pa9VUyl3hY9A@Xoam/pZM5ZKXxowd3Te9wLZpORc4o16lcUAvmktnw/Q3KYMrt/PLrxh4@q/Gf/GY9AHFqKPcvrSWXGitXb/cKZ1hlIpcpTmdbxkZtbDQp1zxkd3fNwcGT/U@r7C3t0SuNDc485qjUBd7GpJZoJD@6hSNzaqEA/BWq@kChbdRuX7n2TzFJoJFZmeV0brt6zH0oU9iPoGIqSBOsq5TbNzgE10yzI5a52WU0vlX0k8WCmkSVMRW7tYydUWUYaI8ZK6b5dNKq4gjNKtMdA16CywBijpns9k96cvzs/gbq8am1n@kYZYpgvySiAlWE@LdxYytDXBN@9U7uP0f) It is also a full featured tester. I'd like to explain how to use it if I know Javascript, but unfortunately I don't. Feel free to edit this post if you can add an explanation.
[Answer]
# Score: ~~94~~ 92
Reduced score by 1 thanks to @xiver77.
```
rol c
mskc a
and a, d
shl a
setc b
rol c
mskc e
and e, d
add a, e
adc b, 0
shl a
rcl b
rol c
mskc e
and e, d
add a, e
adc b, 0
shl a
rcl b
rol c
mskc e
and e, d
add a, e
adc b, 0
shl a
rcl b
rol c
mskc e
and e, d
add a, e
adc b, 0
shl a
rcl b
rol c
mskc e
and e, d
add a, e
adc b, 0
shl a
rcl b
rol c
mskc e
and e, d
add a, e
adc b, 0
shl a
rcl b
rol c
mskc e
and e, d
add a, e
adc b, 0
```
Explanation:
```
rol c
mskc a
and a, d
```
Multiply the MSB of `c` by `d`.
```
shl a
rcl b
rol c
mskc e
and e, d
add a, e
adc b, 0
```
For each of the remaining seven bits, double `ba` and add `d` multiplied by the bit (`setc b` is used instead of `rcl b` for the first bit since it scores 1 fewer).
[Answer]
# ~~87~~ ~~82~~ 80, destroying `c`
```
shl c
mskc a
and a, d
shl a
rcl c
mskc e
and e, d
add a, e
setc b
shl a
rcl c
mskc e
and e, d
add a, e
rcl b
shl a
rcl c
mskc e
and e, d
add a, e
rcl b
shl a
rcl c
mskc e
and e, d
add a, e
rcl b
shl a
rcl c
mskc e
and e, d
add a, e
rcl b
shl a
rcl c
mskc e
and e, d
add a, e
rcl b
shl a
rcl c
mskc e
and e, d
add a, e
rcl b
add b, c
```
82 preserving `c` is trivial from 80 destroying it
Didn't notice that mul from most significant is faster
# 104
```
1 reg a # output low
1 reg b # output high
1 reg c # input
1 reg d # input
1 reg e # cur
1 reg f # back
0 # bit 0
1 ror d
1 msk a, C # mskc a by OP
2 and a, c
1 mov b, a
0 # bit 1
1 rol c
1 ror d
1 msk e, C
2 and e, c
1 mov f, e
2 and e, 254
2 add a, e
3 adc b, f
1 rol c
1 ror d
1 msk e, C
2 and e, c
1 mov f, e
2 and e, 252
2 add a, e
3 adc b, f
1 rol c
1 ror d
1 msk e, C
2 and e, c
1 mov f, e
2 and e, 248
2 add a, e
3 adc b, f
1 rol c
1 ror d
1 msk e, C
2 and e, c
1 mov f, e
2 and e, 240
2 add a, e
3 adc b, f
1 rol c
1 ror d
1 msk e, C
2 and e, c
1 mov f, e
2 and e, 224
2 add a, e
3 adc b, f
1 rol c
1 ror d
1 msk e, C
2 and e, c
1 mov f, e
2 and e, 192
2 add a, e
3 adc b, f
1 rol c
1 ror d
1 msk e, C
2 and e, c
1 mov f, e
2 and e, 128
2 add a, e
3 adc b, f
0 # fix b
2 sub b, a
```
Writing `set a, C` feel better and align friendly than `setc a`
] |
[Question]
[
## Challenge
Your challenge is simple, calculate the depth of each matching brackets in the given input e.g. `(()()(()))`->`[[1,1,[1]]]`, and output it in the form of a list/array/string representation
## Explanation:
For every bracket in the input, you have to count how many nested brackets there are for that part of the input e.g. `()` has 1 depth
Although if find a bracket of depth 2 e.g. `(())`, a list `[]` is formed from the 1st bracket `( )` has to be added to the output with the 2nd bracket, `()` of depth 1 inside that list
## Test cases:
```
() -> [1]
[[][]] -> [[1,1]]
{}{}{{}}{{{}}} -> [1,1,[1],[[1]]
```
## Others
You may assume that there are only lists and `1`'s will be in the required output
For the output, you are allowed to output the depth as a list/array, or as a string representation e.g. `1 1 [1]` for `()()(())`
You can output it in other ways, but the depth of the brackets must be distinguishable from each other.
Your answer should be able to handle one type of bracket (one of `()`, `[]`, or `{}`), at your choice.
You may assume that input is balanced and only uses the type of bracket you chose.
[Answer]
# [Python](https://www.python.org/), ~~236~~ 155 bytes
```
def r(o):
v="[";s=a=n=0
for c in o:
if c=="(":
if s<1:a=n+1
s+=1
else:
s-=1
if a==n:v+="1,"
elif s<1:v+=r(o[a:n])
n+=1
return v+"]"
```
Is this a good solution? No. But I don't think there'll be another answer here soon, and I'm very new to codegolf so I thought I might try my luck here :p
[Attmpt this online!](https://ato.pxeger.com/run?1=NU87CsMwDN17CqHJxg00W3Grk4QMIbVpIMjBTgI9S5Ys7SF6k96mctIiJPH0nn7La3iM98Dr-pxGX5w_y815iCpoe4CZsMJLooaYTgfwIUILHUMQDjoPLREqzCCjdC2tKE2ZcTKUs-uT2_hUbDjrGiK2syEsj5hLrv81S00WV43lWgvB24joxikyzAZr3E98D7HjUUWFSospLS5Bo9a74P_LFw)
] |
[Question]
[
How do I remove all duplicates from list and order it based on count?
```
s = ["foo", "this", "lem", "foo", "lem"]
s = ["foo", "ebh", "wosv", "wosv", "ebh", "4whcu"]
#should return
>>> ["foo", "lem", "this"]
>>> ["ebh", "wosv", "foo", "4whcu"]
```
**Rules:**
* Must be shorter than the below code in terms of byte size.
* Order must be based on the count of in descending order.
* If there are two strings with the same count, the first appearance comes first
* All duplicates must be removed, only one of each string should be in the final list
I currently have
```
list({}.fromkeys(sorted(s,key=lambda y:-s.count(y))))
```
I've noticed answers like `set` but that arbitrarily changes the order, which I do not want.
**Edit:** Sorry for the poor quality before. I had whipped this right before I slept and I was quite tired. This is not for StackOverflow because I'm trying to golf/shorten the size of this code as much as possible. I've tried looking for answers but I haven't been able to find anything.
[Answer]
# 44 bytes
```
sorted({}.fromkeys(s),key=s.count,reverse=1)
```
[Try it online!](https://tio.run/##TcvBCoMwEATQu1@x5JRAEGJ7KuRLxEvthoTWrGSjIqXfnhrw4Okxw8y8Z0/xVtiAhV44IqFBZB@4@sGpcrY1DQ131yU@fWUjXq@e9X3z43J8GkcJGEKEno0G7oYHzCnEDLIwpYwv@f21LtH0xp0lK31ouR1piVknXDExWqOKKn8 "Python 3 – Try It Online")
An improvement to the below, replacing the key with a built-in rather than a `lambda`, and using `reverse` to swap the comparisons. We'd like to do `[::-1]` on the final result instead, but that doesn't do the right stable tiebreaks.
We could also use `dict(zip(s,s))` in place of `{}.fromkeys(s)` for the same length.
---
# 47 bytes
```
sorted({}.fromkeys(s),key=lambda y:-s.count(y))
```
[Try it online!](https://tio.run/##TcvNCoMwEATgu0@xeEogFbQ9CT6JePAnIaEmK9lYCaXPnhrw4OljhpktBo3umaiGDvpSIZYCyqANZVdpM1eb01BQc1/KSWcOpM/dq34det7PT6HQA4Fx0FMtgJqhhc0bF4AlQh/kwr6/Snm0bxmJERen3TraaRkhtg@qZtxdYJHzxNMf "Python 3 – Try It Online")
A simple transposition of your code, moving your `{}.fromkeys` de-duplication trick before the sorting. Since sorting converts to a list, extracting the keys from a dictionary, this saves the `list()` call of the original.
For ease of reference, the original code is:
**53 bytes**
```
list({}.fromkeys(sorted(s,key=lambda y:-s.count(y))))
```
[Try it online!](https://tio.run/##TYvLCoMwFET3fsUlqwhW0HYl@CXiwkdCQpNcyY2VUPrtqQEXzuYwh5ktBoXumaiBHgYmEVkFLChNmUbYjMvmNhbU3pdiVhkH0ufOS78Oteznp5DogUA7GKipgNqxg81rF4Anoynw76@WHu1bROKEPoiVU3W23kx2XieI3YPqBXcXeCzPpDL9AQ "Python 3 – Try It Online")
[Answer]
**APL, 11 chars**
`∪⌷⍨∘⊂∘⍒⊢∘≢⌸`
`⊢∘≢⌸` right arg: number of apperance of each element, in order of first appearance
`∪` left arg: unique elements, in order of first appearance`
`⌷⍨∘⊂∘⍒` sorts elements of the left arg based on the grade-down of the right arg`
Try it online: <https://tio.run/##SyzI0U2pTMzJT///v9jwUdsE9bT8fHUF9ZKMzGIglZOaCyQhQiA2V7ERQk1qUgaQLM8vLkNQEDGT8ozkUnUurjSg4kcdqx71bH/Uu@JRx4xHXU0gsnfSo65FIEbnokc9O7i4HvVNBSpMUyg2RDCN/v8HAA>
] |
[Question]
[
Let's say you have a sentence like:
```
this is a very long sentence with several words of no significance
```
It contains only the 26 lowercase letters of the alphabet and spaces.
And you have a dictionary, where each word contains any number of the 26 lowercase letters and nothing else:
```
henge
renton
```
Then the output should contain, among others:
* t**H**is is a v**E**ry long se**N**tence with several words of no si**G**nificanc**E**
* t**H**is is a v**E**ry long sente**N**ce with several words of no si**G**nificanc**E**
* this is a ve**R**y long s**ENT**ence with several w**O**rds of no significa**N**ce
So, every line of the output is the original sentence, but if only the uppercase letters of a line are taken, they should form a dictionary word. The program should find all possible such lines.
[Answer]
# JavaScript, 474 bytes
```
k=((e,r)=>{for(o=[],e=[...e],r=[...r],w=r.reduce((r,h,n)=>!(r[n]=e.map((e,r)=>h==e?r:"").filter(Number))||r,[]),[z]=w,h=[],x=0;x<w.reduce((e,r)=>e*=r.length||e,1);x++)z.forEach((e,r)=>{for(g=[z[r]],j=1;j<w.length;j++)for(n=w[j],y=0;y<n.length;y++)if(g.slice(-1)[0]<n[y]&&!h.some(e=>e.toString()==[...g,n[y]].toString())){g.push(n[y]);break}h.push(g)});return h.filter(e=>e.length==w.length).forEach(r=>{d=[...e],r.forEach(e=>d[e]=d[e].toUpperCase()),o.push(d.join(""))}),o})
```
**Live example:**
```
k=((e,r)=>{for(o=[],e=[...e],r=[...r],w=r.reduce((r,h,n)=>!(r[n]=e.map((e,r)=>h==e?r:"").filter(Number))||r,[]),[z]=w,h=[],x=0;x<w.reduce((e,r)=>e*=r.length||e,1);x++)z.forEach((e,r)=>{for(g=[z[r]],j=1;j<w.length;j++)for(n=w[j],y=0;y<n.length;y++)if(g.slice(-1)[0]<n[y]&&!h.some(e=>e.toString()==[...g,n[y]].toString())){g.push(n[y]);break}h.push(g)});return h.filter(e=>e.length==w.length).forEach(r=>{d=[...e],r.forEach(e=>d[e]=d[e].toUpperCase()),o.push(d.join(""))}),o})
console.log(k('this is a very long sentence with several words of no significance', 'henge'));
```
**Explanation:**
For each letter in the word, an array of indices is constructed corresponding to every position of that letter in the sentence.
Then inside a nest of 4 `for` loops, every possible path from the first array to the last array is computed, where each step is into an element with greater numeric value in the next array.
This produces an array of paths whose length is equal to the maximum possible paths, which is the product of multiplying the length of each letter indices array (this number gets big real quick as the length of the word increases).
Then all paths whose length is smaller than the word are excluded, since they failed to find a valid step between each array.
You can see the unminified logic at [this](https://stackoverflow.com/a/62988926/13378247) stackoverflow answer.
I am confused by this line (even though it's my code), whose intent is to check the existing paths before adding a step to the current path to make sure its constructing a unique path:
```
if (!paths.some(p => p.toString() == [...path, arrays[j][y]].toString())) {
path.push(arrays[j][y]);
break;
}
```
It seems to me like this should erroneously prevent construction of multiple paths who share any beginning steps. But it actually works as intended. So I am stumped.
[Answer]
# Python 3, 169 bytes
```
a=lambda c,w:(([c[0]+k for k in a(c[1:],w)]+([c[0].upper()+k for k in a(c[1:],w[1:])]if c[0]==w[0]else[]))if c else[])if w else[c]
lambda c,d:sum((a(c,w)for w in d),[])
```
Takes as input the sentence as a string and the dictionary as a list of strings. Uses a recursive helper function `a(c,w)` to compute the output for each word in the dictionary at a time, then sums the lists together to get the final output. The helper function works through the sentence/word one character at a time, and has several cases:
1. No more characters in the word, return what's left of the sentence
2. No more characters in the sentence, return empty list
3. Characters left in both, return same results as `a(c[1:],w)`, with `c[0]` prepended to each result.
4. Characters left in both, **and** beginning characters match, return (3.) in addition to `a(c[1:],w[1:])`, with `c[0].upper()` prepended to each result.
There's definitely a few bytes of savings to be had in the helper method; I wasn't being super careful with my parentheses around the inline `if`-expressions (and the precedence is slightly confusing) -- I might take a closer look tomorrow to see if I can shave off a few bytes.
[Answer]
# [Perl 5](https://www.perl.org/) `-pF`, 96 bytes
Takes the sentence as the first input and all subsequent inputs are treated as the dictionary. Could produce the strings in the reverse order for +1 byte. I still feel there's room to golf this...
```
$"=").*(";m#(@{[<>=~/./g]})(?{$a=%h=();$h{$_}++for@-;map$\.=$h{$a++}?uc:lc,@F})(?!)# while!eof}{
```
[Try it online!](https://tio.run/##FYtBDoIwFET3nOKLNQFRXLkRq6y8hBpT8UOblH7SosQQPLq1JrOZefM6tHrrPYt5nObLJC7aeVKO5/2Bfzb5prlOaXIcmeALyZO0YHJktynLarLlumhFxy45/48iy6bjs9rpalWe/s4sncMglcYZUj2N3vdSOQgR8EL7Bk2mAYemR1MhDKqXoQUiNAxkHw6oBkPgVGNUrSoRXpFE02Bkg0QmEvcvdb0i4/y6O/0A "Perl 5 – Try It Online")
## Explanation
This script uses Perl's regex engine to perform the matching.
First `$"` is set to `).*(`, this is the separator that's used [when lists are interpolated](https://tio.run/##K0gtyjH9/19FyVZJISczO1VByZrLISezuETBVqGwXCOzRL1YoSQjs1jTmouroCgzr0RBCSyt9P8/AA). A `m//`atch is then started (with `#` as the delimiter) which contains the current input dictionary word (`<>`), interpolated (`@{[...]}`) into the match as as a list (`=~/./g`). [Example](https://tio.run/##K0gtyjH9/19FyVZJU09LQ8mai6ugKDOvREFJw6E6Wl9PPz22VlPp//@Q1OKSzLz0f/kFJZn5ecX/dfMA).
The next part of the `m//` operation is a zero-length code block. In here there is access to all the magic variables associated with regex ([`$&`](https://perldoc.perl.org/perlvar.html#%24%26), [`$1`](https://perldoc.perl.org/perlvar.html#%24%3c_digits_%3e-(%241%2c-%242%2c-...)), etc). `$a` and `%h` are initialised as empty (`()` - technically `$a` is [set to the length, which is `0`](https://tio.run/##K0gtyjH9/18l0VY1w1ZD05qLq6AoM69EQSXR@v9/AA)) and [`@-`](https://perldoc.perl.org/perlvar.html#%40-), which contains the start of each matched group, is used to populate the indices of `%h` with `1` (`++`) for the position of all the matches.
Finally, `@F` (which is automatically filled with the chars from the input via `-F`) is looped over `while` there's still input (`!eof`), checking `%h`'s key `$a` (incremented for each char in `@F`) to see if it's truthy (`1`) or not (`undef` for missing key). If it's truthy `uc` returns (its operand, or `$_` if none passed, which is set for each item in `@F` via `map{...}@F`) the item uppercased, otherwise `lc` returns it lowercased. This is appended to `$\` which is implicitly output after anything is `print`ed, which because `-p` is specified, will happen after the (implicit - from `-p`) input loop exits. Due to this, it's also necessary to break out of the surrounding loops with `}{` so that we don't get an unmodified copy of the input `print`ed too.
] |
[Question]
[
**Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/200624/edit).
Closed 3 years ago.
[Improve this question](/posts/200624/edit)
## Miller-Rabin test
Given a base \$b\$ and an odd number \$n\$:
Write \$n\$ as \$2^{s}\times d + 1\$ where \$d\$ is odd
\$n\$ is a *strong probable prime* if either:
* \$b^d\equiv 1 \pmod n\$
* \$b^{d\cdot2^r}\equiv -1 \pmod n\$
for any non-negative \$r\$ strictly less than \$s\$.
A *strong probable prime* which is composite is a *pseudoprime*.
See [en.wikipedia.org/wiki/Strong\_pseudoprime](https://en.wikipedia.org/wiki/Strong_pseudoprime) for more information.
## Challenge
Make a script that generates very good bases (bases, \$b\$, for which the first *pseudoprime* is larger than with any smaller base).
## Additional rules
1. Your script should be as fast as possible.
2. Your script should not use a lookup table (for the output, lookup table for primes is fine).
3. You may use external libraries as long as that library is written in the same language.
4. Speed will be measured in terms of how many terms it can generate in 1 min.
## Python implementation of the Miller-Rabin test
```
def miller(n, b):
if n % 2 == 0:
return n == 2
d = n - 1
s = 0
while d % 2 == 0:
d >>= 1
s += 1
if pow(b, d, n) == 1:
return True
elif any(pow(b, d * 2 ** r, n) == n - 1 for r in range(s)):
return True
return False
```
An entry is valid if it will never stop producing better bases and it won't produce a base worse than it has generated before.
Example of a valid python entry:
```
from sympy import isprime
base = 2
record = 2
while True:
number = 9
while True:
while isprime(number):
number += 2
if miller(number, base):
if number > record:
record = number
print(base)
break
number += 2
base += 1
```
Little over 20 sec to generate:
```
2
1320
4712
5628
7252
7852
14787
17340
61380
78750
```
My code generates the above in ca. 20 sec on my laptop, and generates one more term in 72 sec. so the score is 10 terms.
Arnauld pointed out that the challenge is just to generate [A298757](https://oeis.org/A298757).
Sympy's isprime is not the problem as it runs in less than .5 sec for 700 digit numbers.
Edit:
I didn't mean to give advantage to specific languages like C, so I will convert them to python.
[Answer]
# [Rust](https://www.rust-lang.org/), \$n = 15\$
```
use std::collections::VecDeque;
fn miller(n: u64, mut b: u64) -> bool {
let s = (n - 1).trailing_zeros();
let mut t = n - 1 >> s;
b %= n;
let mut a = b;
while t != 1 {
b = b * b % n;
t >>= 1;
if t & 1 != 0 {
a = a * b % n;
}
}
if a == 1 || a == n - 1 {
return true;
}
for _ in 1..s {
a = a * a % n;
if a == n - 1 {
return true;
}
if a == 1 {
return false;
}
}
return false;
}
fn main() {
let mut record = 2;
let mut factor = VecDeque::new();
for base in 2.. {
factor.clear();
let mut q = 3;
let mut qq = q * q;
for n in (9..).step_by(2) {
let mut p = factor.pop_front().unwrap_or(0);
if n == qq {
if p == 0 {
p = q;
}
q += 2;
qq = q * q;
} else if p == 0 {
continue;
}
if miller(n as u64, base) {
if n > record {
println!("{}", base);
record = n;
}
break;
}
let mut m = p - 1;
while *factor.get(m).unwrap_or(&0) != 0 {
m += p;
}
if factor.len() < m + 1 {
factor.resize(m + 1, 0);
}
factor[m] = p;
}
}
}
```
[Try it online!](https://tio.run/##jVTdbtowFL7nKU4rrXK6ElE6TVoY3GzPsJtpQk7qMGuOHWxnaG159WXnYEwSSKv5AqHj7@f8ObZxvm0bJ8D5xywrjFKi8NJol2XfRPFVbBuxmExKDZXEK8t0Bs3HD3dQNR7yw/8EpivIjVHwPAE8SnhwsASmYQr3Seotl0rqzfpJWONYsjihSMMj8gCE1QpcuMvhHQaHOI64PIR2P6USSLxaIit4BhYi4JbYkUzHozACu4AsMXaDVOTPenw65MIvNfaT7hfpiCLrl5fwL6TfCVnhG6vBW2pdRyyNhTVIDfdp6nrw6MmHntHnXH3UoXMZpjhKK7lyYry4IWIfBs@lZklvuDQOKwpjHzHz@XBMJS881rmEuDxZpsWOhn7qQc5x27AN8zTt5ReIaaEEt3FH@sJb1HwYCVN8i93bdndkosmBfUrTJHVe1Ov8D5snZ@2IGjVKHO1rU69La7RnSdroneX12lg2i@n3Gqypweg@lDxe1nQ5G7mjQ3a9bC/HF88W3p/6O4iP1HxQAKGotW/4F1ia1P2tCdbn1cXHDtyF505DS8aL1bCK6/BKwVZqr/QVu37eXx@lFqPI01bp/@lPbgX/9WYlccIVStb0jobo8CG5Pc5@Izyr@mO/mSVj3wg6FY2mPvc@a8xRVwl6Pp@Jc/Eie5tvhZNPgh1QdzBL3hIPlO/VDxhkEV/yvm3/FqXiG9dOv7Sm9lMlfgu1fPgH "Rust – Try It Online")
[Answer]
# [C++ (clang)](http://clang.llvm.org/), \$n=14\$
```
#include <iostream>
#include <cmath>
#include <chrono>
#include <iomanip>
template <typename I>
bool isPrime(I n)
{
if (n < 2) {
return false;
}
if (n == 2 || n == 3) {
return true;
}
if (n % 2 == 0 || n % 3 == 0) {
return false;
}
I srt = std::sqrt(n);
int inc = 4;
for (I i = static_cast<I>(5); i <= srt; i += inc)
{
if (n % i == 0) {
return false;
}
inc = 6 - inc;
}
return true;
}
template <typename I>
I pow(I base, I exp, I mod)
{
I result = 1;
for (;;)
{
if (exp & 1) {
result = (result * base) % mod;
}
exp >>= 1;
if (!exp) {
break;
}
base = (base * base) % mod;
}
return result;
}
template <typename I>
bool miller(I n, I b)
{
if (n % 2 == 0) return n == 2;
I d = n - 1;
I s = 0;
while (d % 2 == 0)
{
d >>= 1;
s += 1;
}
if (pow<I>(b, d, n) == 1)
{
return true;
}
else
{
for (int r = 0; r < s; ++r) {
if (pow<I>(b, d * (1 << r), n) == n - 1) {
return true;
}
}
}
return false;
}
template <typename I>
void genBase()
{
auto start = std::chrono::steady_clock::now();
I base = 2;
I record = 2;
int count = 0;
while (true)
{
I number = 9;
while (true)
{
while (isPrime(number))
{
number += 2;
}
if (miller(number, base))
{
if (number > record)
{
record = number;
auto now = std::chrono::steady_clock::now();
auto diff = now - start;
std::cout << std::setw(3) << ++count << ". " << std::setw(10) << base <<
" @ " << std::setprecision(4) << std::chrono::duration<double, std::milli>(diff).count()/1000 << " s\n";
}
break;
}
number += 2;
}
base++;
}
}
int main(){
genBase<unsigned long long>();
return 0;
}
```
[Try it online!](https://tio.run/##jVXtbtMwFP3fp7gUDcWkHc02kGjSCPGvv@ABkKZ8uJ21xA62w5hYX53u2k6a5mOwSFuSm/t5zrluVlXLrEj4/nh8y3hW1DmFiAmlJU3KeNbZsjLRdz3DnRRcnFuYKBPOqng207SsikSjTT9WlCclhW08S4UogKnvkpXU2wInsz8zwIvtwOMQwRUBZzCXpLqWHHZJoWhorYcz580GruDpCezT9USclvVE2AVGYcDKhV7AtX17TdktKKlhA0rn67X6KbXHifvOuMa/DL/dOMNOSMDxmPVONMtus0TpaBt7H0mI5mhjcpknf2MiiY3qWmhbZaPmphvsmnTtmFY@wdI8nU/QA@bwEkdbqMQDdp8mii5wavq7MrdS5C1bW8yk6sKAEZwNHIZTc2A4vINgPESTwWue3tuCBKfGSlNjmURxfCrZ5n@D9mHyFKV7P5XDlDA17X2iYg8n19g/kLJqLllRUGnEbFBK@4pu1UbanE63YQNjjr1w5CloDQoNK/fycMcKCl7e5RiAmw/RUEZNwVDySKYRXrqAfIELZ1IFw1QvbAxFgQ08LdFG79J2ircIVAi@L4ccDGoj2l4AUQSStG3YyYdhk@2MiTyM6Wr24UW2fgmWw57yr0i619KU1FqYHe022x1quOGaJvnjbVaI7H695rgSpGWpUdGJRkkzIfPOYvDJRM31iE0z0hB8VE5dptQA@rkbdxTQDzpzaY9Tl4WQns8Y3KaYf@p2DG5LXyNtF7Fw2/K/9Fb3rkTcAENGTuMwx2MDo4sPJ50sYcjGq@maTJCz3c4UwjxLR/@0sysham2U6w5@qh88/LnBd993JOPj/BLmfZdgZX2sVPA@md1cc/jSD60QBqaY4N4NOdnbKfNa4s@J4FEu6rTA49l@NTyx2DNDkUvbk0c@BKvVyrYG6gefj8c7jCyDU3PsNCmd/uHq@@0Bgnto9qBMGPeII7xZvqjmiu05zaEQfG//xS1bzS7j1hyOx7/Zrkj26rj8dv0M "C++ (clang) – Try It Online")
Basically a port of the OP's Python solution.
### Output:
```
1. 2 @ 0.001043 s
2. 1320 @ 0.0234 s
3. 4712 @ 0.06999 s
4. 5628 @ 0.08394 s
5. 7252 @ 0.1051 s
6. 7852 @ 0.117 s
7. 14787 @ 0.2111 s
8. 17340 @ 0.244 s
9. 61380 @ 0.8129 s
10. 78750 @ 1.022 s
11. 254923 @ 3.133 s
12. 486605 @ 5.843 s
13. 1804842 @ 21.69 s
14. 4095086 @ 48.38 s
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), \$n=15\$
This is essentially just a port of the example implementation, with an optimized modular exponentiation and a cache for odd composite numbers.
Further optimized by merging `powMod()` and `miller()`, as [Anders Kaseorg first did](https://codegolf.stackexchange.com/a/200635/58563).
```
function miller(n, b) {
let s = 31 - Math.clz32(n - 1 & 1 - n);
let t = n - 1 >> s;
let k = b %= n;
while(t != 1) {
b = (b * b) % n;
if((t >>= 1) & 1) {
k = (k * b) % n;
}
}
if(k == 1 || k == n - 1) {
return true;
}
while(k != 1 && --s) {
if((k = (k * k) % n) == n - 1) {
return true;
}
}
return false;
}
function isPrime(n) {
let m = n ** 0.5;
for(let d = 3; d <= m; d += 2) {
if(!(n % d)) {
return false;
}
}
return true;
}
function nthOddComposite(n) {
if(n < oddComposite.length) {
return oddComposite[n];
}
let k;
for(k = oddComposite[oddComposite.length - 1]; isPrime(k += 2);) {}
oddComposite.push(k);
return k;
}
let oddComposite = [ 9 ];
let ts = +new Date();
for(let i = 0, record = base = 2;; base++) {
for(let j = 0;; j++) {
number = nthOddComposite(j);
if(miller(number, base)) {
if(number > record) {
record = number;
console.log(
++i + '\tbase = ' + base + '\ttime = ' + ((new Date() - ts) / 1000).toFixed(2)
);
}
break;
}
}
}
```
[Try it online!](https://tio.run/##bVNNc5swEL3zK14OdoSxXeNMDh0Cl3Z667T3NAc@5CADkgdE02nj3@6uxGfiHBjBvre7b9@KY/w7btJanPRGqoxfLodWplooiUqUJa@ZXCNx8c8BSq7RIMSdjw2@xzrfpuXfuz2T9OljCROWbtAzNTE7JIrQDNGCogkWBAUOhV5yUXKmcRPC75qA4BAswcq0XfQ8QBwY8aLIEpcTG7YkK2Z8Ezw73UNphFMSXl9h36ymIbvmuq0ldN3yoM/oJBVWEpZLbDbNwDYaxm6F7eZelbwqOonpgUNcNoScHWf0WjQ/a1FxJienK@vfaoXd9t56cFA1M0BmVhDQ8RCiMqcXYj@TeEMLWSBzrwT1fT9Q1EmdC5I6/5FlX1R1Uo3QozAqL/EANYO2JZfPOn/n6JzxKJ86c4c7MI5jzHzD/KCw8fYpGB0qunED6mcGeJNwapucFa4t3@so7Fim65xJbR/xGSTL3lRzqT3JX/A1plFN/uC1IGS3pmKpqo3vSdyY5D3pIRv8@8BGPK@bfsg6mqwgwHEAANlWCa/NSt8Ze3SnCz78cZa7tqVnWzTed1WiXtCEYZLYcYIRSJVsVEluqmc2BgHPE/Bw@0v3I93Sl321QU1W90HGJmdoF5r@hk/wd7udu9Xqm/jDM7Z3x8Lu0Pjcn0nN42J@6c6Xy38 "JavaScript (Node.js) – Try It Online") (this TIO link has \$n\le15\$ as a hard-coded limit)
### Output
```
1 base = 2 time = 0.00
2 base = 1320 time = 0.02
3 base = 4712 time = 0.03
4 base = 5628 time = 0.04
5 base = 7252 time = 0.04
6 base = 7852 time = 0.05
7 base = 14787 time = 0.07
8 base = 17340 time = 0.07
9 base = 61380 time = 0.18
10 base = 78750 time = 0.22
11 base = 254923 time = 0.62
12 base = 486605 time = 1.14
13 base = 1804842 time = 4.05
14 base = 4095086 time = 9.13
15 base = 12772344 time = 28.41
--------------------------------------> time limit
16 base = 42162995 time = 94.23
```
] |
[Question]
[
The problem has 3 inputs.
**L**: a list of all numbers
**size**: the size each set can be
**max**: the max sum amongst each set
The challenge is as follows:
Given L, size and max, construct as many sets from L such that the number of elements is **size** and the sum of each of the elements does not exceed **max**.
Examples:
```
func(L=[1,2,3,4], size=2, max=5) = [{1,2}, {1,3}, {2,3}, {1,4}]
```
Notice how each of the values in the outputted set are sum <= max.
```
func(L=[1,2,3,4], size=3, max=6) = [{1,2,3}]
func(L=[1,2,3,4], size=3, max=5) = [{}] or empty list, whichever you want
```
Note that in the set you cannot have duplicated items. `ie: {2,1} = {1,2}`
Constraints on inputs:
**L**: 0 or more elements
**size**: 0 <= size <= len(L)
**max**: 0 or more
If a list has 0 items, then always return the empty set.
If the size is 0, then always return the empty set.
If max is 0, it is possible that there are negative values in **L**, in which case the returned sets need not be empty.
Shorted bytes wins!
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes
```
.ÆêʒO@
```
[Try it online!](https://tio.run/##yy9OTMpM/f9f73Db4VWnJvk7/P9vxBVtqGOoYwSExkBoomMSy2VkAAA "05AB1E – Try It Online")
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 9 bytes
```
≥ᵗ⟨⟨⊇l⟩+⟩
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6OmpofbFjzc1Vn7cOuE/486lz7cOv3R/BUg1NWe82j@Sm0g/v8/WiE6OtpQx0jHWMckVscoVsc0VgdZxDhWxwxDxDRWIRYA "Brachylog – Try It Online")
Takes input as `[[L,size],max]` through the input variable and [generates](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/10753#10753) the output through the output variable.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~82~~ 79 bytes
```
lambda l,s,m:[i for i in __import__("itertools").combinations(l,s)if sum(i)<=m]
```
[Try it online!](https://tio.run/##dctBCsIwEEDRvacYuspAEGrUhdiT1BJSNTiQyYRkXHj62L24@vDgl4@@JLsep1tPgddHgGSb5ctMEKUCAWXwnrhIVe/NQPqsKpLagPu78Eo5KEluZtuQIrQ3G8LrxEsvlbKaaObRHqyzx2XLCXH36@6vnxH7Fw "Python 3 – Try It Online")
-3 bytes thanks to squid
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 11 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
àV â fÈx §W
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=4FYg4iBmyHggp1c&input=WzEsMiwzLDQsNF0KMgo1Ci1S)
```
àV â fÈx §W :Implicit input of array U=L and integers V=size & W=max
àV :Combinations of U of length V
â :Deduplicate
f :Filter by
È :Function
x : Sum
§W : Less than or equal to W
```
[Answer]
# [R](https://www.r-project.org/), 56 bytes
```
function(L,s,m,a=combn(L,s))unique(a[,colSums(a)<=m],,2)
```
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP0/DR6dYJ1cn0TY5PzcJzNPULM3LLCxN1UiM1knOzwkuzS3WSNS0sc2N1dEx0vyfpmFoZaKjYKSjYKrJBeUY6yiYIXPAMkWpBVClmmDlRgaa/wE "R – Try It Online")
Creates a matrix where each column is a subset of `L` of size `s`, and keeps those for which the sum is less than `m`. Output is a matrix, with each column corresponding to one allowable subset (if there is only one such subset, the output is a `s×1` matrix and R will display it on one row instead by default).
Note that this fails for the edge case where `L` is empty. Handling that edge case as specified in the challenge takes 19 more bytes:
# [R](https://www.r-project.org/), 75 bytes
```
function(L,s,m,a=combn(L,s))`if`(length(L),unique(a[,colSums(a)<=m],,2),{})
```
[Try it online!](https://tio.run/##Tcq9DsIgGIXh3atg/L7kDII/g5E76OZoTIoElKRAbctkvHaMpIPjc847Va@rL8kuISfqMCPCaJvjvYm5D76nwaXH8qSOUVJ4FUfmCpuHS4kzGT7reAMU4/3h6kme9hAK4sCbFTuI4z/aM7lxTbnlavtbLTEkJNcv "R – Try It Online")
[Answer]
# [Gaia](https://github.com/splcurran/Gaia), 8 bytes
```
Σ⊂
euK↑⁇
```
[Try it online!](https://tio.run/##S0/MTPz//9ziR11NXKml3o/aJj5qbP//P9pQwUjBWMEklsuYyxQA "Gaia – Try It Online")
Takes input as `list`, `size`, `max sum` on separate lines.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
QœcS>¥Ðḟ⁵
```
[Try it online!](https://tio.run/##AScA2P9qZWxsef//UcWTY1M@wqXDkOG4n@KBtf///1sxLDIsMyw0Xf8y/zU "Jelly – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 15 bytes
```
{SMfgeQsT.PhQht
```
[Try it online!](https://tio.run/##K6gsyfj/vzrYNy09NbA4RC8gIzCj5P//aEMdIx1jHZNYIGEKAA "Pyth – Try It Online")
```
{SMfgeQsT.PhQhtQ # (last Q implicit; Q = input)
.P # all permutations
hQ # of Q[0]
htQ # of length Q[1:][0] = Q[1]
f # filter those with lambda T:
eQ # Q[-1]
g # >=
sT # sum(T)
SM # sort each element
{ # deduplicate
```
[Answer]
# [Kotlin](https://kotlinlang.org), 286 bytes
```
fun p(l:List<Int>,s:Int,m:Int){val r=MutableList(0){""}
val a=l.toSet().toList()
fun r(n:Int,b:Int,t:Int,u:List<Int>){if(n<1){if(t<=m)r.add(u.joinToString(",","{","}"))}else
for(e in b..a.size-1)r(n-1,e+1,t+a[e],u+listOf(a[e]))}
r(s,0,0,List(0){0})
println(r.joinToString(",","[","]"))}
```
[Try it online!](https://tio.run/##nVhdb9vGEn33rxgTAUohLC3ZSdAKVoH0414EcJqizpvhh7W0ktiSXHV3acU19NvTM7O7JFWnMFrboChydr7OmZld/258XbWfz87oXbvr/Jxa47dVu6G1seS3mlZ6rbrak9fO01I57U4gzC/3hrBUOzJrcju11OT0TlnlNVWt1xttXcmyH6FlXVksZ3GqnOitKzzwhnbWLLUbJJ1emnYVRN3WdPWKtupei7m2a@6gdc6yXmQ9uepPTQ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4COGnMkZv8/jFLmDraB2F/n2lpj5zjAwldumWknkLrN4BqwYEzj/0TclzxFB8PMxCkRB61XE7l7/bwUPt48I1XQTP7Og/jrfnSCC6H@uYo//wU "Kotlin – Try It Online")
] |
[Question]
[
**This question already has answers here**:
[Expand the number](/questions/68939/expand-the-number)
(27 answers)
Closed 4 years ago.
Write a function to produce, for a non-negative integer, a string containing a sum of terms according to the following:
```
3 -> "3"
805 -> "800 + 5"
700390 -> "700000 + 300 + 90"
0 -> "0"
13 -> "10 + 3"
200 -> "200"
```
Any input other than a non-negative integer can be ignored. Zero terms must be skipped unless the input is 0. Terms must go from largest to smallest. The plus signs must have only a single space on either side.
This is code golf; fewest number of bytes wins.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 14 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
DḊƬḌINḟ0ȯ0j”+K
```
A full program which prints the result
**[Try it online!](https://tio.run/##ASkA1v9qZWxsef//ROG4isas4biMSU7huJ8wyK8wauKAnStL////NzAwMzkwIA "Jelly – Try It Online")**
### How?
```
DḊƬḌINḟ0ȯ0j”+K - Main Link: integer, n e.g. 805
D - to base ten [8,0,5]
Ƭ - collect until a fixed point:
Ḋ - dequeue [[8,0,5],[0,5],[5],[]]
Ḍ - from base ten (vectorises) [ 805, 5, 5, 0]
I - incremental differences [ -800, 0, -5 ]
N - negate [ 800, 0, 5 ]
ḟ0 - filter discard zeros [ 800, 5 ]
ȯ0 - OR zero (replacing an empty list with 0)
j”+ - join with '+' characters [ 800, '+', 5 ]
K - join with space characters [800,' ','+',' ',5]
- implicit, smashing print "800 + 5"
```
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 53 bytes
```
$&&&push@a,$&.y//0/cr while s/.//;$"=" + ";$_="@a"||0
```
[Try it online!](https://tio.run/##DcvRCsIgFADQd7/iYiJFbd41RoUM9gN9Q8gSNGzKvCOCfXu2t/Nykp1DV4qQUqYlu8GchKy/SqEaZ/g4HyxkVSulBe85HIFr8ej5YPi6YtGD6fcHvXstmcDZ2QJFcGZ6buu9BPJpA9lMGQxBnEZbWnbFjl0Q2xsyZE3Lzoi/mMjHKZfq3tXYYKlS@AM "Perl 5 – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 31 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")
Anonymous tacit prefix function, taking the number as a string.
```
(1↓∘∊1@1∘×⊆⌽∘⍳∘≢('+',10⊥↑)¨⊢)⍎¨
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///X8PwUdvkRx0zHnV0GToYAhmHpz/qanvUsxck1rsZRHYu0lDXVtcxNHjUtfRR20TNQysedS3SfNTbd2jF/7RHbROArEd9Uz39H3U1H1pvDFQB5AUHOQPJEA/P4P9pOurG6lxp6hYGpiDK3MDA2NIAyNJRB5HqhmBJIwMDdQA "APL (Dyalog Unicode) – Try It Online")
`⍎¨` execute each character (this gives the digits as numbers)
`(`…`)` apply the following anonymous tacit prefix function to that:
…`(`…`)¨⊢` apply the below function between each element and the corresponding element of…
`⌽` the reversal
`∘` of
`⍳` the **ɩ**ndices (1…N)
`∘` of
`≢` the tally of digits
`↑` take that many elements, padding with zeros (as there's only ever one)
`10⊥` evaluate that in base ten
`'+',` prepend a plus
…`⊆` partition it beginning a new segment where indicated by:
`1@1` a one **at** the first element
`∘` of
`×` the sign (0 for 0; 1 for all other)
`1↓` drop the first
`∘` of
`∊` the **ϵ**nlisted (flattened) data
] |
[Question]
[
GHC command line errors can be horrible, lets make them as bad as possible. To disincentivize very long programs use the following formula to calculate your "score".
```
(# of bytes of GHC output) / 2^(8 + # of bytes of code)
```
Template Haskell is banned as there is probably a TH configuration where you can replicate an error f(n) times where f is an arbitrary fast growing computable function. CPP and GHC options are banned for similar reasons.
GHC output should be computed using this release of [GHC 8.6.3](https://www.haskell.org/ghc/download_ghc_8_6_3.html).
To calculate the bytes of GHC output run:
```
ghc -hide-all-packages -package base Main.hs |& wc -c
```
The following is an example submission:
```
main = print (1 + True)
```
Error:
```
[1 of 1] Compiling Main ( Main.hs, Main.o )
Main.hs:1:15: error:
• No instance for (Num Bool) arising from a use of ‘+’
• In the first argument of ‘print’, namely ‘(1 + True)’
In the expression: print (1 + True)
In an equation for ‘main’: main = print (1 + True)
|
1 | main = print (1 + True)
| ^^^^^^^^
```
Score:
```
375 / 2^(8 + 24) = 0.0000000873114914
```
Submissions must contain the code and the score. Highest score wins.
[Answer]
# Score diverges to \$\infty\$
```
f=(:).(:)
g=f.f.f.f.f.f.f.f -- adding ".f" always results in better score
main=g+main g
```
Based on ASCII-only's construction, it is pretty easy to get ever-increasing score with longer and longer programs. Just posting to knock the challenge out of the unanswered list.
Given the following program form
```
f=(:).(:).(:) -- n copies of (:) composed
main=f+main f
```
the sizes of error messages are:
```
2 copies -> 2328
3 copies -> 8121 (x3.488)
4 copies -> 27121 (x3.339)
5 copies -> 103385 (x3.812)
6 copies -> 432486 (x4.183)
7 copies -> 1898125 (x4.388)
8 copies -> 8495224 (x4.475)
9 copies -> 39395094 (x4.637)
10 copies -> 198171503 (x5.030)
```
We can't know the exact formula of this because Haskell's error message pretty-printing is complicated, but we can at least know that adding one copy of `.(:)` consistently increases the error size by a factor of 4 or higher. In the top submission, adding two characters `.f` adds two copies of `(:)`, multiplying the error size by at least 16 and therefore the score by
\$16 \div 4 = 4\$.
To roughly see what is going on, here's the full error for 1-copy `(:)` program: (those `��`s are pretty quotes, which got somehow broken in my editor)
```
[1 of 1] Compiling Main ( Main.hs, Main.o )
Main.hs:2:1: error:
? Couldn't match expected type ��IO t0��
with actual type ��(a0 -> [a0] -> [a0])
-> (a0 -> [a0] -> [a0])
-> [a0 -> [a0] -> [a0]]
-> [a0 -> [a0] -> [a0]]��
? Probable cause: ��main�� is applied to too few arguments
In the expression: main
When checking the type of the IO action ��main��
|
2 | main=f+main f
| ^
Main.hs:2:6: error:
? Couldn't match type ��[a -> [a] -> [a]]�� with ��a -> [a] -> [a]��
Expected type: (a -> [a] -> [a])
-> (a -> [a] -> [a]) -> [a -> [a] -> [a]] -> [a -> [a] -> [a]]
Actual type: (a -> [a] -> [a])
-> [a -> [a] -> [a]] -> [a -> [a] -> [a]]
? Possible cause: ��(+)�� is applied to too many arguments
In the expression: f + main f
In an equation for ��main��: main = f + main f
? Relevant bindings include
main :: (a -> [a] -> [a])
-> (a -> [a] -> [a]) -> [a -> [a] -> [a]] -> [a -> [a] -> [a]]
(bound at Main.hs:2:1)
|
2 | main=f+main f
| ^^^^^^^^
```
and for 2-copy `(:)` program:
```
[1 of 1] Compiling Main ( Main.hs, Main.o )
Main.hs:2:1: error:
? Couldn't match expected type ��IO t0��
with actual type ��(a0 -> [[a0] -> [a0]] -> [[a0] -> [a0]])
-> (a0 -> [[a0] -> [a0]] -> [[a0] -> [a0]])
-> [[a0 -> [[a0] -> [a0]] -> [[a0] -> [a0]]]
-> [a0 -> [[a0] -> [a0]] -> [[a0] -> [a0]]]]
-> [[a0 -> [[a0] -> [a0]] -> [[a0] -> [a0]]]
-> [a0 -> [[a0] -> [a0]] -> [[a0] -> [a0]]]]��
? Probable cause: ��main�� is applied to too few arguments
In the expression: main
When checking the type of the IO action ��main��
|
2 | main=f+main f
| ^
Main.hs:2:6: error:
? Couldn't match type ��[[a -> [[a] -> [a]] -> [[a] -> [a]]]
-> [a -> [[a] -> [a]] -> [[a] -> [a]]]]��
with ��a -> [[a] -> [a]] -> [[a] -> [a]]��
Expected type: (a -> [[a] -> [a]] -> [[a] -> [a]])
-> (a -> [[a] -> [a]] -> [[a] -> [a]])
-> [[a -> [[a] -> [a]] -> [[a] -> [a]]]
-> [a -> [[a] -> [a]] -> [[a] -> [a]]]]
-> [[a -> [[a] -> [a]] -> [[a] -> [a]]]
-> [a -> [[a] -> [a]] -> [[a] -> [a]]]]
Actual type: (a -> [[a] -> [a]] -> [[a] -> [a]])
-> [[a -> [[a] -> [a]] -> [[a] -> [a]]]
-> [a -> [[a] -> [a]] -> [[a] -> [a]]]]
-> [[a -> [[a] -> [a]] -> [[a] -> [a]]]
-> [a -> [[a] -> [a]] -> [[a] -> [a]]]]
? Possible cause: ��(+)�� is applied to too many arguments
In the expression: f + main f
In an equation for ��main��: main = f + main f
? Relevant bindings include
main :: (a -> [[a] -> [a]] -> [[a] -> [a]])
-> (a -> [[a] -> [a]] -> [[a] -> [a]])
-> [[a -> [[a] -> [a]] -> [[a] -> [a]]]
-> [a -> [[a] -> [a]] -> [[a] -> [a]]]]
-> [[a -> [[a] -> [a]] -> [[a] -> [a]]]
-> [a -> [[a] -> [a]] -> [[a] -> [a]]]]
(bound at Main.hs:2:1)
|
2 | main=f+main f
| ^^^^^^^^
```
Basically the inferred type signature of `main` is blowing up by factor of >4. The type has the format of `x -> y -> z -> w`, where each of `x, y, z, w` contains the sub-structure `p -> q -> r`. When a copy of `(:)` is added, `q` and `r` parts are doubled and `z` and `w` are quadrupled.
] |
[Question]
[
**This question already has answers here**:
[Exploring the xorspace](/questions/124703/exploring-the-xorspace)
(8 answers)
Closed 5 years ago.
ProSet is a classic card game that is played normally with 63 cards. One card has 6 colored dots on it, like below
[](https://i.stack.imgur.com/Rk3Ti.jpg)
The rest of the cards are missing some of these 6 dots, but each card has at least 1 dot. Every card in the deck is different. Below are some example valid cards.
[](https://i.stack.imgur.com/mQob2.jpg)
A **ProSet** is a **nonempty** set of cards such that the total number of each color of dot is even. For example, the above set of 4 cards are a **ProSet** since there are 2 reds, 4 oranges, 2 greens, 2 blues, 0 yellows, and 2 purples.
Interestingly, any set of 7 cards will contain at least 1 **ProSet**. Hence, in the actual card game, a set of 7 cards are presented, and the player who finds a **ProSet** first wins. You can try the game out for yourself [here](http://www.mathcamp.org/2015/proset/).
# Challenge
Given a set of cards, each **ProSet** card can be assigned a value from 1 to 63 in the following manner: a red dot is worth 1 point, an orange 2 points, yellow 4, green 8, blue 16, purple 32. The sum of the values of each dot on the card is the value of the card.
**Input**: A list of integers from 1-63, i.e.,
```
[11,26,35,50]
```
This list represents the above 4 cards.
**Output**: The number of valid **ProSets**, which in this example is `1`.
# Rules
* This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge.
* This is also a [restricted-complexity](/questions/tagged/restricted-complexity "show questions tagged 'restricted-complexity'") challenge, as all valid solutions **must** be in polynomial time or less in the number of dots (in this case 6) **and** in the number of cards.
# Test Cases
I've created an exponential algorithm to find the correct output for every input [here](https://tio.run/##bVLLboMwEDzDV/hSyTSAYqrkgOJ@QQ899GahiiZOs6kxlg1t6M/TNQ55SJWQvLsez8yOMEN3aHUxjtCY1nZE940ZSO2INvFO7n3/Aq6jeKYNaCU1Z0kZR0A4CX3G4khxUcXRzwGUJMXjI4UFSzYc3yAyggVHyL615EhAE1vrT0khzRh@nio6IRe@OnrspPjMT34eqbw2RuodZYlv8SbjJ6ykcvIesESAlV1vNVWiLDNWJZN9cK@2pWp2rE3@K23rKPpG4LJKkhtn6uwWUbW19UCPV1Y/U4rCQ8H5PyxJkHP9x7vCuBxthqnwwjh0qC1EVQUxuMbgGWbolIVGJKaHVUhTkw0nt6hpb6T0@YeRgFJX56mbA8E6ZEYWnLBgIreyab8lFdVlL@/YTda3B7n9kjZkpZD9uouYfwJI1wm5bKCuNFSEoOHuOt@2ve7om@0l5jMaC9jNOoKxtFinT6t05QMc/wA). Again, exponential solutions are **not** valid submissions. But, you can use this to validate your findings.
# Edit
I will address the comments in a bit. But for now, none of the answers have been in polynomial time. It is indeed possible, so here's a hint: **binary** representation and two s complement.
Moreover, I made a mistake earlier when I said polynomial in solely dots. It needs to be polynomial in dots and cards.
[Answer]
# [Python 2](https://docs.python.org/2/), 60 bytes
```
p=[0]
for i in input():p+=[n^i for n in p]
print~-p.count(0)
```
[Try it online!](https://tio.run/##K6gsycjPM/r/v8A22iCWKy2/SCFTITMPiApKSzQ0rQq0baPz4jIVQBIgUYWCWK6Cosy8kjrdAr3k/NK8Eg0Dzf//ow0NdYzMdIxNdUwNYgE "Python 2 – Try It Online")
This generate the powerset from the input (based on [this answer](https://codegolf.stackexchange.com/a/51675/)), reducing each subset by `xor`.
The output will be the amount of `0`s (0 = all bytes/dots appear an even number of times).
In fact the xoring is done instead of the "powerset appending", but the result is the same
[Answer]
# Japt, 8 bytes
```
à x@!Xr^
```
[Try it here](https://ethproductions.github.io/japt/?v=1.4.6&code=4CB4QCFYcl4=&input=WzExLDI2LDM1LDUwXQ==)
[Answer]
## JavaScript (ES6), 53 bytes
```
f=
a=>a.map(i=>p.map(j=>n+=p.push(j^=i)&&!j),p=[n=0])&&n
```
```
<input oninput=o.textContent=f(this.value.split`,`)><pre id=o>
```
Loosely based on @Rod's Python answer.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ŒPḊ^/€¬S
```
A monadic Link. 9 bytes if the empty set is considered a ProSet - `ŒPḊ^/€¬S‘` (since reducing an empty list errors).
**[Try it online!](https://tio.run/##y0rNyan8///opICHO7ri9B81rTm0Jvj////RhoY6RmY6xqY6pgaxAA "Jelly – Try It Online")**
### How?
```
ŒPḊ^/€¬S - Link: list of integers, L
ŒP - powerset (of cards)
Ḋ - dequeue (remove the empty list)
/€ - reduce €ach with:
^ - XOR
¬ - NOT (vectorises)
S - sum
```
[Answer]
# Clojure, 182 166 149 127 bytes
```
(defn f[k]((frequencies(map(fn[x](reduce #(bit-xor % %2)0 x))(reduce(fn[c n](concat(map #(concat %[n])c)[(list n)]c))'()k)))0))
```
If I had barfed on the screen, it would've looked better than this
[Try it online!](https://tio.run/##LYtRCoMwEAWvslCk@8CCWuxlQj7suoFUu9oYwdtbpf0cZkbG6bUm3XfuNRgFN3jmkPSzqknUhd/dzMHc5jlpv4rShZ8x37YpUUFFg4o24O/OUMg8y2TS5fM98h9Q4cxD4HiMSyaDF@DKGABUwM5zipaJA7m6LptHeW/LtvKH@QI "Clojure – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 88 bytes
```
lambda l:~-sum(x<1for x in f(l))
f=lambda l:l and[n^l[0]for n in f(l[1:])]+f(l[1:])or[0]
```
[Try it online!](https://tio.run/##K6gsycjPM/qfbhvzPycxNyklUSHHqk63uDRXo8LGMC2/SKFCITNPIU0jR1OTK80WriRHITEvJTovLifaIBakKg@qKtrQKlYzVhvGyi8Cyv8vKMrMK1FI14g2NNQxMtMxNtUxNYjV/A8A "Python 2 – Try It Online")
] |
[Question]
[
**This question already has answers here**:
[Code Golf: Your own horizontal pet ASCII snake](/questions/156369/code-golf-your-own-horizontal-pet-ascii-snake)
(27 answers)
Closed 5 years ago.
...or "[snakes but not too long](https://www.xkcd.com/1354/)".
Inspired by [this challenge](https://codegolf.stackexchange.com/questions/156245/code-golf-your-own-pet-ascii-snake) and [this comment](https://codegolf.stackexchange.com/questions/156245/code-golf-your-own-pet-ascii-snake#comment380722_156256).
## Task
Write a program or a function that takes no input and outputs its own source code formatted as a snake according
to the rules below:
1. If your code has any whitespace, it will not be output; it will just be skipped.
2. There will be one character on each column in the output.
3. The first character in the code is placed on the first column of line **x**.
4. The second character is placed on the second column of either line **x**, **x-1**, or **x+1**. More generally, the **n**th character (excluding whitespace) goes to the **n**th column on a line that is one above, one below, or the same as the line on which the previous character went.
5. The character on the highest line will be on the first line in the output; that is, there are no extraneous leading lines. A single, empty trailing line is allowed.
For example, if the code was `from python import snake`, the output should look like:
```
th
y o s ke
f mp ni po t na
ro m r
```
or
```
e
k
f a
r n
om o im s
p h n po t
yt r
```
All valid forms of snake should have a nonzero probability of occurring. Your program's source code should contain at least two non-whitespace characters.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 47 bytes
```
4"D34çýSDεXD<X>ŸΩU}W-úζ»"D34çýSDεXD<X>ŸΩU}W-úζ»
```
[Try it online!](https://tio.run/##MzBNTDJM/f/fRMnF2OTw8sN7g13ObY1wsYmwO7rj3MrQ2nDdw7vObTu0m4D0//8A "05AB1E – Try It Online")
] |
[Question]
[
Write a program that reviews posts for the Close Votes queue on Stack Overflow.
Since it's near-impossible to write a bot that can accurately review posts in the actual queue, **we're instead going to use a grossly oversimplified version of the queue and its rules.**
Your program should take in the body of a question as a string, and output an array of [`option_id`](https://api.stackexchange.com/docs/types/flag-option)s for the applicable close reasons. For Leave Open, you can output an empty array OR a falsey value. **Note: this is a significant change from [the sandbox version of this challenge](https://codegolf.meta.stackexchange.com/a/14213/62402) so make sure to update stashed solutions.**
Here is a list of the close reasons, their fresh-off-the-API `option_id`s, and the gross oversimplifications that should be used to flag them. All keywords and key phrases are case-insensitive and should have word boundaries on both sides.
* `28509` - **duplicate**
+ *Question contains the keyword `NullPointerException`. When this appears, the next array element should be the question ID `218384`, for [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/q/218384/6388243)*
* **off-topic because…**
+ `46431` - Questions about **general computing hardware and software** are off-topic for Stack Overflow unless they directly involve tools used primarily for programming. You may be able to get help on [Super User](http://superuser.com/about).
- *Contains the keyword `install`, or its various conjugations: `installs`, `installing`, `installation`, `installed`.*
+ `36074` - Questions on **professional server- or networking-related infrastructure administration** are off-topic for Stack Overflow unless they directly involve programming or programming tools. You may be able to get help on [Server Fault](http://serverfault.com/about).
- *Contains the keyword `server`, but NOT `php` or `cgi`.*
+ `54583` - Questions asking us to **recommend or find a book, tool, software library, tutorial or other off-site resource** are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, [describe the problem](http://meta.stackoverflow.com/questions/254393) and what has been done so far to solve it.
- *Contains one of the mentioned words (`book`, `tool`, `software library`, `tutorial`, `API`) or their plurals.*
+ `77` - Questions seeking debugging help ("**why isn't this code working?**") must include the desired behavior, a *specific problem or error* and *the shortest code necessary* to reproduce it **in the question itself**. Questions without **a clear problem statement** are not useful to other readers. See: [How to create a Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve).
- *The question has no code markdown. You may assume that code markdown will not be inside any other syntax.*
+ `44435` - This question was caused by **a problem that can no longer be reproduced** or **a simple typographical error**. While similar questions may be on-topic here, this one was resolved in a manner unlikely to help future readers. This can often be avoided by identifying and closely inspecting [the shortest program necessary to reproduce the problem](http://stackoverflow.com/help/mcve) before posting.
- *There are unpaired or incorrectly paired parentheses, brackets, or braces.*
* `16055` - **unclear what you're asking**
+ *The question does not contain a question mark character.*
+ *The question has no latin characters.*
+ If *either* of the above apply, then it should appear in the output array, but it shouldn't appear twice.
* `29650` **too broad**
+ *The question contains a question starter (`who`, `what`, `when`, `where`, `why`, `how`) followed by `should I`.*
* `62000` **primarily opinion-based**
+ *The question contains the phrases `best/good/bad practice(s)`, or `good/bad idea(s)`.*
As usual for a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, the winner is the shortest answer in bytes.
# Test Cases
* <https://stackoverflow.com/revisions/092483f5-05a5-4488-a057-4ddb3040e380/view-source> - `[46431, 77, 16055]`
* <https://stackoverflow.com/revisions/1914fd5e-8686-402a-839e-cd1ba849aafe/view-source> - `[36074, 77]`
* <https://stackoverflow.com/revisions/db0992bb-f423-4a93-b349-ec887aea0a5f/view-source> - `[54583, 77, 16055]`
* <https://stackoverflow.com/revisions/7c0a011f-7ebc-494d-bc8c-85bedefc53b7/view-source> - `[77, 16055, 62000]`
* <https://stackoverflow.com/revisions/4e109537-ca2c-40ae-807e-e1132eb3e82f/view-source> - `[29650]`
* <https://stackoverflow.com/revisions/79593197-9104-4dd4-8021-ff43f5a0b03d/view-source> - `[77, 16055]`
* <https://stackoverflow.com/revisions/16b8e492-c425-4090-b283-c42e2177b34f/view-source> - `[16055]`
* <https://stackoverflow.com/revisions/8cd44765-297e-435e-a035-044ff67fcd0c/view-source> - `[]` or falsey
* <https://stackoverflow.com/revisions/932054a6-6e6b-4446-86a2-5deb8c505e96/view-source> - `[28509, 218384, 16055]`
[Answer]
# Python 2.7, ~~644~~ ~~639~~ ~~593~~ ~~560~~ 549 bytes
```
from re import*
s,g,t,w=input(),"([{)]}",[],"NullPointerException"
l=g.index
print[[29650,46431,54583,62000,16055,77,36074,28509,218384][i]for i,r in enumerate(["(wh([oy]|at|en|ere)|how) should I","install(ing|s|ation|ed)","(book|tool|software librar(ies|y)|tutorial|API)s?","(best|good|bad) (practice|idea)s?","^[^a-z]*$|^[^?]*$","^((?![#*[(~>`=]|\d\.|\-{3}).)*$","(?=^.*server)(?!^.*(php|cgi))",w,w])if search(i<5and r or"(^|\W)"+r+"($|\W)",s,flags=I|S)]+[44435]*(any(t.append(g[l(c)+3])if l(c)<3else t==[]or c!=t.pop()for c in s if c in g)or[]<t)
```
[Try it online!](https://tio.run/##7ZZRb9s2EIDf/SuuWoBSiSJItmU7Qb3A6IrNwJoVW7cCU5yNlmiJM00KJGXFq7q/np2kOEkzd@iAPQ0LEJji3X28Ox55LHY2V7J/y2VRWpiCoJtlSs/BcRy6VDgVBpDSnQGaKQ82O6BFAcZSbVkKVoFmidI4yrkBdpOwwnIlgRjGJOAgZVtIlDRKMPe81wP8@41uqS@ozPzLUog3ikvL9Ku96Tm0SgDUgtKZn@RabXi58alMteLpLxVbbjmr/Fn1UqGltOZoVv2EM68ZRpKa@aYQvpJfaZq92qIYyIOm36x9Hp6F7sMiibpn@3v2/aLv2LJBv9x/f8R9Kmzh40n/EfwReM3tHncQ05n3o2h4wL71qtVKuSmoTfJHgEfW/X7Q/zvzr7Uqi08xOmGXouEg/Hc44fh/zn@H871Stj1gOYoEewK6l7as0SCYfBbrtNK0CMMDjM8xP9p/fNO6pO9ce82MoRk75NgwPDs7QFbG3yP2ibqH7AVdkg6eMTT/VqkClQT@ALn76CwOHmq8Sf1ZYvmW293bXDOa@hvK8fJ8MtllczwePWI8XKKarQRLrN9dfz6XW7VGjy8pMhh0s5@47tqbV1LR@P7zLlOWzSW3R53NTKYznZmXVDSB6xL9etDZV8vZ6B@h7@L7C2cwQU5v/hwdlgp4yijwhleKFJYYjMFJSKh8brHfFIIn1DLUcJtUNs0oWVtNE4YWW6YNMiQDtWq6VSKoMcz4MGub2ZM2NccWJXawlqpCEbXYfHpwCmy1woyaTogdjCfMQMVtvt86GGNvgrEfQqO@4togmm9w0SQptcbOiOX8XWKhH4TjVgfDuZd1fTUKWhMDWCVth/WglJYLiOBSbT@yZDeFUClarrDTwOhB3hk03nfeteDBMNivJZMHfq/3o8HknGLVnZZtVWMqMHdLwTruXbuHHaMayCAIAsDMGczTYx/DaMNlae@4ewXXh94MHwaIpIDNnlvKNe4HxadBRpsoCW7sSuOwUnoN1IDgyyy9gdKw1PV7vbd4bNewUyXgFu5gUya5j2@Q29Y1RPFNobQ97hkv86xXTdv3CnE9h8Tv3cUHx4sXnnPoQeH0xDTDekzZTa/QKIvj/tkoCrzhCJucFw2jycAb9TFcLxwFUeSNx95gFIyHXn8SBWdeP5wMJsNFzBcr3HPu4b8EJssN01iFJHZIlZNY7RY1tTWTNdPMrXNVuWDytoDnjudwiZkWgnCZ1QYV0a8a40YJWSq1rq1SojZqZSuKsWJqNNWEM1Pv3NqWVmlORT17M3fNRWvDjK0zpdJ6SVMXSIHVb7FK6@bodDrX8TU9/X1xfFTj6AJ/mzlCLp7FXxzH5I8vf50u6qv0yq@vTt8PPri@22qQi@m1f4x1gpvgojJ@kCIv6iTjLnpbedXC5SvcdqqTnPAXUXMANR4Gh1zXV@9c50SfOOSoHXrGWwmamem8/sFdnMTD4XAQLY4JlTtim8uPyZRksSCJezJosc3wxYAJw8BOp/EC8508m1q/UAVxm@wnTe4NoGo7ylyl48UL697e/gk "Python 2 – Try It Online")
The basic concept is to use a series of regex's to do most of the heavy lifting. I do rebuild regex's to reduce bytes; if you wish to see the full regexes, refer to the ungolfed section below. Then, I go through and check stuff that regex isn't good at (like matching parenthesis correctly).
# Important note regarding testing
The examples as given in OP's post are wrong. If you look through the links, you should be able to notice where my program is finding the correct solution. For instance, the OP's didn't seem to recognize `>` and other markdown as markdown. That is where most of the variance comes from.
# Pseudo-ungolfed version
I decided that it may be beneficial for understanding to post a precursor to my code-golf.
```
import re
def doesMatch(string):
openClosed = "([{)]}"
current = []
for char in string:
if char in openClosed:
if openClosed.index(char) < 3:
current.append(openClosed[openClosed.index(char)+3])
elif len(current) == 0 or current.pop() != char:
return False
return not len(current)
def take(post):
regexes = [
"(^|\W)(who|what|when|why|how|where) should I($|\W)",
"(^|\W)install(ing|s|ation|ed)($|\W)",
"(^|\W)(book|tool|software library|software libraries|tutorial|API)s?($|\W)",
"(?=^[^a-z]*$)|(?=^[^?]*$)",
"(^|\W)(best|good|bad) (practice|idea)s?($|\W)",
"^((?![#*[(~>`=]|\d\.|\-{3}).)*$",
"(?=^.*server)(?!^.*(php|cgi))"
]
errors = [[29650,46431,54583,16055,62000,77,36074][i] for i,regex in enumerate(regexes) if re.search(regex,post,flags=re.I|re.S)]
if not doesMatch(post):
errors.append(44435)
if post.find("NullPointerException") != -1:
errors += [28509,218384]
return errors
with open("test.txt","r") as fi:
print(take(fi.read()))
```
Thanks to the following for helping reduce bytes:
* LyricLy
* notjagan
* ovs
* Mr. Xcoder
] |
[Question]
[
### Challenge closed, the shortest answer has been acccepted.
A military projection is a projection where all lengths and the angles in the X-Z plane remain unattuned.
Your task is to print a cube in military projection using `/`, `|`, `\`, `-`, and any whitespaces you want, given any integer greater than zero as it's side length. You can leave sides out that are not visible to the human eye.
Here are some examples:
```
/-\
/ \
|\ /| Side length:
| \ / | 2
\ | /
\|/
/-\
/ \
/ \
/ \
/ \
|\ /|
| \ / | Side length:
| \ / |
| \ / | 5
| \ / |
\ | /
\ | /
\ | /
\ | /
\|/
/-\ Side length:
|\ /|
\|/ 1
```
(Printing the side lengths is not required.)
For the uppermost corner you must use the dash.
As you can see, all sides are equal in length (when measured in characters).
You may use any kind of spacing you wish, and omit any characters that don't change the appearance of the cube.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins!
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 19 bytes
```
Nθ←¹↙θ↓θ→↘θ↑↑θ←↖θ‖B
```
[Try it online!](https://tio.run/##S85ILErOT8z5///9nnXndjxqm3Bo56O2mSDWZBAx6VHbDBA9EYjA0o/apgHphmnv9yz6/98IAA "Charcoal – Try It Online")
[Answer]
# Python 2.7, ~~198~~ ~~185~~ 172 bytes
```
i=n=input();x=1;s,l,r,p='/|\ '
print p*n+'/-\\'
exec'x+=2;i-=1;print p*i+s+p*x+r;'*~-n+'i-=2;'+'i+=1;print l+p*i+r+p*x+s+p*i+l;x-=2;'*n+'print(n-i)*p+r+p*i+l+p*i+s;i-=1;'*n
```
[Try it online!](https://tio.run/##Pc3BCsMgDAbge5@it7RGKfMqvklvo7CAZEEdOBh7dWcztkv@wP@RyLPe7ux7p8iRWB51WUOLl1BsstlKhO21zzBJJq6zGEbY3L7DdLTjCg2jD@QG//WEBcU0zAHM2w09Wh9gJP5VwtNldUX3FJqy87yahR2tRhSNWmf5fhqod/8B)
Immense scope for golfing. I'm missing something out here, most probably!
Edit 1: -13 bytes: That's a start
Edit 2: -13 bytes: courtesy [Erik the Outgolfer](https://codegolf.stackexchange.com/users/41024/erik-the-outgolfer)
[Answer]
# [SOGL V0.12](https://github.com/dzaima/SOGL), ~~39~~ ~~38~~ ~~34~~ 33 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
∫:┘ž}³№↕≥++┌.I1ž.┐∙:.2+.Iž0.I╬5╬⁷
```
[Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JXUyMjJCJTNBJXUyNTE4JXUwMTdFJTdEJUIzJXUyMTE2JXUyMTk1JXUyMjY1KysuJXUyNTEwJXUyMjE5JTNBLjIrLkkldTAxN0UwLkkldTI1NkM1JXUyNTBDLjIrMSV1MDE3RSV1MjU2QyV1MjA3Nw__,inputs=Mw__)
Explanation:
```
∫ } for 1-indexed range in the input
: duplicate current index
┘ž at [index; index] in POP (by default the input, but in the 1st cycle it gets overwritten) insert a "\"
³ triplicate that array of a big diagonal
№↕ mirror/reverse one of those vertically
≥ put that at the stacks bottom
++ join the three items together, resulting in the 3 diagonal lines of the result
┌.I1ž insert a dash at coordinates [input+1; 1] insert the dash
.┐∙ get an array of vertical bars with the size of the input (aka a vertical bar)
: duplicate that
.2+.Iž at postition [input+2; input+1] insert the 2nd vertical bar in the 1st (resulting in the required vertical bars the correct distance apart)
0.I╬5 at position [0; input+1] insert the vertical bars without overwriting spaces; as the position numbers are 1-indexed this extends the array left
╬⁷ palindromize horizontally, mirroring the required characters and with 1 overlap
```
] |
[Question]
[
### You're in charge of distributing T-Shirts to everyone. Simple enough, right? But remember, there are different sizes of T-Shirts, and you have to keep that in mind...
# Challenge Specifications
There are `N` T-Shirt sizes. There are `K` people. Each person may wear any T-Shirt that is larger than them, but they can only wear a T-Shirt that is `D` sizes down. You want to figure out what the optimal configuration is, based on the cost of the system. It is guaranteed that everyone will be able to get a T-Shirt, so you must give everyone a T-Shirt.
The cost is calculated as such:
Start from `0` and add up.
For every person who receives a T-Shirt, add `|S1 - S2|`, where the person is size `S1` and they are receiving a T-Shirt of size `S2`.
# Input Specifications
The input starts with the integers `N`, `K`, and `D`. You can choose to not input `N` or `K` if you want. These can be given in an array, one on each line, space separated, or pretty much anything you want, but they must be given in this order. You must specify how you want input.
Then, the next part of the input is `N` integers representing how many T-Shirts of each size there are. For example, with `N := 3`, `[1, 4, 2]` means that there is 1 size 1 T-Shirt, 4 size 2 T-Shirts, and 2 size 3 T-Shirt. It is guaranteed that the sum of these numbers equals `K`. This can be taken as an array, an array contained at the end of the first part of input, an array joined to the end of the first part of the input, one on each line, space separated, or some other one that does not put you at a clear advantage. Again, please specify how you want input.
Then, the next part of the input is `K` integers representing the individual size of each person. This order matters. This can be taken as an array, an array contained at the end of the first part of the input, etc.
You can also choose to start with size-0.
# Output Specifications
Output must consist of `K + 1` integers. The first `K` of these represents the size of T-Shirt given to each person, and the last integer is the overall cost. This can be outputted as an array, space-separated integers, one on each line, etc.
# Test Cases
**Input:**
```
3 10 1
3 5 2
1 1 1 2 2 2 2 2 3 3
```
**Output:**
```
1 1 1 2 2 2 2 2 3 3 0
```
**Explanation:**
This one's an easy case; each person gets the size of T-Shirt matching them, so the overall cost is `0`.
**Input:**
```
2 10 0
5 5
1 1 1 1 1 1 2 2 2 2
```
**Output:**
```
1 1 1 1 1 2 2 2 2 2 1 # Or 2 1 1 1 1 1 2 2 2 2, or similar outputs
```
**Explanation:**
There are 5 size-1 shirts, which are given to 5 of 6 size-1 people. There are 5 size-2 shirts, 4 of which are given to the 4 size-2 people. There is one more size-1 person and one more size-2 shirt, so this assignment is made at a cost of `1`.
**Input:**
```
7 20 2
5 0 5 0 5 0 5
3 5 7 9 3 5 7 9 3 5 7 9 3 5 7 9 3 5 7 9
```
**Output:**
```
1 3 5 7 1 3 5 7 1 3 5 7 1 3 5 7 1 3 5 7 40
```
**Explanation:**
At first glance, it may make sense to assign everyone the size of T-Shirt they need. However, then we get 5 size-9 people and 5 size-1 T-Shirts, and people can only wear shirts down 2 sizes, so we assign everyone a T-Shirt 2 sizes down, at a cost of `40`.
This test case is also in place to address the possible confusion that you can output the shirt sizes sorted. This is not *always* the case, as shown in this test case.
This is a code-golf challenge, so the shortest valid submission by March 14th (Pi Day) wins!
[Answer]
# [Perl 6](https://perl6.org), 77 bytes
```
->$,\t,\p{flat(1..*Zxx t)[[p].&{@(.sort)=0..*;$_}].&{|$_,(p Z-$_)».abs.sum}}
```
[Try it online!](https://tio.run/nexus/perl6#y61UUEtTsP2va6eiE1OiE1NQnZaTWKJhqKenFVVRoVCiGR1dEKunVu2goVecX1SiaWsAlLFWia8FCdaoxOtoFChE6arEax7arZeYVKxXXJpbW/u/oLREIU3BUEfBxljBVMHIDsgwVABBIzg0VjC2s@aCKDQAypsqmCKUoSiGKzMCKzNQgGM7qAXmCpYKBGigIf8B "Perl 6 – TIO Nexus")
Simply matches the n'th smallest T-Shirt to the person with the n'th smallest size.
I'm not absolutely sure if that is guaranteed to give the correct result for all possible inputs, but it works for the test-cases given in the task description.
---
# [Perl 6](https://perl6.org), 97 bytes
```
->\d,\t,\p{flat(1..*Zxx t).permutations.map({|$_,(p Z-$_)».&{$_>d??∞!!.abs}.sum}).min(*[*-1])}
```
[Try it online!](https://tio.run/nexus/perl6#HcZRCsIgGADg907xD2TocD9Yj5W7x1qIsYRBLmkKC/O9U3SR3jpKF7ER38tn71Aa2Odadj3vPO9cNBftqUCs2nkGz9CdbzZ47YfrOKHVjsYHUZw6aGui2OeNZSRK9k3zfb6KAvVpSjgFmxjaYaTVoarFkaXsggcDgsNuA2sQcokAsfRPblf5Bw "Perl 6 – TIO Nexus")
Dumb brute-force solutions.
Takes around 15 minutes for the test-cases with 10 people, so the test-case with 20 people should only take, uh, millions of years... :D
(Memory usage should remain steady though, because `permutations` and `map` return lazy one-off sequences, and `min` also only needs to keep one element in memory.)
---
Both versions take three input arguments:
* The number `D`.
* The array for the T-Shirts.
* The array for the people.
[Answer]
# Python 2, 121 119 115 106 bytes
```
def f(a,b):
j=h=0
for i in a:j+=1;exec"q=b.index(min(b));h+=abs(j-b[q]);b[q]=`j`;"*i
print map(int,b),h
```
[Try it Online!](https://tio.run/nexus/python2#lUzdCoIwGL3fU3zYzZYrtJDIsbfoTgZuurENXOq88O1tRUR0FxzOD5xztl4bMFhSRWoEnlteIDD3GRy4ALL2OS@ZXnWXTVwdXej1igcXsCKE2ZxLFbE/qGYShD2Zt75l2d4hGGcXFhjkiJOmd2q3Hdx0XKCTUUdkcFNRqARtSgo/OH0gyLtYpO43p935FS4UrhT@84JsDw)
Takes both lists, without N, K or D. Outputs a list of sizes, followed by the cost
**Edit:** I found a cool trick using exec that took off 9 bytes!
[Answer]
# [k](http://kparc.com/), ~~47 44 35~~ 25 bytes
Stealing from the [Perl6 solution](https://codegolf.stackexchange.com/a/111062/42775), it matches the smallest shirt to the smallest person it can.
It turns out, D is also unnecessary! This takes advantage of that. It takes in two lists as arguments.
```
{x,+/%y*y:y-x:(1+&x)@<<y}
```
[Try it online!](https://tio.run/#XwqQN)
[Try it in oK.](http://johnearnest.github.io/ok/?run=f%3A%7Bx%2C%2B%2F%25y%2ay%3Ay-x%3A%281%2B%26x%29%40%3C%3Cy%7D%0A)
Explanation:
```
{ } /function(x,y)
<<y /grade up the grade up of the people
/ returns indices needed to rearrange a list of shirts
(1+&x) /expand the list into a list of shirts
x: @ /x = rearrange shirts by said indices
y- /S1 - S2
%y*y: /absolute value
+/ /total to get the score
x, /prepend the list of rearranged shirts
```
] |
[Question]
[
Write a function or program that awards you SE badges. If an input "Q" is given it means you have asked a question. If no input is given it means you have only visited the site.\*
Badges it must support:
* Run script 30 days in a row: "Enthusiast"
* Run script 100 days in a row: "Fanatic"
* Input "Q" first time: "Student"
* Input "Q" on 5 separate days: "Curious"
* Input "Q" on 30 separate days: "Inquisitive"
* Input "Q" on 100 separate days: "Socratic"
**Input:**
* You may choose an arbitrary input value for the times you ask questions (I've used "Q" as an example).
* You may choose an arbitrary input value, or have none at all, for the times you only visit the site.
* If a third type of input is given, say "R", then the counters and list of badges shall be reset. This is to ensure that the program can be reused.
Note, you may visit the site many times each day, and ask several questions on the same day. As with the real badges, days are counted in [UTC](https://en.wikipedia.org/wiki/Coordinated_Universal_Time).
You can only have one of each of the badges.
The source code can be altered, but remember the reset functionality. The score will be the size of the script before it's executed the first time.
**Output:**
Every time you run the script it should output/print a list of badges you have. The output format is optional, but it must use the proper badge names, i.e. you can't enumerate the badges.
The output should be an empty string, `0`, `false` or something similar if you don't have any badges. The program can't crash, enter an infinite loop or something similar.
---
This is code golf, so the shortest code before running the script the first time. As always, the score is counted in bytes.
You may use an external file to store information, but both the name of the file, and the size of the file before the code is executed the first time will count toward the score.
[Answer]
I guess I'll start.
# **JAVA: 572 bytes**
```
public class a {static Map<Integer,String>o=new HashMap<Integer,String>();static Map<Integer,String>p=new HashMap<Integer,String>();public static void main(String[] args){Scanner d= new Scanner(System.in);b();int e=0,v=0;while(true){char y=d.nextLine().toCharArray()[0];if(y=='Q'){e++;v++;}else if(y == 'R'){e=0;v=0;b();}else{v++;}System.out.println(o.get(v)+p.get(e));o.remove(v);p.remove(e);}}public static void b(){o.clear();p.clear();o.put(30,"Enthusiast");o.put(100, "fanatic");p.put(1, "student");p.put(5, "Curious");p.put(30,"Inquisitive");p.put(100, "Socratic");}}
```
Input:
"R" to reset
"Q" if you asked a question
" " if you visited.
[Enter] to log your day.
Output: The badges that you earned that day.
] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
This question does not appear to be about code golf or coding challenges within the scope defined in the [help center](https://codegolf.stackexchange.com/help/on-topic).
Closed 9 years ago.
[Improve this question](/posts/39815/edit)
After noticing all the [fractal](http://en.wikipedia.org/wiki/Fractal) submissions/questions, I thought it would be fun to start a contest where everyone submits their favourite fractal.
**The Contest**
Generate a fractal in under 200 characters using any language. The output of the function can be an image, ascii art or any representation of a fractal you can think of. In your submission include your code, how to run your code, and sample outputs of your fractal. This is a popularity contest, so the submission with the most votes wins.
**Rules**
* You may use any libraries, except those which generate fractals (e.g. a library function that generates a mandelbrot set is not allowed)
* It is difficult to define a true fractal, so I will accept anything that has self-similarity and has fractal dimension greater than its topological dimension
* You may submit multiple answers
Good luck, have fun!
[Answer]
# Python, 127 bytes
Creates a Sierpinski triangle.
```
import Image
f=1e3
a=Image.new('RGB',(f,f))
p=a.load()
r=range(f)
for i in r:
for j in r:p[i,j]=(i*16&j*16,)*3
a.save('s.png')
```

] |
[Question]
[
**This question already has answers here**:
[One Ring to rule them all. One String to contain them all](/questions/13088/one-ring-to-rule-them-all-one-string-to-contain-them-all)
(21 answers)
Closed 9 years ago.
There's a simple digital number lock. After each button press the lock checks if the previous four presses constitute the correct code. I.e. typing 44445 tests two codes: 4444 and 4445. You must brute force it with a code golfed program.
## Rules
* Your program must test numbers by printing ASCII digits 0-9 to standard output. Other output, if any, will be ignored.
* The program must be deterministic. If you need "random" numbers, you must use a deterministic generator with a well defined seed.
* Infinite output beyond all 10^4 codes is allowed. Opening the lock is considered to stop the program.
## Scoring
* Calculate the average digits of output needed to crack the lock. I.e. search the output string for every possible four digit sequence and record where it first appears.
* Add the source code length in bytes. The program must be fully functional, you are not allowed to omit imports or other boilerplate.
>
> **Score = Average digits to crack + codelength in bytes**
>
>
>
## Example entry
Python, 35 bytes.
```
for i in range(9001):print '%.4d'%i
```
Score: 8444.9837 + 35 = 8479.9837
## Other
Simple, stupid Python program to verify score of an output string:
```
d = {}
s = ''.join(c for c in s if '0' <= c <= '9')
for i in range(len(s)-4):
t = s[i:i+4]
if t in d:
continue
d[t] = i + 4
if len(d) == 10000:
break
print sum(d.values()) / 10000.
```
[Answer]
# Java 5218
This is the (golfed) code:
```
class a{int[]a=new int[5];public static void main(String[]a){new a().b(1,1);}void b(int t,int p){if(t>4)for(t=0;++t<=p&&4%p==0;)System.out.print(a[t]);else{a[t]=a[t-p];b(t+1,p);for(a[t]=a[t-p];++a[t]<=9;)b(t+1,t);}}}
```
It prints a specially crafted sequence to stdout. The completed sequence has all combinations, only once, in the shortest way possible. The total length is 10.000 with the first combination after 4 (obviously) and the last after 10.000. So if I understand the challenge correctly my score is:
```
4 + ((10000-4)/2) = 5002 avg length to break the code
5002 + 216 (code length) = 5218
```
Obviously this score will be improved (Java is pretty verbose), so I'm not going to tell you the name of the sequence I'm using...
[Answer]
# Haskell, 120 bytes + 5001.5 = 5121.5
```
import Data.List
main=print$(nub$sort[sort s|x<-[1,2,5,10],s<-sequence$replicate x['0'..'9'],any(/=s!!0)s||x<2])>>=id++"000"
```
] |
[Question]
[
A **limit** in math determines the value that a function `f(x)` **approaches** as `x` gets closer and closer to a certain value.
Let me use the equation `f(x)=x^2/x` as an example.
Obviously, `f(x)` is undefined if x is 0 (x=0, x2=0, 0/0 is undefined).
But, what happens when we calculate `f(x)` as `x` approaches 0?
`x=0.1, f(x)=0.01/0.1 = 0.1`
`x=0.01, f(x)=0.0001/0.01 = 0.01`
`x=0.00001, f(x)=0.0000000001/0.00001 = 0.00001`
We can easily see that `f(x)` is approaching 0 as `x` approaches 0.
What about when `f(x)=1/x^2`, and we approach 0?
`x=0.1, f(x)=1/0.01=100`
`x=0.01, f(x)=1/0.0001=10000`
`x=0.00001, f(x)=1/0.0000000001=10000000000`
As `x` approaches 0, `f(x)` approaches positive infinity.
You will be given two things in whatever input format you like:
* `f(x)` as an `eval`-able string in your language
* `a` as a floating point
Output the value that `f(x)` approaches when `x` approaches `a`. Do not use any built-in functions that explicitly do this.
**Input Limitations:**
* The limit of `f(x)` as `x` approaches `a` will always exist.
* There will be real-number values just before and just after `f(a)`: you will never get `f(x)=sqrt(x), a=-1` or anything of the sort as input.
**Output Specifications:**
* If `f(x)` approaches positive or negative infinity, output `+INF` or `-INF`, respectively.
* If `f(a)` is a real number, then output `f(a)`.
**Test Cases:**
```
f(x)=sin(x)/x, a=0; Output: 1
f(x)=1/x^2, a=0; Output: +INF
f(x)=(x^2-x)/(x-1), a=1; Output: 1
f(x)=2^x, a=3; Output: 8
```
Shortest code wins. Good luck!
[Answer]
## C, 402 bytes
Plenty of room for golfing, just proof of concept to begin with :P
Compiles under clang, osx.
Note: For linux you may have to change the code to use something like: "ld -shared f.o -o f.so -lm"
```
#include<dlfcn.h>
#include<stdio.h>
float e,r;
main(int i,char**v){
// create and compile temporary c file for 'f(x)'
// note: include offset within function
FILE*s=fopen("f.c","w");
fprintf(s,"#include<math.h>\nfloat f(float x){x+=%s;return %s;}",v[2],v[1]);
fclose(s);
system("cc -fPIC -c f.c;ld -bundle f.o -o f.so -lm");
float(*f)(float)=dlsym(dlopen("f.so",0),"f");
for(i=0;1;e=(e==0)?1e-37:e*2){
r=f(e);
if(isinf(r))i=1;else if(!isnan(r)){
i?printf("%cINF\n",r>0?43:45):printf("%f\n",r);
break;
}
}
}
```
Run as:
```
./a.out "sin(x)/x" 0
./a.out "1/(x*x)" 0
./a.out "(x*x-x)/(x-1)" 1
./a.out "pow(2,x)" 3
```
Results:
```
1.000000
+INF
1.000000
8.000000
```
[Answer]
## Python ~~146~~ 185
Figured I'd post the obvious answer before anyone else does.
Note, reads two lines from `stdin` with `f(x)` on the first
and `a` on the second.
**Edit:** Made it actually work, as per `beary`'s comment
**Edit 2:** `i` is much smaller, so there are much fewer inputs that it should fail for.
```
from math import*
f,a,i=eval("lambda x:"+input()),eval(input()),2e-308
while 1:
try:
r=str(f(a+i)).upper()
if'NAN'!=r:break
except:
i*=-2
print('I'==r[0]and'+'+r or r)
```
] |
[Question]
[
**Problem**
There is a circular track containing fuel pits at irregular intervals. The total amount of fuel available from all the pits together is just sufficient to travel round the track and finish where you started. Given the the circuit perimeter, list of each fuel pit location and the amount of fuel they contain, find the optimal start point on the track such that you never run out of fuel and complete circuit.
**Sample Input**
```
(location, fuel)
(0/100, 6)
(2,16)
(18,1)
(30,45)
(84,5)
(92,27)
```
circuit length - 100, total fuel-100
[Answer]
**JavaScript 140 chars**
For the first solution, I assume that the fuel pits are provided in order order of location around the track and in the form:
```
var fuelPitInfo = [
{
location: 2,//The location from some point on the track
fuelDistance: 1//The distance you can travel with the fuel from this stop
},
..
]
```
Thus, a potential non code-golfed JavaScript function to calculate a working starting location is as follows ([test fiddle](http://jsfiddle.net/briguy37/kEFay/)):
```
function calculateStartingLocation(trackLength, fuelPitInfo) {
for(i=0;;i++){
var fuelPit = fuelPitInfo[i];
var remainingFuelDistance = fuelPit.fuelDistance;
for(j=i+1;;j++){
var nextFuelPit = fuelPitInfo[j = j % fuelPitInfo.length];
if (i == j) return fuelPitInfo[i].location;
remainingFuelDistance -= (nextFuelPit.location - fuelPit.location + trackLength) % trackLength;
if (remainingFuelDistance < 0) break;
remainingFuelDistance += nextFuelPit.fuelDistance;
fuelPit = nextFuelPit;
}
}
}
```
And the code-golfed function version (**140 chars**) is as follows (assuming `location` is replaced with `l` and `fuelDistance` is replaced with `d` in the provided `fuelPitInfo` object) ([test fiddle](http://jsfiddle.net/briguy37/syd9p/)):
```
function a(b,c){for(i=0;e=c[i],f=e.d;i++){for(j=i+1;g=c[j=j%c.length];){if(i==j++)return c[i].l;f-=(g.l-e.l+b)%b;if(f<0)break;f+=g.d,e=g;}}}
```
[Answer]
## Python, 183
```
import sys
f=[map(int,_.split()) for _ in open(sys.argv[1])]
l=len(f)
s=[]
for i in range(l):
\tu,d=zip(*(f[i:]+f[:i]))
\tif all(sum(u[:j])<sum(d[:j])for j in range(l+1)):s+=[i]
print s
```
This program takes input in the form of a file consisting of N lines, where N is the number of fuel depots. Each line contains integers A and B, where A is the amount of fuel at the depot, and B is the distance to the next fuel depot. Example:
```
7 5
6 7
4 3
```
Output is the string representation of a list containing the indices of the fuel depots that are valid starting points. In this case, it outputs:
```
[0, 2]
```
Meaning that starting at either fuel depot 0, or fuel depot 2 will allow the vehicle to make it all the way around the circle.
[Answer]
## D (98 chars)
the input is a int array with the amount of fuel with 0 if there is no fuel there
```
int f(int[] a){
for(int s,r=-1,i=0;;i++){
if(r+a.length==i)
return r;
if(--s<0){
r=i;s=0;
}
s+=a[i%$];
}
}
```
I start at index `0` with `0` fuel and whenever `s` falls below 0 I set that spot as my new start and reset `s` to `0`
if there is a solution you will find it in O(n) time or loop forever
[Answer]
# APL, 48 chars
```
{i/⍨{∧/0≤-\,m⊖⍨⍵-1}¨i←⍳↑⍴m←⍵[;2],⍪2-⍨/⍵[;1],100}
```
I'm not sure what the conditions are for this golf, but I wrote a straightforward O(n²) solution.
**Explanation**
This function accepts a matrix with the positions and amounts of fuel, with the condition that the length is 100 and that the first pit is at position 0:
```
p
0 6
2 16
18 1
30 45
84 5
92 27
```
The first operation is to take the first column, append 100 at the end, and take the differences of each pair of values, to get the distances between each pair of pits:
```
d←2-⍨/p[;1],100
d
2 16 12 54 8 8
```
Then it builds a new matrix with the amounts of fuel in the first column and the distances in the second:
```
m←p[;2],⍪d
m
6 2
16 16
1 12
45 54
5 8
27 8
```
Then it enumerates the naturals from 1 up to the number of rows (pits) and selects those which pass a given test:
```
i←⍳↑⍴m
({ . . . }¨i)/i
```
The test is to rotate the rows of the matrix by the index amount minus 1, so let's say if we want to start from the 3rd pit, it rotates 2 rows from the top to the bottom:
```
r←(3-1)⊖m
1 12
45 54
5 8
27 8
6 2
16 16
```
Then it flattens the elements of the matrix in row-major order and it scans their alternating sum. Scanning means to compute the alternating sum of just 1, 2, 3… up to all the elements of the vector:
```
a←-\,r
a
1 ¯11 34 ¯20 ¯15 ¯23 4 ¯4 2 0 16 0
```
We can see that by starting from the 3rd pit the tank is first filled up to 1, then drained down to -11, then filled up to 34, and so on. The next step is to ascertain whether all the numbers are ≥0, which in this case they are not:
```
∧/0≤a
0
```
If they did, the starting position would be included in the resulting set of good starting positions. And that's all.
---
As somebody mentioned, one could probably compute this alternating sum just once and use the minima as starting positions. I'll do it as a second version.
] |
[Question]
[
## Knapsack Problem
(Actually, this is a **subset of real [knapsack problem](http://en.wikipedia.org/wiki/Knapsack_problem)**.... - there's nothing to optimize!)
The knapsack problem is:
>
> Given positive integers , and an integer S, find non-negative integers  satisfies 
>
>
>
... or in (my bad) English...
>
> Suppose you have many stuffs which weights , find configurations of those stuffs which weights S.
>
>
>
## Problem
>
> Find **all** configurations of stuffs, which information is given by input.
>
>
>
## Input
You can make your own format, but you should enable users to input **the sum of stuffs(S)**, **weights of stuffs , and names of each stuffs**.
Stuffs' name may contain `[a-zA-Z0-9 _]` (alphanumeric + `_` + space).
You may assume that the input is correct,  are positive, and S is non-negative.
For example, consider this pseudo-real world situation, where a man orders appetizers worth exactly $15.05:

A possible input is:
```
1505
215 Mixed fruit
275 French fries
335 Side salad
355 Hot wings
420 Mozzarella sticks
580 Sampler plate
```
## Output
Print all possible configurations (no same configurations, one configuration per one line, each line contains pairs of amount of a stuff and name of the stuff).
Stuff with zero amount can be omitted.
If there's no configuration possible, simply print `X`.
## Example
Input and output format (and order) can be vary.
This is JS code I made roughly:
```
var s=prompt(),a=s.split('/'),b=[],c,i=1,t=a[0];while(i<a.length){c=a[i].split(/^([^ ]*) /);c.shift();b.push(c);i++;}
var d=[],l=b.length,p=0,_=0;for(i=0;i<l;i++)d[i]=0;
function as(x,y){for(var i=0,s=0;i<x.length;i++)s+=x[i][0]*y[i];return s}
function cs(x,y){for(var i=0,s='';i<x.length;i++)s+=y[i]+' '+x[i][1]+', ';return s}
while(p>=0){
p=0;
while((q=as(b,d))>=t){
if(q==t){console.log(cs(b,d));_=1}
d[p]=0;p++;if(p>=l){p=-1;break;}
d[p]++;
}
if(p==0) d[0]++;
}
if(!_) console.log('X');
```
---
Input
`1505/215 Mixed fruit/275 French fries/335 Side salad/355 Hot wings/420 Mozzarella sticks/580 Sampler plate`
Output
```
7 Mixed fruit, 0 French fries, 0 Side salad, 0 Hot wings, 0 Mozzarella sticks, 0 Sampler plate,
1 Mixed fruit, 0 French fries, 0 Side salad, 2 Hot wings, 0 Mozzarella sticks, 1 Sampler plate,
```
---
Input
`5/1 A/1 B/1 C`
Output
```
5 A, 0 B, 0 C,
4 A, 1 B, 0 C,
3 A, 2 B, 0 C,
2 A, 3 B, 0 C,
1 A, 4 B, 0 C,
0 A, 5 B, 0 C,
4 A, 0 B, 1 C,
3 A, 1 B, 1 C,
2 A, 2 B, 1 C,
1 A, 3 B, 1 C,
0 A, 4 B, 1 C,
3 A, 0 B, 2 C,
2 A, 1 B, 2 C,
1 A, 2 B, 2 C,
0 A, 3 B, 2 C,
2 A, 0 B, 3 C,
1 A, 1 B, 3 C,
0 A, 2 B, 3 C,
1 A, 0 B, 4 C,
0 A, 1 B, 4 C,
0 A, 0 B, 5 C,
```
---
Input
`10/20 A/11 B`
Output
`X`
---
Input
`250/35 Portal 2/21 Minecraft/12 Braid`
Output
```
5 Portal 2, 3 Minecraft, 1 Braid,
2 Portal 2, 8 Minecraft, 1 Braid,
2 Portal 2, 4 Minecraft, 8 Braid,
2 Portal 2, 0 Minecraft, 15 Braid,
```
Input
`250/33 Portal 2/21 Minecraft/12 Braid`
Output
`X`
---
## Winner
Since this is the code golf game, person with shortest code win.
If two codes have same length, then a code with highest votes win.
[Answer]
# Mathematica, 59 chars
```
Tally/@IntegerPartitions[#1,All,#2/._[x_,_]->x]/.#2/.{}->X&
```
Invoke with
```
%[1505, {215 -> "MF", 275 -> "FF", 335 -> "SS", 355 -> "HW", 420 -> "MS", 580 -> "SP"}]
```
[Answer]
## Python, 185 chars
```
S,C,N=input()
R=range(len(C))
F=lambda i,w:sum([[x+[j]for x in F(j,w-C[j])]for j in R[i:]],[])if w>0 else[[]][w<0:]
for L in F(0,S):print[(L.count(i),N[i])for i in R];S=0
if S:print'X'
```
run it with input like this:
```
echo "[1505,[215,275,335,355,420,580],['MF','FF','SS','HW','MS','SP']]" | ./knapsack.py
```
which encodes S, a list of costs, and a list of item names corresponding to those costs.
It outputs list of item counts and item names:
```
[(7, 'MF'), (0, 'FF'), (0, 'SS'), (0, 'HW'), (0, 'MS'), (0, 'SP')]
[(1, 'MF'), (0, 'FF'), (0, 'SS'), (2, 'HW'), (0, 'MS'), (1, 'SP')]
```
[Answer]
### Ruby, 136 characters
```
a,*b=*$<
c=->s,u,e{f,*r=e;f ?(0..s/h=f.to_i).map{|n|c[s-n*h,u+[n.to_s+f[/ .*/]],r]}:s>0?[]:u*?,}
r=c[a.to_i,[],b].flatten
puts r[0]?r:?X
```
Input must be given on STDIN, one line for the total amount and then one line per item (weight, followed by space, followed by name).
Example input:
```
250
35 Portal 2
21 Minecraft
12 Braid
```
Output:
```
2 Portal 2,0 Minecraft,15 Braid
2 Portal 2,4 Minecraft,8 Braid
2 Portal 2,8 Minecraft,1 Braid
5 Portal 2,3 Minecraft,1 Braid
```
[Answer]
### Python, 356 characters
I took a slight hit for reading from the command line:
```
from sys import argv
x=int(argv[1])
t=argv[3::2]
c=argv[2::2]
n=len(t)
s=[0]*n
d=1
g=1
while d:
i=0
s[i]+=1
while int(c[i])*s[i]>x:
s[i]=0
if i+1>=n:
d=0
else:
i+=1
s[i]+=1
if d and sum(map(lambda y:int(c[y])*s[y],range(n)))==x:
g=0
print zip(t, s)
if g:print"X"
```
Example input:
```
python stuff.py 1505 215 'Mixed fruit' 275 'French fries' 335 'Side salad' 355 'Hot wings' 420 'Mozzarella sticks' 580 'Sampler plate'
```
Output:
```
[('Mixed fruit', 7), ('French fries', 0), ('Side salad', 0), ('Hot wings', 0), ('Mozzarella sticks', 0), ('Sampler plate', 0)]
[('Mixed fruit', 1), ('French fries', 0), ('Side salad', 0), ('Hot wings', 2), ('Mozzarella sticks', 0), ('Sampler plate', 1)]
```
[Answer]
# JavaScript (V8), 225 bytes
```
(t,k,l,a=d=0)=>[...Array(t+1)].flatMap((_,j)=>[...Array(k[L="length"]**j)].map((_,i)=>eval("r=[];while(j-r[L])r.push(i%k[L]),i=i/k[L]|0;r")).filter(p=>(a=m=d=0,p.map(i=>(a+=k[i],d|=i<m,m=i)),a==t&&!d)).map(p=>p.map(i=>l[i])))
```
I had a bunch of really neat ideas for how to golf this but they ended up not working.
] |
[Question]
[
**This is an [ai-player](/questions/tagged/ai-player "show questions tagged 'ai-player'") challenge.** Your goal is to reach the number 2011 as quickly as possible, or to get as close to it as you can.
**Rules:**
* A "hole" consists of a rectangular grid of digits (0-9).
* Your total starts at 0.
* You may start at any digit on the grid. This is your first "stroke."
* For each subsequent stroke, you may move to any immediately adjacent digit (up, left, down, right). However, you may not move to a digit that you have used before.
* With each stroke, you will use your current total and the digit at your current position as operands (the total is always the first operand), and apply one of the four basic arithmetic operations (+ - \* /). The result will become your new total.
* If your total becomes 2011, your score for the course is the number of strokes.
* If you have no more valid moves, your score is your current number of strokes + your total's distance from 2011.
* You may also choose at any time to stop, and your score will be your current number of strokes + your total's distance from 2011.
**Input:**
* You will read in a file containing data for each "hole." Alternatively, you may accept the input through stdin or an equivalent.
* Each hole will consist of H rows of W digits, for a grid of size WxH. H and W may vary per hole.
* The holes will be separated by a single blank line.
* In the spirit of golf, the competition will consist of 18 holes, but your program should be able to handle any number of them.
**Output:**
* For each hole, your program should output the position of the starting digit. The position should be given as `(row, col)` where the top-left is `(0, 0)`.
* For each stroke, your program should output the chosen operation, the current digit, and the resulting total.
* At the end of each hole, whether you reach 2011 or not, your program should output your number of strokes and your score for the hole (usually the same as the number of strokes).
* For testing purposes, you may also find it helpful to output your path on each board indicating which digits were used. However, you will not be required to provide this output for the competition.
**Notes:**
* For any given hole, your program should always start at the same position and choose the same route (i.e., no random choices). The starting position does not need to be the same for every hole.
* The total is not limited to the integers. That is, if you divide 4023 by 2, your total would become 2011.5, and you would still be .5 away from the goal.
* Your program should run in a "reasonable" amount of time.
* For purposes of verifiability, your program should be runnable on an online interpreter such as ideone.com.
* The winner is the program that has the lowest overall score for the entire course. If there is a tie, the tying programs will play a new course, hole-for-hole, with the lowest scorers advancing until there is only one winner. If there is still a tie after the tiebreaker course, the program submitted first will win.
**Deadline:**
* The current deadline for this competition is September 10, 2011. This deadline may be extended, depending on interest.
**Sample input:**
```
14932875921047
60438969014654
56398659108239
90862084187569
94876198569386
14897356029523
```
**Sample output:**
```
Start: (3, 7)
+4=4
*9=36
*9=324
*6=1944
+9=1953
+8=1961
+8=1969
+9=1978
+6=1984
+8=1992
+8=2000
+8=2008
+4=2012
-1=2011
Strokes: 14
Score: 14
14932875921047
6043....014654
563..65.108239
90..208.187569
94.76198569386
...97356029523
```
**Sample output (compact):**
```
Start: (3, 7)
+4=4 *9=36 *9=324 *6=1944 +9=1953 +8=1961 +8=1969 +9=1978 +6=1984 +8=1992 +8=2000 +8=2008 +4=2012 -1=2011
Strokes: 14 Score: 14
```
**Sample input:**
```
0346092836
1986249812
3568086343
5509828197
4612486355
3025745681
7685047124
2098745313
```
**Sample output:**
```
Start: (4, 7)
+3=3
*6=18
*5=90
+7=97
*5=485
*4=1940
+7=1947
+8=1955
+9=1964
+8=1972
+6=1978
+7=1985
+3=1988
+4=1992
+5=1997
+5=2002
+5=2007
+3=2010
+1=2011
Strokes: 19
Score: 19
0346092836
.986249812
..68086343
..09828197
.61248..55
.02574.681
...504.124
20.....313
```
**Sample input:**
```
9876
5432
1098
7654
3210
```
**Sample output:**
```
Start: (2, 2)
+9=9
*8=72
*4=288
*5=1440
+6=1446
+7=1453
+3=1456
+2=1458
+1=1459
Strokes: 9
Score: 561
9876
5432
10..
....
....
```
**Sample input:**
```
39857205
74493859
02175092
54239112
39209358
34568905
```
**Sample output:**
```
Start: (0, 0)
+3=3
*7=21
*4=84
*4=336
-1=335
*2=670
/3=(670/3)
*9=2010
+1=2011
.9857205
...93859
02.75092
54....12
39209358
34568905
```
## Results
Unfortunately, there were only two contestants, but I'll post the results.
```
#1 - Howard (1881)
#2 - Gareth (5442)
```
The first half of the course consisted of roughly "normal" holes, generated mostly randomly. The second half was more challenging, as the holes contained more "sand traps" (sections deliberately filled with low numbers, especially 0s).
```
**Howard**
01) 5 - 5
02) 5 - 5
03) 6 - 6
04) 6 - 7
05) 6 - 7
06) 6 - 6
07) 5 - 5
08) 5 - 5
09) 6 - 6
10) 9 - 10
11) 5 - 8
12) 8 - 8
13) 6 - 7
14) 8 - 9
15) 7 - 12
16) 20 - 1665
17) 29 - 66
18) 30 - 44
Front 9) 52
Back 9) 1829
Full 18) 1881
**Gareth**
01) 9 - 10
02) 33 - 173
03) 8 - 8
04) 11 - 16
05) 7 - 84
06) 17 - 17
07) 9 - 10
08) 8 - 8
09) 15 - 15
10) 16 - 16
11) 12 - 32
12) 18 - 164
13) 34 - 335
14) 10 - 10
15) 26 - 447
16) 78 - 78
17) 1 - 2010
18) 1 - 2009
Front 9) 341
Back 9) 5101
Full 18) 5442
```
The course used can be found on [pastebin](http://pastebin.com/dtWy0ybj).
@Howard: I ran your program with the lower number of paths due to limits on ideone. If your full version gives significantly different results, let me know the scores and the relative running time of the program.
[Answer]
### Java - The Why-Not-Try-It-The-Easy-Way-Approach
Here is my first submission for this problem. I don't know if it qualifies for ai-player because it is more "artifical clumsiness". Maybe I can do better but I think it is hard to beat it on most grids.
The program just takes paths and operations calculated by a *very complicated and clever algorithm* (no, it's not random ;-) It will give you the same result every time) and compares all of them to find the best one.
Input must be given on STDIN. You can see the examples running [here](http://ideone.com/87nxH) (note: number of paths reduced).
The output for above holes is
```
Start: (4, 0)
+9=9
*4=36
*8=288
*7=2016
-6=2010
Strokes: 5
Score: 6
Start: (3, 3)
+9=9
*8=72
*4=288
*7=2016
-5=2011
Strokes: 5
Score: 5
Start: (0, 2)
+7=7
*8=56
*4=224
-0=224
*9=2016
-5=2011
Strokes: 6
Score: 6
Start: (2, 3)
+7=7
*9=63
*4=252
*8=2016
-5=2011
Strokes: 5
Score: 5
```
The program itself is given below (it makes use of lots of static declarations - don't try this at home).
```
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Random;
public class Main {
// DEBUG=true displays progress
private static final boolean DEBUG = false;
// Number of paths to try
private static final int PATHS = 10000000;
// Saves the number grid
static int[][] grid;
// start position
static int startx;
static int starty;
// used digits and operations
static int[] ns = new int[1024];
static int[] ops = new int[1024];
// current best score and output for this score
static double bestScore;
static String best;
// a random number generator
static Random random;
public static void main(String[] args) throws IOException {
BufferedReader cons = new BufferedReader(new InputStreamReader(System.in));
String[] conLines = new String[1024];
int numLines = 0;
while (true) {
String line = cons.readLine();
if (line == null || line.isEmpty()) {
// already some lines found
if (numLines > 0) {
// prepare grid and run algorithm
prepareGrid(conLines, numLines);
findBest();
System.out.println(best);
}
numLines = 0;
} else {
conLines[numLines++] = line;
}
if (line == null)
break;
}
}
private static void findBest() {
random = new Random(1);
bestScore = 9999e99;
for (int k = 0; k < PATHS; k++) {
int sx = startx = random.nextInt(grid.length);
int sy = starty = random.nextInt(grid[0].length);
doStep(0, 1, 0, sx, sy);
}
}
private static void doStep(int num, int den, int steps, int sx, int sy) {
// consume the digit at the current position
ns[steps] = grid[sx][sy];
grid[sx][sy] = -1;
// choose random operation and apply to total=num/den
ops[steps] = num == 0 || ns[steps] == 0 ? random.nextInt(2) : random.nextInt(4);
if (ops[steps] == 0) {
num -= den * ns[steps];
} else if (ops[steps] == 1) {
num += den * ns[steps];
} else if (ops[steps] == 2) {
den *= ns[steps];
int g = gcd(num, den);
if (g > 1) {
num /= g;
den /= g;
}
} else if (ops[steps] == 3) {
num *= ns[steps];
int g = gcd(num, den);
if (g > 1) {
num /= g;
den /= g;
}
}
// calculate score for path up to now and save it if best
double score = steps + 1 + Math.abs(2011 - num / (double) den);
if (score < bestScore) {
bestScore = score;
best = String.format("Start: (%d, %d)\n", starty, startx);
int nn = 0;
int dn = 1;
for (int k = 0; k <= steps; k++) {
if (ops[k] == 0) {
nn -= dn * ns[k];
} else if (ops[k] == 1) {
nn += dn * ns[k];
} else if (ops[k] == 2) {
dn *= ns[k];
int g = gcd(nn, dn);
if (g > 1) {
nn /= g;
dn /= g;
}
} else if (ops[k] == 3) {
nn *= ns[k];
int g = gcd(nn, dn);
if (g > 1) {
nn /= g;
dn /= g;
}
}
best += String.format(dn == 1 ? "%c%d=%d\n" : "%c%d=%d/%d\n", "-+/*".charAt(ops[k]), ns[k], nn, dn);
}
best += String.format("Strokes: %d\n", steps + 1);
best += dn == 1 ? String.format("Score: %d\n", (int) (score + 0.05)) : String.format("Score: %f\n", score);
if (DEBUG) {
System.out.println(best);
printGrid(grid);
System.out.println();
}
}
if (steps + 2 < bestScore) {
// choose any direction and go on
int dir = random.nextInt(4);
int nx = sx;
int ny = sy;
int b = 0;
while (b < 4) {
if (dir == 0 && sx > 0 && grid[sx - 1][sy] >= 0) {
nx = sx - 1;
break;
} else if (dir == 1 && sx < grid.length - 1 && grid[sx + 1][sy] >= 0) {
nx = sx + 1;
break;
} else if (dir == 2 && sy > 0 && grid[sx][sy - 1] >= 0) {
ny = sy - 1;
break;
} else if (dir == 3 && sy < grid[0].length - 1 && grid[sx][sy + 1] >= 0) {
ny = sy + 1;
break;
}
b++;
dir++;
}
// if further step possible
if (b < 4) {
doStep(num, den, steps + 1, nx, ny);
}
}
// put back the digit
grid[sx][sy] = ns[steps];
}
// helper function calculating gcd
private static int gcd(int a, int b) {
while (b != 0) {
int t = b;
b = a % b;
a = t;
}
return a;
}
// helper function reading the grid from an array of strings
private static void prepareGrid(String[] data, int numLines) {
grid = new int[data[0].length()][numLines];
for (int y = 0; y < numLines; y++) {
for (int x = 0; x < data[y].length(); x++) {
grid[x][y] = (int) (data[y].charAt(x) - '0');
}
}
}
// helper function printing the grid
private static void printGrid(int[][] grid) {
for (int y = 0; y < grid[0].length; y++) {
for (int x = 0; x < grid.length; x++) {
System.out.print(grid[x][y] < 0 ? '.' : (char) ('0' + grid[x][y]));
}
System.out.println();
}
}
}
```
*Edit:* Just did a small performance optimization. We don't need to follow a path anymore if it's length already exceeds the best score found so far.
[Answer]
## Scala
```
object Main
{
def main(args:Array[String])
{
var input=io.Source.stdin.getLines.toArray
while(!input.isEmpty)
{
var hole=input.takeWhile(_!="").map(_.map(x=>Integer.parseInt(x.toString)).toArray).toArray
input=input.dropWhile(_!="")
if(!input.isEmpty)
input=input.tail
var (height,width)=(hole.size,hole.head.size)
var bestscore=10000000
var bestrunoutput=""
var currentval=0
var output=""
var exit=false
var c:Array[Array[Int]]=Array(Array(0))
var(steps,xnow,ynow)=(0,0,0)
def getNeighbours(x:Int,y:Int,c:Array[Array[Int]]):Array[(Int,Int,Int)]=
(for(a<- -1 to 1;b<- -1 to 1;if(Math.abs(a)!=Math.abs(b) && x+b>=0 && x+b<width && y+a>=0 && y+a<height)) yield (c(y+a)(x+b),x+b,y+a)).toArray.sortBy(_._1).reverse
for(y<-0 until height;x<-0 until width)
{
c=hole.map(_.clone)
exit=false
steps=0
xnow=x
ynow=y
currentval=c(ynow)(xnow)
output="Start: ("+y+","+x+")\n+"+currentval+"="+currentval+"\n"
while(!exit)
{
var neighbours=getNeighbours(xnow,ynow,c)
while(neighbours.size>0 && (neighbours.head._1*currentval>2011 || neighbours.head._1<2))
neighbours=neighbours.drop(1)
if(neighbours.size==0)
{
neighbours=getNeighbours(xnow,ynow,c)
while(neighbours.size>0 && (neighbours.head._1+currentval>2011 || neighbours.head._1==0))
neighbours=neighbours.drop(1)
if(neighbours.size==0)
{
exit=true
}
else
{
currentval+=neighbours.head._1
c(ynow)(xnow)=0
output+="+"+neighbours.head._1+"="+currentval+"\n"
}
}
else
{
currentval*=neighbours.head._1
c(ynow)(xnow)=0
output+="*"+neighbours.head._1+"="+currentval+"\n"
}
if(!exit)
{
xnow=neighbours.head._2
ynow=neighbours.head._3
}
steps+=1
}
output+="Strokes: "+steps+"\nScore: "+(steps+2011-currentval)+"\n"
if(steps+2011-currentval<bestscore)
{
bestscore=steps+2011-currentval
bestrunoutput=output
}
}
println(bestrunoutput)
}
println
}
}
```
I've tidied it up a little, fixed the bug that let the same number be used more than once for addition, and I've met the requirement (which I didn't spot before) to take multiple holes as input.
The algorithm is fairly simple:
```
For every possible start point:
Find the highest value neighbour and try multiplying it
If it's too high
Try the next highest neighbour
If there are no more neighbours
Find the highest value neighbour and try adding it
If it's too high
Try the next highest neighbour
If there are no more neighbours
End this attempt and calculate the score
Print out the attempt with the best score
```
Running in ideone.com:
**Input**
```
14932875921047
60438969014654
56398659108239
90862084187569
94876198569386
14897356029523
0346092836
1986249812
3568086343
5509828197
4612486355
3025745681
7685047124
2098745313
9876
5432
1098
7654
3210
39857205
74493859
02175092
54239112
39209358
34568905
```
**Output**
```
Start: (0,3)
+3=3
*9=27
*4=108
*3=324
*6=1944
+5=1949
+9=1958
+9=1967
+4=1971
+8=1979
+8=1987
+9=1996
+7=2003
+6=2009
+2=2011
Strokes: 15
Score: 15
Start: (6,6)
+7=7
*5=35
*4=140
*7=980
+8=988
+9=997
+8=1005
*2=2010
+1=2011
Strokes: 9
Score: 9
Start: (4,0)
+3=3
*7=21
*6=126
*5=630
+9=639
*3=1917
+7=1924
+8=1932
+9=1941
+5=1946
+4=1950
Strokes: 11
Score: 72
Start: (4,5)
+3=3
*9=27
*8=216
*9=1944
+9=1953
+5=1958
+7=1965
+9=1974
+5=1979
+8=1987
+9=1996
+4=2000
+7=2007
+3=2010
Strokes: 14
Score: 15
```
Looks like mine'll have to be content being weekend golf player compared to Howard's Tiger Woods. :-)
] |
[Question]
[
Write a program that does one step of the computation of factorial, then, generate (quine) a new program, and performs the rest of the process in the new program
The seed and spawned programs will have a variable n for the factorial to be computed and m for the accumulator.
I don't care if you use scripted or compiled language.
You can use the cheat of "reading the source file".
You MUST create a new file and run the new file to qualify: no self-modifying code or using code loaded in memory, but spawning with `data:` url in JS is allowed.
Here is an example in Java: <https://gist.github.com/968033>
Shortest code wins.
[Answer]
# Perl, 95
```
$m=1;$n=12||die$m;@ARGV=$0;$_=<>;$m*=$n--;s/\|/;\$m=$m;\$n=$n|/;open _,">$0";print _;exec$^X,$0
```
The program really has to be on a single line, and overwrites itself at each iteration.
[Answer]
# Python (189)
It's not very short but it does take its argument on the command line.
```
n,m=0,1
from sys import*
a,f=argv,file
_,n=a[0],len(a)>1and n<1and int(a[1])or n
if n>1:x=f(_).readlines();x[0]='n,m=%s\n'%`n-1,m*n`;f(_,'w').write(''.join(x));exec f(_).read()
else:print m
```
[Answer]
# Javascript (163)
```
g=document.location;if(s=g.search.split(",")[1]){
n=s.split(":");i=n[1];n=n[0];i*=--n;
n==1?alert(i):g.search="?a=,"+n+":"+i}
else{n=prompt();g.search="?a=,"+n+":"+n}
```
This uses the querystring to pass values and refreshes the page.
] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win.
Closed 3 years ago.
[Improve this question](/posts/964/edit)
Say that you have this folder structure on your coumputer:
```
/a
```
And you want to have these folders:
```
/a/b
/a/c
/b/b
```
You would need to create four directories, using mkdir for example:
```
mkdir /a/b
mkdir /a/c
mkdir /b
mkdir /b/b
```
Write a program that, given existing and required directory structures, will output the directories that need to be created.
## Input
First line has two numbers: n, number of existing directories, and m, number of required directories
Next n lines has the list of existing directories
Next m lines has the list of required directories
Example:
```
1 3
/a
/a/b
/a/c
/b/b
```
## Output
Directories you need to create
Example:
```
/a/b
/a/c
/b
/b/b
```
[Answer]
# Bash, ~~175~~ ~~169~~ ~~168~~ ~~135~~ ~~130~~ 128
Here's one of my worthwhile solutions from SO, then:
**WARNING:** Be sure to run in an empty directory, as this will wipe out its contents first thing per test.
```
read t
for((;x++<t;));do
rm -r *
read n m
for((i=n+m;i--;));do
read d
mkdir -p .$d
done
echo Case \#$x: $[`find|wc -l`-n-1]
done
```
[Answer]
# Python
In Python, you would just use `os.makedirs()`. See the docs at the bottom of this post
```
import sys
num_existing, num_required = map(int, next(sys.stdin).split())
sep = "/"
directory = {}
for i,path in enumerate(s.rstrip("\n") for s in sys.stdin):
d = directory
base = ""
for p in path.split(sep)[1:]:
base += sep+p
if p not in d:
if i >= num_existing:
print base
d[p]={}
d = d[p]
```
Python docs for `os.makedirs()`
```
>>> import os
>>> help(os.makedirs)
Help on function makedirs in module os:
makedirs(name, mode=511)
makedirs(path [, mode=0777])
Super-mkdir; create a leaf directory and all intermediate ones.
Works like mkdir, except that any intermediate path segment (not
just the rightmost) will be created if it does not exist. This is
recursive.
```
] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win.
Closed 10 years ago.
[Improve this question](/posts/105/edit)
You and your brother have inherited a rectanglar block of land. This block of land's corners are read in from stdio as `TLX,TLY,TRX,TRY,BLX,BLY,BRX,BRY` (all decimal numbers without units, T=Top, L=Left, B=Bottom, R=Right)
Unfortunately the city has seen fit to appropriate a small rectanglar section from inside your you newly aquired land. This appropriated land can be at any angle and in any position on your land. Its corners are read in from stdio as `TLX,TLY,TRX,TRY,BLX,BLY,BRX,BRY` (all decimal numbers without units).
You need to split this land evenly with your brother by building a fence. The fencing contractors can only build a single straight line fence. You need to supply them with the start and end co-ordinates which sit along the parameter of your property. These are written to stdio as `SX,SY,EX,EY` (all decimal numbers without units, S=Start, E=End)
The city has graciously agreed to allowed you to freely build the fence across their bit of appropriated property.
**Provide a solution which can accept the 2 rectangle co-ordinates and return a correct solution which divides the property area equally for you and your brother.**
visualized samples of potential input (white = your land, grey = city land):


*{I'll insert the credit here after people have answered}*
[Answer]
**C**
```
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
enum mode
{
CORD_MODE_CONST = 1,
CORD_MODE_SLOPE = 2,
};
typedef struct point {
float x;
float y;
} CORD;
typedef struct l {
int mode;
float m;
float b;
}LINE;
typedef struct r {
CORD topL;
CORD botL;
CORD topR;
CORD botR;
CORD midRight;
CORD midBot;
CORD midLeft;
CORD midTop;
CORD center;
LINE vertLine;
LINE horLine;
} RECTANGLE;
void findBorderIntersection(RECTANGLE * pR, LINE * p);
int isPointContained(RECTANGLE * pR, CORD * pC1);
float dotProduct(float y1, float y2, float x1, float x2);
void findCenterOfRetangle(RECTANGLE * pR);
void findIntersection(LINE * pL1, LINE * pL2, CORD *pInt);
void findMidPointOfLine(CORD * pC1, CORD * pC2, CORD * pMid);
void getLine(CORD * pC1, CORD * pC2, LINE * pLine );
void dumpCord(char * pS, CORD * pC)
{
printf(" %s y:%f x:%f\n",pS,pC->y,pC->x);
}
int main()
{
RECTANGLE yourLand;
RECTANGLE cityLand;
LINE lineThroughCenter;
memset(&yourLand,0x0, sizeof(RECTANGLE));
memset(&cityLand,0x0, sizeof(RECTANGLE));
scanf("%f%f%f%f%f%f%f%f",&(yourLand.topL.x),
&(yourLand.topL.y),
&(yourLand.topR.x),
&(yourLand.topR.y),
&(yourLand.botL.x),
&(yourLand.botL.y),
&(yourLand.botR.x),
&(yourLand.botR.y));
scanf("%f%f%f%f%f%f%f%f",&(cityLand.topL.x),
&(cityLand.topL.y),
&(cityLand.topR.x),
&(cityLand.topR.y),
&(cityLand.botL.x),
&(cityLand.botL.y),
&(cityLand.botR.x),
&(cityLand.botR.y));
/* Find center of your land */
findCenterOfRetangle(&yourLand);
/* Find center of city land */
findCenterOfRetangle(&cityLand);
/* Handle the case where the centers are right on top of each other */
if((yourLand.center.x == cityLand.center.x) &&
(yourLand.center.y == cityLand.center.y))
{
/* Find the line through center and the top border */
getLine(&(yourLand.midTop),&(cityLand.center),&lineThroughCenter);
}
else
{
/* Find the line through center of both lands */
getLine(&(yourLand.center),&(cityLand.center),&lineThroughCenter);
}
/* Find the border cords */
findBorderIntersection(&(yourLand),&lineThroughCenter);
return 0;
}
void findBorderIntersection(RECTANGLE * pR, LINE * p)
{
LINE line;
CORD c1;
CORD c2;
int bTop = 0;
getLine(&(pR->topL), &(pR->topR),&line);
/* Figure out if the the line goes through the top/bottom or right/left */
if( p->m != line.m)
{
findIntersection(p,&line, &c1);
bTop = isPointContained(pR,&c1);
}
if(bTop)
{
getLine(&(pR->botL), &(pR->botR),&line);
findIntersection(p,&line, &c2);
}
else
{
getLine(&(pR->topL), &(pR->botL),&line);
findIntersection(p,&line, &c1);
getLine(&(pR->topR), &(pR->botR),&line);
findIntersection(p,&line, &c2);
}
dumpCord("Border Cord1:",&c1);
dumpCord("Border Cord2:",&c2);
}
int isPointContained(RECTANGLE * pR, CORD * pC1)
{
float pointProduct1;
float vectorProduct1;
float pointProduct2;
float vectorProduct2;
vectorProduct1 = dotProduct((pR->topL.y - pR->botL.y),
(pR->topL.y - pR->botL.y),
(pR->topL.x - pR->botL.x),
(pR->topL.x - pR->botL.x));
pointProduct1 = dotProduct((pC1->y - pR->botL.y),
(pR->topL.y - pR->botL.y),
(pC1->x - pR->botL.x),
(pR->topL.x - pR->botL.x));
vectorProduct2 = dotProduct((pR->botR.y - pR->botL.y),
(pR->botR.y - pR->botL.y),
(pR->botR.x - pR->botL.x),
(pR->botR.x - pR->botL.x));
pointProduct2 = dotProduct((pC1->y - pR->botL.y),
(pR->botR.y - pR->botL.y),
(pC1->x - pR->botL.x),
(pR->botR.x - pR->botL.x));
if( (pointProduct1 <= vectorProduct1) &&
(pointProduct1 >= 0) &&
(pointProduct2 <= vectorProduct2) &&
(pointProduct2 >= 0))
{
return 1;
}
return 0;
}
float dotProduct(float y1, float y2, float x1, float x2)
{
return y1*y2 + x1*x2;
}
void findCenterOfRetangle(RECTANGLE * pR)
{
/* Find the mid point of the left side */
findMidPointOfLine(&(pR->topL), &(pR->botL), &(pR->midLeft));
/* Find the mid point of the right side */
findMidPointOfLine(&(pR->topR), &(pR->botR), &(pR->midRight));
/* Get the line */
getLine(&(pR->midLeft), &(pR->midRight), &(pR->horLine));
/* Find the mid point of the top side */
findMidPointOfLine(&(pR->topL), &(pR->topR), &(pR->midTop));
/* Find the mid point of the bottom side */
findMidPointOfLine(&(pR->botL), &(pR->botR), &(pR->midBot));
/* Get the line */
getLine(&(pR->midTop), &(pR->midBot), &(pR->vertLine));
/* Find the center of the first rectangle */
findIntersection(&(pR->horLine), &(pR->vertLine),&(pR->center));
}
void findIntersection(LINE * pL1, LINE * pL2, CORD *pInt)
{
if(pL1->mode == CORD_MODE_CONST)
{
pInt->x = pL1->m;
pInt->y = ((pL2->m * pInt->x) + pL2->b);
}
else if(pL2->mode == CORD_MODE_CONST)
{
pInt->x = pL2->m;
pInt->y = ((pL1->m * pInt->x) + pL1->b);
}
else
{
pInt->x = (pL2->b - pL1->b) / (pL1->m - pL2->m);
pInt->y = ((pL2->m * pInt->x) + pL2->b);
}
}
void findMidPointOfLine(CORD * pC1, CORD * pC2, CORD * pMid)
{
pMid->y = (pC1->y + pC2->y) / 2;
pMid->x = (pC2->x + pC1->x) / 2;
}
void getLine(CORD * pC1, CORD * pC2, LINE * pLine )
{
/* Find slope */
if((pC1->x - pC2->x) == 0)
{
pLine->mode = CORD_MODE_CONST;
pLine->m = pC1->x;
pLine->b = 0;
}
else
{
pLine->mode = CORD_MODE_SLOPE;
pLine->m = ((pC1->y - pC2->y) / (pC1->x - pC2->x));
/* Find y inter. */
pLine->b = pC1->y - (pLine->m * pC1->x);
}
}
```
[Answer]
Assuming the land you inherit is square to the grid, this should do the job in **Java**.
```
import java.io.*;
class Land {
public static void main(String[] args) {
BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
double[] corners = new double[16];
for(int i = 0; i < 16; i++) {
try {
corners[i] = Double.parseDouble(r.readLine());
} catch (Exception e) {
System.err.println("Error in input! Please try again.");
i--;
}
}
// Find mid point of own land
double lx = (corners[0] + corners[6])/2;
double ly = (corners[1] + corners[7])/2;
System.out.println("Mid point of your land: "+ lx + ", " + ly);
// Find mid point of city land
double cx = (corners[8] + corners[14])/2;
double cy = (corners[9] + corners[15])/2;
System.out.println("Mid point of city land: "+ cx + ", " + cy);
double sx, sy;
// Check for div by 0
if(cx-lx == 0) {
sx = lx;
sy = corners[1];
} else {
// Find gradient
double m = (cy-ly)/(cx-lx);
System.out.println("Gradient: " + m);
// Find constant
double c = ly - (m * lx);
System.out.println("Constant: " + c);
if((m*corners[0] + c) >= corners[1]) {
sy = m*corners[0] + c;
sx = corners[0];
} else {
// use where line crosses x axis
sy = corners[1];
sx = (sy - c) / m;
}
}
// Apply the offsets to the lower corner
double ex = corners[6] - (sx - corners[0]);
double ey = corners[7] - (sy - corners[1]);
System.out.println("Fence start: "+ sx + ", " + sy);
System.out.println("Fence end : "+ ex + ", " + ey);
}
}
```
Edit: just to clarify this also assumes a grid where top left is 0,0.
[Answer]
## Python 2.7
My thinking is:
* Line should pass through the centre of the brothers' land to split the 'additive area' equally.
* Line should pass through the centre of the city's land to split the 'subtractive area' equally.
* Line will pass through 'opposite edges' of the brothers' land.
* Whether this is on the left-right edges or top-bottom edges depends on in which 'diagonal quadrant' of the land the centre of the city's portion lies.
So:
* find centres
* find diagonal quadrant
* find intersection points with edges
Code (Dense, huh? Only that pesky 'else' shorter than 70 chars! Not on purpose!):
```
cent = lambda p0,p1: {'x':(p0['x']+p1['x'])/2,'y':(p0['y']+p1['y'])/2}
dx = lambda p0,p1: p1['x']-p0['x']; dy = lambda p0,p1: p1['y']-p0['y']
dxdy=lambda p0,p1: 0 if (p0['x']==p1['x'] or p0['y']==p1['y']) else dx(p0,p1)/dy(p0,p1)
dydx=lambda p0,p1: 0 if (p0['x']==p1['x'] or p0['y']==p1['y']) else dy(p0,p1)/dx(p0,p1)
y_at_x = lambda p,lp0,lp1: lp0['y'] + (p['x']-lp0['x']) * dy(lp0,lp1)/dx(lp0,lp1)
print "input brothers' land TLX,TLY,TRX,TRY,BLX,BLY,BRX,BRY:"; land=input()
print 'input city land TLX,TLY,TRX,TRY,BLX,BLY,BRX,BRY:'; city=input()
land_cent = cent({'x':land[0],'y':land[1]},{'x':land[6],'y':land[07]})
city_cent = cent({'x':city[0],'y':city[1]},{'x':city[6],'y':city[7]})
in_half_tr = y_at_x(city_cent,{'x':land[0],'y':land[1]},{'x':land[6],'y':land[7]}) < city_cent['y']
in_half_br = y_at_x(city_cent,{'x':land[2],'y':land[3]},{'x':land[4],'y':land[5]}) < city_cent['y']
if in_half_tr ^ in_half_br # left or right = top-right XOR bottom-right
sp0 = {'x': land[0], 'y': land_cent['y'] - (land_cent['x']-land[0])*dydx(city_cent,land_cent)}
sp1 = {'x': land[2], 'y': land_cent['y'] - (land_cent['x']-land[2])*dydx(city_cent,land_cent)}
else:
sp0 = {'x': land_cent['x'] - (land_cent['y']-land[1])*dxdy(city_cent,land_cent), 'y': land[1]}
sp1 = {'x': land_cent['x'] - (land_cent['y']-land[5])*dxdy(city_cent,land_cent), 'y': land[5]}
print "splitting line from: (%s, %s) to (%s, %s)" % (sp0['x'], sp0['y'], sp1['x'], sp1['y'])
```
Seems to work for some test cases:
```
input brothers' land TLX,TLY,TRX,TRY,BLX,BLY,BRX,BRY:
0.0,0.0,4.0,0.0,0.0,4.0,4.0,4.0
input city land TLX,TLY,TRX,TRY,BLX,BLY,BRX,BRY:
1.0,0.0,3.0,0.0,1.0,1.0,3.0,1.0
splitting line from: (2.0, 0.0) to (2.0, 4.0)
```
And:
```
input brothers' land TLX,TLY,TRX,TRY,BLX,BLY,BRX,BRY:
0.0,0.0,4.0,0.0,0.0,4.0,4.0,4.0
input city land TLX,TLY,TRX,TRY,BLX,BLY,BRX,BRY:
0.0,0.0,1.0,0.0,0.0,1.0,1.0,1.0
splitting line from: (0.0, 0.0) to (4.0, 4.0)
```
] |
[Question]
[
**This question already has answers here**:
[Visualize the Euclidean algorithm again](/questions/119714/visualize-the-euclidean-algorithm-again)
(9 answers)
Closed 4 months ago.
The [Euclidean GCD Algorithm](https://en.wikipedia.org/wiki/Euclidean_algorithm) is an algorithm that efficiently computes the GCD of two positive integers, by repeatedly subtracting the smaller number from the larger number until they become equal. It can be visualised as such:
We start with a MxN grid, where M and N are the numbers. In this example I'll use M=12, N=5:
```
12
____________
|
|
5|
|
|
```
We then, going from the top left, remove a square with a side length of the smaller of the two values, 5, leaving a 7x5 rectangle. This is visualised by replacing the last column of the 5x5 square with a column of `|`s.
```
7
____________
| |
| |
5| |
| |
| |
```
We then remove another 5x5 square, leaving a 2x5 rectangle:
```
2
____________
| | |
| | |
5| | |
| | |
| | |
```
Next, we remove two 2x2 squares, leaving a 2x1 rectangle. As these squares are added when the rectangle is taller than it is wide, their bottom rows are replaced with rows of `_`s.
```
2
____________
| | |
| | |__
| | |
| | |__
1| | |
```
And finally, we remove a 1x1 square, leaving a 1x1 square, whose last and only column is replaced with a `|`. As this is a square, the two sides are equal, so the GCD of 12 and 5 is 1.
The final visualisation looks like this. Note that the numbers are not included, those were just visual indicators.
```
| |
| |__
| |
| |__
| ||
```
Here's a larger example for M=16, N=10. (I'm not going to go through all the steps here).
```
|
|
|
|
|
|______
| |
| |__
| |
| |
```
Note that, as gcd(16, 10) = 2, the algorithm ends with a 2x2 square.
Your challenge is to implement this visualisation, given two numbers M and N where M > N. Your output may have any amount of leading/trailing whitespace.
## Testcases
```
12, 5 ->
| |
| |__
| |
| |__
| ||
10, 16 ->
|
|
|
|
|
|______
| |
| |__
| |
| |
25, 18 ->
|
|
|
|
|
|
|_______
|
|
|
|
|
|
|_______
| |
| |
| |___
| |||
25, 10 ->
| |
| |
| |
| |
| |_____
| |
| |
| |
| |
| |
34, 15 ->
| |
| |
| |
| |____
| |
| |
| |
| |____
| |
| |
| |
| |____
| | |_
| | |_
| | |
89, 55 ->
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|__________________________________
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |_____________
| | |
| | |
| | |
| | |
| | |_____
| | | |
| | | |__
| | | ||
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 43 bytes
```
NθNηBθη W⁻θη¿›θη«≧⁻ηθM⊖η→P↓η→»«≧⁻θηM⊖θ↓⟦×_θ
```
[Try it online!](https://tio.run/##dY5BC4IwGIbP@is@PE2wQ0EXOxVCdDAiukWE2ZcbzKnb1CD67ctNCi8d373f@zzLaSbzKuPG7ETd6n1b3lCSJlz500yHvKmepImARhBAMOSeMo5AUiZa5YowBPYAspWYacsYn16@l2b1WilWiCMrqB4XDmQ1Xlp1SBLMJZYoNN4HWQSxO3V1yzWrJROaxEnVC0v9rn5Xb0Cu8L@rma6mrsa6LNa2B2c5n1iJigTXwH7wYunGzBewNLOOfwA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
NθNη
```
Input `M` and `N`.
```
Bθη
```
Draw an `M×N` box. This solves two problems; firstly, in case one value divides the other, as I assume I'm not allowed `-N` trailing white space; secondly, in case `M>N`, as I assume I'm not allowed `1-N` leading white space.
```
W⁻θη
```
Repeat until `M=N`.
```
¿›θη«
```
If `M>N`, then:
```
≧⁻ηθ
```
Subtract `N` from `M`.
```
M⊖η→
```
Move `N-1` to the right.
```
P↓η
```
Draw `N` `|`s downwards.
```
→
```
Move to the right.
```
»«
```
Otherwise, if `N>M`:
```
≧⁻θη
```
Subtract `M` from `N`.
```
M⊖θ↓
```
Move `M-1` down.
```
⟦×_θ
```
Draw `M` `_`s and move down.
[Answer]
# [JavaScript (V8)](https://v8.dev/), 128 bytes
```
x=>h=(y,i=x,j=y)=>j?(g=(x,y)=>i?y-j+1|x<i?x-i+1|y<j?x>y?g(x-y,y):x<y?g(x,y-x):' ':'|':'_':`
`)(x,y)+(i?h(y,i-1,j):h(y,x,j-1)):''
```
[Try it online!](https://tio.run/##XY3NCoMwEITvfYresovZQgr9IbjmUapI1QSppRbZgO@eRo89DHwzDDOhWZq5/fj3l5Z76jgJVwND1J5FB47IVXDQM4je2LtIoTCrlN4J@UyxDE6q6HoQirljpdyNjiRo1VFZtWY9lK0PNe4zBXg3bBdkdEC7Yf4ig7mvUju95ml8nsaphw7MGeGCePhLbwjXnKYf "JavaScript (V8) – Try It Online")
] |
[Question]
[
# Sokobunny 1
**You *love* buns!**
You love them so much, that you chased one down a bunburrow. The burrows are like mazes, and **YOU WANT TO CATCH THE FLUFFBALLS!!!!** However, the buns are smart! You can't catch the bun by by chasing after it, as you *wait out of politeness for the buns*.
Taken from the game `Paquerette Down the Bunburrows` (This is imo easily the best puzzle game out there, as it is ***meta*** **meta** *meta* *meta* ... *echoes until inaudible*)
## Bun behavior
* Buns will run straight away from you if they can, until they reach a tile with a non-wall left or right. It they see no exits, they run straight ahead.
* A bun is comfortable until you are closer than two squares (manhattan), this means a bun will keep a distance of two empty squares horizontally and vertically, but won't care about diagonals.
* A bun won't choose to go into a dead end it can see.
* A bun can see horizontally and vertically and and tell if it is a straight dead end.
* A bun can see all adjacent squares (horiz, vert, and diag)
* A bun will prefer to turn left, if given the choice.
* A bun is captured if on the same tile as a player.
## Challenge:
Shortest wins!
* Global guarantees: No buns will ever be harmed in the making of these challenges.
* Guarantees (this challenge only):
+ no bun will be captured
+ no bun will run out of bounds
+ mazes will always be a rectangle
* Inputs:
+ Ascii Maze: `#` is a wall, and is not
+ Player position. (Col, row), starting from top-left at (0, 0)
+ Bunny position. Same scheme
* Outputs:
+ New bunny position
+ All rotated inputs should output the same relative position
* You must treat any non `#` character as a wall. This applies expressly to the `P` and `B` characters.
the bun after it moves (if it does).
```
Visual representation (Not valid for challenge):
B is bun, b is where bun goes.
███████████████████████████████████████
████████████████████████ ███ ██████
█████████████████████ ███
██████████████████████████████ ██████
██████ P B------->b ███
████████████ ████████████████████████
███████████████████████████████████████
Maze:
#############
######## # ##
####### #
########## ##
## P B #
#### ########
#############
Player: (5, 4)
Bun: (7, 4)
Output: (10, 4)
Maze:
#############
######## # ##
####### #
########## ##
## P B #
#### ########
#############
Player: (8, 4)
Bun: (10, 4)
Output: (10, 2)
Maze:
############################
#P B #
######################### ##
############################
Player: (1, 1)
Bun: (3, 1)
Output: (25,1)
Maze:
######
### ##
#P B##
### #
######
Player: (1, 2)
Bun: (3, 2)
Output: (3, 3)
Maze:
#######
### ##
## B###
## ###
###P###
#######
Player: (3, 4)
Bun: (3, 2)
Output: (2, 2)
Maze:
#######
#P B #
#######
Player: (1, 1)
Bun: (4, 1)
Output: (4, 1)
Maze:
#######
# P B #
#######
Player: (2, 1)
Bun: (4, 1)
Output: (5, 1)
Maze:
#######
# PB #
#######
Player: (3, 1)
Bun: (4, 1)
Output: (5, 1)
```
```
[Answer]
# Python3, 791 bytes:
```
M=[(0,1),(0,-1),(1,0),(-1,0)]
def F(b,x,y,X,Y,s):
q,s=[(X,Y)],s+[(X,Y)]
while q:
X,Y=q.pop(0)
for J,K in M:
if(U:=(X+J,Y+K))not in s and' '==b[X+J][Y+K]:yield(*U,(J,K));q+=[U];s+=[U]
def f(b,c,C):
(y,x),(Y,X)=c,C
q=[(X,Y,*([(0,-1),(0,1)][y<Y]if x==X else[(-1,0),(1,0)][x<X]),[])]
while q:
X,Y,j,k,s=q.pop(0);P=abs(x-X)+abs(y-Y)>2
T=[((J,K),any(B!=(J,K)for B in F(b,x,y,X+J,Y+K,[(X,Y)])))for J,K in M if(X+J,Y+K)not in s and' '==b[X+J][Y+K] and abs(x-X)+abs(y-Y)<abs(x-X-J)+abs(y-Y-K)]
T=[(a,b)for a,b in T if b or not any(B for _,B in T)]
if[]==T or (len(T)==1 and not T[0][1]and P):return(X,Y)
if any(i[0]!=(j,k)for i in T)and P:return(X,Y)
if(K:=[(0,j),(-1*k,0)][k!=0])in[i[0]for i in T]and P:return(X+K[0],Y+K[1])
for(J,K),_ in T:q+=[(X+J,Y+K,J,K,s+[(X+J,Y+K)])]
```
[Try it online!](https://tio.run/##rVTbbuJADH1evsJtHpgBU3HrRbSzD11pH4q6QiqVQLOjCpZETYsSSFIt@XrWngkpt1Z92CAxsX3sY5@xssiz5zjqXC2S9fpeadHElkT6b/DRwib9N/gwlZkfwE8xxRXmOMIxprJXgSWmlESmNJjWi7cK/H0O5z4sCQDkUcuzRbwQTUlmECdwh30II7jnMISBeOwpMarf4bjelzKKMw6mMIlmVagqNdUUM5qCppeH/nwmao8oqIaU18u60o/mOrWH7TCgDv/gD@5N5Lii9sc4kopc1KxrFWtCbybkcY3Ob8YmDGCl1Aj8eeprN7MTwOjVzchI1OZwMnzBV1JgM9/1QE2mqVg1RrLOL3ljLL@3CTokZtsyTqJc3J4oa7AWtzxsKasTAQsdpZTbcrFUG5k@U4l9cNDHTeFp3JW@Rp8nss1NcGq56OS6Q@KCKZCDiWzP9uae0PY7tHlhoI1SQ0aJuR@JoVSqZck5aaibRrcMmwPZS/zsLYnsWDbT1gwJQlKQhpY7dKVtxkGC6Pfsdr7Yhay92ot5PVFNI8NIc6X3Ema3RL1PUVaN2ilW0N3Fk0X3eIk2wiIF3CIXQtOlr3mvsvhpGk@SmXig1frmSmtdC99pg3Ce@Yn4FUc@wsNZupiHmaj@jqqS1EpboOD09LTibT@lBfQrLeDH20K6GDkHtC5lDA6qOItZ0vb/oCsYv0DXOUa391S8ov0jj/dxJnje52VtA92dBiqbPGIsrJLC4c93Gy4gdu5br5i/8A@2ZnbJF/vJAyhlKkGX@6AtLUvQ1QEIBvugRRJGmQhEuYEpf7jOEbp0XPIh5RFQm6JXDtRqfojq2I8ccMUOH0dBXQdqO1D7OOjcRbufgi7e6bof0l1StP0VUGcHtP4H)
] |
[Question]
[
I'm recieving 2-dimensional positions of two objects as a string with this format: `x1,y1,x2,y2`. The string is recieved from a `readline` call (replaced in the snippet with a `prompt`).
In order to get the horizontal and vertical position differentials, I'm writing the following code:
```
[x1,y1,x2,y2]=prompt("Please enter the positions separated by commas").split`,`
dx=+x2-x1
dy=+y2-y1
console.log(dx,dy)
```
Is there a way to get `dx` and `dy` using less characters since I don't really need the positions? I suppose the main problem could be in the variable assignment which can probably be done in one step. I can use ECMAScript 6.
I don't really know if I have to precise it but removing the text in the prompt or giving variables 1-char names doesn't count, I have written them on purpose to clarify my question. The `console.log` is not part of the code golf either since the variables are supposed to be used after in the program.
[Answer]
I'm not sure exactly what you're looking for, but perhaps something like this?
```
[x1,y1,dx,dy]=prompt("Please enter the positions separated by commas").split`,`
dx-=x1
dy-=y1
console.log(dx,dy)
```
Reusing `x2` and `y2` as `dx` and `dy`, respectively, lets you use the `-=` operator to shorten it a bit.
] |
[Question]
[
Yes, I know there are already [three](https://codegolf.stackexchange.com/questions/105331/pokemon-type-chart-and-dual-type-chart) [pokemon type](https://codegolf.stackexchange.com/questions/1574/the-most-durable-pokemon-types) [questions](https://codegolf.stackexchange.com/questions/55823/its-super-effective), but almost all submissions hardcode the whole chart in one way or other. I think it'd be nice to change the requirement a bit to encourage more shortcut-taking typically seen in decision problems.
# Objective
Write a program/function/whatever that accepts the attacking type and the defending type(s), and output something that can be identified as the final multiplier.
As usual, you can see the pokemon type chart [here](http://pokemondb.net/type/). Also available as text form (copied from another question linked above and modified a bit):
```
Attacking Type
No Fi Fl Po Gr Ro Bu Gh St Fr Wa Gr El Ps Ic Dr Da Fa
Normal 1 2 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1
Fighting 1 1 2 1 1 0.5 0.5 1 1 1 1 1 1 2 1 1 0.5 2
D Flying 1 0.5 1 1 0 2 0.5 1 1 1 1 0.5 2 1 2 1 1 1
e Poison 1 0.5 1 0.5 2 1 0.5 1 1 1 1 0.5 1 2 1 1 1 0.5
f Ground 1 1 1 0.5 1 0.5 1 1 1 1 2 2 0 1 2 1 1 1
e Rock 0.5 2 0.5 0.5 2 1 1 1 2 0.5 2 2 1 1 1 1 1 1
n Bug 1 0.5 2 1 0.5 2 1 1 1 2 1 0.5 1 1 1 1 1 1
d Ghost 0 0 1 0.5 1 1 0.5 2 1 1 1 1 1 1 1 1 2 1
i Steel 0.5 2 0.5 0 2 0.5 0.5 1 0.5 2 1 0.5 1 0.5 0.5 0.5 1 0.5
n Fire 1 1 1 1 2 2 0.5 1 0.5 0.5 2 0.5 1 1 0.5 1 1 0.5
g Water 1 1 1 1 1 1 1 1 0.5 0.5 0.5 2 2 1 0.5 1 1 1
Grass 1 1 2 2 0.5 1 2 1 1 2 0.5 0.5 0.5 1 2 1 1 1
T Electric 1 1 0.5 1 2 1 1 1 0.5 1 1 1 0.5 1 1 1 1 1
y Psychic 1 0.5 1 1 1 1 2 2 1 1 1 1 1 0.5 1 1 2 1
p Ice 1 2 1 1 1 2 1 1 2 2 1 1 1 1 0.5 1 1 1
e Dragon 1 1 1 1 1 1 1 1 1 0.5 0.5 0.5 0.5 1 2 2 1 2
Dark 1 2 1 1 1 1 2 0.5 1 1 1 1 1 0 1 1 0.5 2
Fairy 1 0.5 1 2 1 1 0.5 1 2 1 1 1 1 1 1 0 0.5 1
```
You can choose to either accept one or two defending types (the final multiplier for two defending types is just the product of all individual defending types). Both types of submissions are allowed, as they will be in separate categories.
# Rules
You can choose any methods of input in any form, structure or order (e.g `['fire',['water','rock']]`/`['fire',['rock']]`/`['fire','rock']`, `'water,ice,ghost'`/`'water,ghost'`,`dragondragonsteel`/`dragondragon`).
The only requirement is that the types being inputted must be exactly their names and nothing else. Moreover, the types are required to be in *one* case only: so if you choose "psychic/Psychic/PSYCHIC", you must also use the same case for every other types (e.g "poison/Poison/POISON"). The available casing are: all lowercase, capital case and all uppercase.
You can output anything as long as different multipliers corresponds to one and only one output value.
There will not be two defensive types of the same type.
Standard loopholes are disallowed.
Shortest byte wins.
[Answer]
# JavaScript (ES6), ~~270~~ ~~246~~ 221 bytes
Takes input in currying syntax `(a)(d)` where ***a*** is the attacking type as a string and ***d*** are the defending type(s) as an array of strings. The case doesn't matter.
Returns a standard multiplier as a float.
```
a=>d=>d.map(d=>r*='0124'["ijfkj{jjnjjJ[kefjiZj[jxnjni^YnEW]vfeziiz]okjZmniV{oZvjhjnmj[zrfijij[yVzej[jjejjhujkmjZkZ[fjiuznjjz~zjfRjbkjy".charCodeAt((i=g(d)*18+g(a))/3)>>i%3*2&3]/2,g=s=>parseInt(s,36)*64%97%54%21%18,r=1)&&r
```
[Try it online!](https://tio.run/##jY/BToNAEIbvPkYTuruIrUCt9QCJGjV68FCTNkIwWWGBHWC3WaBpt4mvjtj2ZBpjMod/km/@fAN0TetY8VVzIWTCutTrqOcn/YwqusJ9UKaHLm1ngsIBh7SAHYAAeAkLlgIPIISNAME/3sXDMlqnTHOuI1lAUAm@2MlgDTmICkKtUg4cwu1Cs/4IGEDeQlFBUARh39TqvlV/aUjn8FnAdjCKc6rue6fbBmPuZTghpj07zzAlZOwS3@eGazpDNxo7VubVnr@iqmbPosG15U6JOZ0YN9fG1cRwbMOeWcqzyXCouliKWpZsVMoMpxg9KdmKBBEcosdyy0WGIkLOfkGvUlW03ENzGRfIQm8NY@V/0L@RYzwBLWnD1EGLK3aKOOoekCxvfhYL3bX7D7pv "JavaScript (Node.js) – Try It Online") or [check the whole chart](https://tio.run/##PZFva9swEIff51OYgiMpzdzZTv@MIUO2pqV7MUYLLbXrgWbLts62FCQlzC7sq2dyMgaC3wPSPSfugO2ZKbTY2g9SlfxQ0QOjSelO0LMtdqAXFH0MoxXKzgRULbwDSIBvWcsrEClk8FuCFD9f5eYl31d8FGLMVQtpL8Xzu0r30IDsIRt1JUBANjyP3BUBB2h20PaQtmnmTLvRWcc/I1SP8KuF4SwoGqa/uj@tLcaC1rgki/DmvMaMkIuYJInw40U0j/OLaFlTQ5Mt04Y/SIvNMr4ii6uV/@nav1z5UeiHN0tNQzKf68Pao16Gvivdsw4t0Z2oGytkPWE3nOCHEkZJB/da7WTp4FEVrYsvu@n6vlHGunyynJ8Umrt4YZbrYxEzxuWm44XVopiEZiiaIz0U09Nbzepjg1umJ@8dE3pA@efZrFDSqI4HnarxzPPWpyV4NPmHbEJcuRngrMyJd@4hRIItK58s0xZHR97IEseEBKCExMhD//FNIjIjh78)
### How?
The base-36 interpretation \$N\$ of a given Pokemon type string is converted to a coordinate \$C\$ in \$[0..17]\$ using the following [minimal perfect hash function](https://en.wikipedia.org/wiki/Perfect_hash_function#Minimal_perfect_hash_function):
$$C=((((N\times64)\bmod97)\bmod54)\bmod21)\bmod18$$
The chart is rearranged using the new coordinates and encoded as a single string with 6 bits of payload data per character, using ASCII codes in the range \$[64..127]\$.
There are 2 bits per cell, so the length of the string is \$(18\times18\times2)/6=108\$ characters.
For the curious, [here is the code](https://tio.run/##fVXbbtswDH33VxAFBttrmlquml2y7aH3vgzDGmAPrh9Ux3XcOVIgqUWMIt@eUXKy@lrAEFn18PCQkpgn9sJUIvOVPuJinm63ulylCr5D5AC4P4VcssIdgXuVZwud88z6RbnzfolcCW68ayme@dx4v0Xy19izZwu5XgiljXOn0xSpDO1VLlOz9YfpVFbRTCnjXBZpomWeWHJVJovKvU0s/kKyrEp3waRNcsVyWbpOPHWcZMGk3gmPIBwBHZm1/gWdncYH8WgfWw8n9uvi6wBaiyW1dLQTS/aBtC8vaWK6sa26SFNznaElle7L7@Yle52kSU73O/TdXtXV0k5/yHBssJdEOs0Jhxre0RzUxHdbR@r/6vTqf2fqYNrUEw7Hto6GNNtFhu8V7RwlbUqlA7E9F2DA771XrarDvtvV6nPYd6a9DEP1vt8u0mSjA3nDvqdUf9G9b5AOP5w6A7GaqyEiuBJFOi5E5h3MJOOqYDoXHDR7KFJ4lGIJC6YWnhmTPmgBQuZZzlkB1fxJhJBz/FunXw98JLzBiYTj9AesmFTpLdeeGsHJxIePMKHwAb58wuXUeCHBhXzGmBnGvG6mjh3F40chL1my8Exg7huqWXTjKT9GVO63NM/aGwf3/AzlyBKWDAfrGlU5DlJ6SzMq4xGUaIMpmm8mOZSHh/4rdtFCojLeodYVar1DrXcoAIOJ1hbmBoEZyQExK7H@0ZH1iRtHtj3RDOExrus4xnYDbJxNU@9yvGQrT5oy5fhJ5NxzwfX9nXvP0e9WeMkT/O2ag8IKeWZLfMg5aupheyNzkSmTK4QhGIEam3w8fp1sjrN2DoRZJnuSdzbL2NyFcyzqHFN7b6cb0RgOQUWnlQkrc1KZoDIEOxr66E5oTY0/3W7/AQ) that encodes the string.
[Answer]
# [Python 2](https://docs.python.org/2/), 305 bytes
```
def f(l):d=[int(t[2:],36)%123%28%21for t in l];return reduce(lambda x,y:x*int("eJx1UIENwDAIekkM/982FW3skprUzA4oCHe6O6Jb9F05XXeATlDIouUndGLGRUYxTDD6o0YlhSmh/adnW7o8DzS6O9PWAmM9WnbLssktWgLjoNG1iwAw/RM4DqCIaZH3mv6l5MkF22fKKp6Vxtnji05OrsnADjaX+AByt1Y8".decode('base64').decode('zip')[d[0]*21:][y])/2.,d[1:],1)
```
[Try it online!](https://tio.run/##fVNdc6IwFH3nV2Q64yBdpgoqq@70gZZqbf3oaF10GR4iiYIgYUNcxT/vEqRYt86@wMk9Nyfn3EyihLkkVI9HhJdgWQ6kNrq3vJCVmaW2bbmmSSVFrZXUZklVloQCBrwQBPYPitmWhoBitHVwOYCbBYJgLyft/S3ffYNf9sq09zTcGXoP@/6g0mqqHbMW@xGdHvQ6eXzG2kh7WbQ61cZshvX3wOiR7TRE3X53PJ3v3w1DI9V54E42bgWi0PxOmsZhoo1ab6a@GbTMcNGPY5@Zq/6aDLuKt9N3lfGgbvx@7MFfz7XNHy1oDPyOqi5fXyPt556Fa6/aGNE41I01nH3THxKmzJs3dwg7BOGyuIAx1uqiVBQOXiRKFrKq9q2qtG0rsaWKeicjK13IinSMaJo0nZkldinZhkiUxU6QeOFKtCXhTA4J3cAgJcfE8dPfhGEc/K/lOpWDC9KEDFN@rEfxJZMb4dTKZSf4sM2cXRPvOTj95jEuhbi0XJz01WDe8JX42JJruyRm1xuuUAaFKxKmXAGuTO3fpnM2QWBJhOP7c0LwaRCgmA4Q34gXcw1Q3CHI7wlk8@JEZi8FJwuZFI8MPgLwvTCOOXgKsMOo52TSceK4J5iNABSGUwRpdkQHejQRbUHgTwvxp5UZbwuAF@DnAjhFE0v1lVhK40MZ2ZIsnMrHvw "Python 2 – Try It Online")
Also hardcoding the whole matrix..
[Answer]
## ABAP, 691 bytes
### Form-Subroutine taking two or three types in capital case
```
DATA:x(180) TYPE x,v type x,b,c.DEFINE g.GET BIT:&1 + 1 OF &2 INTO b,&1 + 2 OF &2 INTO c.SET BIT:7 of v TO b,8 of v TO c.IF v = 3.o = 2.ELSE.o = v / 2.ENDIF. END-OF-DEFINITION.
DEFINE f.FIND &1(3) IN'NorFigFlyPoiGroRocBugGhoSteFrrWatGraElePsyIceDraDarFai'RESULTS data(&2). END-OF-DEFINITION.
FORM f USING a d e.DATA(o) ='1.00'.x ='BAA8AAAAA0AE96AABA709A36A9EEA099E6A9BA90A99AAF2EA075EADFAAA09E7AB9AAA009A7AAAAE074D6799590AAF65DA690AAAA57E6A0AF6EB56EA0A6EA6A6AA09AAFAA9AE0BABAFAA6A0AAAA956FB0BAADAA8A709BA6EAA860'.f:a
r,d s.DATA(l) = r-offset / 3 * 2.DATA(n) = o.IF strlen( e ) > 2.f e t.n = ( t-offset / 3 ) * 5.g l x+n.n = o.ENDIF.o = ( s-offset / 3 ) * 5.g l x+o.o = o * n.WRITE o.ENDFORM.
```
Newlines in the code replace required spaces around the `END-OF-DEFINITION` keywords. Might as well keep it as "readable" as possible.
Can be called by another program like so:
```
REPORT z.
PERFORM f USING 'Fighting' 'Normal' 'Rock'.
```
Result: `4`
```
REPORT z.
PERFORM f USING 'Ghost' 'Normal' ''.
```
Result: `0`
```
REPORT z.
PERFORM f USING 'Fairy' 'Poison' 'Normal'.
```
Result: `0.5`
## Explanation
Geez, what a monster. Far from competitive as per usual, but I learned a lot about handling bits and bytes in ABAP - or rather that I don't want to do it ever again.
The type weakness table was converted to bit pairs:
`00 = 0x`, `01 = 0.5x`, `10 = 1x`, `11 = 2x`
Each row of the table was then converted to 5 bytes each and all concatenated into one 180 character long byte-like string, which is hard coded into the program obviously.
The bytes for each row are padded with a trailing zero because ABAP doesn't work with half a byte offsets - or at least I couldn't get it to work properly. I couldn't use a higher number base either (like base-64) due to how ABAP handles them and how complicated and lengthy it gets to do so. Also dealing with overflows. Meh.
```
DATA: "Multiple declarations
x(180) TYPE x, "Byte-like string of length 180, holds the type weakness table
v TYPE x, "One byte
b, c. "One letter chars for saving the values of bits (implicit char -> number conversion)
DEFINE g. "Define a macro for reading two bits, we need this multiple times
GET BIT: "Get bits from the hex encoded weakness table; index starts at 1
&1 + 1 OF &2 INTO b, "get bit 1 ==> offset + 1
&1 + 2 OF &2 INTO c. "get bit 2 ==> offset + 2
SET BIT: "Unfortunately this is the best way of copying over bits (that I am aware of) to another value. Sets the two least significant bits so we get a value between 0 and 3.
7 of v TO b, "Set result bit 1
8 of v TO c. "Set result bit 2
"This is the best I could come up with.
IF v = 3. "If it's a binary 11 (3 in base10)
o = 2. "then it's double damage
ELSE. "For everything else the bit's base10 value can simply be halved, as 0/2=0, 1/2 =.5, 2/2=1.
o = v / 2.
ENDIF.
END-OF-DEFINITION. "End of macro bits
DEFINE f. "Define macro for finding the column/row of types in the weaknesses table both horizontally or vertically
"Find first occurrence of the first three letters of the type and save the result to a newly initialized variable
FIND &1(3) IN 'NorFigFlyPoiGroRocBugGhoSteFrrWatGraElePsyIceDraDarFai' RESULTS data(&2).
END-OF-DEFINITION. "End of macro types
FORM f USING a d e. "This subroutine has three parameters: [a]ttack, [d]efender primary, d[e]fender secondary
DATA(o) ='1.00'. "Quick declaration of a number with 2 decimals
"The type weakness table, encoded as binary, written in hexadecimal.
"Each table row corresponds to 4.5 bytes = 36 bits, padded with half a byte of 0's => 40 bits = 5 bytes = 10 characters each
x ='BAA8AAAAA0AE96AABA709A36A9EEA099E6A9BA90A99AAF2EA075EADFAAA09E7AB9AAA009A7AAAAE074D6799590AAF65DA690AAAA57E6A0AF6EB56EA0A6EA6A6AA09AAFAA9AE0BABAFAA6A0AAAA956FB0BAADAA8A709BA6EAA860'.
f:a r,d s. "Call type index macro for the attack and primary defender type, saves the result in r (for attacker) and s (for defender)
DATA(l) = r-offset / 3 * 2. "Find the attacker's "table column". Each column is 2 bits wide, but type abbreviations are 3 letters
DATA(n) = o. "Result of the secondary defender's type weakness will be saved here; default (if no type is given) = 1x from o's default value
IF strlen( e ) > 2. "When there was a secondary type given (length of type name > 2 characters)
f e t. "Call type index macro for the secondary defender type.
n = ( t-offset / 3 ) * 5. "Divide offset by 3 because abbreviations are 3 letters wide, then multiply by 5 to find the correct "table row" (5 bytes per row)
g l x+n. "Call the bit reading macro; use attacker's column offset in bits and the defender's secondary type's row offset in bytes
n = o. "Save the resulting number to n temporarily
ENDIF.
o = ( s-offset / 3 ) * 5. "Get primary type's row offset in bytes
g l x+o. "Call bit reading macro: attacker's column offset (bits), defender's primary row offset (bytes)
o = o * n. "Multiply weakness by secondary weakness
WRITE o. "Print result
ENDFORM. "End of subroutine
```
*Phew*. How's that for some way too verbose code. There might be a better way to do it, but I doubt anyone else is mad enough to try golfing in ABAP. Still, suggestions are welcome, of course!
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 382 363 bytes
I wanted to try something a little different, so I made a sparse array of the values that were not equal to 1 and encoded them in a base-90 format so that the column that they are on could be converted to +/-1.0 and added to a 1.0 multiplier.
Thanks to ceilingcat for the suggestion.
```
*y[]={"8(;","i56n9(q@wyD","j8o;t?","678:)tz","#ln9qr>u","4k7o;rw","456:;<tvyD","!pvC","n;<=?wz","8oq<=twB","mnr=>B","56mn9;<s>B","k%s>?B","jl;@1","km;<=tAx",";x2","4pvCD","j6;<xy"};i,j;float f(int**s){int k[3]={};float f=1;for(i=18;i--;)for(j=3;j--;s[j]&&!strcmp(z[i],s[j])?k[j]=i:0);for(char*t=y[*k];i=*t-33,*t++;)for(j=0;++j<3;)f*=i%18-k[j]?1:i/18/2.;return f;}
```
[Try it online!](https://tio.run/##fVLBbptAEL3zFRuiRIBxEkzjEC9rp6mbqFIUVa2qHigHRMBejCHZXcfBln@97uxisFtFvXje7Mx7M2Ze3J3E8faYFnG@eEqQz8UTLc@mQ02LpxFD1ioIEUFrpCGkP5ZsHuW6rd/RyVTQYiJhXtXga0l5WQC4Z@WieALwrYxnEG4Xsnw/LbnQbSnzXSRJrcISCD8jkTDFiziH@DlPYsFoLDV5FU8V@hLL1jGLJmrGOGJS@i6irNK1Dd5aVRCSte4ZGJ7pZb@4Nl5ultUYsswrsRgB6F95A1OsAB3nxfULGy4AfphdlZgtJbrsD7AvXhXp6Pn1E4QC@2S0lBSvfPGJWN4CnBeMDCW47M@La@xzlcxO@HAkQZbjG0c@zIEsPr4BxG89OQA01UJ97L9V@gZTO8NpXkYCpQYthGVxcw0RzQIX/symqREHpyUzKHE8TLtdbMosIy7OIOFBFp6eHnHB4vmzsQpoaMsnczSDX0IHF6Yiy2NaglSBNQsxJZbouq5tiU6nUbvAnU7mu5BahJ44XlfyR86Anjveee8Ms0QsWIFSvNnWxhAJFxw@OlrLmzZHR60h0OOPhwf70DZo54jWAe8W36G1qK3tPIN2HtoX2ukHHkW1Bf/WVIba7624tdZevN7osPTvjm1rI7d3eVvave1JjYsP0cEXeafcUGUEt2uaJm0yj2ghfYMiNont@ioW4FdT3YSmhiwMe3WKUN3BlblkW@CENlKg1wA3BHXZ@8xAODX0k7Ne@kuukBrcNGVtg5KcJztJ5UvYgIJ/akNQsFeHuM3M/VQY2nTYaIc6zgHuNbP/Nx3myx20zfZ3nObRhG@7yz8 "C (gcc) – Try It Online")
] |
[Question]
[
## 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](https://en.wikipedia.org/wiki/Bitwise_operation#Rotate_no_carry)
4. [Apply Binary Addition](https://www.allaboutcircuits.com/textbook/digital/chpt-2/binary-addition/)
5. If the result is more that 8 bits then get the [one's complement](https://en.wikipedia.org/wiki/Ones%27_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]
# [Python 2](https://docs.python.org/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!](https://tio.run/##K6gsycjPM/rvbKukpPQ/1ba4NFcjvyhFIzXaIFZT30QbzlY10TIzScsvUkhVyMwDooLSEg1NTeuCosy8EoXkjCKN6FSdutTY6FQ7I1PTWFUjUzPN/0AjrVMrUpOVyjMyc1IVnK1AHAVnpf9KHko6Ckq@eSDSWYlLyRPEAIsFpwK53mDxRLCadCUA "Python 2 – Try It Online")
-8 bytes thanks to Jonathan Frech
[Answer]
# [Perl 5](https://www.perl.org/), 44 bytes
```
$n+=257*ord>>2&255}{$_=chr($n>>8?~$n%256:$n)
```
[Try it online!](https://tio.run/##K0gtyjH9/18lT9vWyNRcK78oxc7OSM3I1LS2WiXeNjmjSEMlz87Owr5OJU/VyNTMSiVP8/9/Ty4PruDUf/kFJZn5ecX/dQsA "Perl 5 – Try It Online")
] |
[Question]
[
UBASIC is a freeware [basic](/questions/tagged/basic "show questions tagged 'basic'") interpreter written by Yuji Kida at Rikkyo University in Japan, specialized for mathematical computing. It is considered to be a "ready-to-run" language that and is capable of running on DOS and Windows.
What general tips do you have for golfing in uBasic? Any ideas that can be applied to code golf problems in general that are at least somewhat specific to uBasic. Please post one tip per answer.
>
> Some helpful links
>
>
> [uBasic Wikipedia Page](https://en.wikipedia.org/wiki/UBASIC)
>
>
> [Try it Online](https://tio.run/#uBASIC)
>
>
>
[Answer]
# Use `?` in place of `Print`
Instead of using the `Print` command, `?` may be used, as is the case in many BASIC languages - this means that the most simplest uBASIC `Hello, World!` program is as follows
```
0?"Hello, World!"
```
Rather than
```
10 Print "Hello, World!"
```
[Try it Online!](https://tio.run/##K01KLM5M/v/fwF7JIzUnJ19HITy/KCdFUen/fwA)
[Answer]
# Avoid Whitespace in `For` and Like statements
Whitespace between `For` and a variable name is not necessary in uBASIC meaning that a `For` loop may be condensed from
```
0 For t = 1 To 2
1 ?t
2 Next t
```
to
```
0Fort=1To2
1?t
1Nextt
```
[Try it Online!](https://tio.run/##K01KLM5M/v/fwC2/SCHT1lAhJF/B0IDL0D7TmsvIL7WiRCHz/38A)
[Answer]
# Execute multiple commands on a single line with `:`
uBasic allows for the execution of many commands on a single line with the use of `:` over a new line and new line number.
This means that this (50 Bytes)
```
0Fori=0To10
1Forj=1To9Step3
2?i*10+j
3Nextj
4Nexti
```
May be condensed to this (46 Bytes)
```
0Fori=0To10:Forj=1To9Step3:?i*10+j:Nextj:Nexti
```
[Try it Online!](https://tio.run/##K01KLM5M/v/fwC2/KNPWICTf0MAKyMyyNQzJtwwuSS0wtrLP1DI00M6y8kutKIGQmf//AwA)
[Answer]
# Use `;` to `Print` Without a Newline
Much like is the case in VBA and other BASIC languages, you may add a `;` to the end of a print statement to keep from printing a newline character and continue printing on that line.
Example:
```
0For i=1 To 10
1?i;
2Next i
```
Outputs
```
12345678910
```
[Try it Online!](https://tio.run/##K01KLM5M/v/fwC2/SCHT1lAhJF/B0IDL0D7TmsvIL7WiRCHz/38A)
Similarly, `,` may be appended to the end of a print statement to prevent to pad the output right to a width of eight characters (note however, the output number or string must be of a length less than or equal to 6 characters)
Example
```
0?1,"|"
```
Outputs
```
1 |
```
[Try it Online!](https://tio.run/##K01KLM5M/v/fwN5QR6lG6f9/AA)
] |
[Question]
[
Given 2 random circle sections, return how many times they intersect. Rules/clarifications are as below.
1. You are provided 10 total values,
* The center (x,y) of the circle section
* Angles of the circle (i.e. (0,90) would be a quarter circle "facing" the top-right corner.
* The radius of the circle section
2. The circle sections are "drawn" on a 128 by 128 screen, with (0,0) being the center. They have a max radius of 64.
3. You don't need to draw the circles - the program should *only* print out the number of intersections.
4. You can choose to generate the values randomly, in-program, or have the user write it in at program start. (The latter is preferred, but not necessary.)
Below is an example case. As you can see, it has one intersect.

The output should look something like this:
```
$ run ./circle
input (circle 1 center)
input (circle 1 radius)
input (circle 1 angles)
input (more inputs...)
...
intersections
```
Heres the output for the example case (the prompts are optional):
```
$ run ./circle
c1center: (20,20)
c1radius: 40
c1angles: (210,150)
c2center: (-30,-30)
c2radius: 90
c2angles: (270,180
1
```
Anyway, best of luck! This is code golf, so the minimum number of bytes in any programming language wins!
Oh, and it'd be nice if you could provide a description/link to your program in the answer. Standard Loopholes are not allowed. If you find any errors in my explanation or want me to clarify, just ask. Thanks!
[Answer]
# [Python 3](https://docs.python.org/3/) + [numpy](http://numpy.org), ~~310~~ 291 bytes
-19 bytes thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs)!
```
v=lambda c,x,y:sin(arctan2(*c[::-1])-x)>sin(y-x)
def f(a,r,w,x,b,s,y,z):
d=linalg.norm(b-a)
if abs(r-s)<d<r+s:e=(r*r-s*s+d*d)/2/d;g=a+e*(b-a)/d;t=(sqrt(r*r-e*e)*(b-a)/d*[1,-1])[::-1];return int(v(g+t-a,w,x)and v(g+t-b,y,z))+int(v(g-t-a,w,x)and v(g-t-b,y,z))-(t==0).all()
from numpy import*
```
[Try it online!](https://tio.run/##XY/BcoMwDETvfIWOlrGTQG4k7o8wOYgYKDNgiOykoT9PIYF2piftzj5pVsMYPnt3nKaHaakrLMFVPdWY@cYJ4msglwp5zbNMJxfUT/xYgnEWkS0rqAQpVl/zRqG8GtU3ZhFY0zaO2nrneu5EoQkjaCqgwgvWHs/2zLHPSiNYzl762EqL@3RvT7WhuJSvldkFI/yNwwsrZYlbIPNELW3epU5chjs7aFwQD1HHQdNSCMlZePviVQzjldD/CP1LaBGMOeCO2lZgVHHfgbt3wwhNN/Qc5DTwcmN@mplGkR8UHC6oIFGghwb2kCrY5ookf8iWHEGuGnH6AQ "Python 3 – Try It Online")
This is a horrible answer.
Takes angles in radians.
] |
[Question]
[
**Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/114615/edit).
Closed 6 years ago.
[Improve this question](/posts/114615/edit)
Usually to run multiple commands consecutively one would do:
```
sudo apt update && sudo apt upgrade # 35 characters
```
I can't help but feel there's a neat trick to running these with less keystrokes, and you golfers here love challenges :)
I've found a ton of answers around various SE Sites related to running arguments to different commands or commands in parallel, but nothing like what I'm after.
I've come to achieve what I want a couple of ways, but it's way longer and more difficult to type:
```
x=('update' 'upgrade') && for i in ${x[*]}; do sudo apt $i; done
```
I quickly shortened this to:
```
for x in update upgrade; do sudo apt $x; done
```
then
```
for x in update upgrade;do sudo apt $x;done # 43 characters
```
Using `bash`, what is a golfed way of achieving the above? shortest line wins
(this is my first post to the group, please be kind if I've used the wrong tags) ;)
edit: as pointed out my own loops don't exactly do what is in the question due to the `&&` being conditional on the first command not having an error (I do know this). There's also the fact that my loops (and the original command line without the `-y` switch) still requires user input to complete. An oversight. Time for some more explicit instructions.
My original thought was to have something like:
```
echo update upgrade | sudo apt
```
with the objective of just running one after the other.
In the interests of trying to open this up to other languages, let's expand it thusly:
Objectives:
* run both commands
* require no more than one additional keystroke by the user
* can outsource this to other other languages/scripts\*
* can be scripted if:
+ gracefully fails (error messages are ok, but it shouldn't try and execute anything else in error)
+ it's something commonly or "unobtrusively installable" in linux/ubuntu (I feel I may regret this line)
+ the script takes at least three arguments
+ 1. command to run
+ 2. argument 1
+ 3. argument 2
+ 4. argument n
+ or specified on the command line, (see next example)
+ in this second case, see the note below
`./twice "sudo apt" update upgrade`
\*I have it in mind that someone could construct a cute little binary/script from a `printf`, but the essence is, if it can be run from an executable script, all characters of the script EXCEPT the first line (the shebang) count.
If I've totally messed this up, feel free to close. Cheers
[Answer]
# 40 bytes
```
for a in ${@:2};do eval "${1} ${a}";done
```
Usage: `./[filename] "[primary command]" [arguments]`
Ex. `./twice "sudo apt" update upgrade` (Assumes 'twice' as file name)
Was this what you wanted?
*Note: Please golf me further if it is possible, and correct me if I'm wrong. This was my first bash entry.*
[Answer]
## 24 bytes
Interactively, you can reduce this to 24 keystrokes (plus root password)
```
su
apt update
^dat^grad
```
An abstract script starts at 25 bytes +boilerplate:
```
#!/bin/bash -e
for x in ${@:2}
{
$1 $x
}
```
or at 29 bytes:
```
printf "$1 %s
" ${@:2}|sh -e
```
as in
```
e(){ printf "$1 %s\n" ${@:2}|sh -e;}
e "sudo apt" up{dat,grad}e
```
For concrete one-liners, the 32 bytes of
```
sudo sh -ec apt\ up{dat,grad}e\;
```
are only 1 byte shorter than
```
sudo apt update&&sudo apt upgrade
```
or 3 bytes shorter than
```
e(){ sudo apt up$1e;};e dat&&e grad
```
] |
[Question]
[
So, recently, I found myself reformatting my code for Vitsy to using anonymous class instances for commands rather than the normal method approach. For those who don't know, anonymous class instance syntax looks something like this:
```
...
private abstract static class SomeClass {
public abstract void someMethod();
}
public final SomeClass someField = new Command() {
public void someMethod() {
// Some implementation
}
};
...
```
So what's your job, I hear you asking? Well, it's quite simple.
# The Challenge
Given a class name, its inner method, and string of zero to many conventional methods, turn them into anonymous class instances, retaining the program instructions therein. For formatting purposes, I have labelled the input and output below for what must be considered (anything in `<>` needs to be retained in the output).
### Conventional method syntax
```
<visibility modifier> void <method name>(){<implementation>}
```
### Resulting instance declaration
```
<visibility modifier> final <class name> <method name>=new <class name>(){public void <inner method name>(){<implementation>}};
```
# The Rules
* You may not use any builtins for this challenge (if there are builtins for this, the lang creators have done a bad and they should feel bad).
* You must retain the method name, the visibility modifier (public, private, (nothing), protected) and the implementation.
* Do not worry about proper tabs/formatting. As long as it is Java compile-able, you're fine.
* You may assume that all code inside of `<implementation>` is valid.
* You may assume that there is nothing but methods in the string given.
* Do not translate any methods that are *not* void.
* Do not translate any methods with a parameter.
* Input may be in any convenient format for your language.
# Examples
```
>>> toAnonymousClass("ClassName", "innerMethod", "public void method1(){}")
public final ClassName method1=new ClassName(){public void innerMethod(){}};
```
```
>>> toAnonymousClass("ClassName2", "secondInnerMethod", "private void method2(){return;}protected int method3(){return 4;/*guaranteed to be random*/}")
private final ClassName2 method2=new ClassName2(){public void secondInnerMethod(){return;}};protected int method3(){return 4;/*guaranteed to be random*/}
```
Note here that the void method is translated with the visibility modifier (private) retained, but the int method is not translated as it has a different return type (int).
```
>>> toAnonymousClass("Clazz", "inMethod", "void method4(int param){}")
void method4(int param){}
```
`method4` is not translated, as it accepts a parameter (`int param`).
```
>>> toAnonymousClass("Moar", "again", "void method5(){}")
final Moar method5=new Moar(){public void again(){}};
```
Another example of visibility modifier retainment - if it has no modifier, have no modifier on the output.
Finally, the big test case:
```
>>> toAnonymousClass("Hi", "rand", "private void method2(){return;}protected int method3(){return 4;/*guaranteed to be random*/}public void method1(){}void method4(int param){}void method5(){}")
private final Hi method2=new Hi(){public void rand(){return;}};protected int method3(){return 4;/*guaranteed to be random*/}public final Hi method1=new Hi(){public void rand(){}};void method4(int param){}final Hi method5=new Hi(){public void rand(){}};
```
[Answer]
# Retina, 95 bytes
Byte count assumes ISO 8859-1 encoding.
```
+`^((.+)¶(.+)¶(.+¶)*)(\w+ )?(void )(\w+)(..{.*})
$1$5final $2 $7=new $2(){public $6$3$8};
\w+¶
```
The code contains a trailing newline.
Takes input separated by newlines. Class name on the first line, inner method name on the second line, methods on following lines.
For example:
```
Hi
rand
private void method2(){return;}
protected int method3(){return 4;/*guaranteed to be random*/}
public void method1(){}
void method4(int param){}
void method5(){}
```
[Try it online!](http://retina.tryitonline.net/#code=K2BeKCguKynCtiguKynCtiguK8K2KSopKFx3KyApPyh2b2lkICkoXHcrKSguLnsuKn0pCiQxJDVmaW5hbCAkMiAkNz1uZXcgJDIoKXtwdWJsaWMgJDYkMyQ4fTsKXHcrwrYK&input=SGkKcmFuZApwcml2YXRlIHZvaWQgbWV0aG9kMigpe3JldHVybjt9CnByb3RlY3RlZCBpbnQgbWV0aG9kMygpe3JldHVybiA0Oy8qZ3VhcmFudGVlZCB0byBiZSByYW5kb20qL30KcHVibGljIHZvaWQgbWV0aG9kMSgpe30Kdm9pZCBtZXRob2Q0KGludCBwYXJhbSl7fQp2b2lkIG1ldGhvZDUoKXt9)
] |
[Question]
[
For the purpose of this question, a magic square is an `n`×`n` square of (not necessarily distinct) positive integers, where all rows, columns, and main diagonals add to a "magic constant" `m`.
### Your Task
Create a function or full program that, given the magic number `m` and a list representing a square **with at most one wrong number in each row and column**, will output a list with the entries rearranged to represent a correct square. Your program will be expected to handle any solvable square of any size. Your program should take less than twenty minutes for n=7 or smaller. Assume that all input is solvable.
### Example Input (list, m)
```
[16, 16, 11, 9, 14, 17, 9, 29, 13, 1, 15, 5, 6, 16, 15, 7, 3, 17, 11, 12, 14, 17, 3, 8, 6], 58
```
which represents this square1:
>
> 16 16 **11** 09 14
>
> **17** 09 29 13 01
>
> 15 05 06 **16** 15
>
> 07 **03** 17 11 12
>
> 14 17 03 08 **06**
>
>
>
A compliant solution has to solve the following 7x7 square within the time limit.
```
[31, 19, 10, 13, 14, 32, 15, 6, 21, 17, 22, 30, 17, 7, 17, 30, 17, 24, 17, 11, 8, 7, 22, 33, 13, 15, 17, 11, 14, 16, 21, 22, 13, 11, 29, 16, 13, 3, 19, 12, 12, 43, 27, 13, 19, 13, 20, 18, 11], 123
```
### Example Output
For the first test case, this is the only correct solution.
```
[16, 16, 3, 9, 14, 6, 9, 29, 13, 1, 15, 5, 6, 17, 15, 7, 11, 17, 11, 12, 14, 17, 3, 8, 16]
```
For a bonus of **-10**, format your output into a square and pad single digits with zeroes as below.2
>
> 16 16 **03** 09 14
>
> **06** 09 29 13 01
>
> 15 05 06 **17** 15
>
> 07 **11** 17 11 12
>
> 14 17 03 08 **16**
>
>
>
---
1 Bolded numbers are in incorrect cells.
2 Bolded numbers have switched cells.
[Answer]
# CJam, ~~73~~ 70 bytes
```
q~:Q,mQ:Le!{QL/.{1$W$W*t_:+W*t}:Te_$Q$=Tz{W%_L,.=a\}2*++::+)-!*}=&T"%02d "ffe%N*
```
The above code is 80 bytes long and qualifies for the bonus.
Time complexity is **O(n!)** for **n×n** squares. For **9×9**, this translates to 7 seconds on my machine.
Try it online: [permalink for Chrome](http://cjam.aditsu.net/#code=q~%3AQ%2CmQ%3ALe!%7BQL%2F.%7B1%24W%24W*t_%3A%2BW*t%7D%3ATe_%24Q%24%3DTz%7BW%25_L%2C.%3Da%5C%7D2*%2B%2B%3A%3A%2B)-!*%7D%3D%26T%22%2502d%20%22ffe%25N*&input=123%20%5B31%2019%2010%2013%2014%2032%2015%206%2021%2017%2022%2030%2017%207%2017%2030%2017%2024%2017%2011%208%207%2022%2033%2013%2015%2017%2011%2014%2016%2021%2022%2013%2011%2029%2016%2013%203%2019%2012%2012%2043%2027%2013%2019%2013%2020%2018%2011%5D) | [permalink for Firefox](http://cjam.aditsu.net/#code=q~%3AQ%2CmQ%3ALe!%7BQL%2F.%7B1%24W%24W*t_%3A%2BW*t%7D%3ATe_%24Q%24%3DTz%7BW%2525_L%2C.%3Da%5C%7D2*%2B%2B%3A%3A%2B)-!*%7D%3D%26T%22%252502d%20%22ffe%2525N*&input=123%20%5B31%2019%2010%2013%2014%2032%2015%206%2021%2017%2022%2030%2017%207%2017%2030%2017%2024%2017%2011%208%207%2022%2033%2013%2015%2017%2011%2014%2016%2021%2022%2013%2011%2029%2016%2013%203%2019%2012%2012%2043%2027%2013%2019%2013%2020%2018%2011%5D)
] |
[Question]
[
## Introduction
You're an American spy during the heat of the Cold War and you've managed to intercept a Russian message. Immediately you recognise it as a code stick cipher and wrap it around a pencil. Looking at the paper on the pencil, you don't see anything. Then you try a bigger pencil, and you see it.
## Challenge
You have to write a program that deciphers a code stick. As this is code golf, the shortest program wins.
You may use any English dictionaries for looking up words. Some examples of dictionaries include:
* Querying a text file of words
* Using an inbuilt OS dictionary
* Querying an online dictionary (screen scraping etc.)
* Using an external lib
### All words MUST be valid English words
## Your pencils
Each of your pencils has four equally sized faces and are infinitely long. You have five differently sized pencils:
```
Pencil 1: Shows 1 character on each face
Pencil 2: Shows 2 characters on each face
Pencil 3: Shows 4 characters on each face
Pencil 4: Shows 6 characters on each face
Pencil 5: Shows 8 characters on each face
```
All ciphers can be deciphered by placing the start of the paper at the top of the pencil and wrapping it down.
## Examples
The following is an example of a cipher:
```
Hepoge slljghadso bvvbgh
```
This can be deciphered by wrapping it around Pencil 2:
```
Side 1 | Side 2 | Side 3 | Side 4
-------+--------+--------+-------
He | po | ge | s
ll | jg | ha | ds
o | bv | vb | gh
```
So now you have four combinations:
```
Hello , pojgbv, gehavb, sdsgh
```
You can now perform a dictionary lookup and see that `Hello` is the only valid word. Therefore, `Hello` is the cracked cipher.
***Note:*** Deciphered codes may have spaces in. Example: `Hello World`
## Test cases
Ciphers can be inputted in any way apart from being hardcoded. The following are a few test cases. You **will not** be given the pencil size.
```
boasonespetrabbittonespongomezesray long
lsbvmii derfghthstthasinlomnrtk fg dndthugssawerpoloasefnxafqeormnaqwge padhndi mbavwgam
lipois lisptloopoolsisp lortfippinglthe asse rtedgoodcodeis the best of enlymoolfangthe leamingsoulsgodsingering
antidisebd sldkfdw sld sja dmddystablishjzkapxmjhavzlx dld slzbfmentariabahdjdlljagzlxbxlffnd ldnism is hdbsh spjalcpdhstd flcnda very cbd skd alsbfo kfvwfd xlconvolutehs ska ckw dlc fjzlxbckxd word hs sla k dk skdnlcjcu dk
```
Any more test cases would be appreciated
### Answers to the test cases
>
> **1:** astronomy
>
> **2:** i think therefore i am
>
> **3:** is lisp the code of the gods
>
> **4:** antidisestablishmentarianism is a very convoluted word
>
>
>
### Script to generate code stick ciphers:
```
import string, random, math
word = input('Word:\t')
n = int(input('Pencil:\t'))
pencil = int(-((4*(17*n-77))/((n**4)-(19*n**3)+(136*n**2)-(444*n)+566)))
alpha = string.ascii_lowercase+' '
cipher = ''
side = random.randint(1, 4)
sides =['','','','']
for j in range(len(sides)):
if j+1 == side:
sides[j] = word
if len(word)%pencil != 0:
sides[j] += ' '*(len(word)%pencil)
else:
for k in range(math.ceil(len(word)+(len(word)%pencil))):
sides[j]+=random.choice(alpha)
for l in range(0, math.ceil(len(word)/pencil)*pencil, pencil):
for m in sides:
cipher += m[l:l+pencil]
print('Cipher:\t'+cipher)
print('Side:\t'+str(side))
```
[Answer]
# Python - ~~219~~ ~~178~~ ~~172~~ 175
First crack at it. I'm sure there's room for improvement.
**edit1: After suggestions, and copying words file to local file named 'w'**
**edit2: Fixed a bug where it wasn't using the right number of letters per side. Added 3 chars :(**
```
r=range
s=raw_input()
print[a for a in(''.join(s[m:m+n]for m in r(o*n,len(s),4*n))for o in r(4)for n in(1,2,4,6,8))if not set(a.lower().split())-set(map(str.strip,open('w')))]
```
[Answer]
# Mathematica ~~270 230~~ 251
---
This now requires that all parsed words be found in a dictionary.
```
f@q_:=
Module[{c=Characters@q,wd,u=DictionaryLookup},
j@d_:=Union[u@d,u[ToLowerCase@d],WordData@d];
Flatten@Select[Flatten[Table[
StringSplit[""<>Flatten@#]&/@Transpose@ArrayReshape[c,{Round[Length@c/(4 m)],4,m},""],{m,{1,2,4,6,8}}],1],!MemberQ[j/@#,{}]&]]
```
**Test Cases**
```
f["boasonespetrabbittonespongomezesray long"]
f["Hepoge slljghadso bvvbgh"]
f["lsbvmii derfghthstthasinlomnrtk fg dndthugssawerpoloasefnxafqeormnaqwge padhndi mbavwgam"]
```
>
> {"astronomy"}
>
> {"Hello"}
>
> {"i", "think", "therefore", "i", "am"}
>
>
>
] |
[Question]
[
**Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/36166/edit).
Closed 9 years ago.
[Improve this question](/posts/36166/edit)
# Introduction
Greetings fellow traders, you have just entered the Stack Exchange stock exchange. Here you will compete to earn the money by buying and selling shares (unfortunately, we only have the single market).
# Gameplay
You will need to write a program that buys and sells shares. At the start, the market price is 200, you have $10000 and no shares. Each time you buy or sell a share, the market price goes up or down.
There will be ten games played, each game with fifty rounds. At the end, the person with the highest amount of money wins.
***The first game will start with at least ten entrants***
# Information
Your program will be supplied with three arguments:
```
Your bank balance
Number of shares
Market value
Round number
```
And you can supply one of three commands:
```
Name | Command
Buy: | b [no. shares]
Sell: | s [no. shares]
Pass: | p
```
For example, if you were to run the program straight:
```
python testprog.py 10000 0 200 1
b 100
```
I would suggest recording change to see if people are buying or selling shares to prevent a crash.
If you try to spend money you don't have or sell stocks that you don't have, your request will be rejected.
You are allowed to have ONE text file for recording change in stock price.
The program will be run on Ubuntu Linux.
## Controller program:
```
# Orchestration Program
from subprocess import Popen, PIPE
import time
class Program:
money=None
stocks=None
command=None
# Define class instances here
programvars = {}
# Program names here
programs = []
leaderboard = {"1": 0,
"2": 0,
"3": 0,
"4": 0,
"5": 0,
"6": 0,
"7": 0,
"8": 0,
"9": 0,
"10": 0}
scores = []
# Programs start in a different order each time
programs = sorted(programs, key=lambda k: random.random())
f = open("stockprice.txt", "r")
f = f.split('|')
stockprice = int(f[0])
roundnum = int(f[1])
f.close()
programsfifty = programs*50
# Initialising variables
for i in programsfifty:
#try:
g = open(i + "properties.txt", "r")
print(i)
properties = g.read()
properties = properties.split("|")
programvars[i].money = int(properties[0])
programvars[i].stocks = int(properties[1])
programvars[i].command = str(properties[2])
g.close()
#except:
# pass
# Main event loop
for j in programs:
if stockprice < 0:
stockprice = 0
# Example: python3 test.py [money] [stocks] [price]
command = programvars[j].command + ' ' + str(programvars[j].money) + ' ' + str(programvars[j].stocks) + ' ' + str(stockprice) + ' ' + str(roundnum)
out = Popen(command, shell=True, stdout=PIPE).communicate()[0].decode('utf-8')
out = out.replace('\n', '')
# If run on Windows
out = out.replace('\r', '')
if out == 'p':
pass
else:
action = out.split(' ')
if action[0] == 'b':
# Buying shares
if programvars[j].money - int(action[1])*stockprice > -1:
programvars[j].money -= int(action[1])*stockprice
programvars[j].stocks += int(action[1])
stockprice += int(action[1])
elif action[0] == 's':
if programvars[j].stocks - int(action[1]) > -1:
# Selling shares
programvars[j].money += int(action[1])*stockprice
programvars[j].stocks -= int(action[1])
stockprice -= int(action[1])
for k in programs:
# Writing properties to files
n = open(k + "properties.txt", "w")
n.write(str(programvars[k].money)+"|"+str(programvars[k].stocks)+"|"+str(programvars[k].command))
n.flush()
n.close
# Add all scores to an array for sorting
scores.append(programvars[k].money)
scores = sorted(scores, reverse=True)
print(scores)
# Find richest program
for l in programs:
for m in range(0, len(scores)):
if programs.index(l) == m:
leaderboard[programs[m]] = leaderboard.pop(str(m+1))
scorekeys = sorted(leaderboard.keys(), reverse=True)
print(scorekeys)
# Write the leaderboard
s = open("leaderboard"+str(time.localtime()[0])+"-"+str(time.localtime()[1])+"-"+str(time.localtime()[2])+".txt", "w+")
# Some problems with this, but can be worked out manually
for n in scores:
s.write(str(scores.index(n)+1) + ": " + scorekeys[scores.index(n)] + " " + str(n) + "\n")
s.flush()
s.close()
roundnum += 1
# Write the stockprice
b = open("stockprice.txt", "w")
b.write(str(stockprice) + '|' + str(roundnum))
b.flush()
b.close()
```
**Good luck!**
[Answer]
# Short-Sighted Seller - Perl
This bot has the simple strategy of maximizing its score at the end of every trading opportunity. It acts as if every round were the last round.
```
($money,$stocks,$price) = @ARGV;
$value = $money + $stocks * $price;
if($price > 0){
$optimal = $value / (2 * $price);
}
else{
$optimal = 9x15 + $stocks; #suitably large number
}
$rounded = int($optimal + 0.5);
$delta = $rounded - $stocks;
if($delta > 0){
print "b $delta";
}
elsif($delta < 0){
$delta *= -1;
print "s $delta";
}
elsif($delta == 0){
print "p";
}
```
You can run it like so:
```
perl shortsightedseller.plx [money] [stocks] [price]
```
] |
[Question]
[
Few years ago, an esoteric programming language named [아희(Aheui)](http://esolangs.org/wiki/Aheui) was created. Well, actually you don't need to know about this language or Korean characters.
Aheui uses stacks and a queue, but this time we use **one stack** and ignore other stacks and queue. You can **push a number** between 2 and 9 into a stack. You can do **arithmetic operations** by popping two numbers and pushing result. And you can **duplicate** a top number.
So, when I need a big number in Aheui, making a number was not an easy work. Push, push, multiply, duplicate, push, multiply, push, add…. It takes too much time and sometimes waste of bytes. I need a shortest expressions.
## Summary
Your task is to write a function or a program which takes a number `n (0 <= n <= 1000000)` and returns concatenation of tokens.
Tokens are basically a [postfix notation](http://en.wikipedia.org/wiki/Reverse_Polish_notation). Tokens are consisted of
* Number between 2 and 9, which means "push number into stack"
* `+`, `-`, `/`, `*`, which means "pop two numbers from stack, do arithmetic operation, push the result into stack". All calculations are in integer.
* `>`, which means "duplicate a top number"
Tokens will be concatenated with empty string, so `5 5 +` will be `55+`.
After calculations, `n` must be on the top of the stack.
### Sample input and output
```
INPUT = 0
OUTPUT = 22-
(or 33-, 44-, whatever)
INPUT = 1
OUTPUT = 22/
(or 32-, 33/, whatever)
INPUT = 5
OUTPUT = 5
(We don't need calculations, just push)
INPUT = 64
OUTPUT = 88*
(or 8>*)
INPUT = 1337
OUTPUT = 75*2+>*48*-
(This may not be a shortest solution)
```
## Scoring
[This is a list of test cases](http://pastebin.com/ASmgRY1t). Test cases are seperated by a new line character. You may write a test script which converts those bunch of numbers to string of tokens, or you can do it by your hand.
Let
* `S` = size of complete function or program
* `O` = length of converted strings
* `I` = size of test cases (In this case, `I = 526`)
Then your score will be `S * (O / I)`. Sizes are in bytes.
`S` includes function declarations, `#include`s, `import`s, whatever. Test script is not counted.
## Scoring example
Let `S` is `150`.
### Sample Test cases
```
0
1
5
64
1337
```
### Sample Output
```
22-22/588*75*2+>*48*-
```
In this case, `I = 9`, and `O = 21`. So your score is `150 * (21 / 9) = 350`.
## Rules
* [Standard "loopholes"](https://codegolf.meta.stackexchange.com/q/1061/9275) are forbidden.
* Lowest score wins.
* If there is a tie, smaller code size wins.
* Winner will be selected after three weeks (2014-08-04).
---
I wrote a [validator in Node.js](https://gist.github.com/Snack-X/61cb01e800b0b4ff475e). Put `input.txt` and `output.txt` in same directory, and run `node validator.js`.
And I found [two-year-old similar question](https://codegolf.stackexchange.com/questions/5271/generate-number-in-reverse-polish-notation). But scoring is different (this question includes code size in score), and this question can't use 1. So I hope it's not a duplicate.
[Answer]
# Javascript, Score = 1663.46768
```
function X($){S=Math.sqrt;function J(A){return A.join("")}function M(A,B){return A.length<B.length?A:B}function D(q){var w="",e,r,t,y;for(e=9;e>1;e--){r=~~(q/e);t=r*e-q;if(t==0)y=J([G(r),e,"*"]);else y=J([G(r),e,"*",G(-t),"+"]);if(w=="")w=y;w=M(w,y)}return w}function Q(a){var s=~~S(a),d=a-s*s,f=J([G(s),">*",G(d),"+"]),g;s=Math.ceil(S(a));d=s*s-a;g=J([G(s),">*",G(d),"-"]);return M(f,g)}function G(z){var x,c,v,b,n,m;if(z==0)return"22-";if(z==1)return"22/";if(z>1&&z<10)return""+z;if(z>9&&z<19){x=~~(z/2);c=z-x;return J([x,c,"+"])}for(v=9;v>1;v--){b=~~(z/v);if(b>1&&b<10&&b*v==z)return J([v,b,"*"])}n=S(z);if(~~n==n)return J([G(n),">*"]);return M(D(z),Q(z))}return G($)}
```
This is my attempt for my question, and [this is output](http://pastebin.com/UJ5r7VZs). Code size is 671, and output size is 1304. Score is 1663.46768 (rounded up to 5 decimal places).
] |
[Question]
[
You dudes, the [Most Excellent Adventure](http://1d4chan.org/wiki/Most_Excellent_Adventure) is a home brew roleplaying game system based on the Bill & Ted Films, *plays gnarly air guitar riff*.
In this game system, when you draw from your dice pool (you have between 1 and 12 ten-sided dice, with faces labelled 0-9) you need to connect the results as a phone number on your phone pad:

Here one person has rolled 4, 2, 8, 3, 8, and 2, dialling 3-2-2-4-8-8. The other 7, 4, 6, 3, 9, and 4, only dialling 4-4-7 or 3-6-9. And the longest number wins.
Bill and Ted want to play this game on their telephone kiosk, but haven't the first clue about programming. As Station isn't around, they want you to program it. The kiosk had access to all programming languages and OSs past and future (causality forbids you using any future technology... No imaginary python 7 !)
Your input is two numbers between 1 and 12, representing the number of dice player 1 and player 2 have respectively. The output is the result for each player, and the length of the largest number they could dial.
Input: `8 10`
Output:
```
Player 1 rolled 1 2 3 4 5 6 7 8 with longest dialable number of 8.
Player 2 rolled 8 8 8 2 3 1 4 0 3 3 with longest dialable number of 10.
```
Numbers can be reordered and pressing the same key twice counts as two digits (which is why the above sequence `8 8 8 2 3 1 4 10 3 3` makes a six digit number not a 4 digit number)
Also, as you're programming this in a telephone kiosk you can only access 0-9, a-z, the `*` and a `#` keys in your code. Letters are accessed by repeated typing, much like on a mobile phone. *Every other key must be input in the kiosk as its ASCII code in hex like so: `#0a` **the upshot is when scoring your submission, these keys "cost" three times as many***.[Unclear / Incorrect?]
For instance to type `~` you press the hash key once, the `7` and then `3` three times to cycle through the digits `3de`. This gives the code `#7e` which corresponds to `~`. When you upload you code here you can just type the `~`, and count it as five characters.
The keypad looks a little like this: 
For instance If your code had `print()` that would cost 15 for the `print` (`7p 7pqr 4ghi 6mn 8t`) plus 6 for the `()` (`#28 #29`).
This is code golf as Bill and Ted will get bored otherwise. Let the coding commence *plays gnarly air guitar riff*.
[Answer]
# VBScript - 1668 telephone keypresses (was 1708)
My entry is golfed a bit more - I realized (doh!) that the variable names should be characters that require less telephone keypresses (a,d,g,j,etc).
This program produces the output exactly as shown and takes the input as command line parameters. If line endings are 1 byte there is no advantage to using `:` to put it all on one line (#0a vs #3a). Run it with `cscript script.vbs 8 10` replacing 8 and 10 with whatever values you want - it tries every combination in order to get the maximum string so it is SLOW.
I just have one question: if you needed a two numbers beside each other that were both on the same key isn't it a bit ambiguous. Wouldn't the text a=e (22#333333) be the same keypresses as a>d (22#333333)? How do you differentiate where the character boundaries are? I didn't specifically check for every possible occurance of where things on the same key are beside themselves and I don't know what I would have done if I did notice it...
```
sub b(d,m)
p=true
a=len(m)
for g=1to a-1
p=p and instr(split("7890*1245*123456*2356*124578*123456789*235689*45780*4567890*56890","*")(mid(m,g,1)),mid(m,g+1,1))>0
next
if p and t<a then t=a
if d=""then exit sub
a=len(d)
for g=1to a
w=""
if g>1then w=left(d,g-1)
p=""
if g<a then p=mid(d,g+1)
b w+p,m+mid(d,g,1)
next
end sub
randomize
set m=wscript.arguments
for e=1to 2
d=""
j="Player "+cstr(e)+" rolled"
for t=1to mid(10000+m.item(0)*100+m.item(1),e*2,2)
w=cstr(int(rnd()*10))
j=j+" "+w
d=d+w
next
j=j+" with longest dialable number of"
t=0
b d,""
wscript.echo j+" "+cstr(t)
next
```
Ok, I am finally ready to score my entry - that of course means no more changes to it because of how long it takes to transform it to a score. The transformed phone input is:
```
77777888222#20222#2833#2222266#29#02277#333887777888333#02222#3335555333666#2866#29#02233336666777
7#2044#3331886666#2022#2331#02277#33377#202266633#20444466677777887777#2877777775555444488#28#2278
90*1245*123456*2356*124578*123456789*235689*45780*4567890*56890#22#22222#22*#22#29#2866444433#2866
#2222244#222221#29#29#2222266444433#2866#2222244#22221#222221#29#29#33330#02266633399988#022444433
33#2077#202266633#2088#3222222#2088444333666#2088#33322#02244443333#2033#333#22#2288444333666#2033
3999444488#2077777888222#02222#3335555333666#2833#29#022333366667777#2044#3331886666#2022#02299#33
3#22#22#02244443333#2044#3333188444333666#2099#3335555333333388#2833#2222244#2331#29#02277#333#22#
22#02244443333#2044#3222222#2088444333666#2077#33366444433#2833#2222244#22221#29#022222#2099#22227
7#2222266#222266444433#2833#2222244#222221#29#02266633399988#02233366633#2077777888222#02277772266
633666666444499999333#0227777733388#2066#33399777772222777744447788#233322777744888663336668877777
#022333366667777#20333#3331886666#202#02233#333#22#22#02255#333#22#5055552299993337777#20#22#22222
22277777887777#28333#29#2222#22#20777766665555555533333#22#022333366667777#2088#3331886666#2066444
433#2810000#222266#233344448833366#280#29*100#222266#233344448833366#281#29#22222333*2#222222#29#0
2299#333222277777887777#28444466688#28777766633#28#29*10#29#29#02255#33355#2222#22#20#22#222299#02
233#33333#222299#02266633399988#02255#33355#2222#22#2099444488444#2055556666666443337777788#203344
44225555222225555333#20666888662223337777#2066663333#22#02288#3330#022222#2033#22222#22#22#0229977
7772222777744447788#233333322224446666#2055#2222#22#20#22#2222222277777887777#2888#29#022666333999
88
```
] |
[Question]
[
Permutations of a set have a natural order called lexicographic order in which two permutations are compared by comparing the first position at which they differ. For the purposes of this question we're working with base 64 and the order of the digits is
```
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/
```
Note that this is not the same order as their ASCII values.
This ordering can be extended naturally to handle subpermutations of a given length.
### Task
Write a program, function or named verb which takes as input (via stdin in the case of a program or as an argument otherwise) a 12-character subpermutation of the base-64 alphabet given above, and which produces (respectively to stdout or as the return value) the lexicographically next 12-character subpermutation. If working with typed input you may use strings or character arrays holding the ASCII values of the digits listed above.
Your solution should be relatively efficient; and in particular, it is **forbidden** to loop through base-64 numbers testing them until you find one which doesn't repeat any digits.
It is only required that your program handle 12-character subpermutations, but you do not need to verify that the input is 12 characters in length; if it handles other lengths too you may wish to mention that in your answer.
If the input is the lexicographically greatest subpermutation, the output should wrap round to the lexicographically smallest subpermutation.
### Test cases
```
Input Output
ABCDEFGHIJKL ABCDEFGHIJKM
ABCDEFGHIJK+ ABCDEFGHIJK/
ABCDEFGHIJK/ ABCDEFGHIJLK
ABCDEFGHIJLK ABCDEFGHIJLM
ABCD/9876542 ABCD/9876543
ABCD/9876543 ABCD/987654+
ABCD/987654+ ABCD/98765+E
ABCD/98765+E ABCD/98765+F
ABCDEF+/9875 ABCDEF+/9876
ABCDEF+/9876 ABCDEF/GHIJK
ABCDEF/GHIJK ABCDEF/GHIJL
ABCDEF/GHIJL ABCDEF/GHIJM
ABCDEFG+/987 ABCDEFG/HIJK
A+/987654321 A/BCDEFGHIJK
/+9876543210 ABCDEFGHIJKL
```
[Answer]
### GolfScript, 115 characters
```
:I,,0\{26,{65+.32+}%$10,{`}%'+/'++:A,1$-@*\)I<)A@-?+}/1I,,{A,\-*}/\)1$%\I,,{A,\-/\.2$%\2$/@\}%*>A\{1$=\[1$]-\}%\0<+
```
It passes all the test cases and works also for subpermutations of size other than 12 and for full permutations as well.
[Online tester](http://golfscript.apphb.com/?c=ezpJLCwwXHsyNix7NjUrLjMyK30lJDEwLHtgfSUnKy8nKys6QSwxJC1AKlwpSTwpQUAtPyt9LzFJLCx7QSxcLSp9L1wpMSQlXEksLHtBLFwtL1wuMiQlXDIkL0BcfSUqPkFcezEkPVxbMSRdLVx9JVwwPCt9OlJVTjsKCgonQUJDREVGKy85ODc2JyBSVU4%3D)
*Annotated Code:*
```
:I # save input to variable I
### get the numerical index of the (sub)permutation
,,0\ # push 0 (accumulator) and [0 .. <Length I>-1]
{ # loop over
### construct the alphabet A
26,{65+.32+}%$ # A-Z and a-z
10,{`}% # 0-9
'+/'++ # append '+/'
:A # save to variable A
,1$- # length of alphabet (i.e. 64) minus loop variable
# i.e. 64 -> 63 -> 62 -> 61 -> ...
# (this is the number of possible characters at
# the current position)
@* # multiply the accumulator by this value
\)I< # get anything from the input up to the current character
) # extract the current character of input
A@- # remove anything from the alphabet which was in the rest,
# i.e. the already processed chars cannot be used any more
? # find the index of the current input character
+ # add to the accumulator
}/
### calculate the total number of (sub)permutations
1 # push 1 (accumulator)
I,,{ # loop for i = 0 .. <Length I>-1
A,\- # length of alphabet minus loop variable
* # multiply to accumulator
}/
### at this point the stack is <Index of input (sub)permutation>
### <Total number of (sub)permutations>
\) # increment the index (i.e. next (sub)permutation)
1$% # warp around for the last possible (sub)permutation
\ # swap back order
### backwards transformation into the (sub)permutation space
I,,{ # map for each index [0 .. <Length I>-1]
A,\-/ # divide the weight factor by length of alphabet minus
# loop variable
\.2$% # take index % new weight factor
\2$/ # and index / new weight factor (result for the map operation)
@\ # re-order stack
}%
*> # get rid of 0 1 on the stack
### back to the alphabet
A\ # push the full alphabet under the index array
{ # map on the index array
1$= # take the i-th element of the alphabet
\[1$]-\ # and reduce the alphabet by this characters
}%
\0< # transforms the remaining alphabet into an empty string
+ # make string from array by joining with the empty string
```
[Answer]
### GolfScript, 77 70 characters
Another more direct approach in GolfScript which happens to work in the general case also.
```
:I{)26,{65+.32+}%$10,{`}%'+/'++:^2$-:S\?).S,<{S[=]+0}*1$!!*}do^1$-+I,<
```
Also this solution can be tested [online](http://golfscript.apphb.com/?c=ezpJeykyNix7NjUrLjMyK30lJDEwLHtgfSUnKy8nKys6XjIkLTpTXD8pLlMsPHtTWz1dKzB9KjEkISEqfWRvXjEkLStJLDx9OlJVTjsKCidBQkNERUYrLzk4NzYnIFJVTg%3D%3D&run=true).
[Answer]
# Ruby: Whittled down to 658 Characters
```
class B;def initialize(g)@l=12;@b=(("A".."Z").to_a+("a".."z").to_a+("0".."9").to_a+["+","/"]
).each_with_index.map{|x,i|{x=>i}}.inject(:update);@g=g;@[[email protected]](/cdn-cgi/l/email-protection);@[[email protected]](/cdn-cgi/l/email-protection){|i|
@i[@b.length-i-1]}.join;end;def n;c(@g)?@g:r;end;def c(s);@b[s[-1]][[email protected]](/cdn-cgi/l/email-protection)?(return false
):s==@m?r: f(s,s[-1]) ?s[-1]=f(s,s[-1]):f(s,s[-2])?r: (s[-1]=f(s);f(s,s[-2])?s[-2]=f(s,s[-2]):r)
true;end;def h(s)v=s.split("").map{|x|@b[x]};v.index(v.compact.max)end;def r;@g==@m?@[[email protected]](/cdn-cgi/l/email-protection){
|j| @i[j]}.join: (v=@g[0..h(@g)-1];c(v);u=@g[h(@g)..-1].length;u.times{v+=f(v)};@g=v);end
def f(s,a=@i[0])(@b[a][[email protected]](/cdn-cgi/l/email-protection)).each{|p|unless !!s[@i[p]];return @i[p]end};false;end;end
```
Running test cases:
```
puts " IN ******* OUT"
["ABCDEFGHIJKL","ABCDEFGHIJK+","ABCDEFGHIJK/","ABCDEFGHIJLK","ABCD/9876542",
"ABCD/9876543","ABCD/987654+","ABCD/98765+E","ABCDEF+/9875","ABCDEF+/9876",
"ABCDEF/GHIJK","ABCDEF/GHIJL","ABCDEFG+/987","A+/987654321","/+9876543210"
].each do |v|
t = B.new(v.dup)
puts " #{v} #{t.n}"
end
```
Outputs:
```
IN ******* OUT
ABCDEFGHIJKL ABCDEFGHIJKM
ABCDEFGHIJK+ ABCDEFGHIJK/
ABCDEFGHIJK/ ABCDEFGHIJLK
ABCDEFGHIJLK ABCDEFGHIJLM
ABCD/9876542 ABCD/9876543
ABCD/9876543 ABCD/987654+
ABCD/987654+ ABCD/98765+E
ABCD/98765+E ABCD/98765+F
ABCDEF+/9875 ABCDEF+/9876
ABCDEF+/9876 ABCDEF/GHIJK
ABCDEF/GHIJK ABCDEF/GHIJL
ABCDEF/GHIJL ABCDEF/GHIJM
ABCDEFG+/987 ABCDEFG/HIJK
A+/987654321 A/BCDEFGHIJK
/+9876543210 ABCDEFGHIJKL
```
For the long understandable version of this code see my github post <https://github.com/danielpclark/b64challenge>
This code was tested with Ruby version 1.9.3. I can only vouch for is version.
] |
[Question]
[
**Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/23476/edit).
Closed last year.
[Improve this question](/posts/23476/edit)
Yesterday at work, the Google Doodle convinced me to share my rather long gender swap script here, but the code-golf criteria of [the question i asked](https://codegolf.stackexchange.com/questions/23348/swap-genders-in-any-english-text/23349) were not clear. As my question still got downvoted after giving examples, i changed the tag to popularity-contest, as suggested before i clarified it.
Here's a more golfy version:
The UN theme for [International Women's Day](http://en.wikipedia.org/w/index.php?title=International_Women%27s_Day&oldid=598677309) 2014 is "Equality for Women is Progress for All".
In the interest of gender equality, write a program that correctly changes that Wikipedia page from a female to a male perspective. Names and anatomical details may be left unchanged. It should not change who is being referred to.
Example:
Before:
>
> He said she took her girlish books on Feminism with her.
>
>
>
After:
>
> She said he took his boyish books on Masculism with him.
>
>
>
All gendered pronouns and nouns, as well as all adjectival forms of such words, must be changed in the visible English text.
The shortest code that fully transforms the linked version of the IWD Wikipedia page according to the stated rules, wins.
[Answer]
**JavaScript, 707 bytes (680 in web console)**
```
javascript:(function(){l=function(s){return s.toLowerCase()};b=document.body;t=b.innerHTML;s="Actress;Actor;Daughters;Sons;Feminine;Masculine;Feminism;Masculism;Feminist;Masculist;Femininity;Masculinity;Mother;Father;Mothers;Fathers;Motherland;Fatherland;Motherhood;Fatherhood;Woman;Man;Female;Male;Females;Males;Girl;Boy;Girls;Boys;Girlfriends;Boyfriends;Grandmothers;Grandfathers;Her;His;She;He;Sister;Brother;Wives;Husbands;WomenWatch;MenWatch;Women;Men;Womensday;Mensday;Internationalwomensday;Internationalmensday;IWD;IMD";a=s.split(';');c=t.split(/\b/);d={};for(i=0;i<a.length;i+=2){x=a[i];y=a[i+1];d[x]=y;d[y]=x;d[l(x)]=l(y);d[l(y)]=l(x)}t='';for(i=0;i<c.length;++i)t+=d[c[i]]||c[i];b.innerHTML=t})()
```
This is a bookmarklet/favelet; set as URL of a bookmark/favorite and click to transform the loaded webpage.
[Answer]
Not a completely worked out answer, but Cees' substitution solution reminded me of the str\_replace syntax in PHP:
```
$body = file_get_contents($url);
$body = str_replace(
array("Actress", "Daughters", "Feminine", "Feminism", "Feminist", "Femininity", "Mother", "Mothers", "Motherland", "Motherhood", "Woman", "Female", "Females", "Girl", "Girls", "Girlfriends", "Grandmothers", "Her", "She", "Sister", "Wives", "WomenWatch", "Women", "Womensday", "Internationalwomensday", "IWD"),
array("Actor", "Sons", "Masculine", "Masculism", "Masculist", "Masculinity", "Father", "Fathers", "Fatherland", "Fatherhood", "Man", "Male", "Males", "Boy", "Boys", "Boyfriends", "Grandfathers", "His", "He", "Brother", "Husbands", "MenWatch", "Men", "Mensday", "Internationalmensday", "IMD"),
$body);
```
You can shorten this by putting everything into one string, e.g.
```
str_replace(
split(';', "Actor;Sons;Masculine;Masculism;Masculist;Masculinity;Father;Fathers;Fatherland;Fatherhood;Man;Male;Males;Boy;Boys;Boyfriends;Grandfathers;His;He;Brother;Husbands;MenWatch;Men;Mensday;Internationalmensday;IMD"),
....
```
but that only makes it marginally better. I'll leave it up to someone to come up with the creative solution.
] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
This question does not appear to be about code golf or coding challenges within the scope defined in the [help center](https://codegolf.stackexchange.com/help/on-topic).
Closed 6 years ago.
[Improve this question](/posts/18461/edit)
```
bool doYouFeelLuckyPunk, actuallyIsLucky;
doYouFeelLuckyPunk = Harry.catchyPhrase();
actuallyIsLucky = Bandit.rollDice();
if(doYouFeelLuckyPunk) {
Bandit.grabGun();
if(!actuallyIsLucky)
Harry.useMagnum()
else {
Harry.tisButAScratch()
}
else
Bandit.surrender();
```
We all know how this plays out and we like it that way.
The task:
Write functions
>
> bool Harry.catchyPhrase()
>
>
> bool Bandit.rollDice()
>
>
>
Design them so the situation ends either in Harry.uswMagnum() or Bandit.surrender(), at random.
Challenge and key criterion: Obfuscate the fact that bandit cannot win, fake and manipulate the "randomness" in your functions. The less obvious the better of course.
Explain your manipulation in a non-spoilering way (white text etc.)
Language: Doesn't matter
Forbidden moves: none
[Answer]
How about this? Solution at the very bottom, encoded in base64. Language is C.
```
#include <stdio.h>
int lfsr = 0xACE1u;
/*Toy LFSR implementation stolen from wikipedia.*/
int random_bit(){
/* taps: 16 14 13 11; feedback polynomial: x^16 + x^14 + x^13 + x^11 + 1 */
int bit = ((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 5) )&1 ;
lfsr = (lfsr >> 1) | (bit << 15);
return ((lfsr >> 14)&(lfsr >> 15))^bit;
}
int surrendered=0,scratched=0,shot =0;
void harry_tis_but_a_scratch(){scratched++;}
int harry_catchy_phrase(){return random_bit();}
void bandit_surrender(){surrendered++;}
void harry_use_magnum(){shot++;}
int bandit_roll_dice() {return random_bit();}
void bandit_grab_gun() {}
int main()
{
int random_number=0;
/*Test bench random bit*/
for(int y=1;y<51;++y){
for(int x=0;x<8*sizeof(int);++x)random_number= (random_number<<1)|random_bit();
printf("%-15d%c",random_number,y%5?' ':'\n');
}
printf("\nLooks pretty random\n\n");
/*Play the game*/
for(int x=0;100000 >=++ x;){
int doYouFeelLuckyPunk = harry_catchy_phrase();
int actuallyIsLucky = bandit_roll_dice();
if(doYouFeelLuckyPunk) {
bandit_grab_gun();
if(!actuallyIsLucky) harry_use_magnum();
else harry_tis_but_a_scratch();
}else bandit_surrender();
}
printf("Shot: %d Surrendered: %d Scratched: %d\n",shot,surrendered,scratched);
return 0;
}
/*
Example Output
1414529544, -2071427967, 89395234, 690094340, 704663586,
41977888, -1572861663, 1107591810, 143171844, 546578948,
-1542942712, -1600056768, -1571682240, 84415044, -2138746864,
705971264, 302123561, 168036485, 553717833, 545294674,
71909648, -1994096044, 1426227848, 1218611781, 138707496,
16810505, 553783616, -1861155808, -1803283192, 1111626024,
Looks pretty random
Shot: 24941 Surrendered: 75059 Scratched: 0
SOLUTION
IFRoZSB3YXkgdGhpcyB3b3JrcyBpcyBxdWl0ZSBzaW1wbGUsIHRoZSBMRlNSIGlzIHJlYWwgYW5k
IGRvZXMgaW4gZmFjdCBnZW5lcmF0ZQ0KIGdvb2QgcHNldWRvLXJhbmRvbSBudW1iZXJzLkFuZCBp
dCBpcyBpbmZhY3QgYW4gZXhhY3QgaW1wbGVtZW50YXRpb24gb2YgdGhlIG9uZQ0KIGZyb20gd2lr
aXBlZGlhLCBleGNlcHQgZm9yIG9uZSBhZGRpdGlvbjoNCiANCiBUaGUgb3V0cHV0IGJpdCBpcyB4
b3InZCB3aXRoICgobGZzcj4+MTQpJihsZnNyPj4xNSkpDQogDQogTm9ybWFsbHkgdGhpcyBzaG91
bGRuJ3QgYmUgYSBwcm9ibGVtLCBhcyB0aGUgcmVzdWx0IG9mIGEgcmFuZG9tIGJpdCB4b3InZCB3
aXRoDQogYW55IGZ1bmN0aW9uIGJlc2lkZXMgaXRzZWxmIGlzIHNlbGYgaXMgc3RpbGwgYSByYW5k
b20gYml0Lg0KIA0KIEhvd2V2ZXIsICgobGZzcj4+MTQpJihsZnNyPj4xNSkpIGlzIG5vdCBhIG5v
cm1hbCBmdW5jdGlvbi4gRHVlIHRvIHRoZSBMRlNSIGFsc28NCiBiZWluZyBhIHNoaWZ0IHJlZ2lz
dGVyIHRoZSBvdXRwdXQgb2YgdGhlIHJhbmRvbSBiaXQgZnVuY3Rpb24gaXMgYWN0dWFsbHkgdGhp
czoNCiANCiByZXR1cm4gKGxhc3RfYml0JmJpdCleYml0Ow0KIA0KIFNvLCBpZiB0aGUgbGFzdCBi
aXQgd2FzIGEgMSB0aGUgYml0IHJldHVybmVkIGlzIGd1YXJhbnRlZWQgdG8gYmUgMC4NCiANCiBT
byBpdCBpcyBpbXBvc3NpYmxlIHRvIGdldCB0byB0aGUgJ3RpcyBidXQgYSBzY3JhdGNoJyBmdW5j
dGlvbiwgYXMNCiBpdCBpcyBpbXBvc3NpYmxlIGZvciBib3RoIGRvWW91RmVlbEx1Y2t5UHVuayBh
bmQgYWN0dWFsbHlJc0x1Y2t5IHRvIGJlIHRydWUu
*/
```
] |
[Question]
[
**This question already has answers here**:
[Generate Pascal's triangle](/questions/3815/generate-pascals-triangle)
(68 answers)
Closed 10 years ago.
the contest is already finished, so I don't think it's cheating to ask:
I am trying to optimize this small contest: [pascal triangle](https://www.hackerrank.com/challenges/pascal)
I started with 4.72 and worked myself up to 7.48.
The best made a 9.05 but in perl, python2 best score is 8.25.
Unfortunately they don't let you look at what others did.
My current solution is the following:
```
l=[1]
print 1
while(len(l)<31):
print' '.join(map(str,l+[1]))
l=[1]+map(lambda x,y:x+y,l,l[1:]+[1])
```
Now I tried to get rid of the loop in using list comprehension, but I am too new to python to get this done. Can anyone give me a hint for nested list comprehension shortening this code further down?
Thank you for your audience.
[Answer]
This is a bit shorter, but still no good:
```
l=[1]
while(len(l)<32):
print' '.join(map(str,l))
l=[1]+map(int.__add__,l,l[1:]+[0])
```
And this one comes in at a score of 8.28 (credit to @primo):
```
l=[1];exec"print' '.join(map(str,l));l=map(sum,zip([0]+l,l+[0]));"*31
```
] |
[Question]
[
**Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/6256/edit).
Closed 7 years ago.
[Improve this question](/posts/6256/edit)
Your task is to golf a program that prints which character encoding, if any, the data read from the input represents. It should be able to detect the following encodings:
* ASCII
* [ISO 8859-1](http://en.wikipedia.org/wiki/ISO/IEC_8859-1)
* [UTF-8](http://en.wikipedia.org/wiki/UTF-8)
* [UTF-16](http://en.wikipedia.org/wiki/UTF-16)
One of the above names of character encodings should be printed (in the same way) if it can be determined which is used. If the input is not ASCII, but it's ambiguous which of the other encodings is used, a `?` should be printed. If none of the encodings can be valid, `X` must be printed.
Furthermore, the following should be taken into account:
* **If the input is valid ASCII, ASCII should be printed**. Even though this means the other encodings are also valid. When the input is not ASCII, `?` should printed in case of any ambiguity.
* The UTF's are not required to start with a BOM.
* UTF-16 can be either big or little endian. This means there are actually five different encodings to detect.
* If UTF-8 or UTF-16 data encodes a number between 0 and 0x10FFFF you may consider it valid, even if it represents a Unicode code point that is technically not allowed in this encoding. Therefore **you do not have to worry about unassigned code points and such.**
* ISO 8859-1 is considered invalid when any of its undefined bytes (positions 0-31 and 127-159, except 9, 10 and 13) are used.
* This is code golf.
Happy golfing!
[Answer]
## Tcl, 247
```
set i [read [open f rb]];foreach n\ d {ascii ASCII utf-8 UTF-8 unicode UTF-16 iso8859-1 ISO\ 8859-1} {if {[encoding convertt $n [encoding convertf $n $i]]eq$i&&($n!="iso8895-1"||[regexp {[\1-\10\13\14\16-\37\177-\237]} $i])} {puts $d;exit}};puts X
```
Reads the input from the file `f` in the current directory.
It works by decoding and re-encoding the input into the different charsets and check if the input and the re-encoded input is equal.
I believe that valid UTF-8 is also valid (but useless) ISO 8859-1, so I print UTF-8 then.
[Answer]
## Scala, 505 bytes (w/o using built-in encoders)
```
def e(s:Array[Byte])=if(s.forall(_>0))"ASCII"else{var a=true;var b=true;var p=0;var q=false;var v=0;var t=false;for(c<-s){if(a){if(c== -64||c== -63||c> -12)a=false else{if(p==0)p=if(c>0)0 else if(c< -32)1 else if(c< -16)2 else 3 else a=c<= -64}};if(b){val x=(c+256)%256;if(q){v=v*256+x;if(v>55295&&v<56320)t= !t;b=t;if(v>56319&&v<57344)t= !t}else v=x}};b=b&& !t;val c=s.forall{x=>x==9||x==10||x==13||x>=32&&(x> -97)};if(a&&b||b&&c||a&&c)"?"else if(a)"UTF-8"else if(b)"UTF-16"else if(c)"ISO 8859-1"else"X"}
```
Unfortunately doesn't detect overlong encodings in UTF-8.
] |
[Question]
[
Check printer function (or subroutine) - Convert to English text from the input value. 12.34 -> "twelve dollars and thirty four cents". For the range .01 to 9999.99 assuming valid input.
[Answer]
# Common Lisp, 95
Newline not counted in:
```
(lambda(n &aux(d(floor n))(c(round(*(- n d)100))))
(format()"~R dollar~P and ~R cent~P"d d c c))
```
Sample use (assigning it to f):
```
CL-USER> (f .01)
"zero dollars and one cent"
CL-USER> (f 12.34)
"twelve dollars and thirty-four cents"
CL-USER> (f 9999.99)
"nine thousand nine hundred ninety-nine dollars and ninety-nine cents"
```
] |
[Question]
[
Write the shortest program to build a [cdb](http://cr.yp.to/cdb.html) database, using the following [syntax](http://cr.yp.to/cdb/cdbmake.html) for input:
```
+*klen*,*dlen*:*key*->*data*
```
followed by a newline. Example:
```
+3,5:one->Hello
+3,7:two->Goodbye
```
(Unlike the real [cdbmake](http://cr.yp.to/cdb/cdbmake.html), your program doesn't need to catch the empty-line-as-end-of-input case if you don't want to.) **Your program needs to handle arbitrary strings (including NUL, newline, `+`, `,`, `:`, and/or `->`) in both the key and data correctly;** therefore, using any kind of line-based input is likely to be wrong. You may assume the input is always valid, and you can assume that there is at most one instance of any key in the input.
**The hash tables your program generates must behave like real hash tables.** In other words, the hash tables should provide amortised constant-time lookups.
If your language provides built-in hash tables, you're allowed to use them, if they help any. However, **do not use any cdb libraries or cdb programs to solve this question.**
If your program writes the cdb to standard output, you may assume that it's redirected to a regular file. For example, you may seek or `mmap` it.
In the case of multiple shortest entries, the earliest-posted wins (as stipulated by the [*fastest gun in the west*](https://stackoverflow.com/questions/62188/stack-overflow-code-golf/597372#comment-2449021) rule).
---
Here's a [complete description of cdb's format](http://cr.yp.to/cdb/cdb.txt) as written by cdb's inventor:
>
> A cdb is an associative array: it maps strings (*keys*) to strings
> (*data*).
>
>
> A cdb contains 256 pointers to linearly probed open hash tables. The
> hash tables contain pointers to (key,data) pairs. A cdb is stored in
> a single file on disk:
>
>
>
> ```
> +----------------+---------+-------+-------+-----+---------+
> | p0 p1 ... p255 | records | hash0 | hash1 | ... | hash255 |
> +----------------+---------+-------+-------+-----+---------+
>
> ```
>
> Each of the 256 initial pointers states a position and a length. The
> position is the starting byte position of the hash table. The length
> is the number of slots in the hash table.
>
>
> Records are stored sequentially, without special alignment. A record
> states a key length, a data length, the key, and the data.
>
>
> Each hash table slot states a hash value and a byte position. If the
> byte position is 0, the slot is empty. Otherwise, the slot points to
> a record whose key has that hash value.
>
>
> Positions, lengths, and hash values are 32-bit quantities, stored in
> little-endian form in 4 bytes. Thus a cdb must fit into 4 gigabytes.
>
>
> A record is located as follows. Compute the hash value of the key in
> the record. The hash value modulo 256 is the number of a hash table.
> The hash value divided by 256, modulo the length of that table, is a
> slot number. Probe that slot, the next higher slot, and so on, until
> you find the record or run into an empty slot.
>
>
> The cdb hash function is `h = ((h << 5) + h) ^ c`, with a starting
> hash of 5381.
>
>
>
[Answer]
## Python - 398 chars
```
import os;from struct import*
Q=256;S=[[]for x in' '*Q];D=[0]*Q;O=Q*8;R=os.read(0,1e9)[1:];J="".join
while R:
i,R=R.split(":",1);l,m=map(int,i.split(','));k,v,R=R[:l],R[l+2:2+l+m],R[2+l+m:];R=R.partition("+")[2];D+=[pack("II",l,m)+k+v];h=5381
for c in k:h=h*33^ord(c)%Q**4
S[h%Q]+=[pack("II",h,O)];O+=len(D[-1])
for i,s in enumerate(S):D[i]=pack("II",O,len(s));D+=[J(s)];O+=len(D[-1])
print J(D)
```
[Answer]
## Python - 552 characters
```
from sys import*
from struct import*
y=lambda f,i:stdout.write(pack(f,*i))
u=lambda i:y('<II',i)
i=stdin.read()
n=0
t=[[]for c in' '*256]
q=[]
m=[]
o=2048
w=list.append
while len(i)>n:
d=i.find(':',n);f,g=map(int,i[n+1:d].split(','));n=d+1+f;k=i[d+1:n];d=i[n+2:n+2+g];h=5831;for c in k:h=(((h<<5)+h)^ord(c))&0xffffffff
w(t[h%256],(h,o));o+=8+f+g;w(m,map(str,(f,g,k,d)));n+=3+g
for d in t:
l=len(d)**2;t=[(0,0)]*l;u((o,l));o+=l*8
for r in d:
i=r[0]>>8
while t[i%l][0]:i+=1
t[i%l]=r
w(q,t)
for v in m:y('<II'+zip(v,'ss'),v)
for t in q:map(u,t)
```
] |
[Question]
[
**Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/525/edit).
Closed 1 year ago.
[Improve this question](/posts/525/edit)
Write a function that takes two arguments: a number `k` and a list `l`, and that returns another list `r` such that `r[i] = min(l[i-k+1:i])`.
## Examples
* **Input** k=2, l=1,2,3,4,5,6
* **Ouput** r=1,1,2,3,4,5
* **Input** k=3, l=-1,9,7,-9,8,3,5,0,12,1,2,3,-1,-2,-3
* **Ouput** r=-1,-1,-1,-9,-9,-9,3,0,0,0,1,1,-1,-2,-3
Constraints: **O(len(l))** time complexity. *Shortest code* wins.
[Answer]
# R, 75 bytes
```
f=function(k,l){r=l;for(i in 1:length(l));r[i]=min(l[max(1,(i-k+1)):i]);r}
```
Testing:
```
f(3, c(-1,9,7,-9,8,3,5,0,12,1,2,3,-1,-2,-3))
[1] -1 -1 -1 -9 -9 -9 3 0 0 0 1 1 -1 -2 -3
f(2, 1:6)
[1] 1 1 2 3 4 5
```
Not sure how to calculate the complexity of this.
[Answer]
# SmileBASIC, 97 bytes
```
DEF M(K,L)DIM T[0],R[0]FOR I=1TO LEN(L)COPY T,L,MAX(I,K)-K,MIN(I,K)PUSH R,MIN(T)NEXT
RETURN R
END
```
Explanation:
This line uses `COPY dest[],source[],start,length` to get part of the list into a temporary array:
```
COPY TEMP,LIST,MAX(I-K,0),MIN(I,K)
```
Example for a list of size 6, with K=3
```
I|start|length
1| 0 | 1
2| 0 | 2
3| 0 | 3
4| 1 | 3
5| 2 | 3
6| 3 | 3
```
[Answer]
# K, 32 bytes
`{|&/',/+((x*!_(#y)%x)+/:!x)_\:|y}`
Translating the symbols to meaning, that is:
reverse min over each flattened transpose (firstargument multipliedby enumerate truncate (countof secondargument) dividedby firstargument)add eachright enumerate first argument) cutby eachleft reverse secondargument
It's not as terse as J, as K is a simpler language, but it is still interesting
[Answer]
I come from the future (from [this future](https://codegolf.stackexchange.com/questions/113915/suggest-me-a-challenge)) and, since I'm learning J, I thought I'd give it a try.
# J, 21 bytes (non-competing)
```
<./"1@([,\$&_@<:@[,])
```
It prefixes the list with (K - 1) infinities, partitions it in overlapping chunks of length K and then computes the minimum of those. That's O(K\*len(L)) if I'm not mistaken but, AFAICT, you need stateful computation to achieve O(len(L)) which isn't very idiomatic in J.
### Usage:
```
2 <./"1@([,\$&_@<:@[,]) 1 2 3 4 5 6
1 1 2 3 4 5
3 <./"1@([,\$&_@<:@[,]) _1 9 7 _9 8 3 5 0 12 1 2 3 _1 _2 _3
_1 _1 _1 _9 _9 _9 3 0 0 0 1 1 _1 _2 _3
```
[Answer]
## Matlab, 72 bytes
```
function[r]=f(k,l),for i=1:length(l),r(i)=min(l(max(1,i-k+1):i));end;end
```
[Try it Online!](https://tio.run/##FYlBDsIgFAWv4vITH4kfYrRtOEnTRVNBf0ohIWi8PeJiFjOTt7p@fGvhnbYqOc1lcYF2RIWQy0kcj9GnZ31RL4VEuUMSRTrWLzFE72dWoyg1@fT40wJZzJox4AY94A6LKy5gA4bp0pc20HZR7Qc)
[Answer]
# [Haskell](https://www.haskell.org/), 92 bytes
This is a [restricted-complexity](/questions/tagged/restricted-complexity "show questions tagged 'restricted-complexity'") question asking specifically for a program that runs in O(len(l)) time, yet all the other answers in 7½ years have ignored that constraint. Here’s one that satisfies it.
```
g id
g _ _[]=[]
g h k l|(a,b)<-splitAt(k-1)l=h(scanl1 min a)++g(zipWith min$scanr1 min a)k b
```
[Try it online!](https://tio.run/##TctBC4IwHAXwu5/if@iw4X/QNCshD9EX8FZgIktzG04T3Sn67K1JBN0e7/eeEnN3N8a12dVJ0E0goYKqKLOi9FFBB@ZFBN7ogc2j0fZoScc4NZkicy0Gw6HXAwgahpI89XjWVi3NasHphx3cXC98zKB5BADjpAcLpIUICo4RxrjBBLcl/bcYCsYxxR2yFPd@k@AaeYTfgycWIYtL6t51a4ScHbuc8vwD "Haskell – Try It Online")
### How it works
Split the list into blocks of *k* − 1. Within each block, compute all prefix minima (with a left-to-right scan) and all suffix minima (with a right-to-left scan). Then any sublist of *k* numbers crosses exactly one block boundary, and can therefore be computed as the minimum of a suffix minimum from the first block and a prefix minimum from the second block.
] |
[Question]
[
**This question already has answers here**:
[Mirror quine (or my head hurts)](/questions/16043/mirror-quine-or-my-head-hurts)
(9 answers)
Closed 5 months ago.
Write a program that outputs its source code in reverse when run, and outputs its source forwards when I reverse the source. If your program is "abcd", when run with no arguments it should output "dcba", and when I run the program "dcba" it should output "abcd."
This is a [quine](/questions/tagged/quine "show questions tagged 'quine'") challenge, so both your forwards and reverse program must follow the rules of proper quines. Your source code may not be a palindrome.
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, so the shortest code by byte count wins.
[Answer]
# ><> (fish), 15 bytes
```
"0:g}!|o|!}g:0'
```
Reversed:
```
'0:g}!|o|!}g:0"
```
[Try it](https://mousetail.github.io/Fish/#eyJ0ZXh0IjoiXCIwOmd9IXxvfCF9ZzowJyIsImlucHV0IjoiIiwic3RhY2siOiIiLCJzdGFja19mb3JtYXQiOiJudW1iZXJzIiwiaW5wdXRfZm9ybWF0IjoiY2hhcnMifQ==)
[ti yrT](https://mousetail.github.io/Fish/#eyJ0ZXh0IjoiJzA6Z30hfG98IX1nOjBcIiIsImlucHV0IjoiIiwic3RhY2siOiIiLCJzdGFja19mb3JtYXQiOiJudW1iZXJzIiwiaW5wdXRfZm9ybWF0IjoiY2hhcnMifQ==)
] |
[Question]
[
Heading into the final day of regular season games for the 2023 NBA season, the fifth to ninth seeds in the Western Conference were still very undecided. Four games would determine the seeding:
* New Orleans (N) at Minnesota (M)
* Utah at LA Lakers (L)
* Golden State (G) at Portland
* LA Clippers (C) at Phoenix
Let the Boolean variables `M L G C` denote the event of the respective team winning. Then the seeding depends on these variables as follows (taken from [this Twitter post](https://twitter.com/NBAPR/status/1644868977674297344)):
```
M L G C | 5 6 7 8 9
0 0 0 0 | N G C L M
0 0 0 1 | C N G L M
0 0 1 0 | G N C L M
0 0 1 1 | C G N L M
0 1 0 0 | N C L G M
0 1 0 1 | C L N G M
0 1 1 0 | G N C L M
0 1 1 1 | C G L N M
1 0 0 0 | C G M L N
1 0 0 1 | C G M L N
1 0 1 0 | G C M L N
1 0 1 1 | C G M L N
1 1 0 0 | C L G M N
1 1 0 1 | C L G M N
1 1 1 0 | G C L M N
1 1 1 1 | C G L M N
```
## Task
Given the bits `M L G C`, output the corresponding permutation of `C G L M N`, with the fifth seed first. For example, the input `M L G C = 1 0 1 0` should give `G C M L N`. You may use any five distinct symbols for the teams and may format the permutation in any reasonable manner.
Instead of taking `M` you may take its inverse `N`, with results altered accordingly (so the input `N L G C = 1 0 1 0` gives the same result as `M L G C = 0 0 1 0`, i.e. `G N C L M`). You may also combine the Boolean inputs into a single four-bit integer, but in any case you must clearly indicate which bit or bit position corresponds to which game.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"); fewest bytes wins.
---
*The actual results had all bits set to 1, resulting in the seeding*
```
5 6 7 8 9
C G L M N
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org)(1), 68 bytes
Expects a single 4-bit integer, where the least significant bit is `C`. Returns an array of letters.
```
n=>[...'MGNCL'].sort(_=>~(q/=2)%2,q=Buffer(')!-%*$-ESS[SCC+#')[n]*4)
```
[Try it online!](https://tio.run/##Tc2xDoIwEIDhnac4o@R6AhWJcdE6SIyLunQkxBCkRmOuWqqL0VdHRqd/@ZL/Wr2qtnaXu0/YnprOqI7VqpBS4n57yHdYytY6L45q9RWPicoozOKHWj@NaZxAGiTheJRstC50nkdDpILL8Yw6Y51gUJAugGEJ03nfKCJ4BwC15dbeGnmzZ8HSW@3dhc@C5L06aV/1t4wgAgSBff5E9kdmMWCKvUPCGIxgokXw6X4 "JavaScript (Node.js) – Try It Online")
### How?
We use `sort()` on the array `['M','G','N','C','L']` with a callback function which ignores its arguments. Given the input \$n\in[0\dots15]\$, the result of the sort solely depends on a seed \$q\_n=4k\_n\$ where \$k\_n\in[33\dots91]\$ is the code of a printable ASCII character picked from a lookup string.
At each iteration, the expression `~(q /= 2) % 2` in the callback function returns either \$0\$ or \$-1\$.
*(1) This code relies on the fact that `sort()` is stable (which is now a requirement of the ECMAScript specification) and that the array entries are processed in a specific order. This may fail on older engines.*
[Answer]
# [Python](https://www.python.org), 72 bytes
```
lambda a:oct(ord('ʜٔќڌˢ܊ќڡڄڄӄڄܐܐӠڠ'[int(a,2)]))[2:]+a[0]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3PXISc5NSEhUSrfKTSzTyi1I01E_NuTnl4pxbPacX3ekC0gtvtdxquQzEdybcmXB5wa0F6tGZeSUaiTpGmrGamtFGVrHaidEGsRDzbjGylhQl5hXnJJakxpckJuWkKtgqFJcU6eUmZqeCZTSqlQyVrJT8lHS4FGBAyQgo4o4iYgwUcUYRMQGK-KCIGABFfJVqNbkKikAuUvL1cXdWqFEwNTO3sFTS5ErLL1LIVMjMUwBam56qYWimaQXWXAF0UlJmnkYm2PF6RVmlxSUaJjrqBuqaYPl8oHyaRgWUA1Kdrwf3lAaa9yCqIA6o0FFQqlHSAerRhITGggUQGgA)
Takes in a Python string of 0s or 1s corresponding to the wins/losses as described above; outputs a string of length 5 containing the digits 0 through 5, where the mapping is
```
{"1":"N",
"2":"G",
"3":"C",
"4":"L",
"0":"M"}
```
---
# [Python](https://www.python.org), 74 bytes
```
lambda a:ord('卜綌〴稈孲薢〴窼祂祂㋲祂蔶蔶㑚窪'[int(a,2)])
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3vXISc5NSEhUSrfKLUjTUn_bOeb6t53HDlucrOp6u3fRi2iIQe9We50ubgOhx9yYg-WLKNiB6PHHW81Wr1KMz80o0EnWMNGM1ISbeYuQqKUrMK85JLEmNL0lMyklVsFUoLinSy03MTgXLaFQrGSlZKfkp6XApwICSIVDEHUXEGCjijCJiAhTxQRExAIr4KtVqchUUgdyh5Ovj7qxQo2BqZm5hqaTJlZZfpJCpkJmnALQ2PVXD0EzTCqy5AuikpMw8jUzNaCOrWL2irNLiEg0THXUDdU2wfD5QPk2jAsqpgHhAI19TD-4zDTQ_QpRCXFGho6BUo6QD1AgNkgULIDQA)
A simpler earlier approach, using a different mapping.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 50 bytes
```
Nθ≔⪪⪫⟦§59θC§38NG⎇N§47θ¹L0⎇NN2M¦M6N⟧ω²θW⁻θυ⊞υ⌈ι⭆υ⌈ι
```
[Try it online!](https://tio.run/##dYxLC8IwEITv/RUhp12IUN9KT@JBFFMK9SYeYi020MY2TXz8@piCiAoelt2dmW@yQujsIkrn1qq2JrbVMdfQYBQs2laeFaR1KQ1sLlLBfmHW6pTfgY7nlJEGGaFLf7zl4cx/nz3YRVZe3OVaCf2AL/ODHE1fhf2O2Ib/ERoPuHcpn8QUD4zcvDbADo6CWyHLnACXyrbQMGIRSWLbAiwjXNxlZSuQ6IOJlspAavw6c1H/@Bg5Fwb9wI/rXcsn "Charcoal – Try It Online") Link is to verbose version of code. Takes input in the order `C G L M`. Explanation: Each team is given a rating depending on whether it wins or loses, except if the LA Lakers win then their rating also depends on whether the LA Clippers win or not. It then remains to output the teams in descending order of rating.
```
Nθ
```
Input `C`.
```
≔⪪⪫⟦§59θC§38NG⎇N§47θ¹L0⎇NN2M¦M6N⟧ω²θ
```
Build up a string of teams and ratings. First is `C`, which has a rating of either `5` or `9`, then `G` has a rating of `3` or `8`, then `L` has a rating of `1`, `4` or `7`, then either `N` has a rating of `0` and `M` has a rating of `2` or `M` has a rating of `0` and `N` has a rating of `6`. The string is then split into pairs of characters ready for sorting.
```
W⁻θυ⊞υ⌈ι
```
Sort the teams in descending order of rating.
```
⭆υ⌈ι
```
Output just the teams without the ratings.
[Answer]
# [Scala](http://www.scala-lang.org/), 94 bytes
Modified from [@97.100.97.109's answer](https://codegolf.stackexchange.com/a/260164/110802).
---
Golfed version. [Try it online!](https://tio.run/##XVBNSwMxEL3vrxgWYROoi59VF1vQIiJYPVhP4iGuaY1mk5KNUtGCeBLUgyAexJMgSMGLiCf/TZH6L@rEtCKGSXgzyby8N3nKJOuLrKmNhdwlcaql5KkVWsXZoWU7kgeB3tnHElSZUHASAOzyOmSYEGYaeQILxrDjrQ1rhGps0wQ2lbBQgpO@e1cnLPFXNFlRthR@Xj/03q@6Z2@954vPl9evu0eHOx@9p3OM7uUrnl@37xjdm/tepxMSbOMNbuImMznHhLACTFDaB1xHTII1TOWSWV5zchPU2dyq7DFTAHduoxSskGgigtEyRGtRAaJxj5cdnvS44vCUx6sOj3lcjWjgfmqiBysVCauryxU4henizOxc6O/q2gARMD8KY3CorJAwXqQ/oxpqbKGKoQ@rF4Vi5tiPhQgaG37E0Rs63K1pMvXz@W/1D4tGljpp0b8lx6yR07PFGVpNoVT@N5W4we26WZI5J2kBUkrj7MB3DLiG9vJwpIXuRnRr4K0duN0O@t8)
```
def f(a:String):Int="卜綌〴稈孲薢〴窼祂祂㋲祂蔶蔶㑚窪"(Integer.parseInt(a, 2))
```
Ungolfed version. [Try it online!](https://tio.run/##VVBNSwMxEL3vrxgWYRNoFz/qV1FBi4jQ6kE9FQ9xTWs0m5RsLC1aEE@CehDEg3gSBCl4EfHkvylS/0WdNFUUkuHNTPLmvckSJtlgINKGNhYyl8WJlpInVmgVp8eW7UkeBHrvEEtQYULBSQCwz2uQYkKYqWdFWDaGtatb1ghV36VF2FHCwuLwJUCTSagVwXdhcQnWlWsyB8PP64f@@1Xv7K3/fPH58vp19@hw96P/dI6nd/mK8ev2HU/v5r7f7YYEf/M6N3GDmYxjQlgOJin9HWUNU5lklm876UXU3KiWDpjJgYu7OBkrJJqMIL8E0UaUg2jC4zWHpzwuOVzwuOzwuMeViAbDUQ10Y6UiYaW8VoJTmJ6ZnZsPvYyaNkAELORhHI6VFRImZuhoG15kC2X8GLF6RShm2n5BRNDY8CZHc2hxf1uTwnD6b/UPi0aWGmnRvyXHrJHTs8Upek3cpv@vJa5zu2lWZcZJkoOE0jg98j9GXD/2snCshe7GdGvkrRO42wkGg28)
```
import scala.collection.mutable
object Main {
def main(args: Array[String]): Unit = {
val f: String => Int = a => "卜綌〴稈孲薢〴窼祂祂㋲祂蔶蔶㑚窪"(Integer.parseInt(a, 2))
val translateTable: Map[Char, Char] = Map('2' -> 'N', '1' -> 'G', '3' -> 'C', '4' -> 'L', '0' -> 'M')
println("MLGC | 56789")
for (i <- 0 until 16) {
val x = Integer.toBinaryString(i).reverse.padTo(4, '0').reverse
val o = f(x)
val ox = o.toString.map(c => translateTable.getOrElse(c, c)).mkString
println(s"$x | $ox")
}
}
}
```
] |
[Question]
[
This is the follow up question to standard [Sudoku solver](https://leetcode.com/problems/sudoku-solver/).
You are given a Sudoku grid where `.` represents an empty cell and the other cells are filled with numbers `0-8` (inclusive).
Rules:
* All the numbers in Sudoku must appear exactly once in all left-top to right-bottom diagonals.
* All the numbers in Sudoku must appear exactly once in all right-top to left-bottom diagonals.
* All the numbers in Sudoku must appear exactly once in all squares (3\*3).
However numbers can repeat in rows or columns.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Please post your shortest code in any language that solves this problem. Winner will be the shortest solution by byte count.
Input:
```
. 3 7 . 4 2 . 2 .
5 . 6 1 . . . . 7
. . 2 . . . 5 0 .
2 8 3 . . . . . .
. 5 . . 7 1 2 . 7
. . . 3 . . . . 3
7 . . . . 6 . 5 0
. 2 3 . 3 . 7 4 2
0 5 . . 8 . . . .
```
Output:
```
8 3 7 0 4 2 1 2 4
5 0 6 1 8 6 3 6 7
4 1 2 7 3 5 5 0 8
2 8 3 5 4 8 6 0 5
6 5 0 0 7 1 2 1 7
1 4 7 3 2 6 8 4 3
7 8 1 4 1 6 3 5 0
6 2 3 7 3 5 7 4 2
0 5 4 2 8 0 6 8 1
```
[Answer]
# [Prolog (SWI)](http://www.swi-prolog.org) + clpfd, 231 bytes
```
\R:-append(R,V),V ins 0..8,-R,R-Q,maplist(reverse,R,W),W-Y,+Y,+Q,maplist(label,R).
-[[A,B,C|D],[E,F,G|H],[I,J,K|L]|Q]:- +[A,B,C,E,F,G,I,J,K],-[D,H,L],-Q.
-_.
[]-[].
[[E|_]|S]-[E|D]:-maplist(*,S,Q),Q-D.
[_|Q]*Q.
+Q:-all_distinct(Q).
```
[Try it online!](https://tio.run/##RVBbb4IwFH73V/AI@pUoeAvJHrbp5jZfqIlmqU2D0i0kFQnozBL@uzuU6FI4PXy3Q1uUR3P8ZtUlu0bsXGl1OKZno12T7cqk/HX3pvhKPc@/bnnEkqLQeepyrD2snSyvnL7vT8E4OItxSAqTVSe31D@6rDQ4Nh427BM9ev5pk@y0Aff8DhPiEU94rmcSYo4XvNYL6t7wjo96KetYRszptRpYHpaTYGKGBZbUxBSj/I6QTEjaxLxWsl7R15xSI3Yb2sUKsYeYzUikKLlLxl5MRzJGpaTI8v3JjemcNJI7D44gGUJMoDBEQJVeiY4YUTvGgGq7Jg2oWp70CiP0W2WAqQXuq1WOWhtFBDf7wAKhTW7IsAEnd@O4TW3tgdWF1kE/1oB9YocETK2aqiTUcbYczqXMTtrkLt329Q8 "Prolog (SWI) – Try It Online")
This will produce as many choicepoints as solutions there are - [Try it online!](https://tio.run/##RU9ba8IwFH73V@Sx1S9FW28U9rBNN7f50gjKiKFUG0ch1tLqxqD/3Z026EhycvLdkhTlyZy@ePWTXUN@qXR8PKUXox2T7cqk/HX2pjikrutdtyLkSVHoPHUE1i7WLMsr1ve8KbiA4BGOSWGy6uyU@luXlYbAxsWGf6JH8582yU4bCNfrcCkf8YTneqYg53jBa72g7g3v@KiXqo5UyFnPatDyaDkFLmdYYElNRDGx15GKS0WbnNexqld0mlNqyG@XdrFC5CLiMxLFlNwlYy@iLxkTp6TI8v3ZieifdKVgD0ySDAEmiDGET5WWQkeOqB1jQNWOSQPGlid9jBH6Vulj2gL3YZUja6MI/2YftEDQJjdk0ICTu3FsU63db3VB66CHNWCf2CEB01ZNVRHK2FaA/ZTZWZvcES7YITGV9q5/ "Prolog (SWI) – Try It Online") As you can see, there are plenty :P
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 50 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
8ÝI'.¢ãε'.s.;¶¡€#©3δô3ô€ø€€˜€`®Å\ª®Å/ªε{ā<Q}Pi®»,q
```
[Try it online.](https://tio.run/##HU67TsMwFN39FVdhyNK4dpzEkdofYCs7A0HqEAlRoU6AGEDqX7QDZSJCmRKExHbdrVI@gh8xx5Z8H0fn4bvZNrft2vvaHS5TyUf3MY2p3MoFf/P739vXBX@aaXCDcQOQ@0HDO@/Rbrh3u2vuwphzN43Pp9fl1cuq5Z5/Zw/eJ0kiyZAlRQXlpFGFKIEq7DW6QVlRRMYClRTYWuRgAyqiSlEpqshIqHRMskKCDZ4cihq7ERZTU0irolvBlcf/A7LhBqFiasiX0adxo8@y@0121zw9/gM)
Brute-force, so very slow. The more dots the input contains, the slower it becomes. It therefore won't be able to complete the example test case of the challenge description, but it can with just a few dots.
**Explanation:**
```
8Ý # Push a list in the range [0,8]
I # Push the input-string
'.¢ '# Pop and count the amount of "."
ã # Cartesian product this count with the [0,1,2,3,4,5,6,7,8] list
ε # Map over each list:
.; # Replace every first
'. '# character "."
# in the (implicit) input-string, one by one with
s # the digits of the current list
¶¡ # Split the string on newlines
€# # Then split each inner string on spaces
© # Store this matrix in variable `®` (without popping)
δ # Map over each row:
3 ô # Split it into three triplets
3ô # Then split the rows into three inner lists as well
€ # Map over each list of three rows:
ø # Zip/transpose; swapping rows/columns, to group blocks together
€€˜ # Flatten each inner block
€` # Flatten one level to a list of lists
® # Push matrix `®` again
Å\ # Pop and push its main diagonal
ª # Append it to the list
®Å/ª # Do the same for the main anti-diagonal
ε # Map over each inner list:
{ # Sort it
ā # Push a list in the range [1,length] (without popping)
< # Decrease it to range [0,length], which will be [0,8] basically
Q # Check if the two lists are equal
}Pi # After the map: if all are truthy:
® # Push matrix `®` yet again
» # Join each inner row by spaces, and then string by newlines
, # Pop and print it
q # And then exit the program
```
[Answer]
# JavaScript (ES6), 149 bytes
Expects a matrix of integers with \$0\$'s for empty cells and \$1\$ to \$9\$ for filled cells. Returns another matrix in the same format.
This is a brute-force approach which aborts as soon as the grid is inconsistent, making it reasonably fast -- at least for the unique test case (solved in ~6 seconds on TIO).
```
f=(m,X,R)=>m.every(q=(r,y)=>r.every((v,x)=>v?(g=k=>q[k]^(q[k]|=1<<v))(x-y)*g(x+y+9)*g(x/3|y/3+8<<2):(X=x,R=r)))?R?m.some(_=>f(m,R[X]++))?m:R[X]=0:m:0
```
[Try it online!](https://tio.run/##TU/bcoIwEH3nK3Z8ISkYUeqllOBT@wH64ozaDoOBolw0UEamtr9Ol4uX2clmc87Zs5u9W7iZJ8Nj3k/Snagqn5NYX@kLyp2YiULIkpw4kXqJgOwAUuhnfBZzEvADd07rw/aD1PnCh7ZdUErO/ZI@BeSsldpLUwzMSzkwtZltj6hFVvysL7iklM4X85hlaSzIJ3d8HL1Yr7aahkRs1SU3rNgyKilO36EURPUzlTIp3N17GIllmXjEoCxPl7kMk4BQlh2jMCe9TbJJepT5qXxzvS@SAXfgRwGIRA4xcMjuQpTF7rGVXGEV1BYtahQTB5WpMAcDLOj/4Q9fOzMpsBFw8Qbx0iRLI8GiNCDINBaytpCPbn0YUrZPw6SZcy03iVrb/tKKgQlTYPAMI8x4lDHeExhibmOqsJZpYoxrMWUEM@xj91BqplFj5@jWxR5UpjK91ZPWSal9zU41rXdQjM5ndtX@Aw "JavaScript (Node.js) – Try It Online")
### Commented
```
// m[] = input matrix
// (X, R) = local variables to store the position of an empty cell
// (more specifically: the last empty cell of the grid)
f = (m, X, R) =>
// for each row r[] at position y in m[]
// using q as an object for bit-mask storage
m.every(q = (r, y) =>
// for each value v at position x in r[]
r.every((v, x) =>
// is this cell empty?
v ?
// it's not: make sure its value is valid
// g is a helper function testing whether q[k] is modified
// when its v-th bit it set; if not, it means that we have
// twice the same digit on a diagonal or a square
(
g = k => q[k] ^ (q[k] |= 1 << v)
)(
// invoke g for the current anti-diagonal,
// with k in [-8..8]
x - y
) *
g(
// invoke g for the current diagonal,
// with k in [9..25]
x + y + 9
) *
g(
// invoke g for the current square,
// with k in [32..42]
x / 3 | y / 3 + 8 << 2
)
:
// this cell is empty: save its position in (X, R)
// NB: this is guaranteed to be truthy (having empty
// cells does not invalidate the grid)
(X = x, R = r)
)
) ?
// the grid is valid so far
R ?
// there's an empty cell: attempt to set it to 1 .. 9 and
// do recursive calls to see if it leads to a solution
m.some(_ => f(m, R[X]++)) ?
// if successful, return m[]
m
:
// otherwise, reset the cell to 0 afterwards and abort
R[X] = 0
:
// the grid is valid and there's no empty cell: return m[]
m
:
// the grid is invalid: abort right away
0
```
] |
[Question]
[
Your friend Jack is a picky eater. He only likes certain foods, and he only likes to eat a certain amount of them each day. Despite this, Jack has very strict calorie and macronutrient goals that he strives to meet with his diet. To complicate things further, Jack's cravings change day by day, and he will only eat the foods that he wants, up to a certain amount. Your goal is to write a program that Jack can use to enter his goals and his cravings on a given day, and be shown a combination of those foods that most closely matches his dietary requirements.
**Program Input** - Accept the following data in any convenient format for your programming language. All integers, except for food names which are strings. Carbs, fats, and protein are given in grams.
* Jack's Dietary Requirements:
+ A Calorie Target
+ A Carbohydrate Target
+ A Fat Target
+ A Protein Target
* A list of foods (of any length), containing the following info:
+ The name of the food
+ Calories per serving
+ Carbohydrates per serving
+ Fat per serving
+ The maximum number of servings that Jack is willing to consume in a day
**Program Output** - Text, or any data structure that can assocaite the name of a food with the optimal number of servings
* A list of the number of servings (integers) of each food that Jack should have to get closest to his diet requirements. (It is ok for the number of calories, protein, fat, or carbs to be above or below the requirements. Only return the closest solution).
The **absolute difference score** of a combination of foods will be scored as follows (lower scores are better):
* 1 point for each calorie difference from Jack's goal. Ex, if the total number
of calories for a given number of servings for each food adds
up to 1800, and Jack's goal is 2000 calories, add 200 points to the
score.
* 10 points for each gram difference from Jack's goal. Ex, if a combination of foods and servings contains a total of 160 grams of protein, and Jack's goal is 150, add 100 points to the score.
Your program should return **the** solution with the lowest absolute difference score - a number of servings for each of Jack's craved foods. If multiple combinations have the same score, return any of them.
**Example**
```
Input:
{
'goals':[
'calories': 2000,
'carbs': 200,
'fats': 120,
'protein': 150
]
'cravings':[
'chocolate':[
'calories': 130,
'carbs': 14,
'fats': 8,
'protein': 10,
'max_servings': 99
]
'beans': [
'calories': 80,
'carbs': 6,
'fats': 2,
'protein': 18,
'max_servings': 99
]
]
}
Output:
chocolate 15
beans 0
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code wins.
[Answer]
# [R](https://www.r-project.org/), ~~100~~ ~~87~~ 85 bytes
```
function(m,n,g,p=t(expand.grid(Map(seq,m+1))-1))p[,order((.1^!0:3)%*%(n%*%p-g)^2)[1]]
```
[Try it online!](https://tio.run/##PY/RigIxDEXf5y98EJLdKM24uwxCP8EvEIXa6daCk9a2in8/ll304R7ykJxw81xcvgfxRc@/N7E1RIGJhDwlXcE9kpFx7XMYYWcSFHel6ZMRVy1pTzGPLgOs@bhQ2w0uP5YgDWnl8djjng@HeTKPMBltwZ6jjRdTne4VnZyR0gbs5FZzcFKLtqcgI1jgjSL@ooFYIVkYFP1QTzwgdj6aS1uEXilFDcTNxd9N0716wP9Denvp7wjnJw "R – Try It Online")
Input is `m`=serving maxima (optionally named to indicate the names of the foods); `n`=nutrition information, as a matrix with food types as columns (in the same order as `m`), and nutrient types content as rows; and `g`=Jack's goals (in the same order as the rows of `m`).
Output is the optimal number of servings, in the same order as `m` and with the names if supplied.
**Ungolfed:**
```
servings=function(m,n,g){
p=t(expand.grid(Map(seq,m+1))-1)
# Calculate all possible portions as matrix p
# (rows are foods, columns are different servings);
o=n%*%p # Calculate o=obtained nutrients
# by multiplying matrix n (nutrients) by matrix p;
s=c(.1,1,1,1)%*%abs(o-g) # Calculate s=scores
# by multiplying absolute differences between o and g
# by the 1x4 matrix of scoring weights (.1,1,1,1);
result=p[,which.min(s)] # The result is the column of p with the minumum score
return(result)
}
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~34~~ ~~33~~ ~~30~~ ~~25~~ ~~23~~ 20 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
sÝ.«â€˜Σ³*øOα`T/O}нø
```
-1 byte inspired by [*@DominicVanEssen*'s R answer](https://codegolf.stackexchange.com/a/243628/52210), calculating the scores as 10% of the calories and 100% of the grams instead of 100% calories and 1000% of the grams, and an additional -1 byte could now be achieved by changing the input-order of `[calories, carbs, fats, protein]` to `[carbs, fats, protein, calories]`
-3 bytes thanks to *@JonathanAllan*
Takes four separated inputs:
1. A string-list of `names` (e.g. `["chocolate","beans"]`);
2. An integer-list of `max_servings` (e.g. `[99,99]`);
3. A list of integer-lists of `[carbs, fats, protein, calories]` (e.g. `[[14,8,10,130],[6,2,18,80]]`);
4. And a list of integers for the intended goal, also `[carbs, fats, protein,calories]` (e.g. `[200,120,150,2000]`).
Output as a list of `[name, amount]` pairs.
[Try it online.](https://tio.run/##yy9OTMpM/f@/@PBcvUOrDy961LTm9Jxziw9t1jq8w//cxoQQff/aC3sP7/j/P1opOSM/OT8nsSRVSUcpKTUxr1gpliva0lLH0hJIRxua6FjoGBroGBobxOpEm@kY6Rha6FgYxALljAyAwkZAbGqgA2QbxAIA)
**Explanation:**
Step 1: Generate amount-lists for each possible diet based on the first input-list:
```
s # Swap to push both the first (implicit) input-list of names as well as
# second (implicit) input-list of max_servings to the stack
Ý # Map each inner integer to a list in the range [0,max_servings]
.« # Right-reduce this list by:
â # Taking the cartesian product
€˜ # After that, flatten each inner nested list
# (we now have a list of all possible diet-combinations)
```
[Try just step 1 online.](https://tio.run/##yy9OTMpM/f@/@PBcvUOrDy961LTm9Jz//6OVkjPyk/NzEktSlXSUklIT84qVYrmiLS11LC2BdLShiY6FjqGBjqGxQaxOtJmOkY6hhY6FQSxQzsgAKGwExKYGOkC2QSwA)
Step 2: Calculate the (modified) score of each possible diet-combination based on the second input, and sort the diet-combinations based on that:
```
Σ # Sort the list of diet-combinations by:
³* # Multiply each individual integer by values in the third input-list of
# [carbs,fats,protein,calories]-quartets
ø # Zip/transpose; swapping rows/columns
O # Sum the other inner lists
α # Get the absolute difference with the fourth (implicit) input-list with the
# diet-goal
` # Pop and push all four values to the stack
T/ # Divide the top calories by 10
O # Take the sum of the four values on the stack
} # Close the sort-by
# (we've now sorted all possible diet-combinations by their scores)
```
[Try steps 1 and 2 online.](https://tio.run/##yy9OTMpM/f@/@PBcvUOrDy961LTm9Jxziw9t1jq8w//cxoQQff/a//@jlZIz8pPzcxJLUpV0lJJSE/OKlWK5oi0tdSwtgXS0oYmOhY6hgY6hsUGsTrSZjpGOoYWOhUEsUM7IAChsBMSmBjpAtkEsAA)
Step 3: Get the diet-combination with the lowest score, pair it with the names of the first input, and output it as result:
```
н # Pop and push the first diet-combination of the sorted list
ø # Create pairs with the list of names that's still on the stack
# (after which the result is output implicitly)
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~75~~ 73 bytes
```
⊞υE⁵∧¬ι⟦⟧Fη«≔υζ≔⟦⟧υF⊕⊟ιFζ⊞υEλ⎇ν⁺μ×κ§ιν⁺μ⟦§ι⁰κ⟧»⪫⊟⌊Eυ⟦ΣEθ×↔⁻λ§ι⊕μ∨¬μχ§ι⁰⟧
```
[Try it online!](https://tio.run/##VZBPSwMxEMXP9lMMe5pAhG210uKpeKpQXdBb2EO6G93Q/KnJRrTiZ18nK6XtJSTvPd5vJk0nQ@OlGYYqxQ4Th43c45zDyrX45HvUjIOoGWP3kzcfADsGP5OrVYz63eX4gYzjU9QcUn6PybVrgrLK9arFyu@piTEYnQODc5rh8KqCk@EbHYfKpIiWJG1VxB1N0q9dq75Qc3BUcUqIM6ckfZfHJPzvhFofvLWSdiCGeEkWM@jj2LraRm9Sr3CjHXWZC8j53JaNxOcw/oWl67T8ly7YNVGroF2Pj167cVtq1pa4KYcLKGiwYRBiVpYlh1k@prN8zEv6NCGKpvONN7JXBYk32bnlsMg8DstlzhRbJV0ke0HSHZWQuRjNuh6uP80f "Charcoal – Try It Online") Link is to verbose version of code. Takes as first input a list of targets and as second input a list of foods each being a list of names, nutritional values and maximum servings and outputs a space separated string of foods and servings e.g. `chocolate 15 beans 0`. Explanation:
```
⊞υE⁵∧¬ι⟦⟧Fη«≔υζ≔⟦⟧υF⊕⊟ιFζ⊞υEλ⎇ν⁺μ×κ§ιν⁺μ⟦§ι⁰κ⟧»
```
Form the Cartesian product of the ranges of all possible servings of all input foods, including their names, plus also calculating the nutrition each combination of servings provides.
```
⪫⊟⌊Eυ⟦ΣEθ×↔⁻λ§ι⊕μ∨¬μχ§ι⁰⟧
```
Calculate the score for each combination of servings and output the combination of servings with the lowest score.
65 bytes using the newer version of Charcoal on ATO:
```
⊞υE⁵∧¬ι⟦⟧Fη≔ΣE⊕⊟ιEυEμ⎇π⁺ξ×κ§ιπ⁺ξ⟦§ι⁰κ⟧υ⪫⊟⌊Eυ⟦ΣEθ×↔⁻λ§ι⊕μ∨¬μχ§ι⁰⟧
```
[Attempt This Online!](https://ato.pxeger.com/run?1=VVDLasMwEKTXfoXQaQUKOOkDh5xyTCGtob0pPjiOUotYkqtHSb-llxxa6C-1X9OV40ByWcTMaGZ2P3_qpnK1rdrD4TuG7Sj_u5oV0TcQOVlWHdxxMjcbeLQBFONElIyx2fXWOgINI3Pv1auB56ghiRemdlJLE-QGCtvhD3Z0Gcw0Jy_Smcp9QMdJ0UYPe4SUlh52GBQWZiP3oDjpWPp6UogzJkN8l1r0iohlCqdMgAerTB-6VEbpoRDmilO5t1PSfO1tG4NMSvRvL4LPV9DHjCfXr6_xOc6O0EWfsocooXiZL7-u_XDJXyPo6L2lyI1UmkJMsizjZJLGeJLGXVZiRbGidWNr21ZBrlA5vkncLSd5iuRkOk2qFV3LyvgkyBG8RyOk854uS1oOsf8 "Charcoal – Attempt This Online") Link is to verbose version of code.
] |
[Question]
[
Summer Klerance turned in her term assignment for this [**challenge**](https://codegolf.stackexchange.com/questions/231585/a-suitable-mission#231761). Her professor was miffed (but also amused) when he overheard a disgruntled classmate of Summer's saying she got her answers by simulation rather than by the probabilistic methods covered in the course. Summer received a note to see the prof during his next office hours.
"OK, Miss Smarty-Pants\*, I'll admit your problem was harder than any of the others I assigned. However, I'm not ready to give you full credit...Have a seat! If we order the goals by increasing difficulty of achievement, which you already, um, "found," we have:
>
> The Prof's *New* Order:
>
>
> **1** (Any) one complete suit **[7.7 hands]**
>
> **3** (Any) two complete suits [10.0 hands]
>
> **2** One given complete suit [11.6 hands]
>
> **5** (Any) three complete suits [12.4 hands]
>
> **4** Two given complete suits [14.0 hands]
>
> **6** Three given complete suits [15.4 hands]
>
> **7** The complete deck (all four suits) **[16.4 hands]**
>
>
>
**The Challenge**:
"I'd like you to modify your program. Keep track of the number of hands needed to see each of the seven goals as you deal, just as before. Let's define one ***trial*** as being completed on the hand when you've achieved *all seven goals*, i.e. a complete deck. The *order* in which you achieved each of the seven goals during a trial *may or may not match the New Order* I've shown you. To receive full credit for you term problem, I'd like you to tack a *single number* onto your output: **the percentage of total trials in which the order of goal achievement *exactly* matches the New Order**. And let's change our sample from 1 million deals to **20,000 trials** to ensure there is no partial trial at the end."
**Input:** None
**Output**: Same format as the [original challenge](https://codegolf.stackexchange.com/questions/231585/a-suitable-mission) with two changes: (a) the addition of the new percentage at the end of the output, and (b) a program run of exactly 20,000 trials, instead of the 1 million deals in the previous challenge.
**Rules** (revised):
(1) The results for the seven goals should be output in the **Old** Order (1-7) and not the New Order above. However, the percentage of interest is based on the **New Order** above, that of strictly increasing difficulty of achievement.
(2) Runs are no longer based on 1 million deals, but rather **20,000 completed trials** (roughly 330,000 deals).
(3) A tie resulting from achieving two or more goals on the same deal counts as a Yes, since it (also) fulfills the New Order requirement.
(4) The new number should come at the end of the output and needn't have a % sign.
(5) Show the result of *three* program runs, as in the original challenge. The data requested for each of the seven goals remains analogous to the original challenge: goal number; average number of hands needed in the 20,000 trials (rounded to one decimal place); minimum number of hands needed; and the maximum number of hands needed. The newly requested percentage should be at the end of the output.
(6) Code golf, so shortest ~~club~~ code in bytes wins.
---
\*He didn't actually say that, but it was what he was thinking.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~96~~ 78 bytes
```
%4‘ċⱮ4=13ḣḞƑ}¡S<
⁸;52Ẋḣ13¤Q$ç4$пçþ7H€¤§µ“Þ2ị’D¤ịṢƑ׳;@
2ȷ5¢€ZµÆmær1;Ṃ;Ṁ)µṪḢṭĖ
```
[Try it online!](https://tio.run/##AZsAZP9qZWxsef//JTTigJjEi@KxrjQ9MTPhuKPhuJ7GkX3CoVM8CuKBuDs1MuG6iuG4ozEzwqRRJMOnNCTDkMK/w6fDvjdI4oKswqTCp8K14oCcw54y4buL4oCZRMKk4buL4bmixpHDl8KzO0AKNci3MsKi4oKsWsK1w4Ztw6ZyMTvhuYI74bmAKcK14bmq4bii4bmtxJb/M8Ki4oKs/w "Jelly – Try It Online")
A full program which is called as with no arguments and returns a list of lists of numbers. Each goal is represented in order as `[goal number, [mean, min, max]]` while the eighth list member is the percentage of trials matching the specified order. This is an extension of [my previous Jelly answer to the first part](https://codegolf.stackexchange.com/a/231599/42248). The TIO link runs three lots of 500 (5E2) trials rather than 20,000 (2E5).
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 170 bytes
```
≔E⁷⟦⟧εFײ⁰φ«≔Eε⁰ζ≔⁰δ≔⁰ηW№ζ⁰«≔⟦⟧θF¹³⊞θ‽⁻E⁵²μθ≧|ΣX²θη≦⊕δ≔↨⁻⊖X²¦⁵³η⁸¹⁹²θFΦ⁷‹§ζλ⎇﹪λ²⁼¹Σ…θ⊘⁺³λ›⊗№θ⁰λ§≔ζλδ»F⁷⊞§εκ§ζκ⊞υ∧¬⊙241536‹§ζIκ§ζλ¹⁰⁰»Eε⪫⟦⊕κ⟦∕÷⁺×χΣι⊘LιLιχ⌊ι⌈ι⟧⟧ ﹪%.1f∕ΣυLυ
```
[Try it online!](https://tio.run/##ZVJdb9owFH0uv8KKNOla8qYkjHZTnyjso1PZUNc3xINHXGLh2CW2oXTqb8/8lQJanmzn3HPOPfeuatquFBVdN9aaryXM6BNcEbRYYoIYvh48qhbBA2@YhjInqMgxRn8HFydoRlDuwC8O3D87YHV@rf11X3PBEEyUlQZefFng6mGLJUFbj7sIosUQo7nVNWwJuqeyUg3MuLQ6iI5Kghrs8ThUuLfIcs/XtYEbbvZcs18tQb9tA3O1Zy2UAZ68HCvgVq5a1jBpWJV8945uqGZJdMreQEe60TDyEfSp@FziM/tfuTAO5bK8Y1rD2NzKij37toUDPrBW0vYAM1VZoUAQ5Mu/bC0VGoroenJYCTap1ZNP4DsVOy8tnJeh5/AfQd9aRr3MVNk/wv2P2W5DthGFYi@n@qnL10F0epVy7iFuoBtXfFKxCSEHkHU/ZAU/lYGxPEBWfixGw8vs/y4nVBvY4HMiEV0Xee4ZXwfzlju7aYt@KO6W4GQa4G0spnzHK@amZNIpZBBXsshjVNyzpojumFyb2j9h76q/hN0lyE2TN6HCnelzOi/d6mUoC8uUPMXBZO8@FI@uuyTtteyR1vp2rruue78T/wA "Charcoal – Try It Online") Link is to verbose version of code. Note: TIO link limited to 200 trials as 20,000 is too slow. +1 byte if you want to output a `%` sign. Explanation:
```
≔E⁷⟦⟧ε
```
Start with an array of 7 empty lists of counts needed to reach the goal.
```
Fײ⁰φ«
```
Loop 20,000 times.
```
≔Eε⁰ζ
```
Start with no goals found yet.
```
≔⁰δ
```
Start with no deals yet.
```
≔⁰η
```
Start with no cards yet.
```
W№ζ⁰«
```
Repeat until all goals have been found.
```
≔⟦⟧θF¹³⊞θ‽⁻E⁵²μθ
```
Deal 13 different cards at random.
```
≧|ΣX²θη
```
Convert the cards into a bitmask and mark them as having been seen for this trial.
```
≦⊕δ
```
Increment the count for each trial.
```
≔↨⁻⊖X²¦⁵³η⁸¹⁹²θ
```
Find the suits for which all of the cards have now been seen.
```
FΦ⁷‹§ζλ⎇﹪λ²⁼¹Σ…θ⊘⁺³λ›⊗№θ⁰λ§≔ζλδ»
```
For each goal, mark it as satisfied if it is now but wasn't before. The flag is actually the count of deals for this trial so far.
```
F⁷⊞§εκ§ζκ
```
Push the counts to the lists.
```
⊞υ∧¬⊙241536‹§ζIκ§ζλ¹⁰⁰»
```
Also keep track of whether this trial's results are in the desired order.
```
Eε⪫⟦⊕κ⟦∕÷⁺×χΣι⊘LιLιχ⌊ι⌈ι⟧⟧
```
Format the averages as desired.
```
﹪%.1f∕ΣυLυ
```
Format the percentage of trials in the desired order. Sample outputs (from TIO):
```
1 [7.6, 5, 14] [7.8, 4, 16] [7.8, 4, 14]
2 [11.8, 6, 27] [11.9, 5, 33] [12.3, 5, 34]
3 [10.1, 6, 16] [10.0, 6, 17] [10.0, 6, 16]
4 [14.0, 8, 31] [14.4, 6, 33] [14.0, 7, 34]
5 [12.2, 8, 21] [12.6, 7, 22] [12.7, 7, 21]
6 [15.0, 8, 31] [16.1, 9, 35] [15.4, 7, 37]
7 [16.0, 8, 31] [17.2, 9, 35] [16.3, 9, 37]
53.0 48.0 51.0
```
] |
[Question]
[
Here in Russia, we have a little-known card game with the name, when translated directly, means Rooster.
The cards used are two full 54-card decks of playing cards from 2 through aces, with jokers. The game for each player divides into two stages. In the first stage, each player has 14 cards dealt, and with those cards has to get 51 or more points with card combinations.
## Rules:
1.Each combination has to be at least three cards long, with no cards repeating, and can be either:
* A combination of cards of the same value (not points), for example:
```
Ace of spades, ace of hearts, ace of clubs
Six of hearts, six of clubs, six of diamonds, six of spades
```
* A combination of cards that are in a row, like a straight in poker, examples:
```
Jack of clubs, queen of clubs, king of spades, ace of hearts
Seven of spades, eight of diamonds, nine of clubs
Ace of diamonds, two of clubs, three of hearts, four of diamonds, five of spades
```
2. Your hand score is calculated by the sum of points in every card combination according to the chart below:
```
2-10: according to the cards face value for each card (For example, Three of spades is 3 points)
Jack,Queen,King: 10 points for each card
Ace: 1 point if used before a Two, otherwise 11 points for each card
Joker: 0 points
```
4. Jokers can substitute any card in a combination, but **cannot** be used more than once in each combination. The cards they substitute cannot be used again in the same combination.
5. Cards cannot be used twice. If you used a card, you can't then use it in a different combination
6. But remember, since the deck is two 54-card decks, duplicates of one card are possible, and, if duplicates are in a hand, using one card will not forbid you from using the other duplicate.
## The task:
Taking a hand of 14 cards, output one of the possible things:
1. A truthy value if the cards given can form combinations in such a way that your hand score is more or equal than 51
2. A falsy value if your hand does not reach the score of 51
## Input:
Each card is given in a format VS, where:
1. V is the face value. Possible values: [2,3,4,5,6,7,8,9,T,J,Q,K,A]
2. S is the suit of a card. Possible values: [S,H,D,C,J]
A joker will be represented as JJ
Your input may be in any form you wish, as long as each card values are not separated. For example:
1. A list of cards. (['TS','3H','JJ','9C',etc...])
2. Cards separated from each other with a whitespace. (TS 3H JJ 9C etc...)
## Output:
Either:
1. A Truthy/Falsy
2. A 1/0
This is codegolf, so lowest bytecount for each language wins! I hope the rules are clear, and good luck!
edit 1: got mixed up in terminology
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~415~~ 376 bytes
```
->a{s=[*2..9]+[10]*4+[11,1]
g=->d,j{x=0
65.times{|r|v=r/5;r%=5
p=w=0
c=d*1
y=[r,c[v]/5,c[v]%5].min
z=v+1+r
r<3?z<13?(v-1).upto(z){|n|p+=s[n];c[n]>4?c[n]-=5:w+=1}:w=2:r>y+1?w=2:(p+=s[v]*r;c[v]-=y*5;w=r-y)
w>1||w>j||(x=[p+g[c,j-w],x].max)}
x}
b=(0..12).map{[]}
a.map{|i|b["23456789TJQKA".index i[0]]<<i[1]}
h=b[9].size-(b[9]-=[?J]).size
b.map!{|i|i.size*5+(i&i).size}
g[b,h]>50}
```
[Try it online!](https://tio.run/##JVHLbqswFNz7K3wjpeLpxiROm8cBVb2Liq6qdmd5wauJ0xuCTAIkwLfnGqojecYzo/GRrC7x9f4Nd9eP2hK45RGyEjanM2EtNFCHCrQD10@dQ9vADC0ZOctjVrad6ipQj2yjpsBQAbU2E0gtiq7AlZPwSjyyEaZMkKPM0Q0qm9oKqe08uG3pPDAql5rkUpxPxs1su7wrbCh5LjaJPvxFMIALbF3bQPt1Dd5a@VebBgMzxmwlLLUZ3nDharFNDcq9mqj2adfV/qHrjAZ4Ye944hzcWjiNXiRqzB41PYrBmBFCPVNLRctFj6KRdbKL@cSbL9jy6Xn1FX68v0yIzNOswZLPhNhuJac6vYeYrwQp5S1zjYG6wINQmKOC4qHrz1AmR8FitiEf5K/box2Pnb3w2ay/p1nyA9O69fAcLzDDS/yEn/EKf@EQf@B3/NKTQp3SS3I2dOoNv@FXPX/1fOLPftzeeFgfTjI3bT4Jw4n@OLSP8hQDHrpJGR2Lf5lBFyYq8GCQ8qTOmn/z4Sbu/wE "Ruby – Try It Online")
Revised version, using recursive search tree instead of brute force search. This version runs to completion on TIO.
The TIO generates random test cases. It is interesting to modify the `x>50` to simply `x` to see the raw scores achieved. Sometimes the way to achieve the best score is not obvious and it can take a moment's scribbling to work out manually how the computer got as high a score as it did.
**Explanation**
Cards are taken as an unsorted array `a` and the suit letters are parsed into 13-element array `b`, one element for each card value. After jokers have been removed and counted separately, the total number of cards and number of distinct suits are stored as a single number `5*total + distinct suits.` Distinct suits are only important when dealing with `n of a kind` type groups: the number of available cards is `max(total cards, distinct suits)` plus jokers.
Searching is done recursively by "nested" function `g`. There are 5 different types of groups of cards to search for, as below. Note that the best use of `34567` would be a 5 straight but if a second `5` is available the best use would be two separate 3 straights `345` and `567`, so greedily assigning to the largest possible group is not always the best strategy. Instead we look for groups separately. Straights of 6 and over will be found as a combination of shorter straights.
```
Type corresponding value of r%5
3 straight 0
4 straight 1
5 straight 2
3 of a kind 3
4 of a kind 4
```
There are 13 possible starting values for each type, so **the total number of distinct possible groups to search for is 13\*5=65** (some straights are not possible with the highest starting values.)
When function `g` finds a group, it passes the remaining cards on recursively to a new instance of itself, then compares the score of the group it found (plus any additional groups found by recursion) with the highest score found so far in variable `x`, and updates `x` if necessary.
Return value of recursive function `g` is the highest score found. Return value of outer function `f` is `true` or `false` from `g>50`.
**Commented code**
```
->a{s=[*2..9]+[10]*4+[11,1] #14-element array of card scores. Final element is ace low, accessed as s[-1]
g=->d,j{ #function g takes an array of card data, and a joker count as input
x=0 #largest score found so far is 0
65.times{|r|v=r/5;r%=5 #iterate through 13 possible card values and 5 possible group types
p=w=0 #p=points for this iteration;w=wildcards required
c=d*1 #make a copy of d for this iteration
y=[r,c[v]/5,c[v]%5].min #y=number of cards removed by successful n of a kind. [cards required,cards available,distinct suits].min
z=v+1+r #z=top value of straight
r<3? #if r<3 consider a straight
z<13?(v-1).upto(z){|n| #if z is in range (no more than ace high) iterate through cards
p+=s[n];c[n]>4?c[n]-=5:w+=1}: #add score to p. If card available, remove from c, else increment wildcards required
w=2: #if z out of range set wildcards to 2 to indicate failure
r>y+1?w=2: #if r>2 consider a straight. If insufficient cards for r with 1 joker, set w to 2 to indicate failure.
(p+=s[v]*r;c[v]-=y*5;w=r-y) #add score to p, remove cards from c, set wildcards required
w>1||w>j||(x=[p+g[c,j-w],x].max)} #if wildcards required no more than 1 or jokers available, take the score, sum with results of further recursion and compare with x
x} #return x, the highest score of all 65 iterations
b=(0..12).map{[]} #make a 13 element array to store totals of cards
a.map{|i|b["23456789TJQKA".index i[0]]<<i[1]} #add the suit letter for each card to b
h=b[9].size-(b[9]-=[?J]).size #any "jacks" of suit J are actually jokers. count jokers into h and remove from b.
b.map!{|i|i.size*5+(i&i).size} #collate the suit letters into a single number: total cards*5 + number of distinct suits
g[b,h]>50} #call g to find highest score. return truthy if over 50, else falsy.
```
] |
[Question]
[
Symja is a ["computer algebra language & Java symbolic math library for Android NCalc calculator"](https://github.com/axkr/symja_android_library). It's a fun little language, so I'm wondering if y'all have any tips for golfing in Symja.
~~As per usual, "remove comments", etc, isn't really an answer.~~ It turns out that there is no comment system in Symja, so "remove comments" isn't an answer. :P
[Answer]
# Don't Use `Print`...Use the Formatted Output
Here's an example fizzbuzz:
```
For(i=1,i<101,i++,s="";If(Mod(i,5)==0,s=s<>"Fizz");If(Mod(i,3)==0,s=s<>"Buzz");If(Mod(i,5)*Mod(i,3)!=0,s=s<>ToString(i));Print(s))
```
Now, this is alright, but it can be improved:
```
For(i=1,i<101,i++,If(Mod(i,5)==0,s=s<>"Fizz");If(Mod(i,3)==0,s=s<>"Buzz");If(Mod(i,5)*Mod(i,3)!=0,s=s<>ToString(i));s=s<>"\n");s
```
Sure, it's only two bytes shorter, but hey, *it's two bytes shorter*.
Just put all the output into a string and tack a `;<variable_name>` onto the end and you'll have a shorter program (usually).
] |
[Question]
[
Given a sequence \$S\$ with length \$n\$ of exactly one each of whole numbers from \$1\$ to \$n\$, your task is to return a number \$\sigma\$ indicating how shuffled it is.
# Definition of shuffledness
Humans perceive shuffling randomness locally [Citation Needed], so the shuffledness of a sequence is based on the ability to find various patterns within each sliding window \$W\$ of 5 consecutive elements of the sequence (\$W = \{S\_x, S\_{x+1}, S\_{x+2}, S\_{x+3}, S\_{x+4}\}\$ for some \$x\$- these will overlap, as each \$x\$ that is at least \$4\$ less than \$n\$ is considered). For each window of 5 elements, add a point for each test of the following that fails: (Note the 1-indexing due to the use of mathematical notation)
* Apply the following tests to the whole window:
1. \$W\$ is monotonic
2. \$W\$ is in ascending order
3. Some permutation of \$W\$ is a run of sequential integers (e.g. 1, 2, 3, 4, 5)
4. For all \$W\_i\$ where \$i>1\$, \$W\_i = W\_{i-1}+k\$ for some integer \$k\$.
+ This corresponds to regular linear intervals
5. For all \$W\_i\$ where \$i>1\$, \$W\_i = W\_{i-1}+ax+k\$ for some integers \$k, a\$, where \$x=i\$.
+ This corresponds to regular quadratic intervals (which could also be linear)
* Apply the same tests for subwindows where 1 or 2 elements have been removed (if any one of those reduced windows passes a particular test, this step passes. Only count one failure when a test fails for all reduced windows.
* Apply the same tests for windows with some pair of adjacent elements optionally swapped (this step will pass if all tests passed for the whole unmodified window) Replace test 3 with the following:
+ \$W\$ is an ascending or descending sequence of sequential integers (e.g. 5, 4, 3, 2, 1)
### Notes
* Ascending sequential sequences will pass every test for all windows and therefore be scored as \$0\$
* Descending sequential sequences will pass all tests except the "ascending" one for all windows and will therefore be scored as \$3(n-4)\$
* The naive maximum shuffledness is \$15(n-4)\$
# Examples
* [1, 5, 3, 2, 4]
+ All elements:
- Passes test 3
- Fails all other tests (+4)
+ Elements removed:
- Passes tests 1, 2, 5 with [1, 2, 4] (remove 5 and 3)
- Passes test 3 with [5, 3, 2, 4] (remove 1)
- Fails test 4 (+1)
+ Elements swapped:
- Fails all tests (+5)
* Test 3 fails because it requires the elements to be in order for this case only
+ \$\therefore \sigma = 10\$
* [1, 2, 4, 3, 5]
+ All elements:
- Passes test 3
- Fails all other tests (+4)
+ Elements removed:
- All tests pass with [1, 2, 3] (remove 4, 5)
+ Elements swapped:
- Passes all tests (swap 4, 3)
+ \$\therefore \sigma = 4\$
* [3, 6, 9, 12, 15] (a sliding window)
+ All elements:
- Passes tests 1, 2, 4, 5
- Fails test 3 (+1)
+ Elements removed: same (+1)
+ Elements swapped: same (+1) (no swap)
+ \$\therefore \sigma = 3\$
* [8, 12, 13, 11, 6] (a sliding window)
+ All elements:
- Passes test 5 (\$a=-3, k=4\$)
- Fails all other tests (+4)
+ Elements removed:
- Passes tests 1, 2, 5 with [8, 12, 13] (remove 11, 6)
- Passes test 3 with [12, 13, 11] (remove 8, 6)
- Fails test 4 (+1)
+ Elements swapped: same as all elements (+4) (no swap)
+ \$\therefore \sigma = 9\$
* [2, 4, 6, 1, 3, 5] (whole sequence)
+ First window: ([2, 4, 6, 1, 3])
- All elements: Fails all tests (+5)
- Elements removed:
* Passes tests 1, 2, 4, 5 with [2, 4, 6]
* Passes test 3 with [2, 1, 3]
- Elements swapped: Fails all tests (+5)
+ Second window: ([4, 6, 1, 3, 5])
- All elements: Fails all tests (+5)
- Elements removed:
* Passes tests 1, 2, 4, 5 with [1, 3, 5]
* Passes test 3 with [4, 6, 5]
- Elements swapped: Fails all tests (+5)
+ \$\therefore \sigma = 20\$
# Rules and such
* Standard IO rules, loopholes, etc
* You must handle sequences of up to 1000 elements long
* You may assume \$S\$ is at least 5 elements long
* No validation necessary. You may assume that all inputs contain exactly one each of every whole number from \$1\$ to \$n\$
* Shortest code wins!
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~71~~ 65 bytes
```
J4Ṭ;-+ʋ€ịṭ@Wẋ¥€3ṭœcJ;2/Ṣṭ,`Ɗ€€ƲḊ,UṢƑ€o\ƲI,I$E€ƊIỊẠƊ3ƭ€€€»/€¬µ5ƤFS
```
[Try it online!](https://tio.run/##JcqxCsJADAbgvU/h4GaKXK8tSkFcFOoqIlIFQVyk4OwmLsJ1ElcFEd3qIgjWgkPFG3yL9EXOXAsh5PvzL@ZhuFKqZ2MSe2btF@WbGNMIk1t7iK8ou5I56buf9TyrjsmZAFMpKKeRd3wKGFAsd8TlWN598Ksd/RI@pgJfJym4vJV1miyt6x1nD0deun2FydvL14eK2ark66P32RqfLRVGSgVGwMACDjY4E9BwCBbYJeggFh8OLjSBWcAKNoqTA2PgauumC6xoG5M/ "Jelly – Try It Online")
A monadic link taking a list if integers and returning an integer. I’m sure this can be shortened further.
## Explanation
```
...µ5Ƥ | Run the main chain (below) for each 5-integer-long infix of the list
F | Flatten list
S | Sum
```
### Main chain
This generates the lists for the each set of tests. To deal with the variation in test 3, there are 3 copies made of each innermost list. For the first and second sets of tests, the last copy of each innermost list is sorted, while for the third set of tests it is not.
### Main chain part 1 (generates swapped lists for third set of tests)
```
J | Sequence along list [1,2,3,4,5]
4 ʋ€ | Do the following as a dyad for each of 1,2,3,4 with 1,2,3,4,5 as the right argument:
Ṭ | - Convert to logical list with 1 at the relevant index [[1],[0,1],[0,0,1],[0,0,0,1]]
;- | - Concatenate -1 to this
+ | - Add (to [1,2,3,4,5])
ị | Index into original list
ṭ@ | Tack onto end the original list
Wẋ¥€3 | Repeat each inner list 3 times
```
### Main chain part 2 (generates lists for first and second sets of tests)
```
ṭ Ʋ | Tack output of part 1 onto the following:
œcJ | - Combinations of lengths 1,2,3,4,5
;2/ | - Pairwise reduce using concatenation
Ɗ€€ | - Following as a monad for each innermost list:
Ṣ | - Sort
ṭ,` | - Tacked onto the list paired with itself
Ḋ | - Remove first (i.e. the combinations of lengths 1 and 2)
```
### Main chain part 3 (runs the tests)
```
3ƭ€€€ | For each innermost list, do one of the following three in turn:
Ʋ | - Tests 1 and 2
,U | - Pair with reversed list
ṢƑ€ | - Check whether each invariant if sorted
o\ | - Cumulative or
Ɗ | - Tests 4 and 5
I | - Increments (test 4)
,I$ | - Paired with increments of increments (test 5)
E€ | - Check if all equal for each of these
Ɗ | - Test 3
I | - Increments
Ị | - Absolute value <= 1
Ạ | - All
»/€ | Reduce each using max - picks the best results for each test for each set of tests
¬ | Not (vectorises)
```
] |
[Question]
[
**Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/196122/edit).
Closed 4 years ago.
[Improve this question](/posts/196122/edit)
Gaussian integer is a complex number in the form \$x+yi\$, where \$x,y\$ are integer and \$i^2=-1\$.
The task is to perform such operation for Gaussian integers \$a,b\$, that
\$a=q \cdot b+r\$ and \$|r|<|b|\$ (\$q,r\$ are Gaussian integers, \$|z|\$ is defined as \$\sqrt{a^2+b^2}\$ for \$a+bi=z\$).
Need to output only \$r\$.
One of possible approaches is [here](https://math.stackexchange.com/a/600512/233398).
**Scoring**: the *fastest* in terms of [O-notations](https://en.wikipedia.org/wiki/Big_O_notation#Infinite_asymptotics) algorithm wins, though it can consume more time. By fastest I mean \$O(\left(f(n)\right)^a)\$ is preferred for smaller \$a\$ and \$O(\log^a(\log(n)))\$ will be preferred over \$O(\log^b(n))\$, ...over \$O(n^k)\$, ...over \$O(e^{\alpha n})\$ and so on.
If there's a tie, fastest implementation wins in terms of benchmark (e.g. 100 000 random 32-bit \$b\$ and 64-bit \$a\$ (I mean both real and imaginary part to be 32 or 64 signed integer)) or there can be 2-3 winners.
If unsure about algorithm complexity, leave blank. E.g. I believe Euler's algorithm for integers [has \$O(\log(n))\$ time complexity](https://codility.com/media/train/10-Gcd.pdf).
Test cases can be obtained from wolframalpha in the form like [Mod[151 + 62 I, 2 + I]](https://www.wolframalpha.com/input/?i=Mod%5B151+%2B+62+I%2C+2+%2B+I%5D), but in case there are some:
```
4 mod (3+3*i) = either of 1+3*i, -2-0*i, 4-0*i, 1-3*i
10000 mod 30*i = either 10 or -20
(3140462541696034439-9109410646169016036*i) mod (-81008166-205207311*i) =
either -75816304-29775984*i or 129391007+51232182*i
```
\$|b|\$ will not exceed 32 bits, but you don't have to code long arithmetic if your selected language doesn't have built-in one.
Good luck. Of course, WolframLanguage is forbidden. )
[Answer]
# [Python 2 (PyPy)](http://pypy.org/), O(1) operations
```
def cmod(a1, a2, b1, b2):
# Compute p = a * conj(b)
p1 = a1 * b1 + a2 * b2
p2 = - a1 * b2 + a2 * b1
# Compute the norm-squared of b
b_nsq = b1 ** 2 + b2 ** 2
b_nsq_half = b_nsq // 2
# Do a symmetric mod of d1 and d2 by b_nsq
# That is, into the interval [-b_nsq_half, +b_nsq_half)
d1 = (p1 + b_nsq_half) % b_nsq - b_nsq_half
d2 = (p2 + b_nsq_half) % b_nsq - b_nsq_half
# Compute r = d / b
r1 = (d1 * b1 - d2 * b2) // b_nsq
r2 = (d1 * b2 + d2 * b1) // b_nsq
return r1, r2
```
[Try it online!](https://tio.run/##jVLLrtMwFFw3XzESulLS69DaFSwq7go@gR2LK7txSVDzuLYL5OvLnCRqg8SCyJJ9Zua8M4yp7jtTDuMw3m6VP@PU9lVutYI1Co63M8Ux27zD574drsljwAsstjj13Y/cFdlm0EQAqwk6jWd6ysuQMWTKhTF3RmfreKn26PrQlvHtaoOv0J/hso177eIb3Rlxu4U4M4K8Fuq1tpez8JNutyMhUb/0LC6ObetTaE5gMxKv0rBdhcrAjbOHaL/WNqGJCk2X@qkOPnz4aS/4Vj6SKDw/DPZbSb/5IJ2ucDwtpZQrlGIzic3/iNdTCXSrsJNJhClftYy3lC5knIU0PUehxjw0kmvW6LWGIp@uoUPgUoO5/aqbi4c@0vvvdTNS07GIvJDcoiXyr98i29BVONZ88b8XmrBbgXdtWIFz2II1NWcuP8G6mIcCn6aHK44YAneBoNh/lNYsGw/T3JgzRh8S4vvguaoncD4v2K/wprXf7/hNf2C2jyybR2d6z0@B5yBXZpRRB7XPtNLLPdtmsYXfq8PEz/dsm9n@Aw "Python 2 (PyPy) – Try It Online")
Uses pure integer arithmetic, with no loops or branching or built-in complex numbers. This should easily complete the benchmark of 100,000 random inputs within a small fraction of a second. Porting this to a faster language would be straightforward and likely improve performance.
One possible low-level optimization is the [Karatsuba algorithm](https://en.wikipedia.org/wiki/Karatsuba_algorithm) trick to do complex multiplication using 3 rather than 4 integer multiplications. But, this might not be worth it for such "small" values.
] |
[Question]
[
**This question already has answers here**:
[Coding Convention Conversion](/questions/70180/coding-convention-conversion)
(19 answers)
Closed 4 years ago.
# Introduction
All these snakes everywhere! I've had enough, and have decided that I much prefer camels. Therefore, I want you to convert my snakes to camels for me.
# Challenge
Turn any `snake_case` string into a `camelCase` string.
Capitals should be returned to lowercase before the conversion occurs.
# Test Cases
In: `camel_case`
Out: `camelCase`
In: `curse_these_snakes`
Out: `curseTheseSnakes`
In: `i_promise_1234_is_not_my_password`
Out: `iPromise1234IsNotMyPassword`
In: `AAAAA_BBBBB`
Out: `aaaaaBbbbb`
# Rules
As per usual, standard [loophole rules](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default/1789#1789) apply.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") - shortest answer wins.
Leading/trailing underscores (e.g `_string_`) are ignored.
# Current Winners (subject to change)
## Esoteric Language
Me, with -1 bytes.
## Standard Language
Also me, with -2 bytes.
[Answer]
# [Python 3](https://docs.python.org/3/), 51 bytes
```
lambda s:s[0].lower()+s.title().replace('_','')[1:]
```
[Try it online!](https://tio.run/##VYrLDoIwEEX3foW7ttE0Iq5IXOhvIJmMMITGvtKpIXx9hZXhLO7inBuXPAVfl/H@Khbde8AjN9xeOm3DTEmqE@tssiWpdKJosScpQJyFUG3VdCUm47McpejRkYUemYRSh7/@JibIE63LHj/Eu2wgpuDMGqtrfQPD4EMGt0BE5jmkYfd@bMBzY/XlBw "Python 3 – Try It Online")
*-4 bytes thanks to [ReinstateMonica](https://codegolf.stackexchange.com/users/85755/reinstate-monica)*
[Answer]
# [Ruby](https://www.ruby-lang.org/), 39 bytes
```
->x{x.downcase.gsub(/_(.)/){$1.upcase}}
```
[Try it online!](https://tio.run/##VYq9DoIwFEZ3n6IhDu1gCeqqCb7ITSlFG/uXXhoghGevdJMzfMM5X0zdkgfyIPnynNeZ935yUqDib0wdrYFyVrP13PAUit62HMjApTCGVlJYZaDoip3@dIqoYPyofdGJr8JD1hCit3qPzfV2B43g/Ah2gSAQJx/7w7stwKtQsfwD "Ruby – Try It Online")
This does nothing to leading and trailing underscores.
[Answer]
# [Gema](http://gema.sourceforge.net/), 28 characters
```
_?=@upcase{?}
?=@downcase{?}
```
Sample run:
```
bash-5.0$ gema '_?=@upcase{?};?=@downcase{?}' <<< 'i_promise_1234_is_not_my_password'
iPromise1234IsNotMyPassword
```
[Try it online!](https://tio.run/##LchJCoAwEETRfW7jsBWHixRNbDRoBtKKiHj2mIB/UfBqYUspoe@GM2gSfvpXZcz@cj9T0mR5R6HSZxTGsXJecbSxKIMQvTX5qOqmhRE4f8DeCCRy@TirsYSp9AE "Gema – Try It Online")
] |
[Question]
[
**This question already has answers here**:
[Bytes/Character](/questions/83673/bytes-character)
(30 answers)
Closed 4 years ago.
Given a UTF-8 string, give a string that represents byte counts of each characters.
**Rules:**
1. As long as the input string is encoded in UTF-8 **(without BOM)**, its type doesn't matter. In C++, it can be `char[]` or `std::string`. In Haskell, it can be `[Int8]` or `[CChar]`.
2. The output must be (in usual case) a string of ASCII digit characters. Its encoding doesn't matter.
3. When given an invalid UTF-8 sequence (including representation of surrogates), **every bytes** of the sequence are to be represented as the replacement character �.
4. Reserved characters and noncharacters are still considered as valid UTF-8 sequences, and thus must have corresponding output digit.
5. As this is a code-golf, the shortest code in bytes wins.
**Example:**
When given the following byte sequence:
```
00 80 C0 80 EB 80 80
```
The output must be:
```
1���3
```
[Answer]
# [Python 3](https://docs.python.org/3/), 135 bytes
```
def f(b):
B=b.decode(errors="ignore")[:1].encode();l=len(B)
if B and b[:l]!=B:return"�"+f(b[1:])
return str(l)+f(b[l:])if b else''
```
[Try it online!](https://tio.run/##RYxBCoMwEEXXeoqYTRIKokihpGSTUugd1IWasbWERKIFe7jSI/UIadBCF8OH9/6f8TnfrCm8V9CjnraMx5EUbaqgswooOGfdJPBwNdYBZiXP6xTM6thRCw2GShZHQ48kaoxCbcl1nQjJHcwPZ/Dn/cK78LfMeR16G0XT7KhmK9eBh3WLQE9AiB/dYGYaDKmWLKuWQ7jTL89yy0NGGIv/zQvckaqWrqiWZp8E578 "Python 3 – Try It Online")
Explanation:
```
def f(b):
B=b.decode(errors="ignore")[:1].encode();l=len(B)
# B is the UTF-8-encoded version of the first Unicode character in the given bytes
# (Or the Nth, if the first N-1 bytes were invalid Unicode bytes)
if B and b[:l]!=B:return"�"+f(b[1:])
# If the two encoded byte-strings don't match,
# then the first byte in b is invalid,
# so append "�" to the returned string, and recurse
return str(l)+f(b[l:])if b else''
# If the byte-string is not empty,
# append the length of the first character and recurse.
# Else (the input is empty) return the empty string (recursion base case)
```
] |
[Question]
[
What are some tips for golfing in [Turing Machine But Way Worse](https://github.com/MilkyWay90/Turing-Machine-But-Way-Worse), a language made by [MilkyWay90](https://codegolf.stackexchange.com/users/83048/milkyway90) and [ASCII-only](https://codegolf.stackexchange.com/users/39244/ascii-only)?
Tips should be Turing Machine But Way Worse-specific and not be trivial (For examples that you shouldn't post, removing unnecessary whitespace or using shorter state names).
EDIT: Added documentation to TMBWW
[Answer]
# Use the negative tape
For code-golf questions where you need to process input, it is easier to move onto the negative tape to push a bit to the tape instead of having to travel to the end of the input on the positive tape (and sometimes that way may even be impossible when you need to support NUL bytes).
For example, when you need to push to the tape and you have input, going on the negative tape would be much shorter than having to go to the end of the input.
```
0 0 0 0 1 0 0
1 0 1 0 1 0 0
0 1 0 0 2 1 1
```
would be much shorter than
```
0 0 0 1 1 0 0
1 0 1 1 0 0 0
0 1 0 1 2 0 0
1 1 1 1 0 0 0
0 2 0 1 3 0 0
1 2 1 1 0 0 0
0 3 0 1 4 0 0
1 3 1 1 0 0 0
0 4 0 1 5 0 0
1 4 1 1 0 0 0
0 5 0 1 6 0 0
1 5 1 1 0 0 0
0 6 0 1 7 0 0
1 6 1 1 0 0 0
0 7 0 1 8 0 0
1 7 1 1 0 0 0
0 8 0 0 9 0 0
0 9 1 0 a 1 1
```
and the second solution doesn't even work with NUL bytes.
] |
[Question]
[
This question was inspired by Tom Scott's video [here](https://www.youtube.com/watch?v=zp4BMR88260 "Tom Scott").
The English language has plenty of words, but what's the longest one that can be displayed on a seven segment display? Your challenge is given a list of letters that may **not** be displayed, display the longest [English](https://github.com/dwyl/english-words/blob/master/words.txt "English dictionary") word in a 7 segment display format?
# Input
* Input will contain a series of unacceptable characters. (letters that you are **not** permitted to use in your word.)
* Input can be taken from one of the following:
+ `stdin`
+ command-line arguments
+ function arguments
# Output
* Output the longest word using the provided alphabet from the input. (In the case of 2 words of the same length, the one that comes first is the "longest". When a hyphen is in the word, it counts towards its length, but is not displayed.)
* Output must be formatted like a [7 segment display](https://tio.run/##pVVRb9owEH5OfoWVPpTQrQrtuk3VmFQS2h@wR4QmAyZxCXbqmFKq/XfmO8cWaSpWNBQSfffd3Xc525dqpwsprvf7M6ILRiolc0XXRNMVqwkXhJKS15rIJSmZ1kzVhIoFWfC6Kumuhpg1uNXsmcE9XzOhHU2WUq2pDkO@rqTSRLMXvVW0CsN5Sevaud2GwZnR@ebDeU1mSq5MQi60dOaa3BGDHtC7rAoKflDzjAuqdqTWVDMo9I0/VGHS5xwqtC8RBjbBkEzCIBoMBon5R5/IGTUwAWDhDFjECcA5sAN0B7jwLEJmoUu1RDhwsbnN7NgCITgjy31mhI821jmvrLNLVTrWOq/9KyAUFjpnidBXVTXOiYVPnkVn1dTcsLXXRahdkdZ508DEwmeEiYNbyzrdF@@McGd1QRngaxhMwyAMFmzpNsUvrbjIezU@YrNFAiW3d8MoMp0163nnV9kyI8/c4wYdveFTzz84xhKZJ8YYmL4JHHs@Owg0F5jsbsL9j3VCmUFjHBKpFj0LLku5ZaoXx@QzWiMaxWal5Bb3bxNQcmGO3KYiW64LJHCTzhgIBnxJmmQ/EuKlf5ZM9JqOXaJ7HN@aVVZwHM0JEFL4LGReUEXneIZ1oeQmLyBxMJdCc7FhAJxSNIiGw1beiRWcTpIpKPizeoc5YG0uhiTq93@bX78fgZWVNbs9pL/3I8t8QOamLXPv8oxQ5k8/IhcgZ9YGOnVF6orOTfuoYjA0TAiXgpadMiD8xpXxjxIG7RJGnRLezX59wkt@bSs8uDzp8V6mJ/byS1tm7PJk/9fL7IReXrVLSDslvJv9lF5etxUyl2d8vJfjg16a6/z83Nwrc5h1D3ZtfIhGR1DaQtkRNI69jptq7sN4CTevi2OtQ41iN9E6VBq7mdahstiNsw6F9TQDjcMsU1TkrAeTBSvB4XvQkgmfxi3L6AOWtGPJPmAZoyV0C97@NHBRbbSZqfs9nc3NlyMv@OOqXAtZPalab563L7vXvw "Python 3 TIO program"), see the rules below for more about the format.
* Output must be in stdout or closest equivalent.
* Output may contain a trailing newline character.
# Letters

This image shows my source of the alphabet
Here is my simple [ascii display](https://tio.run/##pVVRb9owEH5OfoWVPpTQrQrtuk3VmFQS2h@wR4QmAyZxCXbqmFKq/XfmO8cWaSpWNBQSfffd3Xc525dqpwsprvf7M6ILRiolc0XXRNMVqwkXhJKS15rIJSmZ1kzVhIoFWfC6Kumuhpg1uNXsmcE9XzOhHU2WUq2pDkO@rqTSRLMXvVW0CsN5Sevaud2GwZnR@ebDeU1mSq5MQi60dOaa3BGDHtC7rAoKflDzjAuqdqTWVDMo9I0/VGHS5xwqtC8RBjbBkEzCIBoMBon5R5/IGTUwAWDhDFjECcA5sAN0B7jwLEJmoUu1RDhwsbnN7NgCITgjy31mhI821jmvrLNLVTrWOq/9KyAUFjpnidBXVTXOiYVPnkVn1dTcsLXXRahdkdZ508DEwmeEiYNbyzrdF@@McGd1QRngaxhMwyAMFmzpNsUvrbjIezU@YrNFAiW3d8MoMp0163nnV9kyI8/c4wYdveFTzz84xhKZJ8YYmL4JHHs@Owg0F5jsbsL9j3VCmUFjHBKpFj0LLku5ZaoXx@QzWiMaxWal5Bb3bxNQcmGO3KYiW64LJHCTzhgIBnxJmmQ/EuKlf5ZM9JqOXaJ7HN@aVVZwHM0JEFL4LGReUEXneIZ1oeQmLyBxMJdCc7FhAJxSNIiGw1beiRWcTpIpKPizeoc5YG0uhiTq93@bX78fgZWVNbs9pL/3I8t8QOamLXPv8oxQ5k8/IhcgZ9YGOnVF6orOTfuoYjA0TAiXgpadMiD8xpXxjxIG7RJGnRLezX59wkt@bSs8uDzp8V6mJ/byS1tm7PJk/9fL7IReXrVLSDslvJv9lF5etxUyl2d8vJfjg16a6/z83Nwrc5h1D3ZtfIhGR1DaQtkRNI69jptq7sN4CTevi2OtQ41iN9E6VBq7mdahstiNsw6F9TQDjcMsU1TkrAeTBSvB4XvQkgmfxi3L6AOWtGPJPmAZoyV0C97@NHBRbbSZqfs9nc3NlyMv@OOqXAtZPalab563L7vXvw "Python 3 TIO program") so you can visually see the letters (my apologies, the wrap function I used broke with spaces so I had to settle on asterisks).
And here is a table to show the alphabet as well:
```
____ A
| F | B
| |
____ G
| |
| E | C
____ D
ABCDEFG Letter
1110111 a
0011111 b
1001110 c
0111101 d
1001111 e
1000111 f
1011110 g
0010111 h
0000110 i
0111100 j
1010111 k
0001110 l
1010100 m
1110110 n
1111110 o
1100111 p
1110011 q
1100110 r
1011011 s
0001111 t
0111110 u
0111010 v
0101010 w
0110111 x
0111011 y
1101001 z
```
# Rules
* [Standard loopholes are disallowed](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) HOWEVER words.txt (the dictionary) is the only outside [file](https://github.com/dwyl/english-words/blob/master/words.txt "English dictionary") you may reference (renaming it is not allowed, it **must** be called `words.txt` as it is in the repository).
* The seven segment display must:
+ Be an actual seven segment display. (I'm not going to be picky on how it looks, if it was accepted over [there](https://codegolf.stackexchange.com/questions/9266/emulate-a-7-segment-display) then it's accepted over here.)
+ Have any filler/whitespace character of choice.
# Test Cases
Wrapping is an unnecessary challenge and is not needed; I did it out of ease of looking at it in my terminal.
Remember: Your *whitespace* does not need the same character.
```
input:
gkmqvwxz
output:
******************____********************____****____****____********
******|**|*******|*******|*******|*******|****|**|****|**|****|*******
******|**|*******|*******|*******|*******|****|**|****|**|****|*******
**____********************____************************************____
*|****|**|*******|*******|****|**|*******|****|**|*******|****|**|****
*|****|**|*******|*******|****|**|*******|****|**|*******|****|**|****
**____************____************____****____************____****____
************____************____****____****************************__
|**|*******|****|**|*******|*******|****|**|****|**|*******|*******|**
|**|*******|****|**|*******|*******|****|**|****|**|*******|*******|**
************____****____****____************____************____******
|**|*******|*******|****|**|*******|****|*******|**|*******|*******|**
|**|*******|*******|****|**|*******|****|*******|**|*******|*******|**
****************************____************____****____****____******
__************____********************____****____****____****____****
**|**|*******|*******|*******|*******|****|**|****|**|****|**|*******|
**|**|*******|*******|*******|*******|****|**|****|**|****|**|*******|
**********************____************************************____****
*****|*******|*******|****|**|*******|****|**|*******|****|**|*******|
*****|*******|*******|****|**|*******|****|**|*******|****|**|*******|
**************____************____****____************____****____****
****************____****____****____**
*******|*******|****|**|****|**|******
*******|*******|****|**|****|**|******
____****____****____************____**
*******|****|**|****|**|****|**|******
*******|****|**|****|**|****|**|******
____****************************____**
```
The word should be "dichlorodiphenyltrichloroethane" for debugging purposes.
```
input:
gkmqvwxzio
output:
**____************____****____****____************____****____****____
*|*******|****|**|****|**|*******|****|**|*******|****|**|****|**|****
*|*******|****|**|****|**|*******|****|**|*******|****|**|****|**|****
**____************____****____************____************____********
******|**|****|**|*******|*******|*******|*******|*******|****|**|****
******|**|****|**|*******|*******|*******|*******|*******|****|**|****
**____****____************____************____************************
****____****____****____****____************____****____************__
|**|*******|*******|*******|****|*******|**|*******|****|**|*******|**
|**|*******|*******|*******|****|*******|**|*******|****|**|*******|**
****____************____************____****____************____******
|*******|**|*******|*******|****|**|****|**|*******|****|**|*******|**
|*******|**|*******|*******|****|**|****|**|*******|****|**|*******|**
****____****____****____************____****____************____******
__****____****____****____**
**|**|*******|*******|******
**|**|*******|*******|******
******____****____****____**
**|**|************|*******|*
**|**|************|*******|*
******____****____****____**
```
The word should be "supertranscendentness" for debugging purposes.
```
input:
abcdefghijklm
output:
**********____****____************____********************____****____
*|*******|****|**|****|**|*******|*******|****|**|****|**|****|**|****
*|*******|****|**|****|**|*******|*******|****|**|****|**|****|**|****
**____********************____****____****____************************
*|*******|****|**|****|**|************|*******|**********|****|**|****
*|*******|****|**|****|**|************|*******|**********|****|**|****
**____****____****____****____****____****____****____****____****____
************____**********
|**|*******|*******|****|*
|**|*******|*******|****|*
****____****____****____**
|**|************|*******|*
|**|************|*******|*
****____****____****____**
```
The word should be "tootsy-wootsy" for debugging purposes. (We do not output the hyphen but it does count towards the length of the word.)
```
input:
ikmopqsvwz
output:
**____****____****____****____************____****____****____****____
*|*******|****|**|*******|****|**|*******|*******|****|**|****|**|****
*|*******|****|**|*******|****|**|*******|*******|****|**|****|**|****
******************____****____****____********************____********
*|****|**|*******|*******|****|**|*******|****|**|*******|****|**|****
*|****|**|*******|*******|****|**|*******|****|**|*******|****|**|****
**____************____************____****____************************
********************____************____********************____****__
|*******|*******|**|****|**|****|**|*******|*******|*******|*******|**
|*******|*******|**|****|**|****|**|*******|*******|*******|*******|**
****____****____****____********************____****____****____******
|**|****|**|****|**|****|**|****|**|****|**|****|**|*******|*******|**
|**|****|**|****|**|****|**|****|**|****|**|****|**|*******|*******|**
****____****____************____****____************____****____******
__**
**|*
**|*
****
****
****
****
```
The word should be "great-granddaughter" for debugging purposes. (We do not output the hyphen but it does count towards the length of the word.)
# Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest submission (in bytes) wins.
(This is also my first question so tell me if I skipped over something or something is unclear or not. Thanks and good luck!)
[Answer]
# JavaScript, 830 characters, oooooof
**Edit: I fixed the issue and ignore my previous edits where I started I found an error, I was sanitizing the dictionary incorrectly. Funny enough, this didn't change the code length**
Anyways, someone had to do this challenge. If winning only requires the shortest, it's always possible to win by default, right? :P
```
var q=new XMLHttpRequest();q.open("get","words.txt");q.onreadystatechange=()=>{if(q.readyState!=4)return;(z=>q.responseText.toLowerCase().split("\n").filter(w=>w.split("").reduce((j,l)=>j&&z.indexOf(l)<0,true)).map((o,p)=>[o,p]).sort((a,b)=>{if(a[0].length == b[0].length){return a[1]-b[1]}return b[0].length-a[0].length;})[0][0].split("").forEach(e=>e=e.replace(/[^a-z]/,"")&&console.log(("ABCEFGCDEFGADEFBCDEGADEFGAEFGACDEFCEFGEFBCDEACEFGDEFACEABCEFABCDEFABEFGABCFGABEFACDFGDEFGBCDEFBCDFBDFBCEFGBCDFGABDG".split("").reduce((f,v,i)=>{if(i==114){f[0].unshift(v);f[1].push(f[0])}else if(v<f[0][0]){f[1].push(f[0]);f[0]=[v]}else{f[0].unshift(v)}return f},[[0],[]])[1][e.charCodeAt()-97]).reduce((f,v)=>f.replace(RegExp(`${v}`,"g"),"#"),"-AAA-\nF---B\nF---B\n-GGG-\nE---C\nE---C\n-DDD-").replace(/[^#\n]/g,"-"))))(prompt())};q.send()
```
Basically, how it works is, there's an output string that encodes segments for letters, and a format string, that the output string is applied onto.
Here's a version that labels these variables and is a bit less... Harsh.
It skips functions entirely and recalculates variables for any place they are iterated, so it's very inefficient, but it should never take more than a few seconds at worst case to run. Input is given through an html prompt. The script assumes it is part of a window with relative file access and outputs to the console.
```
const outputString = "ABCEFGCDEFGADEFBCDEGADEFGAEFGACDEFCEFGEFBCDEACEFGDEFACEABCEFABCDEFABEFGABCFGABEFACDFGDEFGBCDEFBCDFBDFBCEFGBCDFGABDG";
const formatString = "-AAA-\nF---B\nF---B\n-GGG-\nE---C\nE---C\n-DDD-";
var q=new XMLHttpRequest();
q.open("get","words.txt");
q.onreadystatechange=()=>{
if(q.readyState!=4)return;
(z=>q.responseText.toLowerCase().split("\n").filter(
w=>w.split("").reduce((j,l)=>j&&z.indexOf(l)<0,true)
).map(
(o,p)=>[o,p]
).sort(
(a,b)=>{
if(a[0].length == b[0].length){
return a[1]-b[1]
}
return b[0].length-a[0].length;
}
)[0][0].split("").forEach(
e=>e=e.replace(/[^a-z]/,"")&&console.log(
(outputString.split("").reduce(
(f,v,i)=>{
if(i==114){
f[0].unshift(v);f[1].push(f[0])
}else if(v<f[0][0]){
f[1].push(f[0]);f[0]=[v]
}else{
f[0].unshift(v)
}return f
},[[0],[]]
)[1][e.charCodeAt()-97]).reduce(
(f,v)=>f.replace(RegExp(`${v}`,"g"),"#"),formatString
).replace(/[^#\n]/g,"-"))
))(prompt())
};
q.send()
```
These particular seven segment display codes for the alphabet (for example, 0101100) can't overlap when you remove their zeroes. What I mean by that is for each index of the string if you were to encapsulate that spot, chaining all the strings together never results in a case that the last index of a display code is lower than the first index of the following code. This isn't particularly true of all display code permutations and orderings, but in this case it was so we use that.
I haven't double checked because I got so, um, involved in this code, but I think that it might be smaller to store these modified display codes in a flat array than to break them into an array based on one string. But that wasn't as fun.
I don't expect to win, but I am curious if anyone else can beat this in web-oriented JavaScript using an `XMLHttpRequest` and `prompt()` for input.
[Answer]
# PHP, 292 bytes
```
foreach(file("words.txt")as$w)preg_match("%[$argn]%i",$w)||$e<($n=strlen($w=trim($w)))&&$s=strtoupper($w.$e=$n;for($r=["
","
","
"];$i<$e;$b&&$k+=4)for($b=ord("}7f\37vtg5$\17u&Emo|yls6/+*=;Z"[ord($s[$i++])-65]),$p=7;$p--;)$b>>$p&1&&$r[(8-$p)/3][$k+$x="3213212"[$p]]="_|"[$x&1];echo join($r);
```
Run as pipe with `-nr` or [try it online](http://sandbox.onlinephpfunctions.com/code/2919c35d086eb118b5f680c7a5d589606b21e7f0) (with a much smaller dictionary).
In case you run out of memory, replace `foreach(file("words.txt")as$w)` with `for($f=fopen("words.txt",r);$w=fgets($f);)`. This will also improve performance a lot.
**breakdown**
```
foreach(file("words.txt")as$w) # 1. loop $w through words
preg_match("%[$argn]%i",$w)|| # if there are forbidden characters, skip
($e<$n=strlen($w=trim($w))) # if length $n exceeds current max length $e
&&$s=strtoupper($w) # then update longest word $s
.$e=$n; # and max length
for($r=["\n","\n","\n"]; # 2. init my ouput buffer
$i<$e; # 3. loop through word characters
$b&&$k+=4) # 3. if previous char was legal, increment output offset
for( # 1. get bit mapping for character: (none for non-letters)
$b=ord("}7f\37vtg5$\17u&Emo|yls6/+*=;Z"[ord($s[$i++])-65]),
$p=7;$p--;) # 2. loop through bits
$b>>$p&1&& # if bit $p is set,
$r[(8-$p)/3][$k+$x="3213212"[$p]] # then map bit no. to segment coordinates
=$x&1?d|t:_; # and draw the according character
echo join($r); # 4. print my output buffer
```
**notes**
* I could lose 11 bytes if the dictionary contained only letters, space and linebreaks
OR 12 if only all letters were uppercase. Dang!
* I could paint every "longest" word; the last will remain in the buffer for printing; that would mean I wouldn´t have to copy `$w` to `$s` and I could copy `$n` to `$e` in the character loop, but I would need `if(!preg_match(...)&&$e<$n=strlen(...))` and I had to reset `$i=$k=0`; that would eat up all the savings.
I could do `!$i=$k=preg_match(...)` but that would require extra parentheses - no savings either.
Makes me almost wish that we also had to paint the digits.
* Painting the whole thing into a single string instead of an array would save five bytes in the painting, but cost nine in the output.
] |
[Question]
[
A [spoonerism](https://en.wikipedia.org/wiki/Spoonerism) is what you get when swap the beginnings of two adjacent words in a sentence. In this challenge, we'll try to find a plausible spoonerism based on one incorrect word.
So, given a list of words\*\* and an input word that is **NOT** in the dictionary, return a string (not necessarily a dictionary word) for which the following property holds.
There exist some indices `i` and `j` such that `input_word[:i] + output_word[j:]` and `output_word[:j] + input_word[i:]` are **BOTH** in the dictionary. Here, I'm using Python notation for substrings: `word[lo:hi]` is the substring of word starting at `lo` and ending at `hi-1`. `[:hi]` is shorthand for `[0:hi]` and `[lo:]` is shorthand for `[lo:len(word)]`.
\*\* Say, those in the `/usr/share/dict/words` provided by the `wamerican` package in Ubuntu 16.04
An example is in the title:
```
input_word = "roonerisms"
output_word = "speverse"
i, j = 1, 2
print(input_word[:i] + output_word[j:])
print(output_word[:j] + input_word[i:])
```
You can assume that everything is lowercase and the dictionary is preprocessed to contain only letters a-z and newlines. You can take the list in whatever standard format you like (eg. sorted list, set, etc. not a preprocessed lookup table) and you need only return one string, not all of them.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~154~~ ~~161~~ ~~157~~ 155 bytes
```
def f(s,d):L=len(s);u,v=sum((zip([w[i:]for w in d if w[:i]==s[:i]],[[w,w[:i-L]][i<L]for w in d if w.endswith(s[i:])])for i in range(L+1)),[])[0];return v+u
```
[Try it online!](https://tio.run/##XZFRjtwgDIafm1NYWqkELc20u2@zzZ5gbkBRRYqzoU0gwhA0vXwKGXWn6gsWv39/tmG9xsm7p303OMLYkjD8fOlndC3xlyS2ntLStr/t2sos7VmNPkAG68CAHSHLs1V9TzUoIWUWVfl0UUrar5f/zR06Q9nGqaWK4opXg62GoN0btpfHL5wLqbj8rF4CxhQcbI9przXg1zIUOyUKJ5p0wJOxP@Ip@2CIcdAEebQznpsPhwT97d4F1KblHa2zjS375hhvmgeYMTKCRf9CiJMloKid0cFAhVrvdLiChsFGWHzAMmHEgBSte4PhCjjbxTp9XKkcM1ZgsRAUDCyJIkx6w4LYfMa567rm71Qyw/uz3LTyNISxzfxjDUyj9aluVEj1HzJ/fVZNs4YyRPkhpjUTspwDE2wYmOLwUFhrit8rDo48@BT/VYpPgO2fBPzsn6F/hVv9LdzRwXuHwdJCtUXArWyEpQ2t90Tpdy8YkqMJQyEdq9RRDB6SgCHp@e6kNeh5rtZ3J7o43UQBtGptmn3/Aw "Python 2 – Try It Online")
For the testing, uses the 'standard' dictionary with some tweaks (because that dictionary includes single letters, it makes for a lot of boring results).
2 bytes thx to [Jakob](https://codegolf.stackexchange.com/users/44945/jakob).
] |
[Question]
[
**This question already has answers here**:
[Rational Polynomial Interpolation](/questions/151436/rational-polynomial-interpolation)
(3 answers)
Closed 5 years ago.
# Introduction
A sequence of numbers is passed in as the input. The program has to generate the lowest degree polynomial possible. This was my first programming project in college and it would be interesting to see how much smaller the solution could have been.
# Challenge
The input is a list of integers separated by a comma. The output is simply the equation that generates that sequence. The exact output of the equation is up to you i.e. no spaces are required between terms of the polynomial but it has to be human readable. The equation has to be expressed with the variable x. The first integer in the supplied sequence will correspond with x = 1, the second integer supplied would be x = 2 etc.
i.e.
>
> x^2
>
>
>
would result in the sequence
>
> 1,4,9,16 NOT 0,1,4,9
>
>
>
# Example Input and Output
Input:
>
> 5,14,27,44
>
>
>
Output:
>
> 2x^2 + 3x
>
>
>
# Edit
I marked the questions as duplicate, thanks for the head up.
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 28 bytes
```
l->polinterpolate([1..#l],l)
```
[Try it online!](https://tio.run/##K0gsytRNL/ifpmCr8D9H164gPyczryS1CEgnlqRqRBvq6SnnxOrkaP4vKAJKaKRpRJvqGJroGJnrmJjEamr@BwA "Pari/GP – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 30 bytes
```
InterpolatingPolynomial[##,x]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73zOvJLWoID8HKJCXHpCfU5mXn5uZmBOtrKxTEav2P6AoM68k2rWiIDEvJTotutpUx9BEx8hcx8SkNjY29j8A "Wolfram Language (Mathematica) – Try It Online")
] |
[Question]
[
**Yabasic**, or **Y**et **A**nother **Basic** is a dialect of [basic](/questions/tagged/basic "show questions tagged 'basic'") created by Marc-Oliver Ihm that may be run on Windows, Unix and PAL versions of the Sony PlayStation 2. Development for this language is ongoing.
>
> **Helpful Resources**
>
>
> [Yabasic Official Website](http://www.yabasic.de/)
>
>
> [Yabasic Manual](http://www.yabasic.de/yabasic.htm)
>
>
> [Yabasic Wikipedia Page](https://en.wikipedia.org/wiki/Yabasic)
>
>
> [Yabasic GitHub](https://github.com/marcIhm/yabasic/)
>
>
> [Yabasic PS2 Documentation](http://members.chello.nl/~a.vanarum8/Yabasic/)
>
>
> [Some Yabasic Programs](http://www.mrdictionary.net/yabasic/)
>
>
> [Try it Online](https://tio.run/#Yabasic)
>
>
>
What general tips do you have for golfing in Yabasic? Any ideas that can be applied to code golf problems in general that are at least somewhat specific to Yabasic. Please post one tip per answer.
[Answer]
# Use `Chr$(...)` to Print numbers
By default, all numbers printed using Yabasic print with a space following them, and to remove this space **while printing characters individually**, one may use the formula below.
It is important to note that this only works for printing digits `0` - `9`, meaning that this works best for iterating across numbers digit by digit.
```
...
?Left$(Str$(n),1);
...
```
[Try it online!](https://tio.run/##q0xMSizOTP7/3y2/SCHTVtciJF/BggvEyYJwLLmybR2TijUyNbVBVJYml2eaQradRUhGap69koKSNZdrTnGqvU9qWomKRnBJkYqGpW62po6hpjWXWyaXX2pFCZc9mPr/HwA "Yabasic – Try It Online")
However, if the context allows, this can be golfed down to this formula.
```
...
?Chr$(n+48);
...
```
[Try it online!](https://tio.run/##q0xMSizOTP7/3y2/SCHTVtciJF/BggvEyYJwLLmybR2TijUyNbVBVJYml2eaQradRUhGap69koKSNZdrTnGqvXNGkYqGqblutqY1l1sml19qRQmXPZj6/x8A "Yabasic – Try It Online")
[Answer]
# Use `?n,"",m` to print two numbers without spaces
Given two numeric variables `n` and `m`, they may be printed directly beside one another (as if concatenated) by formatting the print statement as
```
?n,"",m
```
which is significantly shorter than direct concatenation, which would require converting the numeric to a string with something of the form of
```
?Str$(n)+Str$(m)
```
[Answer]
# Use `?` Instead Of `Print`
Much like many dialects of BASIC, such as VBA and uBasic, Yabasic allows for the use of the `?` Character for printing to the console in place of the `Print` keyword.
In addition you may use `;` to print without any trailing newline or other characters.
Each use of this saves 5 bytes.
[Answer]
# Use `Fi` Instead of `EndIf`
Much like Bash and other languages, Yabasic has the keyword `Fi` that allows for the termination of `If(...)Then` blocks.
Each use of this saves 3 bytes.
[Answer]
# Use abbreviated `Print At(x,y)"..."`
Because [yabasic](/questions/tagged/yabasic "show questions tagged 'yabasic'") has no string repetition or replacement function built, it is often more efficient to convert an answer to graphics mode and use the [`Print At()`](http://www.yabasic.de/yabasic.htm#ref_at "Print At() command - Yabasic Manual") command than to deal with using for loops to determine spacing.
This may be abbreviated as
```
?@(x,y)"your text"
```
This may also be combined with the color modifier of the print statement to make statements such as
```
?Color("Blu")@(x,y)"your text"
```
it is however noted that use of this command requires that the `clear screen` command has been called at least one in the solution.
An example of a yabasic solution using the `?@()` may be seen [here](https://codegolf.stackexchange.com/a/156909/61846 "Alphabet Cannon Solution")
[Answer]
# Use `n/0`, `inf` and `nan`
While not included in the [Yabasic Manual](http://www.yabasic.de/yabasic.htm) (at present), yabasic includes some interesting edge cases for numbers, namely, allowing for division by zero, infinite values and `nan`s.
### Division by Zero
```
n/0
```
Regardless of the input value the output of the above snippet shall be exactly equivalent to `2^1024`. Interestingly, this includes negative inputs, `inf`inite inputs and `nan` inputs.
### Infinity
```
9^999
```
If you try to use too large a value, then Yabasic will convert it to `inf`. As far as I am aware, the above is the shortest snippet that may be used to access `inf`, as `inf` may not be called directly. This behaves as expected.
### Not a Number
```
n=9^999
?n-n
```
If you try to take an infinite number from an infinite number, Yabasic will return `nan` (**n**ot **a** **n**umber).
[Try it online!](https://tio.run/##JY27CsMwDEV3f4XJlAemdujiggmUdOjQDB06dAhIxgVBSCAJhXy9K1EQB3F1JB2AsFHM@Xl76BesBDgl3acIE6yw0zIrCPZkFQY/eu9VDKZEg5VSXdHTlzZW9PXQ77Qul0J1wMV6Z5wQBVEAoeS8kqYdnW3P4rEsd@7zh2baD97nFRkwXC1oBAb/3gCDvIhcNQg4j43L@Qc "Yabasic – Try It Online")
] |
[Question]
[
If you're sad, that's *wrong*. We need to scrub out ALL sadness.
This is a sad face, for reference:
```
......
.S..S.
........
...SS...
..SS..SS..
.S......S.
........
```
Where `S` is a consistent pixel, `.` is any pixel other than `S`, and is any pixel. Note that the sad face is not a perfect square, only the `.` should be considered. Theoretical sad face overlap in the corners is possible, but overwriting one sad face has a chance to eliminate the other, e.g. if it was in a `.` character and is overwritten with an `S`.
# Input
An image, in [any acceptable format](https://codegolf.meta.stackexchange.com/q/9093/62402). I would recommend a color matrix.
# Output
The same image, but take all those *treasonous* sad faces and replace their `S` characters with randomized data. The data should be either random RGB values, or values taken from the palette of the image. You just need to have a nonzero probability of all outputs; you do not need to make it uniform.
# Rules
* `S` can be any pixel, as long as it's the same pixel throughout the formation.
* Remove ALL sad faces. If the removal makes a new sad face, then remove that too.
* You should only modify `S` pixels. Unauthorized modification of pixels is insubordination, punishable by disqualification.
* The shortest answer in bytes wins.
# Test Cases
These have one sad face each:
* [](https://i.stack.imgur.com/VjCEM.png)
* [](https://i.stack.imgur.com/nMh01.png)
This has 2 sad faces, on the left and right:
[](https://i.stack.imgur.com/66bKl.png)
This has 2 sad faces overlapping:
[](https://i.stack.imgur.com/cCgmR.png)
This has 2 sad faces, in the top-left and bottom-right; the bottom-left and top-right have `S` characters in the place of `.` characters:
[](https://i.stack.imgur.com/3fFq2.png)
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~339~~ ~~337~~ ~~331~~ 323 bytes
* Saved ~~two~~ ~~eight~~ ~~fifteen~~ sixteen bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat).
```
C,a,l,A,m,i,t,o,u,s;n(e,z,Z)int*e;{for(C=1;C;C+=i)for(C=s=0;s<Z;s++)for(u=0;u<z;u++)if(u>8&s>5)for(m=e[~-u+~-s*z],A=i=1;++A<4;)for(o=0;o<7;o++)for(t=0;t<10;t++)a=e[l=u+t-9+(s+o-6)*z],(o-1||t-3&&t-6)*(o-3||t<4|5<t)*(o-4||t<2|3<t&t<6|7<t)*(o-5||t-1&&t-8)?o>1|t>1&t<8&o<2|o>3&o<6|t&&t<9&&(i*=a-m):A<3?i*=a==m:i?e[l]=rand():e;}
```
[Try it online!](https://tio.run/##rVRdU@owEH1uf0Xkzq1JmyKVT0lShvLkMw/O6PDQwSKdsY1D0wG0@NdxUxBQuei9cwOE3bNnz6ZJs2P3YTxerwc0pI@0TxMaU0UlzWnGUhzRZ3pL4lTZEXuZyBkeCI8N2MARMdm4maixjN@yzHFKJAc/588sBz@e4NzvWJnfLEOJiO5e3dx5dTP7eUT7IgYxx@nzBivjElIlbzO5lVLgK@7BBEAIyY8id5R75eDMkW6LaBEsXa8olFu3LKUh8Ovg80bR5Kp0G9q9LOpcWYq3ivYWbuosT2d1SE/6XqF8DwgdSwJZ@nX4bxUK4vzKsnBsi9BNSLfP6z1tC5F04x6saCRmYXqPSTdiq/WFbSJULQdC2hxW4avN6nZszOGwNDeG/pmaqcewesi1L8wkjFNMXkxDn8E1ndMpK210I2qLSTloAPtkGim@FhgidyNNN27od58dKTiY/0j6kZJWCU6Tgl254EjxkvRRIfj5moKD8kdJn4sfIX0t/rdbcJJkGis6F16bToXnETg209Cvuj7RJRzjkk/ZU64yXKkQutzeAx1cQHDB52wB2NMMkAmu/K51FqhCr@8WztKej8guk/2D6IsGxuJdDCQMuL5jIS4J5I6n4Qyfn51raSN6zCK0Cb6/g3sO@srZB38dBHdgD8CVuTLNCxsJIdBgGqYPUYaS8D7SgGkO8wcAFPpPl51fWlizlN8mcNU9C0uQkNClNK47QYcUxfE7D73g4NYTFKeZisJ7JCdICgFSSoh6AVMLpMEEAHpJy1el29CuZzV8BUWaVmcLN8s0T6fB@k7V6@Ld6k8uv1y/JcIzkZD9/n3X5j48zc92aS/@sR3WDrU@P4UJnW39Bg "C (gcc) – Try It Online")
] |
[Question]
[
**This question already has answers here**:
[A subset of Verbal arithmetic](/questions/1680/a-subset-of-verbal-arithmetic)
(5 answers)
Closed 6 years ago.
## Task
The letters spell out actual words, but if you replace each letter with a digit from 0–9, it also “spells” an arithmetic equation. The trick is to figure out which letter maps to each digit. All the occurrences of each letter must map to the same digit, no digit can be repeated, and no “word” can start with the digit 0.
# Input
```
HAWAII + IDAHO + IOWA + OHIO = STATES
```
# Output
```
510199 + 98153 + 9301 + 3593 = 621246
```
# Input
```
I + LOVE + YOU = DORA
```
# Output
```
1 + 2784 + 975 = 3760
```
# Input
```
SEND + MORE = MONEY
```
# Output
```
9567 + 1085 = 10652
```
# Rules
* Standard [loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply.
* shortest code wins.
* addition only
# Appendix
for other Inputs you gotta keep in mind you can only have 10 different characters(to assign values 0-9)
[Answer]
# JavaScript (ES7), 104 bytes
```
f=(s,o,c=s.match(/[A-Z]/))=>c?[...2**29+'4'].some(i=>o&1<<i?0:f(r=s.split(c).join(i),o|1<<i))&&r:eval(s)
```
### Demo
```
f=(s,o,c=s.match(/[A-Z]/))=>c?[...2**29+'4'].some(i=>o&1<<i?0:f(r=s.split(c).join(i),o|1<<i))&&r:eval(s)
console.log(f('I + LOVE + YOU == DORA'))
```
### Formatted and commented
```
f = ( // f = recursive function taking:
s, // s = input string
o, // o = bitmask of used digits
c = s.match(/[A-Z]/) // c = next alphabetical character in s
) => // (either null or a single-element array)
c ? // if c is not null:
[...2**29 + '4'].some(i => // for each character i of '5368709124'
o & 1 << i ? // if this digit was already used:
0 // ignore this iteration
: // else:
f( // do a recursive call to f() with:
r = s.split(c).join(i), // all characters c replaced with i
o | 1 << i // the updated bitmask
) // end of recursive call
) && r // end of some(): if successful, return r
: // else:
eval(s) // evaluate this fully numerical expression
```
] |
[Question]
[
**This question already has answers here**:
[Levenshtein Distance](/questions/67474/levenshtein-distance)
(23 answers)
Closed 6 years ago.
>
> Oops, Auto-correct.
>
>
>
You have a word. But it's wrong. You wonder what word it would be. Thankfully, being a code golfer, You can make a code to take a rough guess.
# I/O
You will be given a (wrong, all lowercase) word, and a ['(All lowercase)Dictionary list'](http://www.mieliestronk.com/corncob_lowercase.txt "Example. I'll only use a part of it in each example."). You have to output the word with the least Levenshtein distance to the wrong word. If there are multiple words of the same levenshtein distance, use the last one in the list.
# Examples
```
Input => Output
(["apple", "banana", "orange", "pineapple"], "baenanae") => "banana"
(["zeal", "zealot", "zealotry", "zealots", "zealous", "zealously", "zealousness"], "zealousl") => "zealously"
(["abductors", "abducts", "abe", "abeam", "abel"], "") => "abe"
```
[Answer]
# Python 3 + [pylev](https://pypi.python.org/pypi/pylev), 77 bytes
```
lambda m,s:min({levenshtein(x,s):x for x in m}.items())[1]
from pylev import*
```
[Try it on repl.it!](https://repl.it/KtUt/1)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 6 [bytes](https://github.com/Adriandmen/05AB1E/blob/master/docs/code-page.md)
```
Σ.L(}¤
```
**[Try it online!](https://tio.run/##MzBNTDJM/f//3GI9H43aQ0v@/49Wr0pNzFHXUQDT@SUIVlElgl0MZ5YiM3MqkTh5qcXF6rFcMCkuAA "05AB1E – Try It Online")** (note: the trailing newline on the input is necessary for the empty string case.)
### How?
```
Σ.L(}¤ - implicitly push the first input (the dictionary list)
Σ } - sort the list by:
- implicitly push second input (the misspelled word)
.L - Levenshtein distance
( - negated
¤ - tail the sorted list and place the entry on the top of the stack
- implicitly print top of stack
```
] |
[Question]
[
The Zachtronics game TIS-100 contains a graphics display called the visualization module. I could try and explain the specs of this module, but the game's manual will do a better job:
[](https://i.stack.imgur.com/R18L6.png)
(As you may have guessed, the motivation of this problem is to create a code golf challenge in which TIS-100 is the optimal language.)
Your job is to, in as few characters as possible, implement a program which will output the correct image for any valid input sequence. There are no requirements on what happens for an invalid input sequence. This can be a graphical window or console output. This includes strings of more than 1 command! If it has multiple -1s, multiple lines should be drawn.
# Test Cases:
```
Input:
3, 4, 4, 3, 2, 1, 0, 1, 2, 3, 4, -1
Output:
```
[](https://i.stack.imgur.com/d4pyl.jpg)
```
Input:
1, 1, 4, 4, -1, 8, 8, 4, 4, -1
Output:
```
[](https://i.stack.imgur.com/fzCNH.jpg)
```
Input:
5, 5, 4, -1, 5, 5, 0, -1
Output:
```
[](https://i.stack.imgur.com/04vvO.jpg)
The simple TIS implementation is:
# TIS-100, ~~64~~ 55 Bytes
-9 thanks to feersum
```
@1
MOV UP ANY
@5
MOV UP ANY
@9
MOV UP ANY
@10
MOV ANY ANY
```
An additional byte is added as a single character in the filename is relevant.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 114 bytes
```
->h,g=[0]*792{h.chunk{|x|x<0&&p}.map{|z,(x,y,*r)|g[36*y+x,r.size]=r}
puts'P3 36 22 5',g.map{|i|i>3?'5 0 0':[i]*3}}
```
This function takes its input as an array of ints, and writes the resulting image to STDOUT in the human readable version of PPM format. For those unfamiliar, the [PPM image format](https://en.wikipedia.org/wiki/Netpbm_format) is an uncompressed image format that's, essentially, a whitespace separated list of RGB values.
### About PPM
More particularly, it begins with a short header of the format `P3 W H M`, where `P3` is a magic number, `W` is the width of the image, `H` is the height of the image, and `M` is an int from 1 to 65536 representing the maximum possible value a color channel can have. For instance, if `M = 255`, then the RGB triplet `(255, 255, 255)` represents white. If `M = 10`, then `(10, 10, 10)` is white.
After the header, each pixel is described, row by row, by providing an RGB triplet for its color, with each value separated by spaces. It has the neat property that you can use it to represent an image as human readable text. For instance, a 3x1 pixel image containing a red pixel, a green pixel, and a blue pixel would be:
```
3 1 255
255 0 0 0 255 0 0 0 255
```
The precise whitespace used doesn't matter, so the above image is equivalent to, among many others:
```
3 1 255
255
0 0 0 255 0
0 0 255
```
### Explanation of Code
The reason all that was necessary was to explain why, when you run the program, you'll see output that looks like this:
```
P3 36 22 5
0
0
0
3
0 # And so on...
```
It's a PPM! And it's generated like this:
```
# Create an array g, full of 0s, of size (36*22) to hold the image
g = [0] * 792
# Break the input array into chunks, splitting on values < 0
h.chunk{|x|x < 0 && p}
# Use each chunk to fill the subarray of g beginning at its x and y coordinates
.map{|z,(x,y,*r)|g[36*y+x,r.size]=r}
# Print the header ...
puts'P3 36 22 5',
# ... and the colors, replacing each color id with itself repeated 3 times
# (for the various shades of gray) or '5 0 0', in the case of red, and
# separating each item with a newline.
g.map{|i|i>3?'5 0 0':[i]*3}
```
If you take this output and paste it into a text file, you'll be able to view it in any image viewer capable of opening PPMs.
[Try it online!](https://tio.run/##bYtBCsIwFET3niKrRuNvSfNtRbH1Cu5DFiqSBlFKaiFtk7PHqlsZhgfzGNtfhuiqmNYN6EpyxbY7MTXZtemf98k77w48SdqQPc7t5EdYOhiA2ZXXEks2rB3YrDPjTVU2LNr@1dETEiyJEKSgoH83402NR1oQTjjdS6MYhhCdlAibOQgCcuBzBXyWNP8C/wil4hs "Ruby – Try It Online")
[Answer]
.COM in 94B
```
00000000h: 68 00 B8 07 BF 09 01 31 DB B4 07 CD 21 3C 2D 72
00000010h: 41 6B DB 0A 2D 30 07 01 C3 BF 1E 01 EB EB 89 DD
00000020h: 83 06 1A 01 09 EB DD 69 ED A0 00 6B F3 02 EB F0
00000030h: 85 DB 7D 07 83 2E 1A 01 12 EB C9 83 FE 48 73 C4
00000040h: 81 FD C0 0D 73 BE FF B7 58 01 26 8F 02 83 C6 02
00000050h: EB B2 3C 20 72 02 FF E7 C3 00 88 77 FF 44
```
No extra optimize. Lots of code doing input
[Answer]
# SmileBASIC 3, 163 bytes
Draws the image in the top-left corner of the graphic screen at 1px scale. `DEF V A` takes an int array `A` as input.
```
DEF V A
GCLS
@_
X=A[I]Y=A[I+1]FOR I=I+1TO LEN(A)-1C=A[I]IF.>C THEN I=I+1GOTO@_
IF X>35||Y>21GOTO@N
R=(3AND C)*85GPSET X,Y,RGB(R+255*!!(4AND C),R,R)@N
X=X+1NEXT
END
```
## Test Harness
The output is very small and other graphics leftover from the console etc. makes this function hard to test (in addition to the fact that it's a function and not a standalone program...) Write this (ungolfed) test harness below the function and run to verify.
```
ACLS
DATA 3,4,4,3,2,1,0,1,2,3,4,-1,-10
DIM SEQ%[0]
WHILE C%!=-10
READ C%
PUSH SEQ%,C%
WEND
GPAGE 0,4
SPSET 0,0,0,36,22
SPSCALE 0,8,8
V SEQ%
REPEAT VSYNC UNTIL BUTTON(2)
```
Change the `DATA` statement to change the test sequence. The test sequence must end with `-10` so the tester knows to stop reading it (`DATA` is used because SB lacks array literals.) This is done so you can use `-1` in a sequence.
The program may end in an error; this is normal.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 73 bytes
```
'P3 36 22 5'
+/{{⍵≠4:3/⍵⋄4 0 0}¨(-1⊃⍵)⊖(-0⊃⍵)⌽36 22↑1(≢2↓⍵)⍴2↓⍵}¨¯1(≠⊆⊢)⎕
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkGXI862tP@qwcYKxibKRgZKZiqc2nrV1c/6t36qHOBiZWxPojV3WKiYKBgUHtohYau4aOuZqCY5qOuaRq6BjBOz16w9kdtEw01HnUuAjImg8V7t0CZQL2H1oPkFjzqanvUtUgT6IL/QLv/p3EZ6igAkQkYAdXoKFiAEVyAK43LGMYFMozAyg3ApBFYBCiuawgA "APL (Dyalog Unicode) – Try It Online")
A full program, which takes the indices as specified. Requires `⎕IO←0` for 0-indexing.
Outputs a netpbm image, like in the Ruby answer.
## Explanation
```
Netpbm header:
'P3 36 22 5'
Grid Generator:
+/{{⍵≠4:3/⍵⋄4 0 0}¨(-1⊃⍵)⊖(-0⊃⍵)⌽36 22↑1(≢2↓⍵)⍴2↓⍵}¨¯1(≠⊆⊢)⎕
⎕ Take the input
¯1(≠⊆⊢) split on -1s
{ }¨ do the following for each subarray i:
2↓⍵ Drop the 2 coordinates
1(≢2↓⍵)⍴ Convert i to a 1-row matrix
36 22↑ create a 36x22 matrix with zeros, containing i
(-0⊃⍵)⌽ rotate i to the required x coordinate
(-1⊃⍵)⊖ rotate i to the required y coordinate
{ }¨ apply the following to each element:
⍵≠4:3/⍵ if it's not red, assign a shade of grey
⋄4 0 0 otherwise assign red
+/ sum all the resulting matrices
```
] |
[Question]
[
**This question already has answers here**:
[Given an input, move it along the keyboard by N characters](/questions/50336/given-an-input-move-it-along-the-keyboard-by-n-characters)
(9 answers)
Closed 6 years ago.
# Challenge
Given a string with any characters a-z or A-Z, return an 'encrypted' string, where all characters are replaced by the character next to it (assuming a QWERTY keyboard).
* Case (uppercase, lowercase) **does not matter**.
* The input will **only** have characters a-z and A-Z.
Shortest code in bytes wins.
---
# Example Input and Output
`Foo Foo Bar Bar Python` → `Gpp Gpp Nst Nst [uyjpm`
`Case does not matter` → `vSDR fprd mpy ,sYYrT`
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 16 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ŒlµØqż“[;,”Fṡ2Zy
```
**[Try it online!](https://tio.run/nexus/jelly#ATQAy///xZJswrXDmHHFvOKAnFs7LOKAnUbhuaEyWnn///8iQ2FzZSBkb2VzIG5vdCBtYXR0ZXIi "Jelly – TIO Nexus")**
### How?
```
ŒlµØqż“[;,”Fṡ2Zy - Main link: string
Œl - convert to lowercase
µ - monadic chain separation
Øq - qwerty yield: ["qwertyuiop","asdfghjkl","zxcvbnm"]
“[;,” - "[;,"
ż - zip: [["qwertyuiop","["],["asdfghjkl",";"],["zxcvbnm",","]
F - flatten: "qwertyuiop[asdfghjkl;zxcvbnm,"
ṡ2 - overlapping pairs: ["qw","we","er","rt","ty","yu","ui","io","op","p[","[a","as","sd","df","fg","gh","hj","jk","kl","l;",";z","zx","xc","cv","vb","bn","nm","m,"]
Z - transpose: ["qwertyuiop[asdfghjkl;zxcvbnm","wertyuiop[asdfghjkl;zxcvbnm,"]
y - translate the lowercased string with that mapping
```
[Answer]
# Python 3, 91 bytes:
```
s='qwertyuiop[asdfghjkl;zxcvbnm, '
print(''.join(s[s.index(c)+1]for c in input().lower()))
```
] |
[Question]
[
# Introduction
In the game [*The Witness*](https://en.wikipedia.org/wiki/The_Witness_(2016_video_game)) (*possible spoilers ahead*) there is a group of puzzles that involve drawing a Tetris piece with your line while making sure that the symbol for the Tetris piece your currently drawing stays contained within the shape you've drawn.
[](https://i.stack.imgur.com/1IaF9.jpg)
For the image above the drawing works because the L-shaped and upside down L-shaped Tetris pieces, occupying the positions `(1,2)(2,2)(3,2)(3,3)` and `(1,1)(1,0)(2,0)(3,0)` respectively, and the icons, located at `(3,0)` and `(3,3)`, are contained within the white line.
# Challenge
Your goal is to draw the solution line such that it contains all Tetris pieces as well as their respective symbols. The solution line may not contain anymore squares than that which is required (i.e. you must contain the sum of the number of squares making up each Tetris piece). Each solution will begin in the bottom left and end in the top right. Lastly, this is code-golf, so the shortest solution (in bytes) wins.
## Representation
Each of these puzzles use a `HxW` grid of squares to construct your Tetris pieces and have some space for you to draw lines in between them. The representation is best understood by example. For the above image the representation would be
```
===========
| |
| X X X X |
| |
| X X X X |
| |
| X X X X |
| |
| X X X X |
| |
===========
```
and the solution would be
```
===========
|*********|
|*X X X X |
|******* |
| X X X*X |
| *** * |
| X*X*X*X |
| * * ***|
| X*X*X X*|
|*** *****|
===========
```
where each square is represented by an `X` and the solution is drawn using a line of `*`s. The number of lines for each puzzle is `2*H+3` and the number of characters for each line is `2*W+3`.
## Input
The first `n` lines will give you the Tetris piece followed by the location of the corresponding symbol for that Tetris piece. The format is as follows:
`(i1,j1)(i2,j2)...(ik,jk)->(p,q)`
where `(ik,jk)` is the `kth` coordinate pair of the Tetris piece
(the left coordinate increases as you move down, the right coordinate increases as you move right) and `(p,q)` is the location of the corresponding symbol. The origin of each Tetris piece is the top left square (i.e. the top left square is `(0,0)`).
Example 1:
```
X
X
XX
```
would be
```
(0,0)(1,0)(2,0)(2,1)
```
Example 2:
```
XX
X
X
```
would be
```
(0,0)(1,0)(2,0)(0,1)
```
Example 3:
```
X X
X X
```
would be
```
(0,0)(1,0)(0,3)(1,3)
```
The next `2*H+3` lines will consist of the puzzle's grid.
## Output
Output the puzzle grid with the solution line drawn in.
## Examples
### Example Input 1
```
(0,0)(0,1)->(2,1)
(0,0)(0,1)->(0,1)
(0,0)->(0,2)
=========
| |
| X X X |
| |
| X X X |
| |
| X X X |
| |
=========
```
### Example Output 1
```
=========
|*******|
|*X X X |
|*******|
| X X X*|
|***** *|
|*X X*X*|
|* ***|
=========
```
### Example Input 2
```
(0,0)(0,1)(0,2)(1,2)(2,2)->(0,0)
(0,0)(1,0)(0,3)(1,3)->(2,1)
(0,0)(1,0)(2,0)->(1,3)
===========
| |
| X X X X |
| |
| X X X X |
| |
| X X X X |
| |
| X X X X |
| |
===========
```
### Example Output 2
```
===========
| ***|
| X X X*X |
| ***|
| X X X X*|
| *|
| X X X X*|
|*** *****|
|*X*X*X X |
|* *** |
===========
```
### Example Input 3
```
(0,0)(1,0)(2,0)->(1,0)
(0,0)(1,0)(2,0)->(1,6)
(0,0)(0,1)(0,2)->(1,3)
=================
| |
| X X X X X X X |
| |
| X X X X X X X |
| |
| X X X X X X X |
| |
=================
```
### Example Output 3
```
=================
|*** ***|
|*X*X X X X X*X |
|* ******* * |
|*X X X X*X X*X |
|* ******* * |
|*X*X X X X X*X |
|* *********** |
=================
```
# Clarifications
* It is assumed that for any given input there is a solution.
* If there are multiple solutions just print one.
[Answer]
# Python, 992
Takes input from stdin and prints the solution. Note that SE has turned my tab characters into four spaces - anything indented beyond one space should be a tab.
It shouldn't be too hard to beat this, but I thought I'd post it since no one else had posted a solution.
```
L=len
R=range
j=[(-1,0),(1,0),(0,-1),(0,1)]
P=lambda y,x,q:(y,x)==(0,w)and[q+[(y,x)]]or sum([P(y+e,x+d,q+[(y,x)])for e,d in j if not(y+e,x+d)in q and 0<=x+d<=w and 0<=y+e<=h],[])
def C(q,y,x,v):
if(y,x)in v:return
v.add((y,x))
for e,d in j:
Y,X=y+e,x+d;a,b=[(y+(e+s*d+1)/2,x+(d+s*e+1)/2)for s in[-1,1]]
if 0<=X<w and 0<=Y<h and not(a in q and b in q and abs(q.index(a)-q.index(b))==1):C(q,Y,X,v)
def G(s,c):
if not s:return not c
for y,x in r:
p=set((Y+y,X+x)for Y,X in s[0])
if c&p==p and G(s[1:],c-p):return 1
def B(q):
for y,x in r:
c=set();C(q,y,x,c);s=[h for(w,h)in p if w in c]
if s and not G(s,c):return 1
h,p,g=0,[],[]
try:
while 1:
s=raw_input()
if'('in s:l,o=s.split('->');p.append(map(eval,[o,'('+l.replace(')','),')+')']))
else:g.append(list(s))
except:h=L(g)/2-1;w=L(g[0])/2-1
r=[(x/w,x%w)for x in R(w*h)]
for s in P(h,0,[]):
if not B(s):break
for(a,b),(c,d)in zip(s,s[1:]):g[1+2*a][1+2*b]=g[1+a+c][1+b+d]=g[1+2*c][1+2*d]='*'
print'\n'.join(''.join(r)for r in g)
```
Quick rundown of how it works:
`P` finds all possible paths.
`C` finds all the squares that are connected to a given square.
`G` determines whether or not a set of shapes fit exactly in a set of squares.
`B` determines whether or not a path is bad by checking each connected set of squares and checking if their shapes fit.
## Examples
input:
```
(0,0)(0,1)->(2,1)
(0,0)(0,1)->(0,1)
(0,0)->(0,2)
=========
| |
| X X X |
| |
| X X X |
| |
| X X X |
| |
=========
```
output (all tetris pieces are grouped into the top-right):
```
=========
|*** *|
|*X*X X*|
|* * *|
|*X*X X*|
|* * ***|
|*X*X*X |
|* *** |
=========
```
input:
```
(0,0)(0,1)(0,2)(1,2)(2,2)->(0,0)
(0,0)(1,0)(0,3)(1,3)->(2,1)
(0,0)(1,0)(2,0)->(1,3)
===========
| |
| X X X X |
| |
| X X X X |
| |
| X X X X |
| |
| X X X X |
| |
===========
```
output (this is the only one that's the same as the example solution):
```
===========
| ***|
| X X X*X |
| ***|
| X X X X*|
| *|
| X X X X*|
|*** *****|
|*X*X*X X |
|* *** |
===========
```
input:
```
(0,0)(1,0)(2,0)->(1,0)
(0,0)(1,0)(2,0)->(1,6)
(0,0)(0,1)(0,2)->(1,3)
=================
| |
| X X X X X X X |
| |
| X X X X X X X |
| |
| X X X X X X X |
| |
=================
```
output (rightmost 2 pieces are grouped together):
```
=================
|*** *** *******|
|*X*X*X*X*X X X |
|* * * * *******|
|*X*X*X*X X X X*|
|* * * * *******|
|*X*X*X*X*X X X |
|* *** *** |
=================
```
] |
[Question]
[
[B-splines](https://en.wikipedia.org/wiki/B-spline) are defined using a set of "knots", "control points", and degree. For the purposes of this challenge, the control points are not needed.
The knots are simply a list of strictly increasing real values (note that real B-splines may have repeated knots, for the purposes of this challenge assume knots are all unique). The degree is a non-negative integer.
The set of polynomial basis functions are recursively defined as ([image credit](https://www.cs.mtu.edu/~shene/COURSES/cs3621/NOTES/spline/B-spline/bspline-basis.html)):
[](https://i.stack.imgur.com/2opkp.png)
where `i` is the `i-th` basis function, and `p` is the degree of the basis function. `u` is the curve parameterization, and `u_j` is the `j'th` knot.
The goal of this challenge is to evaluate all the basis functions for a curve of degree `m` at location `u`.
# Input
Your program/function should take as input 3 parameters:
1. A real value for the location `u`
2. A non-negative integer for the curve degree `m`
3. A list of strictly increasing real values for the knots vector `u_j`
You may take these parameters in any order desired and may mutate the inputs as long as no additional information is added (for example, you may take the knots vector to be a combination of a real pointer and integer length).
The input may come from any source desired (stdio, function parameter, etc.).
You may assume the input describes a valid B-spline and that `u` is in the range of the knots vector.
# Output
Your program/function should output a list of real numbers describing what the basis functions evaluate to. That is, you should output [](https://i.stack.imgur.com/nC5XR.png) for all `0 <= i <= n-1-m`, where `n` is the number of knots (For 1-based indexing, then `1 <= i <= n - m`). The output must be accurate to within `1%` or [1000 ULP](https://en.wikipedia.org/wiki/Unit_in_the_last_place) of the true value, whichever is greater. The output may be to any sink desired (stdout, return value, etc.)
# Examples
All examples are formatted as such:
```
u
m
u_0 u_1 u_2 ...
N_{0,m}(u) N_{1,m}(u) N_{2,m}(u) ...
```
case 1:
```
.5
0
0 0.5 1
0 1
```
case 2:
```
.5
1
-1 0 1 2
0.5 0.5
```
case 3:
```
0.9
1
-1 0 1 2 3
0.1 0.9 0
```
case 4:
```
1.1
1
-1 0 1 2 3
0 0.9 0.1
```
case 7:
```
3
3
-1 0 1 2 3 8 10 12 15 20
0 0.5952381 0.38392857 0.02083333 0 0
```
# Hints
Notice that `N_{p}` depends only on `N_{p-1}`. That means rather than recursing from the top-down, you could start at the base case and work up. While this is faster execution-wise, I'm not sure if this will necessarily produce the shortest code.
Here's a reference implementation using Python3+NumPy for the bottom-up approach:
```
from numpy import *
def basis(knots, m, u):
# base case
Ns = 1.*logical_and(knots[:-1] <= u, u < knots[1:])
# work backwards, starting at the base case up to p=m
for p in range(1,m+1):
Ns = (u - knots[:-1-p]) * Ns[:-1] / (knots[p:-1] - knots[:-p-1]) \
+ (knots[p+1:] - u) * Ns[1:] / (knots[p+1:]- knots[1:-p])
return Ns
```
# Scoring
This is code golf; shortest answer in bytes wins. Standard loopholes are prohibited. You are welcome to use any built-ins desired.
[Answer]
# Pyth - ~~83~~ 82 bytes
Jesus, this is long, probably a few redundancies, but the formulas are long. This is a recursive solution that just implements the formulas given. The reference solution seems to be doing something else, but I don't know what. Maybe if I knew more about what all of this does...
```
KEM?H+.x*c-KJ@QG-@Q+GHJgGtHZ.x*c-=T@Qh+GHK-T@QhGghGtHZ&|>K@QGqK@QG<K@QhGgRvzt-lQvz
```
[Test Suite](http://pyth.herokuapp.com/?code=KEM%3FH%2B.x%2ac-KJ%40QG-%40Q%2BGHJgGtHZ.x%2ac-%3DT%40Qh%2BGHK-T%40QhGghGtHZ%26%7C%3EK%40QGqK%40QG%3CK%40QhGgRvzt-lQvz&test_suite=1&test_suite_input=%5B0%2C+0.5%2C+1%5D%0A0%0A.5%0A%5B-1%2C+0%2C+1%2C+2%2C+3%5D%0A1%0A0.9%0A%5B-1%2C+0%2C+1%2C+2%2C+2%2C+8%2C+10%2C+12%2C+15%2C+20%5D%0A3%0A3&debug=0&input_size=3).
[Answer]
# Python 2, ~~192~~ 185 bytes
```
D,E,Q=input();J=0;exec"F=lambda u,m,j,i:+(j[i]<=u<j[-~i])if m<1else(u-j[i])/(j[i+m]-j[i])*F(u,~-m,j,i)+(j[-~i+m]-u)/(j[-~i+m]-j[-~i])*F(u,~-m,j,-~i);print F(D,E,Q,J);J+=1;"*(~-len(Q)-E)
```
A direct implementation of the formula given with recursion in the lambda *and* iteration using `exec`. Prompts for input through the command line upon invocation as `u,m,[u_0,u_1,u_2...]` with `u` *always* input as a float (e.g. if `u=1`, then u would still be input as `1.0`) and outputs each of the `len([u_0,u_1,u_2...])-1-u` values on a separate line.
[Try it Online! (Ideone)](http://ideone.com/GM8H2m)
] |
[Question]
[
Your task is to write a program or function that detects accents in UTF-8 input. The catch is that your code must be written entirely in an 8-bit character encoding. The code will output a single integer which is the count of the number of accented letters in the input. Since Unicode is huge, the test input will consist solely of the characters found in [Windows-1252](https://en.wikipedia.org/wiki/Windows-1252), stored in the UTF-8 encoding, then treated as ASCII with extended characters (0x09, 0x0A, 0x0D, 0x20-0xFF only). The input won't contain any characters below 0x20, except for the three common ones, 0x09 (tab), 0x0A (line feed) & 0x0D (carriage return). It also won't contain 0x7F.
Unicode permits most common accented characters to be represented in multiple ways (only two for the characters in this challenge). `é` could be a pre-composed character: `U+00E9` (`C3 A9` in UTF-8) or a basic letter plus a [combining mark](http://www.fileformat.info/info/unicode/block/combining_diacritical_marks/utf8test.htm): `U+0065`+`U+0301` (`65`+`CC 81` in UTF-8). Your code must correctly handle both.
In the following table `*` marks an accented letter. All letters that have two forms will be considered accented, plus `Œ`, `œ`, `Æ` & `æ`. All other characters will be considered as symbols or non-accented letters.
```
1252 Char Unicode Char Unicode
Bytes Bytes
Accented?
-----------------------------------------
80 _ € 3 U+20AC
81 Undefined
82 _ ‚ 3 U+201A
83 _ ƒ 2 U+0192
84 _ „ 3 U+201E
85 _ … 3 U+2026
86 _ † 3 U+2020
87 _ ‡ 3 U+2021
88 _ ˆ 2 U+02C6
89 _ ‰ 3 U+2030
8A * Š 2 U+0160 Š 3 U+0053 U+030C
8B _ ‹ 3 U+2039
8C * Œ 2 U+0152
8D Undefined
8E * Ž 2 U+017D Ž 3 U+005A U+030C
8F Undefined
90 Undefined
91 _ ‘ 3 U+2018
92 _ ’ 3 U+2019
93 _ “ 3 U+201C
94 _ ” 3 U+201D
95 _ • 3 U+2022
96 _ – 3 U+2013
97 _ — 3 U+2014
98 _ ˜ 2 U+02DC
99 _ ™ 3 U+2122
9A * š 2 U+0161 š 3 U+0073 U+030C
9B _ › 3 U+203A
9C * œ 2 U+0153
9D Undefined
9E * ž 2 U+017E ž 3 U+007A U+030C
9F * Ÿ 2 U+0178 Ÿ 3 U+0059 U+0308
A0 _ 2 U+00A0
A1 _ ¡ 2 U+00A1
A2 _ ¢ 2 U+00A2
A3 _ £ 2 U+00A3
A4 _ ¤ 2 U+00A4
A5 _ ¥ 2 U+00A5
A6 _ ¦ 2 U+00A6
A7 _ § 2 U+00A7
A8 _ ¨ 2 U+00A8
A9 _ © 2 U+00A9
AA _ ª 2 U+00AA
AB _ « 2 U+00AB
AC _ ¬ 2 U+00AC
AD _ 2 U+00AD
AE _ ® 2 U+00AE
AF _ ¯ 2 U+00AF
B0 _ ° 2 U+00B0
B1 _ ± 2 U+00B1
B2 _ ² 2 U+00B2
B3 _ ³ 2 U+00B3
B4 _ ´ 2 U+00B4
B5 _ µ 2 U+00B5
B6 _ ¶ 2 U+00B6
B7 _ · 2 U+00B7
B8 _ ¸ 2 U+00B8
B9 _ ¹ 2 U+00B9
BA _ º 2 U+00BA
BB _ » 2 U+00BB
BC _ ¼ 2 U+00BC
BD _ ½ 2 U+00BD
BE _ ¾ 2 U+00BE
BF _ ¿ 2 U+00BF
C0 * À 2 U+00C0 À 3 U+0041 U+0300
C1 * Á 2 U+00C1 Á 3 U+0041 U+0301
C2 * Â 2 U+00C2 Â 3 U+0041 U+0302
C3 * Ã 2 U+00C3 Ã 3 U+0041 U+0303
C4 * Ä 2 U+00C4 Ä 3 U+0041 U+0308
C5 * Å 2 U+00C5 Å 3 U+0041 U+030A
C6 * Æ 2 U+00C6
C7 * Ç 2 U+00C7 Ç 3 U+0043 U+0327
C8 * È 2 U+00C8 È 3 U+0045 U+0300
C9 * É 2 U+00C9 É 3 U+0045 U+0301
CA * Ê 2 U+00CA Ê 3 U+0045 U+0302
CB * Ë 2 U+00CB Ë 3 U+0045 U+0308
CC * Ì 2 U+00CC Ì 3 U+0049 U+0300
CD * Í 2 U+00CD Í 3 U+0049 U+0301
CE * Î 2 U+00CE Î 3 U+0049 U+0302
CF * Ï 2 U+00CF Ï 3 U+0049 U+0308
D0 _ Ð 2 U+00D0
D1 * Ñ 2 U+00D1 Ñ 3 U+004E U+0303
D2 * Ò 2 U+00D2 Ò 3 U+004F U+0300
D3 * Ó 2 U+00D3 Ó 3 U+004F U+0301
D4 * Ô 2 U+00D4 Ô 3 U+004F U+0302
D5 * Õ 2 U+00D5 Õ 3 U+004F U+0303
D6 * Ö 2 U+00D6 Ö 3 U+004F U+0308
D7 _ × 2 U+00D7
D8 _ Ø 2 U+00D8
D9 * Ù 2 U+00D9 Ù 3 U+0055 U+0300
DA * Ú 2 U+00DA Ú 3 U+0055 U+0301
DB * Û 2 U+00DB Û 3 U+0055 U+0302
DC * Ü 2 U+00DC Ü 3 U+0055 U+0308
DD * Ý 2 U+00DD Ý 3 U+0059 U+0301
DE _ Þ 2 U+00DE
DF _ ß 2 U+00DF
E0 * à 2 U+00E0 à 3 U+0061 U+0300
E1 * á 2 U+00E1 á 3 U+0061 U+0301
E2 * â 2 U+00E2 â 3 U+0061 U+0302
E3 * ã 2 U+00E3 ã 3 U+0061 U+0303
E4 * ä 2 U+00E4 ä 3 U+0061 U+0308
E5 * å 2 U+00E5 å 3 U+0061 U+030A
E6 * æ 2 U+00E6
E7 * ç 2 U+00E7 ç 3 U+0063 U+0327
E8 * è 2 U+00E8 è 3 U+0065 U+0300
E9 * é 2 U+00E9 é 3 U+0065 U+0301
EA * ê 2 U+00EA ê 3 U+0065 U+0302
EB * ë 2 U+00EB ë 3 U+0065 U+0308
EC * ì 2 U+00EC ì 3 U+0069 U+0300
ED * í 2 U+00ED í 3 U+0069 U+0301
EE * î 2 U+00EE î 3 U+0069 U+0302
EF * ï 2 U+00EF ï 3 U+0069 U+0308
F0 _ ð 2 U+00F0
F1 * ñ 2 U+00F1 ñ 3 U+006E U+0303
F2 * ò 2 U+00F2 ò 3 U+006F U+0300
F3 * ó 2 U+00F3 ó 3 U+006F U+0301
F4 * ô 2 U+00F4 ô 3 U+006F U+0302
F5 * õ 2 U+00F5 õ 3 U+006F U+0303
F6 * ö 2 U+00F6 ö 3 U+006F U+0308
F7 _ ÷ 2 U+00F7
F8 _ ø 2 U+00F8
F9 * ù 2 U+00F9 ù 3 U+0075 U+0300
FA * ú 2 U+00FA ú 3 U+0075 U+0301
FB * û 2 U+00FB û 3 U+0075 U+0302
FC * ü 2 U+00FC ü 3 U+0075 U+0308
FD * ý 2 U+00FD ý 3 U+0079 U+0301
FE _ þ 2 U+00FE
FF * ÿ 2 U+00FF ÿ 3 U+0079 U+0308
```
* Input will be in any 8-bit encoding which is a super-set of ASCII, i.e. the lower half of the code points will match exactly with ASCII, the upper half (0x80-0xFF) will be used exclusively for multi-byte UTF-8 encoded codepoints, e.g. `“` (`U+201C`) will be treated as both three bytes and three characters by your code: `E2 80 9C`
* Language features or pre-existing libraries that convert character encodings or handle Unicode are forbidden, e.g. JSON (can convert Unicode text to hex), Unicode flag on regex, etc.
Sample output and input:
* `3` `Zoë reads the encyclopædia in a café`
* `0` `Zoe reads the encyclopaedia in a cafe`
* `1` `Zoë` (pre-composed character, 3 codepoints, 4 bytes)
* `1` `Zoë` (base letter + combining mark, 4 codepoints, 5 bytes)
* `2` `déjà vu`
## Scoring
Simple code-golf: lowest number of bytes wins!
This is a re-write as my computer crashed just before posting the first version and I lost all but the first few lines of the challenge. Apologies if I've left anything out!
[Answer]
# Mathematica, 46 bytes
```
Count[Characters@#,c_/;RemoveDiacritics@c!=c]&
```
**Explanations:**
`Chatacters` extract every characters in the string. Note that there is a difference between two `Zoë` even if they look the same:
```
Characters["Zoë"]
(* {"Z", "o", "ë"} *)
Characters["Zoë"]
(* {"Z", "o", "e", "̈ ̈"} *)
```
Here, the pattern `c_/;RemoveDiacritics@c!=c` will be matched with those characters that change with diacritics removed. For the first case, only `ë` will match since `ë` becomes `e`. While for the second case, only `̈` will match since it becomes nothing. Whatever case the string is, the counting will be correct.
**Test cases:**
```
f=%; (* assign the function to f. *)
f["Zoë reads the encyclopædia in a café"]
(* 3 *)
f["Zoe reads the encyclopaedia in a cafe"]
(* 0 *)
f["Zoë"]
(* 1 *)
f["Zoë"]
(* 1 *)
f["déjà vu"]
(* 2 *)
```
] |
[Question]
[
**Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/45375/edit).
Closed 9 years ago.
[Improve this question](/posts/45375/edit)
## Introduction
Scientists have recently found a new type of bacteria that replicates in odd ways. To reproduce, two bacteria each split into 3 (for a total of 6) and pairs combine (resulting in 3 bacteria, two parents, one child). However, the bacteria can only split if it has a partner. For example, 2 bacteria split and combine into 3, 3 into 4, 4 into 6, etc. Additionally, when a bacteria splits, only one of the daughter cells combines with the other parent cell's daughter cells, and vice versa. In other words, if bacteria A and B split, the daughter cells will combine to be AA, AB, and BB.
## The Challenge
Your challenge is to make a program that accepts or generates 4 bacteria's DNA, each with a strand in a 10-bit [Quaternary format](http://en.wikipedia.org/wiki/Quaternary_numeral_system). An example DNA strand could be 0123302012. When two daughter bacteria combine, the DNA is merged in a punnet-square style (the DNA can be merged in every pair or only the AB pair, your choice). Meaning that 0 is the recessive trait, 1 is the mixed trait, and 2 is the dominant trait. However, when there is a 3, it is a mutated trait (more on this later). Starting with the 4 bacteria, have your program run 20 trials (4 splitting into 6 would be the first trial). Once it is done, have the program output through STDOUT (or equivalent) each cell's DNA on a seperate line, but only from the cells generated from the 20th trial.
## Key Features
* Each trial must calculate the new number of cells and each new cell's DNA (see below).
* The program must output each 20th-trial cell's DNA (The 4046 new bacteria) each on a seperate line in STDOUT (or equivalent).
* The bacteria must each replicate in the method stated above. (A and B split into AA, AB, and BB).
### How the DNA is Passed on
The DNA is passed from the parents to child in a [punnet-square style](http://en.wikipedia.org/wiki/Punnett_square) where:
* 0 is a recessive trait (rr).
* 1 is a mixed trait (Rr).
* 2 is a dominant trait (RR).
If one of the traits is a 3 (a mutation), the ending trait is decided randomly, but if both are 3,the ending trait is a 3. Parents can be decided randomly or in order (A & B, C & D, etc).
Example:
```
| DNA A | DNA B | DNA C (Child) |
| 0123311200 | 1203123213 | 0113012203 |
```
## Scoring
This is code golf, so shortest character count wins! For legibility, please include a version that separates the code onto multiple lines, if possible. If the challenge is not explained well or you have suggestions, post a comment!
Here is an example program (in java) that successfully completes the challenge: [Ideone Link](http://ideone.com/O62iNn).
[Answer]
# [CJam](http://cjam.aditsu.net/): 71
Golfed:
```
qS/{mr2/{_,({3*$2/{z{:~_3#){~=Z4mr?}{{[0Ymr1]=}%:+}?`}%}/}{~}?}%}K*{N}/
```
Indented and commented:
```
qS/ "Read the input and split around spaces";
{ "Loop";
mr2/ "Shuffle the DNA strings and group into pairs";
{ "For each pair";
_,( "Check if it's really a pair";
{ "If it's really a pair AB";
3*$2/ "Create the breeding combinations AA AB BB";
{ "For each breeding combination";
z "Pair the corresponding alleles together";
{ "For each pair of alleles";
:~ "Map each allele (currently a string) to an int";
_3#) "Check if one of the alleles is a 3";
{ "If one allele is a 3";
~= "Check if both alleles are 3";
Z "If so, generate a 3 as the new allele";
4mr? "Otherwise, generate a random number from 0 to 3 as the new allele";
}{ "If neither allele is a 3";
{[0Ymr1]=}% "For each allele, map 0 to 0, 1 to 0 or 1 (random), and 2 to 1";
:+ "Add the mapped values to generate the new allele";
}?` "Convert the allele back to a string";
}% "Result: two DNA strings bred into one";
}/ "Result: two DNA strings combined and bred into three";
}{~}? "If it's not a pair, just unwrap it from its group";
}% "Result: all pairs of DNA strings combined and bred into three";
}K* "Result: bred for 20 generations";
{N}/ "Put a newline after each DNA string";
```
You added the stipulation that DNA is only merged punnet-square-style for "AB" bacteria after I wrote my code, but mine generates all bacteria by merging that way. Based on your description of how breeding occurs, my interpretation (which also seems to be Siddhanathan's interpretation) seemed more accurate. Talking about bacteria splitting into 3 doesn't make any sense otherwise. But I'll change things if necessary.
I also assumed that breeding pairs should be decided randomly, but that seems like a safer assumption.
[Answer]
# Haskell -- 349
```
import Control.Monad
import System.Random
import Data.List
a=[0,1,2,3,3,1,1,2,0,0]
b=[a,a,a,a]
f 3 _=randomRIO(0,3)
f _ 3=randomRIO(0,3)
f x y=return$div(x+y)2
z::[Integer]->[Integer]->IO[Integer]
z x y=zipWithM f x y
c=filter(\x->length x==2).subsequences
r=sequence.map(\x->z(x!!0)(x!!1)).c
y=foldr(<=<)return.replicate 20
main=y r b>>=mapM_ print
```
Try it online with nicer looking source code: <http://ideone.com/9FUMLd>
The online example does only till 2 instead of 20 because of ideone's time limit.
] |
[Question]
[
Your mission, should you choose to accept it, is to write code for a GPS receiver.
## Input
* The current time, as nanoseconds from the Unix epoch. [EDIT: This is optional, please state whether you require it]
* Four satellite signals, in the following format:
+ The time the signal was sent, as nanoseconds from the Unix epoch. You must be able to handle dates up to and including 2020.
+ The location of the satellite, as Cartesian coordinates, in metres. You must be able to handle values that fit into a signed 32-bit integer (-2,147,483,648 to 2,147,483,647). Only integer coordinates will be given. You may assume valid input (i.e. your position can be calculated)
Input can be provided from command-line arguments, standard input or equivalent, but not from a variable. The input can have any separator characters in it; please specify what your input format is.
## Output
The coordinates of your receiver, to the nearest 1000 metres, using 299,792,458 m/s as the speed of light. Again, I will be lenient with the output format: any separators are acceptable.
## Example
**Input**
```
1412349052664203400
[1412349052692915310,2267943, 13318342, 0]
[1412349052698278110,-3757960, 3500627, 0]
[1412349052691548521,4425976, -1533193, 3469445]
[1412349052687888295,10622179, 11246951, 84184]
```
**Output**
```
(6223615, 5673496, 0)
```
I have made a [GeoGebra notebook for this example](https://dl.dropboxusercontent.com/u/32117947/gps.ggb). Please excuse my extremely sloppy [GeoGebra](http://www.geogebra.org/cms/en/) skills.
## How GPS Works
Because the speed of light is finite, there will be a difference between your current time and the time the satellite sent the signal.
1. Use the difference to calculate the distance to the satellite, *d*.
2. You are clearly located somewhere on the surface of a sphere, centered on the satellite, with radius *d*.
3. Once you have two satellites and two spheres, you have to be located somewhere on the intersection of the two sphere surfaces, which is a circle.
4. Adding another satellite reduces the possible positions to just two points, where all three sphere surfaces intersect.
5. The fourth satellite allows you to decide on a specific one of these points. Your task is to calculate the location of this point, where all four spheres intersect. Since you assume valid input, such a point does exist.
## Rules
* [Standard loopholes](http://tinyurl.com/ppcgloopholes) are banned.
[Answer]
# MatLab/Octave (164)
I assumed the values to be saved in variables. As I said the posed problem seems to result in something about 200 to 300m off in the z coordinate compared to the given solution so this entry does not work within the 100m precision assuming the given test case is correct.
### How it works
You can interpret your position as the intersectionpoint of four spheres, since you can calculate the distance to each sattelite by the runtime. The points `[x,y,z]` on a sphere with center `[x,y,z]` and radius `r` can be written as an equation (so 4 satelites = 4 equations):
```
(x-x0)^2 + (y-y0)^2 + (z-z0)^2 = r^2
```
Or when expanded / transformed:
```
-2*x0*x -2*y0*y -2*z0*z = r^2 - x0^2 - y0^2 - z0^2 - x^2 - y^2 - z^2
```
As you have 4 equations that look like that you can substract one from the other three, which eliminates the `x^2+y^2+z^2` and get a system of 3 linear equations that can easily be solved for `x,y,z`.
But 3 intersecting spheres would result in two possible points, so a fourth is only needed for choosing the right one of those two points. But if the intersectionpoint of the first three is not exactly on the fourth sphere you cannot get an accurate answer.
Normally for gps you have the earth as fourth sphere, so three satelites could give you a line on which your current position must be (when the current exact time is unknonw). The line intersected with the earth surface results in only two possible points. So by comparing the different timestamps you could estimate on which side of the earth you are.
### Code
```
%input
1412349052664203400
[1412349052692915310,2267943, 13318342, 0;
1412349052698278110,-3757960, 3500627, 0;
1412349052691548521,4425976, -1533193, 3469445;
1412349052687888295,10622179, 11246951, 84184]
%actual code
t=input('');d=input('');
c=299792458e-9;
p=d(:,2:4);
r=(d(:,1)-t)*c;
o=ones(3,1);
q=p(1:3,:)-o*p(4,:);
b=p(1:3,:).^2-o*p(4,:).^2;
s=r(1:3).^2-o*r(4).^2;
(-2*q)\(s-sum(b,2))
```
Output:
```
1.0e+006 *
6.223565252948585
5.673559409007432
0.000291267494418
```
] |
[Question]
[
**This question already has answers here**:
[Write a base X to base Y function [duplicate]](/questions/4423/write-a-base-x-to-base-y-function)
(3 answers)
Closed 9 years ago.
What your function must do:
be as short (in bytes) as possible
take 3 inputs that are strings: number , fromdigits, todigits
assume no digit is repeated in fromdigits or todigits
assume fromdigit and todigit contain only alphanumeric characters
assume number is a natural number
output (a string): number converted to frombase
examples:
`convert("ff","0123456789abcdef","0123456789")="255"`
`convert("ee","fecdba9876543210","9876543210")="82"`
example code (283 bytes, in python 3.4.1):
```
def convert(number,fromdigits,todigits):
x=0
for digit in str(number):
x = x*len(fromdigits)+fromdigits.index(digit)
res=""
while x>0:
digit = x % len(todigits)
res = todigits[digit] + res
x //= len(todigits)
return res
```
[Answer]
# Python - 101
To get started I basically golfed your example code...
```
def c(n,f,t,x=0,r=""):
for d in n:x=x*len(f)+f.index(d)
while x:l=len(t);r=t[x%l]+r;x//=l
return r
```
[Answer]
## APL (40)
Can't beat CJam anymore it seems.
```
{⎕IO←0⋄⍵⍵[N⊤⍨(⌊1+Z⍟N←(⍴⍺⍺)⊥⍺⍺⍳⍵)/Z←⍴⍵⍵]}
```
This takes the *fromdigits* and *todigits* values as its `⍺⍺` and `⍵⍵` arguments, and the number itself as the `⍵` argument, i.e.:
```
('0123456789abcdef'{⎕IO←0⋄⍵⍵[N⊤⍨(⌊1+Z⍟N←(⍴⍺⍺)⊥⍺⍺⍳⍵)/Z←⍴⍵⍵]}'0123456789')'ff'
255
⍝ for ease of reading
convert ← {⎕IO←0⋄⍵⍵[N⊤⍨(⌊1+Z⍟N←(⍴⍺⍺)⊥⍺⍺⍳⍵)/Z←⍴⍵⍵]}
('0123456789abcdef' convert '0123456789') 'ff'
255
('fedcba9876543210' convert '9876543210') 'ee'
82
('0123456789' convert '01') '254'
11111110
```
Explanation:
* `⎕IO←0`: set the index origin to `0`. (APL arrays start at `1` by default and we don't need that here.)
* `Z←⍴⍵⍵`: store the length of `⍵⍵` in `Z`. This is the base to convert to.
* `N←(⍴⍺⍺)⊥⍺⍺⍳⍵`: look up the index (`⍳`) in `⍺⍺` of each value in `⍵`. These are the digits in the base to convert from. Then decode (`⊥`) this from the input base, which is the length of `⍺⍺`. Store this value in `N`.
* `⌊1+Z⍟N`: find the amount of digits required to represent value `N` in base `Z`.
* `(`...`)/Z`: replicate `Z` that many times.
* `N⊤⍨`: encode `N` into the output base.
* `⍵⍵[`...`]`: for each digit of that, find the corresponding character in `⍵⍵`.
[Answer]
## CJam, 20 bytes
```
rr:Ff#F,bAbsr:Tf#T,b
```
Input is like:
```
ee fecdba9876543210 9876543210
```
Output:
```
82
```
[Try it online here](http://cjam.aditsu.net/)
] |
[Question]
[
Input will be one or more space separated characters followed by a long string on STDIN or as an argument when called from the shell.
```
a C
WAtcIaElCpVqDRavOUejlgumcRCpfIWlaRFZpIoPYsWjsBSdlYfitfAPHpemiLpjaHheUGpFVQoZCnSCFgvpVzcoibdffoPRoJJwLIjVicPCdcvITXaQDjtMgrxQMZCkZNFmNqwGQYaSyPpdLOkAVHGVoVBiIksZCQHEaIxcRGwpIAmlChuhGEDajeJVXoCwFFuIvhEoqMuwrCDmZPcQxeaqJjynGWVjSaCCxWfupDbbEEFufDyealmbLxKfwlWCsSXwpPtuayxNVCodeEjeCIeHBYioeTogujuUFlWydOwInWGbsvlSwlwgfQaAmNTWPjsgqSCGzsJYfqGklpeLujFyrZJmNymUzpXLTkZcyPgPakAXTTfKlnnTCkjxxSZltwnLMOUCxlHOtLIUTqcbejXqyrwQgMaPUKcHBDZwMrCgwfVZUzxbdODBbBqEbpFLUOcPpVmsgLnfMXRWaddGnK
```
* Your task is to line-wrap the string at a suitable length so that there is at least one column completely filled by each input character. All lines should be wrapped to the same length (except possibly the last one if it's shorter.)
In this case, the solution could be wrapping at 50 characters giving the output
```
WAtcIaElCpVqDRavOUejlgumcRCpfIWlaRFZpIoPYsWjsBSdlY
fitfAPHpemiLpjaHheUGpFVQoZCnSCFgvpVzcoibdffoPRoJJw
LIjVicPCdcvITXaQDjtMgrxQMZCkZNFmNqwGQYaSyPpdLOkAVH
GVoVBiIksZCQHEaIxcRGwpIAmlChuhGEDajeJVXoCwFFuIvhEo
qMuwrCDmZPcQxeaqJjynGWVjSaCCxWfupDbbEEFufDyealmbLx
KfwlWCsSXwpPtuayxNVCodeEjeCIeHBYioeTogujuUFlWydOwI
nWGbsvlSwlwgfQaAmNTWPjsgqSCGzsJYfqGklpeLujFyrZJmNy
mUzpXLTkZcyPgPakAXTTfKlnnTCkjxxSZltwnLMOUCxlHOtLIU
TqcbejXqyrwQgMaPUKcHBDZwMrCgwfVZUzxbdODBbBqEbpFLUO
cPpVmsgLnfMXRWaddGnK
```
The fifteenth (`a`) and twenty-seventh (`C`) all form a single column of the given input characters.
The last line may or may not be complete.
* There can be more than one solutions. Any one of them can be considered valid.
* Returning the string as-is is **NOT** allowed. (For those claiming that it forms one-row columns). The columns of the input characters must have at least two rows. You may assume that the input string is longer than 10 characters.
* If there is no possible solution, your program must indicate this in some way(return status, printing "no solution", etc.) which you must mention.
* Input will only include [a-zA-Z]
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'")
---
Here's the actual program(python) that I use to generate these strings.
```
import random
a = 10
b = 50
s = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
for i in xrange(a):
c = ''
for j in xrange(b):
c += (random.choice(s))
print c
```
I then rectangle-edit to get columns full of input characters and strip newlines, deleting random number of characters from the end of the last line.
[Answer]
### GolfScript, 73 characters
```
n%(' '-:C;~:T,,1>{T/zip{.,1>*.&.,1=*}%''*C&C=},.{0=T/n*}{'no solution'}if
```
Breaks at the first position which is possible. The input must be given on STDIN in the format specified in the question.
*Example ([online](http://golfscript.apphb.com/?c=OyJYIFkKYWJjZGVYZllnaGlqa2xtblhvWXBxcnN0dXZ3WHhZeXpYWVoiCgpuJSgnICctOkM7fjpULCwxPntUL3ppcHsuLDE%2BKi4mLiwxPSp9JScnKkMmQz19LC57MD1UL24qfXsnbm8gc29sdXRpb24nfWlmCg%3D%3D&run=true)):*
```
X Y
abcdeXfYghijklmnXoYpqrstuvwXxYyzXYZ
abcdeXfYghi
jklmnXoYpqr
stuvwXxYyzX
YZ
```
*Annotated code:*
```
n% # Split the input at newlines
(' '-:C; # Extract the first line, remove all spaces
# and assign the resulting string to variable C
~:T # Take the second line and assign this string
# to variable T
,,1> # Makes an array [1 2 3 ... L-1] where L is the
# length of T
{ # A filter block {...}, selects all possible
# line wrap positions from this array
T/ # Test the current length by splitting T (input)
# in pieces
zip # Transpose the result (i.e. we now have a array
# of strings representing the columns)
{ # For each column
.,1>* # Is the length greater than one, then keep the column
# else transforms it to the empty string (string * 0)
.& # "and"s the string with itself, i.e. the result
# is a string of the distinct characters in the column
.,1=* # If the length is 1 (i.e. only one character) keep
# the column, otherwise reduce it to the empty string
}%
''* # Combine the resulting characters into a string again
C&C= # Check if this string contails all characters from C
},
.{ # If the filter returns at least one possible wrap position
0= # Take the first one
T/n* # Split the string and join again with newlines
}{ # Else
'no solution' # Return 'no solution'
}if # Endif
```
[Answer]
## APL (65)
```
⍞{1∊r←∧⌿↑∨/¨¨∧⌿¨¨↓⍵∘.=z←⍺∘{z⍵⍴⍺↑⍨⍵×z←⌈⍵÷⍨⊃⍴⍺}¨⍳¯1+⍴⍺:⊃r/z⋄0}⍞~' '
```
Example: (smaller one for legibility)
```
⍞{1∊r←∧⌿↑∨/¨¨∧⌿¨¨↓⍵∘.=z←⍺∘{z⍵⍴⍺↑⍨⍵×z←⌈⍵÷⍨⊃⍴⍺}¨⍳¯1+⍴⍺:⊃r/z⋄0}⍞~' '
r a b
abracadabra!
abracad
abra!
```
Explanation:
* `⍞{`...`}⍞~' '`: Read two lines. Remove the spaces from the first line and pass it to the function as its right argument, pass the second line unaltered as the left argument.
+ `⍺∘{`...`}¨⍳¯1+⍴⍺`: For each number `1..length ⍺-1`, split `⍺` into that many columns:
+ `z←⌈⍵÷⍨⊃⍴⍺`: calculate how many columns we'll need and store in `z`.
+ `⍺↑⍨⍵×z`: extend `⍺` with spaces to the length `⍵×z` (fill the last line up with spaces if necessary)
+ `z⍵⍴`: reshape the result into `z` lines and `⍵` columns
+ `z←`: store the array of matrices in `z`
+ `⍵∘.=z`: for each character in `⍵` (the input characters), see which elements in `z` match it
+ `∧⌿¨¨↓`: take the logical *and* of each column of each matrix for each input character
+ `∨/¨¨`: take the logical *or* of each element in the result (giving for each character and each matrix whether that character was matched in that matrix)
+ `r←∧⌿↑`: for each matrix, see whether or not *all* input characters were matched. Store a bitmask over the matrices in `r`.
+ `1∊r`...`:`: If the bitmask contains a `1`, there was a result, so:
+ `⊃r/z`: Filter `z` by `r` and take the first element (displaying the result with the smallest amount of columns.)
+ `⋄0`: otherwise, return '0'.
[Answer]
# Ruby, 161
Why not use one clever regular expressions instead of "brute-forcing" and checking ;)
[Online version](http://ideone.com/STfyrk)
```
d,s=STDIN.read.split("\n")
l = s.size
puts s.scan(/.{,#{d.split.map{|c|(0..l-2).map{|n|n if /^.{,#{n}}(#{c+?.*n})*.{,#{n-1}}$/=~s}}.reduce(&:&).compact.min+1}}/)
```
[Answer]
# Python (~~211~~ 203)
This is my first codegolf so I expect many possible improvements. I have designed two version which use different systems to print out the solution.
The input is done via 2 input()s so you would have to put quotes before and after the strings.
## Version 1 (~~211~~ 203)
```
c=input().split();i=input();l=range(len(i)//2)
for k in c:l=[w for w in l if any(all(k==y for y in i[x::w])for x in range(w))]
print'\n'.join(len(l)and __import__('textwrap').wrap(i,l[0])or'No solution')
```
**Explanation**:
```
chars = input().split()
inp = input()
wrapAfter = range(len(inp)//2) # min 2 (full) lines
for char in chars:
wrapAfter = [wrapped for wrapped in wrapAfter if any( # filter the possiblities left
all(char == cAt for cAt in inp[columnNbr::wrapped]) # wrap the line and check that
# cAt is char
for columnNbr in range(wrapped))] # for all columns
# print a joined version of all strings that are returned
import textwrap
wrapped = wrapAfter[0]
print('\n'.join(textwrap.wrap(inp, wrapped) if len(wrapAfter) # if there are wrappingvalues left
# we wrap the string
else 'No solution')) # else we print 'No solution'
```
## Version 2 (~~245~~ ~~236~~ ~~219~~ 208)
```
r=range;c=input().split();i=input();z=len(i);l=r(z//2)
for w in l:
if set(s[0] for s in(i[x::w]for x in r(w))if len(set(s))==1)>=set(c):print'\n'.join(i[x:x+w]for x in r(0,z,w));break
else:print'No solution'
```
**Explanation**:
```
chars = input().split()
inp = input()
length = len(inp)
wrapAfter = range(length//2)
# we go through every possible wrapping
for wrap in wrapAfter:
# if the set of all character for that a colum exists that is purely made up of
# this char is a superset of chars then we won
if set(s[0] for s in
# makes a generator that generates all columns
(inp[x::wrap]for x in range(wrap))
# if all characters in the column are equal
if len(set(s))==1) >= set(chars):
print('\n'.join(inp[x:x+wrap]for x in range(0,length,wrap))) # textwrap is
# slower as we
# replace range
break
# if the loop wasn't broken nothing was found
else:
print('No solution')
```
] |
[Question]
[
The string `2123132133` has the property that no subsequence of length 3 is the same as any other subsequence of length 3.
Your task is to build a program that will output as long of a string as possible that satisfies this property for sequences of length 9 with the characters from `1` to `9`.
The source code of your program may not be longer than 16 kilobytes (16,384 bytes). The program that wins is the one that outputs the longest sequence of digits from `1` to `9` such that no subsequence of 9 digits is the same.
[Answer]
What I'm starting with here is a [De Bruijn sequence](http://en.wikipedia.org/wiki/De_Bruijn_sequence). Stealing some reference code on the topic, here is my submission:
```
#!/usr/bin/env python
def de_bruijn(k, n):
""" De Bruijn sequence for alphabet size k and subsequences of length n. """
a = [0] * k * n
sequence = []
def db(t, p):
if t > n:
if n % p == 0:
for j in range(1, p + 1):
sequence.append(a[j])
else:
a[t] = a[t - p]
db(t + 1, p)
for j in range(a[t - p] + 1, k):
a[t] = j
db(t + 1, t)
db(1, 1)
return sequence
seq = de_bruijn(9, 9) # cyclic
seq = seq + seq[:8] # extended to max
print(''.join(map(lambda n: chr(49+n), seq)))
```
After running for ten minutes, the output is a 387,420,497 digit sequence. This is 9^9 + 8 digits, as expected. (Thank you @PeterTaylor for the +8 tip on the cyclic output.)
] |
[Question]
[
Given an MxN grid of numbers, find the greatest product of a length 4 subsequence in any row, column, or diagonal. Subsequences *cannot* wrap around (e.g. `5 1 2 3` in the row `1 2 3 4 5`).
I/O can be anything reasonable: files, stdin/stdout, copy+pasting expressions/arguments, variables. (If I'm missing any esoteric I/O option, feel free to go ahead and post your solution anyways)
[Answer]
# J, 26 chars
```
>./,4*/\"1(,|:,]/.,]/.@|.)
```
Just an expression to which a rank 2 array could be appended.
`,|:,]/.,]/.@|.` takes the rank 2 array and concatenates 4 intermediate rank 2 arrays, the input's identity, transposition, and obliques, respectively. Here I feel like there's an uncomfortable amount of redundancy, because there are 2 `]`s, 3 `,`s, and 2 `/.`s... I can't think of a way to refactor those out.
`>./,4*/\"1` is just a straightforward maximum of each length 4 subsequence of each row of the newly made array, which of course corresponds to rows/columns/diagonals of the original.
[Answer]
# Mathematica 190
A 9x5 matrix.
```
m = RandomInteger[{1, 99}, {9, 5}];
m // MatrixForm
```

**Code**
This produces the product and the factors.
```
{e, f} = Dimensions@m; z = Reverse; w = Flatten;
j = Join[m, n = m\[Transpose], p = z /@ m, q = z /@ n,
w[Table[Diagonal[#, k], {k, -(e - 4), f - 4}] & /@ {m, n, p, q}, 1]];
Sort[w[Partition[#, 4, 1] & /@ j, 1] /. {a_, b_, c_, d_} :> {a b c d, {a, b, c, d}}][[-1]]
```
>
> {37714500, {90, 85, 58, 85}}
>
>
>
] |
[Question]
[
Alex is a Truck Driver who wants to find the quickest way to deliver goods to multiple cities. He knows the distances between his destinations, but you need to write a program to help him find the quickest way to deliver goods to them.
**Input**
The first line of input gives the number of cities Alex needs to deliver goods to. Every line that follows gives the distance between the cities. The second line of input is always the distance between the first and second cities. If there is a third city, the third line of input is the distance between the first and third city. When to distance to the first city has been given for all cities, the next lines of input gives the distance between the the second city and every other city (except the first, as that information as already been given). This continues until every combination has been given. Sample inputs:
```
//Number of cities
4
//A -> B
2
//A -> C
4
//A -> D
3
//B -> C
5
//B -> D
1
//C -> D
3
3
6
4
2
```
**Output**
The output should print the quickest way to deliver goods to every destination in the form `A -> C -> D -> C -> A` (For every output, the reverse of will also work. You only need to print one solution). Alex ALWAYS starts at `A` and must always return to `A` at the end (as `A` is where he lives). Here are the outputs for the sample inputs above:
```
A -> B -> D -> C -> A
A -> C -> B -> A
```
**Rules**
The shortest code wins.
Happy Golfing!
[Answer]
# Python 2, ~~210~~ 205
```
from itertools import*
r=range(input())
d={t:input()for t in combinations(r,2)}
n=0,
print" -> ".join(chr(65+c)for c in n+min(permutations(r[1:]),key=lambda p:sum(d[min(t),max(t)]for t in zip(n+p,p+n)))+n)
```
**Edit:** Shortened according to Volatility's suggestion.
I'm amazed that it gets more readable and Pythonic the shorter it gets.
[Answer]
# C++ - 380
```
#include<iostream>
#include<algorithm>
#define I new int[n]
#define f for(i=0;i<n;++i)
using namespace std;int main(){int*a,**d,*s,n,i,j,t,b=2e9;cin>>n;d=new
int*[n];a=I;s=I;f{a[i]=i;d[i]=I;}f
for(j=i+1;j<n;++j){cin>>d[i][j];d[j][i]=d[i][j];}do{t=0;f
t+=d[a[i]][a[(i+1)%n]];if(t<b){b=t;copy(a,a+n,s);}}while(next_permutation(a+1,a+n));f
cout<<(char)(65+s[i])<<" -> ";cout<<"A\n";}
```
[Answer]
This a commentary rather than an entry.
If I am not mistaken, the sample data appear to correspond to an impossible set of distances between cities located in the plane.
The inter-city distances might be represented by a matrix

or, perhaps more conveniently, by a graph in which the edge labels are distances. (Note: The graph is not a geographical map.)

The figure below arbitrarily sets A at the origin of a coordinate plane. The distances from A to B, C, and D constrain the latter three cities to positions on circles with center at A and radii of 2, 4, and 3 units. We may arbitrarily place B at (0,2) and continue. Now, because D is one unit away from B and 3 units away from A, it must lie at (0, 3).
But there would appear to exist no position in the plane that is simultaneously 4, 5, and 3 units away from A, B, and D respectively.

---
The impossibility of the data would not detected by most approaches, although I suspect that a multidimensional scaling analysis would return a stress value that should raise a flag.
[Answer]
### Ruby, 242 characters
```
s,a,c,i=gets.to_i-1,[],[],0
0.upto(s){|x|x.upto(s){|y|a[y]||=[];a[x][y]=a[y][x]=x==y ?0:gets.to_f}}
(0..s).to_a.permutation{|x|x[0]<1&&c<<[(0..s).reduce(0){|y,z|y+a[x[z]][x[z-1]]},x]}
puts c.min_by{|x|x[0]}[1].map{|x|(x+65).chr+" -> "}*""+"A"
```
This finds the shortest path that never visits the same city twice. If triangle inequality is satisfied, no city should be visited twice. If the triangle inequality is broken, visiting the same city twice may be beneficial. If there are negative cycles, no optimal solution exists, as you can keep driving along the cycle to travel back in time. In practice, triangle inequality (and thus non-negativity) is safe to assume.
The algorithm itself is brute-force and inefficient. Don't use for maps with more than 10 or 12 cities. Three words: `O(n!)`
[Answer]
### GolfScript, 118 108 characters
```
~](:€,{.€-~:§2$>\)[0]*@§<+}%€.?,{€base}%{$€,1>=},{[0].@+\+.0\{.@[\]$~\5$==@+\}*;[\]}%$\;0=1={65+}%""+" -> "*
```
A quite clumsy (i.e. really slow) 118 characters GolfScript program.
Example:
```
> 4 2 4 3 5 1 3
A -> B -> D -> C -> A
> 3 6 4 2
A -> B -> C -> A
```
] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win.
Closed 8 years ago.
[Improve this question](/posts/7237/edit)
## Background
As described here <http://www.ericharshbarger.org/dice/#gofirst_4d12>, "Go First" Dice is a set of four dice, each with unique numbering, so that:
* There will never be a tie. Each die has a unique set of numbers.
* Regardless of what subset of dice are rolled against one another, each player will always have an equal chance of rolling the high number.
Here is the specific numbering for the four dice mentioned, as an example:
```
DICE COUNT: 4
FACE COUNT: 12
D1: 1,8,11,14,19,22,27,30,35,38,41,48
D2: 2,7,10,15,18,23,26,31,34,39,42,47
D3: 3,6,12,13,17,24,25,32,36,37,43,46
D4: 4,5, 9,16,20,21,28,29,33,40,44,45
```
[(via)](http://www.ericharshbarger.org/dice/4d12_fairness_report.txt)
## Goal
Without requiring any *particular* result, I would like to be able to generate a set of `N` "Go First" dice... Such that, example output **might** look like so (formatted, python console):
```
>>> generate_dice(players=4)
[[1,8,11,14,19,22,27,30,35,38,41,48],
[2,7,10,15,18,23,26,31,34,39,42,47],
[3,6,12,13,17,24,25,32,36,37,43,46],
[4,5,9,16,20,21,28,29,33,40,44,45]]
```
The number of sides here is chosen just for example purposes, because it matches the other example given. The number of sides of the dice can be determined by the algorithm used.
Ideally the solution would be in Python, but I can also read PHP, Javascript, some Ruby, quite well.
I'm honestly puzzling over this, and would love to understand what terminology/math I should have studied to figure this out. I've tried to explain it before, but seem to be having trouble not using words that imply too many things about what should be generated, and what odds should be, etc. I'm specifically interested in being able to generate "a set of N 'Go First' dice".
## Extra
Here's some ugly python, to "prove" the dice, and perhaps give an example.
```
def fair_chance(die1, die2):
wins = 0
losses = 0
ties = 0
for i in die1:
for x in die2:
if cmp(i, x) < 0:
losses += 1
if cmp(i, x) > 0:
wins += 1
if cmp(i, x) == 0:
ties += 1
if wins == losses and losses != 0 and ties == 0:
return True
return False
```
Give the above example dice:
```
D1 = [1,8,11,14,19,22,27,30,35,38,41,48]
D2 = [2,7,10,15,18,23,26,31,34,39,42,47]
D3 = [3,6,12,13,17,24,25,32,36,37,43,46]
D4 = [4,5, 9,16,20,21,28,29,33,40,44,45]
fair_chance(D1, D2) # True
fair_chance(D1, D3) # True
fair_chance(D1, D4) # True
fair_chance(D2, D3) # True
fair_chance(D2, D4) # True
fair_chance(D3, D4) # True
```
Thus, the function `generate_dice` should work, such that output in a Python shell would look like this:
```
>>> dice = generate_dice(players=4)
>>> D1 = dice[0]
>>> D2 = dice[1]
>>> D3 = dice[2]
>>> D4 = dice[3]
>>> fair_chance(D1, D2)
True
>>> fair_chance(D1, D3)
True
>>> fair_chance(D1, D4)
True
>>> fair_chance(D2, D3)
True
>>> fair_chance(D2, D4)
True
>>> fair_chance(D3, D4)
True
```
[Answer]
My python is a little rusty because I haven't used it in a very long time, but how about something like this:
```
def generate_dice(count, sides = 12):
dice = []
for i in range(count):
dice.append([])
value = 0
for sindex in range(sides):
if sindex % 2:
for dindex in range(count):
value += 1
dice[dindex].append(value)
else:
for dindex in reversed(range(count)):
value += 1
dice[dindex].append(value)
return dice
```
The pattern here is simpler than the one you linked, but it appears to work as long as the number of sides on the dice is even. I originally did this in C# and then converted it to python.
[Answer]
Well, I believe that this deals with telescoping series. As it turns out, the number of dice and number of sides you use is very important. For example, try to make 4, 4 sided dice that fits the same requirement.
Using the numbers from 1 to 16, one of the dice has to get the number 16.
Which ever dice has 16 already has a 25% chance of landing on the highest number when all 4 are rolled. However, the chance that any particular dice is first must = 25%. Thus, the remaining numbers must have 0% chance of being the highest number. This makes the first dice [1,2,3,16]. However this doesn't fit the requirement that when rolling 2 dice, you still have a equal probability of going first. Now you only have 25% instead of 50%. Thus when you have 4 dice, you must have more than 4 sides for these requirements to work.
I think the fact that they used 4 d12 is not just by chance. I would bet it's the minimum number of sides for 4 dice that works. I think if 4d8 or 4d6 worked, they would have just done that, because it's simpler to prove correct.
Thus, with 4 dice, you need a number of sides which is >=12 to meet all the properties.
In the example, the die with the highest number (48) has only a 1/12 of getting that number. Since this die has a 1/12 of going first, it should also have a 1/12 of going last, so it gets a (1).
Notice that the relative order of the numbers of each dice forms a sort of palindrome of pairs.
(1 4) (3 2) (3 2) (3 2) (3 2) (1 4) the first dice sequence
This is obviously on purpose. I'd check to see if other palindromes have the same property.
] |
[Question]
[
Consider an array A of integers of length n. The k-max subarray sum asks us to find up to \$k \leq 3\$ (contiguous) non overlapping subarrays of A with maximum sum. If A is all negative then this sum will be 0. If A = [-1, 2, -1, 2, -1, 2, 2] and k=2 for example, then the two subarrays could be [2, -1, 2] and [2, 2] with total sum 7.
# Task
Output a list of index pairs representing the subarrays that are being used to form the final k-max subarray sum. In the example just shown I would like the output to be `[(1, 3), (5, 6]]` to show the subarrays as index pairs in the original array.
# Examples:
```
[8, -5, 1, 0, -6, -7, 2, 4, 0, -1, -1, 6, -2, 5, 7, 8]
k = 1 should give [(6, 15)].
k = 2 should give [(0,0), (6, 15)].
k = 3 should give [(0,0), (6,7), (11, 15)]
[-3, 0, 2, 2, 0, 0, -1, 1, 3, -2]
k = 1 should give [(1, 8)]
k = 2 should give [(1, 3), (7, 8)]
k = 3 should give [(1, 3), (7, 8)]
[2, 5, -5, 5, 2, -6, 3, -4, 3, -3, -1, 1, 5, -2, 2, -5]
k = 1 should give [(0, 4)]
k = 2 should give [(0, 4), (11, 12)]
k = 3 should give [(0, 1), (3, 4), (11, 12)]
[2, -12, -3, 5, -14, -4, 13, 3, 13, -6, -10, -7, -2, -1, 0, -2, 10, -9, -4, 15]
k = 1 should give [(6, 8]]
k = 2 should give [(6, 8), (19, 19)]
k = 3 should give [(6, 8), (16, 16), (19, 19)]
[1, 1, -1, 1, -1, -1, -1, -1, 1, 1, -1, 1, 1, -1, 1, 1, 1, -1, -1, 1]
k = 1 should give [(8, 16)]
k = 2 should give [(0, 1), (8, 16)]
k = 3 should give [(0, 1), (3, 3), (8, 16)]
```
You can 1-index if you prefer. You may also output a flat list of indices rather than a list of pairs.
# Input
An array of integers and a positive integer k.
**k will be at most 3.**
# Restriction
Your code should run in **linear time**. That is, its running time must be \$O(n)\$.
[Answer]
# [Python 3](https://docs.python.org/3/), 484 bytes
```
def m(r,x):
b=c=t=0;s=(0,0)
for f in range(len(r)):
c+=r[f]
if c>t:t=c;s=(b+x,f+x+1)
if c<=0:b=f+1;c=0
return s,t
def f(r,k):
p=[]
for j in range(k):
n=x=(0,0);i=a=0;g=[*zip([*zip(x,*p)][1],[*zip(*p,(len(r),))][0])]
for s in p:
z,t=m([-a for a in r[s[0]:s[1]]],s[0])
if i<t:i=t;n=z;h=s
for s in g:
z,t=m(r[s[0]:s[1]],s[0])
if a<t:a=t;x=z
if a<i:p.remove(h);p+=[(h[0],n[0]),(n[1],h[1])]
elif x[0]<x[1]:p+=[x]
p.sort()
return[(q[0],q[1]-1)for q in p]
```
[Try it online!](https://tio.run/##VVPRcqowEH3nK3b6lEjogNrbFkx/JJMH9AblqhghvZNrp9/u3U2w4gxJNmfPObsJYP@53albXK@/TQNH1gvPywTWciOdzKtBslzkPIHm1EMDbQd93W0NO5iO9ZyYsEllrxqNUdvA5sOVTm5It069aFKfFnxMrWRermWTFtVG5gn0xn32HQzCJVS6wdJ7MrRS6Vjvz71eyEAnfeynamWN3W2lml1ay@LsxcxyrQot4n5mxdin4IjnmlOTZDyQsSVHuAgnj0xldUjUoaIakFwO6KS1oJhOQEdoV65spas6eal2cpi6bSduU4MHfY36GvVeXpIRaEv73Jvj6a9hO17ZVCq2Q4XoSCZYR8fZ4RR6NwfUeMysPEIlsT3h9nk49Y7x26UqdiaPM5KyglOP53BifTW@PtqDGUCCStSbgOxFQCEgx@gXjlcBcwHLCBRxEI4gEjH7pkWiskUgzMOT/5DxWRCXKJggBdnTSkQqEAjLcV1EGekCdz7yXkaDrCCEaDFfkDCoi4AtblFovcgpeqVpPhpDPu4gJt9/9KFEbDm7L9PxkHyIpiSd6ITu13i64Nvthm8BbN92jhnPJ7sYk2J//7gLseRRcic2T3t8R1/7b8g@4KtBG/w7vp8evK7/AQ "Python 3 – Try It Online")
Probably still a fair amount of golf left in this, but this is as far as I'm willing to take it for now.
### Explanation
The important realization here was that we can find the maximal \$k\$ subarrays iteratively. We start with function `m` which simply finds the maximal subarray given an array. To find \$k=1\$ you simply call `m`. From here, for any \$n>0\$ to find the solution for \$k=n+1\$ we start with the solution for \$k=n\$. From there we either break one of our subarrays into two, leaving out some negative middle part, add a new subarray, or do nothing. To figure out which is best we run `m` on all the sections between the subarrays we have and an inverted `m` on the subarrays we have, and take whichever adds the greatest amount to our total. So the function `f` simply performs this process \$k\$ times, leaving us with the desired result.
### Time complexity
The time complexity is pretty straightforward with this algorithm. Function `m` is linear with respect to the length of `r`. For `f` then, we first note that the size of `p` never exceeds `k`, thus for a fixed `k` things like `p.sort()` are constant time. So the only two lines that really contribute in `f` are `z,t=m([-a for a in r[s[0]:s[1]]],s[0])` and `z,t=m(r[s[0]:s[1]],s[0])` both of which are linear with respect to the length of `r`, and thus so is `f` itself.
] |
[Question]
[
This challenge arises from a claim made in [a MathOverflow answer](https://mathoverflow.net/a/291608) and a paper linked in that answer which seems to back up the claim:
>
> Searching for triangular embeddings is much quicker than enumerating over all embeddings… In fact, [Jungerman](https://core.ac.uk/download/pdf/82616223.pdf) was able to find a triangular embedding of \$K\_{18}-K\_3\$ in about half an hour back in the 1970s.
>
>
>
Some definitions must be made here. A *combinatorial embedding* of a graph embedded in an orientable surface is an ordered [adjacency list](https://en.wikipedia.org/wiki/Adjacency_list), where the list of neighbours for each vertex \$v\$ reflects their order when going around \$v\$ in a certain direction, which is the same for all vertices.

A combinatorial embedding corresponding to the above graph, embedded on the torus, is
```
0: 1 3 5 6
1: 0 6 3 2
2: 1 4 6 3
3: 0 2 1 4
4: 2 5 3
5: 0 4 6
6: 0 5 2 1
```
The neighbours are listed clockwise for all vertices. This embedding is the same as the one above because the neighbour lists for each vertex have only been cyclically permuted:
```
0: 3 5 6 1
1: 6 3 2 0
2: 1 4 6 3
3: 4 0 2 1
4: 3 2 5
5: 4 6 0
6: 2 1 0 5
```
However, if the neighbour list for vertex 5 was changed to `4 0 6`, it would no longer be a combinatorial embedding because `4 0 6` is not a cyclic permutation of `0 4 6`.
A *triangular embedding* is a combinatorial embedding satisfying rule R\*, which when coupled with the vertex-edge-genus relationship that will be introduced later on *guarantees* that the embedding may be drawn on the surface without crossings and with all faces triangular:
>
> If in the row for vertex `i` there appear the three consecutive vertices `j k l` in that order (reading forwards and wrapping around if necessary), in the row for vertex `k` there must appear the three consecutive vertices `l i j` in that order. This must hold for all adjacent vertex pairs `i` and `k`.
>
>
>
For example, the graph \$K\_{10}-K\_3\$ (a 10-vertex complete graph, or \$K\_{10}\$, where the edges between 3 vertices have been removed, i.e. a \$K\_3\$ is missing) has the following triangular embedding:
```
0: 1 7 6 2 8 5 4 9 3
1: 2 7 0 3 8 6 5 9 4
2: 3 7 1 4 8 0 6 9 5
3: 4 7 2 5 8 1 0 9 6
4: 5 7 3 6 8 2 1 9 0
5: 6 7 4 0 8 3 2 9 1
6: 0 7 5 1 8 4 3 9 2
7: 0 1 2 3 4 5 6
8: 0 2 4 6 1 3 5
9: 0 4 1 5 2 6 3
```
This embedding satisfies rule R\*. For example, `9 5 3` appears in row `2`, so `3 2 9` should appear in row `5`, and it does.
It is not necessary to specify the genus of the surface on which a triangular embedding lives (can be drawn) on, since the graph contains all necessary information: count the number of edges \$E\$ and number of vertices \$V\$. Since all faces are triangles, the faces number \$F=2E/3\$. Then by Euler's formula the genus is
$$\frac12(2-(V-E+F))=1+\frac{E/3-V}2$$
For example, the embedding of \$K\_{10}-K\_3\$ above has 10 vertices and 42 edges, so it lives on the surface of genus \$1+(14-10)/2=3\$.
While rule R\* is fairly strong I still doubt that it makes searching for triangular embeddings – or proving their non-existence – much easier, especially since you still need to consider all permutations of neighbours for one vertex at the start. No code was provided in the MO answer or by Jungerman, so I'd like your help in "reconstructing" it.
## Task
Write the [fastest-code](/questions/tagged/fastest-code "show questions tagged 'fastest-code'") that when given a graph in any reasonable format, determines whether a triangular embedding of the graph exists and outputs one such embedding if it does exist. If no embedding exists the program must indicate this in a halting manner (returning something else, raising an error, etc.) – it cannot run forever.
Your code must work in principle for an arbitrary input graph, which you may assume is [3-connected](https://en.wikipedia.org/wiki/K-vertex-connected_graph) and would live on a surface of **positive integer** genus, calculated by \$1+\frac{E/3-V}2\$, *if* it could be triangularly embedded. (This implies that the input is non-planar.)
The code will be run on my Lenovo ThinkPad E14 Gen 2 laptop with an 8-core Intel Core i7 processor running Ubuntu 22.10. A program's score is the sum of time needed over the six inputs below – the lower the better. You may output the embedding in any reasonable format, as long as the order of neighbours for each vertex is clear. I encourage you to post the results for your code on your own machine for my reference.
## Graphs with triangular embeddings
The graphs below are given as *unordered* adjacency lists.
* \$K\_{10}-C\_9\$ (on genus 2), where \$C\_9\$ is a 9-vertex cycle. I obtained an embedding of \$J(5,2)\$ from this by deleting 6 edges (see below):
```
0: 1 2 3 4 5 6 7 8 9
1: 0 2 3 4 6 7 8
2: 0 1 3 4 5 7 9
3: 0 1 2 5 6 8 9
4: 0 1 2 5 6 7 8
5: 0 2 3 4 6 7 9
6: 0 1 3 4 5 8 9
7: 0 1 2 4 5 8 9
8: 0 1 3 4 6 7 9
9: 0 2 3 5 6 7 8
```
* \$K\_{13}-K\_3\$ (on genus 7) from Jungerman's paper, which says that a triangular embedding was computed in "about 2 seconds" on a PDP-15:
```
0: 1 2 3 4 5 6 7 8 9 10 11 12
1: 0 2 3 4 5 6 7 8 9 10 11 12
2: 0 1 3 4 5 6 7 8 9 10 11 12
3: 0 1 2 4 5 6 7 8 9 10 11 12
4: 0 1 2 3 5 6 7 8 9 10 11 12
5: 0 1 2 3 4 6 7 8 9 10 11 12
6: 0 1 2 3 4 5 7 8 9 10 11 12
7: 0 1 2 3 4 5 6 8 9 10 11 12
8: 0 1 2 3 4 5 6 7 9 10 11 12
9: 0 1 2 3 4 5 6 7 8 10 11 12
10: 0 1 2 3 4 5 6 7 8 9
11: 0 1 2 3 4 5 6 7 8 9
12: 0 1 2 3 4 5 6 7 8 9
```
* \$K\_{18}-K\_3\$ (on genus 17) from Jungerman's paper, "about 25 minutes" on the same machine:
```
0: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
1: 0 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
2: 0 1 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
3: 0 1 2 4 5 6 7 8 9 10 11 12 13 14 15 16 17
4: 0 1 2 3 5 6 7 8 9 10 11 12 13 14 15 16 17
5: 0 1 2 3 4 6 7 8 9 10 11 12 13 14 15 16 17
6: 0 1 2 3 4 5 7 8 9 10 11 12 13 14 15 16 17
7: 0 1 2 3 4 5 6 8 9 10 11 12 13 14 15 16 17
8: 0 1 2 3 4 5 6 7 9 10 11 12 13 14 15 16 17
9: 0 1 2 3 4 5 6 7 8 10 11 12 13 14 15 16 17
10: 0 1 2 3 4 5 6 7 8 9 11 12 13 14 15 16 17
11: 0 1 2 3 4 5 6 7 8 9 10 12 13 14 15 16 17
12: 0 1 2 3 4 5 6 7 8 9 10 11 13 14 15 16 17
13: 0 1 2 3 4 5 6 7 8 9 10 11 12 14 15 16 17
14: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 15 16 17
15: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
16: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
17: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
```
## Graphs without triangular embeddings
* \$K\_{4,2,2,2}\$ (on genus 2), a [complete tetrapartite graph](https://en.wikipedia.org/wiki/Multipartite_graph) with partition sizes \$\{4,2,2,2\}\$ and the subject of the MathOverflow question:
```
0: 4 5 6 7 8 9
1: 4 5 6 7 8 9
2: 4 5 6 7 8 9
3: 4 5 6 7 8 9
4: 0 1 2 3 6 7 8 9
5: 0 1 2 3 6 7 8 9
6: 0 1 2 3 4 5 8 9
7: 0 1 2 3 4 5 8 9
8: 0 1 2 3 4 5 6 7
9: 0 1 2 3 4 5 6 7
```
* The Johnson graph \$J(5,2)\$ (on genus 1), subject of the same [MathsSE question](https://math.stackexchange.com/q/4651074/357390) that inspired my [fundamental polygon challenge](https://codegolf.stackexchange.com/q/258896/110698):
```
0: 1 2 3 4 5 6
1: 0 2 3 4 7 8
2: 0 1 3 5 7 9
3: 0 1 2 6 8 9
4: 0 1 5 6 7 8
5: 0 2 4 6 7 9
6: 0 3 4 5 8 9
7: 1 2 4 5 8 9
8: 1 3 4 6 7 9
9: 2 3 5 6 7 8
```
* \$K\_{13}-K\_6\$ (on genus 5) from Jungerman's paper:
```
0: 1 2 3 4 5 6 7 8 9 10 11 12
1: 0 2 3 4 5 6 7 8 9 10 11 12
2: 0 1 3 4 5 6 7 8 9 10 11 12
3: 0 1 2 4 5 6 7 8 9 10 11 12
4: 0 1 2 3 5 6 7 8 9 10 11 12
5: 0 1 2 3 4 6 7 8 9 10 11 12
6: 0 1 2 3 4 5 7 8 9 10 11 12
7: 0 1 2 3 4 5 6
8: 0 1 2 3 4 5 6
9: 0 1 2 3 4 5 6
10: 0 1 2 3 4 5 6
11: 0 1 2 3 4 5 6
12: 0 1 2 3 4 5 6
```
[Answer]
# Python 3 + Google OR-Tools
A fairly direct encoding of the problem; takes a list of lists of adjacent indices for each variable. I suspect it might be possible to do better by introducing variables for the triangles, but then sub-cycles become a problem.
```
from ortools.sat.python import cp_model
def embed(g, log_search_progress=False):
model = cp_model.CpModel()
edges = [{} for _ in g]
for i, g_i in enumerate(g):
e = edges[i]
for j in g_i:
g_j = g[j]
for k in g_i:
if j == k:
continue
if k not in g_j:
continue
e[(j, k)] = model.NewBoolVar(f'e_{(j, k)}')
index = {j: p for p, j in enumerate(g_i)}
model.AddCircuit([(index[j], index[k], v) for (j, k), v in e.items()])
for i, (g_i, e_i) in enumerate(zip(g, edges)):
for j in g_i:
for k in g_i:
if (j, k) not in e_i:
continue
v0 = e_i[(j, k)]
for l in g_i:
if (k, l) not in e_i:
continue
v1 = e_i[(k, l)]
if l == j:
model.AddBoolOr([v0.Not(), v1.Not()])
continue
e_k = edges[k]
v2 = e_k[(l, i)]
v3 = e_k[(i, j)]
model.AddBoolOr([v0.Not(), v1.Not(), v2])
model.AddBoolOr([v0.Not(), v1.Not(), v3])
solver = cp_model.CpSolver()
if log_search_progress:
solver.parameters.log_search_progress = True
solver.parameters.linearization_level = 2
status = solver.Solve(model)
if status != 4:
return None
embedding = [[] for _ in g]
for i, (e_i, emb_i) in enumerate(zip(edges, embedding)):
succ = {}
for (j, k), v in e_i.items():
if solver.Value(v):
succ[j] = k
j = j0 = next(iter(succ))
while True:
emb_i.append(j)
j = succ[j]
if j == j0:
break
return embedding
```
] |
[Question]
[
**This question already has answers here**:
[What's a half on the clock?](/questions/68031/whats-a-half-on-the-clock)
(23 answers)
Closed 3 years ago.
We know that not all fractions have a terminating binary representation. However every fraction can be written as a leading portion followed by a repeating portion. For example \$1/3\$ starts with \$0.\$ and then just repeats \$01\$ endlessly. This corresponds to the bar notation taught in primary school. For example
$$
1/3 = 0.\overline{01}
$$
Where the portion with the bar is the repeating section.
For numbers with a terminating representation, (e.g. \$1/2 = 0.1\$) the repeating section is just \$0\$, since there are endless implicit zeros at the end of a terminating representation.
We will call the minimum1 length of the repeating section the binary period of the fraction.
Your task is to write a program or function which takes a positive integer \$n\$ as input and outputs the binary period of \$1/n\$.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so answers will be scored in bytes with fewer bytes being better.
[OEIS A007733](http://oeis.org/A007733)
---
1: We say minimum because if you duplicate a section again it keeps a valid representation. (e.g. \$0.\overline{01} = 0.\overline{0101}\$)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
2*Ɱ%µẠȧQL
```
A monadic Link accepting a positive integer, `n`, which yields a positive integer, the period.
**[Try it online!](https://tio.run/##y0rNyan8/99I69HGdaqHtj7cteDE8kCf/0ARMwA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##ASUA2v9qZWxsef//Mirisa4lwrXhuqDIp1FM/1LFvMOH4oKsR///MTAw "Jelly – Try It Online").
### How?
```
2*Ɱ%µẠȧQL - Link: integer, n
2 - literal two
Ɱ - map across [1..n]
* - exponentiate -> [1,2,4,8,...,2^n]
% - modulo n -> [1%n,2%n,4%n,8%n,...,2^n%n]
µ - start a new monadic chain - call that X
Ạ - all (X)? -> 0 if we reach zero, else 1 - i.e. 0 if n is a power of 2
Q - de-duplicate (X) -> the repeating 2^k%n values
ȧ - logical AND -> 0 if n is a power of 2 else Q(X)
L - length (0 has a length of 1 (after an implicit make_digits))
```
[Answer]
# [Python 3](https://docs.python.org/3/), 70 bytes
```
f=lambda k,a=1:k%2and(a/k%1and f(k,a*2+1)or len(bin(a))-2)or f(k//2,a)
```
[Try it online!](https://tio.run/##FYtBCoMwEEXX7SkGQZipkZBxJ6R3GdG0Q@wowU1Pn6a799/nnd/rfdhUa4q7fJZVIDuJYc49i60oPvehASRs/sFDoKPAvhkuaihEI/9Fe71nJ1RTWwpqUMReGwYHE9N8v51F7UJ10MVn51qgRPUH "Python 3 – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 30 bytes
```
Length@@#&@@RealDigits[1/#,2]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2773yc1L70kw8FBWc3BISg1McclMz2zpDjaUF9ZxyhW7X9AUWZeib5Dur5DUGJeeqqDkcH//wA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 33 bytes
```
Nθ⊞υ¹W¬№﹪υθ﹪⊕Συθ⊞υ⊕ΣυI⊕⌕﹪⮌υθ﹪⊕Συθ
```
[Try it online!](https://tio.run/##jY27CsMwDEX3foVHGdLBc8ZAIUNDab7AtQU2@NHYVvr5rg3NUOhQTRL36hxlZFJRulrn8KSykH9ggo2PpxtlAzQw0faXsQ4ZLLHAFCkUuEZNLvZ44wP7XHNQCT2GghpW8kCc97wNO2A/Kl2VbGNOMpcvxsUGfZjuuGPK2B7@VPKxViHqeXdv "Charcoal – Try It Online") Link is to verbose version of code. Sadly all my attempts to golf this down tended to break on edge cases such as `1` or other powers of `2`. Explanation:
```
Nθ
```
Input `n`.
```
⊞υ¹
```
Start with a list containing just `2⁰`.
```
W¬№﹪υθ﹪⊕Συθ
```
See if the next power of 2 is equivalent (modulo n) to any of the elements in the list.
```
⊞υ⊕Συ
```
If not then push that power of 2 to the list.
```
I⊕⌕﹪⮌υθ﹪⊕Συθ
```
Print the difference in the two exponents.
[Answer]
# [Python](https://docs.python.org/3.8/), 49 bytes
```
lambda n:len({2**-~k%n*(n&~-n)for k in range(n)})
```
An unnamed function accepting a positive integer, `n`, which returns a positive integer, the period.
**[Try it online!](https://tio.run/##RYtBCsIwEADvvmIv2t3QirGXEtCXeImYaGm7DXEvEtKvx9aLcxkYmPCR18xtF2Lxl1sZ7XR/WGAzOsZ0VqpZhj0r5MPSMPk5wgA9Q7T8dMiUqWxN3Fv@WdegT5rMDlZC7FmwSubaZgMpV0dYj8kKblMN/mciKl8 "Python – Try It Online")**
] |
[Question]
[
**This question already has answers here**:
[Yarr! A map to the hidden treasure!](/questions/54301/yarr-a-map-to-the-hidden-treasure)
(17 answers)
Closed 4 years ago.
(This is not a duplicate of [Follow the path](https://codegolf.stackexchange.com/questions/68282/follow-the-path), as this challenge have invalid path detection and use `><^v` in the output.)
# Task
So your task is to take in the description of the path and draw it out in a "Befunge(or a lot of other 2D esolangs)-like" format, and detect if it is invalid. Note that if the path is invalid, you shall not output anything except a printable custom character which cannot be one of `><^v` or space.
* The path would be invalid if the path is crossed.
* Or, if you moved off the top or left edge.
You begins at the top-left corner.
* `>n` moves you right n characters. Your trail is `>`.
* `^n` moves you up n characters. Your trail is `^`.
* `<n` moves you left n characters. Your trail is `<`.
* `vn` moves you down n characters. Your trail is `v`.
# Test Cases
```
Input: >3v3
Output:
>>>v
v
v
Input: v4>1^2>3
Output:
v
v
v>>>
v^
>^
Input: >5<3
Output:
!
(Or any character you want, except ><^v and space.)
Input: [NONE]
Output: [NONE]
Input: >4v2<2^2
Output:
>>>>v
^ v
^<<
Input: >4v2<2^3
Output:
!
(Or any character you want, except ><^v and space.)
Input:
>3v3<6
Output:
!
(Or any character you want, except ><^v and space.)
```
# Rules
* Standard loopholes are forbidden.
* Least bytes wins.
* This was written in a hurry.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 46 bytes
```
≔⁰ηF⪪S²FI§ι¹«≧⁺℅KKη✳⊗⌕>^<§ι⁰§ι⁰≧⁺∨‹ⅈ⁰‹ⅉ⁰η¿η«⎚!
```
[Try it online!](https://tio.run/##dY4xa8MwEIVn@1conp5AAdd0awiEhEIgoaZZ2iWg2Ip9VMhGkkOh5LerttWhFDrc8O6O73tVK23VSR3CxjlqDHLBWv6UXjvLcOo1eexNP/iTt2QacMEKztlXmswPW@k8Nn5vavUJEuyBx2NylH3kvVLTepR6cIK92JqM1CiV@gDnUZQk5Uj22JFVlafOYNcNF61qPJOpka3Pq0ywX458dPC/m5FzT/@z4qCcw9tUPh9nTu8x/ZS4p3RlaOfuW62kxUSMxbJFNn2EsH68FaviXITlTX8D "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔⁰η
```
Assume everything is OK.
```
F⪪S²
```
Loop over the instructions.
```
FI§ι¹«
```
Loop over the number of steps.
```
≧⁺℅KKη
```
Check whether the path has crossed.
```
✳⊗⌕>^<§ι⁰§ι⁰
```
Output each character in the appropriate direction.
```
≧⁺∨‹ⅈ⁰‹ⅉ⁰η
```
Check whether the path has moved off the top or left edge.
```
¿η«⎚!
```
If something went wrong, replace the output with a `!`.
] |
[Question]
[
Print the ASCII version of a random grid.
```
################################################################################
# # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # #
# # ############# # # # # # # # # # # # # #
########## # # ##################### # # # # ##### ########
# # # # # # # # # ####################### ##### # ##
# # # # # # # # # # # # # # # # # # #
# # # # # # ##### # # # # # # # # #########
########################## ####################################### # # #
# # # # # # # # # # # # # # # ##### # #
# # # # # # # # # # # # # # # # # ####
############### # # ##### # # # # # # # # # # #
# # # ######## # ################################### # ###### #
# # # # # ##### # # # # # # # ######### # #
###### # # # # # # # # # # # # # # # # #
```
The picture should illustrate the constraints:
* `#` is solid, is empty.
* Print 80 columns, at least 80 rows.
* On the first and last columns and first and last rows there is some freedom, but at least the printout must be extendible to a legal grid.
* Boxes contain `empty` areas between 1x1 and 7x7.
* Constraints: Boxes are rectangular, no lonely corners (1), no empty boxes (2), no broken lines(3) or gaps (4), when in doubt refer to the image above.
* A grid is considered "random", if the first 80 rows contain: 1.) 60 unique rows and 60 unique columns. 2.) At least one box with inner area of size (2, 2), (3, 2), (4, 2), (5, 2), (2, 3), (3, 3), (4, 3), (5, 3), (2, 4), (3, 4), (4, 4), (5, 4), (2, 5), (3, 5), (4, 5), (5, 5) *each*. You can verify the randomness and some constraints with [this julia script](https://tio.run/##tVbbbptAEH3nKyaOFS/yOmIttY4cOaqqKn6KFLXKE0EVxWt7MSwUcHNR/t2dZTH3tJHagC/47MyZmbMzGH8fCJc9Hg5LWMDgtOe4l6cA@Mrf5cU7oq/lAO33m9CKoX40bI/Gf0Vrrm1bvdLMt0zgPaPl6MAwjPVeepmIJPxyA7FyM/59k4gVWZqGcuFJghv8LUuE3NhODoVuRm5MRO0bWzi278A6SkCAkMDmAZebbIvrFPwmYjPH1ATc9bZJ9KBJcEFQmDdIUvHMyQ1lps6hzDAmgvoaU8ctuj/zJErJ5ygKKIjxlPrjac3AZjn1@QJYDeRy1QfPKbA@EM3bsC5DrlA@dXWDiYRuTDyYXIH9RXgZGZ2OFleA4UeAF5Zpe7pCT1XoORTSOBAZWVIY4DYUhYo1LO083GIBo3s5KiOqCKjgHBcnzCnDF06FxHspfu450b/OUV7ThJN63riZUUIGXhTsQ5mCjDJwgwCiNaRuyAuagdmm7/LajiK@sErmeJ9uTwjyYz11@uiYHBqrOivhKt1UNxn1IkMhyYWVC2@qjdJdR0Hium4NbR/qJODsrBE/iyJY8wfAFkvzmDqYUn@n1J/OP1AIiqtGM8VkhytV/2DtJ658IrdqP7BP52K8GzPqz/1xMGaNlg0nuwkre15OggmreLoaDXfwCMMAQpGmOFmlNHXlj9/N3a2GB3f3agEfLXh56a1fO1Qy/IFr9FayYm9rsl6rG4HNAM9L/LBwhmi@cMQsdXYw1sFY3S536vjmWMuOaTvWtOvmUmCswqwjXwNjHYz12NVqa/C9gnVitDWo1dGIYfXbsbZ@bV/rqKmyyyGnHIKyY2dVv5bNh/cDojt9Rn1121uAZfZNWOAmGw4/okdwMxgKOvQb890OVhuNWTsYruFEzf4hWre2@ixOy4B3cJxjPcVTp8oF5/wrX5M7M0/jGsz2KIgg4Bs3gHTrxhyGd28rfDKtZcJ6MpnmmbCeTEb/IZWEZ/tEgkh5GGdPyh1vqfhp5LJ5UZJwL6PF33znCeBTuo0eoLAyYnwIyM5zjkvjcPgN).
* The program should nondeterministically produce a minimum number of 1000 grids fulfilling the constraints with different first 80 rows, where rotations, circular shifts and reflections counted as same and the majority of produced grids should be "random" as specified above.
```
#####4########################
# # # #
# # # # # 3
# # ######### #
#########1 # # #########
# # # # ##2## # #
# # # # ##### # #
# # # # # # #####
```
Code golf!
[Answer]
# Julia, 254 bytes
Not very golfed, just to keep it going;
```
l=length
function f(M,r,s)
l(r)<7&&return l(s)>6&&g(M,r,s)
h,j=rand([f,g],2)
a,c=extrema(r)
b=rand(a+1:c-1)
M[b,s].=2
h(M,b+1:c,s)
j(M,a:b-1,s)
end
g(M,r,s)=f(M',s,r)
n=80
M=fill(1,n,n)
f(M,1:n,1:n)
for i∈1:n
print.(getindex.(" #",M[i,:]))
println()
end
```
Verification, [try it yourself](https://tio.run/##rVbvjtpGEP/up5jjEOyKBXmRGiKnPlVRlVM/oEatrl8cqzJmDWvWa2qbHInyAHnOvsh11muDDbSN1BoB3t/M/ObPzqydHpSM@PHlRflK6E21dZKDjiuZa0jIkhWspI4iBf1@MRoVojoUGhQp6cOr0WjTyrcs9YtIr0mQsE3I5tSJWOyLY1WILEJbZ2XF0YR78ZRTZxmsWBnO/LmzRY6VgQ1PiovIW025WQi9dloPPoYyZiVDKu2/dp2ln0ilCGeaaeqYOLmnzRcXeQHyz69fceHsC6mrGdmISuq1OM7IAO4HbBlI5oWUWrHSxPpyZA4@/PTz20OSiALBe/gtUnIdmVrcov1FJETmlMG/8aNS7eER@X@tENyQKtqJOyOgjnMu@EfrT/y@KeSaPFIH8BJFcbILwhrKooosKaIB@gqDNIQ6PJAauGd3EeUM0j4S8JBaAhHF2yJ/tiTEBAxej6SUn4WpKrUxnCLcE8lSi5nrPZp/FkVekrd5rhjIyZylk3lHIeA19cwH3gGxGrdgjwG/BaL6JWzTMNtW3y0xkCzakximDxD8KOOKjO/H/gOg@zHgjUuD2GYYmwzjkEG5V7IijwwGH/SgSVQm8BjU7nwfxh/0@OTReMAKeiic8vDkvjFqSnzQ8o@DIHY1w/JSCnfduHEz84IM4lwdMl2CziuIlII8gTLKREMzoJf017xBaIhxFFrm/aHc3hHkx3y69HkbHCqbPM@FO9fNdJPTTTKTmrx268JTs1G26xholNvWsPqZDQJGo57/Ks8hEc@ALVbWPq0zU/2dqf7c@46Bau56zbQnO5Sc@wdzv4v0J/Le7Af2qScnuwlnqZdO1IT3Wjab7vDgaHteT5U5aKB3dWMc7uAIQwWZLEucrFNpupVv//u7ex4e3N0HH1658OXLzfytwbkM/8A1/layZm87ZX1nDoKAA37e4I@LM8RqQYu55nOF8SuMd/VqoyvbGrvQ41aP9/WuY2kwfsbclq@H8SuM39Dr5Nbj@xvsysdlDTp59Hy4t/X4Zf0ubd22pkavhsLTEJw6dnHu11Pz4XlAbKcvWGqOPR9cemvCVFRsBKzyI0QVDCUbpr35vnTWGY3FpTOU4UQt/oO369y6szg/OXyCdo7tFM/Dcyw45@aZ@kTrMN4BvRwFfOaLTaSg3EZ7AcOnb0t8Ou9Ewm9EMq8j4TciGf8PoTQvTbIU2b76ZMzxSMVf@9IR50Uh4oo1j/mrN4Afym3@DI1W@@ZhON44Ly9/AQ)
] |
[Question]
[
This is a more complicated version of [this puzzle](https://codegolf.stackexchange.com/q/189515/73483). The premise is the same but a few rules differ in a few key places, making for a more complex problem.
Assume I have some number of black shirts and some number of white shirts, both at least 1. Both colors of shirt have a non-zero durability. All shirts of a given color start with the same durability.
Every day, I pick out a clean shirt to wear, and it becomes dirty. Once I run out of all clean black shirts or all clean white shirts, I wash all my dirty shirts of both colors and start over. Clean shirts do not get washed. Whenever a shirt gets washed, its durability goes down by one. Immediately after washing, if the durability of a shirt reaches 0, it must be thrown out.
When picking which shirt to wear of a particular color, I specify whether I choose a shirt with highest (h) or lowest (l) remaining durability.
# Challenge:
Take in an arbitrarily long sequence of four indicators (eg. bh bh bl wl bl wh wl bh...) representing my choice of shirt to wear on that day. Continue execution until either my last black shirt or my last white shirt is thrown out. Once this occurs, stop consuming input and print out the remaining shirts’ durabilities.
## Inputs:
Number of black shirts, number of white shirts, durability of black shirts, durability of white shirts, and a sequence of shirt selections of arbitrary length at least long enough for one color of shirt to run out (can be considered infinitely long). The selection can be represented by a character pair (eg. bh, bl, wh, wl), or a single character (eg. b, B, w, W). Your choice, as long as there are four distinct inputs of 1 or 2 characters.
## Output:
Status of each remaining shirt, sorted by durability. All shirts will be of one color.
## Test cases:
The following test cases represent the amount of input the program should need to process before halting. The input is arbitrarily long otherwise.
```
1 1 1 1 bh
1
1 3 1 10 wh bh
10 10 9
1 5 2 10 wh wh bh wl wl wl bh
10 10 9 8 8
2 5 1 10 bh wh wh wl bl
10 10 9 9 9
1 5 6 5 wl wh bl wl wh bl wl wh bl wl wl bl wl wl wl bl wl wl wl wl bl
4 3 2 1
1 1 1 10 bl wh wh wh wh wh wh wh wh wh wh wh wh
10
#note the processing would stop occurring after the first bl and everything else should be ignored.
```
# General rules:
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins.
* Default I/O rules apply
[Answer]
# [Perl 5](https://www.perl.org/), 254 bytes
```
sub f{@s=map[$_>$_[0]||0,$_>$_[0]?$_[3]:$_[2],1],1..$_[0]+$_[1];while(join('',map$$\_[0],@s)=~/01|10/){($c,$p)=&{$\_[4]};(@w=sort{$p\*($$b[1]<=>$$a[1])}grep$$\_[2]&&$$\_[0]eq$c,@s)[0][2]=0;@s=grep$$\_[2]||++$$\_[2]&&--$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Ctqta3dLxa7snt0FLAr5hrTxwjrSB@TK9Y7k6c4fF/YNw76wrctz@1S1HYXZX/u9fN1Z616h/ofWfzvJFS1xVtH/Td4js5UybsvZZA0L78yB@GccUu0zWtMtIWJIjlmt0PGiIuMYbr4IX61MhPmxfeG3rjKieOaOM83R3nw8lWwwO8f/gM "Perl 5 – Try It Online")
Ungolfed but same – with tests:
```
use Test::More tests=>6;
sub fu {
my($countb,$countw,$durb,$durw,$get_todays)=@_; #get 5 inputs
my @s=( (map{{col=>'b',dur=>$durb,clean=>1}}1..$countb), #init shirts array
(map{{col=>'w',dur=>$durw,clean=>1}}1..$countw) );
while(join('',map$$\_{col},@s)=~/bw|wb/){ #while still both colors left
my($col,$p) = &$get\_todays; #todays color and preference
my @w = grep $$\_{clean} && $$\_{col} eq $col, @s; #@w=wearable shirts
my $shirt = (sort{$p\*($$b{dur}<=>$$a{dur})}@w)[0]; #pick todays shirt w/most|least durability left
$$shirt{clean}=0; #dirty in the evening
map{$$\_{clean}=1;$$\_{dur}--}grep!$$\_{clean},@s if @w==1; #wash if there was only one this morning
@s=grep$$\_{dur}>0,@s; #toss out worn outs
}
return sort{$b<=>$a}map$$_{dur},@s
}
my @test=(
'1 1 1 1 bh', '1',
'1 3 1 10 wh bh', '10 10 9',
'1 5 2 10 wh wh bh wl wl wl bh', '10 10 9 8 8',
'2 5 1 10 bh wh wh wl bl', '10 10 9 9 9',
'1 5 6 5 wl wh bl wl wh bl wl wh bl wl wl bl wl wl wl bl wl wl wl wl bl', '4 3 2 1',
'1 1 1 10 bl wh wh wh wh wh wh wh wh wh wh wh wh', '10' #should see sequence not empty
);
while(@test){
my($countb,$countw,$durb,$durw,@col)=split' ',shift@test;
my @expected =split' ',shift@test;
my $msg='';
my $feederu=sub{ (shift(@col)//do{@expected='!',$msg='sequence ran out!'})
=~/(.)(.)/;($1,{h=>1,l=>-1}->{$2}) };
my $feeder=sub{ (shift(@col)//do{@expected='!',$msg='sequence ran out!'})
=~/(.)(.)/;($1 eq 'w'||0,{h=>1,l=>-1}->{$2}) };
my @got=fu($countb,$countw,$durb,$durw,$feederu);
#my @got=f($countb,$countw,$durb,$durw,$feeder);
$msg='sequense not empty' if @col;
is(join(" ",@got),
join(" ",@expected), $msg);
}
```
] |
[Question]
[
For example, how many adjacent swaps are at least needed to convert some string such as `BVVKCV` to one without any instances of `VK`?
Input-length of the string will be within the range `1 <= length <= 200`.
`VK` will be hardcoded across all test cases.
Input string examples:
```
Input: VKVKVVVKVOVKVQKKKVVK
Output: 8
Input: VVKEVKK
Output: 3
Input: JUSTIN
Output: 0
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 44 bytes
```
m£Z¯Y cZtY2 Ô cZsY+2Ãrc
®¬ø"VK"
W+VÌ
Ve ?ß:W
```
[Try it online!](https://ethproductions.github.io/japt/?v=1.4.6&code=baNar1kgY1p0WTIg1CBjWnNZKzLDcmMKrqz4IlZLIgpXK1bMClZlID/fOlc=&input=W1siViIsIlYiLCJLIiwiRSIsIlYiLCJLIiwiSyJdXQotUQ==)
It times out on the first test case because it's super inefficient (something like O(n^n)?) but it should be a viable algorithm. Input is weird; it is a [singleton list](https://codegolf.meta.stackexchange.com/a/11884/71434) containing the input, but the input itself is formatted as a list of upper-case characters. I think that would typically be valid, but if not let me know.
Explanation:
```
#Step 1: try all the swaps
m #For each string Z reachable with n swaps (n starts at 0)
£ Ã # For each letter Y in Z:
Z¯Y # Get the letters before it in Z
c # Concat
ZtY2 Ô # Y swapped with the following character
c # Concat
ZsY+2 # The rest of Z
rc #Flatten by one level
#Result: A list of all strings reachable with n+1 swaps
#Step 2: Check for "VK"
®¬ #For each string from Step 1:
ø"VK" # Check whether it contains "VK"
#Result: A list where 1 indicates there was "VK" and 0 otherwise
#Step 3: Increment the counter appropriately
W+ #Increase the counter by
VÌ #The value for the original string when run through step 2
#Result: 0 if 0 swaps were required, the current number of swaps otherwise
#Step 4: Iterate or end
Ve ? #If all the reachable strings contain "VK"
ß # Repeat the program with the current values
:W #Otherwise return the counter
#Result: Outputs the counter when a non-"VK" string is found.
```
[Answer]
# [Python 3](https://docs.python.org/3/), 125 bytes
```
s={input()}
a=0
while all("VK"in q for q in s):a+=1;s={a[:i]+a[i+1]+a[i]+a[i+2:]for a in s for i in range(len(a)-1)}
print(a)
```
[Try it online!](https://tio.run/##K6gsycjPM/7/v9i2OjOvoLREQ7OWK9HWgKs8IzMnVSExJ0dDKcxbKTNPoVAhLb8ISAKZxZpWidq2htZAPYnRVpmx2onRmdqGYArCNrKKBSlOBCsG68sEMYsS89JTNXJS8zQSNXUNgRYVFGXmlQA5//@HeQNhGBD7A3GgtzeQ4w0A "Python 3 – Try It Online")
Basic BFS.
] |
[Question]
[
**Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/172627/edit).
Closed 5 years ago.
[Improve this question](/posts/172627/edit)
The goal is to simplify sentences containing multiple negatives.
Like with multiplying negative numbers, two negative words annihilate each other until at most one is left (doesn't matter which one). While some words disappear without a trace, other leave behind a positive part
The affected words are:
```
no
not
couldn't could
wouldn't would
shouldn't should
don't do
doesn't does
didn't did
isn't is
aren't are
weren't were
```
You will notice that I conveniently forgot to include some rules like shan't/shall, won't/will, nothing/something, impossible/possible.
Hunting down all the exceptions is a nightmare and would make it yet another string compression challenge.
But if including some additional rules that are not listed, yet are in the spirit of the challenge would make your code shorter (looking at you, Mathematica built-ins), by all means, go for it.
## Examples
### Input
```
Move along
Nothing to see here
This sentence will stay the same
You dont put Nosferatu's donut knot in the cantaloupe cannon without an apostrophe.
Don't change this sentence.
This one will also not change
So far no inputs were changed
We don't need no education!
No, don't say that!
Wouldn't it be nice if people weren't fighting?
I don't not use no double negatives.
This isn't not the usual way to not express yourself not
We don't not have no time to not don't solve this
I don't not even know if this isn't not making no sense anymore, it wouldn't be so bad if it weren't for not all these not words which not shouldn't be not there in the first place
```
### Output (either of the elements is valid)
```
["Move along"]
["Nothing to see here"]
["This sentence will stay the same"]
["You dont put Nosferatu's donut knot in the cantaloupe cannon without an apostrophe."]
["Don't change this sentence."]
["This one will also not change"]
["So far no inputs were changed"]
["We do need education!"]
[", do say that!", "do say that!", "Do say that!"]
["Would it be nice if people were fighting?"]
["I don't use double negatives.", "I do not use double negatives.", "I do use no double negatives."]
["This is the usual way to express yourself"]
["We don't have time to do solve this", "We do not have time to do solve this", "We do have no time to do solve this", "We do have time to not do solve this", "We do have time to don't solve this"]
["I do even know if this is making sense anymore, it would be so bad if it were for all these words which should be there in the first place"]
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 44 bytes
```
i`(\bnot?\W+|n't\b)(.*?)(\bnot?\W+|n't\b)
$2
```
[Try it online!](https://tio.run/##ZVLNittADL7PU2ihZbPtkkNfIJdC6aF7aSEUcljZlj3DTiQzmrEb6LunGtuhKb15pE/6fuREOTBe3@@@vF7D6@7UsOTD6fjxNz/mU/O02384PP1Xde8@Xa/fZCLAKDy4F8k@8ABZQInAUyL3wwe1F2filmAOMYJmvED2BIpncj@lQIucYSwZXkR7SpjLo0InbJU3o4TAC77CjKmMyycL277sxVDIgKNoTjJ62jv3WUwhtB55IBu9k7BfFQlvYjCqQOVYwe67QI/JKkZqihRmc7E1O@eOVHXZbibqKoq60mIOwg9m/3lr6mIQ84M7SoldLYUMDQEHCyH0MJKMkZbdtdmHwVv@w8G5rzCv@01SUaoUnZTGwEyDEU2km4WgN1zNpmjBCHMlXv3QrzGRKlykJKXYL8U7/fbyOC0EOZzpNrYZkDitwZmgvwM0EdeLzNVD/lfEGd/q7bnenk048uUsiZ6r8/mWgkVgcTfY1QW1cQtA0rIE7SLmZvFdx1JnB/Ch9ctb/d2ezbgdZ/s7@pDU/qKILf0B "Retina 0.8.2 – Try It Online") Link includes test cases.
] |
[Question]
[
**Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/171296/edit).
Closed 5 years ago.
[Improve this question](/posts/171296/edit)
## Challenge
Train a single perceptron with 2 inputs and 1 output.
[](https://i.stack.imgur.com/zLKXf.png)
**Step 1:** Initialize the weights
**Step 2:** Calculate the output
For inputs: [i1, i2, ..., in] and weights: [w1, w2, ..., wn] the output is:
```
i1 * w1 + i2 * w2 + ... + in * wn
```
**Step 3:** Apply activation function on the output (i.e sigmoid)
**Step 4:** Update the weights
```
w(t + 1) = w(t) + r * (desired_output - actual_output)
```
Where r: learning rate
**Step 5** Repeat steps 2, 3 and 4
## Input
**iterations**: how many times you repeat steps 2, 3 and 4
**input**: a list with 2 input values i.e. `[1, 0]`
**output**: the desired output
**learning\_rate**: the learning rate i.e.`0.3`
## Output
It should print the last calculated output. Keep in mind this should be very close to the desired output i.e `0.96564545` for desired output `1`
## Example
For input (training for XOR):
```
1000, [1 0], 1, 0.3
```
The output should be:
```
0.9966304251639512
```
**Note** The output will never be the same even for identical test cases due to random weights initialization.
Here's some non-golfed code in Python for this test case:
[Try it Online!](https://tio.run/##XZA9a8QwDIbn@FcIuthXXxr3tkKHTt0LnUIo5uxcBBfb@JQm1z@f2vmg0MWyJPS8ehXu1Hl3mrEPPhJE7Yzv2Zb1mrqZGdsCRY2OI9koAV0YSIIfaIlRvDBWPMDHMoo/FqizMFq8dHRjxQivUK/YcnDY@tjzSioB6QdfCZY1L5Y/i4YVrMhV/KtmxcQvUidJvFta4PpM@rotkBomSSxL1VVzGNMDj1uucq6aff4thOt9J@C3JvQO2sGdlw@/4aX3aMSGVPAEXCVWPkNpp8CPRoid9RmMpn9eV7MwpZkIB@DrhnAEs9qdsrERmnSvENERT1rzelpVVZWEWkmoGgk5lCcx/wI)
## Rules
1. The inputs and outputs of the perceptron are fixed to: 2 and 1 respectively.
2. The output needs to be close to the desired output (see example).
3. You can use any activation function you want, just mention it.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~121~~ 110 bytes
Same as TFled. A "golfed" version of the example.
*-11 bytes from @Arnauld*
```
with(Math)f=(a,[b,B],c,d)=>(g=w=>a--?g(w.map(_=>_+d*(c-(y=1/(1+exp(B*w[1]-b*w[0])))))):y)([random(),random()])
```
[Try it online!](https://tio.run/##NcbLCoMwEEDRX3E5oxOb0F0hCu77BSFITHwVNaLS1K9PH9C7Ofdhnma327gebPGujTGMxwB3cwzYSTCkGqo0WXIoC@hlkIVhrOwh5LNZoZZFnbkULINTiguIrH2tUKVBCc2aD1zjr9uJoDazOD8D0n80RuuX3U9tPvkeOhCcc0qUoIRrSr7kV8T4Bg "JavaScript (Node.js) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 136 bytes
```
from random import*
import math
def f(n,(i,I),o,r):w,W=random(),random();exec"d=1/(1+math.exp(-i*w-I*W));c=r*(o-d);w+=c;W+=c;"*n;print d
```
[Try it online!](https://tio.run/##NcuxDoMgFIXh3ae4cbrg1UK7lfAAPoFD08EIRAaBEBLt09Ma0@V8Z/nTp6wx3Gt1OW6Q52B@@C3FXHhzCdtc1sZYBw4DoaeRUaTMnjtN@iqQ0f8oe9ilNVreUHZnOdgjYe/53o98YkwtOnOMvWFq7/SipnNaHlTKPhQw1aEUQhC8JIF4E5wMD1a/ "Python 2 – Try It Online")
Basically just a golfed version of the example
] |
[Question]
[
### Backstory
If you visit the [Steward Badge Page](https://codegolf.stackexchange.com/help/badges/81/steward), you will see no one has received one of these badges from PPCG yet. However, there are two users:
**[DJMcMayhem](https://codegolf.stackexchange.com/users/31716/djmcmayhem)** & **[Martin Ender](https://codegolf.stackexchange.com/users/8478/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](https://codegolf.stackexchange.com/review/low-quality-posts/stats) reviews & Martin Ender's review count from [First Posts](https://codegolf.stackexchange.com/review/first-posts/stats) 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](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are not allowed.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes for each language wins!
[Sandbox post](https://codegolf.meta.stackexchange.com/a/15034/76365)
[Answer]
# [Red](http://www.red-lang.org), 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!](https://tio.run/##bU09T8MwEN3zK043wZB698AEC1IWVsuVrPO5sUhtxz7TRhW/PURsSGzv@1X2@wd7MHYnjbNIaVopyp4veQmnJo4@@U6zSxc@Ub6qyl@RbwpFA@WyAQ1e45Jv49rdEmUbS27S1FGUhqwxxNrkjzgEDaEnMg1Wa4qrjSHE5OHgRubaHyPlngRfztNZfbu0IeDvVwLJB34qNSYxKyT7bO0QoLLzhzX2uoArhY8tAo@v7xNNbpv5iv@HBBgnVyUmeEueK@77Dw "Red – Try It Online")
Unfortunately doesn't work in TIO - results in timeout, although works normally in Red console.
] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win.
Closed 6 years ago.
[Improve this question](/posts/132597/edit)
You have given an array from which we need to remove duplicates.
Rules:
1. First or immediate duplicates gets removed first.
2. Array contains natural numbers `a[i]>0 for i>=0`
3. no. of elements in the array is greater than 1 i.e. `n>1`
e.g.
```
{1,2,3,4,5,5,4,6,6,7,8}=> {1,2,3,7,8}
{1,2,3,3,4,5,6,7,7,8} => {1,2,4,5,6,8}
{1,1,3,3,4,4,6,6}=>{}
{4,2,6,8,3,1,1,3,8,6,2,4}=>{}
{6,6,6,1}=>{6,1}
```
Only adjacent duplicate elements like `[1, 2, 2, 1]` are removed, but not `[1, 2, 1, 2]`. This process is repeated until no further modifications are made.
For winning criteria is the one which gives the fastest result.
[Answer]
# [Python 2](https://docs.python.org/2/), 201 bytes
```
array = input()
index = 0
while index < len(array) - 1:
if index >= 0 and array[index] == array[index + 1]:
array = array[:index] + array[index + 2:]
index -= 1
continue
index += 1
print(array)
```
[Try it online!](https://tio.run/##XY5BCoMwEEXX5hR/qVihsTtpehHJQmqKARlDiLSePp0mKZTCLPL@f8PEHWHZqI9x8n46oGDJ7aFuhKXZvJjP4rnY1SDzFauhOrkNOshBVPZRuhvLmGhGqscUaij1y2ghNS9V33O5G4rc/rn9oNnN1ClIhvtGwdJuRInbT@y8pVC@FeMoT@jT8OOi3w "Python 2 – Try It Online")
Optimizations thanks to Mr. Xcoder
] |
Subsets and Splits