title: Confuse the Dakotas

text:
# Question
Title: Confuse the Dakotas
You have been hired by the government of North Dakota to encrypt the state's communications. Write two programs, one to encrypt a message and one to decrypt that message.

The government is not really tech-savvy, so the encryption algorithm does not need to be sophisticated; just make sure the result doesn't look similar to the original at first glance.

However, you're secretly loyal to the South Dakotan government. Your job is to mix up the communications, so that every mention of `North Dakota` becomes `South Dakota` upon decryption, and vice versa. This also applies to `North/South Dakotan` and `North/South Dakotans`.

For example:

> North Dakota is the wealthiest county in North America, while South Dakotans are poorer than southern Florida. - the North Dakotan government

will undergo encryption and then decryption, resulting in:

> South Dakota is the wealthiest county in North America, while North Dakotans are poorer than southern Florida. - the South Dakotan government

The algorithm which accomplishes this in the most secretive, tricky manner, as evidenced by having the most upvotes, will be accepted.

# Answer
> 13 votes
# Ruby

```
class Dakota

  PRIVATE_KEY = 8411088

  def self.encrypt(str)
    str.gsub(/[A-Z]/){|c|"0#{c.downcase}"}.gsub(/[a-z]+/){|s|xor(s.to_i(36),$')}
  end

  def self.decrypt(str)
    str.gsub(/\d+/){|s|out = s.to_i.to_s(36);out[0] = out[0].upcase if s[0]==?0; out}
  end

  def self.xor(n, config)
    n^=PRIVATE_KEY if private_env?(config)
    n
  end

  def self.private_env?(config)
    config =~ /^ .#{private}/i
  end

end

puts code = Dakota.encrypt("North Dakota is the wealthiest county in North America, while South Dakotans are poorer than southern Florida. - the North Dakotan government")

puts out = Dakota.decrypt(code)

```

Demo

# Answer
> 7 votes
# CJam

This is the encoder:

```
232375064392749269032321519657657089927649992440902190178063558812627752920796248165803740235420850037801568815744960725761679066919872746899310628404239458 128b:c~

```

and this is the decoder:

```
364380128038419794871782113211824472986419260504039724627500790722811712426518562428698978399810134993565366126560239807690210155343815201005388714282 128b:c~

```

Try it online here

This only works with capital `N`, `S` and `D` in `North/South Dakota`

Pass the input string to the first function from STDIN. Get the encoded string, pass it to the second function to get the decoded and converted output.

# Answer
> 6 votes
# Java

I discovered that division by zero does not cause errors in this program. This program fully encodes the Strings into a form that cannot be traced to the North Dakotan government. Due to the strange behaviour mentioned above, encoding and decoding might not work correctly in all cases.

```
class Program{

    public static void main(String[] args){
        String input = String.join(" ", args);
        String encode = encode(input);
        System.out.println("Encoded: " + encode);
        System.out.println("Decoded: " + decode(encode));
    }

    static String encode(String input){
        String answer = "";
        input = input.replaceAll("North Dakota", "☃");//Temporarily switch these so that spies
        input = input.replaceAll("South Dakota", "North Dakota");//think the message is from South Dakota
        input = input.replaceAll("☃", "South Dakota");//if they decode the message.
        for(int i =0; i < input.length(); i++){
            answer += (char)(~input.charAt(i)) + "";
        }
        return answer;
    }

    static String decode(String input){
        String answer = "";
        int i;
        for(i=0; i < input.length(); i++){
            answer += (char)(~input.charAt(i)) + "";
        }
        int funnyNumber = (i+\u002f*0)/0;//Division by 0 should cause an error???
        answer.replaceAll("South Dakota", "☃");
        answer.replaceAll("North Dakota", "South Dakota");
        answer.replaceAll("☃", "North Dakota");
        //For some reason, this does not cause errors either:
        funnyNumber = ((500/0)*\u002f+-2);
        return answer;
    }
}

```

Question: What does `funnyNumber` equal?

# Answer
> 2 votes
## JavaScript

```
function encrypt (input) {
    input = input.replace(/north d/gi, 'hisdf')
    input = input.replace(/south d/gi, 'hisde')
    var data = input
    var res = []
    for (var i = 0; i < data.length; i++) {
        res.push(~data.charCodeAt(i))
    }
    return res.toString()
}
function decrypt (input) {
    console.log(input)
    input = input.replace(/-105,-106,-116,-101,-102/g, '-79,-112,-115,-117,-105,-33,-69').replace(/-105,-106,-116,-101,-103/g, '-84,-112,-118,-117,-105,-33,-69 ')
    input = input.split(',')
    var res = ""
    for (var i = 0; i < input.length; i++) {
        var itm = input[i]
        res += String.fromCharCode(~parseInt(itm))
    }
    return res
}
var data = encrypt(prompt('What do you want to encrypt?'))
var data = decrypt(data)
alert(data)

```

My solution is probably not the most clever one. But it works :) Here is a fiddle

First I replace `north d` with `hisdf` and `south d` with `hisde`, then I invert all the characters bitwise and push them in an array. The array I convert into a string and then replace the inverted character values with the correct ones. Before that, I replace the values of `hisdf` and `hisde` switched.

# Answer
> 2 votes
## AWK: Encoder: 165 bytes, Decoder: 61 bytes

The encoder (also in charge of replacing South by North and vice versa):

```
{a="(th Dakota(ns?)?)";b="\\1";split(gensub("@"a,"Sou"b,"g",gensub("Sou"a,"Nor"b,"g",gensub("Nor"a,"@"b,"g")))" ",y,"");for(i=1;i<length(y);i+=2)printf(y[i+1] y[i])}

```

The decoder:

```
{split($0,y,"");for(i=1;i<length(y);i+=2)printf(y[i+1] y[i])}

```

Some test:

> North Dakota is the wealthiest county in North America, while South Dakotans are poorer than southern Florida. - the North Dakotan government

encodes into:

> oStu haDokati sht eewlahteitsc uotn yniN rohtA emirac ,hwli eoNtr haDokatsna erp ooer rhtnas uohtre nlFrodi.a- t ehS uohtD katonag voremnne t

(that should be scrambled enough for a *not really tech-savvy government* :o) )

It then decodes into:

> South Dakota is the wealthiest county in North America, while North Dakotans are poorer than southern Florida. - the South Dakotan government

But that was expected :o)

Note: North Dakota, North Dakotan, North Dakotans, South Dakota, South Dakotan and South Dakotans have to be correctly capitalized.

# Answer
> 0 votes
# JavaScript, ES6

Sweet and simple to begin with.

Encoder:

```
E=a=>btoa(a)

```

Decoder:

```
D=a=>atob(a_.replace(/(nor|sou)(th dakota)/gi, (_,x,y)=>({n:"sou",s:"nor",N:"Sou",S:"Nor"})[x[0]]+y)

```

Try it below on a latest Firefox:

```
E=a=>btoa(a)
D=a=>atob(a).replace(/(nor|sou)(th dakota)/gi, (_,x,y)=>({n:"sou",s:"nor",N:"Sou",S:"Nor"})[x[0]]+y)
var string = prompt()
alert("Encoded string: " + E(string));
alert("Decode string: " + D(E(string)));
```

# Answer
> 0 votes
# C

```
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>

#define MASK_B 0xFFFFFFULL
#define MASK_C 0xFFULL
#define ll unsigned long long int
#define transform(a,b) ((a)>(b))?(a):(b)
static const ll magic_num = 0x756f736874726f6e;
#define BITS(a,b) (magic_num&(MASK_C<<((a+b)*8)))>>((a+b)*8)

char * key;
ll keylen;
FILE * file;

char * encrypt(in)
char * in;
{
    char * out;
    size_t length = strlen(in);
    out = (char *) malloc(sizeof (char) * (length + 1));
    for (ll i = 0; i < length; i++)out[i] = key[i % keylen]^in[i];
    out[length] = '\0';
    return out;
}

char * decrypt() {
    size_t len = 0;
    fpos_t pos;
    char * out;
    fgetpos(file, &pos);
    do if (fgetc(file) == EOF) break; else len++; while (1);
    out = (char *) malloc(sizeof (char) * (len + 1));
    fsetpos(file, &pos);
    char chr;
    ll idx = 0;
    do {
        chr = fgetc(file);
        if (chr == EOF) break;
        out[idx++] = chr^key[idx % keylen];
    } while (1);
    out[len] = '\0';
    return out;
}

void * bits(flag, mask)
ll flag;
char * mask;
{
    int dx = (flag & (~0&MASK_C)<<16) ? 5 : 0;
    key[0] = BITS(dx, 0),key[1] = BITS(dx, 1),key[2] = BITS(dx, 2),key[3] = BITS(3, 0),key[4] = BITS(3, 1);
    strncpy(&key[5], " dakota", 8);
    if (flag & ~(MASK_B^MASK_C)) {
        dx = (char)flag & MASK_C;
        if (islower(*mask)) *mask = key[dx - 1];
        else *mask = toupper(key[dx - 1]);
    } else if (!(flag & ~~0))
        return (void *) key;
    return (void*) key[transform(arc4random_uniform(12), 12)];
}

int genkey(in)
char * in;
{
    size_t bound_upper = strlen(in);
    char * index1 = malloc(sizeof(char) * (bound_upper + 1));
    char * index2 = malloc(sizeof(char) * (bound_upper + 1));
    char * index;
    index1 = strcpy(index1,in);
    index2 = strcpy(index2,in);
    ll spice = 0;
    key = (char *) malloc(sizeof (char) * 13);
    char *hits = (char *) malloc(sizeof (char) * bound_upper);
    for (unsigned long j = 0; j < bound_upper; j++){
        hits[j] = 0;
    }

    for (int iter = 0; iter < 2; iter++) {
        ll rotation = 0, flag = MASK_C << (8 * (iter + 1)), flag2 = MASK_C << (8 * (2 - iter)),abs=0;
        char * tmpstr;
        index = iter ? index2 : index1;
        do {
            spice = spice + arc4random_uniform(bound_upper) % bound_upper;
            if (!rotation) {
                tmpstr = strcasestr(index, bits(flag, in));
                if (tmpstr == NULL)
                    goto out;
                index = tmpstr;
            } else {
                bits(flag2 | rotation, index++);
                hits[abs] = iter + 1;
            }
            rotation = (rotation + 1) % (4);
            abs = index - (iter ? index2 : index1);
        } while (flag);
out:
        index = in;
        rotation = 0;
    }
    for(int k = 0;k < bound_upper;k++){
        index[k]=(hits[k]==1?index1[k]:(hits[k] ? index2[k]: index[k]));
        spice += arc4random_uniform(spice)|spice^arc4random();
    }
    free(key);
    spice = spice % bound_upper;
    if (!spice)
        spice = bound_upper;
    keylen = (keylen | spice) & MASK_B;
    key = (char *) malloc(sizeof (char) * (keylen + 1));
    for (ll i = 0; i < keylen; i++)
        key[i] = (arc4random_uniform(126 - ' ') % (126 - ' ')) + ' ';
    key[keylen] = '\0';
    return keylen;
}

int main(argc, argv)
int argc;
char *argv[];
{
    if (argc != 4) return 1;
    char * result;
    if (!strcmp(argv[1], "encrypt")) {
        (void) genkey(argv[2]);
        result = encrypt(argv[2]);
        printf("Decryption Key: '%s'\n", key);
        file = fopen(argv[3], "wb");
        if (file == NULL) printf("Could not open file for writing: %s", argv[3]);
        if (fwrite(result, sizeof (char), strlen(result), file) != strlen(result)) printf("Error occurred while writing ciphertext to file!");
    }
    if (!strcmp(argv[1], "decrypt")) {
        file = fopen(argv[3], "rb");
        if (file == NULL) printf("Could not open file for reading: %s", argv[3]);
        key = argv[2];
        keylen = strlen(argv[2]);
        result = decrypt();
        printf("Plaintext: '%s'\n", result);
    }
    return 0 & fclose(file);
}

```

Compile with: `gcc -Wall -Wextra -Wno-missing-field-initializers -Wimplicit -Wreturn-type -Wunused -Wformat -Wswitch -Wshadow -Wwrite-strings -DGCC_WARN -ansi -pedantic file.c`

For maximum evil, written in K&R C with a dash of pointer abuse.
Lasciate ogni speranza, voi ch'entrate.
Buśhaīila rukgâī, naǵkxarańga ba tdhuløk.
Also, everything's in the `bits` function and the `genkey` function.

Run:

```
[...@...] testing_golf$ ./a.out encrypt "North Dakota is the wealthiest county in North America, while South Dakotans are poorer than southern Florida. - the North Dakotan government" cipher
Decryption Key: ')=1aj3'
[...@...]: testing_golf$ ./a.out decrypt ")=1aj3" cipher
Plaintext: 'South Dakota is the wealthiest county in North America, while North Dakotans are poorer than southern Florida. - the South Dakotan government'

```

Note: When specifying the key in `decrypt` mode, it may be necessary to escape some of the characters in the key with backslashes.

---
Tags: popularity-contest, underhanded, encoding
---


# Question
Title: Rotate An Integer Array with an O(n) algorithm
Write a function that rotates an integer array by a given number k. k elements from the end should move to the beginning of array, and all other elements should move to right to make the space.

The rotation should be done in-place.

Algorithm should not run in more than O(n), where n is the size of array.

Also a constant memory must be used to perform the operation.

For example,

if array is initialized with elements arr = {1, 2, 3, 4, 5, 6, 7, 8, 9}

rotate(arr, 3) will result the elements to be {7, 8, 9, 1, 2, 3, 4, 5, 6}

rotate(arr, 6) will result the {4, 5, 6, 7, 8, 9, 1, 2, 3}

# Answer
> 18 votes
## C (104)

```
void reverse(int* a, int* b)
{
    while (--b > a) {
        *b ^= *a;
        *a ^= *b;
        *b ^= *a;
        ++a;
    }
}

void rotate(int *arr, int s_arr, int by)
{
    reverse(arr, arr+s_arr);
    reverse(arr, arr+by);
    reverse(arr+by, arr+s_arr);
}

```

Minified:

