title: A Spintax {Task|Problem|Question}

text:
# Question
Title: A Spintax {Task|Problem|Question}
# Article Spinning with Spintax

Article spinning is a search engine optimization technique by which search engine optimizers post a unique version of relevant content on article directories, web 2.0 sites, or other sources for backlinks.

It is occasionally used by website authors on their own sites but usually avoided because the quality of spun content will be lower than hand written content. Spinning works by rewriting existing articles, or parts of articles, and replacing specific words, phrases, sentences, or even entire paragraphs with any number of alternate versions to provide a slightly different variation with each spin.

This process can be completely automated or rewritten manually. Your job today will be to create a program or function which interprets a string containing **Spintax**, the syntax by which a program would read the different options available. Below is an example string that uses Spintax:

```
{Hello|Hi there|Bonjour}, user! {What's up?|How are you?|Feeling alright?|I caught a fish!}

```

As you can see, sections of the string that are to be 'spun' are enclosed in curly braces, where individual options are split by the `|` character. Here are some example sentences this could produce.

```
Hi there, user! What's up?
Hello, user! How are you?
Bonjour, user! Feeling alright?
Hello, user! What's up?
Hi there, user! I caught a fish!

```

# Your Job

Your mission, should you choose to accept it, is to create a program or function which takes an input string that may or may not contain **Spintax**, then print 5 versions of the string, randomly selecting one of the choices from each block of options. You can make a few assumptions:

1. You will not need to handle nested Spintax (`{This|is {an|one}|example}`).
2. The `|`,`{` and `}` characters will not occur anywhere else other than within a Spintax block.
3. You do not need to check if the 5 output sentences are distinct, as long as the code selects options using your language's random number function.
4. You may assume the input ends with a newline.

# Rules

1. No standard loopholes.

# Tests

```
1. {A|The|One} {quick|magnificent|charming|lucky|fast|super|cool} {gold|tan|yellow|white|brown|silver} {beaver|packrat|cat|lion|tiger|fox|dog|wolf} {consumed|ate|pilfered} my {pastry|strudel|cake}.
-------------------------------------------
One cool brown wolf consumed my pastry.
...(3 more here)...
The charming yellow beaver ate my cake.
-------------------------------------------
2. This sentence is valid, and happens to have no Spintax!
-------------------------------------------
This sentence is valid, and happens to have no Spintax!
...(3 more here)...
This sentence is valid, and happens to have no Spintax!
-------------------------------------------
3. {beg|get|ton|sun|bun|can|top|big}{2|3|4|5}{A|B|C|D|E|F|G}{2|3|4|5|6|7}{at|as|be|ex|hi|}{!|#|%}
-------------------------------------------
top2F2hi%
...(3 more here)...
big3E4ex#

```

A fourth test can be found here.

---

This is , so fewest number of bytes wins.

# Answer
# Pyth, 18

```
V5sOMcR\|scR\{cz\}

```

Try it online here

### Explanation:

```
V5sOMcR\|scR\{cz\}                     : z = input()
V5                                     : do this 5 times
              cz\}                     : split z on the } character
          cR\{                         : split each element of the resulting list on {
         s                             : join the list of lists back into a list of strings
     cR\|                              : split these strings on the | character
   OM                                  : Choose a random element from each inner list
  s                                    : join those choices, and print them

```
> 8 votes

# Answer
# Ruby, 46

With command-line flag `-p`, run

```
($_*=5).gsub!(/{(.+?)}/){$1.split(?|).sample}

```

Read in a string with a trailing newline. Concatenate it to itself 5 times, mutate it in place, and output the result. `/{(.+?)}/` is a regular expression with a lazy quantifier: without the `?`, it would match the leftmost `{` to the rightmost `}` instead of the nearest one. `$1` is a magic variable referring to the first capture group in each match, while the `?|` literal refers to the `|` character. `sample` is an array method returning a random element.
> 7 votes

# Answer
# CJam, ~~25~~ ~~22~~ ~~19~~ 18 bytes

```
q5*'}/{'{/~'|/mR}/

```

This code requires the input to contain a trailing newline.

Try it online in the CJam interpreter.

### How it works

```
q     e# Read from STDIN.
5*    e# Repeat the input five times.
'}/   e# Split at right curly brackets.
{     e# For each chunk:
  '{/ e#   Split at left curly brackets.
  ~   e#   Dump both chunks on the stack.
  '|/ e#   Split the right chunk at vertical bars.
  mR  e#   Select a chunk, pseudo-randomly.
}/    e#

```

In each iteration, two chunks (one constant, one variable) are left on the stack and will be printed when the program exits.
> 6 votes

# Answer
# Python 3, 110 bytes

```
import re,random
exec('print("".join(random.choice(s.split("|"))for s in re.split("{(.*?)}",%r)));'%input()*5)

```

Regex splitting, like the others.

# Python 3, ~~121~~ ~~116~~ 114 bytes

```
from random import*
exec(("print(%r[:-1]);"%(input()+'"')).translate({123:"'+choice(['",124:"','",125:"'])+'"})*5)

```

This one performs the appropriate replacements then evaluates it. If it wasn't for escaping backslashes and apostrophes, this would have turned out shorter.

For example, suppose we have the Spintax

```
I {like|hate} {Python|C}.

```

The `.translate` performs a few conversions to give:

```
print('I '+choice(['like','hate'])+' '+choice(['Python','C'])+'.')

```
> 6 votes

# Answer
# Perl, 50

```
$_=$_ x5;s/{(.*?)}/@r=split"\\|",$1;$r[rand@r]/ge

```

`49` characters `+1` for `-p`.

It works by first setting `$_` to the 5 sentences. Then it does a global search and replace, where we search for each `{ | | }` group. It splits the group on `|`, and the picks a random element for the replacement.

Run with:

```
echo '{A|The|One} {quick|magnificent|charming|lucky|fast|super|cool} {gold|tan|yellow|white|brown|silver} {beaver|packrat|cat|lion|tiger|fox|dog|wolf} {consumed|ate|pilfered} my {pastry|strudel|cake}.' | perl -pe'$_=$_ x5;s/{(.*?)}/@r=split"\\|",$1;$r[rand@r]/ge'

```
> 4 votes

# Answer
# Ostrich v0.7.0, 27 characters

```
{`{.*?}`{);(;"|/.,R*F=}X}5*

```

Explanation:

```
{...}5*  repeat 5 times
  `{.*?}`  regex to match "spintax" sections
  {...}X   replace with...
    );(;     remove first and last characters (the curly brackets)
    "|/      split on |
    .,R*     multiply length of that array by a random number
    F=       take the floor of that and get the nth element of the array

```

(note: the 0.7.0 release was made after this question was posted, but the answer is still valid as all the commits that made up that release were all pushed before this questions was posted.)
> 4 votes

# Answer
# Pip, ~~25~~ ~~22~~ 20 bytes

Late to the party, but here's mine. Takes input as a command-line argument, which may need to be quoted.

