title: Hyper about quines

text:
# Question
Title: Hyper about quines
*Inspired by Hyperprogramming: N+N, N×N, N^N all in one.
Thanks to @MartinEnder and @trichoplax for their help in the sandbox.*

# Definitions

## Hyperquines

Define a **hyperquine** of order **n** as a quine-like full program or function **P** that satisfies all rules that apply to proper quines and, in addition, has the following structure.

**P** is the concatenation of character groups that consist of **n** copies of the same character. When **P** is executed, the *output* is the concatenation of the same groups, augmented by one more copy of the character.

### Examples

* In a hypothetical programming language where the source code `aabbcc` generates the output `aaabbbccc`, this program constitutes a hyperquine of order **2**.
* The definition does *not* require the characters of different groups to be different.

If the source code `aabbcc` generates the output `aaaabbbbcccc`, the program is a hyperquine of order **1**; the source code consists of six single-character groups, the output of six character pairs.
* In GS2, the empty program prints `\n`, and the program `\n` prints `\n\n`. However, neither `\n` nor `\n\n` are hyperquines, since they they do not satisfy all properties of proper quines; no part of the source code encodes a *different* part of the output.

## Hyperquine chains

Define a **hyperquine chain** of length **n** as a finite sequence of **n** full programs or **n** functions
**(P1, …, Pn)** that satisfies the following constraints.

1. The outputs of **P1, …, Pn-1** are **P2, …, Pn**, respectively.
2. **P1, …, Pn** are hyperquines.
3. The orders of **P1, …, Pn** form a *strictly increasing* sequence of *adjacent* integers.

Finally, define an **infinite hyperquine chain** as an infinite sequence of full programs or functions **(P1, P2, …)** such that each initial interval **(P1, …, Pn)** constitutes a hyperquine chain of length **n**.

### Examples

* In a hypothetical programming language where the source code `aabbcc` generates the output `aaabbbccc`, which, in turn, generates the output `aaaabbbbcccc`, the pair (`aabbcc`, `aaabbbccc`) constitutes a hyperquine chain of length **2**.

Note that `aaaabbbbcccc` – the output of the last hyperquine in the chain – doesn't have to produce a specific output; it doesn't even have to be valid source code.
* Continuing the previous example, if `aaaabbbbcccc` generates the output `aaaaabbbbbccccc`, the triplet (`aabbcc`, `aaabbbccc`, `aaaabbbbcccc`) constitutes a hyperquine chain of length **3**.

If this pattern continues forever, the sequence (`aabbcc`, `aaabbbccc`, `aaaabbbbcccc`, …) constitutes an infinite hyperquine chain.
* The pair of programs (`abc`, `aabbcc`) with outputs (`aabbcc`, `aaaabbbbcccc`) is *not* a hyperquine chain, since the orders of the hyperquines are both **1**, so they do not form a strictly increasing sequence.
* The pair of programs (`aabbcc`, `aaaabbbbcccc`) with outputs (`aaaabbbbcccc`, `aaaaabbbbbccccc`) is *not* a hyperquine chain, since the orders of the hyperquines are **1** and **4**, so they do not form a sequence of adjacent integers.

# Rules

## Task

In a programming language of your choice, write a non-trivial hyperquine chain, i.e., a chain that consists of at least **2** hyperquines.

As usual, your programs may not take any input or access their own source code in any form.

If your interpreter prints an implicit newline, your hyperquines *have to* account for this.

All standard loopholes – especially those related to quines – apply.

## Scoring

The longest **hyperquine chain** wins. If two or more submissions are tied, the submission among these that starts with the shortest hyperquine (measured in characters) wins. As usual, posting time is the final tiebreaker.

---

You must use the same character encoding for source code, output, character count, and execution. For example, the Python program `print 42` is *not* a 2-character UTF-32 submission, since the interpreter treats each byte as a single character. If your language of choice is not character-based, treat all individual bytes as characters.

# Answer
# Befunge-98, infinite order, ~~54~~ ~~52~~ ~~38~~ 36 bytes

## Second approach - infinite order, 36 bytes

This program would actually break at the 34th hyperquine since the ASCII value of `"` would disrupt the string interpretation (and at 59, `;`), but we offset the storage of that value to a position that will never be executed (i.e. `(0, 1)` instead of `(0, 0)`).

```
1+::0*x01pn'!1+:#jr;,kg10@k!:kg10;#"

```

Try it online: , , 10, 34, 42

### Explanation

```
INSTRUCTIONS  STACK (PYTHON PSEUDOCODE)           EXPLANATION
1+            [n]                                 Push n many 1s onto the stack, then sum them up
::            [n]*(at least 3)                    Duplicate that sum at least twice
0*            [n]*(at least 2)+[0]                Push a whole lot of zeros, then multiply them all together
x             [n]*(at least 1)                    Pop a vector off the stack (n, 0) and set the IP delta to that; now the IP is only executing every nth character
01p           [n]*(at least 1)                    Place n in the program at coordinates (0, 1); this is just for storage
n             []                                  Clear the stack
'!1+          ['"']                               '!' is character 33; one less than 34, or '"'
:#jr          ['"']                               We duplicate the 34 (all we care is that it's a rather large number), then turn around and skip that many spaces
                                                  The IP, having jumped 34*n instructions to the left, is now way in the negatives
                                                  Execution resumes on the other side of the program (the following instructions have been reversed for readability
"             [the program of order 1]            The quote-at-the-end-of-the-program is a common trick for one-liner Befunge quines
#; ... ;                                          Jumps into a loop (when the IP hits one semicolon it skips to the next, restarting the loop)
01gk:         [(rest of string), char*(n+2)]      This duplicates the letter n+1 times*, leaving n+2 copies on the stack
!k@                                                If the number on the top of the stack is zero (i.e. we are printing), it will execute '@',
                                                  ending the program; otherwise, it will NOT execute '@' and will instead continue normally
                                                  Vague* 'k' instruction FTW
10gk,                                             If we aren't done yet, print the character n+1 times* (and restart the loop)

* 'k' is a very strange instruction. It pops a number off the stack; if the number is zero, it skips the command in front of it. If the number is greater than zero,
  it will execute the instruction that many times PLUS ONE. This is actually strangely advantageous in this program.

```

---

## First approach - order 34, 52 bytes (uses introspection, so technically not legal)

For the reason in the above post, this program would break at order 34 (though I haven't tested).

```
1+::0*x:00p'1\k:00gk,1#;:00g*0g00gk:$00gk,1+:'4-!k@;

```

Try it online!
> 10 votes

# Answer
## \>\<\>, infinite order, 178 bytes

The program contains a trailing linefeed.

```
^
.
*
&
:
&
+
*
2
b
*
*
6
9
$
0
)
*
4
8
:
~
.
*
&
:
&
+
*
2
b
*
*
2
b
$
0
)
i
:
-
1
o
a
&
:
&
o
~
.
*
&
:
&
+
*
7
7
*
*
4
6
$
0
)
0
:
-
1
$
o
:
$
&
:
&
&
,
*
8
b
-
1
l
}
*
3
d
'

```

**Try it online:** , , , 10 (That last one takes a while to run.)

Retina script to generate source from linear program.

### Explanation

The main idea is to turn the quine vertical, so that the actual control flow isn't affected by the repetition. E.g. the second hyper quine begins like:

```
^^

..

**

```

Since we're only moving through the first column, we don't have to worry about repeated characters. Also when we push the majority of the code as a string with `'`, this will push a space for each empty line, which gives us a way to determine the number of repetitions. That said, there are some limitations due to these empty lines:

* We can't use `"` to push large numbers as character codes in the main part of the quine, because this would push additional `32`s which we don't want.
* We can't use `?` or `!` because they only skip the next character which would be a space in that case (so they wouldn't actually skip the next command).

Hence, all control flow is done with explicit jumps (2D goto, basically), whose actual offsets we need to calculate based on the number of repetitions.

So let's look at the actual code. We start with `^` so the code is executed bottom up. For easier reading, let's write out the actual code in execution order (and drop the `^` because it's never executed again):

```
'd3*}l1-b8*,&&:&$:o$1-:0)0$64**77*+&:&*.~o&:&ao1-:i)0$b2**b2*+&:&*.~:84*)0$96**b2*+&:&*.

```

The `'` is the standard quining technique for \>\<\> (and Befunge, I guess). It switches to string mode which means that the encountered characters are pushed onto the stack until the next `'` is encountered. Empty lines are implicitly padded with spaces which is why we get all the spaces in between. Empty lines at the end of the program are ignored. So after the IP wraps around and hits the `'` again, we've got the first column of the program on the stack, except for the `'` itself.

Let's look at how we use this to print the entire program.

```
d3*}    Put a 36 (the ') at the bottom of the stack. Now the stack holds
        a representation of the entire first column.
l1-     Push the depth of the stack, minus (so minus to ').
b8*,    Divide by 88. The original program has 89 lines. If we divide the
        depth of the stack (minus 1) by 88, we get the order of the current
        hyperquine (due to all the spaces we've pushed).
&       Store the order of the hyperquine in the register.
        Begin of main loop:
&:&       Push a copy of the register onto the stack. Call that N.
          Begin of line-printing loop:
$:o$        Print a copy of the top character on the stack.
1-          Decrement N.
:0)         Check whether it's still positive (gives 0 or 1).
0$          Put a 0 underneath. This will be the x-coordinate of a jump.
64**        Multiply the conditional by 24. This is the number of commands
            in this inner loop.
77*+        Add this to 49, the offset of the end of the loop.
            The result is line we want to jump to in the order-1 hyperquine.
&:&*        Multiply by the order of the quine (so that we jump further on
            higher quine orders).
.         Jump. If N isn't zero yet, this repeats the inner loop. Otherwise
          we continue right here.
~         Discard N (now 0).
o         Output one last copy of the top character on the stack.
&:&       Push a copy of the register onto the stack. Call that N.
          Begin of linefeed-printing loop:
ao          Print a linefeed.
1-          Decrement N.
:i)         Check whether it's still non-negative (gives 0 or 1).
            The next bit is essentially the same loop structure as above,
            but with loop length 22 and offset 22:
0$
b2**
b2*+
&:&*
.         Jump. If N isn't -1 yet, this repeats the inner loop. Otherwise
          we continue right here.
          Begin of space-clearing loop:
~           Discard the top of the stack. On the first iteration this is the
            -1 from the previous loop. Afterwards, it's one of the spaces
            representing an empty line.
:84*)       Check if the top of the stack is a space.
            And another loop conditional. This one works the other way round:
            the difference is 54, which is the distance between the beginning
            of this loop and the main loop. The offset is the beginning
            of this loop, at 22 as above.
0$
96**
b2*+
&:&*
.         Jump. If the top of the stack is still a space this repeats the
          inner loop. Otherwise we continue from the top of the main loop.

```

The program terminates when the stack is empty and the first inner loop fails to print another character.
> 10 votes

---
Tags: code-challenge, quine, source-layout, code-generation
---


title: It's time to make a histogram

text:
# Question
Title: It's time to make a histogram
Your task is to make a histogram given a sample of arbitrary size.

**Input**

A float array or any other reasonable form of input with an arbitrary number of elements.

**Output**

The histogram; more to follow.

**How to make a histogram**

We'll use the sample: `[1.1, 3, 5, 13, 15.5, 21, 29.7, 63, 16, 5, 5.1, 5.01, 51, 61, 13]`

To make a histogram, you first separate your observations into classes. The ideal number of classes is the lowest `k` such that `2^k > n`, where `k` is the number of classes, and `n` is the number of observations. In our case, `k = 4`. The number of bars is not final. This `k` value's purpose is only to find the width of each class.

The width of each class is the range of your data set divided by the number of classes. The range of our data set is `63 - 1.1 = 61.9`, so the width of each class is `15.475`. This means that the first class is `[1.1, 16.575)`, the second is `[16.575, 32.05)` and so on. The last class is `[63.0, 78.475)`. The second value of the last class (`b` in `[a,b)`) must be greater than the max value of the set.

Now we rearrange our data into the classes; for us:

```
[1.1, 16.575): [1.1, 3, 5, 5, 5.01, 5.1, 13, 13, 15.5, 16]
[16.575, 32.05): [21, 29.7]
[32.05, 47.525): []
[47.525, 63.0): [51, 61]
[63.0, 78.475): [63]

```

And finally, we graph!

For our purposes, a bar will be a  stacked for the number of observations in the class (because I think that looks good). You can count the  as one byte in your source code. There should be no space between bars (unless there is an empty bar), nor do you need to label axes or any of that fancy stuff. There can be trailing whitespace at the end of your output. In our case, that would be:

```
▉
▉
▉
▉
▉
▉
▉▉
▉▉ ▉
▉▉ ▉▉