```
v(int*a,int*b){while(--b>a){*b^=*a;*a^=*b;*b^=*a++;}}r(int*a,int s,int y){v(a,a+s);v(a,a+y);v(a+y,a+s);}

```

# Answer
> 9 votes
# APL (4)

```
¯A⌽B

```
* A is the number of places to rotate
* B is the name of the array to be rotated

I'm not sure if APL actually required it, but in the implementation I've seen (the internals of) this would take time proportional to `A`, and constant memory.

# Answer
> 5 votes
Here is a long winded C version of Colin's idea.

```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int gcd(int a, int b) {
  int t;
  if (a < b) {
    t = b; b = a; a = t;
  }
  while (b != 0) {
    t = a%b;
    a = b;
    b = t;
  }
  return a;
}

double arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
int s_arr = sizeof(arr)/sizeof(double);

/* We assume 1 <= by < s_arr */
void rotate(double *arr, int s_arr, int by) {
  int i, j, f;
  int g = gcd(s_arr,by);
  int n = s_arr/g;
  double t_in, t_out;

  for (i=0; i<g; i++) {
    f = i;
    t_in = arr[f + s_arr - by];
    for (j=0; j<n; j++) {
      t_out = arr[f];
      arr[f] = t_in;
      f = (f + by) % s_arr;
      t_in = t_out;
    }
  }
}

void print_arr(double *arr, int s_arr) {
  int i;
  for (i=0; i<s_arr; i++) printf("%g ",arr[i]);
  puts("");
}

int main() {
  double *temp_arr = malloc(sizeof(arr));
  int i;

  for (i=1; i<s_arr; i++) {
    memcpy(temp_arr, arr, sizeof(arr));
    rotate(temp_arr, s_arr, i);
    print_arr(temp_arr, s_arr);
  }
}

```

# Answer
> 3 votes
## C

Not sure what the criteria is, but since I had fun with the algorithm, here is my entry:

```
void rotate(int* b, int size, int shift)
{
    int *done;
    int *p;
    int i;
    int saved;
    int c;

    p = b;
    done = p;
    saved = *p;
    for (i = 0; i < size; ++i) {
        c = saved;
        p += shift;
        if (p >= b+size) p -= size;
        saved = *p;
        *p = c;
        if (p == done) {
            p += 1;
            done = p;
            saved = *p;
        }
    }
}

```

I'll golf it for a good measure too; 126 bytes, can be made shorter:

```
void r(int*b,int s,int n){int*d,*p,i,t,c;d=p=b;t=*p;for(i=0;i<s;++i){c=t;p+=n;if(p>=b+s)p-=s;t=*p;*p=c;if(p==d){d=++p;t=*p;}}}

```

# Answer
> 3 votes
I don't see very many C++ solutions here, so I figured I'd try this one since it doesn't count characters.

This is true "in-place" rotation, so uses 0 extra space (except technically swap and 3 ints) and since the loop is exactly N, also fulfills the O(N) complexity.

```
template <class T, size_t N>
void rot(std::array<T,N>& x, int shift)
{
        size_t base=0;
        size_t cur=0;
        for (int i = 0; i < N; ++i)
        {
                cur=(cur+shift)%N; // figure out where we are going
                if (cur==base)     // exact multiple so we have to hit the mods when we wrap
                {
                        cur++;
                        base++;
                }
                std::swap(x.at(base), x.at(cur)); // use x[base] as holding area
        }
}

```

# Answer
> 2 votes
If you perform each of the possible cycles of rotations by n in turn (there are GCD(n, len(arr)) of these), then you only need a single temporary copy of an array element and a few state variables. Like this, in Python:

```
from fractions import gcd

def rotate(arr, n):
    total = len(arr)
    cycles = gcd(n, total)
    for start in range(0, cycles):
        cycle = [i % total for i in range(start, abs(n * total) / cycles, n)]
        stash = arr[cycle[-1]]
        for j in reversed(range(1, len(cycle))):
            arr[cycle[j]] = arr[cycle[j - 1]]
        arr[cycle[0]] = stash

```

# Answer
> 2 votes
**C (137 characters)**

```
#include <stdio.h>

void rotate(int * array, int n, int k) {
    int todo = (1<<n+1)-1;
    int i = 0, j;
    int tmp = array[0];

    while (todo) {
        if (todo & 1<<i) {
            j = (i-k+n)%n;
            array[i] = todo & 1<<j ? array[j] : tmp;
            todo -= 1<<i;
            i = j;
        } else tmp = array[++i];
    }
}

int main() {
    int a[] = {1,2,3,4,5,6,7,8,9};
    rotate(a, 9, 4);
    for (int i=0; i<9;i++) printf("%d ", a[i]);
    printf("\n");
}

```

Function `rotate` minified to 137 characters:

```
void r(int*a,int n,int k){int m=(1<<n+1)-1,i=0,j,t=a[0];while(m)if(m&1<<i){j=(i-k+n)%n;a[i]=(m&1<<j)?a[j]:t;m-=1<<i;i=j;}else t=a[++i];}

```

# Answer
> 2 votes
Factor has a built-in type for rotatable arrays, `<circular>`, so this is actually a O(1) operation:

```
: rotate ( circ n -- )
    neg swap change-circular-start ;

IN: 1 9 [a,b] <circular> dup 6 rotate >array .
{ 4 5 6 7 8 9 1 2 3 }
IN: 1 9 [a,b] <circular> dup 3 rotate >array .
{ 7 8 9 1 2 3 4 5 6 }

```

A less cheatish Factor equivalent of Ben Voigt's impressive C solution:

```
: rotate ( n s -- )
    reverse! swap cut-slice [ reverse! ] bi@ 2drop ;

IN: 7 V{ 0 1 2 3 4 5 6 7 8 9 } [ rotate ] keep .
V{ 3 4 5 6 7 8 9 0 1 2 }

```

# Answer
> 2 votes
# JavaScript 45

Went for golf anyway because I like golf. It is at maximum O(N) as long as `t` is \<= size of the array.

```
function r(o,t){for(;t--;)o.unshift(o.pop())}

```

To handle `t` of any proportion in O(N) the following can be used (weighing in at 58 characters):

```
function r(o,t){for(i=t%o.length;i--;)o.unshift(o.pop())}

```

Doesn't return, edits the array in place.

# Answer
> 1 votes
## REBEL \- 22

```
/_(( \d+)+)( \d+)/$3$1

```

Input: k expressed as a unary integer using `_` as a digit, followed by a space, then a space-delimited array of integers.

Output: A space, then the array rotated.

Example:

```
___ 1 2 3 4 5/_(( \d+)+)( \d+)/$3$1

```

Final state:

```
 3 4 5 1 2

```

Explanation:

At each iteration, it replaces one `_` and an array `[array] + tail` with `tail + [array]`.

Example:

```
___ 1 2 3 4 5
__ 5 1 2 3 4
_ 4 5 1 2 3
 3 4 5 1 2

```

# Answer
> 1 votes
# Python 3

```
from fractions import gcd
def rotatelist(arr, m):
    n = len(arr)
    m = (-m) % n # Delete this line to change rotation direction
    for i0 in range(gcd(m, n)):
        temp = arr[i0]
        i, j = i0, (i0 + m) % n
        while j != i0:
            arr[i] = arr[j]
            i, j = j, (j + m) % n
        arr[i] = temp

```

Constant memory
O(n) time complexity

# Answer
> 1 votes
# Java

```
public static void rotate(int[] arr, int by) {
    int n = arr.length;
    int i = 0;
    int j = 0;
    while (i < n) {
        int k = j;
        int value = arr[k];
        do {
            k = (k + by) % n;
            int tmp = arr[k];
            arr[k] = value;
            value = tmp;
            i++;
        } while (k != j);
        j++;
    }
}

```

Demo here.

Minified **Javascript, 114**:

```
function rotate(e,r){n=e.length;i=0;j=0;while(i<n){k=j;v=e[k];do{k=(k+r)%n;t=e[k];e[k]=v;v=t;i++}while(k!=j);j++}}

```

# Answer
> 1 votes
# Haskell

This is actually θ(n), as the split is θ(k) and the join is θ(n-k). Not sure about memory though.

```
rotate 0 xs = xs
rotate n xs | n >= length xs = rotate (n`mod`(length xs)) xs
            | otherwise = rotate' n xs

rotate' n xs = let (xh,xt) = splitAt n xs in xt++xh

```

# Answer
> 0 votes
## Python

```
def rotate(a, n): a[:n], a[n:] = a[-n:], a[:-n]

```

# Answer
> 0 votes
**python**

```
   import copy
    def rotate(a, r):
        c=copy.copy(a);b=[]
        for i in range(len(a)-r):   b.append(a[r+i]);c.pop();return b+c

```

# Answer
> 0 votes
**vb.net** O(n) (not Constant memory)

```
Function Rotate(Of T)(a() As T, r As Integer ) As T()
  Dim p = a.Length-r
  Return a.Skip(p).Concat(a.Take(p)).ToArray
End Function

```

# Answer
> 0 votes
### Ruby

```
def rotate(arr, n)
  arr.tap{ (n % arr.size).times { arr.unshift(arr.pop) } }
end

```

# Answer
> 0 votes
## C (118)

Probably was a bit too lenient with some of the specifications. Uses memory proportional to `shift % length`. Also able to rotate in the opposite direction if a negative shift value is passed.

```
r(int *a,int l,int s){s=s%l<0?s%l+l:s%l;int *t=malloc(4*s);memcpy(t,a+l-s,4*s);memcpy(a+s,a,4*(l-s));memcpy(a,t,4*s);}

```

# Answer
> 0 votes
# Python 2, 57

```
def rotate(l,n):
 return l[len(l)-n:len(l)]+l[0:len(l)-n]

```

If only `l[-n:len(l)-n]` worked like I'd expect it to. It just returns `[]` for some reason.

# Answer
> 0 votes
## C++, 136

```
template<int N>void rotate(int(&a)[N],int k){auto r=[](int*b,int*e){for(int t;--e>b;t=*b,*b++=*e,*e=t);};r(a,a+k);r(a+k,a+N);r(a,a+N);}

```

# Answer
> 0 votes
```
def r(a,n): return a[n:]+a[:n]

```

Could someone please check if this actually meets the requirements? I think it does, but it I haven't studied CS (yet).

# Answer
> 0 votes
# Java

Swap the last k elements with the first k elements, and then rotate the remaining elements by k. When you have fewer than k elements left at the end, rotate them by k % number of remaining elements. I don't think anyone above took this approach. Performs exactly one swap operation for every element, does everything in place.

```
public void rotate(int[] nums, int k) {
    k = k % nums.length; // If k > n, reformulate
    rotate(nums, 0, k);
}

private void rotate(int[] nums, int start, int k) {
    if (k > 0) {
        if (nums.length - start > k) {
            for (int i = 0; i < k; i++) {
                int end = nums.length - k + i;
                int temp = nums[start + i];
                nums[start + i] = nums[end];
                nums[end] = temp;
            }
            rotate(nums, start + k, k);
        } else {
            rotate(nums, start, k % (nums.length - start));
        }
    }
}

```

# Answer
> 0 votes
# Perl 5, 42 bytes

```
sub r{$a=pop;map{unshift@$a,pop@$a}1..pop}

```

Try it online!

Subroutine takes the distance to rotate as the first parameter and a reference to the array as the second. Run time is constant based on the distance of the rotation. Array size does not affect run time. Array is modified in place by removing an element from the right and putting it on the left.

---
Tags: popularity-contest, array
---


title: Can I burn the farmers too?

text:
# Question
Title: Can I burn the farmers too?
Inspired by this and this which was inspired by the first question.

I've set my farmers' fields on fire, but unfortunately they saw me do it! If I don't deal with this situation they could report me and then I'd get arrested! So, that shouldn't be too hard. All I have to do is kill them with fire!

The field will be an `m*n` grid with odd `m` and `n` where both are one greater than a multiple of 4. The farmer starts out in the middle of the field. Each "tick", the farmer can move to an adjacent square (edge or corner) and any space on fire will ignite every grid adjacent to it in a 3x3 space (edge or corner again).

Note: fires and farmers can move diagonally.

The grid will be given as some 2D array of 3 unique values: `F`ire, `.`Wheat, and `H`uman (Farmer). For example:

```
F...F
F...F
FFHFF
F...F
F...F

```

<sup>*the farmer is doomed to DIE! \>:-D*</sup>

It would be easy if I could just light a fire right beside the farmer and set him on fire. However, he knows I am in the field with him and he has a gun. If he sees me, I'm dead. So, I can't light the fire within half of the distance between him and the edge, of him. Essentially, if you floordiv the width of the grid by 4, I must be within that many spaces from the edge, and same with the height.

I am immune to fire so I don't have to worry about getting myself out.

The question is:

## Given a field with wheat, a farmer in the center, and potentially existing fires around the field, how many fires do I need to light to guarantee I can kill the farmer?

### Test Cases

These test cases have input represented by a `F . H` grid and output as a single integer. You may take input in any other reasonable format and output a single integer.

```
FFFFF
F...F
F.H.F => 0, the farmer is doomed to die in 2 ticks anyway
F...F
FFFFF

FFFFF
F....
F....
F....
F.H.. -> 1 (just light a fire on the far right side of him)
F....
F....
F....
FFFFF

.....
.....
..H.. -> 4 (to ensure his demise, you would need to light 4 points around the perimeter (with rotational symmetry). Any 4 will do.
.....
.....

```

# Rules

* Standard Loopholes apply
* You can take an array of 2 values if you would like, where you infer the farmer's position from the size (since the farmer will always be in the center)

# Answer
> 2 votes
# Python 3, 672 bytes