```
L5P_@RR#_Ma^`}|{`^'|

```

Explanation:

```
L5                    Loop 5 times:
          a^`}|{`     Split cmdline arg on curly braces using regex
                 ^'|  Split each item of the result on pipe (if there isn't one,
                        the result is a single-item list)
         M            Map this function to each item a in the result:
   _@RR#_             Calculate a random number between 0 and len(item)-1; use it to
                        index into item
  P                   Print the resulting list, concatenating elements together

```

## 17 bytes (but not a valid submission)

```
L5PRC_Ma^`}|{`^'|

```

Requires the latest version of Pip, updated after this question was posted. The RC (random choice) operator was planned for some time, but I never got around to implementing it until just now. :^(

Learn more about Pip
> 4 votes

# Answer
# JavaScript ES6, ~~86~~ 84 bytes

```
f=s=>s.repeat(5).replace(/{(.+?)}/g,(_,e)=>(p=e.split`|`)[Math.random()*p.length|0])

```

This expects the input to have a trailing newline. It starts by repeating the input 5 times, and then replacing each Spintax string with a random word from it, which is obtained by splitting out the `|` characters and then choosing a random number between 0 and the length of the resulting array minus 1. In this case, `|0` is just a shorter way of doing `Math.floor`. Thanks to vihan1086 for reminding me about tagged template strings.

The Stack Snippet below contains ungolfed and easily testable code.

```
f=function(s){
  return s.repeat(5).replace(/{(.+?)}/g,function(_,e){
    return (p=e.split('|'))[Math.random()*p.length|0]
  })
}

run=function(){document.getElementById('output').innerHTML=f(document.getElementById('input').value+'\n')};document.getElementById('run').onclick=run;run()
```

```
<input type="text" id="input" value="{A|The|One} {quick|magnificent|charming|lucky|fast|super|cool} {gold|tan|yellow|white|brown|silver} {beaver|packrat|cat|lion|tiger|fox|dog|wolf} {consumed|ate|pilfered} my {pastry|strudel|cake}." style="width: 400px;" /><button id="run">Run</button><br />
<pre id="output"></pre>
```
> 3 votes

# Answer
# Perl, 82 bytes

```
while($o=<>){for(0..4){$_=$o;s/{(.*?)}/@x=split\/\|\/,$1 and$x[rand@x]/ge;print;}}

```
> 2 votes

# Answer
# Python 2, 139 bytes

Added two bytes for quotes around input string. If these are not needed let me know.

**Try it here**

```
import re,random
s=input()
exec"print''.join(t*(t!=''and(t[0]!='{'))or random.choice(t[1:].split('|'))for t in re.split('({.*?)}',s));"*5

```
> 2 votes

# Answer
# Javascript, ~~143~~ 142 bytes

```
a=prompt(b=5);for(c=[];b--;c.push(a.replace(/{(.+?)}/g,function(_,j){return (d=j.split("|"))[d.length*Math.random()|0]})));alert(c.join("\n"))

```
> 1 votes

# Answer
# Java, 243 215 242 234 bytes

```
int i,k;void f(String s){String a,b[],c=s;for(;k++<5;System.out.println(c),c=s)while((i=c.indexOf("{"))>=0){a=c.substring(i,c.indexOf("}")+1);b=a.replaceAll("\\{|\\}","").split("\\|");c=c.replace(a,b[(int)(Math.random()*b.length)]);}}

```

Finds strings within braces `{}` and replaces them with a random element from the array of strings created by splitting by the pipe character. (I realized a little too late that five sentences had to be printed :P)
> 1 votes

# Answer
# Bash: ~~144~~ 138 characters

```
IFS={} read -ap
w()(for o in "${p[@]}";{
[[ $o =~ \| ]]&&{
IFS=\| read -aa<<<"$o"
o=${a[RANDOM%${#a[@]}]}
}
echo -n "$o"
}
echo)
w
w
w
w
w

```

Sample run:

```
bash-4.3$ bash spintax.sh <<< "Look {ma'|daddy|mr. president}! No {bin|core|doc|find|mail}utils tools nor {Awk|Sed|jq|XML Starlet}!"
Look ma'! No docutils tools nor Awk!
Look daddy! No binutils tools nor XML Starlet!
Look mr. president! No docutils tools nor XML Starlet!
Look ma'! No docutils tools nor Awk!
Look mr. president! No binutils tools nor Sed!

```
> 1 votes

# Answer
# Python 3, 97 bytes

Using a lambda function in regex substitution. This is somewhat similar to how I did it in my Spintax module https://github.com/AceLewis/spintax however it does not deal with nested Spintax or escaping the characters.

```
import re,random
print(re.sub("{(.*?)}",lambda x:random.choice(x.group(1).split('|')),input()*5))

```

If you do not assume the input ends with a newline then it will be 104 bytes.

```
import re,random
print(re.sub("{(.*?)}",lambda x:random.choice(x.group(1).split('|')),(input()+'\n')*5))

```
> 1 votes

# Answer
# Japt `-R`, 18 bytes

```
5Ær"\{(.+?)}"Ïq| ö

```

Try it
> 0 votes

---
Tags: code-golf
---


title: Find the nearest greater number

text:
# Question
Title: Find the nearest greater number
# The task

Given any array of integers, e.g.:

```
[-1,476,578,27,0,1,-1,1,2]

```

and an index of that array (this example uses **0 based indexing**, though you can use **1 based indexing** as well.):

```
         index = 5
                 v
[-1,476,578,27,0,1,-1,1,2]

```

Then **return the nearest number greater than the element at that index**. In the example, the closest number greater than 1 is 27 (at 2 indices away).

```
         index = 5
                 v
[-1,476,578,27,0,1,-1,1,2]
            ^
Nearest greater number

Output = 27

```

# Assumptions

* Nearest does not include wrapping.
* The program will never be given an array of length 1 (e.g; `[55]`).
* You are to assume there is **always** a number greater than the given element.
* If there are 2 numbers greater than the element at equal distances, you can return **either one**.

This is so the shortest code in bytes wins

# I/O pairs

```
Input:
Index = 45
Array = [69, 43, 89, 93, 62, 25, 4, 11, 115, 87, 174, 60, 84, 58, 28, 67, 71, 157, 47, 8, 33, 192, 187, 87, 175, 32, 135, 25, 137, 92, 183, 151, 147, 7, 133, 7, 41, 12, 96, 147, 9, 134, 197, 3, 107, 164, 90, 199, 21, 71, 77, 62, 190, 122, 33, 127, 185, 58, 92, 106, 26, 24, 56, 79, 71, 24, 24, 114, 17, 84, 121, 188, 6, 177, 114, 159, 159, 102, 50, 136, 47, 32, 1, 199, 74, 141, 125, 23, 118, 9, 12, 100, 94, 166, 12, 9, 179, 147, 149, 178, 90, 71, 141, 49, 74, 100, 199, 160, 120, 14, 195, 112, 176, 164, 68, 88, 108, 72, 124, 173, 155, 146, 193, 30, 2, 186, 102, 45, 147, 99, 178, 84, 83, 93, 153, 11, 171, 186, 157, 32, 90, 57, 181, 5, 157, 106, 20, 5, 194, 130, 100, 97, 3, 87, 116, 57, 125, 157, 190, 83, 148, 90, 44, 156, 167, 131, 100, 58, 139, 183, 53, 91, 151, 65, 121, 61, 40, 80, 40, 68, 73, 20, 135, 197, 124, 190, 108, 66, 21, 27, 147, 118, 192, 29, 193, 27, 155, 93, 33, 129]
Output = 199

Input:
Index = 2
Array = [4,-2,1,-3,5]
Output = 4 OR 5

Input:
Index = 0
Array = [2124, -173, -155, 146, 193, -30, 2, 186, 102, 4545]
Output = 4545

Input:
Index = 0
Array = [1,0,2,3]
Output = 2

Input:
Index = 2
Array = [3,-1,-3,-2,5]
Output = -1 OR -2

```

# Answer
> 7 votes
# MATL, 10 bytes

```
yt&y)>fYk)

```

This uses 1-based indexing. **Try it online!**

### Explanation

Consider inputs `[4,-2,1,-3,5]`, `3` as an example.

```
y     % Take two inputs implicitly. Duplicate 2nd-top element in the stack
      % STACK: [4,-2,1,-3,5], 3, [4,-2,1,-3,5]
t     % Duplicate top of the stack
      % STACK: [4,-2,1,-3,5], 3, [4,-2,1,-3,5], [4,-2,1,-3,5]
&y    % Duplicate 3rd-top element in the stack
      % STACK: [4,-2,1,-3,5], 3, [4,-2,1,-3,5], [4,-2,1,-3,5], 3
)     % Index: select elements from first input as indicated by second input
      % STACK: [4,-2,1,-3,5], 3, [4,-2,1,-3,5], 1
>     % Greater than, element-wise
      % STACK: [4,-2,1,-3,5], 3, [1,0,0,0,1]
f     % Find: gives indices of non-zero entries
      % STACK: [4,-2,1,-3,5], 3, [1,5]
Yk    % Closest element: gives closest element of each entry in second input
      % ([1,5]) to each entry in the first input (3). In case of a tie it
      % gives the left-most one
      % STACK: [4,-2,1,-3,5], 1
)     % Index: select elements from first input as indicated by second input
      % STACK: 4
      % Implicitly display

```

# Answer
> 6 votes
# Jelly, 10 bytes

```
ị<ṛTạ⁸$ÞḢị

```

Try it online!

# Answer
> 5 votes
# Jelly, ~~11~~ 12 bytes

+1 byte - No wrapping allowed.

```
Jạż⁸ṢZṪ»\Q2ị

```

1-indexed.

**Try it online!**

---

Previous 11 byter (wrapping indexing), 0-indexed:

```
ṙżU$Fµ>ḢTḢị

```

# Answer
> 4 votes
## JavaScript (ES6), ~~57~~ 55 bytes

Takes the array `a` and the index `i` in currying syntax `(a)(i)`.

```
a=>g=(i,p)=>(x=a[i-p])>a[i]||(x=a[i+p])>a[i]?x:g(i,-~p)

```

### Test cases

```
let f =

a=>g=(i,p)=>(x=a[i-p])>a[i]||(x=a[i+p])>a[i]?x:g(i,-~p)

console.log(f([-1, 476, 578, 27, 0, 1, -1, 1, 2])(5))

console.log(f([69, 43, 89, 93, 62, 25, 4, 11, 115, 87, 174, 60, 84, 58, 28, 67, 71, 157, 47, 8, 33, 192, 187, 87, 175, 32, 135, 25, 137, 92, 183, 151, 147, 7, 133, 7, 41, 12, 96, 147, 9, 134, 197, 3, 107, 164, 90, 199, 21, 71, 77, 62, 190, 122, 33, 127, 185, 58, 92, 106, 26, 24, 56, 79, 71, 24, 24, 114, 17, 84, 121, 188, 6, 177, 114, 159, 159, 102, 50, 136, 47, 32, 1, 199, 74, 141, 125, 23, 118, 9, 12, 100, 94, 166, 12, 9, 179, 147, 149, 178, 90, 71, 141, 49, 74, 100, 199, 160, 120, 14, 195, 112, 176, 164, 68, 88, 108, 72, 124, 173, 155, 146, 193, 30, 2, 186, 102, 45, 147, 99, 178, 84, 83, 93, 153, 11, 171, 186, 157, 32, 90, 57, 181, 5, 157, 106, 20, 5, 194, 130, 100, 97, 3, 87, 116, 57, 125, 157, 190, 83, 148, 90, 44, 156, 167, 131, 100, 58, 139, 183, 53, 91, 151, 65, 121, 61, 40, 80, 40, 68, 73, 20, 135, 197, 124, 190, 108, 66, 21, 27, 147, 118, 192, 29, 193, 27, 155, 93, 33, 129])(45))

console.log(f([4, -2, 1, -3, 5])(2))

console.log(f([2124, -173, -155, 146, 193, -30, 2, 186, 102, 4545])(0))
```

# Answer
> 3 votes
# PHP, 106 Bytes

```
<?for($y=($a=$_GET[0])[$x=$_GET[1]];$y>=$a[$x-++$i]&&$y>=$a[$x+$i];);echo$y<$a[$x+$i]?$a[$x+$i]:$a[$x-$i];

```

Online Version

# Answer
> 3 votes
# Haskell, 48 bytes

```
i%l=minimum[[j*j,x]|(j,x)<-zip[-i..]l,x>l!!i]!!1

```

Try it online! Test framework from Ørjan Johansen.

# Answer
> 2 votes
# Python, 62 bytes

```
lambda a,i:min((v<=a[i],abs(j-i),v)for j,v in enumerate(a))[2]

```

**Try it online!**

# Answer
> 2 votes
# x86-64 Assembly, 40 bytes

Inspired by analyzing Johan du Toit and 2501's C solutions, the following is a function that can be assembled with MASM for x86-64 platforms.

It follows the Microsoft x64 calling convention for passing parameters, so the total length of the array is passed in `ECX`, the position of interest is passed in `EDX`, and the pointer to the integer array is passed in `R8` (it's a 64-bit platform, so it's a 64-bit pointer).

It returns the result (the "nearest greater number") in `EAX`.

```
             FindNearestGreater PROC
8B F2       \    mov     esi, edx     ; move pos parameter to preferred register
8B D9       |    mov     ebx, ecx     ; make copy of count (ecx == i; ebx == count)
            | MainLoop:
8B C6       |    mov     eax, esi     ; temp  = pos
2B C1       |    sub     eax, ecx     ; temp -= i
99          |    cdq
33 C2       |    xor     eax, edx
2B C2       |    sub     eax, edx     ; temp = AbsValue(temp)
            |
41 8B 14 B0 |    mov     edx, DWORD PTR [r8+rsi*4]
41 39 14 88 |    cmp     DWORD PTR [r8+rcx*4], edx
7E 04       |    jle     KeepGoing    ; jump if (pValues[i] <= pValues[pos])
3B D8       |    cmp     ebx, eax
77 02       |    ja      Next         ; jump if (count > temp)
            | KeepGoing:
8B C3       |     mov     eax, ebx    ; temp = count
            | Next:
8B D8       |     mov     ebx, eax    ; count = temp
E2 E3       |     loop    MainLoop    ; equivalent to dec ecx + jnz, but smaller (and slower)
            |
            |     ; Return pValues[temp + pos]
03 C6       |     add     eax, esi
41 8B 04 80 |     mov     eax, DWORD PTR [r8+rax*4]
C3          /     ret
             FindNearestGreater ENDP

```

If you wanted to call it from C code, the prototype would be:

```
extern int FindNearestGreater(unsigned int count,
                              unsigned int pos,
                              const    int *pValues);

```

# Answer
> 1 votes
# Ruby, 64 bytes

```
->a,i{a[(0...a.size).select{|j|a[j]>a[i]}.min_by{|j|(i-j).abs}]}

```

Try it online!

# Answer
> 1 votes
# Ohm, 20 bytes

Basically a translation of this Ruby answer.

```
Dl#)░┼_ª┼┘ª>;╥┘_-A;ª

```

Try it online!

Explanation will come later when I'm not doing homework.

# Answer
> 1 votes
# Pyth - 28 bytes

```
JEehf>@T1@JQo@NZm(adQ@Jd)UlJ

```

Try it

# Answer
> 1 votes
# Haskell, 53 bytes

`(#)` takes an `Int` and a list of `Int`s or `Integer`s (actually any `Ord` type), and returns an element of the list.

```
n#l=[x|i<-[1..],x:_<-(`drop`l)<$>[n-i,n+i],x>l!!n]!!0

```

# How it works

* `n` is the given index and `l` is the given list/"array".
* `i`, taking on values from 1 upwards, is the distance from `n` currently being tested.
* For each `i`, we check indices `n-i` and `n+i`.
* `x` is the element of `l` being tested. If it passes the tests it will be an element of the resulting list comprehension.
    + Indexing arbitrary indices with `!!` could give an out of bounds error, while `drop` instead returns either the whole list or an empty list in that case. The pattern match with `x:_` checks that the result is not empty.
    + `x>l!!n` tests that our element is greater than the element at index `n` (which is guaranteed to exist).
    + `!!0` at the end returns the first match/element of the list comprehension.

Try it online!

# Answer
> 1 votes
# Brachylog, 17 bytes

```
hH&∋₎<.&t:I≜+:H∋₍

```

Try it online!

### Explanation

```
hH                      Call the list H
  &∋₎<.                 Output is greater than the number at the specified index
       &t:I≜            Label I (0, then 1, then -1, then 2, then -2, …)
            +           Sum I with the input Index
             :H∋₍       Output is the element of H at index <the sum>

```

# Answer
> 1 votes
# Java (OpenJDK 8), 98 bytes

```
int f(int n,int[]a){for(int s=1,i=1,x=a[n];;n+=i++*s,s=-s)if(0<=n&n<a.length&&a[n]>x)return a[n];}

```

Try it online!

Checks the indices in the order specified by the partial sums of the following sum:

```
initial value + 1 - 2 + 3 - 4 + 5 - 6 + ...

```

# Answer
> 1 votes
## C, 69 bytes

```
t;b;f(*d,c,p){for(b=c;c--;)d[c]>d[p]&(t=abs(p-c))<b?b=t:0;*d=d[p+b];}

```

First argument is an in/out argument. Output is stored in its first element.

See it work online.

# Answer
> 1 votes
# PHP, 73 bytes

```
function($i,$a){for(;$b<=$a[$i];)$b=max($a[++$d+$i],$a[$i-$d]);return$b;}

```

closure takes 0-based index and array from arguments. Verify all test cases.

# Answer
> 1 votes
# R, 59 bytes

```
function(l,i)l[j<-l>l[i]][which.min(abs(1:length(l)-i)[j])]

```

returns an anonymous function. In the event that there are two elements greater at equal distances, will return the first (lesser index).

Try it online!

# Answer
> 1 votes
**Java, 96 Bytes**

```
int f(int n,int[]a){for(int s=1,i=1,x=a[n];0>(n+=i++*s)|n>=a.length||a[n]<=x;s=-s);return a[n];}

```

Identifiers are named like @Leaky Nun's answer. Furthermore, most parts have been aligned to be basically the same: In comparison, the `if` has been replaced by the `for`-condition (sacrificing the additional semicolon). A colon has been removed by moving increment-part into condition (so the parentheses of the previous if-statement practically "moved") - changing & to | did not have impact on character count.

# Answer
> 1 votes
# Jelly, 9 bytes

```
>ị@TạÞị⁸Ḣ

```

Try it online!

## How it works

```
>ị@TạÞị⁸Ḣ - Main link. Takes the array A on the left and the index i on the right
 ị@       - Get the i'th element of A, k
>         - Is k greater than each element of A?
   T      - Get the indices of the 1s
     Þ    - Sort these indices by:
    ạ     -   Absolute difference with i
      ị⁸  - Index back into A
        Ḣ - Take the first element

```

# Answer
> 0 votes
# Pyth, 16 bytes

```
JEh>#@JQ@LJaDQUJ

```

Test suite.

# Answer
> 0 votes
# C (gcc), ~~110~~ 108 bytes

```
c,o;e(g,l,f)int*g;{for(o=g[l],c=1;c<f;c++)l+c<f&&g[l+c]>o?o=g[l+c],c=f:0,l>=c&&g[l-c]>o?o=g[l-c],c=f:0;g=o;}

```

-2 bytes thanks to ceilingcat!!

Try it online!

# Answer
> 0 votes
## Clojure, 95 bytes

```
#(%(nth(nth(sort-by first(for[i(range(count %)):when(>(% i)(% %2))][(Math/abs(- i %2))i]))0)1))

```

This is the shortest I could come up with :( I also tried playing around with this but couldn't bring it to the finish line:

```
#(map(fn[f c](f c))[reverse rest](split-at %2 %))

```

# Answer
> 0 votes
# JavaScript, 44 bytes

```
a=>g=(i,p)=>(x=a[i-p])>a[i]?x:g(i,p<0?-p:~p)

```

Try it online!

from https://codegolf.stackexchange.com/a/118765/

# Answer
> 0 votes
# 05AB1E, 10 bytes

```
è›ƶ0K<¹.xè

```

0-based indexing.

Try it online or verify all test cases.

**Explanation:**

```
è           # Get the item in the second (implicit) input-list at the first (implicit)
            # input-index
 ›          # Check for each value in the second (implicit) input-list if it's larger
            # than this value (1 if truthy; 0 if falsey)
  ƶ         # Multiply each by its 1-based index
   0K       # Remove all 0s from this list
     <      # Decrease each value by 1 to make it a 0-based index
      ¹.x   # Pop the list and get the item closest to the first input-index
         è  # Use that to index into the second (implicit) input-list
            # (after which the result is output implicitly)

```

# Answer
> 0 votes
# Japt `-g`, 11 bytes

```
gUð>UgV)ñaV

```

Try it

# Answer
> 0 votes
# APL(Dyadic Classic), 21 bytes

```
A[1↑{⍵[⍋|I-⍵]}⍸A>I⌷A]

```

Try it online!

# Answer
> 0 votes
# TI-Basic, 46 bytes

```
Prompt A
Prompt I
seq(abs(J-I),J,1,dim(ʟA→B
SortA(ʟB,ʟA
ʟA(1+sum(not(cumSum(ʟA>ʟA(1

```

Index is 1-based. Output is stored in `Ans` and is displayed at the end.

---
Tags: code-golf, array, integer
---


# Question
Title: Best response to the Evolution of Trust? - Part 1
## Backstory

I was fiddling around with the Evolution of Trust and thought of this.
**Warning**: I recommend you go check it out first before attempting this challenge.

## Summary for people who haven’t played

A quick summary of what it says on the site: there is a machine. If you put in one coin, your **opponent** gets **three** coins (and vice versa). You can either Cooperate (put in a coin) or Cheat (don't put in a coin).

## Challenge

Given the name of a strategy (`copycat`, `alwayscheat`, `alwayscooperate`, `grudger` or `detective`) and the number of rounds, return/output a list of truthy (Cooperate) and falsey (Cheat) values that, when put against that strategy, will give you the maximum possible amount of coins. (I'm using Y for cooperate and N for cheat in my examples)

For clarification, check the **Input and Output** section.

## Quick info for people who have played

The amount of rounds is given in the input. There are no mistakes, and the rewards for Cooperating/Cheating are the same as the site \- see the image below.

Yes, this is basically a Prisoner's Dilemma - Nicky Case says this in the “feetnotes” of the game.
Also, "Cheat" is basically the same as Defect.

## The characters

* Copycat `copycat`
* Always Cooperate `alwayscooperate`
* Always Cheat `alwayscheat`
* Grudger `grudger`
* Detective `detective`

## The characters' strategies from the site

* Copycat: Hello! I start with Cooperate, and afterwards, I just copy whatever you did in the last round. *Meow*
* Always Cheat: *the strong shall eat the weak* (always cheats)
* Always Cooperate: Let's be best friends! \<3 (always cooperates)
* Grudger: Listen, pardner. I'll start cooperatin', and keep cooperatin', but if y'all ever cheat me, **I'LL CHEAT YOU BACK 'TIL THE END OF TARNATION.** (cooperates until you cheat once, then cheats you back for the rest of the game)
* Detective: First: I analyze you. I start: Cooperate, Cheat, Cooperate, Cooperate. If you cheat back, I'll act like Copycat. If you never cheat back, I'll act like Always Cheat, to exploit you. Elementary, my dear Watson.

## Input and Output

Input is the name of the strategy and the amount of rounds in any order you specify, in a list, or a space-separated string.

Output is a list of truthy (Cooperate) and falsey (Cheat) values that, when put against the strategy, gives you the most amount of points.

## Test cases

```
"grudger 3" => "YYN" or [<2 truthy values>, falsey]
"detective 5" => "NNNYN" or [<3 falsey values,> truthy, falsey]
"alwayscheat 7" => "NNNNNNN" or [<7 falsey values>]
"alwayscooperate 99" => <insert 99 N's here> or [<99 falsey values>]
"copycat 7" => "YYYYYYN" or [<6 truthy values>, falsey]
"detective 4" => "NNNN" (4 N's) or [<4 falsey values>]
"alwayscheat 999" => 999 N's or [<999 falsey values>]
"grudger 1" => "N" or [falsey]

```

Easy copy paste:

```
grudger 3
detective 5
alwayscheat 7
alwayscooperate 99
copycat 7
detective 4
alwayscheat 999
grudger 1

```

## Rules

* This is , shortest answer wins, tiebreaks sorted by time(stamp) created
* Standard loopholes are not allowed, unless they are creative (e.g. asking for list input and using the fact that it is a *list* to shorten your code). No extra points are given for this

> WD

# Answer
> 3 votes
# Jelly, 13 bytes

An OP accepted, but somewhat rule-bending, 13 byter since all the integers are now wrapped in lists - so it only works if we may assume any truthy/falsey operator will vectorise - that can be fixed for 1 byte for a different 14 to my original, e.g. add `F`.)

```
M_5+Ṡ$×<¥ⱮḊ;0

```

A dyadic Link that accepts the opponent classification on the left and the number of turns to play on the right and yields a list of wrapped integers (non-zeros are truthy in Jelly, while zeros are falsey).

**Try it online!** Or see the test-suite.

### How?

There are, for the purpose of our choices, only three classes of opponent here:

1. If we face `alwayscheat` or `alwayscooperate` we should always cheat
2. If we face `grudger` or `copycat` we should cooperate until our penultimate turn and then cheat on our final turn.
3. If we face `detective` we should cooperate from the fourth turn (if it is not our last turn) until our penultimate turn and then cheat on our final turn.

```
M_5+Ṡ$×<¥ⱮḊ;0 - Link: opponent, turns
M             - maximal indices
                -> alwayscheat:[5] alwayscooperate:[5] grudger:[3] copycat:[4] detective:[8]
                       ^               ^                 ^            ^               ^
 _5           - subtract five
                -> alwayscheat:[0] alwayscooperate:[0] grudger:[-2] copycat:[-1] detective:[3]
   +Ṡ$        - add the sign of that (call this "category")
                -> alwayscheat:[0] alwayscooperate:[0] grudger:[-3] copycat:[-2] detective:[4]
         Ɱ    - map (across turn in [1..turns]) with:
        ¥     -   last two links as a dyad, f(category, turn)
       <      -     (category) less than (turn)?
      ×       -     (category) multipied by (that)
          Ḋ   - dequeue
           ;0 - concatenate a zero

```

---

14: `OḢ%4C×4×<¥ⱮḊ;0`

And another 14: `OḢ%4ȯ7B¤Ṭo¥@’ṁ`

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

```
Å0Dā4›Àā¤Ê)ICθè

```

First input is the amount of rounds, second input the strategy of the opponent.
Output is a list of 1s/0s.

Try it online or verify all test cases.

**Explanation:**

There are three different output variations based on the input \\$n\\$:

* `detective`: \\$N(\min(n-1,3))Y(n-4)N(1)\\$
* `grudger`/`copycat`: \\$Y(n-1)N(1)\\$
* `alwayscheat`/`alwayscooperate`: \\$N(n)\\$

So in my program I create these three possible lists first; convert the string input to an index-integer; and use it to output the correct list of the three.

```
Å0         # Push a list with the first (implicit) input amount of 0s: [0,0,...,0,0]
D          # Duplicate this list
ā          # Push a list in the range [1, length] (without popping the list)
 4›        # Check for each whether it's larger than 4 (0 if <=4; 1 if >4)
   À       # Rotate it once left: [0,0,0, 1,1,...,1,1, 0]
ā          # Push a list in the range [1, length] (without popping the list)
 ¤         # Get its last value (without popping)
  Ê        # Check for each that it's NOT equal to this integer: [1,1,...,1,1, 0]
    )      # Wrap all four lists on the stack into a list
     I     # Push the input-string
      C    # Convert it from a binary-string to an integer
       θ   # Only leave its final digit
        è  # Use that to 0-based modulair index into the list of lists
           # (after which this list is output implicitly as result)

```

`C` on strings basically gets the index of each characters in the string `0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzǝʒαβγδεζηθвимнт ΓΔΘιΣΩ≠∊∍∞₁₂₃₄₅₆ !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~Ƶ€Λ‚ƒ„…†‡ˆ‰Š‹ŒĆŽƶĀ‘’“”–—˜™š›œćžŸā¡¢£¤¥¦§¨©ª«¬λ®¯°±²³\nµ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ•`, and then converts this list of indices to a base-2 integer.

| String | `C` | `θ` | Modulair index | Resulting list |
| --- | --- | --- | --- | --- |
| detective | 21282 | 2 | 2 | `[0,0,0, 1,1,...,1,1, 0]` |
| grudger | 5893 | 3 | 3 | `[1,1,...,1,1, 0]` |
| copycat | 5607 | 7 | 3 | `[1,1,...,1,1, 0]` |
| alwayscheat | 87191 | 1 | 1 | `[0,0,...,0,0]` |
| alwayscooperate | 1397550 | 0 | 0 | `[0,0,...,0,0]` |

# Answer
> 2 votes
# Ruby, ~~48~~ ~~44~~ 42 bytes

Based on OP's answer

```
->a,b{([p]*(~a.ord%4)+[a>?b]*b)[0,b-1]<<p}

```

Try it online!

`[p]*(~a.ord%4)` could be `[p]*3*a.sum[2]` or `[p]*(a.hex/74)` instead for the same length.

# Answer
> 2 votes
# Python 2, ~~50~~ 48 bytes

```
lambda a,b:(hash(a)%5%4*[0]+[a>'b']*b)[:b-1]+[0]

```

Try it online!

| name | `hash(name)` | `hash(name)%5%4` | `name>'b'` | pattern |
| --- | --- | --- | --- | --- |
| grudger | -2066041371107544871 | 0 | True | `N{0}Y{b-1}N` |
| detective | -4897940859603653632 | 3 | True | `N{3}Y{b-4}N` |
| alwayscheat | 5996996683077751943 | 3 | False | `N{3}N{b-4}N` |
| alwayscooperate | 6213961190923822520 | 0 | False | `N{0}N{b-1}N` |
| copycat | 8335118083446687010 | 0 | True | `N{0}Y{b-1}N` |

# Answer
> 2 votes
# Python 3, 45 bytes

```
lambda o,r:([len(o)<8]*3+[o>'c']*r)[:r-1]+[0]

```

Try it online!

The easiest way to group `detective` with `alwayscooperate` and `alwayscheat` was based on text length, while the easiest to group `detective` with `copycat` and `grudger` was alphabetically.

This might internally generate a list that is too long, but that gets trimmed down in the end.

# Answer
> 1 votes
# JavaScript (ES6),  ~~42~~  41 bytes

Expects `(strategy)(rounds)`. Returns a string of 0's and 1's.

```
(s,i=14)=>g=b=>--b&&[s>g&!s[++i>>1]]+g(b)

```

Try it online!

### Commented

```
(                // main function taking:
  s,             //   s = strategy string
  i = 14         //   i = internal counter
) =>             //
g = b =>         // g is a recursive function taking b = number of rounds
  --b &&         //   decrement b; if b = 0, stop and return a final 0
  [              //   singleton array:
    s > g &      //     yield 1 if the strategy is not 'always[something]'
                 //     (i.e. it's greater than 'b...')
    !s[++i >> 1] //     and the character in s at floor(++i / 2) is not
                 //     defined, which is:
                 //       - always true for 'copycat' and 'grudger'
                 //       - true only after 3 turns for 'detective'
  ]              //   end of array, implicitly coerced to a string
  + g(b)         //   append the result of a recursive call

```

This is based on OP's original answer (now deleted).

# Answer
> 1 votes
# Java 11, ~~76~~ ~~71~~ 70 bytes

```
s->n->(1-s[6]%2+"").repeat(n>3?3:n-1)+(s[0]/98+"").repeat(n>4?n-4:0)+0

```

-5 bytes thanks to *@Arnauld*
-1 byte thanks to *@ovs*

Input as a character-array and integer, output as a String of 1s/0s.

Try it online.

**Explanation:**

```
s->n->                          // Method with character-array and integer parameters
                                // and String return
                                //  Return the following String:
  (1-                           //   Subtract 1 by:
     s[6]                       //    The 7th unicode value of the input-array
         %2                     //    Modulo-2
           +"")                 //   Convert that 0 or 1 to a String
               .repeat(n>3?     //   If `n` is larger than 3:
                           3    //    Repeat it 3 times
                          :     //   Else:
                           n-1) //    Repeat it `n-1` times instead
  +                             //   Concat:
   (s[0]                        //    The 1st unicode value of the input-array
        /98                     //    Integer-divided by 98
           +"")                 //    Convert that 0 or 1 to a String
                .repeat(n>4?    //    If `n` is larger than 4:
                            n-4 //     Repeat it `n-4` times
                           :    //    Else:
                            0)  //     Don't repeat it at all
  +0                            //   And concat an additional trailing "0"

```

| String |  | `s[6]` | `s[6]%2` | `1-s[6]%2` |  | `s[0]` | `s[0]/98` |
| --- | --- | --- | --- | --- | --- | --- | --- |
| detective |  | 105 (`i`) | 1 | 0 |  | 100 (`d`) | 1 |
| grudger |  | 114 (`r`) | 0 | 1 |  | 103 (`g`) | 1 |
| copycat |  | 116 (`t`) | 0 | 1 |  | 99 (`c`) | 1 |
| alwayscheat |  | 99 (`c`) | 1 | 0 |  | 97 (`a`) | 0 |
| alwayscooperate |  | 99 (`c`) | 1 | 0 |  | 97 (`a`) | 0 |

---
Tags: code-golf, game
---


title: Converting to Secret Language

text:
# Question
Title: Converting to Secret Language
Write some code in any language that inputs a string such as "Today is a great day" (Note that there is no punctuation) and converts it to the "Secret Language". Here are the rules for the "Secret Language".

* a=c, b=d, c=e and so on (y=a and z=b)
* separate each word by a space
* make sure there is proper capitalization

Example:

```
Input: "Today is a great day"

Output: "Vqfca ku c itgcv fca"

```

It is a popularity-contest. Other users should give points by looking for most "to the point" yet "unique" code.

CHALLENGE: I was looking up uncommon programming languages and I found a language called Piet (esolang). I challenge anyone to write it in this language.

# Answer
# Smalltalk (Smalltalk/X), 29 27 chars

I am lucky - it is already in the String class:

```
'Today is a great day' rot:2
    -> 'Vqfca ku c itgcv fca'

```

adding I/O, this makes it:

```
(Stdin nextLine rot:2)print

```

in the spirit of doorknob's obfuscated example below, how about:

```
Parser evaluate:('(Uvfkp pgzvNkpg tqv:2)rtkpvPN' rot:-2)

```
> 20 votes

# Answer
## Postscript

The HQ requires, that from now on all agents shall receive communication in printed form only (as electronic channels proved too unreliable) using special top secret font. It is your responsibility to include this top secret procedure into prologue of our printing software:

```
/define_Secret_font {
    /Secret_font
    /Coronet findfont dup
    /Encoding get
    aload pop 256 array astore
    /secret_proc {
        2 copy
        26 getinterval aload pop
        26 -2 roll 26 array astore
        putinterval
    } def
    dup 65 secret_proc
    dup 97 secret_proc
    exch dup length dict dup
    3 -1 roll {put dup} forall
    exch /Encoding 4 -1 roll put
    definefont pop
} def

```

And only that font is allowed, e.g.:

```
define_Secret_font
/Secret_font 36 selectfont
0 841 translate
20 -60 moveto
(Today is a great day) show
20 -120 moveto
(Programming Puzzles & Code Golf) show
showpage

```

And that's what it prints:
> 15 votes

# Answer
# Ruby, obfuscated edition (with commentary included!)

I suggest reading the entire thing; I find it quite amusing ;)

```
$s='';class Module;def const_missing c

# MAGIC:
$s+="#{c}".split("#{$;}").map{|x|x.ord-8**2}.reduce(:"#{43.chr}").chr;end;end

              # My commentary ;)

ZZZY          # ?
YAYYY         # Oookay; you seem excited
Yaz           # Typo?
Yay           # Better
JEEEEEEF      # You misspelled Jeff's name
LAZZZY        # Yes, you are very lazy
Yax           # Another typo...
LLAMA         # Definitely not completely random at all...
EEEEEEEEEEEEE # Ouch my ears
IIIII         # Ouch stop
ASDFASDFASDF  # I SAID STOP BANGING ON THE KEYBOARD
YUMMY         # ... you eat keyboards?
IIIII         # Stop!
YUMMYY        # Why are you eating your keyboard
LLAMA         # That doesn't make sense :(
VV            # :(
LLAMA         # Could you stop saying that?!
CODEGOLF      # Yay, one of my favorite SE sites! :D
VW            # I don't drive
ASDFASDFASDF  # Why do you keep banging on your keyboard?!?!
EEEEEEEEEEEEE # No
VVV           # Stop
HELLOo        # ...it's a little late for a greeting, isn't it?
DOGS          # ...
OOOOOo        # No, you're not a ghost.
HELLOOOO      # Just a *bit* late.
NNNNNNN       # Huh?
LLAMA         # I said to stop.

print eval$s

```

Hints on how it works (spoilers, hover to show):

> This code builds a string and then evaluates it.

> It uses `const_missing` in order to build the string character by character.

> The string it ends up building is `gets.tr'A-Za-z','C-ZABc-zab'`.
> 13 votes

# Answer
# bash

Classic.

```
tr A-Za-z C-ZABc-zab

```

Example:

```
$ tr A-Za-z C-ZABc-zab <<< "Today is a great day"
Vqfca ku c itgcv fca

```
> 11 votes

# Answer
DFSORT (IBM Mainframe sorting program)

```
 OPTION COPY
 INREC BUILD=(1,80,TRAN=ALTSEQ)

```

No SORT control statement can start in column one.

For the above to work on its own, you'd have to change the default installation alternate translation table, to offset all values for upper- and lower-case letters, wrapping around the final two letters.

Without changing the default table, it would require an ALTSEQ statement listing all the required pairs of hex values (from-hex-code immediately followed by to-hex-code, each pair of hex values separated by a comma):

```
 OPTION COPY
 INREC BUILD=(1,80,TRAN=ALTSEQ)
 ALTSEQ CODE=(xxyy,...)

```

So to get upper-case EBCDIC A to C and B to D:

ALTSEQ CODE=(C1C3,C2C4)

For the whole thing, that would be a lot of error-prone typing, of course, so you'd use another SORT step to generate the control cards for this step, and let SORT read them from the dataset created by that new step.

Of course, for any language which supports a "translation table", it is as easy as changing the translation table. Nice COBOL program, with a specific Codepage, and it could be done in one line of COBOL procedure code (plus the obligatory lines of COBOL that go with everything... not so many in this particular case).

Oh, the 1,80 is the "card image" which will contain the text. Probably all in upper-case on the first run...
> 6 votes

# Answer
# C, 75 bytes

```
main(c){while((c=getchar())>0)putchar(isalpha(c)?(c&224)+((c&31)+2)%26:c);}

```

Example:

```
$echo "Today is a great day" |./a.out
Vqfca ku c itgcv fca

```
> 4 votes

# Answer
# Java, it's actually understandable.

I know that anything with whitespace and parentheses has a hard time on CG, but here's a shot.

```
    class SecretLanguage {

    public static void main(String[] args) {
    for (String S : args) {
        for (char s : S.toCharArray()) {
        System.out.print((char) (s + ((s < 'y') ? 2 : -24)));
        }
        System.out.print(" ");
    }
    }
}

```

There are separate contests for obfuscating code, but I can make mine ridiculous too.

```
class S{public static void main(String[]args){for(String str:args){for(char i:(str).toCharArray())System.out.print((char)(i+((i<'y')?2:-24)));System.out.print(" ");}}

```
> 3 votes

# Answer
## PHP

Not the shortest one though!

Live example: https://eval.in/102173

```
<?php
$str = 'Today is a great day';
$out = implode('', array_map(function ($val) {
  if ($val == ' ') return ' ';
  $c = ord($val)+2;

  if (ctype_lower($val)) {
    if ($c > ord('z')) {
      return chr(ord('`') + ($c - ord('z')));
    }
    return chr($c);
  }
  else {
    if ($c > ord('Z')) {
      return chr(ord('A') + ($c - ord('Z')));
    }
    return chr($c);
  }
}, str_split($str)));