```

**This is , so shortest code in bytes wins!**

# Answer
# 05AB1E, ~~50~~ ~~49~~ 52 bytes

```
g.²òD>Ýs¹ZsWs\©-s/*®+v¹y.S>_O})¥ZUv'▉y×ðXy-×«S})øRJ»

```

Try it online!

**Explanation**

First we calculate k as the inclusive round up of log2 of the input length.

`g.²ò`

We then construct a list of upper bounds of the classes.
This is constructerd as `range[0 .. k+1]*((max(input) - min(input))/k)+min(input)` using the code:

`D>Ýs¹ZsWs\©-s/*®+`

Now we loop over this list counting the numbers of the input under these upper bounds. As we only want the numbers between each lower and upper bound we reduce this list by subtraction. Unfortunately due to a bug when comparing floats this becomes longer than it should be.

`v¹y.S>_O})¥`

Now that we have a list of the observation within each class we loop over these creating a matrix of the special char and fill them out with spaces so that each row in the matrix will have equal length.

`v'▉y×ðXy-×«S})`

This matrix has the staples of the histogram horizontally and we want them vertically. To remedy this, we transpose the matrix. This is the reason we filled the rows with spaces (as transpose need equal length lists). This gives us vertical bars starting from the top running down, so we reverse the order of the rows in the matrix. Now that we have the data in the correct order we print the matrix by joining the rows and joining the columns on newlines.

`øRJ»`
> 2 votes

# Answer
# Python 3, 139

Generates histogram with numpy, takes on account the strange last column rule and prints.

```
from numpy import*
def f(l):
 h,_=histogram(l,'fd');h[-1]-=1
 for i in zip(*((max(h)-i)*' '+i*'▉'for i in append(h,1))):print(''.join(i))

```
> 3 votes

# Answer
# CJam, ~~72~~ 71 bytes

```
l',-~$__,2b,\)\(:A\;-\d/:B;{AB+:A;_{A<},,_@>}h;]_:e>:M;{'▉*MSe[}%NM*a+z

```

Try it online!

---

```
l',-~$     e# read and sorts the list
__,2b,     e# find k
\)\(:A     e# find max and min (keep min as A)
\;-\d/:B;  e# find width (keep as B)
{          e# while entries remain
  AB+:A;   e#    find intervals upper bound
  _{A<},,  e#    count entries below bound
  _@>      e#    remove entries below bound
}h;        e# end while
]_:e>:M;   e# find maximum size
{'▉*MSe[}% e# convert to bars and pad columns
NM*a+z     e# add newlines and transpose to display upright

```
> 2 votes

# Answer
# Pyth, 76 bytes

This code is absolutely disgusting. I've mentioned before how bad I am at golfing string-output challenges, right?

```
J_Mr8Smf>+*T/-h.MZQKh.mbQ.EllQKd)Q)=Y_.tUMme@+J]0xhMJdSheJ;jmj""m@"▉ "qk\ dY

```

Explanation to follow.

Test it out online!
> 1 votes

# Answer
# R, ~~105~~ 95 bytes (non-competing)

Takes input from stdin, prints to stdout. As a bonus, outputs an actual histogram as well as the ASCII art. Was able to golf away 10 bytes thanks to partial argument matching (`c` instead of `counts`) and reworking the output so as to avoid using `apply`.

```
cat(t(cbind(sapply(h<-hist(scan())$c,function(i)c(rep(" ",max(h)-i),rep("▉",i))),"\n")),sep="")

```

Input:

```
1.1, 3, 5, 13, 15.5, 21, 29.7, 63, 16, 5, 5.1, 5.01, 51, 61, 1

```

Output:

```
▉
▉
▉
▉
▉▉
▉▉▉   ▉
▉▉▉  ▉▉

```

This version is non-competing because it just lets R decide what the best number of bins is, using Sturge's formula. (Sturges, H. A. (1926) The choice of a class interval. *Journal of the American Statistical Association* 21, 65–66.) The OP uses a specific method, which has the last bar reserved exclusively for the maximum value, which is bizarre. R makes it hard to do it this way (perhaps because it was built by statisticians), but it's still possible, in **165** bytes:

```
k=ceiling(log2(length(i<-scan())))
cat(t(cbind(sapply(h<-hist(i,br=min(i)+diff(range(i))/k*0:(k+1)-1e-5)$c,function(i)c(rep(" ",max(h)-i),rep("▉",i))),"\n")),sep="")

```

Example output:

```
▉
▉
▉
▉
▉
▉
▉
▉
▉▉ ▉
▉▉ ▉▉

```
> 1 votes

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


title: String Similarity using Jaro-Winkler

text:
# Question
Title: String Similarity using Jaro-Winkler
# String Similarity

String similarity is basically a ratio of how similar one string is to another. This can be calculated in many ways, and there are various algorithms out there for implementing a ratio calculation for string similarity, some being more accurate than others. It's actually very useful to use these methods in diff algorithms for the calculation of how similar one document or string is to one another.

A couple of the most popular algorithms are:

In practice, calculating all three and taking the average works very well for most purposes. However, to keep the challenge more simple, I am not going to over-ask. For the purpose of this challenge, you must implement the **Jaro-Winkler algorithm**.

# Rules

* Built ins are welcome, but must be marked non-competing, (E.G. `.L` *\- **05AB1E***)
* Your input must only be 2 strings `f(a,b)`.
* The comparison should be Case insensitive, that is to say: `f('aBc','aBC')=f('abc','Abc')=f('abc','abc')=1.0`
In other words, convert the strings to lower case before the comparison or something like that.
* Your output must be a double, float or ratio appropriately expressed in the language of your choice; as long as the output is obviously interpreted, it's fine.
* This is , shortest answer wins.

# Examples

* `jw(a,b)` represents Jaro-Winkler similarity.

## Example Algorithm in Java

```
/**
 * Calculates the similarity score of objects, where 0.0 implies absolutely
 * no similarity and 1.0 implies absolute similarity.
 *
 * @param first
 *            The first string to compare.
 * @param second
 *            The second string to compare.
 * @return A number between 0.0 and 1.0.
 */
public static final double jaroSimilarity(final String first,
        final String second) {
    final String shorter;
    final String longer;

    // Determine which String is longer.
    if (first.length() > second.length()) {
        longer = first.toLowerCase();
        shorter = second.toLowerCase();
    } else {
        longer = second.toLowerCase();
        shorter = first.toLowerCase();
    }

    // Calculate the half length() distance of the shorter String.
    final int halflength = (shorter.length() / 2) + 1;

    // Find the set of matching characters between the shorter and longer
    // strings. Note that
    // the set of matching characters may be different depending on the
    // order of the strings.
    final String m1 = getSetOfMatchingCharacterWithin(shorter, longer,
            halflength);
    final String m2 = getSetOfMatchingCharacterWithin(longer, shorter,
            halflength);

    // If one or both of the sets of common characters is empty, then
    // there is no similarity between the two strings.
    if (m1.length() == 0 || m2.length() == 0)
        return 0.0;

    // If the set of common characters is not the same size, then
    // there is no similarity between the two strings, either.
    if (m1.length() != m2.length())
        return 0.0;

    // Calculate the number of transpositions between the two sets
    // of common characters.
    final int transpositions = transpositions(m1, m2);

    // Calculate the distance.
    final double dist = (m1.length() / ((double) shorter.length())
            + m2.length() / ((double) longer.length()) + (m1.length() - transpositions)
            / ((double) m1.length())) / 3.0;
    return dist;

}

/**
 * Gets a set of matching characters between two strings. Two characters
 * from the first string and the second string are considered matching if
 * the character's respective positions are no farther than the limit value.
 *
 * @param first
 *            The first string.
 * @param second
 *            The second string.
 * @param limit
 *            The maximum distance to consider.
 * @return A string contain the set of common characters.
 */
private static final String getSetOfMatchingCharacterWithin(
        final String first, final String second, final int limit) {

    final StringBuilder common = new StringBuilder();
    final StringBuilder copy = new StringBuilder(second);
    for (int i = 0; i < first.length(); i++) {
        final char ch = first.charAt(i);
        boolean found = false;

        // See if the character is within the limit positions away from the
        // original position of that character.
        for (int j = Math.max(0, i - limit); !found
                && j < Math.min(i + limit, second.length()); j++) {
            if (copy.charAt(j) == ch) {
                found = true;
                common.append(ch);
                copy.setCharAt(j, '*');
            }
        }
    }
    return common.toString();
}

/**
 * Calculates the number of transpositions between two strings.
 *
 * @param first
 *            The first string.
 * @param second
 *            The second string.
 * @return The number of transpositions between the two strings.
 */
private static final int transpositions(final String first,
        final String second) {
    int transpositions = 0;
    for (int i = 0; i < first.length(); i++) {
        if (first.charAt(i) != second.charAt(i)) {
            transpositions++;
        }
    }
    transpositions /= 2;
    return transpositions;
}

```

Here's all my test cases, if you want another one, ask me.

```
jw ('abc','AbC')=1.0
jw ('i walked to the store','the store walked to i')=0.7553688141923436
jw ('seers','sears')=0.8666666666666667
jw ('banana','bandana')=0.9523809523809524
jw ('abc','xyz')=0.0
jw ('1234567890qwertyuiopasdfghjklzxcvbnm','mnbvcxzlkjhgfdsapoiuytrewq0987654321')=0.5272904483430799
jw ('#faceroll:j4565j6eekty;fyuolkidsujkr79tp[8yiusyweryhjrn7ktgm9k,u[pk7jf6trhvgag5vhbdtnfymghu,','#faceroll:ezbrytnmugof7ihdgsyftwacvegybrnftiygihdugs5ya4tsyrdu6htifj7yif')=0.6512358338650381

```

# Answer
# Python 3, ~~351~~ ~~350~~ ~~347~~ 346 bytes

```
l=len
r=range
a,b=input(),input()
x,y=(a.lower(),b.lower())[::1-2*(l(a)>l(b))]
h=l(y)//2+1
n=o=''
for a,b in(x,y),(y,x):
 for i in r(l(a)):
  for j in r(max(0,i-h),min(i+h,l(b))):
   if b[j]==a[i]:o+=a[i];b=b[:j]+'*'+b[j+1:];break
 n,o=o,n
q,z=l(n),l(o)
print(0if(any((n,o))-1or z!=q)else(z/l(y)+q/l(x)+(z-sum(n[i]!=o[i]for i in r(l(n)))/2)/z)/3)

```

Expects the two inputs on STDIN, newline-separated. Example run:

```
$ echo -e "seers\nsears" | python jaro.py
0.8666666666666667

```

*Saved 1 byte thanks to @Shebang!*
> 2 votes

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


title: Movie Title Styled String

text:
# Question
Title: Movie Title Styled String
**Challenge**

Ever seen those movie trailer titles (namely Martian, Interstellar, etc) where they have huge gaps in between letters slowly spreading out?

The challenge is to recreate this effect given a string, gap multiplier and direction, by inserting appropriate amount of spaces in between the letters.

**Example**

**Input**: 'INTERSTELLAR', Gap multiplier: 1.0, Direction: Increasing Inward

```
Output: I N  T   E    R     S      T     E    L   L  A R

```

The spacing is: \[1, 2, 3, ... , 3, 2, 1\]; replacing the spaces with '.' to better demonstrate the spacing:

```
I.N..T...E....R.....S......T.....E....L...L..A.R

```

**Input**: 'INTERSTELLAR', Gap multiplier: 0.5, Direction: Increasing Inward

```
Output: IN T E  R  S   T  E  L L AR

```

The spacing is multiplied by 0.5, therefore we get \[0, 1, 1, 2, ... 2, 1, 1, 0\] from integer division; using '.':

```
IN.T.E..R..S...T..E..L.L.AR

```

**Input**: 'CODEGOLF', Gap multiplier: 2.0, Direction: Increasing Outward

```
Output: C        O      D    E  G    O      L        F

```

The spacing is multiplied by 2, increasing outward, therefore we get \[8,6,4,2,4,6,8\]; replacing with '.':

```
C........O......D....E..G....O......L........F

```

**Input**: 'CODEGOLF', Gap multiplier: 0.4, Direction: Increasing Outward

```
Output: C O DEGO L F

```

The spacing is multiplied by 0.4, increasing outward, therefore we get \[1,1,0,0,0,1,1\]; replacing with '.':

```
C.O.DEGO.L.F

```

**Rules**

* Takes 3 input: string, gap multiplier and direction
* If input string is odd in length (even in # of gaps) e.g. 'HELLO', the spacing of the inner most 2 gaps should be the same `H E L L O`
* The direction and gap multiplier can be parsed however you want, e.g. you could use -2 as 'increasing inward with a multiplier of 2', 1 as 'increasing outward with a multiplier of 1', etc.
* It is only required to use spaces, however it is a bonus if the character filling is customizable.

**Reference Animation**

Have fun golfing!

# Answer
## JavaScript (ES6), ~~86~~ ~~82~~ ~~81~~ 80 bytes

Input is expected in currying syntax `f(s)(r)`, with:

* `s` = string
* `r` = ratio + direction: a negative float for inward or a positive float for outward

```
let f =

