title: Oops, I blew it up (with numbers)

text:
# Question
Title: Oops, I blew it up (with numbers)
*Inspired by There, I fixed it (with rope), There, I fixed it (with Tape), There, I broke it (with scissors)*

Given a string with characters from `a-z` or `A-Z` (whichever you prefer), turn missing letters into numbers and make them explode.

---

# Example

Input: `abcafabc`

Output: `a12344321c`

***Why?***

1) Find the missing letters (only going forward in the alphabet): `abca(bcde)fabc`

2) Replace them with the number of missing letters: `abca4fabc`

3) Replace the number with

* Itself twice if it's even
* Itself + 1 if it's odd

In this case: `abca44fabc`

4) Explode those numbers outwards replacing any letters: `a12344321c`

---

# Challenge Rules

1. Explosions can't exceed the boundaries of the string

* `ae -> 343` (3 letters are missing but since 3 is odd, it's been replaced by 4)
2. Numbers can be greater than 9

* `az -> 23242423` (24 letters are missing and since 24 is even, it's repeated twice)
3. You can have multiple explosions

* `abcefghijmnop -> ab121fghi1221nop`
4. Multiple explosions can overlap, take the sum of the number when they do

* `abceghij -> abc(2)e(2)ghij -> ab12(1+1)21hij -> ab12221hij`
5. It's possible that no explosions occur, in that case simply return the string
6. No explosions between `ab`, `aa`, `aaa`, etc.
7. You are allowed to take the input in any reasonable format. Can be a single string, string-array/list, character-array/list, etc. Output has the same flexibility.
8. You are allowed to use lowercase and/or uppercase any way you'd like. This applies both to the input, output.

# General Rules

* This is , so the shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-golfing languages.
* Standard rules apply.
* Default Loopholes are forbidden.
* If possible, please add a link to a test for your code, preferably Tio.
* Also, please add an explanation if necessary.

---

# Test cases:

```
Input  : 'abcdefgklmnopqrstuvwxyz'
Output : 'abcd1234321nopqrstuvwxyz'

Input  : 'abdefgjkl'
Output : 'a121ef1221kl'

Input  : 'xyzaz'
Output : '20212223242423'

Input  : 'abceghij'
Output : 'ab12221hij'

Input  : 'zrabc'
Output : 'zrabc'

```

# Answer
> 2 votes
# Perl 5, `-p` ~~110~~ 109 bytes

Handling the even/odd rules waste around 20 bytes

```
#!/usr/bin/perl -p
s#.#$p+=$.;$c{$p-$_}+=$-=$z-abs$_+$z%2/2for-25..($z=ord($')-ord$&);$&x($.=$z<2||$z%2+2)#eg;s##$c{+pos}||$&#eg

```

Try it online!

# Answer
> 3 votes
# Ruby, 162 bytes

```
->a{b=[*a=a.reduce{|x,y|[*x,*[(n=y.ord+~x[-1].ord)+n%2]*(n<1?0:2-n%2),y]}];i=-1;b.map{|x|d=-~i+=1;a.map!{|y|(z=x.to_i-(d-=1)*s=d<=>0)<1||x==b[i-s]?y:z+y.to_i}};a}

```

Try it online!

Takes input as an array of chars, returns a mixed array of chars/ints. (I'm still not sure whether this is allowed after reading the comments to the original post. If not allowed, it's +3 bytes to fix).

## Explanation

First, we apply a `reduce` operation, where we aren't actually reducing anything, but rather reconstruct the array `a` as `[*x,*[...],y]`, where the middle part contains the numbers inserted at ground zero.

We also make a copy of the array: `b=[*a]` to serve as a reference, so that we don't get confused which numbers are at the center of the explosion, and which ones are introduced later on.

Then we iterate through `b` and for each element `x`, iterate through `a` to record, what effect `x` will have on each element `y` of `a`.

Conveniently, `to_i` method returns 0 for non-numeric chars, so that we don't have to worry about distinction between numbers and text.

In my initial code, arrays were indexed by `i` and `j`, but this was golfed down to use a "delta" value `d=i-j`.

Another helper variable is the sign of the delta: `s=d<=>0`. At the first occurrence it performs the same function as `abs`, and at the second - it helps us to block the other side of one-sided explosions as in `12344321`.

Ultimately, if `z` is estimated to be positive, we add it up with the integer equivalent of `y` and store in `a`, otherwise, `y` remains intact.

# Answer
> 2 votes
# Python 3, ~~351~~ 348 bytes

```
Z=zip
R=range
E=lambda o:R(o,0,-1)
D=lambda d:[]if d<1else[[E(d),E(d+1)]]if d%2else[[E(d-1),[d]],[[],E(d)]]
def f(s):
	s=sum(([c]+D(ord(n)+~ord(c))for c,n in Z(s,s[1:]+' ')),[]);l=len(s);v=[0]*l
	for i,c in enumerate(s):
		if len(c)>1:
			for j,d in list(Z(R(i-1,-1,-1),c[0]))+list(Z(R(i,l),c[1])):v[j]+=d
	print(*(d or c for c,d in Z(s,v)),sep='')

```

Try it online!

* −3 thanks to Kevin

The function `f` takes one string as input and prints the result to standard output.

## Ungolfed

```
def range_downto_0(o):
    return range(o, 0, -1)

def D(d):
    return (
        []
        if d >= 0 else
        [[range_downto_0(d), range_downto_0(d + 1)]]
        if d % 2 else
        [[range_downto_0(d - 1), [d]], [[], range_downto_0(d)]]
    )

def f(s):
    s = sum(([c] + D(ord(n) + ord(c) - 1) for c, n in zip(s, s[1:] + ' ')), [])
    v = [0] * len(s)
    for i, c in enumerate(s):
        if len(c) == 2:
            for j, d in itertools.chain(
                zip(range(i - 1, -1, -1), c[0])),
                zip(range(i, len(s)), c[1])
            ):
                v[j] += d
    return ''.join(str(d) if d else c for c, d in zip(s, v))

```

## Explanation

1. Expand the string `s` to insert number range objects as placeholders for the "outward explosions". Save the result as a list `s`.
2. Create a list of zeros `v` with the same length as `s`.
3. Inspect `s` and, for every number range, add the numerical values to the value at their respective position in `v`. `v` now contains all the numbers that are going to be in the result at their correct positions.
4. Iterate over `s` and `v` simultaneously, take the entry from `v` if it is greater than 0 or the entry from `s` otherwise and print each chosen entry in order.

The expensive repeated array concatenation in step 1 is at best in O(n2) but could be expressed in O(n) using a generator (assuming Python can construct lists from generators in O(n)). The remainder of this algorithm is in O(n ⋅ min{n, |Σ|} ⋅ log |Σ|) with Σ being the alphabet or, if you want to regard Σ as a constant, straight out O(n) (assuming that Python can join string generators in O(n)). “min{n, |Σ|}” comes from the outward range expansion and “log |Σ|” results from the conversion of numbers to strings.

# Answer
> 1 votes
# C (gcc), 395 bytes

```
#include<stdlib.h>
#include<stdio.h>
f(char*s){char*S=s;while(*S++);const int l=S-s-1;int i=1,j=0,k,d,o,t[l*3],*v;for(;i<l;i++)(d=s[i]+~(t[j++]=s[i-1]))>0&&(t[j++]=-d,d%2||(t[j++]=0));l>0&&(t[j++]=s[l-1]);v=calloc(k=j,4);for(i=0;i<k;i++){if((d=-t[i])>0){d+=o=d%2;for(j=0;j<d&&j<=i;j++)v[i-j]+=d-j;i+=!o;for(j=o;j<d&&i+j<k;j++)v[i+j]+=d-j;}}for(i=0;i<k;i++){d=v[i];printf(d?"%d":"%c",d?d:t[i]);}}

```

Try it online!

`f` takes input as a null-terminated character array and returns its result on standard output.

## Explanation

This is my first C submission to Code Golf. The algorithm is the same as in my Python submission.

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


title: Percent-Encode a String

text:
# Question
Title: Percent-Encode a String
## Introduction

As some of you may know, URLs actually have a list of characters that do special things. For example, the `/` character separates parts of the URL, and the `?`, `&`, and `=` characters are used to pass query parameters to the server. In fact, there is a bunch of characters with special functions: `$&+,/:;=?@`. When you need to use these characters in the URL for any other reason besides the special functions, you have to do something called percent-encoding.

Percent encoding is when you take a character's hexadecimal value and prepend a `%` character to the beginning of it. For example, the character `?` would be encoded as `%3F`, and the character `&` would be encoded as `%26`. In a URL specifically, this allows you to send these characters as data via the URL without causing parsing problems. Your challenge will be to take a string, and percent-encode all of the characters that need to be encoded.

## The Challenge

You shall write a program or function that takes in a single string consisting of characters with codepoints 00-FF (ASCII and Extended ASCII characters). You will then have to output or return the same string with each character percent-encoded if necessary. **Built-ins that accomplish this task are not allowed, nor are standard loopholes.** For reference, here is a list of every character that needs to be percent encoded:

* Control characters (Codepoints 00-1F and 7F)
* Extended ASCII characters (Codepoints 80-FF)
* Reserved characters (`$&+,/:;=?@`, i.e. codepoints 24, 26, 2B, 2C, 2F, 3A, 3B, 3D, 3F, 40)
* Unsafe characters (`" <>#%{}|\^~[]``, i.e. codepoints 20, 22, 3C, 3E, 23, 25, 7B, 7D, 7C, 5C, 5E, 7E, 5B, 5D, 60)

Here is a the same list, but instead as a list of decimal codepoints:

```
0-31, 32, 34, 35, 36, 37, 38, 43, 44, 47, 58, 59, 60, 62, 61, 63, 64, 91, 92, 93, 94, 96, 123, 124, 125, 126, 127, 128-255

```

**This is code golf, so shortest code in bytes (or approved alternative scoring method) wins!**

## Test Cases

```
http://codegolf.stackexchange.com/  =>  http%3A%2F%2Fcodegolf.stackexchange.com%2F
[@=>]{#}  =>  %5B%40%3D%3E%5D%7B%23%7D
Test String  =>  Test%20String
ÑÉÐÔ®  =>  %D1%C9%D0%D4%AE
  =>  %0F%16%7F (Control characters 0F, 16, and 7F)
 ¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ  =>  %80%81%82%83%84%85%86%87%88%89%8A%8B%8C%8D%8E%8F%90%91%92%93%94%95%96%97%98%99%9A%9B%9C%9D%9E%9F%A0%A1%A2%A3%A4%A5%A6%A7%A8%A9%AA%AB%AC%AD%AE%AF%B0%B1%B2%B3%B4%B5%B6%B7%B8%B9%BA%BB%BC%BD%BE%BF%C0%C1%C2%C3%C4%C5%C6%C7%C8%C9%CA%CB%CC%CD%CE%CF%D0%D1%D2%D3%D4%D5%D6%D7%D8%D9%DA%DB%DC%DD%DE%DF%E0%E1%E2%E3%E4%E5%E6%E7%E8%E9%EA%EB%EC%ED%EE%EF%F0%F1%F2%F3%F4%F5%F6%F7%F8%F9%FA%FB%FC%FD%FE%FF (Extended ASCII characters 80-FF)
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~  =>  %20!%22%23%24%25%26'()*%2B%2C-.%2F0123456789%3A%3B%3C%3D%3E%3F%40ABCDEFGHIJKLMNOPQRSTUVWXYZ%5B%5C%5D%5E_%60abcdefghijklmnopqrstuvwxyz%7B%7C%7D%7E

```

# Answer
# Pyth, 30 28 26 bytes

```
L?hx+G+rG1CGbb+\%.HCbsmydz

```

try it online

## Explanation

```
L?hx+G+rG1CGbb+\%.HCbsmydz
L?hx+G+rG1CGbb+\%.HCb       First part, L defines the function y(b)
 ?hx+G+rG1CGbb+\%.HCb       ? is the ternary operator
  hx+G+rG1CGb               This part will be evaluated
  hx                        x will find the first occurence of a
                            character in a list. If it doesn't
                            find one, it will return -1. hx then
                            equals 0 (or false).
    +G+rG1CG                The list of allowed characters, a
                            concetanation (+) of the alphabet (G),
                            uppercase alphabet (rG1) and numbers
                            (CG, see below for details)
            b               The character to find in the list
             b              True branch of the ternary operator,
                            the character is allowed and returned.
              +\%.HCb       False branch, convert to hex and add %
                     smydz  The actual program
                      mydz  Map every character in the input (z)
                            using the function y on every d
                     s      Join the array, and implicit print.

```

`CG` is this trick that generate a huge number that contains all possible digits. This is perfect, since we don't care for duplicates when checking whether a string is in another.
> 2 votes

# Answer
# Vim, 67 bytes/keystrokes

```
:s/\c[^a-z!'()*0-9._-]/\='%'.printf("%02x",char2nr(submatch(0)))/g<cr>

```

Note that `<cr>` represents the enter key, e.g. `0x0D` which is a single byte.

This is a pretty straightforward solution. Explanation:

```
:s/                                                                    "Search and replace
   \c                                                                  "Case-insensitive
     [^a-z!'()*0-9._-]/                                                "A negative range. Matches any character not alphabetc, numeric or in "!'()*0-9._-"
                       \=                                              "Evaluate
                         '%'                                           "a percent sign string
                            .                                          "Concatenated with
                             printf("%02x",char2nr(submatch(0)))       "The hex value of the character we just matched
                                                                /g     "Make this apply to ever match
                                                                  <cr> "Actually run the command

```

That `printf("%02x",char2nr(submatch(0)))` garbage is terribly *ungolfy*.
> 3 votes

# Answer
## Perl, 40 bytes

**39 bytes code + `-p`.**

A bit lame, but I think it's the shortest solution...

```
s/[^!'()*-.\w]/sprintf'%%%02x',ord$&/ge

```

### Usage

```
echo -n ' !"#$%&'\''()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqstuvwxyz{|}~' | perl -pe "s/[^'()*-.\w]/sprintf'%%%02x',ord$&/ge"
%20%21%22%23%24%25%26'()*+,-.%2f0123456789%3a%3b%3c%3d%3e%3f%40ABCDEFGHIJKLMNOPQRSTUVWXYZ%5b%5c%5d%5e_%60abcdefghijklmnopqstuvwxyz%7b%7c%7d%7e

```
> 2 votes

# Answer
# Julia, 47 bytes

```
!s=replace(s,r"[^\w!'()*.-]",c->"%"hex(c[1],2))

```

Try it online!
> 2 votes

# Answer
# Python 3, 92 bytes

**5 bytes thanks to orlp.**

**1 byte thanks to Sp3000.**

```
import re;lambda s:''.join(re.match("[!'-*.0-9\w-]",c,256)and c or'%%%02X'%ord(c)for c in s)

```

Ideone it!
> 1 votes

# Answer
# C, 83 bytes

```
f(char*p){for(;*p;++p)printf(isalnum(*p)||strchr("!'()*-._",*p)?"%c":"%%%02X",*p);}

```
> 1 votes

# Answer
# Python, 86 bytes

```
lambda s:"".join(["%%%02X"%ord(c),c][c<"{"and c.isalnum()or c in"!'()*-._"]for c in s)

```

Port of my C answer.
> 1 votes

# Answer
# Jelly, ~~28~~ 27 bytes

```
ḟØWḟ©“!'()*-.”Od⁴‘ịØH”%p®,y

```

This is a monadic link. Try it online!

### How it works

```
ḟØWḟ©“!'()*-.”Od⁴‘ịØH”%p®,y  Monadic link. Argument: s (string)

 ØW                          Yield “0...9A...Z_a...z”.
ḟ                            Remove these characters from s.
     “!'()*-.”               Yield “!'()*-.”.
   ḟ                         Remove these characters from s.
    ©                        Copy the result to the register.
              O              Ordinal; get the code point of each character.
               d⁴            Divmod 16; yield quotient and remainder modulo 16.
                 ’           Decrement the results.
                  ịØH        Index into “0123456789ABCDEF”.
                     ”p%     Perform Cartesian product with ”%, prepending it to
                             each pair of hexadecimal digits.
                        ®,   Yield [t, r], where t is the string in the register
                             and r the result of the Cartesian product.
                          y  Use this pair to perform transliteration on s.

```
> 1 votes

# Answer
# Ruby, 37 + 3 = 40 bytes

Run with `-p` (3 extra bytes), like `$ ruby -p percent_encode.rb`:

```
gsub(/[^\w!'()*-.]/){"%%%02X"%$&.ord}

```
> 1 votes

# Answer
# Haskell, ~~201~~ ~~179~~ ~~178~~ ~~127~~ 119 bytes

```
import Data.Char;import Numeric;f=(=<<)(\c->if isAlphaNum c&&isAscii c||elem c"-_.~"then[c]else '%':(showHex$ord c)"")

```

Ungolfed:

```
import Data.Char
import Numeric

f=(=<<) e
e c = if isAlphaNum c && isAscii c && c `elem` "-_.~" then [c] else '%' : (showHex $ ord c) ""

```
> 1 votes

# Answer
## 16/32-bit x86 assembly, 73 bytes

Byte code:

```
AC 3C 21 72 2A 74 3E 3C 26 76 24 3C 2B 72 36 3C
2C 76 1C 3C 2F 72 2E 74 16 3C 3A 72 28 74 10 3C
5F 74 22 50 0C 60 3C 60 74 02 3C 7B 58 72 16 D4
10 3C 09 1C 69 2F 86 E0 3C 09 1C 69 2F 92 B0 25
AA 92 AA 86 E0 AA E2 B8 C3
```

Disassembly:

```
l0: lodsb         ;fetch a character
    cmp  al, 21h
    jb   l1       ;encode 0x00-0x20
    je   l2       ;store 0x21
    cmp  al, 26h
    jbe  l1       ;encode 0x22-0x26
    cmp  al, 2bh
    jb   l2       ;store 0x27-0x2A
    cmp  al, 2ch
    jbe  l1       ;encode 0x2B-0x2C
    cmp  al, 2fh
    jb   l2       ;store 0x2D-0x2E
    je   l1       ;encode 0x2F
    cmp  al, 3ah
    jb   l2       ;store 0x30-0x39
    je   l1       ;encode 0x3A
    cmp  al, 5fh
    je   l2       ;store 0x5F
    push eax
    or   al, 60h  ;merge ranges
    cmp  al, 60h
    je   l3       ;encode 0x40, 0x60
    cmp  al, 7bh
l3: pop  eax
    jb   l2       ;store 0x41-0x5A, 0x61-0x7A
                  ;encode 0x3B-0x3F, 0x5B-0x5E, 0x7B-0xFF

l1: aam  10h      ;split byte to nibbles
    cmp  al, 9    ;convert 0x0A-0x0F
    sbb  al, 69h  ;to
    das           ;0x41-0x46 ('A'-'F')
    xchg ah, al   ;swap nibbles
    cmp  al, 9    ;do
    sbb  al, 69h  ;other
    das           ;half
    xchg edx, eax ;save in edx
    mov  al, '%'
    stosb         ;emit '%'
    xchg edx, eax
    stosb         ;emit high nibble
    xchg ah, al

l2: stosb         ;emit low nibble or original character
    loop l0       ;until end of string
    ret
```

Call with:
\- esi = pointer to buffer that holds source string;
\- edi = pointer to buffer that receives encoded string;
\- ecx = length of source string.
> 1 votes

# Answer
## Python 2, 78 bytes

```
lambda s:"".join(["%%%02x"%ord(c),c][c.isalnum()or c in"!'()*-._"]for c in s)

```

More nicely formatted:

```
lambda s:
    "".join(["%%%02x" % ord(c), c][c.isalnum() or c in"!'()*-._"] for c in s)

```
> 0 votes

# Answer
# SQF, ~~199~~ 176

Using the function-as-a-file format:

```
i="";a="0123456789ABCDEF!'()*-.GHIJKLMNOPQRSTUVWXYZ_";{i=i+if((toUpper _x)in a)then{_x}else{x=(toArray[_x])select 0;"%"+(a select floor(x/16))+(a select(x%16))}}forEach _this;i

```

Call as `"STRING" call NAME_OF_COMPILED_FUNCTION`
> 0 votes

# Answer
## PowerShell v2+, 146 bytes

```
param($n)37,38+0..36+43,44,47+58..64+91,93+96+123..255-ne33|%{$n=$n-replace"[$([char]$_)]",("%{0:x2}"-f$_)};$n-replace'\\','%5c'-replace'\^','%5e'

```

Long because I wanted to show a different approach rather than just copy-pasting the same regex string that every else is using.

Instead here, we loop through every code point that *must* be percent-encoded, and do a literal `-replace` on the input string `$n` each iteration (re-saving back into `$n`). Then we need to account for the two special characters that need escaping, `\` and `^`, so those are in separate `-replace` elements at the end. Since we didn't re-save that final string, it's left on the pipeline and printing is implicit.
> 0 votes

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


title: Shifting-Oriented Programming

text:
# Question
Title: Shifting-Oriented Programming
A string can be *shifted* by a number `n` by getting the byte value `c` of each character in the string, calculating `(c + n) mod 256`, and converting the result back to a character.

As an example, shifting `"ABC123"` by 1 results in `"BCD234"`, shifting by 10 in `"KLM;<="`, and shifting by 255 in `"@AB012"`.

### The Task

Pick as many numbers `n` with `0 < n < 256` as you dare and write a program or function that takes a string as input and

* returns the string unchanged when the source code is unchanged, but
* returns the string shifted by `n` when the source code is shifted by `n`.

### Rules

* The score of your submission is the number of supported `n`, with a higher score being better. The maximum score is thus 255.
* Your submission must support at least one shift, so the minimal score is 1.
* In case of a tie the shorter program wins.
* All shifted programs need to be in the same language.

# Answer
# Brainfuck, score: 31 (2208 bytes)

Base64-encoded program:

```
[encoded data, 5160 characters]
```

Works for shifts 0, 4, 8, 12, 32, 36, 40, 44, 64, 68, 72, 76, 96, 100, 104, 108, 128, 132, 136, 140, 160, 164, 168, 172, 192, 196, 200, 204, 224, 228, 232 and 236.

For every value between 0 and 255, there is exactly one of those shifts that sends that character to a valid brainfuck instruction.

The program relies on 8-bit cells with wrapping on overflows. This could probably be golfed quite a bit, as the shift just consists of a repeated `+` or `-` (whichever is shorter).

Python code used to generate this:

```
l = [0, 4, 8, 12, 32, 36, 40, 44, 64, 68, 72, 76, 96, 100, 104, 108, 128, 132, 136, 140, 160, 164, 168, 172, 192, 196, 200, 204, 224, 228, 232, 236]
shift = lambda s,n:"".join(chr((ord(i)+n)%256) for i in s)
code = ""
for i in l:
    code += shift(",[{}.,]".format(i*"+" if i<=128 else (256-i)*"-"),-i)

```
> 24 votes

# Answer
# lHaskell, Score 255 (27,026 bytes)

The program works but putting it in my clipboard seems to destroy it so here is code that outputs my program.

## Verification

So if copying things to a clipboard breaks it how do I verify that it works?

You can use this here. You can adjust `N` and the string (currently `Big ol' egg`) to see that it works yourself.

This will test all N on a single input in succession but tends to time out.

## Explanation

This abuses literate Haskell's comment notation. In literate Haskell any line that does not start with `>` is a comment. So to make our code work we make 255 copies of the program each shifting by `n` and then we shift each individual copy by `-n`.
> 21 votes

# Answer
# C, score: 1 (73 bytes)

```
aZ0;/*0\:..*/f(s){puts(s);}//	e'bg`q)r(zenq':)r:**r(otsbg`q'')r*0($145(:|
```

Try it online!

**Shifted by 1:**

```
b[1<0+1];//+0g)t*|qvut)t*<~00
f(char*s){for(;*s;++s)putchar((*s+1)%256);}

```

Try it online!
> 20 votes

# Answer
# 05AB1E, Score: 3 (24 bytes)

```
¶Ä0(ä.g){n·Å0)åH*oHÆ0*æI

```

Try it online!

**Explanation**

```
¶Ä0(ä.g){n·Å0)åH*oHÆ0*æ  # Doesn't matter
                       I # Push the original input to the stack, implicit display

```

Shifted once:

```
·Å1)å/h*|o¸Æ1*æI+pIÇ1+çJ

```

Try it online!

**Explanation**

```
·Å1)å/h*|o¸Æ1*æI+p       # Doesn't matter
                  IÇ     # Push the ASCII values of the input
                    1+   # Increment by 1
                      çJ # Push the chars of the ASCII values, join, implicit display

```

Shifted twice:

```
¸Æ2*æ0i+}p¹Ç2+çJ,qJÈ2,èK

```

Try it online!

**Explanation**

```
Æ2*æ0i+}p         # Doesn't matter
         ¹Ç       # Push the ASCII values of the input
           2+     # Increment by 2
             çJ   # Push the chars of the ASCII values, join
               ,q # Print and terminate

```

Shifted thrice:

```
¹Ç3+ç1j,~qºÈ3,èK-rKÉ3-éL

```

Try it online!

**Explanation**

```
¹Ç        # Push the ASCII values of the input
  3+      # Increment by 3
    ç1j   # Push the chars of the ASCII values, join
       ,q # Print and terminate

```
> 7 votes

# Answer
# Javascript, score: ~~1~~ 4 (~~94~~ 346 bytes)

Pretty straight-forward, has different sections commented out when rotated, the difficult bit was finding usable variable names and comment sections that don't break Javascript syntax.

Unrotated:

```
hc/*% *%nnS/0S eb^[fRR _SbS/0Efd[`Y Xda_5ZSd5aVWS UZSd5aVW3f"#&$'( \a[`RR!! %34hc/*$ifb_jVV$cWfW34Ijh_d]$\hec9^Wh9eZ[W$Y^Wh9eZ[7j&!'&(+,$`e_dVV%%%*89hc/)nkgdo[[)h\k#\89Nomdib)amjh>c\m>j_`###\)^c\m>j_`<o#+$&0$ -01$$$)ejdi[[***/=>/*ch*/hc//chhcchvw*/g¬©¥¢g¦©avw«¢§ g«¨¦|¡«|¨aaag¡«|¨zaibdjrrb^knobbbg£¨¢§

```

Rotated by 5:

```
mh4/*%$/*ssX45X%jgc`kWW%dXgX45Jki`e^%]ifd:_Xi:f[\X%Z_Xi:f[\8k' "(+ ),-   %af`eWW &&%*89mh4/)nkgdo[[)h\k#\89Nomdib)amjh>c\m>j_`###\)^c\m>j_`<o#+$&,+$ -01$$$)ejdi[[***/=>mh4.split``.map(a=>String.fromCharCode(((a.charCodeAt(0)+5)%256))).join``///4BC4/hm/4mh44hmmhhm{|/4l±®ª§²l«®f{|²°§¬¥l¤°«¦°¢£fffl¡¦°¢£²fngiowwgcpstgggl¨§¬

```

Rotated by 10:

```
rm94/*)4/xx$]9:]*olhep\\*i]l$]9:Opnejc*bnki?d]n?k`a$$$]*_d]n?k`a=p$,%'-0%!.12%%%*fkej\\%++*/=>rm94.split``.map(a=>String.fromCharCode(((a.charCodeAt(0)+10)%256))).join``///4BCrm93xuqnyee3rfu-fBCXywnsl3kwtrHmfwHtij---f3hmfwHtijFy-5.0:.*7:;...3otnsee4449GH94mr49rm99mrrmmr49q¶³¯¬·££q°¤³k¤·µ¬±ªq©µ²°«¤µ²§¨kkk¤q¦«¤µ²§¨·kslnt||lhuxylllq²¬±££

```

Rotated by 14: things finally got interesting here, got to abuse the Javascript type system.

```
vq=83.-83||(a=>a.split``.map(a=>String.fromCharCode(((a.charCodeAt(0)+14)%256))).join``)//.3ABvq=82wtpmxdd2qet,eABWxvmrk2jvsqGlevGshi,,,e2glevGshiEx,4-/54-)69:---2nsmrdd3338FGvq=7|yur}ii7vjy1jFG\}{rwp7o{xvLqj{Lxmn111j7lqj{LxmnJ}1924>2.;>?2227sxrwii888=KL=8qv8=vq==qvvqqv8=uº·³°»§§u´¨·o¨»¹°µ®u¹¶´¯¨¹¶«¬ooo¨uª¯¨¹¶«¬»owprxply|}pppu±¶°µ§§

```

Rotated by 199:

```
/*öñìçæñì55áö÷ç,)%"-ç&)áö÷-+"' ç+(&ü!+ü(áááç!+ü(ú-áéâäêíâÞëîïâââç#("'âèèçìúû/*öñë0-)&1ë*-åúû1/&+$ë#/,*%/,!"åååë %/,!"þ1åíæèîíæâïòóæææë',&+ìììñÿ/*öð52.+6""ð/#2ê#ÿ64+0)ð(41/*#41&'êêê#ð%*#41&'6êòëí÷ëçô÷øëëëð,1+0""ñññööñ*/ñö/*öö*//**/=>ñö.split``.map(a=>String.fromCharCode(((a.charCodeAt(0)+199)%256))).join``

```

To find the solutions, I built a small tool to show me different snippets when rotated by a variable amount, I then found certain patterns that I could use as useful building blocks.

The main gist of it is that `a/**/=>a` is still a valid function definition, which allows you to embed a reverse rotated function in the comment section. From there on, it can be repeated a few times, if done correctly.

Since most of the comment sections are nested, it might be possible to find another result, but making it work becomes increasingly difficult with each added answer due to collisions and control characters.

---

Replacing all usages of `charCodeAt(0)` with `charCodeAt``` would shave 4 bytes off the whole solution, but it's too much work to do from scratch.
> 6 votes

# Answer
# PHP with `-d output_buffering=on -d short_open_tag=on`, score: 255 (25,731 bytes)

```
<?die($argv[1]);?>
=@pc`dmfbo)*<ejf)qsfh`sfqmbdf`dbmmcbdl)#0/0#-gvodujpo)%n*|sfuvso!dis)pSe)%n\1^*.2*<~-%bshw\2^**<@?>Aqdaengcp*+=fkg*rtgiatgrncegaecnndcem*$101$.hwpevkqp*&o+}tgvwtp"ejt*qTf*&o]2_+/4+=.&ctix]3_++=A@?Brebfohdq+,>glh+suhjbuhsodfhbfdooedfn+%212%/ixqfwlrq+'p,~uhwxuq#fku+rUg+'p^3`,06,>?/'dujy^4`,,>BA
@Csfcgpier,-?hmi,tvikcvitpegicgeppfego,&323&0jyrgxmsr,(q-vixyvr$glv,sVh,(q_4a-18-??0(evkz_5a--?CBADtgdhqjfs-.@inj-uwjldwjuqfhjdhfqqgfhp-'434'1kzshynts-)r.?wjyzws%hmw-tWi-)r`5b.2:.@?1)fwl{`6b..@DCBEuheirkgt./Ajok.vxkmexkvrgikeigrrhgiq.(545(2l{tizout.*s/?xkz{xt&inx.uXj.*sa6c/3</A?2*gxm|a7c//AEDCFvifjslhu/0Bkpl/wylnfylwshjlfjhssihjr/)656)3m|uj{pvu/+t0?yl{|yu'joy/vYk/+tb7d04>0B?3+hyn}b8d00BFEDGwjgktmiv01Clqm0xzmogzmxtikmgkittjiks0*767*4n}vk|qwv0,u1?zm|}zv(kpz0wZl0,uc8e15@1C?4,izo~c9e11CGFEHxkhlunjw12Dmrn1y{nph{nyujlnhljuukjlt1+878+5o~wl}rxw1-v2?{n}~{w)lq{1x[m1-vd9f26B2D?5-j{pd:f22DHGFIylimvokx23Enso2z|oqi|ozvkmoimkvvlkmu2,989,6pxm~syx2.w3?|o~|x*mr|2y\n2.we:g37;:3E?6.k|q?e;g33EIHGJzmjnwply34Fotp3{}prj}p{wlnpjnlwwmlnv3-:9:-7q?yntzy3/x4?}p?}y+ns}3z]o3/xf;h48<<4F?7/l}r?f<h44FJIHK{nkoxqmz45Gpuq4|~qsk~q|xmoqkomxxnmow4.;:;.8r?zo?u{z40y5?~q??~z,ot~4{^p40yg<i59=>5G?80m~s?g=i55GKJIL|olpyrn{56Hqvr5}rtlr}ynprlpnyyonpx5/<;</9s?{p?v|{51z6?r??{-pu5|_q51zh=j6:>@6H?91nt?h>j66HLKJM}pmqzso|67Irws6~?sum?s~zoqsmqozzpoqy60=<=0:t?|q?w}|62{7??s???|.qv?6}`r62{i>k7;?A;?7I?:2o?u?i?k77IMLKN~qnr{tp}78Jsxt7?tvn?t{prtnrp{{qprz71>=>1;u?}r?x~}73|8??t???}/rw?7~as73|j?l8<@D8J?;3p?v?j@l88JNMLOros|uq~89Ktyu8??uwo?u?|qsuosq||rqs{82?>?2<v?~s?y~84}9??u???~0sx?8bt84}k@m9=AF9K?<4q?w?kAm99KONMP?spt}vr9:Luzv9??vxp?v?}rtvptr}}srt|93@?@3=w?t?z?95~:??v???1ty?9?cu95~lAn:>BH:L?=5r?x?lBn::LPO
...

```

Similar to the Haskell solution, copying and pasting this breaks, so I generated this using this Perl script.

Verification for shifted 1, 16, 32 and 255 times.

## Explanation

Using PHP's `<?` delimiter made this fairly easy, but I had to avoid any strings that could end up as `<?` elsewhere in the code, this basically means `03`, `14`, `25`, `36`, `47`, `58` and `69`. Working around those was fairly easy using arithmetic. It might well be possible to reduce the byte count in the original program too.
> 5 votes

# Answer
# Crane-Flak, Score 3 (252 bytes)

```
%&'()%&%X'Z&xx\()'()z%xz|%&'()%&'()%&'()9;=&'()9;=%XZ\&'z|%&'(9;=(9;=%&'XZ\(|xz|9;=%&'%&(%X'Z&\('()xxz%xz|9;=&'()9;=%XZ\&'z|9;=(9;=%&'XZ\(|9;=)))))))%&Y[]'()yy{}%&y{}%&'()%&'():<>'():<>%&Y[]'(){}y{}:<>%&Y[]'()yy{}::<><>:<>%&y{}:<>'():<>%&Y[]'(){}::<><>

```

Try it online!

*(Doesn't quite work in Brain-Hack because only Crane-Flak mods by 256)*

**Shifted by 1**

```
&'()*&'&Y(['yy])*()*{&y{}&'()*&'()*&'()*:<>'()*:<>&Y[]'({}&'():<>):<>&'(Y[])}y{}:<>&'(&')&Y(['])()*yy{&y{}:<>'()*:<>&Y[]'({}:<>):<>&'(Y[])}:<>*******&'Z\^()*zz|~&'z|~&'()*&'()*;=?()*;=?&'Z\^()*|~z|~;=?&'Z\^()*zz|~;;=?=?;=?&'z|~;=?()*;=?&'Z\^()*|~;;=?=?

```

Try it online!

**Shifted by 2**

```
'()*+'('Z)\(zz^*+)*+|'z|~'()*+'()*+'()*+;=?()*+;=?'Z\^()|~'()*;=?*;=?'()Z\^*~z|~;=?'()'(*'Z)\(^*)*+zz|'z|~;=?()*+;=?'Z\^()|~;=?*;=?'()Z\^*~;=?+++++++'([]_)*+{{}'({}'()*+'()*+<>@)*+<>@'([]_)*+}{}<>@'([]_)*+{{}<<>@>@<>@'({}<>@)*+<>@'([]_)*+}<<>@>@

```

Try it online!

**Shifted by 3**

```
()*+,()([*]){{_+,*+,}({}()*+,()*+,()*+,<>@)*+,<>@([]_)*}()*+<>@+<>@()*[]_+{}<>@()*()+([*])_+*+,{{}({}<>@)*+,<>@([]_)*}<>@+<>@()*[]_+<>@,,,,,,,()\^`*+,||~€()|~€()*+,()*+,=?A*+,=?A()\^`*+,~€|~€=?A()\^`*+,||~€==?A?A=?A()|~€=?A*+,=?A()\^`*+,~€==?A?A

```

Try it online!

## Explanation

The main code at work here is

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

```

where `n` is an arbitrary number. This moves everything to the offstack adding `n` to each item (modulo 256 is implicit upon output), and then moves them all back.

However for the first program (i.e. shifted by 0) we don't need to do any of this because shifting by zero is the cat program. So we start with this code:

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

```

and shift it down by 1

```
'Z\(zz|'z|m;=(;='Z\(|z|;='Z\(zz|'z|;=(;='Z\(|;=

```

This is unbalanced so we have to fix it. There are a number of ways we could do this by my choice method (for reasons that will become apparent) is the following:

```
'Z\(zz|'z|m;=(;='Z\(|z|;='Z\(zz|'z|;=(;='Z\(|;=)))))){}{}{}{}{}

```

Shifting this up by 2 we get

```
)\^*||~)|~o=?*=?)\^*~|~=?)\^*||~)|~=?*=?)\^*~=?++++++}}}}}