var_dump($out);

```

Note:

```
ord('`') = ord('a') - 1

```
> 3 votes

# Answer
TI-Basic (the language that runs on TI-83 graphing calculators)

```
:ClrHome
:" abcdefghijklmnopqrstuvwxyz" //all symbols that can be interpreted
:Ans+Ans+Ans->Str1
:Menu("crippter","encript",1,"decript",2
:Lbl 2
:1->C
:Lbl 1
:if not(C)
:Imput ">",Str2
:if C
:Imput "<",Str2
:length(Str2)->D
:lenght(Str1)/3->E
:if not(C)
:Then
:randInt(1,E)->B
:sub(Str1,B,1)->Str3
:Else
:inString(Str1,sub(Str2,1,1),1)->B
":"->Str3
:For(X,1+C,D
:inString(Str1,sub(Str2,X,1)->A
:if not(C
:A+E-B-X->A
:if C
:A+B+X-1->A
:Str3+sub(Str1,A,1)->Str3
:End
:if C
:sub(Str3,2,D-1)->Str3
:Pause Str3
:Goto A

```

This is some nice encryption software (for a TI-83). By ti-83 I mean any calculator in the ti-83 or ti-84 family. "-\>" means "STORE" accessed by "STO\>"
> 3 votes

# Answer
**Ruby ~~40~~ 32**

```
p gets.tr("A-XY-Za-xy-z","C-ZA-Bc-za-b")

```

update (as seen from danieros bash solution):

```
p gets.tr("A-Za-z","C-ZABc-zab")

```
> 3 votes

# Answer
I think I'll ROT2 it!

## Javascript

```
function r(a,b){return++b?String.fromCharCode((a<"["?91:123)>(a=a.charCodeAt()+2)?a:a-26):a.replace(/[A-z]/g,r)}

console.log(r('Qccipcr'));

```
> 3 votes

# Answer
# Python

```
a = list('abcdefghijklmnopqrstuvwxyz')
b = list('yzabcdefghijklmnopqrstuvwx')

c = {}

#generate conversion dictionary

for i in range(len(a)):
    c[a[i]] = b[i]

instring = "the weather is very nice today"

outstring = ""

for i in list(instring):
    try:
        outstring += c[i]
    except:
        outstring += i

print outstring

```

Output:

rfc ucyrfcp gq tcpw lgac rmbyw
> 2 votes

# Answer
## Javascript

```
var str = '';
var textInput = 'myString';
for (var i = 0; i < textInput.length; i++) {
    str += textInput.charAt(i).replace(/([a-zA-Z])[^a-zA-Z]*$/, function (a) {
        var c = a.charCodeAt(0);
        switch (c) {
            case 89:
                return 'A'; //Letter Y!
            case 90:
                return 'B'; //Letter Z!
            case 121:
                return 'a'; //Letter y!
            case 122: //Letter z!
                return 'b';
            default:
                return String.fromCharCode(c + 2); //If not y, Y, z, or Z, then just two more from the usual char code
        }
    })
}
console.log(str);

```

What with all the comments, my hamster can understand this.
> 2 votes

# Answer
# JavaScript

```
// setup alphabet and secret rotated alphabet
//
var alpha=' abcdefghijklmnopqrstuvwxyz'
var rotor=' cdefghijklmnopqrstuvwxyzab'
alpha+=alpha.toUpperCase()
rotor+=rotor.toUpperCase()

function encrypt(str) {
 return crypt(str, alpha, rotor)
}

function decrypt(str) {
 return crypt(str, rotor, alpha)
}

// swap position of char from one dictionary to the other
function crypt(msg, d1, d2) {
 var out=''
 var len=str.length
 for(var i=0; i < len; i++) {
  var c = msg.charAt(i)
  var j = d1.indexOf(c)
  out += d2.charAt(j)
 }
 return out
}

```
> 2 votes

# Answer
# Python 2.x

An attempt at a feature rich Python solution.

Features:

* the use of a dict
* handling the list in a circular way, so that `shift=2` can be varied
* you can also use it to decipher when you know `shift` (just use minus), it'll also allows you to test your output.
* ability to add "shifting scopes" -- scopes in which you cycle
* option to either be `strict` for undefined characters, or just return the undefined input character.
* a secret language leaves no trace ;)

Here goes:

```
# Shifting scopes
lower_case = map(chr, range(97, 123))
upper_case = map(chr, range(65, 91))
space = [" "] # space will always be transformed to space

def secret(instring, shift, scopes, strict=False):
    def buildTranslationDict(scores):
        translation_dict = {}
        for scope in scopes:
            for index in range(len(scope)):
                translation_dict[scope[index]] = scope[(index+shift) % len(scope)]
        return translation_dict
    translation_dict = buildTranslationDict(scopes)
    # Use the translation dictionary to transform input
    output = ""
    for char in instring:
        if strict:
           output += translation_dict[char]   # will crash if unexpected char
        else:
            try:
               output += translation_dict[char]
            except:
               output += char
    return output

```

Proof:

```
secret(instring="Today is a great day", shift=2, scopes=[lower_case, upper_case, space])
'Vqfca ku c itgcv fca'

```

Can you decipher `'Wrpruurz lv qrw edg hlwkhu!'` :) ?
> 2 votes

# Answer
# Haskell

Here's a lens based implementation. I'm using `Iso` to represent the isomorphism between regular text and text converted into the secret language. Unless you provide the `--from` option, the input is converted into the secret language. If the `--from` option is provided, the opposite conversion is performed.

```
module Main where
import Control.Lens
import System.Environment (getArgs)
import Data.Char          (ord, chr, isUpper, isSpace)
import Data.Word          (Word8)

ord8 :: Char -> Word8
ord8 = fromIntegral . ord

chr8 :: Word8 -> Char
chr8 = chr . fromIntegral

ordIso :: Iso' Char Word8
ordIso = iso ord8 chr8

firstLetterOrd :: Word8 -> Word8
firstLetterOrd n
  | n ^. from ordIso . to isUpper = ord8 'A'
  | otherwise                     = ord8 'a'

secretChar :: Iso' Char Char
secretChar =
  iso toSecret
      fromSecret
  where
    toSecret, fromSecret :: Char -> Char
    toSecret   = secretConversion   2
    fromSecret = secretConversion (-2)

secretConversion :: Int -> Char -> Char
secretConversion n c
  | isSpace c = c
  | otherwise = c & over ordIso (secretShift n)

secretShift :: Int -> Word8 -> Word8
secretShift shiftAmount =
  preserveLetters $ (`mod` 26) . (+ shiftAmount)

preserveLetters :: (Int -> Int) -> Word8 -> Word8
preserveLetters fn n =
  firstLetter + overWord8 fn (n - firstLetter)
  where
    firstLetter = firstLetterOrd n

overWord8 :: (Int -> Int) -> Word8 -> Word8
overWord8 fn = fromIntegral . fn . fromIntegral

help :: IO ()
help =
  putStr
  $ unlines
      ["SecretLang [--from]"
      ,"If the --from option is provided, the program"
      ,"converts from the secret language. Otherwise,"
      ,"it converts to the secret language."
      ]

convertContents :: (String -> String) -> IO ()
convertContents fn = do
  input <- getContents
  putStrLn . ("Output: " ++) $ fn input

main :: IO ()
main = do
  args <- getArgs

  case args of
    ("--from":_) ->
      convertContents (^. mapping (from secretChar))

    ("--help":_) -> help
    ("-h"    :_) -> help

    _            ->
      convertContents (^. mapping secretChar)

```

Examples:

```
$ ./SecretLang
Today is a great day
Output: Vqfca ku c itgcv fca

$ ./SecretLang --from
Vqfca ku c itgcv fca
Output: Today is a great day

```
> 2 votes

# Answer
### Powershell

```
$chars = [int]('a')[0]..[int]('z')[0] | %{ [char]$_, [char]::ToUpper([char]$_) }

$y = $args[0].ToCharArray() | %{
    $idx = $chars.indexOf($_);
    if ($idx -ge 0) {
        $chars[($idx + 4) % 52]
    } else  {
        $_
    }
}

-join [char[]]$y

```

Output:

```
PS C:\Temp> .\z.ps1 "Today is a great day"
Vqfca ku c itgcv fca
PS C:\Temp>

```
> 2 votes

# Answer
# C

```
    #include<stdio.h>

    int main()
    { char p[256];
    int i;
    fgets ( p, 256, stdin );
    for(i=0; i<256 ; i++)
    {
   if ( p[i] == '\n' )
    {
    p[i] = '\0';
    break;
    }
    else
    {

    if((p[i] >= 'a' && p[i] <= 'x') || (p[i] >= 'A' && p[i] <= 'X') )
    {
        p[i] +=2;
    }

    else
    {
    switch(p[i])
     {
        case 'y':    p[i] = 'a';
                     break;

       case 'Y':    p[i] = 'A';
                     break;

       case 'z':    p[i] = 'b';
                     break;
       case 'Z':    p[i] = 'B';
                     break;
       case ' ':    p[i] = ' ';
                     break;

     }
    }
}}

printf("%s", p);

    return 0;
 }

```
> 1 votes

# Answer
# EcmaScript 6:

```
alert(prompt(_='').split(_).map(x=>String.fromCharCode(x.charCodeAt()+(x>' '?x>'x'|x>'X'&x<'['?-24:2:0))).join(_))

```
> 1 votes

# Answer
**JAVA**

`32` is `space` so we print it out as is
`88` is `X` so anything less than `89` moves up 2 characters
`90` is `Z` so anything less than `91` moves down 24 characters (with anything less than `89` already handled so only `89` and `90` effectively)
Repeat same process for lowercase letters, ranging from `97` as `a` to `122` as `z`.

```
void secret(String s) {
    for (char c : s.toCharArray()) {
        System.out.print((char)(c == 32 ? c : c < 89 ? c + 2 : c < 91 ? c - 24 : c < 121 ? c + 2 : c - 24));
    }
}

```
> 1 votes

# Answer
# PHP

This solution is rather boring:

```
echo strtr('Today is a great day','ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz','CDEFGHIJKLMNOPQRSTUVWXYZABcdefghijklmnopqrstuvwxyzab');

```
> 1 votes

# Answer
## Python 3

I think i didn't quite understand the question, but anyway:

```
alphabet = "abcdefghijklmnopqrstuvwxyz"
rot = alphabet[2:] + alphabet[:2]
rot = rot + rot.upper()
alphabet = alphabet + alphabet.upper()

def encode_letter(letter):
    return rot[alphabet.index(letter)]

def encode_word(word):
    return "".join(encode_letter(letter) for letter in word)

def encode_string(string):
    return " ".join(encode_word(word) for word in string.split())

print("Output: " + encode_string(input("Input: ")))

```
> 1 votes

# Answer
# JavaScript (V8)

```
t=>t.replace(/./g,d=>/[a-z]/i.test(d)?((parseInt(d,36)-8)%26+10).toString(36)[/[A-Z]/.test(d)?"toUpperCase":"valueOf"]():d)

```

This is code golf, short *is* popular.
> 1 votes

# Answer
# Python 3

```
# To understand recursion, go to the bottom of the program

from string import ascii_letters

translate_table = {
    c: chr(ord(c) + 2) for c in ascii_letters
}

def translate_helper(string):
    if len(string) == 1:
        if string not in {"y", "z"}:
            return translate_table[string]
        else:
            return "a" if string == "y" else "b"
    else:
        return translate_helper(string[:-1]) + translate_helper(string[-1])

def translate(string):
    return " ".join(map(translate_helper, string.split(" ")))

print(translate("Today is a great day"))

# To understand recursion, go to the top of the program

```
> 1 votes

# Answer
## Javascript, 255 bytes

```
const sl = text =>
  text
    .split(" ")
    .map(word =>
      word
        .split("")
        .map(c => String.fromCharCode(c.charCodeAt(0) + (c < "y" ? 2 : -24)))
        .join("")
    )
    .join(" ");

console.log(sl("Today is a great day"));

```
> 1 votes

# Answer
# Vyxal

```
@rotate:letter|
 kL ←letter c [
   ←letter \Y = [
     \A | ←letter \y = [
       \a | ←letter \Z = [
         \B | ←letter \z = [
           \b | ←letter C 2 + C
         ]
       ]
     ]
   ] | ←letter
 ]
;

`Today is a great day`f °rotate; M ¤j

```

Try it Online!

Finally, a chance to use the more obscure features of Vyxal! Behold the beauty of named functions, variables, if-else chains and function references. I also got to make good use of the codemirror functionality built into the online interpreter for once.

Also, I know caird said not to, but I answered anyway, because I never get the chance to properly show off the cooler stuff of my esolang.
> 1 votes

# Answer
# Extended BrainFuck

Since this is a popularity contest I've written this with the intention of it being as easy to follow as EBF can be. It's heavily commented and I've intentionally used macros to make the program flow more literal.

Probably the most difficult thing here is the main switch since EBF doesn't have any special means of doing it so it's in reality no simpler than how one would do it in BrainFuck except for the variables and balancing parentheses.

```
;;;; rot2.ebf : Perform rot2 on ascii text
;;;; Usage: bf ebf.bf < rot2.ebf > rot2.bf
;;;;        echo "Today is a great day" | bf rot2.bf
;;;;        # => Vqfca ku c itgcv fca
;;;;
;;;; BF interpreter/Compiler requirement:
;;;; Wrapping cells at any size (allmost all of them do)
;;;;

;;; Memory map
:tmp    ; a temporary cell used for the read routine
:input  ; a copy of the input for output purposes
:switch ; a copy of the input for the switch statements
:flag   ; flag to indicate the predicate has been processed or not

;;; Macros
;; Ultracompatible read
;; supports EOF 0, -1 and no change
{read_tmp
  $input+
  $tmp(-),
  [+[-$input-]] ; blanks for all EOFs
  $switch [
    @input &clear
    $switch
  ]
}

;; for the switch we need
;; to do destructive testing
;; and we need to preserve the
;; original as well.
{copy_input
  $tmp(-$input+$switch+)
}

;; clears the cell
{clear (-)}

;; prints current cell
{print .}

;;; Main proram
;;; flow starts here
&read_tmp
while $tmp not eof
(
  &copy_input
  $flag+
  $switch 10-(22-(
    ;; not linefeed/space
    $switch 57-(-(31-(-(
       ;; default: not wrapping
       &clear
       $flag-
       $input 2+))))
    $flag (-
       ;; wrapping
       $input 24-)))
  $flag &clear
  $input &print &clear
  &read_tmp
)
;;; End

```
> 0 votes

# Answer
**Javascript**

```
var STR = "Today is a great day";
//so i can replace chars at a index in the string
String.prototype.replaceAt=function(i, char) {
    var a = this.split("");
    a[i] = char;
    return a.join("");
}

function secretIt( str ){
    for( var i = 0; i < str.length; i++ ) {
        var c = str.charCodeAt( i );
        /**
        * check for spaces first
        * check if get outside of the letter range for both lower and upper
        * if we dont go then were good
        * if so go back 26 chars
        */
        str = str.replaceAt( i, String.fromCharCode( ( c == 32 ) ? c : ( ( c = c + 2 ) > 91 && c < 97 || c < 123 ) ? c : c - 26 ) ) ;
    }
    return str;
}

console.log( secretIt( "Qsncp qcapcr ambc" ), ' ' , secretIt( STR ));

```
> 0 votes

# Answer
**C#** 5KB

> (381 chars)

391

```
using System;
namespace WinHelper {
    class P {
        static void Main(string[] args) {
            char[] f =  "abcdefghijklmnopqrstuvwxyz ".ToCharArray();
            char[] g =  "cdefghijklmnopqrstuvwxyzab ".ToCharArray();

            foreach (char c in Console.ReadLine().ToCharArray().ToLower())
                Console.Write(g[Array.FindIndex(f, a => a == c)]);
        }
    }
}

```
> 0 votes

# Answer
# C#, 163

Yes, this is not code-golf. I went for shortest anyway (or at least, made a first stab at it)

```
using System.Linq;class P{static void Main(string[]a){System.Console.WriteLine(string.Concat(a[0].Select(c=>(char)(c==32?c:c<89?c+2:c<91?c-24:c<121?c+2:c-24))));}}

```

Formatted:

```
using System.Linq;
class P
{
    static void Main(string[] a)
    {
        System.Console.WriteLine(string.Concat(a[0].Select(c => (char)(c == 32 ? c : c < 89 ? c + 2 : c < 91 ? c - 24 : c < 121 ? c + 2 : c - 24))));
    }
}

```

Yes, I did have a peek at ufis' answer.
> 0 votes

# Answer
# Q

```
{x^(raze a!'rotate[2] each a:.Q`a`A)x}

```
> 0 votes

# Answer
## Java

```
void sl(String s){
    for (char c: s.toCharArray()){
        char l = Character.toLowerCase(c);
        System.out.print((char)(c + (l < 'y'? l < 'a'? 0: 2: -24)));
    }
}

```
> 0 votes

# Answer
# Bash, 8 characters

...if you happen to have the bsdgames package installed! Reads from standard input.

```
caesar 2

```

## Example

```
echo Today is a great day|caesar 2

```

Output: `Vqfca ku c itgcv fca`
> 0 votes

# Answer
## C

```
#include <stdio.h>
char c[100];
int main()
{
gets(c);
char *p=c,x;
while(*p)
{
    x=*p;
    if(x>='a'&&x<='z')
    {
        *p=((*p-'a'+2)%(26)+'a');
    }
    if(x>='A'&&x<='Z')
    {
        *p=((*p-'A'+2)%(26)+'A');
    }

    p++;
}
puts(c);
}

```
> 0 votes

# Answer
## Brainfuck

Must have (at least) 7-bit wrapping cells to work.

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

```
* Infinite input loop `+[`
* Get input `>,`
* Make a loop to get number 30 `>+++++[<------>-]>`
* If the symbol is a space, output the space `[<<++++++++++++++++++++++++++++++.>>>+<]>-`
* Otherwise, shift the ASCII value by two and output `[<<<++++++++++++++++++++++++++++++++.[-]]<`
* Get more input `]`
> -1 votes

---
Tags: popularity-contest
---


title: Generate Gmail Dot-Aliases

text:
# Question
Title: Generate Gmail Dot-Aliases
# Background

You may be aware that periods in between letters in gmail addresses are ignored. Email sent to example@gmail.com, exam.ple@gmail.com, and e.x.a.m.p.l.e@gmail.com all end up in the same place! This is a great way to have multiple different emails addresses for things like signing up for free trails, or filtering mail from different website. We will refer to gmail address aliases created in this way as dot-aliases.

# The Task

Write a program to generate all possible dot-aliases of a given Gmail address.

# Input

A Gmail address as a string. You may choose whether or not the "@gmail.com" part is included in the input. The maximum length of a Gmail ID (the part before the '@') is 30 characters (not including dots). The minimum is 6 characters. You may assume the input will not already include any dots.

For more details on gmail ID requirements: https://support.google.com/mail/answer/9211434?hl=en

# Output

All of the dot-aliases, in any order, with no duplicates. This can mean printing them to stdout, writing to a file, returning them in a container, returning a iterator, etc. The output **must** contain the "@gmail.com" suffix. You may choose whether or not to include the original input address in the output.

# Scoring

Code Golf here, solution with fewest bytes wins. In the event of a tie, the code who's least common character has the highest number of occurrences wins. In the event of a double tie, earliest timestamp wins.

# Example:

```
Input:
abcabc@gmail.com
or
abcabc
(you pick)

Output:
a.bc.a.bc@gmail.com
a.b.cab.c@gmail.com
abc.ab.c@gmail.com
ab.cabc@gmail.com
a.b.cabc@gmail.com
ab.c.abc@gmail.com
a.b.c.abc@gmail.com
abc.a.bc@gmail.com
a.b.ca.b.c@gmail.com
abc.a.b.c@gmail.com
a.bc.a.b.c@gmail.com
a.bcabc@gmail.com
ab.c.a.b.c@gmail.com
a.b.c.a.b.c@gmail.com
a.b.c.ab.c@gmail.com
ab.c.a.bc@gmail.com
a.b.c.a.bc@gmail.com
abcab.c@gmail.com
a.bcab.c@gmail.com
ab.cab.c@gmail.com
a.bc.ab.c@gmail.com
ab.c.ab.c@gmail.com
abca.b.c@gmail.com
a.bca.b.c@gmail.com
ab.ca.b.c@gmail.com
abca.bc@gmail.com
a.bca.bc@gmail.com
ab.ca.bc@gmail.com
a.b.ca.bc@gmail.com
abc.abc@gmail.com
a.bc.abc@gmail.com
abcabc@gmail.com (optional)

```

**-8% Byte Bonus:** Even though the longest Gmail ID is 30 characters, the maximum length for any valid email address prefix is 64 characters. Make your program work for input up to 64 characters before the '@', but ensure output is also limited to 64 characters before the '@'.

# Answer
> 8 votes
# Python 3, ~~72~~ 69 bytes

-3 bytes thanks to Jitse!

Input includes `@gmail.com`.

```
f=lambda s:s[11:]and[s[0]+w+x for x in f(s[1:])for w in('.','')]or[s]

```

Try it online!

# Answer
> 6 votes
# Python 3, ~~207~~ ~~145~~ ~~140~~ 138 bytes

Removed the flexibility to accept both with and without @gmail.com, now requires the domain to be omitted.

```
g=lambda e:(f"{''.join(p+t for p,t in zip(((['','.'][s>>i&1]for i in range(len(e)-1,-1,-1))),e))}@gmail.com"for s in range(2**(len(e)-1)))

```

Try it online!

# Answer
> 5 votes
# Haskell, 52 bytes

Input includes `@gmail.com`.

```
c s@(a:'@':x)=[s]
c(a:b)=[a:s++x|x<-c b,s<-["","."]]

```

Try it online!

# Answer
> 4 votes
# APL (Dyalog Extended), ~~51~~ ~~45~~ ~~34~~ 29 bytes

Anonymous tacit prefix function. Requires `⎕IO←0` and trailing `@gmail.com`. Returns a list of strings.

```
⊂{∊,∘'.'¨@⍵⊢⍺}∘⍸∘⊤¨∘⍳2*∘≢11∘↓

```

Try it online!

`11∘↓` drop the first eleven characters from the argument

count the number of remaining characters

`2*∘` raise two to that power

**ɩ**ntegers 0…that

`¨∘` on each index:

convert **T**o binary

`⍸∘`**ɩ**ndices where 1-bits are

`⊂{``}∘` call the following function with that as right argument () and the entire original argument as left argument ()

`⊢⍺` on the original text

`@⍵` **at** the given indices

`¨` for each of the indexed characters

`,∘'.'` append a period

**ϵ**nlist (flatten)

# Answer
> 4 votes
# 05AB1E, 11 bytes

-4 bytes thanks to Kevin Cruijssen.

```
.œʒθgT›}'.ý

```

Try it online!

## Explanation

```
.œ          All partitions
  ʒ         Filter:
   θ            The last part
    g           Has a length
     T›}        Larger than 10
        '.ý Join by periods

```

# 05AB1E, ~~16~~ 15 bytes

Saved a lot by porting Adám's APL answer.

```
g11-oÝ¨bεRÅÏ'.«

```

Try it online!

# Explanation

```
g                Find the input's length
 11-             Minus 11
    o            2 ** x
     Ý           0-range
      ¨          Pop the last item
       b         Convert to binary
        ε        For every binary item:
         R       Reverse this item
          ÅÏ     Apply to all truthy indices of this binary item:
            '.«  Append a period

```

# Answer
> 3 votes
# Perl 6, 48 bytes

```
*.comb.reduce({@$^a X~$,'.'X~$^b})X~'@gmail.com'

```

Try it online!

# Answer
> 3 votes
# Bash \+ sed, 39

Takes input of just the local part of the email address and not the @gmail.com. Takes input from STDIN.

```
eval echo `sed 's/\B/{,.}/g'`@gmail.com

```

Try it online!

# Answer
> 3 votes
# Ruby `-n`, ~~70~~ 56 bytes

Input includes "@gmail.com". Generates all possible ways to distribute valid combinations of dots and empty strings within the id by finding the location of the second character before the @ (this works because the input is guaranteed to have 6 characters), and zips them into the original input.

```
r=p,?.
r.product(*[r]*~/..@/){|e|puts$_.chars.zip(e)*''}

```

Try it online!

# Answer
> 2 votes
# Perl 5 \+ `-F/(?=.+@)/n` 21 bytes

Much less offensive flags thanks to @Abigail!

```
$"="{,.}";say for<@F>

```

Try it online!

### Explanation

`-F` splits the input based on the regular expression passed in (with no argument it splits the string into chars) and stores in `@F`. Setting `$"` specifies the string used to join list entries when interpolating. `<...>` is short syntax for a `glob` string which accepts interpolation. In some (most POSIX-compliant?) shells, the glob `a{,.}` expands to the list `a` and `a.`. for an input `abcd@gmail.com`, `<@F>` is expanded to `<a{,.}b{,.}c{,.}d{,.}@gmail.com>` thanks to setting `$"`, which finally expands to the list of all permutations which are iterated with `for` and printed using `say`.

---

# Perl 5 with `-F`, 32 bytes

Excludes `@gmail.com` from the input.

```
$"="{,.}";say for<@F\@gmail.com>

```

Try it online!

# Answer
> 2 votes
# C (gcc), 90 bytes

```
char s[],*i=s+91;main(j){for(gets(i);*i;j+=i[10]&&fork(s[j]=46))s[j++]=*i++;write(1,s,j);}

```

Try it online!

According to my test `write` is atomic, while standard IO aren't

# C (gcc), 93-8%=85.56 bytes

```
char s[],*i=s+91;main(j){for(gets(i);*i;j+=i[10]&&fork(s[j]=46))s[j++]=*i++;write(j<76,s,j);}

```

Try it online!

First one to do bonus

# Answer
> 1 votes
# Retina 0.8.2, 40 bytes

```
^.
$&@
+%`@(.)
$1@$'¶$`.$1@
@
@gmail.com

```

Try it online! Takes input without the domain. Explanation:

```
^.
$&@

```

Insert a marker `@` after the first character.

```
+%`@(.)
$1@$'¶$`.$1@

```

Move the `@` right one character each time, duplicating each line, with an extra `.` in the duplicate.

```
@
@gmail.com

```

Add the domain suffix to all lines.

# Answer
> 1 votes
# C (gcc), <sup>~~134~~ \\$\cdots\\$ ~~103~~</sup> 102 bytes

Saved ~~4~~ ~~8~~ 9 bytes thanks to ceilingcat!!!
Saved ~~7~~ ~~9~~ 10 bytes thanks to l4m2!!!

```
i;j;k;f(char*g){i=strlen(g)-10;for(j=1<<i;j-=2;k=!puts(g+i))for(;k<i;printf(".%c"+!(j>>k++&1),g[k]));}

```

Try it online!

Takes an email address with the `@gmail.com` part included and prints out all of its dot-aliases (not with the original).

**How**

Loops over \\$0\dots2^{n-1}\\$ where \\$n\\$ is the length of email address up to `@`. Uses the binary bits of that loop variable to decide whether or not to insert a dot in between letters.

# Answer
> 1 votes
# Pyth, ~~14~~ 12 bytes

```
/#>11QjL\../

```

Try it online!

Input includes `@gmail.com`.

`./` Partitions of input into disjoint substrings

`jL\.` Join the chunks of each partition using `.`

`/#>11Q` Keep only elements where the last 11 characters of the input string appear in that element (this checks that the "@gmail.com" suffix and preceding character are still intact)

# Answer
> 1 votes
# , ~~115~~ ~~104~~ ~~103 bytes~~ 95 bytes

```
d=function(s,p=2,`[`=substring)"if"(s[p,p]=="@",s,c(d(s,p+1),d(paste0(s[1,p-1],".",s[p]),p+2)))

```

Try it online!

Input includes "@gmail.com" (or any other domain, but that's not relevant to the challenge...)

*Edit: -8 bytes thanks to Giuseppe*

# Answer
> 1 votes
# Wolfram Language (Mathematica), 52 bytes

```
Thread@StringInsert[#,".",Subsets@Range[2,StringLength@#-10]]&

```

Try it online! Pure function. Takes a string as input and returns a list of strings as output. Ignore any `StringInsert::psl` messages generated.

# Answer
> 1 votes
# Jelly, 12 bytes

```
ŒṖẈṪ>ɗƇ⁵j€”.

```

Try it online!

## How it works

```
ŒṖẈṪ>ɗƇ⁵j€”. - Main link. Takes an email E on the left
ŒṖ           - All partitions
     ɗƇ⁵     - Keep those partitions f(P, 10) for which the following is true:
  Ẉ          -   The lengths of each part of P
   Ṫ         -   The last one
    >        -   is greater than 10
        j€”. - Join each of those remaining by ”.

```

# Answer
> 0 votes
# 05AB1E, 29 bytes

```
g©<'.и.ιæʒ'.мJg®Q}J’@g‚ç.ŒŒ’«

```

Try it online!

# Answer
> 0 votes
# T-SQL, 261 bytes

Input is taken from column `U` of table `T` (according to the Code Golf rules for SQL).

```
WITH V(N)AS(SELECT 1UNION ALL SELECT N+1FROM V WHERE N<(SELECT LEN(U)FROM T)),C AS(SELECT U FROM T UNION ALL SELECT CONVERT(VARCHAR(64),STUFF(U,N+1,0,'.'))FROM C,V WHERE N<LEN(U)AND SUBSTRING(U,N,2)NOT LIKE'%.%'AND LEN(U)<64)SELECT DISTINCT U+'@gmail.com'FROM C

```

DB Fiddle

Duration of execution grows exponentially and it takes minutes on my machine for strings longer than 10 characters, but theoretically (if given unlimited time) it should work for input strings up to 64 characters, limiting the output to 64 characters. Therefore, it should also get the -8% bonus, getting to 240 bytes.

# Answer
> 0 votes
# JavaScript (Node.js), 86 bytes

```
(m,e,i)=>{while(m[i])w=m.substr(0,i)+'.'+m.substr(i),console.log(w+e),f(w,e,i+2),i++}

```

Try it online!

# JavaScript (Node.js), 80 bytes

```
(m,e,i,c)=>{while(m[i])w=m.substr(0,i)+'.'+m.substr(i),c(w+e),f(w,e,i+2,c),i++}

```

Try it online!

# Answer
> 0 votes
# PHP, 110 bytes

```
function f($a,$b,$c){while($a[$c]){$w=substr($a,0,$c).'.'.substr($a,$c);echo $w.$b,"\n";f($w,$b,$c+2);$c++;}};

```

Try it online!

### Human readable version

```
<?php
function f($address, $suffix, $i)
{
    while ($address[$i]) {
        $str = substr($address, 0, $i) . '.' . substr($address, $i);
        echo $str . $suffix, "\n";
        f($str, $suffix, $i + 2);
        $i++;
    }
};

f('abcabc', '@gmail.com', 1);

```

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


# Question
Title: We all know how to SKI, but can you BCKW?
## Background

Lambda calculus is a model of computation using *lambda terms*.

* A variable \\$x\\$ is a lambda term.
* If \\$E\\$ is a lambda term, the lambda abstraction \\$\lambda x. E\\$ is a lambda term.
* If \\$E\_1, E\_2\\$ are lambda terms, the lambda application \\$E\_1 E\_2\\$ is a lambda term.

The rule of computation is called \\$\beta\\$-reduction: \\$(\lambda x. E\_1) E\_2\\$ is reduced to \\$E\_1\\$ in which every occurrence of \\$x\\$ is replaced with \\$E\_2\\$. For example, \\$(\lambda x. x x)(\lambda y. y)\\$ is reduced to \\$(\lambda y. y)(\lambda y. y)\\$, then to \\$\lambda y. y\\$.

Combinatory logic operates on a similar premise, but instead of variables and lambda abstraction, it uses a fixed set of combinators. Each combinator has a fixed arity, and it is \\$\beta\\$-reduced only when it gets enough number of arguments applied to it.

For example, \\$S\\$ and \\$K\\$ have following reduction rules:

$$ \begin{align} S x y z &\mapsto x z (y z) \\ K x y &\mapsto x \end{align} $$

\\$S\\$ has an arity of 3, so \\$SKK\\$ is not reducible. But if you apply one more argument to it, it reduces to \\$SKKx \mapsto Kx(Kx) \mapsto x\\$, which shows that \\$SKK\\$ is extensionally equal to the identity function \\$\lambda x. x\\$ in lambda calculus.

SKI combinator calculus is a well-known *complete* combinatory logic system, i.e. a system where any arbitrary lambda calculus term can be represented. This section on Wikipedia shows how to transform any given lambda term into a SKI expression.

BCKW system is a lesser known complete system, discovered by Haskell Curry in 1930. It uses four combinators defined as follows:

$$ \begin{align} B x y z &\mapsto x (y z) \\ C x y z &\mapsto x z y \\ K x y &\mapsto x \\ W x y &\mapsto x y y \end{align} $$

In Haskell terms, \\$B\\$ equals `(.)`, \\$C\\$ equals `flip`, and \\$K\\$ equals `const`. Haskell doesn't have a built-in for \\$W\\$, but it is equal to `(<*>id)`.

## Challenge

Given a lambda term, convert it to an equivalent term in BCKW system.

The I/O format is flexible. The lambda term and BCKW term can be represented as a string notation (fully parenthesized or using prefix notation) or a (pre-parsed) nested structure. It is also allowed to use four distinct values (numbers, chars, strings) in place of BCKW combinators. The lambda term can also use de Bruijn indexes or other directly equivalent representations.

Standard rules apply. The shortest code in bytes wins.

## Examples

There are infinitely many different correct outputs for every input, so these are merely examples of possible conversions.

```
\x. x
=>  W K  or  B C C
\x. x x
=>  W (W K)
\x y z. x (y z)
=>  B
\x y z. z x y
=>  B C (C (W K))
\f g x y. f (g x) (g y)
=>  B W (B (B C) (B (B (B B)) B))
\x y z. y (y y) y
=>  K (W (W (W (B (B (B (B K))) B))))
\f x. f (f (f x))
=>  W (W (C (B B (B B B)) B))

```

# Answer
> 7 votes
# Haskell, 133 bytes

```
data T=T:@T|L T|V Int|B|C|K|W
l(x:@y)=W:@(B:@(C:@l x):@l y)
l(V 0)=W:@K
l(V n)=K:@V(n-1)
l x=K:@x
f(L x)=l$f x
f(x:@y)=f x:@f y
f x=x

```

Try it online!

Accepts De Bruijn–indexed lambda terms with \\$λ\\$ written as `L`, application written as `:@`, and variables written `V 0`, `V 1`, … from innermost to outermost.

This uses the standard unoptimized \\$SKI\\$ abstraction elimination algorithm, with \\$Sxy\\$ and \\$I\\$ replaced by \\$W(B(Cx)y)\\$ and \\$WK\\$. As such, it’s very inefficient in terms of output size.

# Answer
> 4 votes
# Python 3, 451 bytes

```
I='W','K'
F=lambda v,e:v==e[0]or F(v,e[1])if[]==e*0else e!=v if''==e*0else F(v,e[0])and F(v,e[1])
f=lambda x,u:0*x==()and u==x[1]
T=lambda e,v='$':e if''==e*0else(T(e[1][0],v)if f(*e[::-1])and F(e[0],e[1][0])else(('K',T(e[1],v))if F(*e)else(I if e[0]==e[1]else T([e[0],T(*e[::-1])],v))))if[]==e*0else((('W',e[0][0])if f(e,v)else(('C',e[0][0]),e[1]),v)if f(e[0],v)else(((('B',e[0]),e[1][0]),v)if f(e[1],v)else((I,v)if v==e[0]else T(e[0],v),T(e[1],v))))

```

Try it online!

Previous byte counts: 628, 617, 559, 552, 536, 506, 495, 480, 472, 461, 456

I was working on a term-rewriting procedure for this in my free time anyways, why not golf it? Input/Output format is strings for variables, ~~tuples~~ lists of length two for lambda abstractions, and ~~lists~~ tuples of length two for applications.

(Reduced char count by switching input/output method)

(Reduced to 559 bytes thanks to @ovs)

---
Tags: code-golf, functional-programming, combinatory-logic, lambda-calculus
---


title: Encrypt this Message

text:
# Question
Title: Encrypt this Message
Given a permutation of the alphabet and an input string, encrypt the input string by replacing all characters with the one's you've been given. The capitalization should be kept the same and non-letters are not to be changed.

```
[hnvwyajzpuetroifqkxmblgcsd], "Hello, World!" -> "Zytti, Giktw!"

```

As `[abcdefghijklmnopqrstuvwxyz]` has been mapped to `[hnvwyajzpuetroifqkxmblgcsd]`

## IO

Input may be taken in any reasonable form, output can either be to `STDOUT` or as a String.

## More test cases:

```
[ghrbufspqklwezvitmnjcdyaox], "Foo"                -> "Fvv"
[ubjvhketxrfigzpwcalmoqysdn], "123Test String :D"  -> "123Mhlm Lmaxze :V"
[qscxudkgemwrtbvnzolhyfaipj], "AAbcdeFghijK"       -> "QQscxuDkgemW"

```

Standard ruleset applies!

# Answer
# JavaScript (Node.js), 60 bytes

Expects `(permutation_string)(string)`.

```
p=>s=>(B=Buffer)(s).map(c=>(B(p)[q=c&32,c-q-65]||c)&95|q)+''

```

Try it online!

---

# JavaScript (ES6), 42 bytes

Assuming using lists of ASCII codes is acceptable:

```
p=>s=>s.map(c=>(p[q=c&32,c-q-65]||c)&95|q)

```

Try it online!
> 5 votes

# Answer
# 05AB1E, 7 bytes

```
DuìD{s‡

```

Try it online!

```
Du       # make a copy of the permutation and convert it to uppercase
  ì      # prepend the uppercase copy to the permutation
   D{    # make a copy of the new string and sort it
         # this always creates 'A ... Za ... z'
     s   # swap alphabet and permutation
      ‡  # transliterate the second input based on the given strings

```
> 5 votes

# Answer
# Jelly, 8 bytes

```
Œu;$ØẠ,y

```

Try it online!

Chaining rules make this too long.

## How it works

```
Œu;$ØẠ,y - Main link. Takes permutation P on the left, string S on the right
   $     - Last two links as a monad f(P):
Œu       -   Uppercase P
  ;      -   Prepend that to P
    ØẠ   - Alphabet; Yield "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
      ,  - Pair; [ØẠ, P ; upper(P)]
       y - Transliterate S, according to that mapping

```
> 4 votes

# Answer
# Vyxal, 7 bytes

```
:⇧+kL$Ŀ

```

Try it Online!

## Explained

```
:⇧+kL$Ŀ
:⇧+      # append the uppercase version of the input to the input
   kL    # push a-zA-Z
     $   # swap those
      Ŀ  # and transĿiterate the message

```
> 3 votes

# Answer
# Zsh, 18 bytes

```
tr a-zA-Z $1${1:u}
```

Attempt This Online!

Trivial.
> 3 votes

# Answer
# APL (Dyalog Extended), ~~25~~ 21bytes

```
{(×⍵)×⍺∘(,⊃⍨⎕A⍳⊢)¨⌈⍵}

```

Try it online!

This can most definitely be shorter.

-4 bytes thanks to ovs.
> 2 votes

# Answer
## Python 3, ~~147~~ ~~179~~ 151 Bytes

This method doesn't work for test cases containing ABCDEF due to the "g-97" statement.

~~```
x=[ord(i) for i in input()];c=chr
print("".join([c(g)*(not(c(g).isalpha())) or(c(x[g-97])*(g>97)or c(x[g-65]-32))for g in[ord(i)for i in input()]]))

```~~

There must be a shorter way to do this using mapping, but I haven' quite figured the mapping function out yet. Golf'ed down from an original 180 just a shame its not quite a one liner.

```
x=[ord(i)for i in input()];y=[ord(i) for i in input()];t=""
for i in range(len(y)):
    g=y[i]
    if 122>g>97:t+=chr(x[g-97])
    else:t+=chr(g)*(not(90>g>65))or chr(x[g-65]-32)
print(t)

```

New method gets it to work with fewer bytes:

```
x=[ord(i)for i in input()];c=chr
print("".join([(c(x[g-97])if 123>g>96 else c(x[g-65]-32))if c(g).isalpha()else c(g)for g in[ord(i)for i in input()]]))

```

Movatica has a shorter solution using the string library. And using := I could reduced my answer to a one-liner at the expense of a few bytes
> 1 votes

# Answer
# Python 3, 84 bytes

*Codebook needs to be a string too.*

```
lambda a,s:s.translate(str.maketrans(ascii_letters,a+a.upper()))
from string import*

```

Try it online!
> -1 votes

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


title: Operations with Lists

text:
# Question
Title: Operations with Lists
Inspired by this question.

Given a list containing numbers, print:

* The sum and product of the numbers in the list
* The average and median
* The differences between each term in the list (e.g. `[1,2,3] -> [1,1]: 1+1=2, 2+1=3`)
* The list, sorted ascending
* The minimum and maximum of the list
* The standard deviation of the list

For reference:

**Standard Deviation**

$$\sigma=\sqrt{\frac1N\sum^N\_{i=1}(x\_i-\mu)^2}$$

Where \\$\mu\\$ is the mean average, \\$x\_i\\$ is the \\$i\\$th term in the list, and \\$N\\$ is the length of the list.

Shortest code wins. Good luck!

# Answer
# Q, 41

```
{(+/;*/;avg;med;-':;asc;min;max;dev)@\:x}

```
> 14 votes

# Answer
# TI-BASIC, 41 bytes

`1-Var Stats` is one byte, and `Σx`, , etc. are two bytes each.

```
Ans→L₁
1-Var Stats
SortA(L₁
Disp Σx,prod(Ans),x̄,Med,ΔList(Ans),L₁,minX,maxX,σx

```

If changing the output order is allowed, a close-paren can be saved, bringing the score to 40 bytes.
> 7 votes

# Answer
## J, 73 70 characters

```
((+/;*/;a;(<.@-:@#{/:~);2&-~/\;/:~;<./;>./;%:@:(a@:*:@:(-a)))[a=.+/%#)

```

Usage:

```
   ((+/;*/;a;(<.@-:@#{/:~);2&-~/\;/:~;<./;>./;%:@:(a@:*:@:(-a)))[a=.+/%#)1 2 3 4
+--+--+---+-+-------+-------+-+-+-------+
|10|24|2.5|3|1 1 1 1|1 2 3 4|1|4|1.11803|
+--+--+---+-+-------+-------+-+-+-------+

```
> 5 votes

# Answer
# Q (87 chars)

```
(sum;prd;avg;{.5*(sum/)x[((<)x)(neg(_)t;(_)neg t:.5*1-(#)x)]};(-':);asc;min;max;dev)@\:

```

eg.

```
q) (sum;prd;avg;{.5*(sum/)x[((<)x)(neg(_)t;(_)neg t:.5*1-(#)x)]};(-':);asc;min;max;dev)@\: 10 9 8 7 6 5 4 3 2 1
55
3628800
5.5
5.5
10 -1 -1 -1 -1 -1 -1 -1 -1 -1
`s#1 2 3 4 5 6 7 8 9 10
1
10
2.872281

```
> 4 votes

# Answer
### Ruby 187

```
O=->l{g=l.size
r=l.sort
s=l.inject(:+)+0.0
m=s/g
p s,l.inject(:*),m,g%2>0?r[g/2]:(r[g/2]+r[g/2-1])/2.0,l.each_cons(2).map{|l|l[1]-l[0]},r,r[0],r[-1],(l.inject(0){|e,i|e+(i-m)**2}/g)**0.5}

```

*Usage syntax:* `O[<array>]` (for example, `O[[1,2,3]]`)

Outputs all the required values to the console, in the order specified in the question.

*IdeOne examples:*
> 4 votes

# Answer
# Julia 0.6, 66 bytes

```
x->map(f->f(x),[sum,prod,mean,median,diff,sort,extrema,std])|>show

```

Try it online!

# Julia 0.6, 88 bytes (uncorrected std dev, as in op)

```
x->map(f->f(x),[sum,prod,mean,median,diff,sort,extrema,x->std(x,corrected=false)])|>show

```

Try it online!
> 3 votes

# Answer
### Scala ~~208~~ ~~202~~ 188:

```
val w=l.size
val a=l.sum/w
val s=l.sortWith(_<_)
Seq(l.sum,l.product,a,s((w+1)/2),(0 to w-2).map(i=>l(i+1)-l(i)),s,l.min,l.max,(math.sqrt((l.map(x=>(a-x)*(a-x))).sum*1.0/w))).map(println)

```

Test:

```
scala> val l = util.Random.shuffle((1 to 6).map(p=>math.pow(2, p).toInt))
l: scala.collection.immutable.IndexedSeq[Int] = Vector(64, 8, 4, 32, 16, 2)

scala> val a=l.sum/l.size
a: Int = 21

scala> val s=l.sortWith(_<_)
s: scala.collection.immutable.IndexedSeq[Int] = Vector(2, 4, 8, 16, 32, 64)

scala> Seq(l.sum,l.product,a,s((s.size+1)/2),(0 to l.size-2).map(i=>l(i+1)-l(i)),l.sortWith(_<_),l.min,l.max,(math.sqrt((l.map(x=>(a-x)*(a-x))).sum*1.0/l.size))).map(println)
126
2097152
21
16
Vector(-56, -4, 28, -16, -14)
Vector(2, 4, 8, 16, 32, 64)
2
64
21.656407827707714

```
> 2 votes

# Answer
# Jelly, 27 bytes

```
_ÆmÆḊ÷L½$
Wẋ9SPÆmÆṁIṢṂṀÇ9ƭ€

```

Try it online!

## How it works

```
_ÆmÆḊ÷L½$ - Helper link. Takes a list l on the left
 Æm       - Yield the mean of l
_         - Subtract the mean from each element of l
   ÆḊ     - Calculate the norm
        $ - Run the previous two commands over l:
      L   -   Length of l
       ½  -   Square root
     ÷    - Divide the norm by the square root of l's length

Wẋ9SPÆmÆṁIṢṂṀÇ9ƭ€ - Main link. Takes a list l on the left
W                 - Yield [l]
 ẋ9               - Repeat 9 times
              9ƭ€ - Generate a 9 element list by running the previous 9 commands over l
                    and collecting the results together:
   S              -   Sum
    P             -   Product
     Æm           -   Mean
       Æṁ         -   Median
         I        -   Forward increments
          Ṣ       -   Sort
           Ṃ      -   Minimum
            Ṁ     -   Maximum
             Ç    -   Helper link (standard deviation)

```
> 2 votes

# Answer
# Python 3.8, ~~174~~ ~~167~~ ~~148~~ 147 bytes

*-7 bytes thanks to @wasif*
*-19 bytes thanks to `math.prod()`*
*-1 bytes thanks to @The Fifth Marshal*

```
lambda l:[sum(l),math.prod(l),mean(l),median(l),[m-n for n,m in zip(l,l[1:])],sorted(l),min(l),max(l),stdev(l)]
import math
from statistics import*

```

Try it online!
> 2 votes

# Answer
# C++14, ~~340~~ 383 bytes

As generic unnamed lambda. First parameter `L` is the list as `std::list` of floating point type and second parameter is the desired output stream, like `std::cout`.

```
#import<cmath>
#define F(x);O<<x<<'\n';
#define Y l=k;++l!=L.end();
#define A auto
[](A L,A&O){A S=L;A l=L.begin(),k=l;A n=L.size();A s=*l,p=s,d=s*s,h=n/2.;for(S.sort(),Y s+=*l,p*=*l,d+=*l**l);for(l=S.begin();--h>0;++l)F(s)F(p)F(s/n)F(*l)for(Y)O<<*l-*k++<<","F(' ')for(A x:S)O<<x<<","F(' ')F(S.front())F(S.back())F(sqrt((d-s*s/n)/(n-1)))}

```

Compiles with a warning, C++ does not allow `"` directly followed by literals like `F`. Program still running.

* -1 & -2 bytes thanks to Zacharý

Ungolfed:

```
#include<iostream>
#include<list>

#import<cmath>
#define F(x);O<<x<<'\n';
#define Y l=k;++l!=L.end();
#define A auto

auto f=
[](A L, A&O){
  A S=L;                  //copy the list for later sorting
  A l=L.begin(),          //main iterator
    k=l;                  //sidekick iterator
  A n=L.size();
  A s=*l,                 //sum, init with head of list
    p=s,                  //product, same
    d=s*s,                //standard deviation, formula see https://en.wikipedia.org/wiki/Algebraic_formula_for_the_variance
    h=n/2.;               //for the median later
  for(
    S.sort(),             //now min/med/max is at known positions in S
    Y //l=k;++l!=L.end(); //skip the headitem-loop
    s += *l,              //l points the next element which is fine
    p *= *l,              //since the head given at definiten
    d += *l * *l          //needs the sum of the squares
  );
  for(
    l=S.begin();          //std::list has no random access
    --h>0;                //that's why single increment loop
    ++l                   //until median is crossed
  )
  F(s)  //;O<<s<<'\n';    //sum
  F(p)                    //product
  F(s/n)                  //average
  F(*l)                   //median (in S)
  for(Y) //l=k;++l!=L.end(); //set l back to L
    O<<*l-*k++<<","       //calc difference on the fly
  F(' ')
  for(A x:S)              //output sorted list
    O<<x<<","
  F(' ')
  F(S.front())            //minimum
  F(S.back())             //maximum
  F(sqrt((d-s*s/n)/(n-1))) //standard deviation
}

;

using namespace std;

int main() {
 list<double> l = {10,3,1,2,4};
 f(l, cout);
}

```
> 1 votes

# Answer
# Perl 5, 204 + 1 = 205 bytes

```
@L=sort{$a<=>$b}@F;$p=1;$s+=$_,$p*=$_,$a+=$_/@F for@L;for(0..$#F){$o=($F[$_]-$a)**2/@F;push@d,$F[$_]-$F[$_-1]if$_}$o=sqrt$o;$m=@F%2?$F[@F/2]:$F[@F/2]/2+$F[@F/2-1]/2;say"$s $p$/$a $m$/@d$/@L$/@L[0,-1]$/$o"

```

Try it online!
> 1 votes

# Answer
# Factor \+ `math.unicode`, 90 bytes

```
[| s | s Σ s Π s mean s median s differences s [ > ] sort s minmax s population-std .s ]

```

Try it online!

Should be pretty self-explanatory, I hope. Factor has a built-in for each of these, but only a few have short aliases. While cleaving is cool, it's much shorter to go with locals here. Locals are also shorter than storing the words in a list and using `[ execute ] with each` on them, which would eventually catch up if the list had been re-used even more.
> 1 votes

# Answer
# Pyt, 39 bytes

```
←ĐĐĐĐĐĐĐŞ⇹Ʃ3ȘΠ4Șµ5Ș₋⇹6Ș↕⇹7ȘṀ↔ĐĐµ-²Ʃ⇹Ł/√

```

This outputs, in order, the median, the product, the differences, the list reversed, the sum, the maximum and minimum, the mean, and the standard deviation.q

Try it online!

Explanation:

```
←ĐĐĐĐĐĐĐ                                              Push the array onto the stack 8 times
        ş                                             Sort in ascending order
         ⇹                                            Stack management
          Ʃ                                           Sum
           3Ș                                         Stack management
             Π                                        Product
              4Ș                                      Stack management
                µ                                     Mean (as a float)
                 5Ș                                   Stack management
                   ₋                                  Differences
                    ⇹6Ș                               Stack management
                       ↕                              Minimum and maximum
                        ⇹7Ș                           Stack management
                           Ṁ                          Median
                            ↔                         Stack management
                             ĐĐµ-²Ʃ⇹Ł/√               Standard Deviation

```
> 0 votes

# Answer
# APL NARS, 119 chars, 182 bytes

```
{m←(s←+/w)÷n←⍴w←,⍵⋄s,(×/w),m,(n{j←⌊⍺÷2⋄2|⍺:⍵[1+j]⋄2÷⍨⍵[j]+⍵[j+1]}t),(⊂¯1↓(1⌽w)-w),(⊂t←w[⍋w]),(⌊/w),(⌈/w),√n÷⍨+/(w-m)*2}

```

test

```
  h←{m←(s←+/w)÷n←⍴w←,⍵⋄s,(×/w),m,(n{j←⌊⍺÷2⋄2|⍺:⍵[1+j]⋄2÷⍨⍵[j]+⍵[j+1]}t),(⊂¯1↓(1⌽w)-w),(⊂t←w[⍋w]),(⌊/w),(⌈/w),√n÷⍨+/(w-m)*2}
  ⎕fmt h 0
┌9──────────────────────┐
│        ┌0─┐ ┌1─┐      │
│0 0 0 0 │ 0│ │ 0│ 0 0 0│
│~ ~ ~ ~ └~─┘ └~─┘ ~ ~ ~2
└∊──────────────────────┘
  ⎕fmt h 3
┌9──────────────────────┐
│        ┌0─┐ ┌1─┐      │
│3 3 3 3 │ 0│ │ 3│ 3 3 0│
│~ ~ ~ ~ └~─┘ └~─┘ ~ ~ ~2
└∊──────────────────────┘
  ⎕fmt h 1 2 3
┌9───────────────────────────────────────┐
│        ┌2───┐ ┌3─────┐                 │
│6 6 2 2 │ 1 1│ │ 1 2 3│ 1 3 0.8164965809│
│~ ~ ~ ~ └~───┘ └~─────┘ ~ ~ ~~~~~~~~~~~~2
└∊───────────────────────────────────────┘
  ⎕fmt h 1 2 3 4
┌9────────────────────────────────────────────────┐
│              ┌3─────┐ ┌4───────┐                │
│10 24 2.5 2.5 │ 1 1 1│ │ 1 2 3 4│ 1 4 1.118033989│
│~~ ~~ ~~~ ~~~ └~─────┘ └~───────┘ ~ ~ ~~~~~~~~~~~2
└∊────────────────────────────────────────────────┘
  ⎕fmt h 1 2 7 3 4 5
┌9──────────────────────────────────────────────────────────────────┐
│                       ┌5──────────┐ ┌6───────────┐                │
│22 840 3.666666667 3.5 │ 1 5 ¯4 1 1│ │ 1 2 3 4 5 7│ 1 7 1.972026594│
│~~ ~~~ ~~~~~~~~~~~ ~~~ └~──────────┘ └~───────────┘ ~ ~ ~~~~~~~~~~~2
└∊──────────────────────────────────────────────────────────────────┘

```
> 0 votes

# Answer
# Ocaml - 288 bytes

Assuming the given list is a non-empty list of floats (to avoid conversions), and that the returned median is the weak definition of the median :

> `median l = n` such that half the elements of `l` are smaller or equal to `n` and half the elements of `l` are greater or equal to `n`

```
open List
let f=fold_left
let z=length
let s l=f(+.)0. l
let a l=(s l)/.(float_of_int(z l))let rec i=function|a::[]->[]|a::b->(hd b -. a)::(i b)let r l=let t=sort compare l in(s,f( *.)1. l,a t,nth t((z t)/2+(z t)mod 2-1),t,i l,nth t 0,nth t((z t)-1),sqrt(a(map(fun n->(n-.(a l))**2.)l)))

```

The readable version is

```
open List

let sum l = fold_left (+.) 0. l
let prod l = fold_left ( *. ) 1. l
let avg l = (sum l) /. (float_of_int (length l))
let med l =
        let center = (length l) / 2 + (length l) mod 2 -1 in
        nth l center
let max l = nth l 0
let min l = nth l ((length l) - 1)
let dev l =
let mean = avg l in
        sqrt (avg (map (fun n -> (n -. mean)**2.) l))

let rec dif =
        function
        | a::[] -> []
        | a::b -> ((hd b) - a) :: (dif b)

let result l =
        let sorted = sort compare l in
        (
                sum sorted,
                prod sorted,
                avg sorted,
                med sorted,
                sorted,
                dif l,
                max sorted,
                min sorted,
                dev sorted
        )

```
> 0 votes

# Answer
# PHP, 213 bytes

```
function($a){echo$s=array_sum($a),_,array_product($a),_,$v=$s/$c=count($a);foreach($a as$i=>$x){$d+=($x-$v)**2;$i&&$f[]=$x-$a[$i-1];}sort($a);var_dump(($a[$c/2]+$a[$c/2+~$c%2])/2,$f,$a,$a[0],max($a),sqrt($d/$c));}

```

Try it online.
> 0 votes

# Answer
# 05AB1E, 27 (or 25?) bytes

**If the order is mandatory:**

```
O,P,ÅA,Åm,¥,{R,ß,à,ÅA-nÅAt,

```

Try it online.

**If the order doesn't matter:**

```
O,P,Åm,¥,{R,ß,à,ÅA=-nÅAt,

```

Does the average just before the standard deviation, every other operation is in the same order.

Try it online.

**Explanation:**

```
O         # Sum the (implicit) input-list
 ,        # Pop and print it with trailing newline
P,        # Same for the product
ÅA,       # Same for the average
Åm,       # Same for the median
¥,        # Same for the deltas / forward differences
{R,       # Same for the descending sort (sort + reverse)
ß,        # Same for the minimum
à,        # Same for the maximum
          # Same for the standard deviation:
ÅA        #  Get the average of the (implicit) input-list
  -       #  Subtract it from each value in the (implicit) input-list
   n      #  Square each
    ÅA    #  Take the average of this list
      t   #  Take the square-root of that
       ,  #  And print it as well

```
> 0 votes

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