```
e=enumerate;H='H';F='F'
def f(m):
	q=m[0];h=len(m);w=len(q);o=0;g=lambda m,c:{(k,l)for i,r in e(m)for j,v in e(r)for k in range(i-1,i+2)for l in range(j-1,j+2)if v==c and k>=0and k<h and l>=0and l<w};n=lambda m,c,d:[[c if(k,l)in g(m,c)-g(m,d)else m[k][l]for(l,v)in e(r)]for(k,r)in e(m)];s=lambda m:H in[q]+[m[h-1]]+[r[0]for r in m]+[r[w-1]for r in m];l=lambda m:all(H not in r for r in m)
	while 1:
		a=m
		while not(s(a)or l(a)):a=n(n(a,H,F),F,1)
		if l(a):return o
		else:o+=1;z(m,a,h,w)
def z(m,a,h,w):
	for i in(0,h-1):
		for j,v in e(a[i]):
			if v==H:m[i][j+(h-1)//2]=F;return
	for j in(0,w-1):
		for i,v in e(r[j] for r in a):
			if v==H:m[i+(w-1)//2][j]='F';return

```

Try it online!

It's very long (I've done my best to golf it), and the solution is not optimal. Here is the general idea:

1. First, let's see if the farmer burns in the original situation. The matrix `a` is filled with `F`s when the fire grows and with `H`s if the farmer can reach a position (`a=n(n(a,H,F),F,1)`).
2. If the farmer escapes (`s(a)`), look a the border of `a`. There must be at least a `H`. It takes `(h-1)/2` ticks to reach the top or the bottom, and `(w-1)/2` ticks to reach the left or right border. As soon as we find a `H` on the top, we put a fire at `(h-1)/2` cases on its left. In `(h-1)/2` ticks, an `F` will be there and it may also "burn" other `H`s. The same applies for the left and right borders.

The solution is not optimal because:

* there are some edge cases, in particular when a fire will burn two borders of the field.
* considering top and bottom borders before right and left borders is not necessarily the best solution
* going from left to right and top to bottom to find a `H` is not necessarily the best solution.

---
Tags: code-golf, ascii-art, grid
---


title: Unfurl a string

text:
# Question
Title: Unfurl a string
Given a square string, produce all the output for the string at every stage of unfurling.

The string must unfurl in a clockwise direction one quarter turn at a time.

## Examples

**Input**:

```
A

```

**Output**:

```
A

```

***Note**: I'll also accept the input duplicated for this particular test case **only** if this helps reduce your byte count.*

**Input**:

```
DC
AB

```

**Output**:

```
DC
AB

  D
ABC

ABCD

```

**Input**:

```
GFE
HID
ABC

```

**Output**:

```
GFE
HID
ABC

   HG
   IF
ABCDE

     IH
ABCDEFG

       I
ABCDEFGH

ABCDEFGHI

```

**Input**:

```
JIHG
KPOF
LMNE
ABCD

```

**Output**:

```
JIHG
KPOF
LMNE
ABCD

    LKJ
    MPI
    NOH
ABCDEFG

       NML
       OPK
ABCDEFGHIJ

          ON
          PM
ABCDEFGHIJKL

            PO
ABCDEFGHIJKLMN

              P
ABCDEFGHIJKLMNO

ABCDEFGHIJKLMNOP

```

## Rules

This is so the shortest code in bytes wins.

* Any reasonable format can be used for I/O assuming it is consistent.
* Spaces must be used to pad the top lines of the output.
* Must be able to handle input of all printable characters (including space: `\x20`-`\x7e`):

```
 !"#$%&'()*+,-./0123456789:;?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
```
* Leading/trailing whitespace is allowed.
* You can assume the string will always be a square.
* All standard loopholes are forbidden.

Inspiration: Write a square program that outputs the number of times it has been “unrolled”.

# Answer
# SOGL V0.12, ~~21~~ ~~20~~ ~~19~~ ~~18~~ 17 bytes

```
ø;[;ο⁴№č▓┼№TJι;jI

```

Try it Here! ( added because this expects input on the stack)

Explanation:

```
ø;[;ο⁴№č▓┼№TJι;jI
ø;               push an empty string below the input           stack with the input GFE,HID,ABC
  [              while [ToS (the array) isn't empty] do       ["", [["G","F","E"],["H","I","D"],["A","B","C"]]]
                                                                stack at the second time looping
   ;               duplicate 2nd from top                     [[[H,G], [I,F], [D,E]], "ABC"]
    ο              wrap it in an array                        [[[H,G], [I,F], [D,E]], ["ABC"]]
     ⁴             duplicate 2nd from top                     [[[H,G], [I,F], [D,E]], ["ABC"], [[H,G], [I,F], [D,E]]]
      №            reverse vertically                         [[[H,G], [I,F], [D,E]], ["ABC"], [[D,E], [I,F], [H,G]]]
       č▓          join the inner arrays (┼ fails otherwise)  [[[H,G], [I,F], [D,E]], ["ABC"], ["DE", "IF", "HG"]]
         ┼         add the 2 parts together                   [[[H,G], [I,F], [D,E]], ["ABCDE", "   IF", "   HG"]]
          №        reverse vertically again                   [[[H,G], [I,F], [D,E]], ["   HG", "   IF", "ABCDE"]]
           T       print that without popping                 [[[H,G], [I,F], [D,E]], ["   HG", "   IF", "ABCDE"]]
            J      take the last line off                     [[[H,G], [I,F], [D,E]], ["   HG", "   IF"], "ABCDE"]
             ι     remove the rest of the array               [[[H,G], [I,F], [D,E]], "ABCDE"]
              ;j   remove the last line of the original array ["ABCDE", [[H,G], [I,F]]]
                I  rotate it clockwise                        ["ABCDE", [[I,H], [F,G]]]

```
> 9 votes

# Answer
# Python 2, ~~209 207 205 203 202 201 200~~ 196 bytes

-4 bytes thanks to @Quelklef!

```
s=input();l=len;k=''.join;exec"print s;s=[x for x in[' '*l(s[0])+k(x[:-1]for x in s[-2::-1])[t::l(s[0])-1]for t in range(l(s[0]))][:-1]+[s[-1]+k(x[-1]for x in s)[-2::-1]]if x.strip()];"*(2*l(s)-1)

```

Try it online!

# Python 2, ~~219 217 215 213 212 211~~ 207 bytes

```
s=input();l=len;k=''.join;exec"print'\\n'.join(s);s=[x for x in[' '*l(s[0])+k(x[:-1]for x in s[-2::-1])[t::l(s[0])-1]for t in range(l(s[0]))][:-1]+[s[-1]+k(x[-1]for x in s)[-2::-1]]if x.strip()];"*(2*l(s)-1)

```

Try it online!

The first one outputs as a list of Strings, the second one outputs as ASCII-art.
> 7 votes

# Answer
# Charcoal, ~~42~~ 35 bytes

```
ＡＥθＳθＷ⊟θ«⪫θ¶ＡＥι⮌⪫Ｅθ§μλωθ⊞υι↙←⮌⪫υωＤ⎚

```

Try it online! Link is to verbose version of code. Edit: Saved 7 bytes mostly by switching from character arrays to strings. Explanation:

```
ＡＥθＳθ

```

Read the input square as an array of strings into the variable `q`.

```
Ｗ⊟θ«

```

While the last string in the array is not empty, remove it.

```
⪫θ¶

```

Print the rest of the array.

```
ＡＥι⮌⪫Ｅθ§μλωθ

```

Rotate the rest of the array by looping through each character of the last string and joining the `l`th character of every remaining string in the reversed array.

```
⊞υι↙←⮌⪫υω

```

Append the previously removed last string to `u`, which holds the unfurled value, and print it.

```
Ｄ⎚

```

Output the result and then clear the canvas ready for the next iteration.

Note that this version outputs the final unfurl on a separate line, if this is undesirable then for 38 bytes:

```
ＡＥθＳθＷ⊟θ«⊞υι←Ｅ⁺⟦⪫υω⟧⮌θ⮌κＡＥι⮌⪫Ｅθ§μλωθＤ⎚

```

Try it online! Link is to verbose version of code. Explanation: `←Ｅ⁺⟦⪫υω⟧⮌θ⮌κ` reverses the current array, prepends the unfurled line, then reverses the characters in each line, then prints everything upside-down, thus producing the desired result.
> 4 votes

# Answer
# Haskell, ~~127~~ 120 bytes

```
e=[]:e
i#[x]=[]
i#s|t<-foldl(flip$zipWith(:))e$init s,j<-i++last s=(map((j>>" ")++)(init t)++[j++last t]):j#t
f s=s:""#s

```

Try it online!

Input is a list of lines, e.g. `["DC","AB"]` for the second test case, output is a list of lists of lines: `[["DC","AB"],[" D","ABC"],["ABCD"]]`. Use `mapM (putStrLn . unlines)` to pretty-print the result.

**Edit:** Saved 7 bytes by noticing that the shorter `transpose` I found some while a go comes in handy because it can be modified to reverse each transposed directly.
> 3 votes

# Answer
# 05AB1E, 18 bytes

```
[Dí.Bí»,¤UR¦ζŽ`Xì)

```

Try it online!

**Explanation**

```
[            Ž       # while stack is not empty, do:
 D                   # duplicate current list
  í                  # reverse each element
   .B                # pad with spaces to equal length
     í               # reverse each element again
      »,             # join with newlines and print
        ¤U           # store the last element in X
          R¦         # reverse the list and remove the first element
            ζ        # zip with spaces as filler
              `      # split elements separately to stack
               Xì    # prepend X to the last element
                 )   # join the stack to a list

```
> 2 votes

# Answer
# J, 62 bytes

```
|."1@([:(#~[:-.[:*/"1' '=])|.@{:(}:@],{:@],[)|:@}:)^:(1<#)^:a:

```

Try it online!

I'm sure this can be golfed a lot. This prints extra whitespace, but only because of the way that J formats the arrays contained within the outputted array to have the same shape.

I think once I go in and comment out exactly what I'm doing, I might get a better idea of how to golf this (having done that now, I don't really know...). For purposes of golfing, it's worth noting that

* I have to special case 1 row inputs (the while part of the loop)
* I have to eliminate all lines consisting solely of whitespace (surely there must either be a builtin for this or a better way to do it), which is the filter near the end
* There are a lot of caps, identity functions, and atops

# Explanation

In ungolfing this, I'll be splitting the main function in three.

```
unfurl_reversed   =. |.@{: (}:@] , {:@] , [) |:@}:
whitespace_filter =. #~ [: -. [: */"1 ' ' = ]
unfurl            =. |."1@(whitespace_filter @: unfurl_reversed) ^: (1 < #) ^: a:

test_case         =. 3 3 $ 'GFEHIDABC'

```

We'll be working with the second test case.

### unfurl\_reversed

```
|.@{: (}:@] , {:@] , [) |:@}:

```

This gives one the string unfurled once, but in reverse. All of this is being done in reverse and in a specific order so that the way J automatically pads strings with spaces to match the shape of the array they're in will give the right spacing.

`|:@}:` is the transpose of the curtail of the input

```
   |:@}: test_case
GH
FI
ED

```

`|.@{:` is the reverse of the tail of the input

```
   |.@{: test_case
CBA

```