```

Since `()` is easier to deal with than `{}` we will use the `}`s to complete the program we desire. That means that the `)` can be balanced with pretty obvious means. With some fiddling we can turn that into:

```
()\^*||~()|~()*=?*=?()\^*~|~=?()\^*||~()|~=?*=?()\^*~=?+++++++([]_)*+{{}({}()*+()*+<>@)*+<>@([]_)*+}{}<>@([]_)*+{{}<<>@>@<>@({}<>@)*+<>@([]_)*+}<<>@>@

```

Shifting that back down we get

```
&'Z\(zz|&'z|&'(;=(;=&'Z\(|z|;=&'Z\(zz|&'z|;=(;=&'Z\(|;=)))))))&Y[]'()yy{}&y{}&'()&'():<>'():<>&Y[]'(){}y{}:<>&Y[]'()yy{}::<><>:<>&y{}:<>'():<>&Y[]'(){}::<><>

```

The step up to 3 is so complex I don't really understand it any more. I used the same technique and just fiddled around with it until I finally got all 4 of them to work at once. The technique is pretty much the same there is just a lot more fiddling.
> 4 votes

# Answer
# Python 3, Score 1, 76 bytes

Shift 0: no change

```
""!="";print(input());exit()#   oqhms'&&-inhm'bgq'nqc'i(*0(enq'i(hm'hmots'((((

```

Shift 1:

```
##">##<qsjou)joqvu)**<fyju)*$
print(''.join(chr(ord(j)+1)for(j)in(input())))

```

Started work on shift 2, but "" becomes $$ and you can't start a line with that.

When you save it to a file, make sure it doesn't end with a newline. (vim -b file.py + set noeol)
> 3 votes

# Answer
# Jelly, score ~~1~~ 2

## ~~8~~ 15 bytes

**Shift 0:**

```
M««Ṃ¬ịị¶Ɓ|L(0Ḷṇ

```

Try it online!

**Shift 2:**

```
O‘‘Ọµḷḷ¹Ɗ~N*2Ṇṛ

```

Try 2 online!

**Shift 3:**

```
P’’Ṛ½ṃṃ²Ƒ¶O+3Ọṣ

```

Try 3 online!
> 2 votes

---
Tags: string, code-challenge, source-layout
---


title: Print custom alphabet

text:
# Question
Title: Print custom alphabet
## The Challenge

Display the alphabet from a given letter read from console input. If the letter is uppercase, you have to display the alphabet uppercased. The alphabet printed must end in the precedent letter of the one inserted. If an additiontal parameter is added to the input (a simple dot `.`) the alphabet should be printed one letter in each line. Otherwise, the alphabet should be printed in the same line, separed by a simple space. If wrong input is send to the program it will not print anything.

Inputs examples:

Input:

```
c

```

Program's ouput:

```
d e f g h i j k l m n o p q r s t u v w x y z a b

```

Input

```
H.

```

Program's ouput:

```
I
J
K
L
M
N
O
P
Q
R
S
T
U
V
W
X
Y
Z
A
B
C
D
E
F
G

```

# Answer
> 12 votes
## GolfScript ~~48 75 73 70 67 66 63 57~~ 53

```
(91,65>.+.{32+}%+.@?>(;25<''+.,1>*\['''.']?[' 'n 0]=*

```

Online demos:

### Update:

Now the last rule is also implemented. Thanks to Ventero for pointing out the issue.

### Update:

I rewrote the code from scratch and found new ways to shorten it even further.

### History of modifications:

```
.,3<\(:x;:§['''.']?)and{91,65>.+.{32+}%+.x?).{>25<''+{§n' 'if}%}{;;}if}''if
.,3<\(:x;:§['''.']?)*{91,65>.+.{32+}%+.x?).{>25<''+{§n' 'if}%}{;;}if}''if
.,3<\(:x;:§['''.']?)*{91,65>.+.{32+}%+.x?).!!@@>25<''+{§n' 'if}%*}''if
.,3<\(:x;:§['''.']?)*!!91,65>.+.{32+}%+.x?).!!@@>25<''+{§n' 'if}%**
.,3<\(:x;:§['''.']?)*91,65>.+.{32+}%+.x?).@@>25<''+{§n' 'if}%@@*!!*
.(@,3<@:§['''.']?)*91,65>.+.{32+}%+@1$?).@@>25<''+{§n' 'if}%@@*!!*
.(@,3<@:§['''.']?)*91,65>.+.{32+}%+@1$?):x>25<''+{§n' 'if}%\x*!!*
.(@,3<@:§['''.']?)*91,65>.+.{32+}%+@1$?):x>25<''+§n' 'if*\x*!!*
(\:§['''.']?)91,65>.+.{32+}%+@1$?):x>25<''+§n' 'if*\x*!!*
(91,65>.+.{32+}%+.@?>(;25<''+.,1>*\['''.']?[' 'n 0]=*

```

# Answer
> 10 votes
## C, 135 129  128 chars

Damn, so many different magic numbers, but no way to get rid of them.

Has to be run with the input as program parameter. Now follows the "wrong input" requirement.

```
c;main(a,b)char**b;{if(a==2&&isalpha(**++b)&&!(c=1[*b])||c==46&&!2[*b])for(;++a<28;)printf("%c%c",**b-=**b+6&31?-1:25,c?10:32);}

```

Explanation:

```
c;                   // Variable that will be used later
main(a,b)char**b;{   // There's one parameter => a = 2, b[1] = the parameter
                     // Wrong input checks: We want...
  if(
     a==2 &&         // 1 parameter and ...
     isalpha(**++b)  // lower- or uppercase letter as parameter,
                     // increase b so we can access it better
     &&              // and ...
     !(c=1[*b]) ||   //   either no further character,
                     //     save the character in c, or...
     (c==46&&!2[*b]) //   a dot as next character and no further characters
    )                // if check succeeded, execute the for loop, else do nothing
  for(;++a<28;)      // This will loop 26 times (2..27)
    printf("%c%c",   // Print two characters
                     // First character to print:
      **b            // We'll print the first character of the parameter,
       -=            // but decrement it before printing
       **b+6&31?     // if the last five bits (31 = 11111b) are not 26 (6 == -26 mod 32)
        -1           //   decrement it by -1 (aka increment it)
        :25,         //   else (char=z/Z) decrement by 25, so we start over at a/A
                     // Second character to print:
      c?             // c is either ASCII 0 or a dot (ASCII 46)
       10            //   dot     -> print a newline
       :32);         //   ASCII 0 -> print a space (ASCII 32)
}

```

The `**b+6&31` part uses the fact that the ASCII codes for lowercase/uppercase character are the same if only looking at the last 5 bits and the remaining 5 bits are in range 1..26.

Version without "wrong input" requirement (82 chars):

```
main(a,b)char**b;{for(b++;++a<28;)printf("%c%c",**b-=**b+6&31?-1:25,1[*b]?10:32);}

```

# Answer
> 7 votes
### Ruby, 72 71 61 characters

```
gets;25.times{$><<$_=$_.succ[0]+=$1?$/:' '}if~/^[a-z](\.)?$/i

```

This ruby version uses a regular expression to verify the input. Fortunately, the Ruby string method `succ` does most of the work for us (including the wrap-around).

*Edit:* 61 characters with the help of chron and Ventero.

# Answer
> 6 votes
# Ruby: ~~127~~ ~~113~~ 92 (?) characters

(I can't find the rule about the penalty score on using `-p`. Added 1 for now. If wrong, please correct me.)

```
$_=if ~/^([a-z])(\.)?$/i;s,e=$1>?Z?[?a,?z]:[?A,?Z];[*$1.succ..e,*s...$1]*($2==?.?$/:" ")end

```

Sample run:

```
bash-4.2$ ruby -pe '$_=if ~/^([a-z])(\.)?$/i;s,e=$1>?Z?[?a,?z]:[?A,?Z];[*$1.succ..e,*s...$1]*($2==?.?$/:" ")end' <<< c
d e f g h i j k l m n o p q r s t u v w x y z a b

bash-4.2$ ruby -pe '$_=if ~/^([a-z])(\.)?$/i;s,e=$1>?Z?[?a,?z]:[?A,?Z];[*$1.succ..e,*s...$1]*($2==?.?$/:" ")end' <<< H.
I
J
K
L
M
N
O
P
Q
R
S
T
U
V
W
X
Y
Z
A
B
C
D
E
F
G

bash-4.2$ ruby -pe '$_=if ~/^([a-z])(\.)?$/i;s,e=$1>?Z?[?a,?z]:[?A,?Z];[*$1.succ..e,*s...$1]*($2==?.?$/:" ")end' <<< seven

```

# Answer
> 6 votes
# Ruby, ~~101~~ 95

```
i,d=gets.split''
[*?a..?z].join[/#{i}/i]
($'+$`).chars{|c|$><<(i>?Z?c:c.upcase)+(d==?.?$/:' ')}

```

Try it online

# Answer
> 6 votes
## Perl, 131 127 117 112 106 104 102 98 96 92 91 90 93 71 66 65 64 58 characters

```
s!^([a-z])(\.?)$!print chop,$2?$/:$"for($1..az)[1..25]!ie

```

Usage:

```
perl -ne 's!^([a-z])(\.?)$!print chop,$2?$/:$"for($1..az)[1..25]!ie'

```

One character has been added to the count for the `n` option.

Largest cut was only possible because of seeing the behaviour of `++` on characters in Jon Purdy's answer.

# Answer
> 6 votes
### GolfScript, 80 72 Characters

```
.).46={;)}*25,{65+.32+}%?)\""=*!!\([{)..31&26-!26*-}25*;]n+\"."=n" "if**

```

Lots of the code is testing for valid input and the "print nothing"-option. The actual logic is 37 characters only.

Test cases online

# Answer
> 6 votes
## q/k4 66 64 63 60 58 56 + 2 penalty

penalty for global variable init, algorithm is 56 as below:

**56:**

```
if[&/x in".",l:(a;A)90>*x;1@/1_,/|_[0,l?x;l,'"  \n"@#x]]

```

**58:**

```
if[&/x in".",l:(a;A)90>*x;1@/(1_,/|_[0,l?x;l]),'"  \n"@#x]

```
* change from if-else to if allowed to reorganize code and get rid of ";" at the end

**60:**

```
1@/$[&/x in".",l:(a;A)90>*x;1_,/|_[0,l?x;l];" "],'"  \n"@#x;

```
* eventually got rid of this redundant check

**63:**

```
1@/$[&/x in".",l:(a;A)90>*x;1_,/|_[0,l?x;l];" "],'" \n""."in x;

```
* print chars recursively instead a whole object
* still can't get off identity comparsion *x in "."* in two places... :(
* semicolon at the end is required, otherwise print function (1@) would print it's return value to stdout.... damn

**64:**

```
2@,/$[&/x in".",l:(a;A)90>*x;1_,/|_[0,l?x;l];" "],'" \n""."in x;

```

**EDIT:**

Added penalty of 2 for global initialization(x:), same if wrapping function into brackets (as slackware suggested)
not sure if changing namespace should be punished as well...then it's another 3

```
(.Q`a`A) instead of (a;A)

```

Example:

```
q)\         - switch interpreter to k4
 \d .Q     - change to native namespace
  x:"c"
  if[&/x in".",l:(a;A)90>*x;1@/1_,/|_[0,l?x;l,'"  \n"@#x]]
d e f g h i j k l m n o p q r s t u v w x y z a b

  x:"@"
  if[&/x in".",l:(a;A)90>*x;1@/1_,/|_[0,l?x;l,'"  \n"@#x]]
  x:"H."
  if[&/x in".",l:(a;A)90>*x;1@/1_,/|_[0,l?x;l,'"  \n"@#x]]
I
J
K
L
M
N
O
P
Q
R
S
T
U
V
W
X
Y
Z
A
B
C
D
E
F
G
  x:...

```

# Answer
> 5 votes
## Perl, 149, 167

### Update

* Added sanity check.
* Took ardnew suggestion about the separator application.

```
exit if $ARGV[0] !~ /[a-z]\.?/i;    # sanity check input
($x,$d)=split //,$ARGV[0];          # split input arguments
@l=65..90;                          # define uc letter range
push @l,splice @l,0,ord(uc $x)-64;  # rotate letter range
pop @l;                             # remove the argument letter
print join $d?$/:$",                # print the joined list
  map {ord($x)>90?lc chr:chr} @l;   # map chr and lc as appropriate

```

# Answer
> 4 votes
## Python, 83

```
r=raw_input()
i=ord(r[0])
exec"i+=1-26*(i%%32>25);print chr(i)%s;"%","["."in r:]*26

```

# Answer
> 4 votes
# Mathematica 158 159 204 199 183 167 165 162

**Code**

```
f@h_ := Most@RotateLeft[#, Position[#, h][[1, 1]]] &[FromCharacterCode /@
        (65~Range~90 + 32 Boole@LowerCaseQ@h)];
g = Characters@# /. {{p_} :> Row[f@p, " "], {p_, "."} :> Column@f@p, _ -> ""} &

```

**Usage**

```
g["c"]
g["H"]
g["H."]
g["seven"]

```

# Answer
> 4 votes
## PHP, ~~120~~ ~~119~~ 113

```
<?$v=fgets(STDIN);$f=$c=$v[0];ctype_alpha($c++)||die;for(;$c[0]!=$f;$c=$c[0],$c++)echo$c[0],$v[1]=='.'?"\n":" ";

```

# Answer
> 3 votes
# J 43

```
|:1j1#(25{.(u:,2#65 97+/i.26)(>:@i.}.[)])"0

```

## Examples:

```
|:1j1#(25{.(u:,2#65 97+/i.26)(>:@i.}.[)])"0 's'

```

t u v w x y z a b c d e f g h i j k l m n o p q r

```
|:1j1#(25{.(u:,2#65 97+/i.26)(>:@i.}.[)])"0 's.'

```

t
u
v
w
x
y
z
a
b
c
d
e
f
g
h
i
j
k
l
m
n
o
p
q
r

```
|:1j1#(25{.(u:,2#65 97+/i.26)(>:@i.}.[)])"0 '['

```

This solution evolved on the J programming forum: http://jsoftware.com/pipermail/programming/2012-August/029072.html

Authors: AlvordBossCerovskiCyrEllerHuiLambertMcCormickMillerQuintanaSchottSherlockTaylorTherriault

## Explanation

J phrases are executed starting on the right, passing the on-going result to the left as it gets evaluated. Since it's interactive, we can look at pieces of the solution in isolation to better understand them.

The middle part generates the upper and lower case alphabet in Unicode:

```
   u:,2#65 97+/i.26
ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz

```

The " u: " verb converts its numeric right argument to Unicode characters. The numeric argument is generated from the ASCII values for the upper- and lower-case characters by adding the numbers for "A" and "a" each to the values from 0 to 25 generated by "i.26":

```
   65 97+/i.26
65 66 67  68  69  70  71  72  73  74  75  76  77  78  79  80  81  82  83  84  85  86  87  88  89  90
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122

```

The right-hand portion,

```
   ((>:@i.}.[)])"0

```

looks up ( i. ) the position of the right argument ( \] ) in the left ( \[ ) - which is the vector of letters above - and drops ( }. ) one more ( \>: ) than that number. The ' "0 ' applies this phrase to 0-dimensional (scalar) arguments.

```
   ('123H999' (>:@i.}.[)])"0 'H'
999

```

The " 25 {. " phrase takes the first 25 elements of the vector on the right.

The penultimate phrase " 1j1 # " on the left replicates its right argument according the number on the left. A simple number does a simple replication:

```
   2 # 'ABCD'
AABBCCDD

```

However, a complex number - indicated by the " j " between the real and imaginary portions - inserts a fill element according to the imaginary part. Here we indicate one fill element by the one to the right of the " j ".

```
   2j1 # 'ABCD'
AA BB CC DD

```

As with most J primitives, the replicate verb ( # ) works on numeric arrays in an analagous fashion to how it works on character arrays. As shown here,

```
   1j1 # 1 2 3
1 0 2 0 3 0

```

we see that the default numeric fill element is zero whereas for characters it is the space character.

Finally, the leftmost token " |: " transposes the result of the preceding verbs to its right.

Explanation provided by Devon McCormick. Thank you Devon.

# Answer
> 3 votes
# brainfuck, 303

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

```

Currently it doesn't support the `If wrong input is send to the program it will not print anything` part, and it can probably be shorter. I plan on fixing it later. Right now my brain is too \****ed to continue.

# Answer
> 2 votes
## C, 110

Sometimes prints "spaces" between letters, sometimes not.

```
i,j;main(int c,char*l){gets(l);l[1]&=10;j=*l%32;c=*l&~31;for(i=j;i<j+25;i++){l[0]=c+i%26+1;printf("%2s",l);}}

```

Slighly more readable:

```
i,j;
main(int c,char*l)
{
  gets(l);
  l[1]&=10;          // makes . to line feed and some other chars to "start of text"
                     // which looks like space in some cases
                     // (the byte can become either 0, 2, 8 or 10)

  j=*l%32;           // 0b 000c cccc, these five bits code which letter was chosen
  c=*l&~31;          // 0b ccc0 0000, these three bits code upper/lowercase

                     // 0b ccc0 0000 + (0b 000c cccc + [0..24])%26 + 1
  for(i=j;i<j+25;i++){l[0]=c+i%26+1;printf("%2s",l);}
}

```

Runs:

```
$ ./a.out
G
 H I J K L M N O P Q R S T U V W X Y Z A B C D E F

$ ./a.out
p.
q
r
s
t
u
v
w
x
y
z
a
b
c
d
e
f
g
h
i
j
k
l
m
n
o

```

# Answer
> 2 votes
## VBA 225

Formatted to run from the immediate window:

```
s=InputBox(""):n=Asc(Left(s,1)):l=Len(s):p=IIf(l<3,IIf(l=2,IIf(Right(s,1)=".",vbCr,"")," "),""):c=IIf(n>64 And n<91,65,IIf(n>96 And n<123,97,99)):o=n-c+1:If o>0 And p<>"" Then For i=o To o+24:x=x & Chr(i Mod 26+c) & p:Next:?x

```

Broken down into individual lines (needs to be surrounded by `Sub` block and needs a different `print` method to work in a module, thus making the code longer):

```
s=InputBox("")
n=Asc(Left(s,1))
l=Len(s)
p=IIf(l<3,IIf(l=2,IIf(Right(s,1)=".",vbCr,"")," "),"")
c=IIf(n>64 And n<91,65,IIf(n>96 And n<123,97,99))
o=n-c+1
If o>0 And p<>"" Then
For i=o To o+24
x=x & Chr(i Mod 26+c) & p
Next
End If 'Not needed when completed in single line format
MsgBox x

```

# Answer
> 2 votes
# Perl, ~~77~~ ~~76~~ ~~70~~ 68

```
chomp(($a,$b)=split//,<>);$"=$/if$b;map{++$a=~/(.)$/}1..25;print"@a"

```

Edits:

1. Saved a character using regex instead of `substr`.
2. Saved 6 characters using `map` instead of `for`.
3. Saved 2 characters by omitting final newline.

# Answer
> 2 votes
# JavaScript, 137

Unfortunately a bit verbose (`String.fromCharCode` and `charCodeAt`).

```
for(x=b=(n=prompt(m={122:97,90:65})).charCodeAt(r='');/^[a-z]\.?$/i.test(n)&&(x=m[x]||x+1)!=b;)r+=String.fromCharCode(x)+(n[1]?"\n":" ");

```

# Answer
> 2 votes
## R, 219

Ugly, long... still works.

```
f=function(l){if(!nchar(l)%in%c(1,2))invisible()else{s=ifelse(nchar(l)==1," ","\n");l=substr(l,1,1);v=letters;if(l%in%v){}else v=LETTERS;l=grep(l,v);if(l==26)cat(v[1:25],sep=s)else cat(c(v[l+1:(26-l)],v[1:l-1]),sep=s)}}

```

Usage:

```
f("a")
f("c.")
f("H")
f("z")
f("Z.")
f("seven")

```

# Answer
> 2 votes
## C, 146 chars *(terrible)*

```
main(){char b[100];gets(b);for(char a=b[0],c=a,d=a&223,e=b[1];++c!=a&64<d&d<91&(!e|e==46&!b[2]);(c&31)>26?(c&=96):(putchar(c),putchar(e?10:32)));}

```

I'm not very experienced in C, which probably shows... \>.\< I had a feeling that chars being integers would be helpful, but it didn't actually seem to make as big of an impact as I hoped... I'll leave my attempt here though, feel free to suggest improvements.

Unminified version:

```
main() {
  char b[999]; // assume that the line will fit in 999 chars...
  gets(b);

  // a is the char we start on, c is the char that we iterate,
  // d is toUppercase(a), e is just an alias for the second char.
  for (char a = b[0], c = a, d = a&223, e=b[1];
      // increment c, make sure that we haven't reached a yet.
      // also check the other conditions (first char is letter, second char
      // is either '.' or NULL, third char is NULL if second char was '.').
      ++c != a & 64 < d & d < 91 & (!e | e == 46 & !b[2]);
      (c&31) > 26     // check if we need to wrap around
        ? (c &= 96)   // if so, wrap
        : (putchar(c), putchar(e?10:32))  // otherwise, print char & separator
  );
}

```

# Answer
> 2 votes
# Java 8, 127 bytes

```
a->{String r="",d=a.length>1?"\n":" ";char c=a[0],C=c;for(;++c<(c<97?91:123);r+=c+d);for(c=C<97?64:'`';++c<C;r+=c+d);return r;}

```

**Explanation:**

Try it online.

```
a->{                        // Method with character-array parameter and String return-type
  String r="",              //  Result-String, starting empty
         d=a.length>1?      //  If the length of the input is larger than 1
            "\n"            //   Set the delimiter to a new-line
           :                //  Else:
            " ";            //   Set the delimiter to a space
  char c=a[0],              //  Get the input letter
       C=c;                 //  And create a copy of it
  for(;++c<(c<97?91:123);   //  Loop from this letter + 1 to (and including) 'Z'/'z'
    r+=c+d);                //   And append the result with a letter + the delimiter
  for(c=C<97?64:'`';++c<C;  //  Loop again from 'A'/'a' to (and excluding) the input-letter
    r+=c+d);                //   And append the result with a letter + the delimiter
  return r;}                //  Return the result

```

# Answer
> 1 votes
## **Mumps, 91, 86, 82,79,76**

```
r t i t?1A.1"." s a=$A(t),p=a>90*32+65 f i=1:1:25 w *(a+i-p#26+p) w:t["." !

```

Not such a modern language ;) I'm sure there's a bit of optimization space left..

Explanation:

```
r t

```

read input

```
i t?1A.1"."

```

check if t matches the required input

```
s a=$A(t),p=a>90*32+65 f i=1:1:25 { w *(a+i-p#26+p) w:t["." !}

```

basic for loop through the alphabet. Note that mumps is strictly evaluating left to right. True=1, so you get 65 or 97 as a result for p, # is the modulo operator

tests:

```
USER>d ^golf
d.e
f
g
h
i
j
k
l
m
n
o
p
q
r
s
t
u
v
w
x
y
z
a
b
c

USER>d ^golf
tuvwxyzabcdefghijklmnopqrs
USER>d ^golf
h.i
j
k
l
m
n
o
p
q
r
s
t
u
v
w
x
y
z
a
b
c
d
e
f
g

USER>d ^golf
hallo
USER>

```

(you'll need a mumps runtime env, ie Caché to run this this)

edit: bold heading

edit: had a wrong solution, fixed now. Thanks to rtfs and Averroees for pointing this out

# Answer
> 1 votes
**JavaScript: 141**

```
c="",b=c[0].charCodeAt()<91,a="abcdefghijklmnopqrstuvwxyz",b&&(a=a.toUpperCase()),a=a.split(c[0]),a=a[1]+a[0],a=c[1]?a.split("").join("\n"):a

```

Commented version:

```
c="", //write input here (examples "a", "B", "c.", "D.")
b=c[0].charCodeAt()<91, //true for upperC, false for lowerC
a="abcdefghijklmnopqrstuvwxyz", //the abc
b&&(a=a.toUpperCase()), //if upper, turn main string to upperC
a=a.split(c[0]), //split by the first char of input
a=a[1]+a[0], //swap the two parts
a=c[1]?a.split("").join("\n"):a //if input second char, add breaklines in between
//the output is inside 'a'

```

jsFiddle DEMO

# Answer
> 0 votes
Here is my first attempt at it with APL.

```
⍞{1 1≡(2⌈⍴⍺)⍴⍺∊'.',⍵:⊃(~=/2⍴⍺)⌷(,X,' ')(X←25 1⍴1↓(X⍳⊃⍺)⌽X←(⎕A∊⍨⊃⍺)⌷2 26⍴⍵)}6↓26⌽⎕UCS 65+⍳58

```

if I can use a single global variable `A←2 26⍴6↓26⌽⎕UCS 65+⍳58` then I can shorten the above down to the following:

```
{1 1≡(2⌈⍴⍵)⍴⍵∊'.',,A:⊃(~=/2⍴⍵)⌷(,X,' ')(X←25 1⍴1↓(X⍳⊃⍵)⌽X←(⎕A∊⍨⊃⍵)⌷A)}⍞

```

# Answer
> 0 votes
C++11

```
#include <iostream>
#include <vector>
#include <cstdio>

int main(int argc, const char * argv[])
{
    std::vector<char> list1,list2;
    for( char c = 'a'; c <='z'; c++ )
    {
        list1.push_back( c );
        list2.push_back( toupper( c ) );
    }
    char c = getchar();
    auto f = [ c ]( std::vector<char> list )
    {
        auto i = std::find( list.begin(), list.end(), c );
        if( i == list.end() )
            return;
        auto c = i;
        for( ;; )
        {
            c++;
            if( c == list.end() ) c = list.begin();
            if( c == i )break;
            std::cout<<*c<<"\n";
        }
    };
    f( list1 );f(list2);
    return 0;
}

```

# Answer
> 0 votes
## Perl, 226 characters

```
die "Invalid input " if $ARGV[0] !~ /[a-z]\.?/i;
@listA=(a...z);
$index=ord(lc(substr($ARGV[0],0,1)))-97;
print join(substr($ARGV[0],1) ? "\n" : " ",map{$ARGV[0] =~ /[A-Z]/?uc $_:$_}(@listA[$index+1...25],@listA[0...$index]));

```

# Answer
> 0 votes
C (111)

```
main(int i, char**c){if(isalpha(*c[1]))for(i=0;i<25;i++) printf("%c",isalpha((*c[1])+1)?++*c[1]:(*c[1]-=25));}

```

---

## dissection

```
if(isalpha(*c[1])) // start with char-check.

for(i=0;i<25;i++) // we need 25 values, excluding input char. reusing i.

printf("%c", // print char. ofcourse.

isalpha((*c[1])+1) ? ++*c[1] : (*c[1]-=25));
//check if we are past z/Z and fall back to a/A.
//make that available to print.

```

---

Works\]$ ./test 5

Works\]$ ./test W XYZABCDEFGHIJKLMNOPQRSTUV

Works\]$ ./test M NOPQRSTUVWXYZABCDEFGHIJKL

Works\]$ ./test g hijklmnopqrstuvwxyzabcdef

Works\]$ ./test \[

Works\]$ ./test a bcdefghijklmnopqrstuvwxyz

Works\]$ ./test Z ABCDEFGHIJKLMNOPQRSTUVWXY

---

Thank you for some food for thought.

# Answer
> 0 votes
**C# 170**

```
using System.Linq;namespace N{class P{static void Main(string[]a){foreach(char e in"abcdefghijklmnopqrstuvwxyz".ToCharArray().Where(o =>o>'c'))System.Console.Write(e);}}}

```

Uncompressed

```
using System.Linq;
namespace N {
    class P {
        static void Main(string[]a){
            foreach (char e in "abcdefghijklmnopqrstuvwxyz".ToCharArray().Where(o => o > 'c'))
                System.Console.Write(e);
        }
    }
}

```

# Answer
> 0 votes
# C, 117

```
main(c,s,d){d=c=getchar(),s=getchar();for(s=s<0?32:s^46?0:10;d+=d+6&31?1:-25,s&&isalpha(c)&&d^c;printf("%c%c",d,s));}

```

Credit to schnaader for the d+6&31 trick.

http://ideone.com/ts1Gs9

# Answer
> 0 votes
# Bash: 110 bytes

```
(([[ $1 =~ [a-z] ]]&&echo {a..z})||([[ $1 =~ [A-Z] ]]&&echo {A..Z}))|([ "${1:1:1}" = . ]&&sed 's/ /\n/g'||cat)

```

In terms of explanation, it's pretty straightforward, no magic tricks - this is just something that bash is intrinsically well suited for. In terms of the non-obvious bits:

* `{a..z}` is a very underused trick in bash - it expands to `a b c d...`. You can do the same to generate numerical sequences.
* Bash can do regex matching, `[[ $1 =~ [a-z] ]]` runs a regex match against the first program argument for characters from a to z. Likewise for A-Z. You need double square brackets for it though, `[` can't do it.
* `${1:1:1}` gets a substring of $1 (the first argument), one character in, one character long - that is, it returns the second character of the string, what we expect to be `.`.
* `sed 's/ /\n/g'` simple regex: searches and replaces spaces with newlines. If `.` is the second character of the string, we pipe input to this, or otherwise...
* `cat` is the final trick here - if we don't want to replace spaces with newlines, we feed stdin to cat instead which simply outputs it again.

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


title: Sort by shuffling blocks

text:
# Question
Title: Sort by shuffling blocks
## Block shuffle sort

The *block shuffle sort* is a (rather artificial) method of sorting a list. It works as follows, illustrated by an example.

```
[6, 1, 0, 3, 2, 4, -2, -1]
                            Break list into contiguous blocks
[6][1, 0][3, 2, 4][-2, -1]
                            Sort each block
[6][0, 1][2, 3, 4][-2, -1]
                            Sort blocks lexicographically
[-2, -1][0, 1][2, 3, 4][6]
                            Concatenate
[-2, -1, 0, 1, 2, 3, 4, 6]

```

The partition into contiguous blocks can be chosen arbitrarily. However, not all choices of blocks will yield a sorted list at the end:

```
[6, 1, 0, 3, 2, 4, -2, -1]
[6, 1, 0][3, 2, 4][-2, -1]
[0, 1, 6][2, 3, 4][-2, -1]
[-2, -1][0, 1, 6][2, 3, 4]
[-2, -1, 0, 1, 6, 2, 3, 4]

```

If all blocks have length 1, or if there is only one block, then the result will of course be sorted. But these are rather extreme cases. In this challenge, your task is to find a balance between the number of blocks and the maximum length of a block.

## The task

Your input is a nonempty list of integers **L**, taken in any reasonable format. Your output shall be the smallest integer **N** such that **L** can be block shuffle sorted so that the number of blocks and the length of each block are at most **N**.

The lowest byte count in each language wins. Standard rules apply.

## Test cases

```
[5] -> 1
[1,2] -> 2
[0,2,1,-1] -> 3
[-1,0,2,1] -> 2
[9,3,8,2,7] -> 4
[9,2,8,3,7] -> 3
[5,9,3,7,2,4,8] -> 7
[-1,-2,1,2,-1,-2,7] -> 4
[6,1,0,3,2,4,-2,-1] -> 4
[12,5,6,-6,-1,0,2,3] -> 3
[1,0,1,0,1,0,1,0,1,0] -> 6
[1,2,1,3,1,2,3,2,4,3] -> 5
[7,7,7,7,8,9,7,7,7,7] -> 4

```

# Answer
> 5 votes
## Brachylog, ~~23~~ ~~22~~ ~~20~~ 19 bytes

*Thanks to Zgarb, H.PWiz and Fatalize for saving some amount of bytes.*

```
~cᶠ{oᵐoc≤₁&≡ᵃlᵐ⌉}ˢ⌋

```

Try it online!

I'm sure there's more to golf here...

### Explanation

```
~cᶠ      Find all lists that concatenate into the input, i.e. all partitions
         of the input.
{        Discard all partitions for which this predicate fails, and replace
         the rest with the output of this predicate.
  oᵐ       Sort each sublist of the partition.
  o        Sort the entire list.
  c≤₁      And require concatenation of the result to be sorted.
  &        Then:
  ≡ᵃ       Append the partition to itself.
  lᵐ       Map "length" over this list, i.e. we get the length of each block, as
           well as the length of the partition itself.
  ⌉        Take the maximum.
}ˢ
⌋        Take the minimum of all those maxima.

```

# Answer
> 3 votes
# Jelly, 17 bytes

```
Ṣ€ṢF
ŒṖÇÐṂ+Z$€L€Ṃ

```

Try it online!

### Alternate version, 15 bytes, postdates challenge

In the latest version, `Ɗ` combines three links into a monadic chain. This allows the following golf.

```
ŒṖṢ€ṢFƊÐṂ+ZLƊ€Ṃ

```

Try it online!

### How it works

```
Ṣ€ṢF          Helper link. Argument: P (partitioned array)

Ṣ€            Sort each chunk.
  Ṣ           Sort the sorted chunks.
   F          Flatten.

ŒṖÇÐṂ+Z$€L€Ṃ  Main link. Argument: A (array)

ŒṖ            Generate all partitions of A.
  ÇÐṂ         Keep those for which the helper link returns the minimal array, i.e.,
              those that return sorted(A).
     +Z$€     Add each partition to its transpose.
              Due to how Jelly vectorizes, the length of the sum is the maximum of
              the length of the operands, and the length of the transpose is the
              length of the array's largest column.
         L€   Take the length of each sum.
           Ṃ  Take the minimum.

```

# Answer
> 2 votes
# Stax, ~~28~~ ~~26~~ ~~25~~ ~~24~~ 23 bytesCP437

```
é%(>ù│ê²☻û◙T╠►╜◘íaæAtI╥

```

Run and debug online!

*Credits to @recursive for saving 3 bytes.*

Stax is a bit verbose here. It takes two bytes to sort an array by default, two bytes to get the maximum/minimum of an array and two bytes to flatten an array. Anyway I am still posting the solution  ~~and hope there can be helpful suggestions on how to improve it~~  there is.

## Explanation

Uses the unpacked version to explain.

```
%cFxs|!F{{omo:f:^!C_Mch\%|m
%cFxs|!F                        Do for all partitions, grouped by number of sub-arrays
                                    Grouping by number of sub-arrays in this problem does not help but it's the default
        {{om{o                  Sort inside block then sort blocks lexicographically
              :f:^              The result when flattened is sorted
                  !C            Skip the rest of the loop if the last line is false
                    _|<         Take the current partition, pad to the longest

                       h        Take the first element, whose length is now the maximum of all sub-arrays in the original partition
                        \       Zip with the current partition, the shorter one is repeated
                         %      Number of elements
                                Which is the maximum of all sub-array sizes and the number of sub-arrays in the current partition
                          |m    Take the minimum among all choices of partitions

```

# Answer
> 2 votes
# Brachylog, 17 bytes

```
~c₎{oᵐoc≤₁&lᵐ⌉≤}ᵈ

```

Try it online!

## Explanation

This is a self-answer; I designed this challenge with Brachylog in mind and found `~c₎{…}ᵈ` an interesting construct.

The built-in `c` concatenates a list of lists. If it is given a subscript `N`, it requires the number of lists to be `N`. The symbol  modifies a built-in to take a pair as input and use its right element as the subscript. Thus `c₎` takes a pair `[L,N]`, requires that the number of lists in `L` is `N`, and returns the concatenation of `L`. When run in reverse, `~c₎` takes a list `L` and returns a pair `[P,N]`, where `P` is a partition of `L` into `N` blocks. They are enumerated in increasing order of `N`.

The metapredicate  transforms an ordinary predicate into one that checks a relation between the two elements of a pair. More explicitly, `{…}ᵈ` takes a pair `[A,B]`, checks that `A{…}B` holds, and outputs `B`. I use it to verify that `P` can be block-sorted and only contains lists of length at most `N`.

```
~c₎{oᵐoc≤₁&lᵐ⌉≤}ᵈ  Input is a list, say L = [9,2,8,3,7].
~c₎                Guess the pair [P,N]: [[[9],[2],[8,3,7]],3]
   {           }ᵈ  Verify this predicate on P and N and return N:
    oᵐ              Sort each list in P: [[9],[2],[3,7,8]]
      o             Sort lexicographically: [[2],[3,7,8],[9]]
       c            Concatenate: [2,3,7,8,9]
        ≤₁          This list is nondecreasing: true.
          &lᵐ       Length of each list in P: [1,1,3]
             ⌉      Maximum: 3
              ≤     This is at most N: true.

```

Note that `P` may contain empty lists. This ensures correctness also in those cases where the maximal length of a block is greater than the number of blocks.

# Answer
> 1 votes
# Python 2, ~~186~~ 146 bytes

```
lambda l:min(max(map(len,z+[z]))for z in p(l)if sum(s(z),[])==s(l))
p=lambda l:[q+[s(l[i:])]for i in range(len(l))for q in p(l[:i])]or[l]
s=sorted

```

Try it online!

The second function is taken from this tip by feersum.

# Answer
> 1 votes
# Ruby, 158 bytes

```
f=->l,i=[],s=l.size,m=s{k=*l;i.sum==s&&i.map{|z|k.shift(z).sort}.sort.flatten==l.sort&&[m,[i.size,*i].max].min||i.sum<s&&(1..s).map{|z|f[l,i+[z],s,m]}.min||m}

```

Try it online!

# Answer
> 1 votes
# Pyth,  ~~24 23~~  20 bytes

```
hSmeSlMs]Bd.msSSMb./

```

**Test suite.**

### How it works

```
hSmeSlMs]Bd.msSSMb./ – Full program. Hereby, Q represents the input.
                  ./ – All possible partitions of Q.
           .m        – Take the partitions which yield a minimal (i.e. sorted) list over:
             sSSMb   – Sorting function. Uses the variable b.
               SMb   – Sort each list in each partition b.
              S      – Sort the partition b.
             s       – And flatten (by 1 level).
  meSlMs]Bd          – Map. Uses a function whose variable is d.
        ]Bd          – Pair d with its wrapping in a singleton list. Returns [d, [d]].
       s             – Flatten (by 1 level). Returns [*d, d], where "*" is splatting.
     lM              – Take the length of each element.
   eS                – Retrieve the maximal length.
hS                   – Return the minimum element of the list of maximal lengths.

```

# Answer
> 0 votes
# APL (Dyalog Classic), ~~71~~ 67 bytes

```
{⌊/(⌈/≢,≢¨)¨T/⍨{S[⍋S]≡∊⍵[⍋↑⍵]}¨T←{⍵[⍋⍵]}¨¨⊂∘S¨(-≢S)↑¨2⊥⍣¯1¨⍳2*≢S←⍵}

```

`⎕IO` must be `0`

Try it online!

## How?

* `⌊/` \- **Find the minimum of ...**
* `(⌈/≢,≢¨)` \- **... the maximum of the length and number of elements ...**
* `¨` \- **... of each element of ...**
* `T/⍨` \- **... the elements that ...**
* `{S[⍋S]≡∊⍵[⍋↑⍵]}¨` \- **... are sorted when flattened, of ...**
* `T←{⍵[⍋⍵]}¨¨` \- **... the sorted elements of the elements of ...**
* `⊂∘S¨(-≢S)↑¨2⊥⍣¯1¨⍳2*≢S←⍵` \- **... the partitions of the argument (along with some junk)**

---
Tags: code-golf, array, sorting, optimization
---


title: Construct a companion matrix

text:
# Question
Title: Construct a companion matrix
You have a number of polynomials who are lonely, so make them some companions (who won’t threaten to stab)!

For a polynomial of degree `n`, there is an `n by n` companion cube matrix for it. You need to make a function that accepts a list of coefficients for a polynomial in either ascending (`a + bx +cx^2 + …`) or descending (`ax^n + bx^(n-1) + cx^(n-2)+…`) order (but not both) and output the companion matrix.

for a polynomial `c0 + c1x + c2x^2 + ... + cn-1x^(n-1) + x^n`, its companion matrix is

```
     (0, 0, 0, ..., -c0  ),
     (1, 0, 0, ..., -c1  ),
     (0, 1, 0, ..., -c2  ),
     (...................),
     (0, 0, ..., 1, -cn-1)

```

note that the coefficient for `x^n` is 1. For any other value, divide all the rest of the coefficients by `x^n`'s. Additionally, the 1's are offset from the diagonal.

If the language you’re using already contains a function or module that does this, you can’t use it – you must write your own.

For instance, if you had `4x^2 – 7x + 12`, the coefficients in ascending order are `(12, -7, 4)` and descending order `(4, -7, 12)`. The function or program should output `[(0, -3.0), (1, 1.75)]` for either order. Specify which order your code accepts. Minimum polynomial should be a quadratic. Coefficients are restricted to real numbers.

Below are examples – your output does not have to match the pretty formatting but it should output the rows (in the `()`) of the matrix in order.

Ascending order:

```
input:
    [3., 7., -5., 4., 1.]
output:
    [(0, 0, 0, -3.),
     (1, 0, 0, -7.),
     (0, 1, 0,  5.),
     (0, 0, 1, -4.)]

input:
    [-4., -7., 13.]
output:
    [(0, 0.30769231),
     (1, 0.53846154)]

input:
    [23., 1., 92., 8., -45., 88., 88.]
output:
    [(0, 0, 0, 0, 0, -0.26136364),
     (1, 0, 0, 0, 0, -0.01136364),
     (0, 1, 0, 0, 0, -1.04545455),
     (0, 0, 1, 0, 0, -0.09090909),
     (0, 0, 0, 1, 0,  0.51136364),
     (0, 0, 0, 0, 1, -1.        )]

```

Descending order:

```
input:
    [1., 4., -5., 7., 3.]
output:
    [(0, 0, 0, -3.),
     (1, 0, 0, -7.),
     (0, 1, 0,  5.),
     (0, 0, 1, -4.)]

input:
    [13., -7., -4.]
output:
    [(0, 0.30769231),
     (1, 0.53846154)]

input:
    [88., 88., -45., 8., 92.,1., 23.]
output:
    [(0, 0, 0, 0, 0, -0.26136364),
     (1, 0, 0, 0, 0, -0.01136364),
     (0, 1, 0, 0, 0, -1.04545455),
     (0, 0, 1, 0, 0, -0.09090909),
     (0, 0, 0, 1, 0,  0.51136364),
     (0, 0, 0, 0, 1, -1.        )]

```

---

Dennis wins with 20 bytes!

# Answer
> 3 votes
# CJam, ~~23~~ 20 bytes

```
{)W*f/_,,_ff=1f>\.+}

```

This is a function that pops the input (ascending order) from the stack and pushes the output in return.

Try it online in the CJam interpreter.

### How it works

```
)   e# Pop the last element from the input array.
W*  e# Multiply it by -1.
f/  e# Divide the remaining array elements by this product.
_,  e# Push a copy of the array and compute its length (L).
,_  e# Push [0 ... L-1] twice.
ff= e# For each I in [0 ... L-1]:
    e#   For each J in [0 ... L-1]:
    e#     Push (I==J).
    e# This pushes the L x L identity matrix.
1f> e# Discard the first element of each row, i.e., the first column.
\   e# Swap the result with the modified input.
.+  e# Vectorized append; append the input as a new column.

```

# Answer
> 3 votes
# CJam, ~~32~~ ~~31~~ 28 bytes

```
0q~)f/f-_,(_,\0a*1+fm<~]W%z

```

Try it online

This takes the input in ascending order, using the CJam list format. Sample input:

```
[-4.0 -7.0 13.0]

```

Explanation:

```
0     Push a 0 for later sign inversion.
q~    Get and interpret input.
)     Pop off last value.
f/    Divide all other values by it.
f-    Invert sign of values.
_,    Get count of values, which corresponds to n.
(     Decrement by 1.
_,    Create list of offsets [0 1 ... n-1] for later.
\     Swap n-1 back to top.
0a*   Create list of n-1 zeros.
1+    Append a 1. This is the second-but-last column [0 0 ... 0 1].
fm<   Apply rotation with all offsets [0 1 ... n-1] to column.
~     Unwrap the list of 0/1 columns.
]     Wrap all columns
W%    Invert their order from last-to-first to first-to last.
z     Transpose to get final matrix.
`     Convert to string for output.

```

# Answer
> 3 votes
# APL, ~~40~~ 30 bytes

```
{(-n↑⍵÷⊃⊖⍵),⍨⍉1↓⍉∘.=⍨⍳n←1-⍨≢⍵}

```

Accepts input in ascending order.

Explanation:

```
{
                        n←1-⍨≢⍵    ⍝ Define n = length(input)-1
                   ∘.=⍨⍳           ⍝ Create an n×n identity matrix
               ⍉1↓⍉                ⍝ Drop the leftmost column
            ,⍨                     ⍝ Append on the right:
  (-n↑⍵                            ⍝ n negated coefficients,
       ÷⊃⊖⍵)                       ⍝ divided by the n+1st
}

```

Try it online

# Answer
> 3 votes
# Julia, 43 bytes

```
c->rot180([-c[2:(n=end)]/c[] eye(n-1,n-2)])

```

This uses descending order for the input. It constructs the matrix rotated 180 degrees, in order to enable more efficient use of "eye", then rotates the matrix into the right orientation.

# Answer
> 2 votes
# Julia, ~~64~~ 44 bytes

```
c->(k=c[n=end];[eye(n-=1)[:,2:n] -c[1:n]/k])

```

Accepts a vector of the coefficients in ascending order.

Ungolfed:

```
function f(c::Array)
    # Simultaneously define k = the last element of c and
    # n = the length of c
    k = c[n = end]

    # Decrement n, create an n×n identity matrix, and exclude the
    # first column. Horizontally append the negated coefficients.
    [eye(n-=1)[:,2:n] -c[1:n]/k]
end

```

Try it online

Saved 20 bytes thanks to Glen O!

# Answer
> 2 votes
# R, ~~71~~ 59 bytes

Takes input in ascending order.

```
function(x)cbind(diag(n<-length(x)-1)[,2:n],-x[1:n]/x[n+1])

```

Ungolfed:

```
f <- function(x) {
    # Get the length of the input
    n <- length(x)-1

    # Create an identity matrix and exclude the first column
    i <- diag(n)[, 2:n]

    # Horizontally append the negated coefficients divided
    # by the last one
    cbind(i, -x[1:n]/x[n+1])
}

```

# Answer
> 1 votes
# Matlab, 66 bytes

```
function y=f(c)
n=numel(c);y=[[0*(3:n);eye(n-2)] -c(1:n-1)'/c(n)];

```

It uses ascending order for the input, with format `[3., 7., -5., 4., 1.]` or `[3. 7. -5. 4. 1.]`.

Try it online (in Octave).

Example (in Matlab):

```
>> f([23., 1., 92., 8., -45., 88., 88.])
ans =
                   0                   0                   0                   0                   0  -0.261363636363636
   1.000000000000000                   0                   0                   0                   0  -0.011363636363636
                   0   1.000000000000000                   0                   0                   0  -1.045454545454545
                   0                   0   1.000000000000000                   0                   0  -0.090909090909091
                   0                   0                   0   1.000000000000000                   0   0.511363636363636
                   0                   0                   0                   0   1.000000000000000  -1.000000000000000

```

---

*If a program is valid (instead of a function), with stdin and stdout:*

# Matlab, 59 bytes

```
c=input('');n=numel(c);[[0*(3:n);eye(n-2)] -c(1:n-1)'/c(n)]

```

# Answer
> 1 votes
# Octave, ~~45~~ 44 bytes

Assuming `c` is a column vector with the coefficient of the highest power of `x` at the end.

```
@(c)[eye(n=rows(c)-1)(:,2:n),-c(1:n)/c(end)]

```

Old version:

```
@(c)[eye(n=numel(c)-1)(:,2:n),-c(1:n)/c(end)]

```

High five, Julia!

# Answer
> 1 votes
# Python 2, 141 bytes

My own attempt:

```
def C(p):
 c,r=p.pop(0),range;d=[-i/c for i in p];n=len(d);m=[[0]*n for i in r(n)]
 for i in r(n-1):m[i][i+1]=1
 m[-1]=d[::-1];return zip(*m)

```

Takes a list of the coefficients in descending order and first builds the transpose of the companion matrix - known for stabbing and being talkative. The return uses zip to produce the transpose of this transpose to get the actual matrix.

```
>>> C([1., 4., -5., 7., 3.])
[(0, 0, 0, -3.0), (1, 0, 0, -7.0), (0, 1, 0, 5.0), (0, 0, 1, -4.0)]

```

# Answer
> 1 votes
# JavaScript (ES6) 85

Ascending order.

Test running the snippet below in any EcmaScript 6 compliant browser.

```
f=c=>alert(c.map((v,i)=>c.map((x,j)=>++j-i?j-c.length?0:-v/m:1),m=c.pop()).join(`
`))

// test
// redefine alert to write into the snippet body
alert=x=>O.innerHTML+=x+'\n'

function test() {
  v=I.value.match(/\d+/g)
  I.value=v+''
  alert(v)
  f(v)
}

test()
```

```
<input value='23.,1.,92.,8.,-45.,88.,88.' id=I><button onclick="test()">-></button>
<pre id=O></pre>
```

# Answer
> 0 votes
# TI-BASIC, 50 bytes

```
Ans→X
List▶matr(ΔList(Ans-cumSum(Ans)),[A]
dim(Ans
augment(augment(0randM(Ans-2,1),identity(Ans-2))ᵀ,[A]∟X(Ans)⁻¹

```

Takes input in ascending order. Note that this will not work for polynomials of degree \<2, because TI-BASIC does not support empty matrices or lists. Pending a ruling from OP, I can fix this at the cost of a few bytes.

First, we store the list into `∟X` to use the last element later; then, we calculate `ΔList(Ans-cumSum(Ans))`, which is just the negated list with the last element chopped off, and convert it to a column vector. Since `List▶matr(` doesn't modify `Ans`, we can use the next line to take the dimension of the list, which we use thrice. TI-BASIC doesn't have vertical concatenation, so we need to take transposes and horizontally concatenate. In the last line, `[A]/∟X(Ans` wouldn't work because matrices can be multiplied by scalars but not divided.

An aside: To generate the row vector of zeros, we take advantage of the rarely useful `randM(` command. `randM(` creates a random matrix, but its entries are always random integers between -9 and 9 (!), so it's really only useful to create zero matrices.

# Answer
> 0 votes
# Pari/GP, 42 bytes

```
p->concat(matid(#p-1),-p[^#p]~/p[#p])[,^1]

```

Try it online!

---
Tags: code-golf, math, matrix, polynomials, linear-algebra
---


title: What is the frequency of this note?

text:
# Question
Title: What is the frequency of this note?
Quick musical refresher:

The piano keyboard consists of 88 notes. On each octave, there are 12 notes, `C, C♯/D♭, D, D♯/E♭, E, F, F♯/G♭, G, G♯/A♭, A, A♯/B♭` and `B`. Each time you hit a 'C', the pattern repeats an octave higher.

A note is uniquely identified by 1) the letter, including any sharps or flats, and 2) the octave, which is a number from 0 to 8. The first three notes of the keyboard, are `A0, A♯/B♭` and `B0`. After this comes the full chromatic scale on octave 1. `C1, C♯1/D♭1, D1, D♯1/E♭1, E1, F1, F♯1/G♭1, G1, G♯1/A♭1, A1, A♯1/B♭1` and `B1`. After this comes a full chromatic scale on octaves 2, 3, 4, 5, 6, and 7. Then, the last note is a `C8`.

Each note corresponds to a frequency in the 20-4100 Hz range. With `A0` starting at exactly 27.500 hertz, each corresponding note is the previous note times the twelfth root of two, or roughly 1.059463. A more general formula is:

where n is the number of the note, with A0 being 1. (More information here)

# The Challenge

Write a program or function that takes in a string representing a note, and prints or returns the frequency of that note. We will use a pound sign `#` for the sharp symbol (or hashtag for you youngins) and a lowercase `b` for the flat symbol. All inputs will look like `(uppercase letter) + (optional sharp or flat) + (number)` with no whitespace. If the input is outside of the range of the keyboard (lower than A0, or higher than C8), or there are invalid, missing or extra characters, this is an invalid input, and you do not have to handle it. You can also safely assume you will not get any weird inputs such as E#, or Cb.

# Precision

Since infinite precision isn't really possible, we'll say that anything within one cent of the true value is acceptable. Without going into excess detail, a cent is the 1200th root of two, or 1.0005777895. Let's use a concrete example to make it more clear. Let's say your input was A4. The ***exact*** value of this note is 440 Hz. Once cent flat is `440 / 1.0005777895 = 439.7459`. Once cent sharp is `440 * 1.0005777895 = 440.2542` Therefore, any number greater than 439.7459 but smaller than 440.2542 is precise enough to count.

# Test cases

```
A0  --> 27.500
C4  --> 261.626
F#3 --> 184.997
Bb6 --> 1864.66
A#6 --> 1864.66
A4  --> 440
D9  --> Too high, invalid input.
G0  --> Too low, invalid input.
Fb5 --> Invalid input.
E   --> Missing octave, invalid input
b2  --> Lowercase, invalid input
H#4 --> H is not a real note, invalid input.

```

Keep in mind that you don't have to handle the invalid inputs. If your program pretends they are real inputs and prints out a value, that is acceptable. If your program crashes, that it also acceptable. Anything can happen when you get one. For the full list of inputs and outputs, see this page

As usual, this is code-golf, so standard loopholes apply, and shortest answer in bytes wins.

# Answer
> 23 votes
# Japt, ~~41~~ ~~37~~ ~~35~~ 34 bytes

I finally have a chance to put `¾` to good use! :-)

```
55*2pU¬®-1¾ª"C#D EF G A B"bZ /C} x

```

Try it online!

### How it works

```
          // Implicit: U = input string, C = 12
U¬®    }  // Take U, split into chars, and map each item Z by this function:
-1¾       //  Subtract 1.75 from Z. This produces NaN for non-digits.
ª"..."bZ  //  If the result is falsy (NaN), instead return the index of Z in this string.
          //  C produces 0, D -> 2, E -> 4, F -> 5, G -> 7, A -> 9, B -> 11.
          //  # -> 1, and b -> -1, so we don't need to calculate them separately.
/C        //  Divide the index by 12.
x         // Sum.
2p        // Take 2 to the power of the result.
55*       // Multiply by 55.

```

## Test cases

All the valid test cases come through fine. It's the invalid ones where it gets weird...

```
input --> output       (program's reasoning)
A0  --> 27.5           (Yep, I can do that for you!)
C4  --> 261.625565...  (Yep, I can do that for you!)
F#3 --> 184.997211...  (Yep, I can do that for you!)
Bb6 --> 1864.6550...   (Yep, I can do that for you!)
A#6 --> 1864.6550...   (Yep, I can do that for you!)
A4  --> 440            (Yep, I can do that for you!)
D9  --> 9397.27257...  (Who says that's too high?)
G0  --> 24.49971...    (I've heard that note before.)
Fb5 --> 659.25511...   (Wait, Fb isn't supposed to be a note?)
E   --> 69.295657...   (I'm gonna guess that the missing octave is 1¾.)
b2  --> 61.735412...   (I assume that b means Cb...)
H#4 --> 261.625565...  (H# is C!)

```

# Answer
> 8 votes
# Pyth, ~~46~~ ~~44~~ ~~43~~ ~~42~~ ~~39~~ 35 bytes

```
*55^2tsm.xsdc-x"C D EF GbA#B"d9 12z

```

Try it online. Test suite.

The code now uses a similar algorithm to ETHproductions's Japt answer, so credit to him for that.

### Explanation

```
                                            implicit: z = input
       m                          z         for each character in input:
          sd                                  try parsing as number
        .x                                    if that fails:
               "C D EF GbA#B"                   string "C D EF GbA#B"
              x              d                  find index of character in that
             -                9                 subtract 9
            c                   12              divide by 12
      s                                     sum results
     t                                      decrement
   ^2                                       get the correct power of 2
*55                                         multiply by 55 (frequency of A1)

```

## Old version (42 bytes, 39 w/ packed string)

```
*55^2+tsezc+-x"C D EF G A B"hz9-}\#z}\bz12

```

### Explanation

```
<pre>
                                         implicit: z = input
                                     GET OFFSET BY NOTE:
              ."…"                       string "C@D@EF@G@A@B" packed
             x    hz                     get index of first char in input
            -       9                    subtract 9
                                     PARSE #/b:
           +          }\#z               add 1 if input contains "#"
                     -    }\bz           subtract 1 if input contains "b"
                                     CONVERT OFFSET TO OCTAVES:
          c                   12         divide by 12
                                     FIND OCTAVE IN INPUT:
        ez                               last char of input
       s                                 convert to number
                                     GET FINAL RESULT:
      t                                  decrement the octave
     +                                   add the octave and the note offset
   ^2                                    get the correct power of 2
*55                                      multiply by 55 (frequency of A1)
</pre>
```

# Answer
> 7 votes
# Mathematica, 77 bytes

```
2^((Import[".mid"~Export~Sound@SoundNote@#,"RawData"][[1,3,3,1]]-69)/12)440.&

```

---

**Explanation**:

The main idea of this function is to convert the string of note to its relative pitch, and then calculate its frequency.

The method I use is export the sound to midi and import the raw data, but I suspect that there is a more elegant way.

---

**Test cases**:

```
f=%; (* assign the function above to f *)
f["A4"]    (* 440.    *)
f["A5"]    (* 880.    *)
f["C#-1"]  (* 8.66196 *)
f["Fb4"]   (* 329.628 *)
f["E4"]    (* 329.628 *)
f["E"]     (* 329.628 *)

```

# Answer
> 4 votes
# MATL, ~~56~~ ~~53~~ ~~50~~ 49 48 bytes

```
Hj1)'C D EF G A B'=f22-'#b'"G@m]-s+ 12/G0)U+^55*

```

Uses current release (10.1.0), which is earlier than this challenge.

**Try it online**!

### Explanation

```
H                   % push 2
j1)                 % get input string. Take first character (note)
'C D EF G A B'=f    % find index of note: 1 for C, 3 for D...
22-                 % subtract 22. This number comes from three parts:
                    % 9; 1 for 0-based indexing; 12 to subtract 1 octave
'#b'"G@m]-s         % For loop. Gives 1 if input contains '#', -1 if 'b', 0 otherwise
+                   % add to previous number. Space needed to separate from next literal
12/                 % divide by 12
G0)                 % push input and get last character (octave)
U+                  % convert to number and add to previous number
^                   % raise 2 (that was initially pushed) to accumulated number
55*                 % multiply by 55 (=27.5*2). Implicitly display

```

# Answer
> 4 votes
# JavaScript ES7, ~~73~~ ~~70~~ 69 bytes

```
x=>[...x].map(c=>t+=c-1.75||"C#D EF G A B".search(c)/12,t=0)&&2**t*55

```

Uses the same technique as my Japt answer.

# Answer
> 3 votes
# Ruby, ~~69~~ 65

```
->n{2**((n.ord*13/8%12-n.size+(n=~/#/?7:5))/12.0+n[-1].to_i)*55/4}

```

**Ungolfed in test program**

```
f=->n{
  2**(                    #raise 2 to the power of the following expression:
   (
     n.ord*13/8%12-       #note name C..B maps to number 0..11 calculated from the ascii code of n[0]
     n.size+(n=~/#/?7:5)  #Correction for flat: length of n is 1 more for flat (or sharp) than for natural. Then apply correction for sharp
                          #now we have a number 3..14 for C..B (so 12 for A, will be a whole number when divided)
   )/12.0+                #divide by 12 to convert into a fraction of an octave

  n[-1].to_i              #add the octave number, last character in n
  )*                      #end of power expression, now we have A0=2,A1=4,A2=4 etc

  55/4                    #multiply to get correct frequency, this is shorter than 13.75 or 440/32
}

#complete octave test case
puts %w{A0 A#0 Bb0 B0 C1 C#1 Db1 D1 D#1 Eb1 E1 F1 F#1 Gb1 G1 G#1 Ab1 A1 A#1}.map{|e|[e,f[e]]}

#test case per OP
puts %w{A0 C4 F#3 Bb6 A#6}.map{|e|[e,f[e]]}

```

**Output**

```
A0
27.5
A#0
29.13523509488062
Bb0
29.13523509488062
B0
30.867706328507758
C1
32.70319566257483
C#1
34.64782887210901
Db1
34.64782887210901
D1
36.70809598967595
D#1
38.890872965260115
Eb1
38.890872965260115
E1
41.20344461410875
F1
43.653528929125486
F#1
46.2493028389543
Gb1
46.2493028389543
G1
48.999429497718666
G#1
51.91308719749314
Ab1
51.91308719749314
A1
55.0
A#1
58.27047018976123
A0
27.5
C4
261.6255653005986
F#3
184.9972113558172
Bb6
1864.6550460723593
A#6
1864.6550460723593

```

# Answer
> 2 votes
# ES7, 82 bytes

```
s=>55*2**(+s.slice(-1)+("C D EF G A B".search(s[0])+(s[1]<'0')-(s[1]>'9')-21)/12)

```

Returns 130.8127826502993 on input of "B#2" as expected.

Edit: Saved 3 bytes thanks to @user81655.

# Answer
> 2 votes
# C, 123 bytes

```
float d(char*s){int n=*s++,m=(n*12+(n<67?90:6))/7,o=*s++,a=o^35?o^98?0:-1:1;return exp((m+(a?*s++:o)*12+a)/17.3123-37.12);}

```

Usage:

```
#include <stdio.h>
#include <math.h>

float d(char*s){int n=*s++,m=(n*12+(n<67?90:6))/7,o=*s++,a=o^35?o^98?0:-1:1;return exp((m+(a?*s++:o)*12+a)/17.3123-37.12);}

int main()
{
    printf("%f\n", d("A4"));
}

```

The calculated value is always about 0.8 cents less than the exact value, because I cut as many digits as possible from the floating-point numbers.

Overview of the code:

```
float d(char*s){
    int n=*s++,        // read the letter
        m=(n*12+       // multiply by 12/7 to convert from A...G to 0...11
        (n<67?90:6)    // if A or B, add 1 octave; also add some fix-up rounding value
        )/7,

        o=*s++,        // read next char: the octave digit or accidental

        a=o^35?o^98?0:-1:1; // if accidental, convert it into +1 or -1; else 0

        return exp((m+ // I adjusted the factors to use exp instead of pow
            (a?*s++:o) // if was accidental, now read the octave digit
            *12+a)/
            17.3123-   // a more exact value is 17.3123404447
            37.12);    // a more exact value is 37.1193996632
}

```

# Answer
> 1 votes
# R, ~~157~~ ~~150~~ ~~141~~ 136 bytes

```
f=function(x){y=strsplit(x,"")[[1]];55*2^(as.double(y[nchar(x)])-1+(c(10,12,1,3,5,6,8)[LETTERS==y[1]]-switch(y[2],"#"=9,"b"=11,10))/12)}

```

With indent and newlines:

```
f=function(x){
     y=strsplit(x,"")[[1]]
     55 * 2^(as.double(y[nchar(x)]) - 1 +
         (c(10,12,1,3,5,6,8)[LETTERS==y[1]] -
         switch(y[2],"#"=9,"b"=11,10))/12)
     }

```

Usage:

```
> f("A0")
[1] 27.5
> f("C8")
[1] 4186.009
> sapply(c("C4","Bb6","A#6","A4"),f)
       C4       Bb6       A#6        A4
 261.6256 1864.6550 1864.6550  440.0000

```

# Answer
> 1 votes
# Python, ~~97~~ 95 bytes

```
def f(n):a,*b,c=n;return 2**(int(c)+('C@D@EF@G@A@B'.find(a)-(21,(22,20)['#'in b])[b>[]])/12)*55

```

Based on Pietu1998's (and others') old approach of looking for the index of the note in the string `'C@D@EF@G@A@B'` for some blank char or another. I use iterable unpacking to parse the note string without conditionals. I did a little bit of algebra at the end to simplify the conversion expression. Don't know if I can get it shorter without changing my approach.

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

```
ToExpression@("Music`"<>StringReplace[#,{"b"->"flat","#"->"sharp"}])&

```

Using the music package, with which simply entering a note as an expression evaluates to its frequency, like this:

```
 In[1]:= Eflat3
Out[1]:= 155.563

```

To save bytes by avoiding to import the package with `<<Music`, I'm using the fully qualified names: `Music`Eflat3`. However, I still have to replace `b` with `flat` and `#` with `sharp` to match the input format of the question, which I do with a simple `StringReplace`.

---
Tags: code-golf, music
---