s=>r=>s.replace(/./g,(c,i)=>c+' '.repeat(n+=i<l?-r:r),l=s.length/2,n=r>0&&l*r+r)

console.log(f("INTERSTELLAR")(-1));
console.log(f("INTERSTELLAR")(-0.5));
console.log(f("CODEGOLF")(2));
console.log(f("CODEGOLF")(0.4));
```
> 3 votes

# Answer
# 05AB1E, 33 bytes

Uses CP-1252 encoding.

Gap multiplier is taken as negative when outwards increasing.

```
g;>Î.S<_²**ÄU¹vyð²¹g<;N.S*X+DUï×J

```

Try it online!
> 2 votes

# Answer
# PHP, 129 Bytes

12 Bytes saved by @Titus Thank You

string = $argv\[1\],ratio = $argv\[2\], direction = $argv\[3\] inward = 0 ,Outward =1

```
for($i=0;$i+1<2*$l=strlen($t=($x=$argv)[1]);)echo$i%2?str_pad("",$x[2]*abs($x[3]*(0^$l/2+1)-($i++>=$l?$l-$i/2:$i/2))):$t[$i++/2];

```
> 1 votes

# Answer
# APL, 40 bytes

```
{⍵\⍨0~⍨∊1,⍨1,¨-⌊⍺×(1+⌈/-+)⍣⍺⍺(⌽⌊+)⍳⍴1↓⍵}

```

This takes the string as its right argument, the ratio as its left argument and the direction as its left operand (0 for inward and 1 for outward).

```
      1 (0 {⍵\⍨0~⍨∊1,⍨1,¨-⌊⍺×(1+⌈/-+)⍣⍺⍺(⌽⌊+)⍳⍴1↓⍵}) 'INTERSTELLAR'
I N  T   E    R     S      T     E    L   L  A R
      0.5 (0 {⍵\⍨0~⍨∊1,⍨1,¨-⌊⍺×(1+⌈/-+)⍣⍺⍺(⌽⌊+)⍳⍴1↓⍵}) 'INTERSTELLAR'
IN T E  R  S   T  E  L L AR
      2 (1 {⍵\⍨0~⍨∊1,⍨1,¨-⌊⍺×(1+⌈/-+)⍣⍺⍺(⌽⌊+)⍳⍴1↓⍵}) 'CODEGOLF'
C        O      D    E  G    O      L        F
      0.4 (1 {⍵\⍨0~⍨∊1,⍨1,¨-⌊⍺×(1+⌈/-+)⍣⍺⍺(⌽⌊+)⍳⍴1↓⍵}) 'CODEGOLF'
C O DEGO L F

```

Explanation:

* `⍳⍴1↓⍵`: get a list of numbers from 1 to N-1, where N is the length of the string
* `(⌽⌊+)`: invert the list, and at each position, get the lowest number of both lists (this gives the sizes of the gaps if increasing inwards)
* `(1+⌈/-+)⍣⍺⍺`: subtract each number in the list from the highest number in the list, and add 1. Do this `⍺⍺` times. (If `⍺⍺=0`, nothing will happen, and if `⍺⍺=1`, this will give the sizes of the gaps if increasing outwards.)
* `-⌊⍺×`: multiply each gap by , round it downwards, and negate it.
* `∊1,⍨1,¨`: add a 1 in front of each gap, and a 1 at the very end of the list.
* `0~⍨`: remove any zeroes.
* `⍵\⍨`: use the resulting list to expand . Expand (`\`) works in the following manner: for each positive number, the current character is replicated that many times, and for each negative number, that many spaces are inserted, with the caveat that `0` and `¯1` do the same thing, which is why all the zeroes had to be removed earlier.
> 1 votes

# Answer
# MATL, 31 bytes

```
nq:tPvX<i?tX>Qw-]*kQ1whYs''1Gb(

```

Inputs are: string; `0` or `1` for inward or outward increasing; multiplier.

Try it online!

### Explanation

Consider inputs `'INTERSTELLAR'`, `1`, `0.5` as an example.

```
nq:    % Input string implicitly. Push [1 2 ... N-1] where N is the string length
       %   STACK: [1 2 3 4 5 6 7 8 9 10 11]
tP     % Duplicate, reverse
       %   STACK: [1 2 3 4 5 6 7 8 9 10 11], [11 10 9 8 7 6 5 4 3 2 1]
vX<    % Vertically concatenate. Minimum of each column
       %   STACK: [1 2 3 4 5 6 5 4 3 2 1]
i      % Input direction flag
       %   STACK: [1 2 3 4 5 6 5 4 3 2 1], 1
?      % If input flag was 1 (meaning outward increasing)
  tX>  %   Duplicate. Maximum
       %     STACK: [1 2 3 4 5 6 5 4 3 2 1], 6
  Q    %   Add 1
       %     STACK: [1 2 3 4 5 6 5 4 3 2 1], 7
  w-   %   Swap. Subtract
       %     STACK: [6 5 4 3 2 1 2 3 4 5 6]
]      % End
*k     % Input multiplier implicitly. Multiply. Round down
       %   STACK: [3 2 2 1 1 0 1 1 2 2 3]
Q      % Add 1
       %   STACK: [4 3 3 2 2 1 2 2 3 3 4]
1wh    % Prepend a 1
       %   STACK: [1 4 3 3 2 2 1 2 2 3 3 4]
Ys     % Cumulative sum
       %   STACK: [1  5  8 11 13 15 16 18 20 23 26 30]
''     % Push empty string
       %   STACK: [1  5  8 11 13 15 16 18 20 23 26 30], ''
1G     % Push input string again
       %   STACK: [1  5  8 11 13 15 16 18 20 23 26 30], '', 'INTERSTELLAR'
b      % Bubble up
       %   STACK: '', 'INTERSTELLAR', [1  5  8 11 13 15 16 18 20 23 26 30]
(      % Assign the characters from the top string into the empty string at the
       % given positions. Intermediate positions are filled with character 0,
       % which is displayed as a space
       %   STACK: 'I   N  T  E R ST E L  L  A   R'
       % Dispaly implicitly

```
> 1 votes

# Answer
## Racket 348 bytes

```
(define(f s)(let*((c #\space)(sp(λ(l)(define ol'())(for((i(length l)))(for((j i))
(set! ol(cons c ol)))(set! ol(cons(list-ref l i)ol)))(for((n(floor(/(length l)2))))
(set! ol(cons c ol)))ol))(m(floor(/(string-length s)2)))(s1(sp(string->list(substring s 0 m)
)))(s2(sp(reverse(string->list(substring s m))))))(list->string(append(reverse s1)s2))))

```

Ungolfed:

```
(define(f s)
  (let* ((c #\space)
         (sp (λ (l)           ; subfn to add increasing spaces to list of characters
               (define ol '())
               (for ((i (length l)))
                 (for ((j i))
                   (set! ol (cons c ol)))
                 (set! ol (cons (list-ref l i)ol)))
               (for ((n (floor(/ (length l)2))))
                 (set! ol (cons c ol)))
               ol))
         (m (floor (/ (string-length s) 2)))                 ; find midpoint
         (s1 (sp (string->list (substring s 0 m))))          ; add spaces to first part
         (s2 (sp (reverse (string->list (substring s m)))))) ; add spaces to second part
    (list->string (append (reverse s1) s2))                  ; re-combine 2 parts
    ))

```

Testing:

```
(f "INTERSTELLAR")

```

Output:

```
"I N  T   E    R     S      T     E    L   L  A R"

```
> 1 votes

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


title: Super Folding Numbers

text:
# Question
Title: Super Folding Numbers
We have already defined a folding number here.

But now we are going to define a Super Folding Number. A Super Folding number is a number that if folded enough times it will eventually reach one less than a power of two. The method of folding is slightly different than in the folding number question.

The folding algorithm goes as follows:

* Take the binary representation

e.g. 5882

```
1011011111010

```
* Spilt it into three partitions. First half, last half and middle digit (iff it has a odd number of digits)

```
101101 1 111010

```
* If the middle digit is zero this number cannot be folded
* Reverse the second half and superimposed on the first half

```
010111
101101

```
* Add the digits in place

```
111212

```
* Iff there are any 2s in the result the number cannot be folded otherwise the new number is the result of the folding algorithm.

A number is a Super Folding number if it can be folded to a continuous string of ones. (All Folding numbers are also Super Folding Numbers)

Your task is to write code that takes in a number and outputs a truthy value if the number is a Super Folding number and falsy otherwise. You will be scored on the size of your program.

## Examples

### 5200

Convert to binary:

```
1010001010000

```

Split in half:

```
101000 1 010000

```

The middle is one so we continue Superimpose the halves:

```
000010
101000

```

Added them:

```
101010

```

No twos so we continue Split in half:

```
101 010

```

Fold:

```
010
101

111

```

The result is `111` (7 in decimal) so this is a Super Folding Number.

## Test Cases

The first 100 Super Folding Numbers are:

```
[1, 2, 3, 6, 7, 8, 10, 12, 15, 20, 22, 28, 31, 34, 38, 42, 48, 52, 56, 63, 74, 78, 90, 104, 108, 120, 127, 128, 130, 132, 142, 150, 160, 170, 178, 192, 204, 212, 232, 240, 255, 272, 274, 276, 286, 310, 336, 346, 370, 400, 412, 436, 472, 496, 511, 516, 518, 524, 542, 558, 580, 598, 614, 640, 642, 648, 666, 682, 704, 722, 738, 772, 796, 812, 852, 868, 896, 920, 936, 976, 992, 1023, 1060, 1062, 1068, 1086, 1134, 1188, 1206, 1254, 1312, 1314, 1320, 1338, 1386, 1440, 1458, 1506, 1572, 1596]

```

# Answer
> 9 votes
Here's my first ever shot at code golf:

# Python 3, 167 bytes

167 bytes if tabs or single spaces are used for indentation

```
def f(n):
 B=bin(n)[2:];L=len(B);M=L//2
 if'1'*L==B:return 1
 S=str(int(B[:M])+int(B[:-M-1:-1]))
 return 0if(~L%2==0and'0'==B[M])or'2'in S else{S}=={'1'}or f(int(S,2))

```

Edit: Thanks to everyone's help below, the code above has been reduced from an original size of 232 bytes!

# Answer
> 5 votes
## Java 7, 202 bytes

```
boolean g(Integer a){byte[]b=a.toString(a,2).getBytes();int i=0,l=b.length,o=0,c,z=(a+1&a)==0?-1:1;for(;i<l/2&z>0;o+=o+c*2,z*=c>1|(l%2>0&b[l/2]<49)?0:1)c=b[i]+b[l-++i]-96;return z<0?1>0:z<1?0>1:g(o/2);}

```

It took a bit of effort to make the old folding function recursable, but here it is. It's ugly as sin, to be honest. I'll have to take a look in the morning to see if I can golf it further, since I can barely stand to look at it right now.

With line breaks:

```
boolean g(Integer a){
    byte[]b=a.toString(a,2).getBytes();
    int i=0,l=b.length,o=0,c,z=(a+1&a)==0?-1:1;
    for(;i<l/2&z>0;o+=o+c*2,z*=c>1|(l%2>0&b[l/2]<49)?0:1)
        c=b[i]+b[l-++i]-96;
    return z<0?1>0:z<1?0>1:g(o/2);
}

```

# Answer
> 3 votes
# CJam, ~~47~~ 44 bytes

```
ri2b{_W%.+__0e=)\_,1>\0-X+:*3<*&}{_,2/<}w2-!

```

Try it online! or generate a list of super folding numbers up to a given number.
Golfing attempts can be seen here.

---

The code breaks down to the following phases:

```
ri2b                e# get input in binary
{                   e# While fold is legal
 _W%.+_             e#   "fold" the whole number onto itself
 _0e=)\             e#   count zeros and add 1 (I)
 _,1>\              e#   size check, leave 0 if singleton (II)*
 0-X+:*3<           e#   product of 2s, leave 0 if too many (III)
 *&                 e#   (II AND III) AND parity of I
}{                  e# Do
 _,2/<              e#   slice opposite to the actual fold**
}w                  e# End while
2-!                 e# return 1 if "fold" ended in all 2s

```

**EDIT:** This version more or less takes a De Morgan's Law approach to the previous version.

*\*The problem with running on singletons is that we get stuck with an empty string after the slice.*

*\** If a binary number is super folding, its mirror image (with leading 0s if needed) is. This saves a byte over taking the right half.*

# Answer
> 2 votes
# JavaScript, 149 bytes

```
f=(i,n=i.toString(2),l=n.length,m=l/2|0)=>/^1*$/.test(n)?1:/[^01]/.test(n)|!+n[m]&l?0:f(0,+n.slice(0,m)+ +n.slice(m+l%2).split``.reverse().join``+"")