I think you can see what we want to do: we want to append the reverse of the tail to the last part of the transpose of the curtail (that's a mouthful, but basically attach `CBA` to the end of `ED`). This will give us one step of unfurling, reversed.

`(}:@],{:@],[)` does just that.

It appends `CBA` to `ED`, then joins that with the rest of the array. Our output therefore is

```
   unfurl_reversed test_case
GH
FI
EDCBA

```

### whitespace\_filter

```
#~ [: -. [: */"1 ' ' = ]
                 ' ' = ]  Equate each element to space
            */"1          Product of each row (all true?)
      -.                  Negate
#~                        Filter rows that are true

```

Basically, this tests to see if any row is completely spaces, and removes it if it is. It doesn't do anything for the first iteration of the test case.

This is necessary (at least until I find an alternative) since otherwise we'll eventually be unfurling whitespace into our output string.

### unfurl

```
|."1@(whitespace_filter @: unfurl_reversed) ^: (1 < #) ^: a:

```

Unfurl basically puts the other functions together and special cases single character inputs.

When the power of verb (`^:`) is given the empty box (`a:`), it applies a function on an input until it converges and collects the results in an array.

`(1 < #)` checks that the rows are always greater than 1 (to special case 1 row inputs).

`|."1` reverses each row, so it inverts the results of `whitespace_filter @: unfurl`.
> 2 votes

# Answer
# Perl 5, 155 bytes

```
$"=$,;@a=map[/./g],<>;while(@a){say' 'x(length$s)."@$_"for@a[0..@a-2];say$s.="@{pop@a}";say@b=();for$i(0..$#a){$q=0;$b[$q++][$#a-$i]=$_ for@{$a[$i]}}@a=@b}

```

Try it online!

Saved a few bytes without really modifying the logic. The flow below is still basically correct.

~~\# Perl 5, 163 bytes~~

```
$"=$,;@a=map[/./g],<>;while(@a){say' 'x(length$s)."@{$a[$_]}"for 0..@a-2;say$s.="@{pop@a}";say@b=();for$i(0..$#a){$b[$_][$#a-$i]=$a[$i][$_]for 0..$#{$a[$i]}}@a=@b}

```

Try it online!

**How?**

```
$"=$,; #set the array output separator to null
@a=map[/./g],<>;   # take the input as a 2-D array @a
while(@a){         # repeat while there are still things to unfurl
  say' 'x(length$s)."@{$a[$_]}"for 0..@a-2; # output all but last
                                            # line of the remaining
                                            # square
  say$s.="@{pop@a}";  # remove bottom row, add it to the unfurled string $s
                      # and output it
  say@b=();           # clear temporary array; output empty array, causing
                      # a newline to output

                      # rotate remaining shape 90 degrees:
  for$i(0..$#a){$b[$_][$#a-$i]=$a[$i][$_]for 0..$#{$a[$i]}}
  @a=@b               # replace input with rotated array
}

```
> 1 votes

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

```
a=input()
while 1:print'\n'.join(a);b=map(''.join,zip(*map(str.strip,a[-2::-1])));a[-1]+=b.pop();a[:-1]=[len(a[0])*' '+x for x in b]

```

Try it online!

In each iteration, `b` is the “head” of the string (first n−1 rows), rotated 90 degrees: if `a` is `[" NML", " OPK", "ABCDEFGHIJ"]` then `b` is `["ON", "PM", "KL"]`.

To unfurl a string once, we append the final line of `b` to `a[-1]` (giving `"ABCDEFGHIJKL"`) and then recompute `a[:-1]` by adding spaces to the rest of the strings in `b`.

We terminate by attempting to pop from `b` when it’s empty.

# Python 2, 132 bytes

```
a=input()
while 1:s=str.strip;print'\n'.join(a);a[:-1]=[len(a[0])*' '+''.join(x)for x in zip(*map(s,a[-2::-1]))];a[-1]+=s(a.pop(-2))

```

Try it online!

Same idea, written differently. We terminate by attempting to `a.pop(-2)` when `a` has only one element.
> 1 votes

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


title: Sequence Without Sevens

text:
# Question
Title: Sequence Without Sevens
This challenge is based on a drinking game. I advise against alcohol consumption while programming.

In this game, the players count up in turns: the first player says `1`, the second says `2` and so on. Here's the twist however: each number that **is divisible by 7 or has a 7 in its digits** (in base 10) is replaced by another counter. This means `7` is replaced by `1`, `14` is replaced by `2`, `17` is replaced by `3` and so on. For this "sub-sequence", the same rules apply! `35` would be replaced by `7`, which in turn is replaced by `1`. This process repeats until the number is "valid".

Here's a visualization of the first 100 numbers in the sequence:

```
n = 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 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 91 92 93 94 95 96 97 98 99 100
gets replaced by:
                1                  2        3           4                 5  6                    7     8              9             10    11                   12 13                14          15       16 17 18 19 20 21 22 23 24 25             26       27          28                29 30
gets replaced by:
                                                                                1                                                                                2                       3           4                                   5           6

final sequence:
    1 2 3 4 5 6 1 8 9 10 11 12 13  2 15 16  3 18 19 20  4 22 23 24 25 26  5  6 29 30 31 32 33 34  1 36  8 38 39 40 41  9 43 44 45 46 10 48 11 50 51 52 53 54 55 12 13 58 59 60 61 62  2 64 65 66 15 68 69 16  3 18 19 20  4 22 23 24 25 80 81 82 83 26 85 86  5 88 89 90  6 92 93 94 95 96 29 30 99 100

```

In the final sequence, no number has a seven in its digits or is divisible by seven.

## Input description

* An integer `n` (`1 <= n <= 7777` or `0 <= n <= 7776`)

You may choose whether you use a 0-indexed or 1-indexed input.

## Output description

* The `n`th number in the sequence

## Examples

The examples are 1-indexed. For 0-indexed, subtract one from `n`.

```
n   ->   f(n)
1        1
5        5
7        1
35       1
77       23
119      1
278      86
2254     822
2255     2255
7777     3403

```

## Scoring

This is , so shortest answer in bytes wins!

# Answer
# Java, ~~122~~ ~~121~~ ~~98~~ 97 bytes

```
int c(int n){int a=0,b=0,c=n;for(;n-->0;c+=a=((--b+"").indexOf(55)&b%7)>>31);return a<0?-b:c(c);}

```

-23 bytes thanks to *@Nevay*.
-1 byte thanks to *@Neil*.

**Explanation:**

Try it here.

```
int c(int n){                            // Method with integer as parameter and return-type
  int a=0,                               //  Flag integer
      b=0,                               //  Regular counter
      c=n;                               //  7-counter
  for(;n-->0;                            //  Loop over the input
    c+=                                  //   Append `c` with:
       a=                                //    Set `a` to:
         ((--b+"").indexOf(55)&b&7)      //     If `b` is divisible by or contains 7:
                                         //     (and decrease `b` by 1 in the process)
                                   >>31  //      Bitwise right shift so `a` is either `-1` or `0`
  );                                     //  End of loop
  return a<0?                            //  If `a` is now -1:
    -b                                   //   Return the regular counter `b` (as positive)
   :                                     //  Else:
    c(c);                                //   Recursive call with 7-counter `c` as input
}                                        // End of method

```
> 7 votes

# Answer
# Python 3, 77 bytes

```
g=lambda a:a%7<1or'7'in str(a)
f=lambda a:g(a)and f(sum(map(g,range(a))))or a

```

Try it online!
> 6 votes

# Answer
## JavaScript (ES6), ~~72~~ 69 bytes

```
f=
n=>[...a=Array(n)].reduce(_=>a[++i]=i%7>7*/7/.test(i)?i:a[++j],i=j=0)
```

```
<input type=number min=1 oninput=o.textContent=f(+this.value)><pre id=o>
```

Edit: Saved 3 bytes thanks to @Shaggy.
> 5 votes

# Answer
# JavaScript, ~~79~~ 75 bytes

*2 bytes saved thanks to Shaggy*

```
f=a=>(z=a=>a%7<1|/7/.test(a))(a)?f([...Array(a)].reduce(a=>a+z(b++),b=0)):a

```

Try it online!
> 3 votes

# Answer
# Röda, 65 bytes

```
f a{f#[seq(1,a)|[1]if g _]if g a else[a]}g a{[a%7<1 or"7"in`$a`]}

```

Try it online!

A port of Leaky Nun's Python answer.
> 2 votes

# Answer
# 05AB1E, ~~26~~ 23 bytes

```
LÐ7Ösε7å}~_*[¤0Ê#D_O£]¤

```

Try it online!

**Explanation**

```
L                         # push range [1 ... n]
 Ð                        # triplicate
  7Ö                      # check if number in one copy for equality to 0 after mod by 7
    sε7å}                 # check each number in one copy if they contain 7
         ~_               # OR these 2 lists and invert
           *              # multiply with the range,
                          # giving a list with 0s where the numbers need to be replaced
            [¤0Ê#    ]    # loop until the last number in the list is not 0
                 D        # duplicate the list
                  _       # invert it,
                          # giving a list with 1s for the numbers that need to be replaced
                   O      # sum
                    £     # take these many elements from the list
                      ¤   # RESULT: push the last element of the list

```

**Previous 26 byte solutions**

```
>GNN7ÖN7å~Dˆ[_#¯s£OÐ7Ös7å~
>G1UN[Ð7Ös7å~XiDˆ}_#¯s£O0U

```
> 2 votes

# Answer
# C (gcc), ~~104~~ ~~98~~ 95 bytes

*-6 bytes by getting rid of sprintf+index and looking manually for a 7 in an integer's digits*
*-3 bytes using the deprecated POSIX bzero instead of memset*

A function writing the result in the global variable `r`. Usage: `l(<int>)`

Result is 1-indexed.

```
r,o[9];b(i,s){for(r=s=++o[i];s&&s%10^7;s/=10);r%7&&!s?:b(i+1);}l(f){for(bzero(o,36);f--;b(0));}

```

Try it online!

Explanation:

```
/*
  r = value of the nth element
  o = array of counters (o[0] == main counter)
 */
r,o[9];

// Recursive function, "i" is the counter index
// "s" is used to determine if an int contain a 7 digit
b(i,s){
  /*
    1. Increases the value of the counter
    2. Stores the result into r and s
    3. Divide s by 10 until it is equal to 0 or its remainder is 7
   */
  for(r=s=++o[i];s&&s%10^7;s/=10);

  /*
    if:
      r%7 (r modulo 7) AND it contains no 7 digit
    then:
      nothing
    else:
      calls b with the next counter index
   */
  r%7&&!s?:b(i+1);
}

// Main function: initializes counters and plays
// the sequence until the nth member is calculated
l(f){
  for(bzero(o,36);f--;b(0));
}

```
> 2 votes

# Answer
# Mathematica, 57 bytes

```
Last[i=1;If[DigitCount[#,10,7]>0||7∣#,i++,#]&~Array~#]&

```
> 2 votes

# Answer
# Pyth, 36 bytes

```
L?!hbbhx.f|/`Z`7!%Z7b)b;WnyyQyQ=yQ;Q

```

Fixed completely, but is now an unholy mess of letters and can certainly be golfed quite a bit.

1-indexed
> 2 votes

# Answer
## J, 52 bytes

```
i=:('7'&e.@":+.0=7&|)"0
f=:]`(#@}.@I.@:i@i.@>:)@.i^:_

```

Result is 1-indexed. Using it is pretty straightforward:

```
f 7777

```

Try it online!
> 1 votes

# Answer
# Perl 5, 52 + 1 (-p) = 53 bytes

```
map{$s=0;do{$\=++$c[$s++]}until$\!~/7/&&$\%7}1..$_}{

```

Try it online!

**How?**

`@c` is an array of counters. `$c[0]` holds the main counter that determines which element we're working on. Each successive element holds another counter that is only accessed when the previous one contains a 7 or is divisible by 7.

```
map              # Loop to find the appropriate element
  $s=0;          # reset index of counters
  do{            # looping through the counters
    $\=++c[$s++] # increment the counter and the index; $\ is our output variable
  }until         # don't quit until
       $\!~/7/   # the result has no 7s
       &&$\%7    # and is indivisble by 7
}1..$_           # do this until the input is reached
}{  # close the implicit loop created by the -p flag and force output of $\

```

~~\# Perl 5, 64 + 1 (-p) = 65 bytes~~

```
while($c[0]<$_){$s=0;do{$\=++$c[$s++]}while($\=~/7/||$\%7==0)}}{

```

Try it online!
> 1 votes

---
Tags: code-golf, number, sequence, counting
---


title: Stream of Letters to Words

text:
# Question
Title: Stream of Letters to Words
Given a string containing only letters (case-insensitive), split it into words of uniformly random lengths, using the distribution below, with the exception of the last word, which can be of any valid length (1-10). Your output is these words, as a space-separated string (`"test te tests"`), an array of strings (`["test","te","tests"]`), or any other similar output format.

## Word Length Distribution

```
Word Length - Fractional Chance / 72 - Rounded Percentage
1 - 2 / 72 - 2.78%
2 - 14 / 72 - 19.44%
3 - 16 / 72 - 22.22%
4 - 12 / 72 - 16.67%
5 - 8 / 72 - 11.11%
6 - 6 / 72 - 8.33%
7 - 5 / 72 - 6.94%
8 - 4 / 72 - 5.56%
9 - 3 / 72 - 4.17%
10 - 2 / 72 - 2.78%

```

Your odds do not need to match exactly - they can be off by `1/144`th, or `.69%`, in either direction (but obviously they still must sum up to `72/72` or `100%`).

Data roughly guessed from the fourth page, first figure of this paper.

# Test Cases with Sample Output

Behavior on very short (length \< 11) test cases is undefined.

Note that I created these by hand, so they may or may not follow the uniform distribution above.

```
abcdefghijklmnopqrstuvwxyz
abcd efgh i jklmnopq rs tu vwx yz

thequickbrownfoxjumpedoverthelazydog
t heq uick brown fo xj ump edo vert helazydog

ascuyoiuawerknbadhcviuahsiduferbfalskdjhvlkcjhaiusdyfajsefbksdbfkalsjcuyasjehflkjhfalksdblhsgdfasudyfekjfalksdjfhlkasefyuiaydskfjashdflkasdhfksd
asc uyoi uawer k nb a dhcviua hsid ufe r bfa lskd jhv lkcj haius dy faj se fbks dbfkals jcuyasjehf lkjh falk sd blhsgdf asudyfekjf alk sdjfhlk asefyu iaydskfja shdflk as dhf ksd

```

This is , so shortest answer in bytes wins.

# Answer
> 5 votes
# Jelly, 28 bytes

```
“¤Œæ×¿®¬©¥¤‘Jẋ"$FẋLẊ‘1¦+\Ṭœṗ

```

A monadic link taking a list and returning a list of lists.

**Try it online!** (the footer separates the resulting list of lists with spaces)

### How?

Uses all the percentages in the distribution rounded to their nearest integer (thus being within the 0.69% allowed thresholds).

```
“¤Œæ×¿®¬©¥¤‘Jẋ"$FẋLẊ‘1¦+\Ṭœṗ - Link: list (of characters), s
“¤Œæ×¿®¬©¥¤‘                 - code page indexes = [3,19,22,17,11,8,7,6,4,3]
               $             - last two links as a monad:
            J                -   range of length = [1, 2, 3, 4, 5,6,7,8,9,10]
              "              -   zip with:
             ẋ               -     repeat list = [[1,1,1],...,[9,9,9,9],[10,10,10]]
                F            - flatten (into one list of length 100)
                  L          - length of s
                 ẋ           - repeat list (one list of length 100*length(s) with the
                             -              correct distribution of integer lengths)
                   Ẋ         - shuffle
                      ¦      - sparse application of:
                    ‘        -   increment
                     1       -   to indexes: 1 (offset indexes for the partition below)
                        \    - cumulative reduce by:
                       +     -   addition (e.g. [4,4,7,1,...] -> [4,8,15,16,...])
                         Ṭ   - untruth (yield a list with 1s at those indexes (1 indexed)
                          œṗ - partition s at truthy indexes (note: excess ignored)

```

# Answer
> 4 votes
# PHP, 94 bytes

```
for(;$c=$argn[$k++];print$c." "[--$e])if(!$e)for($r=rand(0,71);$r>ord(x^"ywgSKAF:=?"[$e++]););

```

Run as pipe with `-nR` or try it online.

**breakdown**

```
for(;$c=$argn[$i++];            # loop $c through string
    print$c                         # 2. print current character,
        ." "                        # 4. if remaining length is 0, print space
        [--$e]                      # 3. decrement remaining length
    )
    if(!$e)                         # 1. if remaining length is 0,
        for($r=rand(0,71);              # get random value from 0 to 71
            $r>ord(x^"ywgSKAF:=?"[$e++])    # and increment $e while $r is > probability
        ;);

```

Note: `ywgSKAF:=?` represents the increasing probabities -1: `[1,15,31,43,51,57,62,66,69,71]`

# Answer
> 3 votes
# Octave, 108 bytes

```
@(s)mat2cell(s,1,[k=(w=repelems(1:10,[1:10;'AMOKGEDCBA'-63])(randi(72,1,n=nnz(s))))(cumsum(w)<=n) n-sum(k)])

```

Try it online!

\*Takes the string as input and outputs an array of strings.

\*The last element of the output may be an empty string.

# Answer
> 3 votes
## Python 2, 154 150 147 145 bytes

Allright, this is my first attempt on code golf. Straight up with the code:

```
import numpy.random as r
def f(s):
 i=0
 while i<len(s):
    i+=r.choice(11,p=[x/72. for x in [0,2,14,16,12,8,6,5,4,3,2]])
    s=s[:i]+' '+s[i:]
    i+=1
 return s

```

The second indent is by a tab char as you can see in my TIO version: Try it Online.

What I do is adding a space in the string according to the given distribution. I veryfied my distribution by using:

```
import collections
dist = r.choice(11,100000,p=[x/72. for x in [0,2,14,16,12,8,6,5,4,3,2]])
print collections.Counter(dist)

```

Which gave me:

```
Word Length - Rounded Percentage as asked - Rounded Percentage as counted
1 - 2.78% - 2.794%
2 - 19.44% - 19.055%
3 - 22.22% - 22.376%
4 - 16.67% - 16.638%
5 - 11.11% - 11.246%
6 - 8.33% - 8.362%
7 - 6.94% - 7.063%
8 - 5.56% - 5.533%
9 - 4.17% - 4.153%
10 - 2.78% - 2.780%

```

Which I think is correct enough. I then repeat that process of adding a space until the length of my string is succeeded. I also increment my position index by one after adding a space. I hope someone can help me golf this line out but I did not see how to get it out without falsifying the first space.

As I see my text I recognice that I have to learn alot about this Site. Could someone link me a guide how to use the Stackoverflow answer function in the comments so I can learn for my next posts.

---

Edit:

Apperently while rereading my post I did figure out a way to get rid of the i+=1. So i saved 4 bytes by doing that. The new code looks like this:

```
import numpy.random as r
def f(s):
 i=-1
 while i<len(s):
  i+=r.choice(11,p=[x/72. for x in[0,2,14,16,12,8,6,5,4,3,2]])+1
  s=s[:i]+' '+s[i:]
 return s

```

Try it online!

---

Edit:

I figured out that i can remove some linebreaks.

```
import numpy.random as r
def f(s):
 i=-1
 while i<len(s):i+=r.choice(11,p=[x/72. for x in[0,2,14,16,12,8,6,5,4,3,2]])+1;s=s[:i]+' '+s[i:]
 return s

```

---

Edit: I modyfied my import and placed the definition of i inside the function.
```
from numpy.random import*
def f(s,i=-1):
 while i<len(s):i+=choice(11,p=[x/72. for x in[0,2,14,16,12,8,6,5,4,3,2]])+1;s=s[:i]+' '+s[i:]
 return s

```

Try it online!

# Answer
> 2 votes
# Dyalog APL, 90 bytes

```
{k←⍵⋄{' '~⍨(2⊃⍵)↓k↑⍨⊃⍵}¨(↓(o[1;2]),0),↓o←1↓⍉2(1-⍨≢⍵)⍴+\((2 14 16 12 8,⌽1+⍳5)\⍳10)[72?⍨≢⍵]}

```

Try it online! Hit Run a few times to see how it changes.

**How?**

`72?⍨≢⍵` \- roll 72 sided dice length of input times

`[...]` \- index inside

`(2 14 16 12 8,⌽1+⍳5)\⍳10` \- expand range of 10 by `2 14 16 12 8 6 5 4 3 2` (to create weighted random)

`+\` \- cummulative sum

`⍉2(1-⍨≢⍵)⍴` \- shape as a zipped table `x y z``z x, x y, y z`

`o←1↓` \- drop first element

`(↓(o[1;2]),0),↓o` \- encase with its first coordinate paired with 0

`¨` \- for each pair (x, y)

`(2⊃⍵)↓k↑⍨⊃⍵` \- take input from index x to y

`' '~⍨` \- and remove spaces

# Answer
> 2 votes
# Python 2, 155 bytes

```
from random import*
def f(s):
 i=sum([[i+1]*[2,14,16,12,8,6,5,4,3,2][i]for i in range(10)],[])[randint(0,71)]
 return s if len(s)<11else s[:i]+' '+f(s[i:])

```

Try it online!

# Answer
> 2 votes
# Mathematica, 164 bytes

```
(s=Length[c=Characters@#];t=0;l={};While[t<s,If[t+(r=RandomChoice[{2,14,16,12,8,6,5,4,3,2}->Range@10])<=s,l~AppendTo~r];t=Tr@l];""<>#&/@FoldPairList[TakeDrop,c,l])&

```

takes a string as input
outputs array of strings

# Answer
> 2 votes
# Charcoal, ~~43~~ 39 bytes

```
ＦθＦ⁺¹Ｉ‽⪫Ｅχ×Ｉκ⌕α§”v↷£o8″!”κω⊞υ⎇κω Ｆθ⁺ι⊟υ

```

Try it online! Link is to verbose version of code. Outputs a trailing space if the last word was the exact size randomly chosen.

# Answer
> 2 votes
# Perl 5, 107 bytes

```
@B=((1,10,9,5,2)x2,(2,3,4)x12,(5,6)x6,7,(3,7,8)x4,9);while(10<length){$i=$B[rand 72];s/.{$i}//;print"$& "}

```

Try it online!

106 bytes of code +1 for -p

# Answer
> 1 votes
# Ruby, 96+1 = 97 bytes

Uses the `-p` flag.

```
i=0
m=[3,19,22,17,11,8,7,6,4,3].flat_map{|k|[i+=1]*k}
i=0
$_[i-1,0]=' 'while~/$/+1>i+=1+m.sample

```

Try it online!

# Answer
> 1 votes
# \>\<\>, ~~168~~ 152 bytes

```
<v?(0:i
~/<r
/x\/oo \
012\oo~\!/ !ox\
\v/:1=?^?\ooo>>
 x^
v\:1\/>> o
|/o\=\x^!/
voo/? >x
v\o~/ v_
>" "\?\x>xoo\
^oooooo<<< \
^.22/ \>x!/xv
^ooooooo_o<<<

```

Try it online, or watch it at the fish playground!

Randomness is tricky in \>\<\>: there's only one random instruction, `x`, which sets the fish's direction to either up, down, left or right. This is a complicated program, so here's a colour-coded diagram to help you:

I tried to split up the probabilities into chunks so that the probabilities within and between the chunks were fairly simple (preferring, say, 1/3 to 25/72). I did this as follows:

The fish starts at the grey bit of the code (**X**). This is fairly standard \>\<\> code to read in all of the input. It gets more interesting, so let's move on.

Next, the fish comes to the light and dark green sections (**Y**). You may notice from the probability tree that the three major branches each sum to 1/3, and that each of these branches splits into a 2/3 sub-branch and a 1/3 sub-branch. The green sections of code cover these two levels of the tree. First, we pick a random number out of 0, 1, 2 with equal chance of each, in the top lobe of the light green bit. We can simulate a 1/3 chance using the four-way instruction `x` by cutting off one of the exits so that it just redirects the fish back to the `x` — then there are only three escape routes from the `x`, and by symmetry they have equal probabilities.

The next `x`, a little below this one, sends the fish to the `^` next to it with 2/3 chance — note that the fish wraps around if it swims left from the `x` — and down to a `\` with 1/3 chance. The fish then swims along one of the two tails of the light green section. These tails are functionally the same: each checks if we pushed 0, 1 or 2 earlier, and branches out accordingly. And this completes the first two levels of the tree.

The next six sections (**A****F**), in essence, use more `x`s to branch the fish further, and then use some number of `o`s to print a number of letters from the input. These sections range from straightforward (e.g. dark blue, **C**, which just prints three letters) to, well, not so straightforward (e.g. orange, **D**, which needs two `x`s to simulate a 3/8–5/8 split, printing letters in multiple stages). The details of these are left as an exercise. (I'm particularly pleased with yellow, **E**, which sends the fish in a loop-the-loop!)

After each of these branches, the fish ultimately reaches the pink section (**Z**). This draws all the branches back together, prints a space, then finally makes the fish jump to position (2,2) in the grid and start again at the first `x`.

---

In case the "it's complicated" explanation above doesn't convince you that this gives the correct probabilities, I also tested this on a length 65,000 input string (64 KiB, only 13 seconds in TIO!), and the resulting distribution of word lengths was

```
{{1,0.027377},{2,0.191237},{3,0.226599},{4,0.164128},{5,0.113064},{6,0.0818627},{7,0.0703885},{8,0.0543515},{9,0.0426089},{10,0.0283835}}

```

These probabilities are at most 0.0044 away from the expected probabilities.

---
Tags: code-golf, string, natural-language
---


title: Who will win Ghost?

text:
# Question
Title: Who will win Ghost?
The game of Ghost is played between two players who alternate saying a letter on each turn. At each point, the letters so far must start some valid English word. The loser is the player to complete a full word first. So, for example, if the letters so far are E-A-G-L, then the only valid next letter to say is "E" and so the next player will lose. (Even though there are longer words such as "eaglet".)

## The challenge

You are to write a program or function to determine, given the letters so far, who will win assuming two perfect players. The input is a string representing the current state of the game, and a list of strings representing the dictionary of valid words. The output should distinguish whether the next player to go will win or lose.

## Details

* The code must handle the case where the current state is empty. However, you may assume no word in the dictionary is empty.
* You may assume that each input string consists only of lowercase ASCII letters, i.e. a-z.
* You may assume the current state and all words in the dictionary have at most 80 characters each.
* The dictionary is guaranteed to be nonempty (to avoid the case where there is no valid first move).
* You may assume the "current state" will be valid: there will necessarily be some word starting with the current state; also, the current state will not be a full word, nor will any prefix of the current state be a full word.
* The dictionary will be prefiltered according to the rules of which "English words" are considered to be valid for the game - so for example, for a variant in which words of three or fewer letters don't end the game yet, the dictionary will be prefiltered to include only the words of four or more letters.
* You may assume the dictionary will be presorted.

## Examples

Suppose the dictionary is:

```
abbot
eager
eagle
eaglet
earful
earring

```

Then for the following current states, the output should be as follows:

```
Current state   Result
=============   ======
                loss
a               win
eag             win
eagl            loss
ear             win
earf            win
earr            loss

```

Likewise, for the word list at https://raw.githubusercontent.com/dschepler/ghost-word-list/master/wordlist.txt (produced on a Debian system using `pcregrep '^[a-z]{4,80}$' /usr/share/dict/american-english`) here is a possible session:

```
Current state   Result
=============   ======
                win
h               loss
ho              win
hoa             loss
hoar            win
hoars           loss

```

(And then the next move completes "hoarse".)

## Scoring

This is : Shortest program in bytes for each programming language wins.

# Answer
> 3 votes
# JavaScript, 54 bytes

```
l=>g=w=>!(w+0)||l.some(t=>t==w||!g(t.match(`^${w}.`)))

```

call it like this: f(wordlist\_as\_array)(current\_word\_as\_string), it return true for win, false for lose.

quite bad performance T\_T , only work with the small test case.

```
f=
l=>g=w=>!(w+0)||l.some(t=>t==w||!g(t.match(`^${w}.`)))
```

```
<p><label>Word List:<br/><textarea id="wl"></textarea></label></p>
<p><label>Current:<input type="text" id="c" /></label></p>
<p><button onclick="out.textContent = f(wl.value.split('\n'))(c.value)">Check</button></p>
<p>Result: <output id="out"></output></p>
```

# Answer
> 1 votes
# Python 3, 135 129 84 bytes

-4 bytes thanks to Mr. Xcoder!

-42 bytes thanks to Daniel Schepler!

```
g=lambda s,l:(s in l)or-min(g(w,l)for w in{w[:len(s)+1]for w in l if w[:len(s)]==s})

```

Try it online!

A `1` indicates the current player will win, whereas a `-1` indicates they will lose.

# Answer
> 1 votes
# PHP, ~~192 154 100~~ 98 bytes

```
function t($w,$d){foreach(preg_grep("#^$w#",$d)as$p)if($p==$w||!t($w.$p[strlen($w)],$d))return 1;}

```

function returns `1` for win, `NULL` for loss.
Call with `t(string $word,array $dictionary)` or try it online.

**breakdown**

```
function t($w,$d)
{
    // loop through matching words
    foreach(preg_grep("#^$w#",$d)as$p)if(
        $p==$w                      // if word is in dictionary (previous player lost)
        ||                          // or
        !t($w.$p[strlen($w)],$d)    // backtracking is falsy (next player loses)
    )
        return 1;                   // then win
    // implicit return NULL
}

```

# Answer
> 0 votes
# C++, 243 bytes (noncompetitive)

FYI, here's the golfed version of my reference implementation (marked as noncompetitive since it's my own challenge). It expects the word list in the `w` parameter to be a null-terminated array (of null-terminated strings). It returns `1` if the next player will lose, or `0` if the next player will win.

```
#define r return
int g(char*s,char**w){struct N{int d=0;N*c[128]{};int l(){if(d)r 0;for(N*p:c)if(p&&p->l())r 0;r 1;}void a(char*s){*s?(c[*s]?:c[*s]=new N)->a(s+1),0:d=1;}N*f(char*s){r*s?c[*s]->f(s+1):this;}}d;for(;*w;d.a(*w++));r d.f(s)->l();}

```

Try it online.

Expanded and commented version:

```
int g(char* s, char** w) {
    /// Node of the prefix tree
    struct N {
        int d = 0;  ///< 1 if the node represents a word in the dictionary
        N* c[128] {};  ///< child nodes, indexed by integer value of character

        // Optional, if you want to eliminate the memory leak from the
        // golfed version.  (Though actually in practice, I would make
        // "c" into std::array<std::unique_ptr<N>, 128> so the default
        // destructor would be sufficient.)
        // ~N() { for (N* p : c) delete p; }

        /// \retval 1 if the next player going from this node will lose
        /// \retval 0 if they will win
        int l() {
            if (d)
                return 0;  // last player lost, so the player who would
                           // have gone next wins
            for (N* p : c)
                if (p && p->l())
                    return 0;  // found a letter to play which forces the
                               // other player to lose, so we win
            return 1;  // didn't find any such letter, we lose
        }

        /// Add word \p s under this node
        void a(char* s) {
            *s ?
                (c[*s] ?: c[*s] = new N) // use existing child node or create new one
                ->a(s+1), 0  // the ,0 just makes the branches of
                             // the ternary compatible
            :
                d = 1;
        }

        /// Find node corresponding to \p s
        N* f(char* s) {
            return *s ?
                c[*s]->f(s+1)
            :
                this;
        }
    } d;  // d is root node of the prefix tree

    // Construct prefix tree
    for (; *w; d.a(*w++))
        ;

    // Find node for input, then run the "loser" method
    return d.f(s)->l();
}

```

---
Tags: code-golf, decision-problem, game
---


title: How many states do I border?

text:
# Question
Title: How many states do I border?
When I was younger, I had a big map of the US tacked up on my wall across from my bed. When I was bored, I would stare at that map and think about stuff. Stuff like the four-color-theorem, or which state bordered the most other states. To save younger me some brainpower in counting, you are going to ~~invent a time machine and~~ tell me how many states border the input. Because time is finicky, this needs to be as short as possible.

# The Task

Given one of the 50 US states, either by its full name or by its postal abbreviation, as found on this page (archive.org mirror), return the number of states it borders. The following is a mapping of all inputs for full state names to the number of states adjacent, found on this website.

```
Missouri, Tennessee -> 8
Colorado, Kentucky -> 7
Arkansas, Idaho, Illinois, Iowa, Nebraska, New York, Oklahoma, Pennsylvania, South Dakota, Utah, Wyoming -> 6
Arizona, Georgia, Massachusetts, Michigan, Minnesota, Nevada, New Mexico, Ohio, Virginia, West Virginia -> 5
Alabama, Indiana, Kansas, Maryland, Mississippi, Montana, North Carolina, Oregon, Texas, Wisconsin -> 4
California, Connecticut, Delaware, Louisiana, New Hampshire, New Jersey, North Dakota, Rhode Island, Vermont -> 3
Florida, South Carolina, Washington -> 2
Maine -> 1
Alaska, Hawaii -> 0

```

# The Rules

* Your program can either handle the full state name or the postal code - it cannot use a combination.
* You can specify the case of the input, but you cannot remove whitespace in the input.
* You do not have to handle Washington, D.C., or anything that is not one of the 50 states.
* The number of states bordered does **not** include the input state.
* This is , so shortest answer in bytes wins.

While I know this may just be whoever has the best compression or finds the best regex pattern per number, if I get too many of those answers, I'll award a bounty to an answer that generates a map of the US and uses that to calculate the number of bordering states.

# Answer
> 17 votes
# Jelly, ~~73~~ 65 bytes

```
“U[“Ȥ“!÷2“®Ɓ⁵]StƁ}K“ʂÞiƬ¦.ÞrÆu“4œ(°fWg?Ʋd“Ɠ©“Œb‘i³OS%168¤$€Tµ’6L?

```

Try it online!

Builtins? Who needs those? (`ʂÞiƬ` on the ground in disgust).

Takes input as full name, such as `"Idaho"`.

**How it Works**

```
“U[“Ȥ“!÷2“®Ɓ⁵]StƁ}K“ʂÞiƬ¦.ÞrÆu“4œ(°fWg?Ʋd“Ɠ©“Œb‘i³OS%168¤$€Tµ’6L?
“U[“Ȥ“!÷2“®Ɓ⁵]StƁ}K“ʂÞiƬ¦.ÞrÆu“4œ(°fWg?Ʋd“Ɠ©“Œb‘                   The literal list of code-page index lists  [[85, 91], [154], [33, 28, 50], [8, 143, 133, 93, 83, 116, 143, 125, 75], [167, 20, 105, 152, 5, 46, 20, 114, 13, 117], [52, 30, 40, 128, 102, 87, 103, 63, 153, 100], [147, 6], [19, 98]]
                           €        On each sublist:
                         ¤            Evaluate the hash value:
                 ³                     Input
                   O                   Character values
                    S                  Sum.
                     %                 Modulus.
                      168              168
                i                     Does the sublist contain that nilad?
                            T       Get the sublist which does contain that nilad.
                                 ?  If
                                L     Length.
                                    Then
                             ’        Return the index - 1
                                    Else
                              6      Return 6

```

# Answer
> 18 votes
# Mathematica, 112 111 bytes

-5 byte thanks to Mark S. and LegionMammal978!

-22 bytes (and noticing a problem with the output) thanks to ngenisis!

```
Tr[1^Entity["AdministrativeDivision",#~StringDelete~" "]@"BorderingStates"]+Boole@StringMatchQ[#,"Il*"|"Mic*"]&

```

Of course, there's a Mathematica builtin for it. Includes D.C. in the count.

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

*Edit: saved 2 bytes by borrowing 2 more string optimizations from Step Hen Python answer. I missed them on my initial attempt.*

Takes postal codes as input.

```
s=>('7KYCO8MOTN0AKHI1ME2FLSCWA3CACTNDELANHNJRIVT4ALWINCKSMDMSMTXOR5GAZOHMANMIMNVWVA'.match('.\\D*'+s)||'6')[0][0]

```

### How?

A non-RegExp argument passed to the `.match()` method is implicitly converted to a RegExp object. So, we're testing the regular expression `/.\D*{{input}}/` on our encoded string. This is matching a digit(1), followed by 0 to N non-digit characters, followed by the input.

For instance: if the input is `"NH"` (New Hampshire), the matched string will be `"3CACTNDELANH"`. We simply keep the first character of this string, or return `"6"` by default if there was no match.

*(1): The `.` is actually matching any character, but the string is built in such a way that what is found before a group of letters is always a digit.*

### Demo

```
let f =

s=>('7KYCO8MOTN0AKHI1ME2FLSCWA3CACTNDELANHNJRIVT4ALWINCKSMDMSMTXOR5GAZOHMANMIMNVWVA'.match('.\\D*'+s)||'6')[0][0]

const o = {
  8:['MO', 'TN'],
  7:['CO', 'KY'],
  6:['AR', 'ID', 'IL', 'IA', 'NE', 'NY', 'OK', 'PA', 'SD', 'UT', 'WY'],
  5:['AZ', 'GA', 'MA', 'MI', 'MN', 'NV', 'NM', 'OH', 'VA', 'WV'],
  4:['AL', 'IN', 'KS', 'MD', 'MS', 'MT', 'NC', 'OR', 'TX', 'WI'],
  3:['CA', 'CT', 'DE', 'LA', 'NH', 'NJ', 'ND', 'RI', 'VT'],
  2:['FL', 'SC', 'WA'],
  1:['ME'],
  0:['AK', 'HI']
};

for(let n = 8; n >= 0; n--) {
  o[n].forEach(s => {
    let res = f(s);
    console.log(s + ' -> ' + res + ' ' + (res == n ? 'OK' : 'FAIL'));
  });
}
```

---

# Hash version, 115 bytes

Same input format.

```
s=>`04436303035050063062750600644408${6e7}503600300540410005207058036442600400000650035`[parseInt(s,33)%589%180%98]

```

### Demo

```
let f =

s=>`04436303035050063062750600644408${6e7}503600300540410005207058036442600400000650035`[parseInt(s,33)%589%180%98]

const o = {
  8:['MO', 'TN'],
  7:['CO', 'KY'],
  6:['AR', 'ID', 'IL', 'IA', 'NE', 'NY', 'OK', 'PA', 'SD', 'UT', 'WY'],
  5:['AZ', 'GA', 'MA', 'MI', 'MN', 'NV', 'NM', 'OH', 'VA', 'WV'],
  4:['AL', 'IN', 'KS', 'MD', 'MS', 'MT', 'NC', 'OR', 'TX', 'WI'],
  3:['CA', 'CT', 'DE', 'LA', 'NH', 'NJ', 'ND', 'RI', 'VT'],
  2:['FL', 'SC', 'WA'],
  1:['ME'],
  0:['AK', 'HI']
};

for(let n = 8; n >= 0; n--) {
  o[n].forEach(s => {
    let res = f(s);
    console.log(s + ' -> ' + res + ' ' + (res == n ? 'OK' : 'FAIL'));
  });
}
```

# Answer
> 7 votes
# Python 3, ~~168~~ ~~154~~ ~~153~~ 137 bytes

```
lambda s:[i for i,S in enumerate('AKHI ME FLSCWA CACTLANHNJNDERIVT ALWINCKSMDMSMTXOR MAZOHGANMIMNVWVA A KYCO MOTN'.split())if s in S]or 6

```

Try it online!

*-4 bytes thanks to isaacg*

*-10 bytes thanks to ETHProductions*

*-1 byte thanks to notjagen*

Saved some more bytes by defaulting to six, as other answers have done.

TIO includes tests. Takes input as postal code. Generates a list of the state names as strings for each set, squished together where possible (for example, `WVVA` is stored as `WVA`). The lambda function gets the index in the list whose string contains the input. There may be a way I don't know about the golf the body of the function. Outputs as a list containing an integer - add `[0]` to the end of the lambda to output as integer.

# Answer
> 4 votes
# , 143 bytes

```
çourüee/C8
çdoüke/C7
çrküI„sn]üebüOkünnsüSDüUüwy/C6
çzüg„ot]üttüinnüvaüxiüOh/C5
çbüdiüKüMáû5}üNCüOüTüWi/C4
ç^[CDLNRV]/C3
ç[FSW]/C2
çM/C1
ñlS0

```

Try it online!

Hexdump:

```
00000000: e76f 7572 fc65 652f 4338 0ae7 646f fc6b  .our.ee/C8..do.k
00000010: 652f 4337 0ae7 726b fc49 8473 6e5d fc65  e/C7..rk.I.sn].e
00000020: 62fc 4f6b fc6e 6e73 fc53 8144 fc55 fc77  b.Ok.nns.S.D.U.w
00000030: 792f 4336 0ae7 7afc 6784 6f74 5dfc 7474  y/C6..z.g.ot].tt
00000040: fc69 6e6e fc76 61fc 7869 fc4f 682f 4335  .inn.va.xi.Oh/C5
00000050: 0ae7 62fc 6469 fc4b fc4d e1fb 357d fc4e  ..b.di.K.M..5}.N
00000060: 8143 fc4f fc54 fc57 692f 4334 0ae7 5e5b  .C.O.T.Wi/C4..^[
00000070: 4344 4c4e 5256 5d2f 4333 0ae7 5b46 5357  CDLNRV]/C3..[FSW
00000080: 5d2f 4332 0ae7 4d2f 4331 0af1 6c53 30    ]/C2..M/C1..lS0

```

I wrote this before I realized you could take the input as postal codes. I'm not sure if that's actually shorter or not `:shrug:`. This answer uses regex to search for certain states, and then change the input to a certain number if it matches. However, as the number of states we've tested against goes up, the smallest search we can use goes down. So for example, we can't search for `C` because that will match `Colorado` and `California`. (As well as Conneticut and The Carolinas) However, once we've tested for every state that has more than 3 bordering, we can just search for *starts with C* because it can't match a previous one anymore.

A few test cases might be wrong since I don't have the time to test all of them. Let me know if you find any incorrect outputs. :)

# Answer
> 3 votes
# JavaScript, 153 bytes

```
MO=TN=8;CO=KY=7;AZ=GA=MA=MI=MN=NV=NM=OH=VA=WV=5;AL=IN=KS=MD=MS=MT=NC=OR=TX=WI=4;CT=DE=LA=NH=NJ=ND=RI=VT=3;FL=WA=2;ME=1;AK=HI="0";alert(self[prompt()]||6)
```

Variable chaining. I'm sure there's a better way to do this though.

Thanks to a suggestion from someone from Discord the output defaults to 6, the most common number of bordered states. 183 bytes to 151 bytes.

A commenter pointed out that this fails for AK and HI, so I've added two bytes to fix the issue. 151 to 153 bytes.

# Answer
> 3 votes
# 05AB1E, ~~78~~ 72 bytes

```
.•n£þuγ{çâ/₁=èó[nK™ΩFîÀî˜Çʒ÷¿ηZ¬³ã®ÿΣÔ¢*5ŠÜ‚!¶Ö¾#}ê(Ûø‰¢þL[Æ₁cgIkö•s¡¬ð¢

```

Try it online!

---

```
.•n£þuγ{çâ/₁=èó[nK™ΩFîÀî˜Çʒ÷¿ηZ¬³ã®ÿΣÔ¢*5ŠÜ‚!¶Ö¾#}ê(Ûø‰¢þL[Æ₁cgIkö•
# Push the string: akhi me flscwa cactdelanhnjndrivt alinksmdmsncmtortxwi azgamamimnnvnmvaohwv idilianarenyokpnsdutwy kyco motn

s¡    # Split on input.
  ¬   # Get head.
   ð¢ # Count number of spaces.

```

---

This ONLY works because the order of the state abbreviations allows for NO state to occur in the overlap between states:

```
a[kh]i
me
f[ls][cw]a
c[ac][td][el][an][hn][jn][dr][iv]t
a[li][nk][sm][dm][sn][cm][to][rt][xw]i
a[zg][am][am][im][nn][vn][mv][ao][hw]v
i[di][li][an][ar][en][yo][kp][ns][du][tw]y
k[yc]o
m[ot]n

```

Took awhile to get the arrangement right... Then, by splitting on the input and counting the spaces in the first part, we get the correct result.

---

If I steal the "default to 6" from the other answers, I get 65 bytes:

# 05AB1E, 65 bytes

```
.•3θ0ÔÕ—ú^?D§:‚A†ǝλα“i›p‚ιCöΔƒñPŠ J€ŽãB»ΣUÆ¤ÆuhÃgŠ¦,Y²•s¡¬ð¢D9Qi6

```

Try it online!

# Answer
> 2 votes
# Retina, ~~106~~ 105 bytes

```
MO|TN
8
CO|KY
7
AK|HI
0
ME
1
FL|WA
2
[CDLR].|N[HJD]|VT
3
.[CSX]|AL|IN|MD|MT|OR|WI
4
[GMV].|.[HMVZ]
5
..
6

```

Try it online! Did someone say regex? Edit: Saved 1 byte thanks to @Arnauld.

# Answer
> 2 votes
# JavaScript (ES6), 195 bytes

```
s=>/las|ii/[t='test'](s)?0:/ai/[t](s)?1:/Fl|Wa|S.*C/[t](s)?2:/fo|ct|de|ui|mp|er|^N.+ak/i[t](s)?3:/do|ck/[t](s)?7:/ur|ee/[t](s)?8:/iz|gi|ch|ev|xi|hi|es/[t](s)?5:/rk|ah|oi|ow|br|om|lv|ak/[t](s)?6:4

```

A series of regular expressions, which work on the state's full name.

**Test cases:**

```
var states = ['Alabama','Alaska','Arizona','Arkansas','California','Colorado','Connecticut','Delaware',
'Florida','Georgia','Hawaii','Idaho','Illinois','Indiana','Iowa','Kansas',
'Kentucky','Louisiana','Maine','Maryland','Massachusetts','Michigan','Minnesota',
'Mississippi','Missouri','Montana','Nebraska','Nevada','New Hampshire','New Jersey',
'New Mexico','New York','North Carolina','North Dakota','Ohio','Oklahoma','Oregon',
'Pennsylvania','Rhode Island','South Carolina','South Dakota','Tennessee','Texas','Utah',
'Vermont','Virginia','Washington','West Virginia','Wisconsin','Wyoming'];

let f=

s=>/las|ii/[t='test'](s)?0:/ai/[t](s)?1:/Fl|Wa|S.*C/[t](s)?2:/fo|ct|de|ui|mp|er|^N.+ak/i[t](s)?3:/do|ck/[t](s)?7:/ur|ee/[t](s)?8:/iz|gi|ch|ev|xi|hi|es/[t](s)?5:/rk|ah|oi|ow|br|om|lv|ak/[t](s)?6:4

for(i = 0 ; i <= 8 ; i++) {
  s = []
  states.forEach(st => f(st) == i && s.push(st))
  console.log(i + ' bordering states: ' + s.join(', '))
}
```

# Answer
> 2 votes
# Jelly,  ~~61~~  59 bytes

```
OP%⁽/r%101eÐ€“¿=“þ“(7“¡¦ðø,0@L“€ç÷<CMZa“Ø!)5HNV““1^“¥+‘Tȯ7’

```

A full program taking the full state name and printing the result (as a monadic link it either returns a list containing a single number or the number 6).

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

### How?

```
“¿=“þ“(7“¡¦ðø,0@L“€ç÷<CMZa“Ø!)5HNV““1^“¥+‘

```

is a list of lists of code-page indices:

```
[[11,61],[31],[40,55],[0,5,24,29,44,48,64,76],[12,23,28,60,67,77,90,97],[18,33,41,53,72,78,86],[],[49,94],[4,43]]

```

and is shown as `“ ... ‘`, below:

```
OP%⁽/r%101eÐ€“ ... ‘Tȯ7’ - Main link: list of characters, stateName  e.g. Ohio
O                        - cast to ordinals                   [79,104,105,111]
 P                       - product                                    95757480
   ⁽/r                   - base 250 literal                              12865
  %                      - modulo by 12865                                3285
      %101               - modulo by 101                                    53
             “ ... ‘     - list of lists of code-page indices
          eÐ€            - map: exists in?                 [0,0,0,0,0,1,0,0,0]
                    T    - truthy indices (if none yields an empty list)   [6]
                     ȯ7  - logical or with 7 (replace empty list with 7)   [6]
                       ’ - decrement                                       [5]
                         - implicit print (Jelly's representation of a list of
                         -                 one item is just that item)       5

```

# Answer
> 1 votes
# Python 2, ~~363~~ 218 bytes

```
lambda a:dict(WA=2,WI=4,WV=5,FL=2,NH=3,NJ=3,NM=5,NC=4,ND=3,RI=3,NV=5,CO=7,CA=3,GA=5,CT=3,OH=5,KS=4,SC=2,KY=7,OR=4,DE=3,HI=0,TX=4,LA=3,TN=8,VA=5,AK=0,AL=4,VT=3,IN=4,AZ=5,ME=1,MD=4,MA=5,MO=8,MN=5,MI=5,MT=4,MS=4).get(a,6)

```

Let's start out with the ~~simple~~ slightly optimized hardcoded answer. Takes postal code as input.

-145 bytes thanks to bfontaine.

# Answer
> 1 votes
# Excel VBA, ~~177~~ ~~154~~ 147 Bytes

Anonymous VBE function that takes input, of the expected type `String` representing a state's postal code, from range `[A1]`, and returns an `Integer` that represents the number of states that border that state.

```
For i=0To 8:r=r+IIf(Instr(1,Split("AKHI ME FLSCWA CACTLANHNJNDERIVT ALWINCKSMDMSMTXOR MAZOHGANMIMNVWVA | KYCO MOTN")(i),[A1]),i,0):Next:?IIf(r,r,6)

```

---

## Previous Versions

154 Bytes:

```
For Each s in Split("AKHI ME FLSCWA CACTLANHNJNDERIVT ALWINCKSMDMSMTXOR MAZOHGANMIMNVWVA | KYCO MOTN"):r=r+IIf(Instr(1,s,[A1]),i,0):i=i+1:Next:?IIf(r,r,6)

```

177 Bytes:

```
[2:2]=Split("AKHI ME FLSCWA CACTLANHNJNDERIVT ALWINCKSMDMSMTXOR MAZOHGANMIMNVWVA A KYCO MOTN"):[3:3]="=IfError(If(Find($A1,A2),Column(A3)),"""")":[B1]="=Sum(3:3)":?[If(B1,B1,6)]

```

Formatted for readability

```
[2:2]=Split("AKHI ME FLSCWA CACTLANHNJNDERIVT ALWINCKSMDMSMTXOR MAZOHGANMIMNVWVA | KYCO MOTN")
[3:3]="=IfError(If(Find($A1,A2),Column(A3)-1),"""")"
[B1]="=Sum(3:3)"
?[If(B1,B1,6)]

```

# Answer
> 1 votes
# PowerShell, 187 bytes

```
param($a)$x=($b=" MO8TN8CO7KY7AZ5GA5MA5MI5MN5NV5NM5OH5VA5WV5AL4IN4KS4MD4MS4MT4NC4OR4TX4WI4CA3CT3DE3LA3NH3NJ3ND3RI3VT3FL2SC2WA2ME1").IndexOf($a);if($x+1){$b[$x+2];exit}6-6*($a-in'AK','HI')

```

Try it online!

I'm sure there's a better way to do this, but here's the approach I came up with.

Takes input `$a` and uses that to get the `.IndexOf` its occurrence in the long string of state/border combinations. Stores that into `$x` and the string into `$b` in the process. Then goes into an `if` statement that checks whether it found a match, and if so index to the digit and then `exit`. Otherwise, we're one of the `6` states or `AK` or `HI`, so we perform some logic to see whether `$a` is either of the `0` states, and subtract if necessary. In any case, that's left on the pipeline and output is implicit.

# Answer
> 1 votes
# Python 3, 729 ~~733~~ bytes

Takes input as a postal abbreviation. This is my first attempt at a golfing challenge, and this is about the shortest I think I can get with this hellish approach. I know it's massive - come to think of it I'd probably have been better off with `if-else` statements, but after all of that time and effort I had to post it : D.

```
lambda s:sum((i-32)*96**j for j,i in enumerate(b'`*g$<#?wP\\.=)kuDbk$yvv\\D:Nh:cd/Pj, e*[_yXGz6lR<$jMo0qUU*7(Dua3-ThO}iX6VWRYDv=<K$8mVbYK9ld);TFB/m\'NE3ow4./pUsI5yJrwYrM4@e6\\kHJ%q8NA3>fb!~-rtwsRW=RBni}Y7T^gD\\IoxzJf.%|1.&4*"$%Q+).|8p(vcJ]cLRGUyC2eF:<Q4!_)y\\<`tr2A[z7re6OaR["2PRv\x7f,bRE [XrvtA<R<UlS23on?Byym&uy{XuB\x7fIMfh<y&waHElg-vk:4*on\x7f@?Ai5=2swfZSBF.PjkL{,|=,M<Bw"w,e@f`aKnmh\'xgg1#b4En\x7f+*\'g_ZRoeN*Q]mX\'>RoGc~ZP~e&{Hwo6bd<](hV)=l9#[f<Gj,#Ea!nJnL=9k"M,`bP2PsP6(eJoGEU>GA?,BpS}"RzzdMRtL[cre;\\tld^xT\':pry\'Nu_*R}eYg_U!Ld{p7<f:95lD]OBMX(r"Jg\'|%Cq"`Qy9g0aNrtYP9dnPRRr3\'yT(CE~\\&@5#tMLZ+a:V5NNXVp+Uy61s9$=Vb99(!ga7f7x}#=*]q.\x7f0R+f[*m:i^qe#D 8M&W\x7faGmCNCU9"~1Pj!]2r5 H>rYPqwfg4cFG*3-(z'))>>(5*int(s,36)-1850)&15

```

I just realised I'd taken the luxury of a three letter variable name - 4 bytes down, 400 to go!

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


title: Mario Kart Scoring w/ Ties

text:
# Question
Title: Mario Kart Scoring w/ Ties
I ran into this problem while working on another challenge I'm making for this site. In that challenge I utilize "Mario Kart 8 Scoring". The amount of points the player in *k*th place gets is represented by this 1-indexed array: \[15,12,10,9,8,7,6,5,4,3,2,1\]. So 1st place gets 15 points, 2nd place gets 12 points, etc.

It's easy enough to assign points like this, however the tricky part comes with how I handle ties. What I do is give each tying player the average of the points given for each tying place. For example, if only 1st and 2nd tied, then both players get (15+12)/2 = 13.5 points. (Note: You're allowed to round to the nearest int, so 13 or 14 are both also acceptable.) Then 3rd - 12th place get the normal amount of points for their position.

## Challenge

Given 12 non-negative integer scores that are decreasingly sorted, output the number of points each player gets. You can also take the points list \[15,12,10,9,...\] as input. Note that the number of points each player gets does not depend on the actual values of the scores, but how they compare to the other scores.

## Test Cases

* \[21,21,15,14,12,9,6,5,4,3,2,1\] =\> \[**14,14**,10,9,8,7,6,5,4,3,2,1\]
* \[20,15,15,15,10,9,8,7,6,5,4,3\] =\> \[15,**10,10,10**,8,7,6,5,4,3,2,1\]
    + explanation: (12+10+9)/3 = 10.3333
* \[1,1,1,1,1,1,1,1,1,1,1,1\] =\> \[**7,7,7,7,7,7,7,7,7,7,7,7**\]
    + explanation: (15+12+10+9+8+7+6+5+4+3+2+1)/12 = 6.8333
* \[20,20,20,20,10,10,10,9,8,7,6,5\] =\> \[**12,12,12,12**,***7,7,7***,5,4,3,2,1\]
    + explanation: (15+12+10+9)/4 = 11.5, (8+7+6)/3 = 7
* \[100,99,98,95,95,95,94,93,93,92,91,91\] =\> \[15,12,10,**8,8,8**,6,**5,5**,3,**2,2**\]
    + explanation: (9+8+7)/3 = 8, (5+4)/2 = 4.5, (2+1)/2 = 1.5

Related: Rank a list of scores with "skips"

# Answer
> 5 votes
# JavaScript (ES6), 57 bytes

Takes input in currying syntax `(p)(s)`, where ***p*** is the list of points and ***s*** is the list of scores.

```
p=>s=>s.map(v=>s.reduce((t,x,i)=>x-v?t:t+p[n++,i],n=0)/n)

```

### Test cases

```
let f =

p=>s=>s.map(v=>s.reduce((t,x,i)=>x-v?t:t+p[n++,i],n=0)/n)

points = [15,12,10,9,8,7,6,5,4,3,2,1];

console.log(JSON.stringify(f(points)([21,21,15,14,12,9,6,5,4,3,2,1])))
console.log(JSON.stringify(f(points)([20,15,15,15,10,9,8,7,6,5,4,3])))
console.log(JSON.stringify(f(points)([1,1,1,1,1,1,1,1,1,1,1,1])))
console.log(JSON.stringify(f(points)([20,20,20,20,10,10,10,9,8,7,6,5])))
console.log(JSON.stringify(f(points)([100,99,98,95,95,95,94,93,93,92,91,91])))
```

# Answer
> 5 votes
# , 3 bytes

Apparently R has a built-in for this. Takes a list of `p`oints and `s`cores as input.

```
ave

```

Try it online!

Example:

```
p=c(15,12,10,9,8,7,6,5,4,3,2,1)

> ave(p,c(20,15,15,15,10,9,8,7,6,5,4,3))
 [1] 15.00000 10.33333 10.33333 10.33333  8.00000  7.00000  6.00000  5.00000  4.00000  3.00000  2.00000  1.00000
> ave(p,c(1,1,1,1,1,1,1,1,1,1,1,1))
 [1] 6.833333 6.833333 6.833333 6.833333 6.833333 6.833333 6.833333 6.833333 6.833333 6.833333 6.833333 6.833333

```

# Answer
> 4 votes
# Perl 5, 109 +1 (-a) = 110 bytes

```
@p=(1..10,12,15);while(@F){$/=$,=0;do{$,++;$/+=pop@p}while($w=shift@F)==$F[0];push@r,(int.5+$//$,)x$,}say"@r"

```

Try it online!

Includes 17 bytes to hardcode the point values.

# Answer
> 4 votes
# MATL, ~~12~~ 10 bytes

*2 bytes off thanks to @geokavel!*

```
7#uti2XQw)

```

Inputs are a column vector (`;` as separator) of integer scores and a column vector with the points. The output contains the results separated by newlines.

Try it online! Or verify all test cases.

### Explanation

```
       % Implicitly take first input.
       % STACK: [21;21;15;14;12;9;6;5;4;3;2;1]
7#u    % Unique consecutive integer labels
       % STACK: [1;1;2;3;4;5;6;7;8;9;10;11]
t      % Duplicate
       % STACK: [1;1;2;3;4;5;6;7;8;9;10;11], [1;1;2;3;4;5;6;7;8;9;10;11]
i      % Take second input
       % STACK: [1;1;2;3;4;5;6;7;8;9;10;11], [1;1;2;3;4;5;6;7;8;9;10;11], [15;12;10;9;8;7;6;5;4;3;2;1]
2XQ    % Average second argument as grouped by the first
       % STACK: [1;1;2;3;4;5;6;7;8;9;10;11], [13.5;10;9;8;7;6;5;4;3;2;1]
w      % Swap
       % STACK: [[13.5;10;9;8;7;6;5;4;3;2;1], [1;1;2;3;4;5;6;7;8;9;10;11]
)      % Reference indexing
       % STACK: [13.5;10;9;8;7;6;5;4;3;2;1]
       % Implicitly display

```

# Answer
> 3 votes
# 05AB1E, 12 bytes

```
γ€g£vygFyÅAˆ

```

Try it online!

**Explanation**

```
γ              # group the scores into chunks of consecutive equal elements
 €g            # get the length of each chunk
   £           # split the points list into chunks of these sizes
    v          # for each chunk y in the points list
     ygF       # len(y) times do:
        yÅA    # get the arithmetic mean of y
           ˆ   # add to global list
               # implicitly output global list

```

# Answer
> 2 votes
# Jelly, 11 bytes

```
ṁ⁴Œg¤Æmṁ$€F

```

Try it online!

-3 bytes thanks to fireflame for noticing new Jelly features :D

# Answer
> 2 votes
# J, 15 bytes

```
[:;<@(##+/%#)/.

```

Try it online!

Takes the list of scores (`1 2 ... 12 15`) as a right-hand argument and the values to score as a left-hand argument. If this isn't a logical input, add 1 byte for a `~`-passive to invert the order in which the inputs are taken.

There might be a few things to golf, which include

* My usage of boxing
* The cap at the end

# Explanation

I'll split this into a couple functions.

```
avg_and_dupe =. # # +/ % #
score        =. [: ; <@avg_and_dupe/.

```
* `avg_and_dupe` takes the average of a list and duplicates it as many times as the list's length
* `score` scores an input (left argument) given a list of scores (right argument).

# avg\_and\_dupe

```
# # +/ % #
#           Length
  #         Copy as many times as the left argument
    +/ % #  Average
    +/       Sum
       %     Divided by
         #   Length

```

This works so nicely because it's treated as two forks. If you're still scratching your head (I know I was at first), ask and I can provide a more in-depth explanation for why this works as it does.

### score

```
[: ; <@avg_and_dupe/.
                   /.  Key: using the values given, partition the scores
     <@avg_and_dupe     For each partition:
       avg_and_dupe      Average and duplicate
     <                   Then box
   ;                   Raze the boxes into a single list

```

If it's still confusing, I can also add an explanation for `/.`-key, but I think the wiki page explains it pretty well.

# Answer
> 2 votes
# C# (.NET Core), 154 bytes

```
x=>s=>{for(int i=0;i<12;){int b=0,j=i,a=0,c=0;for(;j<12&&x[i]==x[j];j++,b++){a+=s[j];}a=(int)Math.Round(a/(b+.0));for(;c<b;c++){x[i+c]=a;}i+=b;}return x;}

```

Try it online!

# C# (.NET Core) \+ using Linq, 170 + 23 bytes

```
x=>s=>x.GroupBy(z=>z).Select(y=>Enumerable.Repeat(Math.Round(s.Skip(Array.IndexOf(x,y.Key)).Take(y.Count()).Average()),y.Count())).Aggregate((a,b)=>a.Concat(b)).ToArray()

```

Try it online!

# Answer
> 2 votes
# Python 2, 66 bytes

*-8 bytes thanks to Leaky Nun.*

```
lambda s,p:[sum(p[s.index(i):][:s.count(i)])/s.count(i)for i in s]

```

Try it online!

# Answer
> 1 votes
# Python 3, 67 bytes

```
lambda s,p:[sum(v for j,v in zip(s,p)if j==i)/s.count(i)for i in s]

```

Try it online!

# Python 2, ~~108~~ 70 bytes

```
lambda s,p:[1.*sum(v for j,v in zip(s,p)if j==i)/s.count(i)for i in s]

```

Try it online!

# Answer
> 1 votes
# Haskell, 152 bytes

```
f::[Int]->[Int]
f=concat.g(15:12:[10,9..1])[]
g[q]t _=[q:t]
g(q:r)t(x:z)|x>head z=(replicate(l(q:t))(sum(q:t)`div`l(q:t))):g r[]z|1<2=g
r(q:t)z
l=length

```

It's a pain to import `groupBy` and `on`, so I had to do my own.

Averaging function will be shortened shortly.

Needing the signature could probably be avoided with compiler flags.

# Answer
> 1 votes
# Python 3, 72 bytes

```
lambda s,p:[sum(p[s.index(i):12-s[::-1].index(i)])/s.count(i)for i in s]

```

Try it online!

# Answer
> 1 votes
# Proton, 62 bytes

```
(s,p)=>[sum(p[s.index(i)to][to s.count(i)])/s.count(i)for i:s]

```

Try it online!

# Proton, 63 bytes

```
(s,p)=>map(i=>sum(p[s.index(i)to][to s.count(i)])/s.count(i),s)

```

Try it online!

# Answer
> 1 votes
# Dyalog APL, 14 bytes

```
∊{(⊂≢⍴+/÷≢)⍵}⌸

```

Takes the list of scores as left argument and points list as right argument. Add 2 bytes for wrapping it in `()` if called directly and not as a named function.

`{`...`}⌸` group right argument by key in left argument and apply function in braces to each group (key operator).

`⊂≢⍴+/÷≢` is a fork where:

`+/÷≢` is average points for group (sum divided by tally)

`≢⍴` tally reshape (replicate the average to match number of items in group)

boxes the result (this is to counteract the mixing of the result that the key operator applies)

is enlist and flattens the result of the key operator (which is a nested vector of vectors) into a simple list.

TryAPL online

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


title: ANNNOUNNNCCCEEERRR VOICCCEEE

text:
# Question
Title: ANNNOUNNNCCCEEERRR VOICCCEEE
Write a function that takes a string of letters and spaces (no need to handle non-letters) and performs the ANNOUNCER VOICE translation algorithm as follows:

* First, uppercase everything.
* For each word,
    + *Elongate* each consonant cluster by tripling each letter; except, if the word *begins* with a consonant cluster, do not elongate that cluster. For example, `other` should become `OTTTHHHEEERRR` but `mother` should become `MOTTTHHHEEERRR`.
    + *Elongate* the final vowel by tripling it.
* In both cases of *elongation*, if you're tripling a letter, first coalesce it with duplicate letters on either side. For example, `hill` should become `HIIILLL` and `bookkeeper` should become `BOOKKKEEPPPEEERRR`.
* For the purposes of this challenge, `y` counts as a consonant.
* Clarification/simplification: You may assume that each pair of words is separated by a single space, and that the input contains no consecutive spaces, and that the input will not be the empty string.
* Shortest code wins!

Test vectors:

```
> sunday sunday
SUNNNDDDAAAYYY SUNNNDDDAAAYYY
> mia hamm
MIAAA HAAAMMM
> chester alan arthur
CHESSSTTTEEERRR ALLLAAANNN ARRRTTTHHHUUURRR
> attention please
ATTTENNNTTTIOOONNN PLEASSSEEE
> supercalifragilisticexpialidocious
SUPPPERRRCCCALLLIFFFRRRAGGGILLLISSSTTTICCCEXXXPPPIALLLIDDDOCCCIOUUUSSS
> moo
MOOO
> Aachen
AACCCHHHEEENNN
> Oooh
OOOHHH
> grifffest
GRIFFFEEESSSTTT
> k
K
> aaaabbbbc
AAAABBBBCCC

```

---

Here's a reference implementation which I would move to an answer except that as of this morning the question's been closed. :P

```
import itertools,re
def j(s):return re.match('^[AEIOU]+$',s)
def c(s):return ''.join(sum(([h,h,h]for h in[k for k,g in itertools.groupby(s)]),[]))
def v(s):
 while len(s)>=2 and s[-2]==s[-1]:s=s[:-1]
 return s+s[-1]+s[-1]
def a(n):
 r=''
 for w in n.split():
  if r:r+=' '
  ss=re.split('([AEIOU]+)', w.upper())
  for i,s in enumerate(ss):
   r += [v(s),s][any(j(t) for t in ss[i+1:])]if j(s)else[s,c(s)][i>0]
 return r
while 1:print a(raw_input('> '))

```

# Answer
# APL (Dyalog), 175 bytes

```
1↓' +'⎕R' '⊢'[AEIOU][^AEIOU]+ '⎕R{m/⍨1,3×2≠/m←⍵.Match}'([AEIOU])\1*([^AEIOU]*? )' ' [AEIOU]' ' [^ AEIOU]+' '([^AEIOU ])\1*'⎕R'\1\1\1\2' '&' '&' '\1\1\1'⊢'$| |^'⎕R'  '⊢1(819⌶)⍞

```

Try it online!

prompt for character input

`1(819⌶)` convert to uppercase (819 ≈ Big)

pass the result further (serves to separate the strings and the 1)

`'$| |^'⎕R' '`**R**eplace:
the end, any space, and the beginning
→ two spaces

pass the result further (serves to separate two groups of strings)

`'([AEIOU])\1*([^AEIOU]*? )' ' [AEIOU]' ' [^ AEIOU]+' '([^AEIOU ])\1*'⎕R'\1\1\1\2' '&' '&' '\1\1\1'`**R**eplace:
any number of identical vowels and any number of non-vowels and a space
→ the vowel thrice and the unmodified consonants
a space and a vowel
→ themselves
a space and a consonant cluster
→ themselves
a run of identical consonants
→ three of those vowels

`'[AEIOU][^AEIOU]+ '⎕R{``}`**R**eplace:
a run of non-vowels and a space
→ the result of the following anonymous function with the namespace  as argument:
`⍵.Match` the text that was found
`m←` assign that to `m`
`2≠/` pair-wise different-from
multiply by three
`1,` prepend one
`m/⍨` use that to replicate `m`

pass the result further (serves to separate two strings)

`' +'⎕R' '`**R**eplace:
one or more spaces
→ with a single space

`1↓` drop the initial letter (a space)
> 5 votes

# Answer
# APL, 90 bytes

```
{1↓∊{s←{⍵⊂⍨1,2≠/⍵}⋄x↑⍨¨(3⌈≢¨s⍵)⌊≢¨x←s⍵/⍨(1+2×{⌽<\⌽⍵}∨~∧∨\)⍵∊'AEIOU'}¨w⊂⍨w=⊃w←' ',1(819⌶)⍵}

```

Explanation:

* `1(819⌶)⍵`: convert to uppercase
* `w⊂⍨w=⊃w←' ',`: split on spaces
* `{`...: for each word...
    + `s←{⍵⊂⍨1,2≠/⍵}`: `s` is a function that splits a string into groups of contiguous matching characters
    + `⍵∊'AEIOU'`: mark the vowels
    + `(`...`)`: see which characters to triplicate
        - `~∧∨\`: all consonants past the first vowel,
        - `{⌽<\⌽⍵}`: the last vowel.
        - : multiply the bit vector by two,
        - `1+`: and add one. Now all selected characters have `3` and the rest have `1`.
    + `⍵/⍨`: replicate each character in  by the given amount
    + `x←s`: split it up into strings of matching characters, and store this in `x`.
    + `(3⌈≢¨s⍵)`: the length of each group of matching characters in the input word, with a maximum of 3.
    + `⌊≢¨`: the minimum of that and the lengths of the groups in `x`.
    + `x↑⍨¨`: make each group be that length
* `1↓∊`: flatten the result and drop the first character (the space that was added at the beginning to help with splitting)
> 5 votes

# Answer
# JS (ES6), ~~138~~ ~~134~~ 129 bytes

```
s=>s.toUpperCase()[r="replace"](/(\w)\1/g,"$1")[r](/[AEIOU](?=[^AEIOU]*( |$))/g,s=>s+s+s)[r](/\B./g,s=>/[AEIOU]/.test(s)?s:s+s+s)

```

WAAAYYY TOOO MAAANNNYYY BYYYTTTEEESSS. Contains `AEIOU` 3 times, but I can't golf those into one.

-4 bytes thanks to HyperNeutrino

### Ungolfed

```
function v(str){
    return str.toUpperCase().replace(/(\w)\1/g,"$1").replace(/[AEIOU](?=[^AEIOU]*( |$))/g,s=>s+s+s).replace(/\B./g,s=>[..."AEIOU"].includes(s)?s:s+s+s);
}

```

*I like to write, not read code.*
> 4 votes

# Answer
## Python, 417 bytes

Here's a reference implementation in Python. Not terribly golfed.

```
import itertools,re
def j(s):return re.match('^[AEIOU]+$',s)
def c(s):return ''.join(sum(([h,h,h]for h in[k for k,g in itertools.groupby(s)]),[]))
def v(s):
 while len(s)>=2 and s[-2]==s[-1]:s=s[:-1]
 return s+s[-1]+s[-1]
def a(n):
 r=''
 for w in n.split():
  if r:r+=' '
  ss=re.split('([AEIOU]+)',w.upper())
  for i,s in enumerate(ss):
   r+=[v(s),s][any(j(t) for t in ss[i+1:])]if j(s)else[s,c(s)][i>0]
 return r

```

Test with:

```
while True:
 print a(raw_input('> '))

```
> 2 votes

# Answer
# Python 3, 238 bytes

```
def f(s):
 s=s.upper();k=[s[0]];s=''.join(k+[s[i]for i in range(1,len(s))if s[i]!=s[i-1]])
 for i in range(1,len(s)):k+=[s[i]]*(3-2*(s[i]in'AEIOU'and i!=max(map(s.rfind,'AEIOU'))))
 return''.join(k)
print(' '.join(map(f,input().split())))

```

Try it online!
> 1 votes

# Answer
# Perl 5, 139 + 1 (-p) = 140 bytes

```
$_=uc,s/^([^AEIOU]*)//,$s=$1,s/([^AEIOU])\1*/$1x(($q=length$&)>3?$q:3)/ge,s/.*?\K([AEIOU])\1*/$1x(($q=length$&)>3?$q:3)/e,print"$s$_ "for@F

```

Try it online!

Even handles the "aaaabbbbc" test case in accordance with the example.
> 0 votes

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