```

Defines a recursive function.

## Explanation:

```
f=(i                       //Defines the function: i is input
,n=i.toString(2)           //n is the current number
,l=n.length                //l is the length of the number,
,m=l/2|0)=>                //m is the index of the center character
/^1*$/.test(n)?1:          //returns 1 if the number is all ones
/[^01]/.test(n)            //returns 0 if the number has any chars other than 0 or 1
|!+n[m]&l?0:               //or if the middle char is 0
f(0,+n.slice(0,m)+ +n.slice(m+l%2).split``.reverse().join``+"")
                           //otherwise recurses using the first half of the number plus the second half

```

# Answer
> 2 votes
## JavaScript (ES6), ~~113~~ ~~109~~ 108 bytes

```
f=(n,[h,...r]=n.toString(2),b='')=>++n&-n-n?h?f(2,r,r[0]?b+(h- -r.pop()):+h?b:2):!isNaN(n=+('0b'+b))&&f(n):1

```

### Formatted and commented

```
f = (                               // given:
  n,                                // - n = integer to process
  [h, ...r] = n.toString(2),        // - h = highest bit, r = remaining low bits
  b = ''                            // - b = folded binary string
) =>                                //
  ++n & -n - n ?                    // if n is not of the form 2^N - 1:
    h ?                             //   if there's still at least one bit to process:
      f(                            //     do a recursive call with:
        2,                          //     - n = 2 to make the 2^N - 1 test fail
        r,                          //     - r = remaining bits
        r[0] ?                      //     - if there's at least one remaining low bit:
          b + (h - -r.pop())        //       append sum of highest bit + lowest bit to b
        : +h ? b : 2                //       else, h is the middle bit: let b unchanged
      )                             //       if it is set or force error if it's not
    : !isNaN(n = +('0b' + b)) &&    //   else, if b is a valid binary string:
      f(n)                          //     relaunch the entire process on it
  : 1                               // else: n is a super folding number -> success

```

### Demo

```
f=(n,[h,...r]=n.toString(2),b='')=>++n&-n-n?h?f(2,r,r[0]?b+(h- -r.pop()):+h?b:2):!isNaN(n=+('0b'+b))&&f(n):1

// testing integers in [1 .. 99]
for(var i = 1; i < 100; i++) {
  f(i) && console.log(i);
}

// testing integers in [1500 .. 1599]
for(var i = 1500; i < 1600; i++) {
  f(i) && console.log(i);
}
```

# Answer
> 2 votes
# Perl, ~~71~~ 70 bytes

Includes +1 for `-p`

Give number on STDIN

`superfolding.pl`:

```
#!/usr/bin/perl -p
$_=sprintf"%b",$_;s%.%/\G0$/?2:/.\B/g&&$&+chop%eg while/0/>/2/;$_=!$&

```

# Answer
> 1 votes
# Python 2, 151 bytes

```
f=lambda n,r=0:f(bin(n)[2:],'')if r<''else(r==''and{'1'}==set(n)or(n in'1'and f(r,'')+2)or n!='0'and'11'!=n[0]+n[-1]and f(n[1:-1],r+max(n[0],n[-1])))%2

```

**ideone**

A doubly-recursive function which takes an integer, `n`, and returns `0` or `1`.

A variable `r` is maintained to allow both the result of folding and to know if we currently: have an integer (first only); have a new binary string to try to fold (outer); or are folding (inner).

On the first pass `n` is and integer, which is `<''` in Python 2 so the recursion starts by casting to a binary string.

The next execution has `r=''` and so the test `{'1'}==set(n)` is executed to check for a continuous string of `1`s (the RHS cannot be `{n}` as we may need to pass this point later with `r=''` and an empty `n` when that would be a dictionary which wont equal `{'1'}`, a set).

If this is not satisfied the inner tail criteria is tested for (even if unnecessary): if `n in'1'` will evaluate to True when `n` is an empty string or a single `1`, whereupon a new outer recursion is begun by placing `r`, by the then folded, binary string into `n` and `''` into `r`. The literal `2` is added to the result of this function call to allow no fall through to the next part (to the right of a logical `or`) that is corrected later.

If that is not a truthy value (all non-zero integers are truthy in Python) the outer tail recursion criteria is tested for: `n!=0` excludes the case with a middle `0` and the outer two characters are tested they do not sum to `2` by the string concatenation `'11'!=n[0]+n[-1]`; if these both hold true the outer bits are discarded from `n` with `n[1:-1]`, and then a `1` is appended to `r` if there is one on the outside otherwise a `0` is, using the fact that `'1'>'0'` in Python with `max(n[0],n[-1])`.

Finally the addition of `2` at each inner recursion is corrected with `%2`.

# Answer
> 0 votes
# PHP, 113 bytes

```
for($n=$argv[1];$n!=$c;$n=($a=$n>>.5+$e)|($b=$n&$c=(1<<$e/=2)-1))if($a&$b||($e=1+log($n,2))&!(1&$n>>$e/2))die(1);

```

exits with error (code `1`) if argument is not super-folding, code `0` else. Run with `-r`.
Input `0` will return true (code `0`).

**breakdown**

```
for($n=$argv[1];
    $n!=$c;                 // loop while $n is != mask
                            // (first iteration: $c is null)
    $n=                     // add left half and right half to new number
        ($a=$n>>.5+$e)      // 7. $a=left half
        |
        ($b=$n&             // 6. $b=right half
            $c=(1<<$e/=2)-1 // 5. $c=mask for right half
        )
)
    if($a&$b                // 1. if any bit is set in both halves
                            // (first iteration: $a and $b are null -> no bits set)
        ||                  // or
        ($e=1+log($n,2))    // 2. get length of number
        &
        !(1&$n>>$e/2)       // 3. if the middle bit is not set -> 1
                            // 4. tests bit 0 in length --> and if length is odd
    )
    die(1);                 // -- exit with error

```

# Answer
> 0 votes
# PHP, 197 Bytes

```
function f($b){if(!$b)return;if(!strpos($b,"0"))return 1;for($n="",$i=0;$i<($l=strlen($b))>>1;)$n.=$b[$i]+$b[$l-++$i];if($l%2&&!$b[$i]||strstr($n,"2"))return;return f($n);}echo f(decbin($argv[1]));

```

Expanded

```
function f($b){
    if(!$b)return; # remove 0
    if(!strpos($b,"0"))return 1; # say okay alternative preg_match("#^1+$#",$b)
    for($n="",$i=0;$i<($l=strlen($b))>>1;)$n.=$b[$i]+$b[$l-++$i]; #add first half and second reverse
    if($l%2&&!$b[$i]||strstr($n,"2"))return; #if middle == zero or in new string is a 2 then it's not a number that we search
    return f($n); #recursive beginning
}
echo f(decbin($argv[1]));

```

True values \< 10000

> 1, 2, 3, 6, 7, 8, 10, 12, 15, 20, 22, 28, 31, 34, 38, 42, 48, 52, 56, 63, 74, 78, 90, 104, 108, 120, 127, 128, 130, 132, 142, 150, 160, 170, 178, 192, 204, 212, 232, 240, 255, 272, 274, 276, 286, 310, 336, 346, 370, 400, 412, 436, 472, 496, 511, 516, 518, 524, 542, 558, 580, 598, 614, 640, 642, 648, 666, 682, 704, 722, 738, 772, 796, 812, 852, 868, 896, 920, 936, 976, 992, 1023, 1060, 1062, 1068, 1086, 1134, 1188, 1206, 1254, 1312, 1314, 1320, 1338, 1386, 1440, 1458, 1506, 1572, 1596, 1644, 1716, 1764, 1824, 1848, 1896, 1968, 2016, 2047, 2050, 2054, 2058, 2064, 2068, 2072, 2110, 2142, 2176, 2180, 2184, 2222, 2254, 2306, 2320, 2358, 2390, 2432, 2470, 2502, 2562, 2576, 2618, 2650, 2688, 2730, 2762, 2866, 2898, 2978, 3010, 3072, 3076, 3080, 3132, 3164, 3244, 3276, 3328, 3380, 3412, 3492, 3524, 3584, 3640, 3672, 3752, 3784, 3888, 3920, 4000, 4032, 4095, 4162, 4166, 4170, 4176, 4180, 4184, 4222, 4318, 4416, 4420, 4424, 4462, 4558, 4674, 4688, 4726, 4822, 4928, 4966, 5062, 5186, 5200, 5242, 5338, 5440, 5482, 5578, 5746, 5842, 5986, 6082, 6208, 6212, 6216, 6268, 6364, 6508, 6604, 6720, 6772, 6868, 7012, 7108, 7232, 7288, 7384, 7528, 7624, 7792, 7888, 8032, 8128, 8191, 8202, 8206, 8218, 8232, 8236, 8248, 8318, 8382, 8456, 8460, 8472, 8542, 8606, 8714, 8744, 8814, 8878, 8968, 9038, 9102, 9218, 9222, 9234, 9248, 9252, 9264, 9334, 9398, 9472, 9476, 9488, 9558, 9622, 9730, 9760, 9830, 9894, 9984

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


title: Show off your tree analysing toolbox

text:
# Question
Title: Show off your tree analysing toolbox
As a programmer or computer scientist one might encounter quite a lot of trees - of course not the woody growing-in-the-wrong-direction kind, but the nice, pure mathematical kind:

```
  *<- root (also a node)
 /|\<- edge
* * *<- inner node
|  / \
* *   *<- leaf (also a node)
  |
  *

```

Naturally over time we all have put together our own small handy toolbox to analyse such trees as we encounter them, right? Now is the time to show it off!

---

**Task**

The toolbox must include the following functions:

* `size`: The number of nodes in the tree.
* `depth`: The number of edges on the longest path from the root to any leaf.
* `breadth`: The number of leaves.
* `degree`: The maximum number of child nodes for any node.

You have to submit a program or function for each of the tools, however they might share subroutines (e.g. parsing) which then have to be submitted only once. Note that those subroutines need to be full programs or functions too.

---

**Input Format**

The trees can be given in any reasonable format capturing the structure, e.g. the tree

```
  *
 / \
*   *

```

could be represented through parentheses `(()())`, lists of lists `[[],[]]`, or data structures with a constructor `T[T[],T[]]`. However not through linearisation `[2,0,0]` or a format like `(size, depth, breath, degree, whatever-else-is-needed-to-make-this-format-unique-for-every-tree)`. Generally speaking, your tree format should not contain numbers.

**Output Format**

A natural number for each of the properties described above.

**Scoring**

Lowest code in bytes for the 4 functions *in every language* wins, thus I will not accept an answer.

Feel free to provide additional tree tools like `fold`, `isBinaryTree`, `preLinearise`, `postLinearize`, or whatever you like. Of course those don't have to be included in the byte count.

**Examples**

First the tree is given in the sample formats from above, then the results of the functions as `(size, depth, breadth, degree)`.

```
()
[]
T[]
(1,0,1,0)

(()())
[[],[]]
T[T[],T[]]
(3,1,2,2)

((())()((())()))
[[[]],[],[[[]],[]]]
T[T[T[]],T[],T[T[T[]],T[]]]
(8,3,4,3)

((()())((())()((())()))(()())(()))
[[[],[]],[[[]],[],[[[]],[]]],[[],[]],[[]]]
T[T[T[],T[]],T[T[T[]],T[],T[T[T[]],T[]]],T[T[],T[]],T[T[]]]
(17,4,9,4)

((((((((()))))))))
[[[[[[[[[]]]]]]]]]
T[T[T[T[T[T[T[T[T[]]]]]]]]]
(9,8,1,1)

(((((((()()))((()()))))((((()()))((()()))))))((((((()()))((()()))))((((()()))((()())))))))
[[[[[[[[],[]]],[[[],[]]]]],[[[[[],[]]],[[[],[]]]]]]],[[[[[[[],[]]],[[[],[]]]]],[[[[[],[]]],[[[],[]]]]]]]]
T[T[T[T[T[T[T[T[],T[]]],T[T[T[],T[]]]]],T[T[T[T[T[],T[]]],T[T[T[],T[]]]]]]],T[T[T[T[T[T[T[],T[]]],T[T[T[],T[]]]]],T[T[T[T[T[],T[]]],T[T[T[],T[]]]]]]]]
(45,7,16,2)

```

# Answer
> 8 votes
## Ruby, ~~122~~ 110 bytes

```
f=->s{->t{t.to_s.scan(s).size}}
s=f[?[]
d=->t{[-1,*t.map(&d)].max+1}
b=f['[]']
g=->t{([t.size]+t.map(&g)).max}

```

Inspired by Neil's JavaScript solution. **d** and **g** are just translations from his JS to Ruby. For **s** and **b** I'm using string conversion tricks.

Shaved a few bytes off of **s** and **b** by adding the helper **f**, and a few more byte off of **d** and **g** thanks to Jordan.

# Answer
> 4 votes
## Python, 136 bytes

```
f=lambda z,c:lambda t:eval(t,{'T':lambda*a:a and eval(z)or c})
s,d,b,g=map(f,['sum(a)+1','max(a)+1','sum(a)','max(len(a),*a)'],[1,0]*2)

```

The input format is the 'T\[\]' format but with parens instead of brackets and passed as a string. It's the longest submission so far, but I thought the approach is pretty cute.

# Answer
> 3 votes
## tinylisp, 248 bytes

```
(d X(q((m n)(i(l m n)n m))))(d F(q(()g(c(q(T))(c(c(q i)(c(q T)g))())))))(d S(F(s(S(h T))(s 0(S(t T))))1))(d H(F(X(s 1(s 0(H(h T))))(H(t T)))0))(d B(F(s(B(h T))(s 0(i(t T)(B(t T))0)))1))(d C(F(s 1(s 0(C(t T))))0))(d D(F(X(C T)(X(D(h T))(D(t T))))0))

```

Fun fact: 49% of that program is parentheses.

tinylisp is a minimalistic version of Lisp, containing only 10 built-in functions and macros. Because Lisp is awesome, it is nonetheless very powerful, and well-suited to manipulating abstract data structures like trees.

The program defines functions `S`, `H` (for "height"), `B`, and `D`, as well as a max function `X` and a number-of-children function `C`. It uses the `(()())` form of trees, with the added requirement that each tree must be *quoted* to be treated as data rather than code: `(q (()()))`. Example run:

```
tl> (d tree (q ((())()((())()))))
tree
tl> (S tree)
8
tl> (H tree)
3
tl> (B tree)
4
tl> (D tree)
3

```

Here's an ungolfed version, with a couple extra utility functions defined to make things clearer. For reference, the built-ins used are `d`efine, `q`uote, `i`f, `l`ess than, `c`ons, `s`ubtract, `h`ead, and `t`ail. (Yes, addition has to be implemented from subtraction.)

```
(d lambda (q (() args args)))

(d add
 (lambda (a b)
  (s a (s 0 b))))

(d max
 (lambda (a b)
  (i (l a b) b a)))

(d size
 (lambda (tree)
  (i tree
   (add (size (h tree)) (size (t tree)))
   1)))

(d depth
 (lambda (tree)
  (i tree
   (max (add 1 (depth (h tree))) (depth (t tree)))
   0)))

(d breadth
 (lambda (tree)
  (i tree
   (add
    (breadth (h tree))
    (i (t tree)
     (breadth (t tree))
     0))
   1)))

(d children
 (lambda (tree)
  (i tree
   (add 1 (children (t tree)))
   0)))

(d degree
 (lambda (tree)
  (i tree
   (max (children tree) (max (degree (h tree)) (degree (t tree))))
   0))))

```

This is pretty horrible Lisp style, since there's no tail recursion, but hey--it's code golf. ;^)

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

```
s=a=>a.reduce((r,e)=>r+s(e),1)
d=a=>Math.max(...a.map(d),-1)+1
b=a=>a.reduce((r,e)=>r+b(e),+!a[0])
g=a=>Math.max(...a.map(g),a.length)

```

Since all the functions are recursive, I've given them one letter names to save bytes: **s**ize, **d**epth, **b**readth and de**g**ree. Takes input using the `[,]` format.

# Answer
> 2 votes
## Perl 5 - 130 bytes

```
sub z{$_[0]=~y/<//c}
sub d{$_=$_[0];{s/><//&&redo}-1+z$_}
sub b{()=$_[0]=~/<>/g}
sub g{(grep{$_[0]=~/<(<(?1)*>){$_}>/}0..z$_)[-1]}

```

These take input as a string using angle brackets (e.g. `<<><>>`). `z` (size) and `b` (breadth) count the substrings for either all nodes or leafs, `d` (depth) collapses adjacent nodes until there's no branching then gets the size, and `g` (degree) uses a recursive regex to test for the presence of nodes of each degree up to the size then returns the largest found.

# Answer
> 2 votes
# C#, ~~380~~, 357 bytes

I've just noticed I forgot to remove some of my test code, so 23 bytes shaved off...

This is my first submission on PPCG and I'm not sure if the format is entirely correct especially because I'm using C#, but here are my four functions:

```
int d(string t){int l=-1,p=0;t.Max(m=>p=p<(l+=m=='('?1:-1)?l:p);return p;}
int s(string t){return t.Count(c=>c=='(');}
int f(string t){int q=0,w=d(t)+2;int[]l=new int[w],i=new int[w];t.Max(m=>l[q]=m=='('?l[q++]+1:(0*(i[q]=l[q]>i[q]?l[q]:i[q])*(q--)));return i.Max();}
int b(string t){var f='(';int l=0;t.Max(m=>l+=(f=='('&m==')')?(f=m)*0+1:(f=m)*0);return l;}

```

d: Depth s: Size: f: Degree b: Breadth

The functions use `()` as input

I'm using LINQ's Max function to iterate through the items in the string array. I'm not using the functionality of `Max`, I only use it because it's the shortest iterative function; I could just as well have used `Min`. There's no recursion and all is done in linear time.

A slightly more readable version of my code, but the LINQ is still a bit cryptic:

```
    /*Depth: Increment counter on open bracket and
     decrement on closed bracket;
     return highest number reached*/
    int d(string t)
    {
        int l = -1, p = 0;
        t.Max(m => p = p < (l += m == '(' ? 1 : -1) ? l : p);
        return p;
    }

    int s(string t)//Size: Count the number of open brackets
    {
        return t.Count(c => c == '(');
    }

    int f(string t)//Degree, this one took me hours to figure out
    {
        int q = 0, w = d(t) + 2;
        int[] l = new int[w], i = new int[w];
        t.Max(m => l[q] = m == '(' ? l[q++] + 1 : (0 * (i[q] = l[q] > i[q] ? l[q] : i[q]) * (q--)));
        return i.Max();
    }

    int b(string t)//Breadth
    {
        var f = '(';
        int l = 0;
        t.Max(m => l += (f == '(' & m == ')') ? (f = m) * 0 + 1 : (f = m) * 0);
        return l;
    }

```

# Answer
> 1 votes
# Mathematica, 77 bytes

```
s=LeafCount
d=Depth@#-2&
b=Length@Level[#,{-2}]&
g=Max[Length@#,##&@@#]&//@#&

```

Take any Mathematica expression as input.

# Answer
> 0 votes
# Standard ML, 149 bytes

```
val m=Int.max
val% =foldl
fun f?(T%)= ?(map(f?)%)
val s=f(%op+1)
val d=f(fn t=>1+ %m~1t)
val b=f(fn[]=>1|t=> %op+0t)
val g=f(fn t=>m(length t,%m 0t))

```

Try it on Tutorialspoint. Uses the constructor notation (e.g. `T[T[],T[]]`) with the following data structure declaration: `datatype tree = T of tree list`

Ungolfed:

```
fun fold f (T xs) = f (map (fold f) xs)

val size    = fold (foldl op+ 1)
val depth   = fold (fn t => 1 + foldl Int.max ~1 t)
val breadth = fold (fn nil => 1 | t => foldl op+ 0 t)
val degree  = fold (fn t => Int.max(length t, foldl Int.max 0 t))

```

---
Tags: code-golf
---


title: pssssssssssssst

text:
# Question
Title: pssssssssssssst
**Introduction**

This is one is pretty straightforward. We will be drawing a snake in ascii. This was inspired by that old snake game where you have to collect the fruit and you continuously grow.

**Definition**

Given a positive integer N that represents the snake's length, draw a snake so that it has a body of n plus a head and a tail.

Parts:

* head: `<, >, ^, v`
* tail: `@`
* vertical: `|`
* horizonal: `-`

All corners should be satisfied with a `\` or `/` respectively. Unless the head ends on a corner in which case the head `<, >, ^, v` takes priority in the direction the snake is curled. i.e. for the length 1 example, it is turned counter clockwise and so the head is turned that way. For a clockwise solution it would be to the right `>`.

The snake must start in the middle with its tail but it may go outwards in any direction you choose either clockwise or counter-clockwise. It must also wrap tightly around itself as it expands outwards in a circular fashion.

**Example**

```
/--\
|/\|
||@|
|\-/
\--->

```

Where the `@` is the tail and starting position. As seen above the tail starts in the middle, goes up to the left in a counter-clockwise rotation outward.

Here the length is `19` plus a tail and a head.

As another example, here is length `1`:

```
<\
 @

```

**Winning**

This is code-golf so the answer that is submitted with the smallest number of bytes wins, with time to be used as a tie breaker.

Have fun!

# Answer
> 10 votes
# MATL, ~~85~~ 83 bytes

And I thought that having a `spiral` builtin would make for short code...

```
Oli2+XH:UQXItH:+XJh(YsXKoQ3I(4J(5l(H:)0HX^XkU(6H(3M1YL3X!P)'|-\/@' '<v>^'KHq))h0hw)

```

**Try it online!**

### Explanation

Let *N* denote the input. We will create a vector of length `ceil(sqrt(N+2))^2`, that is, the smallest perfect square that equals or exceeds *N*+2. This vector will be filled with numeric values, rolled into a spiral (that's why its length needs to be a perfect square), and then the numeric values will be replaced by characters.

Let *n* denote each step starting from 1 at the center of the spiral. The steps where the snake turns are given by *n*2+1 (that is: 2, 5, 10, ...) for `\` symbols and *n*2+*n*+1 (that is: 3, 7, 13, ...) for `/`. The steps between a `\` and a `/` should be `-`, and those between a `/` and a `\` should be `|`.

The vector is created such that it contains `1` at the turn points (2,3,5,7,10,13...) and `0` at the rest. The parity of the cumulative sum tells if each entry should be a `-` or a `|`. Adding 1 to this result we get a vector containing `1` (for `|`) or `2` (for `-`). But this makes the turn points themselves become `1` or `2` too. So the turn points, whose positions we know, are overwritten: positions *n*2+1 are filled with `3` and positions *n*2+*n*+1 are filled with `4`. The tail and head are also special cases: the first element of the vector (tail) is set to `5`, and the element with index *N*+2 (head) is set to `6`. Finally, elements with indices exceeding *N*+2 are set to `0`.

Taking input *N*=19 as an example, we now have a vector with length 25:

```
5 3 4 1 3 2 4 1 1 3 2 2 4 1 1 1 3 2 2 2 6 0 0 0 0

```

We need to roll this vector into a spiral. For this we use a builtin function that generates a spiral matrix, followed by a reflection and a transposition to produce:

```
13 12 11 10 25
14  3  2  9 24
15  4  1  8 23
16  5  6  7 22
17 18 19 20 21

```

Indexing the vector with the matrix gives

```
4 2 2 3 0
1 4 3 1 0
1 1 5 1 0
1 3 2 4 0
3 2 2 2 6

```

where `0` corresponds to space, `1` corresponds to `|`, `2`to `-`, `3` to `\`, `4` to `/`, `5` to `@`, and `6` to the head.

To know which of the four characters `^`, `<`, `v`, or `>` the head should have, we use the cumulative sum of turn points that we previously computed. Specifically, the second-last value of this cumulative sum (i.e. the *N*+1-th value) modulo 4 tells us which character should be used for the head. We take the second-last value of the cumulative sum, not the last, because of the requirement "if the head ends on a corner the head `<`, `>`, `^`, `v` takes priority in the direction the snake is curled". For the *N*=19 example the head is `>`.

Now we can build a string containing all the snake characters, including the appropriate character for the head at the sixth position: `'|-\/@> '`. We then index this string with the above matrix (indexing is 1-based and modular, so space goes last), which gives

```
/--\
|/\|
||@|
|\-/
\--->

```

# Answer
> 8 votes
# Python 2, ~~250~~ ~~233~~ 191 bytes

```
n=input()
l=[''],
a=x=0
b='@'
while a<=n:x+=1;l+=b,;l=zip(*l[::-1]);m=x%2;b='\/'[m]+x/2*'-|'[m];k=len(b);a+=k
l+=b[:n-a]+'>v'[m]+' '*(k-n+a-1),
if m:l=zip(*l[::-1])
for i in l:print''.join(i)

```
* *Saved 39 bytes thanks to @JonathanAllan*

repl.it

Draw the snake by rotating the entire snake 90º clockwise and adding the bottom segment, this way the snake will always be anticlockwise.
The new segment will always start with `\` and have `-` as body for even sides and `/` `-` for odd sides. The segments sizes (without corners) are `0`,`1`,`1`,`2`,`2`,`3`... which is `floor(side/2)`.
If the segment is the last, it remove the excess characters, add the head and complete with spaces.

```
desired_size=input()
snake=[['']]
snake_size=side=0
new_segment='@'
while snake_size<=desired_size:
    side+=1
    snake+=[new_segment]
    snake=zip(*snake[::-1])
    odd_side=side%2
    new_segment='\/'[odd_side]+side/2*'-|'[odd_side]
    snake_size+=len(new_segment)
diff=desired_size-snake_size
snake+=[new_segment[:diff]+'>v'[odd_side]+' '*(len(new_segment)-diff-1)]
if odd_side:
    snake=zip(*snake[::-1])

for line in snake:print ''.join(line)

```

# Answer
> 7 votes
# JavaScript (ES6), 193 ~~201 203 215 220 224~~

*Edit* saved 4 bytes thx @Arnauld
*Edit2* changed logic, not storing the current increments for x and y, just get them from the current direction
*Edit3* having saved a few bytes, I decided to use them for a better management of the blank space
*Edit4* 8 bytes saved not following exactly the examples about the head direction - like other answers

The current version works with Chrome, Firefox and MS Edge

~~This answer gives some trailing and leading space (and blank lines).~~

```
n=>(t=>{for(x=y=-~Math.sqrt(++n)>>1,g=[i=t];(g[y]=g[y]||Array(x).fill` `)[x]='^<v>|-/\\@'[t?n?i-t?4+t%2:x-y?7:6:t%4:8],n--;i=i>1?i-2:++t)d=t&2,t&1?x+=d-1:y+=d-1})(0)||g.map(x=>x.join``).join`
`

```

*Slightly less golfed*

```
n=>
{
  g = [],
  // to save a few bytes, change line below (adds a lot of spaces)
  // w = ++n,
  w = -~Math.sqrt(++n)
  x = y = w>>1,
  s=c=>(g[y] = g[y] || Array(x).fill(' '))[x] = c, // function to set char in position
  s('@'); // place tail
  for (
     i = t = 0; // t increases at each turn, t%4 is the current direction
     n--;
     i = i > 0 ? i - 2 : t++ // side length increases every 2 turns
  )
     d = t & 2,
     t & 1 ? x += d-1: y += d-1
     s(!n ? '^<v>' [t % 4] // head
          : '|-/\\' [i > 0 ? t % 2 : x-y ? 3 : 2]) // body
  return g.map(x=>x.join``).join`\n`
}

```

```
f=
n=>(t=>{for(x=y=-~Math.sqrt(++n)>>1,g=[i=t];(g[y]=g[y]||Array(x).fill` `)[x]='^<v>|-/\\@'[t?n?i-t?4+t%2:x-y?7:6:t%4:8],n--;i=i>1?i-2:++t)d=t&2,t&1?x+=d-1:y+=d-1})(0)||g.map(x=>x.join``).join`
`

function update() {
  O.textContent=f(+I.value);
}

update()
```

```
<input type=number id=I value=19 oninput='update()'
 onkeyup='update() /* stupid MS browser, no oninput for up/down keys */'>
<pre id=O>
```

# Answer
> 3 votes
## JavaScript (ES7), 200 bytes

```
(n,s=(n*4+1)**.5|0,i=+`1201`[s%4],d=i=>`-`.repeat(i))=>[...Array(s-2>>2)].reduce(s=>`/-${d(i)}\\
${s.replace(/^|$/gm,`|`)}
|\\${d(i,i+=2)}/`,[`/\\
|@`,`/-\\
|@/`,`@`,`/@`][s%4])+`
\\${d(n-(s*s>>2))}>`

```

ES6 version for ease of testing:

```
f=(n,s=Math.sqrt((n*4+1))|0,i=+`1201`[s%4],d=i=>`-`.repeat(i))=>[...Array(s-2>>2)].reduce(s=>`/-${d(i)}\\
${s.replace(/^|$/gm,`|`)}
|\\${d(i,i+=2)}/`,[`/\\
|@`,`/-\\
|@/`,`@`,`/@`][s%4])+`
\\${d(n-(s*s>>2))}>`;
```

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

# Answer
> 3 votes
# Perl, ~~111~~ 110 bytes

Includes +1 for `-p`

Give size on STDIN

`snake.pl`:

```
#!/usr/bin/perl -p
s%> %->%+s%\^ %/>%||s/
/
/g+s%.%!s/.$//mg<//&&join"",//g,$/%seg+s/ /^/+y%/\\|>-%\\/\-|%for($\="/
\@
")x$_}{

```

# Answer
> 0 votes
## Batch, 563 bytes

```
@echo off
if %1==1 echo /@&echo v&exit/b
set w=1
:l
set/ah=w,a=w*w+w
if %a% gtr %1 goto g
set/aw+=1,a=w*w
if %a% leq %1 goto l
:g
call:d
set r=/%r%\
set/ae=h%%2,w=%1-h*w+2
for /l %%i in (1,1,%h%)do call:r
call:d
echo \%r%^>
exit/b
:d
set r=
for /l %%i in (3,1,%w%)do call set r=%%r%%-
exit/b
:r
echo %r:!=^|%
if %e%==0 set r=%r:@!=\/%
set r=%r:@/=\/%
set r=%r:!\=\-%
set r=%r:/@=\/%
set r=%r:/!=-/%
set r=%r:@!=\/%
set r=%r:/\=!@%
set r=%r:/-=!/%
if %e%==1 set r=%r:/\=@!%
set r=%r:/\=@/%
set r=%r:-\=\!%
if %e%==1 set r=%r:/\=/@%

```

Explanation: Special-cases 1 as the rest of the code requires a snake width of at least two. Next, calculates the largest quarter square (either an exact square or a rectangle 1 wider than it is high) whose area is less than the length of the snake. The snake will be coiled into this rectangle starting at the bottom left corner and ending with the tail in the middle, and the remaining length will run under the bottom of the rectangle. The rectangle is actually generated from simple string replacements; most of the time each line is generated from the previous line by moving the diagonals 1 step, but obviously the tail also has to be dealt with, and there are slight differences depending on whether the height of the rectangle is even or odd.

# Answer
> -1 votes
**Python 2.7, A WHOPPING 1230 bytes**

I am new to python and code golf but I felt I had to answer my own question and sulk away in shame after the fact. A lot of fun working on it though!

```
def s(n):
x = []
l = 0
if n % 2 == 1:
    l = n
else:
    l = n + 1
if l < 3:
    l = 3
y = []
matrix = [[' ' for x in range(l)] for y in range(l)]
slash = '\\'
newx = l/2
newy = l/2
matrix[l/2][l/2] = '@'
newx = newx-1
matrix[newx][newy] = slash
#newx = newx-1
dir = 'West'

for i in range(0, n-1):
    newx = xloc(newx, dir)
    newy = yloc(newy, dir)
    sdir = dir
    dir = cd(matrix, newx, newy, dir)
    edir = dir

    if (sdir == 'West' or sdir == 'East') and sdir != edir:
        matrix[newx][newy] = '/'
    else:
        if (sdir == 'North' or sdir == 'South') and sdir != edir:
            matrix[newx][newy] = '\\'
        else:
            if dir == 'East' or dir == 'West':
                matrix[newx][newy] = '-'
            else:
                matrix[newx][newy] = '|'
newx = xloc(newx, dir)
newy = yloc(newy, dir)
sdir = dir
dir = cd(matrix, newx, newy, dir)
edir = dir
print 'eDir: ' + dir
if dir == 'North':
    matrix[newx][newy] = '^'
if dir == 'South':
     matrix[newx][newy] = 'v'
if dir == 'East':
     matrix[newx][newy] = '>'
if dir == 'West':
     matrix[newx][newy] = '<'

p(matrix, l)

def cd(matrix, x, y, dir):
if dir == 'North':
    if matrix[x][y-1] == ' ':
        return 'West'
if dir == 'West':
    if matrix[x+1][y] == ' ':
        return 'South'
if dir == 'South':
    if matrix[x][y+1] == ' ':
        return 'East'
if dir == 'East':
    if matrix[x-1][y] == ' ':
        return 'North'
return dir

def p(a, n):
for i in range(0, n):
    for k in range(0, n):
        print a[i][k],
    print ' '

def xloc(x, dir):
if dir == 'North':
    return x -1
if dir == 'West':
    return x
if dir == 'East':
    return x
if dir == 'South':
    return x + 1
 def yloc(y, dir):
if dir == 'North':
    return y
if dir == 'West':
    return y - 1
if dir == 'East':
    return y + 1
if dir == 'South':
    return y

s(25)

```

https://repl.it/Dpoy

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


# Question
Title: Hurricane Matthew and the Lightning Bolts
**Challenge**

Inspired by this challenge and the nasty Hurricane Matthew, we will be generating some lightning bolts dynamically.

`n` = 15:

```
   \
   /\
  /  \
 /   /
/\  /\
 /  \ \
/   / /\
   /\ \
  / /  \
 /\ \  /\
  /  \ \
 /\  /
   \
    \
    /\

```

**Input**

Positive Integer `n` determines the depth of the lightning round.

**Rules and Constraints**

* `/` and `\` should be used
* The probability guiding the lightning's direction is as follow:
> + 25% Splits into 2 paths
>     + 25% Path reaches dead end
>     + 25% Goes Left
>     + 25% Goes Right
>     + There are a few exceptions regarding overlapping and dead end below:
* The code should not be deterministic, a new lightning bolt should be generated randomly every time
* The bolts should not overlap: e.g. if there is already a bolt to the left of the current bolt, the current bolt should either end or go right, but not go left or split (probability still applies, in this case it become 50%end/50%right)
* If there does not exist another available split path, the path should not end: e.g. in the beginning when there is only 1 path, the path should not end until it splits, also applies when there are multiple paths but all except one path are dead, (probability becomes 33%split/33%left/33%right) **your goal is to reach the bottom**
* Whitespaces can be added on the left (all you would need should only be height-1)
* However you want to generate the bolt is up to you, you can go from bottom up, left to right, etc. As long as all the rules above are satisfied

**Another example**

`n` = 10

```
 \
 /
 \
 /\
  /\
 / /
/\ \
 / /\
 \   \
 /

```

**Stay safe and have fun golfing!** **Please golf responsibly only when you are in a safe area!!**

# Answer
# Perl, ~~92~~ ~~90~~ ~~89~~ 84 bytes

Includes +1 for `-n`

Give height on STDIN:

```
perl -M5.010 bolt.pl <<< 15

```

`bolt.pl`:

```
#!/usr/bin/perl -n
map{$_=$;until$;=$_,s/.6|3.?/53|16*rand/eg,/3|6/>/36/;say y|3615|\\/ |r}(1x$_.6)x$_

```

## Explanation

If you call the offset of the starting point 0 (a point is at the corner of a character box), then on the next row you can have gone left or right (or not) and can end up with points on offsets `-1,1`. The next row gives `-2,0,2` as possible offsets etc. They all differ by 2. If you then call the character to the lower left of a point even and the character to the lower right odd you can extend that to assigning even or odd to each character position on a row such that even and odd alternate (in fact the whole plane is tiled in a checkerboard pattern). An even position can have a `/` or , an odd position can have `\` or .

The character just before a `/` is in an odd position so it could be either `\` or , but `\/` is forbidden so only  is possible. Similarly the character after a `\` ***must*** be a  (assuming the row is padded with enough spaces to the left and the right so the row boundaries are no issue). So a lightning bolt continues on the next row always directly below a `\` or below a `/`. In either case the lower point is in the middle and the next row can have one of , `/`, `\` or `/\` directly below the top 2 characters. So to generate the next row I can simply replace any `\` or `/` by any of these 4 expansions with equal probability (you could also independently replace the first character by  or `/` and the second character by  or `\`). In perl you could do this with something like:

```
s#\\ | /#("  "," \\","/ ","/\\")[rand 4]#eg

```

If the resulting row however contains `\/` (forbidden join) or no `/` or `\` at all (bolt dies and does not reach the bottom) the result is invalid. In that case I throw away the whole row and simply try again. A valid continuation always exists and if you try often enough one will be found (e.g everything dies except for 1 flow). This is a slightly different probability distribution from the suggested anti-overlap algorithm, but I think this is in fact better since it has no directional bias. Validity can be testing in a golfish way using

```
m#\\|/#>m#\\/#

```

The problem here is that the random substitution is so looooong and all these `\` escapes also eat bytes. So I decided to build my rows using strings of digits and replace the appropriate digits by , `/` and `\` just before printing. The basic random replacement is

```
53|16*rand

```

which gives one of `53`, `55`, `61` or `63` with equal probability. I then interpret `5` and `1` as , `3` as `\` and `6` as `/`. That explains the row print:

```
say y|3615|\\/ |r

```

In a serious golf competition I would now start to systematically explore alternative magic formulas, but this should be pretty good (within 3 bytes of optimal)

The rest of the components of the program:

```
1x$_.6

```

This initializes `$_` (see the next map) to height spaces followed by a `/`. This is an invisible row above the first one being printed and makes sure the field is wide enough so the bolt can never run out of space at the left

```
map{ ... ; say ...}(1x$_.6)x$_

```

I will process this same initial string height times printing a new row each time

```
$_=$;until$;=$_,...

```

Save the current row in `$;`. If the replacement turns out to be invalid restore `$_` from `$;`

```
s/.6|3.?/53|16*rand/eg

```

Do the actual substitution. I don't have to check what is before `/` or after `\` since it ***must*** be a space. This is convenient since space can be represented by either `1` or `5`. Since I only padded the string to the left the space after the `\` can still be absent, so make that character optional

```
/3|6/>/36/

```

Check if the new row is valid
> 6 votes

# Answer
## JavaScript (ES6), 154 bytes

```
f=(n,r=[],s=" ".repeat(n)+"/",t=s.replace(/ \/|\\ |\\$/g,_=>"  /  \\/\\".substr(Math.random()*8&6,2)))=>n?/^ +$|\\\//.test(t)?f(n,r,s):f(n-1,[...r,t],t):r
```

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

I struggled with the implementation until I saw @TonHospel's answer, at which point it just degenerated into a port. Sample output:

```
         /\
        / /\
       /\   \
        /\   \
         /\  /
          / /\
         / / /\
            / /\
            \   \
             \

```
> 0 votes

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


title: Find the Swirling Words!

text:
# Question
Title: Find the Swirling Words!
Don't ask me how or why but while coding on a project I noticed that the characters of a couple of words had a particular pattern referred to the alphabet, I connected each character of the words with the pencil on the alphabet and I obtained two spirals, then I noticed that the first spiral was clockwise and the other was counterclockwise, and other characteristics... so I named them ***Swirling Words***!

A *Swirling Word* can be:

1. clockwise or counterclockwise
2. centripetal or centrifugal

Here there are some examples of *Swirling Words*:

### Task 1:

Write a full program or function that will take a word from standard input and will output if is a *Swirling Word* and it's characteristics, in a readable format, extended text, 3 characters, flags, etc.

Test cases and example outputs for different words (but you can decide how to represent the results):

```
EARTH, GROUP            > NO        // NOT A SWIRLING WORD
OPERA, STAY, IRIS       > SW,CF,CW  // SWIRLING WORD, CENTRIFUGAL, CLOCKWISE
MINER, TAX, PLUG, META  > SW,CF,CC  // SWIRLING WORD, CENTRIFUGAL, COUNTERCLOCKWISE
AXIOM, AXIS, COOK       > SW,CP,CW  // SWIRLING WORD, CENTRIPETAL, CLOCKWISE
WATCH, YETI, PILL       > SW,CP,CC  // SWIRLING WORD, CENTRIPETAL, COUNTERCLOCKWISE

MORE EXAMPLES OF FALSE TEST CASES (NOT SWIRLING WORDS):
EARTH, GROUP, OUTPUT, WORD, CONNECTION, ODD, MOM, DAD,
CHARACTER, EXAMPLE, QUESTION, NEWSLETTER, OTHER

```

### Rules:

1. The connection between the first two characters must be *up* (like in the graphics), all the even connection must be *down*, all the odd connections must be *up*.
2. You can ignore upper/lowercase or consider/convert all to upper case or all to lower case.
3. The input words are only characters in the alphabet range of A-Z, no spaces, no punctuation, etc.
4. If a word has double characters, like "GROOVE", you must collapse the doubles to one character: "GROOVE" \> "GROVE".
5. The input words will contain at least 3 distinct characters. Words like "MOM", "DAD", "LOL" are not valid words.
6. It's possible to pass multiple times in the same character, like "IRIS".
7. Shortest code wins.

### Task 2:

To obtain more reputation, find the longest *Swirling Words*, and it's characteristics, that you can find in the english dictionary, following the above rules. You can take for example as reference the complete list of the english words here.

Happy coding!

# Answer
# MATL, ~~33~~ ~~31~~ 30 bytes

```
lydhg)dt|dZSXz&=wZSdh?4M1)3M1)

```

Input is in uppercase letters (or in lowercase letters, but not mixed).

Output is:

* If the word is non-swirling: no output is produced
* If it is swirling: two numbers are produced in different lines:
    + First number `1`/ `-1` indicates centrifugal / centripetal.
    + Second number `1`/ \`-1' indicates clockwise / counterclockwise.

Try it online! Or verify all test cases (code modified to take all inputs and to produce the two output numbers on the same line)

### Explanation

Let's take input `'OPERAA'` as an example.

The first part of the code removes double letters:

```
l     % Push 1
      %   STACK: 1
y     % Take input implicitly from below, and duplicate
      %   STACK: 'OPERAA', 1, 'OPERAA'
d     % Convert to code points and compute differences
      %   STACK: 'OPERAA', 1, [1 -11  13 -17 0]
h     % Concatenate horizontally
      %   STACK: 'OPERAA', [1 1 -11  13 -17 0]
g     % Convert to logical
      %   STACK: 'OPERAA', [true true true true true false]
)     % Index
      %   STACK: 'OPERA'

```

We now check if the distances between letters are non-decreasing (necessary condition for the word to be swirling):

```
d     % Convert to code points and compute differences
      %   STACK: [1 -11  13 -17]
t|    % Duplicate and take absolute value
      %   STACK: [1 -11  13 -17], [1 11  13 17]
d     % Differences
      %   STACK: [1 -11  13 -17], [10 2 4]
ZS    % Signum
      %   STACK: [1 -11  13 -17], [1 1 1]
Xz    % Remove zeros (gives a vertical vector). Needed for words like 'IRIS',
      % where some consecutive distances are equal
      %   STACK: [1 -11  13 -17], [1; 1; 1]
&=    % All pairwise equality comparisons. Gives a matrix. If all the signs
      % were equal the matrix will contain all ones
      %   STACK: [1 -11  13 -17], [1 1 1; 1 1 1; 1 1 1]

```

We then check if the letters go back and forth (this is the other condition for the word to be swirling):

```
w     % Swap
      %   STACK: [1 1 1; 1 1 1; 1 1 1], [1 -11  13 -17]
ZS    % Signum
      %   STACK: [1 1 1; 1 1 1; 1 1 1], [1 -1 1 -1]
d     % Differences
      %   STACK: [1 1 1; 1 1 1; 1 1 1], [-2 2 -2]

```

Lastly, we check if the two conditions hold, and in that case produce the output:

```
h     % Concatenate horizontally
      %   STACK: [1 1 1 1 1 1 1 1 1 -2 2 -2]
?     % If all elements are nonzero
  4M  %   Push first signum array without zeros, from the automatic clipboard
      %     STACK: [1; 1; 1]
  1)  %   Get first element (tells if first difference was positive or negative)
      %     STACK: 1
  3M  %   Push second signum array, from the automatic clipboard
      %     STACK: 1, [1 -1 1 -1]
  1)  %   Get first element (tells if first movement was right or left)
      %     STACK: 1, 1
      %   Implicitly end if
      % Implicitly display

```
> 11 votes

# Answer
# Mathematica, ~~117~~ 111 bytes

*Thanks to JHM for saving 6 bytes, and making it case-insensitive to boot!*

```
 {o=OrderedQ/@{a=Abs[d=Differences[#&@@@Split@LetterNumber@#]],Reverse@a},d[[1]]>0,Or@@o&&Max[Most[d]Rest@d]<0}&

```

Unnamed function that takes a string and returns a nested list of booleans in the form `{{B1,B2},B3,B4}`. B4 records whether the word is swirling (and if it's not, the rest of the output is garbage). If the word is swirling, then B1 records whether the word is centrifugal, B2 records whether the word is centripetal, and B3 records whether the word is clockwise (True) or counterclockwise (False).

Here's a longer version that post-processes (first line) the above function (spaced over the 2nd-5th lines) to make it identical to the OP: `NO` if the word isn't swirling, and the appropriate choice of `{SW,CF,CW}` , `{SW,CF,CC}` , `{SW,CP,CW}`, or `{SW,CP,CC}` if the word is swirling:

```
If[#3, {SW, If[#[[1]], CF, CP], If[#2, CW, CC]}, NO] & @@
  {o = OrderedQ /@
    {a = Abs[d = Differences[# & @@@ Split@LetterNumber@#]], Reverse@a},
  d[[1]] > 0,
  Or @@ o && Max[Most[d] Rest@d] < 0} &

```

The explanation is the same as in Martin Ender's CJam answer, with one additional note: the list of consecutive differences must alternate in sign for the word to be swirling, and that can be detected by making sure all products of pairs of consecutive differences are negative (that's what `Max[Most[d]Rest@d]<0` does).

Running the function on all 40,000+ words of Mathematica's `WordList[]`, we find the following 8-letter swirling words, which are the longest of their respective swirling types:

```
operetta    {SW, CF, CW}
opposite    {SW, CF, CW}
stowaway    {SW, CF, CW}
assassin    {SW, CP, CW}
assessor    {SW, CP, CW}
baccarat    {SW, CF, CC}
keenness    {SW, CF, CC}
positive    {SW, CF, CC}

```

(Brownie points to `positive` for having no double letters, and fewer repeated letters than `stowaway`.)

But the absolute champion is the 9-letter counterclockwise-swirling centripetal word `vassalage`!
> 6 votes

# Answer
# Scala, 110 bytes

```
def/(s:String)={val ? =s.sliding(2).map(t=>(t(0)-t(1)).abs).toSeq
(Seq(?,?reverse)indexOf(?sorted),s(0)<s(1))}

```

Returns a tuple `(a,b)` with

* `a == 1` if s is centripetal
* `a == 0` if s is centrifugal
* `a == -1` if s is not swirling

and

* `b == true` if s is clockwise
* `b == false` if s is counterclockwise
* b can be true or false if s is not swirling

Explanation:

```
def/(s:String)={      //define a method called / with a String argument
  val ? =s            //define ? as...
    .sliding(2)       //an iterator for each two consecutive elements
    .map(t=>          //foreach 2 chars
      (t(0)-t(1)).abs //get the absolute value of their difference
    )
    .toSeq            //and convert the iterator to a Seq, because iterator doesn't have reverse and sorted methods
  (                   //return a tuple of
    Seq(?,?reverse)     //a Seq of ? and reversed ?
    .indexOf(?sorted)   //and check which of them is sorted ?
  ,                   //and
   s(0)< s(1)          //the difference bewteen the first two elements of the string.
  )
}

```
> 5 votes

# Answer
# Jelly,  ~~30~~  23 bytes

```
OIḟ0µAI©Ṡḟ0ṂṭḢṠ$µ®ḟ0ṠEṭ

```

**Try it online!** Or see the test cases

All upper or all lower.
Returns a flag list `[D, F, S]`:
`D`: clockwise = `1` / anticlockwise = `-1`
`F`: centrifugal = `1` / centripetal = `-1`
`S`: spinning = `1` / not spinning = `0`
\- if `S` is `0` the other flags are still evaluated even though they carry no useful information.

### How?

```
OIḟ0µAI©Ṡḟ0ṂṭṠḢ$µ®ḟ0ṠEṭ - Main link: s
O                       - ordinals
 I                      - deltas (i.e. [a,b,c,...] -> [b-a,c-b,...])
  ḟ0                    - filter out zeros
                        - (call this Z)
    µ                   - start a new monadic chain (i.e. f(Z))
     A                  - absolute values
      I                 - deltas
       ©                - copy to register
        Ṡ               - signs
         ḟ0             - filter out zeros
           Ṃ            - minimum
                        - (i.e. F = {centrifugal: 1; centripetal: -1})
               $        - last two links as a monad:
             Ḣ          -   head (Z)
              Ṡ         -   sign
                        - (i.e. D = {clockwise: 1; anticlockwise: -1})
            ṭ           - tack
                µ       - start a new monadic chain (i.e. f([D,F]))
                 ®      - recall from register
                  ḟ0    - filter out zeros
                    Ṡ   - signs
                     E  - all equal?
                        - (i.e. S = {spinning: 1; not spinning: 0})
                      ṭ - tack
                        - (i.e. [D,F,S])

```
> 5 votes

# Answer
# CJam, 39 bytes

```
r{2ew::-V}:D~-_:g_0=\D#)!@:zD-:g_0=\(-!

```

Try it online!

The input can be uppercase or lowercase, but not mixed.

The program inadvertently points out words which are not necessarily centrifugal or centripetal, but otherwise meet the requirements of being spiral. These are described as "circular" in the chart below.

**To interpret the output use this chart:**

```
SPIRAL (output contains four 1s)
-11-11 : Clockwise Centrifugal
-1111  : Clockwise Centripetal
11-11  : Counter-clockwise Centrifugal
1111   : Counter-clockwise Centripetal

CIRCULAR (output contains two 1s)
-11    : Clockwise Circular
11     : Counter-clockwise Circular

NONSPIRAL (output contains a 0)

```

**Explanation:**

The program actually evaluates whether the sequence of non-zero differences between characters starts off positive or negative, if it alternates in sign, if the magnitudes start off increasing or decreasing, and if it continues to do so. If the magnitudes don't increase or decrease then the program breaks by operating on an empty array. The major steps are shown below (this code will also show the progress of the stack):

```
r{2ew::-V}:D~-   e# take difference of overlapping pairs, removing 0s handles duplicates
               ede# store difference function plus 0 as D, it's multipurpose
_:g_0=\          e# compute signs differences, keep first to show starting direction
               ede# -1 = CLOCKWISE, 1 = COUNTERCLOCKWISE
D#)!@            e# difference of signs includes 0 if not alternating, keep in stack
               ede# 1 = ALTERNATING, 0 = NOT ALTERNATING
:zD-:g           e# signs of difference of absolute values, ignoring 0s (fixed magnitude)
_0=\             e# keep first sign in stack to indicate how the sequence starts
               ede# -1 = INCREASING, 1 = DECREASING
(-!              e# remove first item from entire list and see if nothing remains
               ede# 1 = EMPTY(MONOTONE), 0 = NONEMPTY

```
> 3 votes

# Answer
# PHP, 322 Bytes

```
for(;++$i<strlen($z=preg_replace("#(.)\\1#","$1",$argv[1]));){$t[]=$z[$i-1]<=>$z[$i]?:0;$o[]=$z[0]<=>$z[$i];$i<2?:$k[]=$z[$i-2]<=>$z[$i];}$s=preg_match("#^1?(-11)*(-1)?$#",join($t))?($t[0]!=1?1:2):0;$s+=2*preg_match($r="#^(-1|0)?([01](-1|0))*[01]?$#",join($o));$s*=preg_match($r,join($k));count_chars($z,3)[2]?:$s=0;echo$s;

```

for a more pretty Output `echo["n","+P","-P","+F","-F"][$s];`

Expanded version

```
for(;++$i<strlen($z=preg_replace("#(.)\\1#","$1",$argv[1]));){
    $t[]=$z[$i-1]<=>$z[$i]?:0;
    $o[]=$z[0]<=>$z[$i];
    $i<2?:$k[]=$z[$i-2]<=>$z[$i];
    }
$s=preg_match("#^1?(-11)*(-1)?$#",join($t))?($t[0]!=1?1:2):0; #Clockwise direction or not
$s+=2*preg_match($r="#^(-1|0)?([01](-1|0))*[01]?$#",join($o)); # True centrifugal
$s*=preg_match($r,join($k)); #true or false second test for not
count_chars($z,3)[2]?:$s=0; # word must have >2 different characters
echo$s;# short output
echo["n","+P","-P","+F","-F"][$s]; #long output alternative

```

## Task 2 second value without short doubles rule

> 4 -F killingness 11 Bytes positivize 10 Bytes
>
> 3 +F oppositive 10 Bytes logogogue 9 Bytes
>
> 2 -P vassalage 9 Bytes sarcocol,sasarara 8 Bytes
>
> 1 +P assession 9 Bytes apanage, aramaic, argonon, auction, avision, awarded, crenele, exesion, exition, eyewink 7 Bytes

## Visualize a word

```
header('Content-Type: image/svg+xml; charset=UTF-8');
$w=$_GET["w"]??"OOPERRA";
$w=strtoupper($w);
echo '<?xml version="1.0" encoding="UTF-8"?>'
.'<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">'

.'<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 -100 420 400">'
.'<title>Swirl Word</title><desc>Viualize a Word</desc>';
echo '<text x="210" y="-50" text-anchor="middle" font-family="arial">'.$w.'</text>';

foreach(range("A","Z")as $x=>$c){
    echo '<text x="'.(15+$x*15).'" y="110" text-anchor="middle" font-family="arial">'.$c.'</text>';
    $r[$c]=15+$x*15;
}
for($i=0;++$i<strlen($w);){
    echo '<path d="M '.($r[$w[$i-1]]).',105 A '.($radius=abs($r[$w[$i]]-$r[$w[$i-1]])/2).' '.($radius).' 0 0 0 '.($r[$w[$i]]).',105" style="stroke:gold; stroke-width:1px;fill:none;" />';
}
echo '</svg>';

```

in the snippet is the result of the SVG I have create

```
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 -100 420 400"><title>Swirl Word</title><desc>Viualize a Word</desc><text x="210" y="-50"  text-anchor="middle" font-family="arial">KILLINGNESS</text><text x="15" y="110" text-anchor="middle" font-family="arial">A</text><text x="30" y="110" text-anchor="middle" font-family="arial">B</text><text x="45" y="110" text-anchor="middle" font-family="arial">C</text><text x="60" y="110" text-anchor="middle" font-family="arial">D</text><text x="75" y="110" text-anchor="middle" font-family="arial">E</text><text x="90" y="110" text-anchor="middle" font-family="arial">F</text><text x="105" y="110" text-anchor="middle" font-family="arial">G</text><text x="120" y="110" text-anchor="middle" font-family="arial">H</text><text x="135" y="110" text-anchor="middle" font-family="arial">I</text><text x="150" y="110" text-anchor="middle" font-family="arial">J</text><text x="165" y="110" text-anchor="middle" font-family="arial">K</text><text x="180" y="110" text-anchor="middle" font-family="arial">L</text><text x="195" y="110" text-anchor="middle" font-family="arial">M</text><text x="210" y="110" text-anchor="middle" font-family="arial">N</text><text x="225" y="110" text-anchor="middle" font-family="arial">O</text><text x="240" y="110" text-anchor="middle" font-family="arial">P</text><text x="255" y="110" text-anchor="middle" font-family="arial">Q</text><text x="270" y="110" text-anchor="middle" font-family="arial">R</text><text x="285" y="110" text-anchor="middle" font-family="arial">S</text><text x="300" y="110" text-anchor="middle" font-family="arial">T</text><text x="315" y="110" text-anchor="middle" font-family="arial">U</text><text x="330" y="110" text-anchor="middle" font-family="arial">V</text><text x="345" y="110" text-anchor="middle" font-family="arial">W</text><text x="360" y="110" text-anchor="middle" font-family="arial">X</text><text x="375" y="110" text-anchor="middle" font-family="arial">Y</text><text x="390" y="110" text-anchor="middle" font-family="arial">Z</text><path d="M 165,105 A 15 15 0 0 0 135,105" style="stroke:gold; stroke-width:1px;fill:none;" /><path d="M 135,105 A 22.5 22.5 0 0 0 180,105" style="stroke:gold; stroke-width:1px;fill:none;" /><path d="M 180,105 A 0 0 0 0 0 180,105" style="stroke:gold; stroke-width:1px;fill:none;" /><path d="M 180,105 A 22.5 22.5 0 0 0 135,105" style="stroke:gold; stroke-width:1px;fill:none;" /><path d="M 135,105 A 37.5 37.5 0 0 0 210,105" style="stroke:gold; stroke-width:1px;fill:none;" /><path d="M 210,105 A 52.5 52.5 0 0 0 105,105" style="stroke:gold; stroke-width:1px;fill:none;" /><path d="M 105,105 A 52.5 52.5 0 0 0 210,105" style="stroke:gold; stroke-width:1px;fill:none;" /><path d="M 210,105 A 67.5 67.5 0 0 0 75,105" style="stroke:gold; stroke-width:1px;fill:none;" /><path d="M 75,105 A 105 105 0 0 0 285,105" style="stroke:gold; stroke-width:1px;fill:none;" /><path d="M 285,105 A 0 0 0 0 0 285,105" style="stroke:gold; stroke-width:1px;fill:none;" /></svg>
```
> 3 votes

# Answer
# Haskell, 148 bytes

```
z f=tail>>=zipWith f
g c=and.z c.filter(/=0).map abs.z(-).map fromEnum
(a:b:r)%c|a==b=(b:r)%c|1<3=c a b
f s|a<-[g(>=)s,g(<=)s]=or a:a++[s%(<),s%(>)]

```

Try it on Ideone.

Input must be either al lower or all upper-case.
Output is a list of five booleans: `[SW?, CF?, CP?, CW?, CC?]`.

`f "positive" -> [True,True,False,False,True]`

This turned out longer than expected, especially handing the collapsing of repeated characters takes about 40 bytes.

At first I compared just the first two characters to yield `CW` or `CC` before noticing that testcases like `bba` or `bbc` are valid too and defeat this approach.
> 2 votes

# Answer
# Python, 152 bytes:

```
lambda C:[C[-1]in max(C)+min(C),C[1]>C[0]]*all([[i>g,i<g][[h%2>0,h%2<1][C[1]>C[0]]]for i,g,h in filter(lambda i:i[0]!=i[1],zip(C,C[1:],range(len(C))))])

```

An anonymous lambda function. Call as `print(<Function Name>('<String>'))`.

Takes input as all lowercase or uppercase, but *not* mixed case.

Outputs an array containing nothing (`[]`) if the word is not swirly, or an array in the following format otherwise:

* 1st element is `True/False` for `Centrifugal/Centripetal`.
* 2nd element is `True/False` for `Clockwise/Counterclockwise`.

Try It Online! (Ideone)
> 2 votes

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


title: Correlation Coefficient of Words

text:
# Question
Title: Correlation Coefficient of Words
This is going to be relatively quick...

## Challenge

Given a lower-case word as input, calculate the Pearson's Correlation Coefficient between the letter position of the word (nth letter within the word, x), and the letter position within the alphabet (nth letter of the alphabet, y).

## Background

Pearson's Correlation Coefficient is worked out for data sets x and y, as:

where **x** and **y** are the respective data sets as explained above (and further below), and **n** is the length of the string.

## Examples

```
  Input: forty
  Output: 0.964406804

```

**Explanation:**

```
  Letters: f o r t y
  Alphabet Number (y): 6 15 18 20 25
  Letter Position (x): 1 2 3 4 5
  Length of word (n): 5

```

Correlation coefficient is worked out from the above formula.

```
  Input: bells
  Output: 0.971793199

```

**Explanation:**

```
  Letters: b e l l s
  Alphabet Number (y): 2 5 12 12 19
  Letter Position (x): 1 2 3 4 5
  Length of word (n): 5

```

Correlation coefficient is once again worked out from the above formula.

## Rules

1. Input must provide the word as a lower-case alphabetic string with no spaces (assumed input). The delivery of this string is entirely up to you (file, STDIN, function, array, carrier pigeon, etc.)
2. Output is in the form of a numeric that will, by the formula, provide r, such that -1 \<= r \<= 1. Delivery of the output, once again, is entirely up to you.
3. No silly loop holes
4. This is not code-golf, as I'm sure there will be many languages that may have native statistical functions. Instead, this will be a popularity contest, so most votes wins here, so make your entry count... I'll be throwing in a bounty for the most creative answer that attracts my attention a little later down the line...

Any questions/comments?

# Answer
> 2 votes
## R, 63 bytes

```
s=strsplit(scan(,""),"")[[1]];cor(match(s,letters),1:length(s))

```

**Ungolfed :**

```
#Takes the input and splits it, letters by letters
s=strsplit(
           scan(,""),
           "")[[1]];

#Finds the positions of each letters in the lowercase alphabet, and correlates them with
#their position in the word
cor(
    match(s,letters),
    1:length(s)
    )

```

# Answer
> 2 votes
# Python

That's a lot of traversals, let's do all we need to do in one pass for efficiency.

Since `y` will be `[1,2,...,len(x)]` we can calculate it's sum and sum of squares using the formulas for triangle and square pyramid numbers respectively.

...and there's really no need for two square roots since the two are multiplied we can just square the product.

```
def p(l):
    y = sx = sxy = sx2 = 0
    for c in l:
        y += 1
        x = ord(c) - 96
        sx += x
        sxy += x * y
        sx2 += x * x
    sy = y * (y + 1) / 2
    sy2 = sy * (2 * y + 1) / 3
    return (n * sxy - sx * sy ) / ((n * sx2 - sx * sx) * (n * sy2 - sy * sy)) ** .5

```

# Answer
> 1 votes
# Python 3

Simply uses the formula in the challenge. Doesn't use any libraries like `numpy` and friends.

```
from math import sqrt

def correlation_coefficient(word):
  alphabet = 'abcdefghijklmnopqrstuvwxyz'

  x = list(range(len(word)))
  y = list(map(alphabet.index, word))
  n = len(word)

  top = n * sum(a*b for a, b in zip(x, y)) - sum(x) * sum(y)
  bottom = (sqrt(n * sum(a ** 2 for a in x) - sum(x) ** 2)
          * sqrt(n * sum(a ** 2 for a in y) - sum(y) ** 2))

  r = top / bottom
  return r

```

Ideone it!

---
Tags: popularity-contest, statistics
---