text:
Word with greatest repeat of letters
Recently there was a question on Stack Overflow where the OP was trying to write a function to find the word in a string that has the most repeated letters. It is of course not hard to write one up in seconds, and I wrote one in Javascript as short as I can for fun. But I'm not an expert in code golfing, so I wonder how much shorter can this simple program be!

Challenge
Write a program or function that takes in a string of words and return or print the word with the most repeating single letters.
Rules:

Choose the word with the greatest number of repeating single letters (see examples below)
If no word has repeating letters, return -1.
If two words have the same maximum number of repeating letters, choose the one closer to the start of the string.
The shortest submission in bytes wins.

Input
Take as input a string consisting of one or more space-delimited words. Input can be from STDIN (or closest alternative), command line parameters, or function arguments.
Output
Print the output to STDOUT to return it.
Examples
Consider the string aaabbb cccc. This contains two words: aaabbb and cccc. The word aaabbb has 3 a's and 3 b's, and cccc has 4 c's. So the maximum number of repeated letters in aaabbb is 3 and the maximum in cccc is 4. We want to choose the word with the maximum number of repeated single letters, so the output for aaabbb cccc should be cccc.
Other test cases:
Today, is the greatest day ever!  --> greatest
This is a great day               --> -1
aaabbb cccc                       --> cccc

What if more than one words have the same # of repeated letters? Do we print any or all?

@Maltysen Look at the first example - see ever

@isaacg but greatest has two repeating, t and e.

I'm not sure what is meant by the number of repeated letters. I assume aabb has 2 repeated letters. Would aaaabb be considered to have 4 repeated letters (2nd, 3rd, 4th a, 2nd b) or 2 repeated letters (a and b).

@feersum aaaabb would count as 4. Pick the maximum of the numbers of repetitions in each word.

@Maltysen Only print one of them if there are more than one word with the same number of repeated letters.

@Derek朕會功夫 To clarify, by repetition do you simply mean a letter that has appeared previously in the word?

@isaacg I mean, for example aaaabb would be chosen over aabbb since the former has 4 repetitions of "a" which is more than 3 repetitions of "b" in the latter.

So, which would win, aaabbb or cccc - do the 2nd and 3rd a's and 2nd and 3rd b's win, or does the 4 times repeated c win?

@isaacg cccc wins, since although aaabbb has 3 a's and 3 b's, cccc has 4 c's which is greater than both 3's.

@Derek朕會功夫 I'm still not totally sure on the rules for greatest repeats. Could you please write out the conditions explicitly?

The way I understand it based on the examples and comments, I think it would be clearer to say "most repeated letter" instead of "most repeated letters" in the question, because only a single letter counts. Or maybe "the word that contains the highest frequency of a single letter".

Will the words contain any non-alphabetical characters (other than ending punctuation)?

@xnor I added some clarifications in the question. Sorry for the confusion!

@kirbyfan64sos You can assume punctuation marks will not repeat in the same word, ie "a,,,b" will not happen.

I made edits to the wording and formatting of the challenge. If my edits do not match your original intent, please roll back. Note that it was unclear what should happen in the case of multiple output candidates, so I added the specification from the original SO question.

Note that the original question is from Coderbyte. I looked on their website for copyright information (since this is a reproduction of Letter Count I) but I couldn't find anything.

C - GCC - 159 145 135 Bytes
x=0,w=0,i,j,c;main(int _,char**z){while(--_)for(j=i=0;_[z][i];j=++i,x=c>x?w=_,c:x)for(c=0;j--;)c+=z[_][i]==z[_][j];puts(x?z[w]:"-1");}

Will update when I can truncate it a bit
How to compile:         gcc -w cg.c
How to run:             ./a.out word1 word2 aass ddaaa ssdddd
Output:                 ssdddd
No-Output/No-match:     -1
First off, I cheated a bit, by taking in the words as program arguments, but getting GCC to parse the words and give me a word count for free was too much reward to pass up.
How does it work?
We have 3 nested loops. The first incrementing through each word, the next two are mimicking a bubble sort to compare values. The first letter is never compared with itself, and each subsequent letter is compared to each previous letter. Whenever a word has more same letters than a previous word, the word is stored in x, and the count of how many same letters is also stored.
GCC Abuse
We use implicit global auto int delcarations for our integers. We allow argv to be an int instead of a char (currently a char, this is a TODO). We make use of default functions such as puts and getchar. We also make use of the comma operator to overload our trinary (conditional) operator.
Want 2 less bytes?
Replace "-1" with *z and name the file -1
Program unobfuscated and untested:
int main(int argc, char * argv[])
{
    int word = 0           // Current most repeat letters word
    int count = 0;        // Current most repeat letters
    int i, j, increment; // Counter variables

    while(--argc != 0) // While we have words from program parameters
    {
        for(j = i = 0; argv[argc][i] != '\0'; j = ++i) // Iterate through each letter until end of word
        {
            for(increment = 0; j > 0; j--) // Iterative backwards through each letter
            {
                if(argv[argc][i] == argv[argc][j])
                {
                    increment++;
                }
            }
            if(increment > count) // New greatest lettered word
            {
                word = argc;
                count = increment;
            }
        }
    }

    if(word == 0)
    {
        puts("-1");
    }
    else
    {
        puts(argv[word]);
    }

    return 0;
}

Welcome to PPCG!  Nice golfing; if you get time, I'd love to see an explanation of how your code works.

Updated OP with an explanation

No GCC abuse, just some old style but regular C

thats a record! congrats

Pyth, 14 bytes
eoeS/LNN+czd_1

Demonstration. Test harness.
eoeS/LNN+czd_1
                  Implicit: z = input(), d = ' '
         czd      chop z on delimeter d.
        +   _1    Add an -1 to the end of the list.
 o                Order the list by
  eS              the maximum of
    /LN           the occurence count in the word
       N          of letters in the word.
                  (If we are mapping over -1, this will give -1/-1 = 1)
                  Since Python's sort is stable, this will leave -1 at the end if
                  all words have maximum repetition count 1.
e                 Take the final element of the resulting list and print it.

Still doesn't seem to be working. As per feersum's comment "aaaabb" should have 4 repeats and thus more than "greatest". But https://pyth.herokuapp.com/?code=eo.-N%7BNc%2Bz%22+-1&input=Today%2C+is+the+aaaabb+greatest+day+ever!&debug=0 still gives greatest.

Putting an l before .- seems to do it.

@Maltysen Right, I was silly and attempted to use string sorting.

This is short and beautiful.

@Derek朕會功夫 Thanks! Consider upvoting.

@isaacg I have upvoted every (working) answers as they were posted actually :)

@Derek朕會功夫 Ah, well thank you again then.

K, 35 bytes (missing -1 requirement, just noticed, but time to sleep)
{1#w[>{|/{#:&:x=y}[x]'x}'w:" "\:x]}

how it works:
1 take
1#

of the words indexed by
w[

the indices to put in ascending order
>

the maximum
|/

count where
#:&:

string = char
x=y

for each char in word
'x

for each word where w (words) are
'w:

the string split by spaces
\:x

Obviously I sacrificed a bit of precision for expressiveness and legibility in the English explanation. I hope it was interesting.

I think you can follow the requirement by adding ,-1 to the end of the function.

You should be able to leave off the colons for #:&: since from context they should parse as their monadic forms. You could also use @ to index instead of brackets, and first (*) instead of 1#.

Haskell, 100 bytes
import Data.List
f=g.last.sort.map((,)=<<last.sort.map length.group.sort).words
g(1,_)="-1"
g(_,w)=w

Usage example: f "Today, is the greatest day ever!" -> "greatest"
How it works:
                                                words  -- split input at spaces into list of words
          map(                                 )       -- for each word
              (,)=<<                                   -- build a pair, where the second element is the word itself
                                                       -- and the first element is made by
                                           sort        -- sort the letters
                                      group            -- group equal letters
                            map length                 -- take length of each group
                        sort                           -- sort the lengths
                    last                               -- take the last
                                                       -- now we have a list of (l,w) pairs where l is how often the most frequent letter occurs for word w
     sort                                              -- sort the list
 last                                                  -- take last element
g                                                      -- call g which checks the "-1" case

Haskell, 79 77 bytes (untested)
import Data.List
last.sortOn(last.sort.map length.group.sort).words.(++" -1")

This uses sortOn from Data.List v4.8.0.0, which I don't have installed, so I cannot test it.

Python 2, 97 77 Bytes
Fairly straightforward solution, just maps the input (surrounded by quotes) to a tuple containing the word and the number of repeated characters. Gets the maximum, and prints out the word if the most repeated letter is repeated at all, otherwise it prints -1.
I saved 20(!) bytes by rearranging the order of input so that I didn't need a key for finding the max.
j=max((max(map(x.count,x)),x)for x in input().split())
print[-1,j[1]][j[0]>1]

CJam, 25 bytes
lS/{_$e`$W=0=(\}%2/$W=~W?

Try it online
Explanation:
lS/   Get input and split at spaces.
{     Start of loop over all words.
  _     Copy, need to keep original word.
  $     Sort letters.
  e`    RLE.
  $     Sort RLE result. Sort is increasing by count.
  W=    Get last count/letter pair, which corresponds to largest count.
  0=    Extract count from pair.
  (     Decrement count, so that it has a falsy value when the count is 1.
  \     Swap count and word, so that we can sort the pairs by count.
}%    End of loop over words.
2/    Split list into pairs, which are the count/word pairs.
$     Sort the pairs.
W=    Get last one, which is the largest count.
~     Unwrap the pair.
W?    Output word if count is truthy, -1 otherwise.

SWI-Prolog, 158 154 149 bytes
a(A,R):-split_string(A," ","",B),findall(X:Z,(member(Z,B),string_codes(Z,D),length(D,L),sort(D,E),length(E,M),X is M-L,X<0),S),sort(S,[_:R|_]);R= -1.

Example: a("Today, is the greatest day ever!",R). outputs R = "greatest" ..

JavaScript, 86 111 108 bytes
s=>(l=(x=s.split` `,r=x.map(l=>(/(.)\1+/.exec(l)||[''])[0].length),x)[r.indexOf(k=Math.max(...r))],k<2?-1:l)

Definitely golf-able, the whole -1 thing added about 20 bytes.

R, 107 bytes
w=scan(,"");l=sapply(w,function(x)max(table(strsplit(x,"")[[1]])));cat(ifelse(max(l)>1,w[which.max(l)],-1))

This reads from STDIN and prints to STDOUT.
Ungolfed + explanation:
# Read a string and split it into a vector on spaces
w <- scan(, "")

# Get the maximum number of letter repeats in each element of w
l <- sapply(w, function(x) max(table(strsplit(x, "")[[1]])))

# If the largest number in l is 1, print -1, otherwise get the word
cat(ifelse(max(l) > 1, w[which.max(l)], -1)

C# 166 Bytes
string a(string i){var z=i.Split(' ');int g=1,c=0;var m="-1";foreach(var w in z)foreach(var l in w.Distinct()){c=w.Where(x=>x==l).Count();if(c>g){g=c;m=w;}}return m;}

Straightforward coding. Nothing Special in here.
C# sucks for code golfing :-/

Pure Bash (no external commands) 129 bytes
This is quite long, but still compares favourably with some of the other longer entries.
m=1
w=-1
for b;{
declare -A a
for((i=0;i<${#b};i++));{
c=${b:$i:1}
let a[$c]++
d=${a[$c]}
((d>m))&&w=$b&&m=$d
}
unset a
}
echo $w

I'm not entirely happy with some of the constucts, having to use that inner for loop is annoying. Any suggestions?

Python, 58
max('-1',*input().split(),key=lambda w:len(w)-len(set(w)))

JavaScript (ES7?), 99
Using array comprehension, that is implemented in Firefox but no more included in EcmaScript 6.
Test using the snippet below (Firefox only)

f=s=>s.split(' ').map(w=>[for(c of(l=[m=0],w))(n=l[c]=-~l[c])>m?m=n:0]&&m>x&&(x=m,v=w),x=1,v=-1)&&v

// TEST
out=x=>O.innerHTML+=x+'\n';

test=x=>out(x+' -> '+f(x))

;["aaabbb cccc","This is a great day","Today, is the greatest  day ever a!"]
.forEach(t=>test(t));

Try:<input id=I><button onclick='test(I.value),I.value=""'>-></button>

Ungolfed And more compatible

function f(s)
{
  v = -1;
  x = 1;
  s.split(' ')
  .forEach(function(w){
    l=[];
    m=0;
    w.split('').forEach(function(c){
      n=l[c]=-~l[c];
      if (n>m) m=n;
    })
    if (m>x) x=m,v=w;
  })
  return v;
}

// TEST
out=function(x) { O.innerHTML+=x+'\n' }

test=function(x) { out(x+' -> '+f(x)) }

;["aaabbb cccc","This is a great day","Today, is the greatest  day ever a!"]
.forEach(function(t) { test(t)} );

Try:<input id=I><button onclick='test(I.value),I.value=""'>-></button>

C (167)
double m,k,n=k=2,*O,V[256];char*f(char*c,char*s){return*c?((*O=!((n+=!(*c*=*c!=32))>1.1/modf(*(O=V+*c),&m))*m+1/n+1)>k)?f(c+!!(k=*O),c):f(c+1,s):s?!*s?s+1:f(c,s-1):0;}

TRY IT
HOW DOES THIS WORK?

the function is inner recursive one inside another recursive function, the insider function retrieves the beginning of a string where an inclusive character is returned by first function.
maximum number is given by hashing characters over an ascii table.

Q (44 bytes)
{w l?0|/l:{max(#:)'[(=)x]}'[w:" "vs"-1 ",x]}

ungolfed
{
    words:" " vs "-1 ",x;
    counts:{max count each group x} each words;
    : words counts ? max counts;
}

Haskell 96 Bytes

r o=(last.sort.map length$(group.sort)o,o)
w p=n$maximum(map(r)(words p))
n (1,_)="-1"
n (_,w)=w

```

r is a function that takes a word and return a tuple (n,w) where n is the number of occurrence of the most occurring char in the word w. For instance let x="norep", y="dnredundant", then r x=(1,norep), r y=(3,ndredundant)
w is a function that takes a string containing a number of space-separated words and:

Split the list on space words p
foreach word create a list of (n,w)
take the tuple that has the greatest n (occurrence counter)
If it has n equals to 1 simply return the string -1, the word itself (stored in the second component of the tuple) otherwise.

For instance take p="Today, is the greatest day ever!"

produces ["Today,","is","the","greatest","day","ever!"]
[(1,"Today,"),(1,"is"),(1,"the"),(2,"greatest"),(1,"day"),(2,"ever!")]
(2,"greatest")
2 != 1 then greatest is the solution!


text:
VSEPR Strikes Back! [Revamped Again]
(Note: I know that the VSEPR method fails sometimes, and that there are exceptional molecules. The challenge is about the molecules which conform.)
Most people who have taken an introductory chemistry course know about molecules, and (probably) the VSEPR theory of chemical bonding. Basically, the theory predicts the shape of a molecule given three main properties:

A: The central atom. You may assume this is the first element appearing in the chemical formula; for example, in CH4, you may assume the central atom is C.
X: The number of atoms bonded to the central atom A.
E: The number of "lone electron pairs" on the central atom. For the purposes of this challenge, the number of outer electrons A has is given by the last digit of the element's column number on the periodic table.

If A is bonded to an element X in column 17 of the periodic table, there will be a mutual sharing of electrons, so that A effectively has one additional electron for each atom of X attached to it. (This does not apply for elements such as O or S in column 16.)

Each bond requires two of these electrons. Leftover electrons not used in bonding with other atoms are found in pairs of two, called lone pairs. So E is the number of electrons not used in bonding by the central atom A divided by 2. (It may be assumed that input will always lead to A having an even number of electrons.)
For example, a molecule which has 1 lone pair and 3 atoms bonded to the main atom is AX3E1, which is the trigonal pyramidal configuration. (There is always only 1 central atom, so A never has a subscript.)
The Challenge
Your job is, given a string representing a covalent chemical compound, to output the shape of that molecule. "But wait!", exclaim the exasperated programmers, "you can't expect us to input all of the molecular data for every element!" Of course we can, but as that wouldn't be fun, we'll only consider the compounds formed by the following 7 elements:
Carbon    C
Sulfur    S
Oxygen    O
Nitrogen  N
Chlorine  Cl
Bromine   Br
Fluorine  F

The input is any molecule composed of the above 7, such as CO2 or SF4, that is in the form AXN, where A and X are each one of the above seven element symbols, X is not C or N, and N is a number between 2 and 6 inclusive.
The output should be the name of the geometric shape of the molecule, for example "linear".
The following (don't get scared, I swear they're less than they seem!) is a list of all possible configurations along with their AXE number and a drawing of how they look (adapted from Wikipedia's nifty table):

Test Cases

CO2: CO2 -> linear
  OF2: OF2 -> bent
  CCl2: CCl2 -> bent
  BrF3: BrF3 -> T-shaped
  SF4: SF4 -> seesaw

Notes:
 - We won't consider compounds in which the first element has a subscript other than 1, such as C2H4.
 - Standard loopholes apply.
 - This is a code golf, so the shortest answer wins (obviously)

Welcome to PPCG. Apart from the fact that Ethylene is C2H4 there are multiple ambiguities here. 1.I think you should abandon substances like ethylene and guarantee that the first named element will be A and there will be only one. 2.Your explanation is inadequate for a non chemist, you should at least explain that the number of electrons in the outer shell can be found by looking at the periodic table. 3. Is X guaranteed to be mono or divalent? is it only halogens, hydrogen and oxygen? 4.there is nothing in the basic spec about ionic compounds such as NaCl, which ones have to be detected?

Voting to close as unclear. I suggest you simplify the bonuses and give a fixed list of elements that must be supported (and that edge cases where VSEPR fails, including ionic compounds, be ignored, otherwise it's a chemistry question not a programming one.) You should also list the molecule shapes exactly as they are to be output. Writing a good question is hard. I suggest you consider using  http://meta.codegolf.stackexchange.com/q/2140/15599

BTW, I don't think this deserves a downvote (if whoever gave it is reading.) There's potential for a good question. It's just that codegolf requires a really tight spec to be fair and sporting. A few more points: 5. What is the maximum value of X+E to be supported? The examples go up to 6, I'm used to going up to 7, but Wikipedia goes up to 9! 6. you should explain subtleties around AB3X2 : T shaped preferred to keep the lone pairs far apart. 7. Angles can only be found by looking them up, not calculating, so have no place in a programming question like this. BrF3 is actually 86.2deg, not 90.

@steveverrill Hello and thanks for such a thorough breakdown of where my question doesn't add up. I actually did place the question in the sandbox a day or two before, but got no feedback, so I decided to just try my luck. About your suggestions (thanks again for those!): 1. Changed. 2. Tried to make clearer and more elementary. 3. I only allowed 7 elements, so that should make the question less broad. 4. I defined what counts as an ionic compound here, didn't fully understand what you meant though. Simplified the bonuses and other small things like removing the angles.

I think X + E is bounded by the restrictions on the possible compounds, otherwise 6 should be good (and I doubt it goes higher than that.) 6. I'd prefer to remove it altogether so as not to make the question too technical. 7. Took them out.

Feedback in the sandbox can be patchy and slow, especially when your question needs knowledge of a particular field. With the restriction on elements I agree X+E is limited to 6. Of the remaining bonuses 2 doesn't make sense because the elements in wikipedia's exceptions are outside the ones listed. Bonus 1 requires a library of all nonmetals, but some elements are ambiguous. A cheat implementation would be to consider all elements not on the list of 7 to be "metals." for example if I said "ionic" for iodine it would pass, because the program isn't supposed to cope with that element.

+1 for what you've fixed so far, but in order to cast a reopen vote, I'd like to see: bonuses gone as they don't seem to make sense; removal of the examples containing metals, as they'd no longer be relevant; but on the other hand, if you want to include ions, give some examples of that. And most importantly, include the table of AXnEm with the required output for each one (all relevant lines from AX to AX5E / AX6). I know it's halfway down the wikipedia article, but it would be far less ambiguous if it were in the question.

@steveverrill Changed as per your suggestions, although on seeing the table of configurations, I'm starting to think a steric number of 6 is a bit too high. Maybe I should reduce it further to 5? Thanks again for all your time on this question.

I've made some edits to your explanation. A does not neccesarily have 8 electrons, it actually has (X+E)*2 electrons, which can be a reduced octet as in BF3 or SO3 (6 electrons) or an increased octet as in SF4 (10 electrons.) That's why you get the different shapes. The issue of pi backdonation by O in compounds like SO3 or CO2 (to create a double bond) is best ignored in VSEPR. I deleted the bit about ions as it creates some issues (though I'm no longer sure they're serious.) roll back if you disagree.

I don't see the need to reduce steric number. 6 is a natural number for the elements you've restricted it to, as in SF6 or SCl5 (i'm not sure if steric number refers to X or X+E.) Reducing it would be a new arbitrary change. Does output have to be exactly per the table? (It's a lot of characters, that's why I've wanted to clarify.) I assume seesaw is accepted instead of disphenoidal. If you agree with what I've done I'll cast a reopen vote. It's a shame it's taken a while to get this clear. Next time leave it a bit longer in the sandbox, it's recommended to wait for some upvotes or a comment

@steveverrill thank you (and Thomas) for your edits. Your help has both really made the question do a 180 in terms of quality and clarity (although on second thought any subsequent science questions I might do in the future should be much less technical.) I do agree 6 is the natural value of X + E imposed by the elements chosen, and reducing it would probably cause more harm than good. Oh and yes, the names of the shapes should be exact, and as they're long, I don't really expect to see any ultra-short answers anyway. (and seesaw is accepted, who uses disphenoidal anyways?)

Ruby, 250
s=gets
e=7-"FBOSN C".index(s[0])/2+(s[1]==?l?3:0)
x=s.reverse!.to_i
e+="Frl".index(s[2])?x:0
t="trigonal "
puts [["linear",b="bent",b],[t+"planar",t+p="pyramidal","T-shaped"],["tetr"+h="ahedral","seesaw"],[t+"bi"+p,"square "+p],["oct"+h]][x-2][e/2-x]

Note that with the rules as they are, AX2E3 and AX4E2 are not possible with the given elements, so they are not supported. All test cases passed.
with comments
s=gets                                     #get input with newline attached
e=7-"FBOSN C".index(s[0])/2+(s[1]==?l?3:0) #calculate the number of electrons (not lone pairs) from A. Note the addition required to differentiate C and Cl.
x=s.reverse!.to_i                          #reverse the input string so the number is at the beginning (after the newline) and evaluate the string as a number to get X.
e+="Frl".index(s[2])?x:0                   #if the character after the number is in "Frl" we have a halogen so increment number of electrons accordingly.
t="trigonal "                              #as "trigonal " goes at the beginning of the string, we cannot define it on the fly, it is defined as a constant here.
                                           #array of outputs below. note the subscripts at the end: x-2 to put it in the range 0..4 and e/2-x to convert e into the actual number of lone pairs.
puts [["linear",b="bent",b],[t+"planar",t+p="pyramidal","T-shaped"],["tetr"+h="ahedral","seesaw"],[t+"bi"+p,"square "+p],["oct"+h]][x-2][e/2-x]

Nice answer. I like the way you were able to cut down on the bytes for the names by concatenating bits and pieces of the words. Cheers!

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Tricky interview puzzle: get longest sequence by flipping 1 bit
A friend of mine got this question during an interview.
The interview ended with no luck for him, but still, we're very curious to hear the solution. The question is as follows:
Modify the code below (change 3 lines maximum) so the function will return the length of the longest sequence of the same bit, if you would flip one bit in the given array.
Note: the method's parameter is a bits array.
For example: take the bits array: "11001001010". By flipping the 5th bit from "1" to "0", we'll get: "11000001010" and the result would be: 5.
private static int solution(int[] a) {

    int n = a.length;
    int result = 0;
    int i;

    for (i = 0; i < n - 1; i++) {

        if(a[i] == a[i + 1])
            result = result  + 1;
    }
    int r = 0;
    for (i = 0; i < n; i++) {

        int count = 0;
        if(i > 0)   {
            if(a[i - 1] != a[i])
                count = count + 1;
            else
                count = count - 1;
        }
        if(i < n - 1)   {
            if(a[i + 1] != a[i])
                count = count + 1;
            else
                count = count - 1;
        }

        if(count > r)
            r = count;
    }

    return result + r;
}

Why is this off topic? This looks exactly like what the the tag wiki describes for for [tag:programming-puzzle]. And we've had programming puzzles that are just solved, without additional scoring like fewest bytes.

I would like to join to @xnor's question - why is this off topic?

I voted "unclear". What counts as changing a line? It seems that in principle this would allow dropping in a one-liner solution and using none of the supplied code at all. And what do you mean by "the length of the longest sequence of the same bit, if you would flip one bit in the given array"? I presume we have to interpret the int[] as a bit[] and maximise the longest sequence over each case of "flip bit X", but what endianness (or endiannesses - in some contexts it's different for the 4 bytes in an int and the 8 bits in a byte) should we use to interpret the int[] as a bit[]?

@PeterTaylor - I think that it's common sense not to do that in a one liner... Think of the real world - if you would go to a job interview right now, would you dare writing a one liner?? Regarding the int vs bit array - you're right. I've added an example and changing right now the description.

@xnor There is no objective primary winning criterion, as stated in the close reason under the question.

@Doorknob Isn't [tag:programming-puzzle] relieved from that requirement, just like [tag:popularity-contest]?

@orlp Popularity-contest is absolutely not relieved from that requirement (most votes is the primary objective winning criterion), nor is programming-puzzle to the best of my knowledge. Do you have a meta post or a tag wiki that is the source of that rule?

@Doorknob It would be rather strange if a site called "Programming Puzzles and Code Golf" does not actually allow programming puzzles.

@xnor Of course we allow them. It would also be rather strange for a certain question to be arbitrarily able to bypass a rule we've had in place since almost the very beginning of the site. (Please post on meta if you think the policy should be changed.)

@ofirbt. You could edit your question to a suitable challenge by asking for a working function with the minimum number of changes. Be precise about specifying what counts as a +1 change. Add some testcases - inputs & expected outputs. A shame it is language specific.

@Doorknob OK, meta post, though I don't necessarily think the policy should be changed, it's just a strange contradiction between policy and practice.

This need more clarification about what is valid and what is not. If the answer cannot be one-liner, it is still not clear whether 3 statements on the same line, or if(false) equivalents are valid. The "common sense" thing discourages creative ideas.

@gnibbler - The question is not about getting any solution, but understanding this specific one. And although it's written in Java, I think it's perfectly understandable - this code looks like pseudo! Plus, it's taken from Codility and it's a legitimate programming puzzle.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Draw the combinations that add up to 100
You have a box with a single digit number in each corner:
1|2
---
3|4

If we concatenate the digits along rows left to right, we get 12 and 34. If we concatenate the digits along columns top to bottom, we get 13 and 24. If we add all of these numbers, we get 12+34+13+24 = 83.
Challenge
Write a program to print all such boxes where the sum calculated as above is equal to 100.
Assuming each corner contains a single digit number between 1 and 9, there are 9 combinations: 1157, 1247, 1337, 1427, 1517, 2138, 2228, 2318, and 3119. (Note that there are 25 combinations if we include 0, but we're not for this challenge.)
Note that the example 1234 doesn't work since 12+34+13+24 does not equal 100.
Input
None
Output
Answer boxes in the following format:
A|B
---
C|D

Output should be printed to STDOUT or closest alternative.
Rules

AB + CD + AC + BD = 100
Each corner will contain the positive integers 1-9 only.
0 is excluded.
Numbers can be used more than once.
You need to draw the boxes, as above. (A|B\n---\nC|D\n)
You need to output all valid answers.
An additional trailing newline is fine.
code-golf, so shortest code in bytes wins.
Standard loopholes and T&C's apply.

This is my first submission so please do let me know if I need to clarify anything.

Could you show what the output is supposed to be? Also, what about a trailing newline character?

Nice challenge. I think you need to explicitly tell what numbers need to be added. The line "The two, concatenated, two digit numbers across PLUS the two, two digit numbers down have to equal 100." is not clear enough. I only figured out using the example of 1234. Also, I am only getting 9 such combinations. Can you please mention the 16 combinations ?

Sure, I'll update the question to be more specific. Thanks.

Sorry @Optimizer, I forgot a few solutions that contained 0 in my list. You are correct.

Welcome to PPCG. For future reference, I think this would have been better if you had included zero. The reason is, with only 9 combinations it makes sense to hardcode the solutions, which is 36 characters (or 6 combinations / 24 characters if you count diagonal reflections as equivalent.) Including zero would have made it worthwhile to write code to search for all combinations. But as you already have an answer , I wouldn't change the rules now.

@steveverrill ah, here I thought I was making it more interesting as one would need to manually exclude answers with '0' (if searching through the possible answers)

So I can choose which of the 9 solutions I want to output?

Oh, sorry for not being specific. No, you should output all valid combinations.

I made a few edits to the explanation and formatting. If it doesn't match your original intent, please roll back the edit.

@DenhamCoote actually, my semi-hardcoded solution was quite interesting to do, because it's only semi-hardcoded. This has been an exception to the rule, because questions where blatant hardcoding is the best / most obvious option often don't produce interesting answers (see recent borromean rings question for example.) Thank you for the question.

Are trailing spaces in the blank lines allowedd?

@kirbyfan64son since the blank lines are in fact optional, sure, trailing spaces in blank lines are ok.

One question for you regulars: Am I supposed to 'accept' the answer with the fewest bytes, or are the upvotes the decider? If I should, how long does one typically wait?  Thank you very much to everyone who has answered so far!

Accept the answer with fewest bytes, as that is what's stated in your question (in accordance with the codegolf tag.) This means languages like Pyth or Cjam nearly always win. The fairness of this has been questioned by many new users on meta, but the answer is always the same: an interesting answer in a verbose language gains more reputation from its upvotes, so failing to get accepted doesn't matter. It's strongly preferred to verify the answer yourself before accepting. BTW, questions which "win" by getting the most upvotes are tagged popularity contest (These are disliked by many people.)

Ah, thanks for that! I didn't set a time limit on this, so how long is usually appropriate before accepting? A week? Then, if I accept and then a shorter answer comes, should I change the accepted answer? (Sorry, don't know what's considered rude.  Also, why are popularity contests disliked? Surely, just don't take part if it's not someone's cup of tea?)

Accepting an answer may give the impression the question is finished, so I'd leave it a while yet. If you get more answers afterwards, you can change the acceptance, but that means you have to keep a lookout, which you may not have time to do. Popularity contests are disliked because they are often lazily written and overly broad, often of the type "Do X in the most complex way possible." Generally the only good popularity questions are in image processing, where human evaluation is the only way to decide if the algorithm is good or not. Image processing excludes pure art which is off topic.

Pyth, 42 38 34 bytes
V^ST4IqC\ds*VNsM^,T1 2Xj\|N3"
---

The trailing newline in the code is important. The main reason I'm competitive is because I use the vector dot product of [1, 1, 5, 7] and [20, 11, 11, 2] and compare it to 100.

"|" -> \| , \n -> (literal linefeed) and you don't need the final quote.

@Dennis Was sleeping >.<

If you don't mind, could you please add an explanation for those (like me) who can't decipher your incredibly short answer?

Ruby, 71
As hardcoding is not disallowed (and in any case it is difficult to draw a line) here's a partial hardcoded answer.
1.upto(3){|i|1.upto(7-i*2){|j|print i,?|,j,'
---
',8-j-2*i,?|,i+6,'
'}}

Explanation
The formula for a solution is as follows:
A*20+(B+C)*11+D*2=100

By modular arithmetic arguments, we see that A and D must differ by a constant amount, such that (A*20+D*2)%11 is constant. In fact D=A+6. The i loop iterates through the three possible values of A.
The value of B can be anything from 1 to 7-i*2 and the total of B and C must be 14-A-D. Thus we obtain the following expressions, which are printed. Ruby allows literal newlines in strings enclosed in ''
   i     |    j
------------------
8-j-2*i  |   i+6

Java, 202 200 198
Trying for the first time :D
EDIT: saved 2 bytes with slightly smaller calculation found in an other comment.
class C{public static void main(String[]c){for(int i=0;++i<5;)for(int j=0;++j<7;)for(int k=0;++k<10;)for(int l=0;++l<10;)if(20*i+11*(j+k)+2*l==100)System.out.printf("%s|%s%n---%n%s|%s%n",i,j,k,l);}}

Batch - 187 bytes
Brute force.
@!! 2>nul||cmd/q/v/c%0&&exit/b
set y=for /l &set z= in (1,1,9)do
%y%%%a%z%%y%%%b%z%%y%%%c%z%%y%%%d%z%set/aa=%%a%%b+%%c%%d+%%a%%c+%%b%%d&if !a!==100 echo %%a^|%%b&echo ---&echo %%c^|%%d

Un-golfed it's slightly less disgusting:
@echo off
setLocal enableDelayedExpansion
for /l %%a in (1,1,9) do (
    for /l %%b in (1,1,9) do (
        for /l %%c in (1,1,9) do (
            for /l %%d in (1,1,9) do (
                set/aa=%%a%%b+%%c%%d+%%a%%c+%%b%%d
                if !a!==100 (
                    echo %%a^|%%b
                    echo ---
                    echo %%c^|%%d
                )
            )
        )
    )
)

CJam, 40 bytes
A4m*{[KBBY].*:+56=},{:)2/'|f*"
---
"*N}/

The approach for finding the combinations is different from @Optimizer's, but the code for printing them is identical.
Try it online in the CJam interpreter.
How it works
A4m*     e# Push all vectors of length 4 with coordinates in [0 ... 9].
         e# We'd normally use [0 ... 8] here, but "9 4m*" is 1 byte longer and
         e# "A4m*" doesn't produce any false positives.

{        e# Filter the vectors:
[KBBY].* e#   Multiply the elements of the vector by 20, 11, 11 and 2.
:+       e#   Add all four products.
56=      e#   Check if the sum is 56. 56 is used instead of 100 since all elements
         e#   of the vector will be incremented and 56 + 20 + 11 + 11 + 2 == 100.
},       e# Keep only vectors for which = pushed a truthy value.

{        e# For each vector:
:)       e#   Increment each coordinate.
2/       e#   Split into pair.
'|f*     e#   Join each pair, delimiting by '|'.
"
---
"*       e#   Join the two pairs, delimiting by "\n---\n".
N        e#   Push "\n".
}/       e#

Since I know very little apart from some Java, I'd love an explanation of how this works, if you're willing..?

That's a nice trick.

Wow. I have much to learn. Thanks for the explanation :)

Haskell, 125 121 bytes
s=show
f=putStr$unlines[s a++'|':s b++"\n---\n"++s c++'|':s d|[a,b,c,d]<-mapM id$"abcd">>[[1..9]],20*a+11*(b+c)+2*d==100]

Usage:
*Main> f
1|1
---
5|7
1|2
---
4|7
1|3
---
3|7
1|4
---
2|7
1|5
---
1|7
2|1
---
3|8
2|2
---
2|8
2|3
---
1|8
3|1
---
1|9

>> in "abcd">>[[1..9]] makes a list with 4 (length of 1st parameter) copies of the second element, i.e. [[1..9],[1..9],[1..9],[1..9]]. mapM id makes a list of all combinations thereof, i.e [0,0,0,0] to [9,9,9,9]. Keep those that sum up 100 and build a string with the box of it. Print all boxes.
Thanks @Mauris for 1 byte and making me review my post to find 3 more.

mapM id saves a byte vs. sequence.

Haskell, 107 131 bytes
s=show
r=[1..9]
v=putStr$unlines[s a++"|"++s b++"\n---\n"++s c++"|"++s d++"\n"|a<-r,b<-r,c<-r,d<-r,(2*a+b+c)*10+b+2*d+c==100]

The second version of my first Haskell program ever!
This time with display as per requirements, shamelessly stolen adapted from nimi's (well I did some research but it seems there aren't so may efficient ways to display characters in Haskell so that putStr$unlines is hard to avoid).
And...apart from the factorisation of the formula at the end, it's still readable =)

CJam, 43 42 bytes
A,1>4m*{2/_z+Afb:+100=},{2/'|f*"
---
"*N}/

Explanation to follow.. by today EOD
Try it online here

My golfed java version (which doesn't bother with boxes, it only lists the sequences) was 197 chars. This does it all in a quarter of the length! Cool :)

@DenhamCoote That's every CJam, Pyth, and GolfScript answer.

Still looking forward to that explanation ;-)

Python 2, 145 129 Bytes
I'm currently toying with a few different methods of calculating which should be shorter than what is outlined, but I will post what I have now.
i=int
for k in range(1000,9999):
 a,b,c,d=`k`
 if i(a+b)+i(c+d)+i(a+c)+i(b+d)==100and not'0'in`k`:print a+'|'+b+'\n---\n'+c+'|'+d

Python 3, 159
Quick and dirty.
N='123456789'
D='%s|%s\n'
O=D+'---\n'+D
I=int
[print(O%(a,b,c,d)if I(a+b)+I(c+d)+I(a+c)+I(b+d)==100 else'',end='')for a in N for b in N for c in N for d in N]

Java, 450
My first (ungolfed) attempt looked like this:
class B{
  public static void main(String[]a){
    for(int i=1;i<10;i++)
      for(int j=1;j<10;j++)
        for(int k=1;k<10;k++)
          for(int l=1;l<10;l++)
            if(Integer.parseInt(i+""+j)+Integer.parseInt(k+""+l)+Integer.parseInt(i+""+k)+Integer.parseInt(j+""+l)==100){
              System.out.println(i+"|"+j);
              System.out.println("---");
              System.out.println(k+"|"+l+"\n");
            }
  }
}

Hint: 20*a + 11*(b + c) + 2*d == 100.

Yeah, this solution was purely string concatenation - a very humble first attempt.

I count only 436 bytes, not 450. Also, the whitespace isn't necessary, which would save you a considerable amount.

Furthermore, removing unnecessary whitespace, this should be closer to 340 bytes :)

R, 165 bytes
e=expand.grid(d<-1:9,d,d,d)
a=apply
o=a(e[a(e,1,function(x)20*x[1]+11*(x[2]+x[3])+2*x[4]==100),],1,function(x)cat(x[1],"|",x[2],"\n---\n",x[3],"|",x[4],"\n",sep=""))

This would have been significantly shorter had I chosen to hard-code the output in some way. Like a few other solutions, this takes advantage of the identity 20 x1 + 11 (x2 + x3) + 2 x4 = 100.
Ungolfed + explanation:
# Create a matrix where each row is a combination of the digits 1-9
e <- expand.grid(1:9, 1:9, 1:9, 1:9)

# Filter the rows of the matrix using the aforementioned identity
e <- e[apply(e, 1, function(x) 20*x[1] + 11*(x[2]+x[3]) + 2*x[4] == 100), ]

# Print each row formatted into boxes
o <- apply(e, 1, function(x) cat(x[1], "|", x[2], "\n---\n", x[3], "|", x[4], sep = ""))

You may be wondering why the last statement is an assignment. As it turns out, the cat function, which concatenates and prints, returns a value of NULL. When you call cat from within a function like apply, the output will be followed by NULL, which is undesirable. There are two ways around this: assign it to a variable or wrap it in invisible. Here I've opted for the former since it's significantly shorter.
You can try it online.

PowerShell , 98
adapted steveverrill's formula
:\>cat printbox.ps1

1..9|%{for($j=1;$j-lt10;$j++){if(($k=(8-$j-2*$_))-gt0){"{0}|{1}`n---`n{2}|{3}"-f$_,$j,$k,
($_+6)}}}

:\>powershell -f printbox.ps1
1|1
---
5|7
1|2
---
4|7
1|3
---
3|7
1|4
---
2|7
1|5
---
1|7
2|1
---
3|8
2|2
---
2|8
2|3
---
1|8
3|1
---
1|9


text:
Printing the Cracker Barrel Game
Revised formatting and instructions
Given a list of moves for a Cracker Barrel peg board game, or as @Steveverrill stated, Peg Triangle Solitaire:
Game 1        Game 2         Game 3
1:  0 ,-1, -1   C, -1, -1     4, -1, -1  #starting point
2:  3, 1, 0     3, 7, C       B, 7, 4    #jump_from, jump_over, jump_to
3:  A, 6, 3     0, 1, 3       D, C, B
4:  8, 4, 1     6, 3, 1       5, 8, C
5:  B, 7, 4     5, 2, 0       1, 4, 8
6:  2, 4, 7     C, 8, 5       E, 9, 5
7:  D, C, B     A, B, C       6, 3, 1
8:  9, 5, 2     D, C, B       2, 5, 9
9:  1, 3, 6     9, 5, 2       B, C, D
10: 0, 2, 5     1, 4, 8       9, 8, 7
11: 6, 7, 8     0, 2, 5       0, 1, 3
12: 5, 8, C     5, 8, C       3, 7, C
13: B, C, D     B, C, D       D, C, B
14: E, D, C     E, D, C       A, B, C

Here is your task

Write a program that takes a list of moves, each move has three arguments which are slots on the board (jump_from, jump_over, jump_to). Move the peg from jump_from to jump_to and remove jump_over. (If that is unclear then read the instructions linked at the top)
Print the board for each move

The direction of the move a.k.a. the arrow
The slot jumped from a.k.a. the *
The slot jumped to (if peg 3 was in slot 3, and jumped to slot 0, then print a 3 in slot 0)
print a . for any empty slots

How to play
-If you don't understand these rules then there is a link at the top.
I've provided three different games that result in one peg remaining. The idea of the game is to start with one peg missing in the board and remove pegs until there is one left. A move is jumping over a peg into an empty slot and removing the peg you jumped over. Valid moves are diagonals and horizontal moves only. Example (assume slots 1, 2, 3, and 6 are open):

8 over 4 to 1 is valid
8 over 7 to 6 is valid
8 over 7 or 4 to 3 is invalid
B over 7 and 4 is invalid

Your output should look like the following. Each board printed is one move
(Use hex instead of decimal since printing the board in decimal causes the last row to be too wide)
This is Game 1 from the move set at the top

       / 0 \        #This is the board with all slots filled
      / 1 2 \
     / 3 4 5 \
    / 6 7 8 9 \
   / A B C D E \

       / * \        #Move 1: remove the first peg which is 0
      / 1 2 \
     / 3 4 5 \
    / 6 7 8 9 \
   / A B C D E \

       / 3 \        #Move 2: Move peg 3 from slot 3 over slot 1 to slot 0
      / ↗ 2 \       Remove peg 1 from slot 1
     / * 4 5 \
    / 6 7 8 9 \
   / A B C D E \

       / 3 \        #Move 3
      / . 2 \
     / A 4 5 \
    / ↗ 7 8 9 \
   / * B C D E \

       / 3 \        #Move 4
      / 8 2 \
     / A ↖ 5 \
    / . 7 * 9 \
   / . B C D E \

       / 3 \        #Move 5
      / 8 2 \
     / A B 5 \
    / . ↗ . 9 \
   / . * C D E \

       / 3 \        #Move 6
      / 8 * \
     / A ↙ 5 \
    / . 2 . 9 \
   / . . C D E \

       / 3 \       #Move 7
      / 8 . \
     / A . 5 \
    / . 2 . 9 \
   / . D ← * E \

       / 3 \        #Move 8
      / 8 9 \
     / A . ↖ \
    / . 2 . * \
   / . D . . E \

       / 3 \        #Move 9:
      / * 9 \       Move peg 8 from slot 1 over slot 3 to slot 6
     / ↙ . . \      Remove peg A
    / 8 2 . . \
   / . D . . E \

       / * \        #Move 10
      / . ↘ \
     / . . 3 \
    / 8 2 . . \
   / . D . . E \

       / . \        #Move 11
      / . . \
     / . . 3 \
    / * → 8 . \
   / . D . . E \

       / . \        #Move 12
      / . . \
     / . . * \
    / . . ↙ . \
   / . D 3 . E \

       / . \        #Move 13
      / . . \
     / . . . \
    / . . . . \
   / . * → D E \

       / . \        #Move 14
      / . . \
     / . . . \
    / . . . . \
   / . . E ← * \

The * represents the most recent peg removed. That is why the board starts with a * at slot 0 instead of a 0. . represents an empty slot. The slots stay in the same position but the pegs are numbered and move around so for the very last move peg E moves from slot E over peg/slot D to slot C
The direction of the move is the unicode characters u2190 through u2199
This is code golf so lowest number of bytes wins. Good Luck!
If something is unclear don't hesitate to ask. I will do my best to clarify.

I don't understand your representation of the board. There is no "0" peg at the beginning, but after the first jump, a "0" peg appears. So I thought maybe you are just numbering the positions, but then somehow a 3 ended up on the bottom row, which means the pegs are moving around. Can you explain your output?

@Rainbolt You were confused for good reason. I had my output screwed up but I think I fixed it and if not hopefully enough to be understood. I also added some clarification near the end

You've explained the meaning of the * and ., but the non-ASCII symbols are not mentioned. Are they required in the output?

That's the direction of the move which is required. I have that at the top but I'll make it more clear

@Rainbolt The input should always be valid. There's no need to check for invalid moves. Regarding the identifying holes vs pegs if you only identify holes then you can represent the pegs being moved, only the holes being filled or not which makes the board harder to read. It's however you want to look at it honestly. I chose pegs and holes to describe which peg was moving and to where. Lastly, I will change it to be hex only since the board doesn't display neatly with the last row being decimal.

@SirParselot Whoops, I deleted my comment right before you replied because it was only really a suggestion and this is your first challenge. By the way, you can post challenge in the Sandbox once you gain a tiny amount of reputation (I think 50?), and then you can get feedback on challenges before you post them. Totally optional, but highly recommended if you want your challenge to be polished before you post it.

@Rainbolt I appreciate the suggestions. I like hearing feedback about my challenge.

What are the rules of the game? Are you missing words to the effect of "For each move in the list" somewhere in the description of what should be output, or is the example covering lots of different inputs? How can we "post your output as well" if the output depends on the input? (And if it's going to be the same as the example output, why on Earth should we force everyone who wants to read the answers to scroll past a massive chunk of text which doesn't add any value to the page?)

@PeterTaylor Sorry, I just assumed people would know the rules of the game. Everyone knows them from where I'm from. I'll post them. I will also add more description about the moves in the list.

We don't have Cracker Barrel restaurants outside the US. I've added a link to a website with the rules (it seems the name of the game is in fact peg triangle solitaire) but I think you should describe them also.

@steveverrill thanks, I completely passed over that detail

Ruby -pa, 181 bytes
$_=b||=+-s=(1..5).map{|i|"/ #{[*:A6310[-i]..?E][0,i]*' '} \\".center 13}*$/+$/
f,o,t=$F.map{|i|s=~/#{i}/}
b.tr!(a='→↙↘*↖↗←',?.)?(b[t],b[o]=b[f],a[(o-f)/7]):$><<b
b[f]=?*

Try it online!
The score would be 169 if counted by characters. It's unfortunate that the arrow characters are 3 bytes each, but using them directly is shorter than every method I tried for generating their codepoints (which are irregularly spaced).
Explanation
The board, stored as a multiline string, is padded out to a rectangular grid with leading and trailing spaces on each line. Let \$f\$ and \$o\$ be the indices within this string of the slots being jumped from and over, respectively. Then the following table describes all jumps, independent of the specific slots involved:

Direction
\$o-f\$
\$\left\lfloor(o-f)/7\right\rfloor\$

←
\$\phantom{1}{-2}\$
\$-1\$

→
\$\phantom{-1}2\$
\$\phantom{-{}}0\$

↖
\$-15\$
\$-3\$

↗
\$-13\$
\$-2\$

↘
\$\phantom{-{}}15\$
\$\phantom{-{}}2\$

↙
\$\phantom{-{}}13\$
\$\phantom{-{}}1\$

Conveniently, we see that \$\left\lfloor(o-f)/7\right\rfloor\$ yields a unique value between \$-3\$ and \$2\$ for each jump direction, ideal for indexing into a string (a) containing the arrow characters.
Flags
-p: Loop through the code for every line of input and implicitly print the contents of $_ at the end of each iteration.
-a: Form the array $F by splitting the input on spaces.
Line by line
$_=b||=+-s=(1..5).map{|i|"/ #{[*:A6310[-i]..?E][0,i]*' '} \\".center 13}*$/+$/

Two boards are saved: s is the starting configuration (all slots filled) whereas b (shadowed by $_) is the current configuration. For each line \$i\in[1,5]\$ in s, slot numbers are generated by taking the first \$i\$ elements of a character range beginning with 0, 1, 3, 6, or A and always ending with E. Each line is padded with leading and trailing spaces (.center 13), the lines are joined by newlines (*$/), and a trailing newline is appended (+$/).
On the first iteration only, s is cloned into b (b||=+-s). $_ is set equal to b so that the board will be printed at the end of each iteration. Since b and $_ point to the same string object, all subsequent operations on b affect $_ too.
f,o,t=$F.map{|i|s=~/#{i}/}

Map the input slot numbers to indices in s, saving the results in f (jump_from), o (jump_over), and t (jump_to). The mapping is as follows: 0 → 6, 1 → 19, 2 → 21, 3 → 32, 4 → 34, 5 → 36, 6 → 45, 7 → 47, 8 → 49, 9 → 51, A → 58, B → 60, C → 62, D → 64, E → 66.
b.tr!(a='→↙↘*↖↗←',?.)?(b[t],b[o]=b[f],a[(o-f)/7]):$><<b

In b, replace the * and arrow character from the previous jump with .. The shouty .tr! modifies b in place, returning nil (falsey) on the first move (no previous jump so no replacements performed) and b (truthy) on all other moves. If it is the first move, print the board with all slots filled ($><<b). Otherwise, update the jump_to slot with the peg from the jump_from slot and set the jump_over slot to the appropriate arrow character by indexing into a as described above.
b[f]=?*

Set the jump_from slot to *, after which the board is implicitly printed.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Useful C++ template metaprograms
C++ implements a Turing-complete functional programming language which is evaluated at compile time.
Hence, we can use a C++ compiler as an interpreter to run our metaprogram without ever generating code.  Unfortunately, static_assert won't allow us to emit our result at compile-time, so we do need* to generate an executable to display the result.
* we can display via a compile-time error in template instantiation, but the result is less readable.
Challenge
Implement a useful or impressive program purely via template metaprogramming.  This is a popularity contest, so the code with the most votes wins.
Rules:

Your program must compile against the C++14 standard.  This means that the actual compiler you use doesn't matter to anyone else.
-std=c++14
"External" input is passed via preprocessor definitions.
-Dparam=42
Output is via a single cout/printf line which does no run-time calculations besides those necessary for stringifying the result, or is via a compile-time error.
int main(int argc, char **argv) {
     std::cout << MyMetaProgram<param>::result << std::endl;
 }

Example: Factorial
bang.h
template <unsigned long long N>
struct Bang
{
    static constexpr unsigned long long value = N * Bang<N-1>::value;
};

template <>
struct Bang<0>
{
    static constexpr unsigned long long value = 1;
};

bang.cpp
#include <iostream>
#include "bang.h"

int main(int argc, char **argv)
{
    std::cout << Bang<X>::value << std::endl;
}

execute
$ g++ -std=c++14 -DX=6 bang.cpp -o bang && ./bang
120

I think "useful" and "impressive" are too subjective and broad for this challenge to be a good fit for the site.

That's why it's a popularity contest :)  I'll let the voting system decide

Popularity contests still need the task to be specific and well-defined. I suggest taking a look at the popularity contest tag wiki.


text:
Simpson diversity index
The Simpson index is a measure of diversity of a collection of items with duplicates. It is simply the probability of drawing two different items when picking without replacement uniformly at random.
With n items in groups of n_1, ..., n_k identical items, the probability of two different items is

For example, if you have 3 apples, 2 bananas, and 1 carrot, the diversity index is
D = 1 - (6 + 2 + 0)/30 = 0.7333
Alternatively, the number of unordered pairs of different items is 3*2 + 3*1 + 2*1 = 11 out of 15 pairs overall, and 11/15 = 0.7333.
Input:
A string of characters A to Z. Or, a list of such characters. Its length will be at least 2. You may not assume it to be sorted.
Output:
The Simpson diversity index of characters in that string, i.e., the probability that two characters taken randomly with replacement are different. This is a number between 0 and 1 inclusive.
When outputting a float, display at least 4 digits, though terminating exact outputs like 1 or 1.0 or 0.375 are OK.
You may not use built-ins that specifically compute diversity indices or entropy measures. Actual random sampling is fine, as long as you get sufficient accuracy on the test cases.
Test cases
AAABBC 0.73333
ACBABA 0.73333
WWW 0.0
CODE 1.0
PROGRAMMING 0.94545

Leaderboard
Here's a by-language leaderboard, courtesy of Martin Büttner.
To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:
# Language Name, N bytes

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:
# Ruby, <s>104</s> <s>101</s> 96 bytes

function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/53455/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function getAnswers(){$.ajax({url:answersUrl(page++),method:"get",dataType:"jsonp",crossDomain:true,success:function(e){answers.push.apply(answers,e.items);if(e.has_more)getAnswers();else process()}})}function shouldHaveHeading(e){var t=false;var n=e.body_markdown.split("\n");try{t|=/^#/.test(e.body_markdown);t|=["-","="].indexOf(n[1][0])>-1;t&=LANGUAGE_REG.test(e.body_markdown)}catch(r){}return t}function shouldHaveScore(e){var t=false;try{t|=SIZE_REG.test(e.body_markdown.split("\n")[0])}catch(n){}return t}function getAuthorName(e){return e.owner.display_name}function process(){answers=answers.filter(shouldHaveScore).filter(shouldHaveHeading);answers.sort(function(e,t){var n=+(e.body_markdown.split("\n")[0].match(SIZE_REG)||[Infinity])[0],r=+(t.body_markdown.split("\n")[0].match(SIZE_REG)||[Infinity])[0];return n-r});var e={};var t=1;answers.forEach(function(n){var r=n.body_markdown.split("\n")[0];var i=$("#answer-template").html();var s=r.match(NUMBER_REG)[0];var o=(r.match(SIZE_REG)||[0])[0];var u=r.match(LANGUAGE_REG)[1];var a=getAuthorName(n);i=i.replace("{{PLACE}}",t++ +".").replace("{{NAME}}",a).replace("{{LANGUAGE}}",u).replace("{{SIZE}}",o).replace("{{LINK}}",n.share_link);i=$(i);$("#answers").append(i);e[u]=e[u]||{lang:u,user:a,size:o,link:n.share_link}});var n=[];for(var r in e)if(e.hasOwnProperty(r))n.push(e[r]);n.sort(function(e,t){if(e.lang>t.lang)return 1;if(e.lang<t.lang)return-1;return 0});for(var i=0;i<n.length;++i){var s=$("#language-template").html();var r=n[i];s=s.replace("{{LANGUAGE}}",r.lang).replace("{{NAME}}",r.user).replace("{{SIZE}}",r.size).replace("{{LINK}}",r.link);s=$(s);$("#languages").append(s)}}var QUESTION_ID=45497;var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";var answers=[],page=1;getAnswers();var SIZE_REG=/\d+(?=[^\d&]*(?:<(?:s>[^&]*<\/s>|[^&]+>)[^\d&]*)*$)/;var NUMBER_REG=/\d+/;var LANGUAGE_REG=/^#*\s*((?:[^,\s]|\s+[^-,\s])*)/
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
<link rel=stylesheet type=text/css href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Leaderboard

	AuthorLanguageSize

Winners by Language

LanguageUserScore

{{PLACE}}	{{NAME}}{{LANGUAGE}}{{SIZE}}Link

{{LANGUAGE}}{{NAME}}{{SIZE}}Link

You're using the Gini-Simpson index, when a much better measure to use is the inverse Simpson index a.k.a. effective number of types.

Basically 1/ instead of 1-. [amateur statistician rant hat off]

Python 2, 72
The input may be a string or a list.
def f(s):l=len(s);return sum(s[i%l]<>s[i/l]for i in range(l*l))/(l-1.)/l

I already know that it would be 2 bytes shorter in Python 3 so please don't advise me :)

What are the angle brackets <> doing at position 36? I've never seen that syntax before.

@TuttiFruttiJacuzzi: it's a synonym for !=.

@TuttiFruttiJacuzzi It's only python 2 unless you from __future__ import barry_as_FLUFL

@Vioz- Not with the l=len(s); in there

@Sp3000 Right, didn't notice how many times it was used.

J, 26 bytes
1-+/((#&:>@</.~)%&(<:*])#)

the cool part
I found the counts of each character by keying </. the string against itself (~ for reflexive) then counting the letters of each box.

(#&:>@</.~) can be (#/.~) and (<:*]) can be (*<:). If you use a proper function this gives (1-(#/.~)+/@:%&(*<:)#). As the surrounding braces are generally not counted here (leaving 1-(#/.~)+/@:%&(*<:)#, the body of the function) this gives 20 bytes.

Pyth - 19 13 12 11 bytes
Thanks to @isaacg for telling me about n
Uses brute force approach with .c combinations function.
csnMK.cz2lK

Try it here online.
Test suite.
c                Float division
 s               Sum (works with True and False)
  nM             Map uniqueness
   K             Assign value to K and use value
    .c 2         Combinations of length 2
      z          Of input
 lK              Length of K

You can replace .{ with n- they're equivalent here.

@isaacg oh didn't know it automatically splats, cool.

SQL (PostgreSQL), 182 Bytes
As a function in postgres.
CREATE FUNCTION F(TEXT)RETURNS NUMERIC AS'SELECT 1-sum(d*(d-1))/(sum(d)*(sum(d)-1))FROM(SELECT COUNT(*)d FROM(SELECT*FROM regexp_split_to_table($1,''''))I(S)GROUP BY S)A'LANGUAGE SQL

Explanation
CREATE FUNCTION F(TEXT) -- Create function f taking text parameter
RETURNS NUMERIC         -- declare return type
AS'                     -- return definition
    SELECT 1-sum(d*(d-1))/(sum(d)*(sum(d)-1)) -- Calculate simpson index
    FROM(
        SELECT COUNT(*)d  -- Count occurrences of each character
        FROM(             -- Split the string into characters
            SELECT*FROM regexp_split_to_table($1,'''')
            )I(S)
        GROUP BY S        -- group on the characters
        )A
'
LANGUAGE SQL

Usage and Test Run
SELECT S, F(S)
FROM (
    VALUES
    ('AAABBC'),
    ('ACBABA'),
    ('WWW'),
    ('CODE'),
    ('PROGRAMMING')
   )I(S)

S              F
-------------- -----------------------
AAABBC         0.73333333333333333333
ACBABA         0.73333333333333333333
WWW            0.00000000000000000000
CODE           1.00000000000000000000
PROGRAMMING    0.94545454545454545455

Python 3, 66 58 Bytes
This is using the simple counting formula provided in the question, nothing too complicated. It's an anonymous lambda function, so to use it, you need to give it a name.
Saved 8 bytes(!) thanks to Sp3000.
lambda s:1-sum(x-1for x in map(s.count,s))/len(s)/~-len(s)

Usage:
>>> f=lambda s:1-sum(x-1for x in map(s.count,s))/len(s)/~-len(s)
>>> f("PROGRAMMING")
0.945454

or
>>> (lambda s:1-sum(x-1for x in map(s.count,s))/len(s)/~-len(s))("PROGRAMMING")
0.945454

Javascript, 119 bytes
Today on "Komali sucks at code golf"...
s=>eval('q=[];for(i of new Set(s))q.push((r=s.split(i).length-1)*(r-1));1-(q.reduce((z,x)=>x+z)/((l=s.length)*(l-1)))')

Test cases:

let s1= "AAABBC"
let s2 = "ACBABA"
let s3 = "WWW";
let s4 = "CODE";
let s5 = "PROGRAMMING"
let f =
s=>eval('q=[];for(i of new Set(s))q.push((r=s.split(i).length-1)*(r-1));1-(q.reduce((z,x)=>x+z)/((l=s.length)*(l-1)))')

console.log(f(s1))
console.log(f(s2))
console.log(f(s3))
console.log(f(s4))
console.log(f(s5))

Came across this question while doing biology homework. There has to be ways to improve this; I only spent like half an hour golfing it...

(r-1) ->~-r, ditto with l (you might just want a separate function that does n*n-1), q.reduce((z,x)=>x+z) -> eval(q.join`+`)although you probably want to makeq` a number and add to it.

APL, 39 36 bytes
{n←{≢⍵}⌸⍵⋄N←≢⍵⋄1-(N-⍨N×N)÷⍨+/n-⍨n×n}

This creates an unnamed monad.
{
  n ← {≢⍵}⌸⍵               ⍝ Number of occurrences of each letter
  N ← ≢⍵                   ⍝ Number of characters in the input
  1-(N-⍨N×N)÷⍨+/n-⍨n×n     ⍝ Return 1 - sum((n*n-n)/(N*N-N))
}

You can try it online!

Python 3, 56
lambda s:sum(a!=b for a in s for b in s)/len(s)/~-len(s)

Counts the pairs of unequal elements, then divides by the number of such pairs.

Pyth, 13 bytes
csnM*zz*lztlz

Pretty much a literal translation of @feersum's solution.

CJam, 25 bytes
l$_e`0f=_:(.*:+\,_(*d/1\-

Try it online
Fairly direct implementation of the formula in the question.
Explanation:
l     Get input.
$     Sort it.
_     Copy for evaluation of denominator towards the end.
e`    Run-length encoding of string.
0f=   Map letter/length pairs from RLE to only length.
      We now have a list of letter counts.
_     Copy list.
:(    Map with decrement operator. Copy now contains letter counts minus 1.
.*    Vectorized multiply. Results in list of n*(n-1) for each letter.
:+    Sum vector. This is the numerator.
\     Bring copy of input string to top.
,     Calculate length.
_(    Copy and decrement.
*     Multiply. This is the denominator, n*(n-1) for the entire string.
d     Convert to double, otherwise we would get integer division.
/     Divide.
1\-   Calculate one minus result of division to get final result.

JavaScript, 105 bytes
f=(r,f=[],n=0,a=0)=>{for(k in [...r].map(k=>f[k]=(f[k]||0)+ ++n/n),f)a+=f[k]*(f[k]-1);return 1-a/(n*n-n)}

Welcome to Code Golf! I don't think you need the f=, so this can be two bytes shorter.

Well done; beat me! I believe you can omit the initial braces and return if you put the whole thing in an eval. Also you can probably put the definitions for a and n outside the arguments if you do a=n=0;for(/*...*/. Regardless, very nice answer!

K (ngn/k), 30 bytes
{1-+//((x=\:x)-=l)%(l-1)*l:#x}

33 bytes if you want it to be faster:
{1-(+/j x)%(j:{x*x-1})[+/x]}@#'=:

This is the part where not having combinators hurt k's expressiveness. Also the problem statement is wrong: the equation corresponds to taking elements without replacement.
Try it online!

JavaScript (Node.js), 81 bytes
s=>s.map(t=>s[t]=-~s[t])&&s.map(x=>(n++,a=s[x],s[x]=0,q+=a--*a),n=q=0)&&1-q/n--/n

Try it online!
Magic
The first part defines letters as keys of s by abusing that the default key is undefined, and -~undefined = 1. Then, we iteratively delete the dictionary entries after using them (the first time we encounter them) while incrementing n to count the length. Finally, we compute 1-q/n--/n.

Nice! Glad to see this golfed down...

J, 37 bytes
(1-([:+/]*<:)%+/*[:<:+/)([:+/"1~.=/])

but I believe it can be still shortened.
Example
(1-([:+/]*<:)%+/*[:<:+/)([:+/"1~.=/]) 'AAABBC'

This is just a tacit version of the following function:
   fun =: 3 : 0
a1=.+/"1 (~.y)=/y
N=.(+/a1)*(<:+/a1)
n=.a1*a1-1
1-(+/n)%N
)

After some extra golfing and making it a proper function: (1-(%&([:+/]*<:)+/)@(+/"1@=)) gives 29 bytes. 27 if we don't count the braces surrounding the function (1-(%&([:+/]*<:)+/)@(+/"1@=)) as it is common here. Notes: =y is exactly (~.=/])y and the compose conjuction (x u&v y = (v x) u (v y)) was very helpful too.

Thanks for the suggestions! I am still learning to write tacit expressions myself. For now, I use 13 : 0 to generate tacit definitions part by part and combine.

C,89
Score is for the function f only and excludes unnecessary whitespace, which is only included for clarity. the main function is only for testing.
i,c,n;
float f(char*v){
  n=strlen(v);
  for(i=n*n;i--;)c+=v[i%n]!=v[i/n];
  return 1.0*c/(n*n-n);
}

main(int C,char**V){
  printf("%f",f(V[1]));
}

It simply compares every character with every other character, then divides by the total number of comparisons.

at return 1.0, couldn't you golf the 0 ?

CJam, 23 bytes
1r$e`{0=,~}%_:+\,,:+d/-

Byte-wise, this is a very minor improvement over @RetoKoradi's answer, but it uses a neat trick:
The sum of the first n non-negative integers equals n(n - 1)/2, which we can use to calculate the numerator and denominator, both divided by 2, of the fraction in the question's formula.
Try it online in the CJam interpreter.
How it works
 r$                     e# Read a token from STDIN and sort it.
   e`                   e# Perform run-length encoding.
     {    }%            e# For each [length character] pair:
      0=                e#   Retrieve the length of the run (L).
        ,~              e#   Push 0 1 2 ... L-1.
                        e# Collect all results in an array.
            _:+         e# Push the sum of the entries of a copy.
               \,       e# Push the length of the array (L).
                 ,:+    e# Push 0 + 1 + 2 + ... + L-1 = L(L-1)/2.
                    d/  e# Cast to Double and divide.
1                     - e# Subtract the result from 1.

Haskell, 83 bytes
I know I'm late, found this, had forgotten to post. Kinda inelegant with Haskell requiring me to convert integers to numbers that you can divide by each other.
s z=(l(filter id p)-l z)/(l p-l z) where p=[c==d|c<-z,d<-z]
l=fromIntegral.length

APL, 26 bytes
{1-+/÷/{⍵×⍵-1}({⍴⍵}⌸⍵),≢⍵}

Explanation:

≢⍵: get the length of the first dimension of ⍵. Given that ⍵ is supposed to be a string, this means the length of the string.
{⍴⍵}⌸⍵: for each unique element in ⍵, get the lengths of each dimension of the list of occurrences. This gives the amount of times an item occurs for each item, as a 1×≢⍵ matrix.
,: concatenate the two along the horizontal axis. Since ≢⍵ is a scalar, and the other value is a column, we get a 2×≢⍵ matrix where the first column has the amount of times an item occurs for each item, and the second column has the total amount of items.
{⍵×⍵-1}: for each cell in the matrix, calculate N(N-1).
÷/: reduce rows by division. This divides the value for each item by the value for the total.
+/: sum the result for each row.
1-: subtract it from 1

Excel, 67 bytes
=LET(n,COUNTA(A:A),c,COUNTIF(A:A,UNIQUE(A:A)),1-SUM(c^2-c)/(n^2-n))

Input is a list of characters in the column A. One character per cell. Output is wherever the formula is which can be anywhere except in column A.
The LET() function allows you to define variables that can be referenced later and it saves most of the bytes here. The arguments are in pairs of variable,value except for the last argument which is not in a pair and is instead the output.

n,COUNTA(A:A) stores the count of how many non-blank cells there are in column A.
c,COUNTIF(A:A,UNIQUE(A:A)) creates an array of all the unique items from column A and then counts how many times each of those unique values appear. Technically, the UNIQUE() array will include a 0 at the end (presuming there are blank cells in A:A) but COUNTIF() will return 0 for it's count so that doesn't impact the calculations.
1-SUM(c^2-c)/(n^2-n) is the final output. Except for turning a(a-1) into a^2-a to save a byte, then is a straightforward implementation of the formula. The denominator could have also been /n/(n-1) for the same byte count but I chose the more aesthetically pleasing option.

=LET(n,ROWS(A1#),c,COUNTIF(A1#,UNIQUE(A1#)),1-SUM(c^2-c)/(n^2-n)) (or =LET(a,A1#,...) ) lets you drop two bytes if you specify that input must be of the form of a vertically aligned array of chars (ie [A1]=={"a";"b";"a";"a";"b";"c"})

TI-Basic, 75 bytes
seq(inString(Ans,sub(Ans,I,1)),I,1,length(Ans→A
SortA(ʟA
augment({0},1 and ΔList(ʟA
seq(sum(cumSum(Ans)=I),I,0,sum(Ans
1-sum(Ans²-Ans)/(sum(Ans)²-sum(Ans

Takes input in Ans as a string. Output is stored in Ans and is displayed.

Octave, 31 bytes
A port of xnor's Python answer.
@(s)nnz(s!=s')/(l=nnz(s))/(l-1)

Try it online!

K (ngn/k), 24 23 bytes
{1-/%/{x*x-1}(#'=x;#x)}

Try it online!
An adaption of @marinus' APL answer.

(#'=x;#x) create a two item list containing: a dictionary mapping each distinct character to the number of times it appears in the input; and the length of the input string
{x*x-1} multiply each value in the above list by itself minus one
%/ divide the (adjusted) counts of characters by the (adjusted) length of the input
1-/ use a minus-reduce, seeded with 1, subtracting each of the above to (implicitly) return the metric

JavaScript, 100 bytes
a=>(n=a.length,1-[...new Set(a)].map(b=>((c=a.split(b).length-1)-1)*c).reduce((a,b)=>a+b)/(n*(n-1)))

Welcome to Code Golf, and nice first answer! Glad to see the eval was able to be omitted with this strategy!

PHP 4 (72 chars)
Given $argv[1] as a command line argument :
foreach(count_chars($argv[1])as$c)@$r-=$c*$c+$g-$g+=$c;echo$r/$g/--$g+1;

Try it Online

JavaScript, 96 bytes
a=>eval('h=0,c=0,o=[];for(i of a)o[i]=o[i]+1||1,c++;for(i in o)h+=(v=o[i])*(v-1);1-h/(c*(c-1))')

Posted this as a seperate answer since it's not an update to my older one.

Pyt, 16 bytes
ĐĐỤ⇹ɔ⁻△Ʃ⇹Ł⁻△ᵮ/⁻~

Try it online!
Takes a list of characters
ĐĐ                    implicit input; Đuplicates on the stack twice
  Ụ                   get Ụnique elements
   ⇹ɔ                 get ɔount of each unique element in original list
     ⁻△               decrement count and get the corresponding triangular number n*(n-1)
       Ʃ              sum the triangular numbers
        ⇹Ł            get Łength of original list
          ⁻△          decrement and get triangular number
            ᵮ/        divide (cast to ᵮloat first due to bug in division coding)
              ⁻~      subtract one and negate (equivalent to subtracting from one)
                      implicit print


text:
Square from Digits with Largest Sum
You should write a program or function which receives a list of digits as input and outputs or returns the largest sum achievable by putting these digits in a square.
Input will always contain a square number of digits. An example square arrangement for the input 9 1 2 3 4 5 6 7 7 could be
677
943
125

The sum is calculated as the sum of all rows and columns. For the above arrangement the sum would be 677 + 943 + 125 + 691 + 742 + 735 = 3913. Note that this is not the maximal sum so this isn't the expected output.
Input

A list with length n^2 (n>=1) containing non-zero digits (1-9).

Output

An integer, the largest sum achievable with the input digits put in a square.

Examples
Example format is input => output.
5 => 10

1 2 3 4 => 137

5 8 6 8 => 324

9 1 2 3 4 5 6 7 7 => 4588

2 4 9 7 3 4 2 1 3 => 3823

8 2 9 4 8 1 9 3 4 6 3 8 1 5 7 1 => 68423

5 4 3 6 9 2 6 8 8 1 6 8 5 2 8 4 2 4 5 7 3 7 6 6 7 => 836445

This is code golf so the shortest entry wins.

Just to double check, does the input have to be space-separated digits exactly or is an unambiguous list format okay?

@Sp3000 Any simple unambiguous list format is okay including the list format of your chosen language.

Pyth, 15 bytes
s*VSsM^^LTUQ2SQ

Demonstration. Test harness.
Note: Input in any python sequence format, such as a,b,c, or [a, b, c]. Fails on a.
This will be an explanation for the example input 5,8,6,8.
^LTUQ: This is a list of powers of 10, out to the length of Q. [1, 10, 100, 1000].
^ ... 2: Then, we take pairs of powers of 10. [[1, 1], [1, 10], ....
sM: Then, we sum those pairs. [2, 11, 101, ... Each number repesents the value of a grid location. The value of the bottom right corner is 2, because the digit placed there is in the ones place of the two numbers it is in. Note that 16 values were generated, even though we only need 4. This will be handled shortly.
S: Sort the value in increasing order. [2, 11, 11, 20, 101, .... Note that the only values which are relevant for this input are the first 4, because this square will not have hundreds or thousands places.
SQ: Sort the input in ascending order. [5, 6, 8, 8]
*V: Vectorized multiplication over the two lists. Pyth's vectorized multiplication truncates the longer input, so this performs [5*2, 6*11, 8*11, 8*20], equivalent to filling in the grid, smallest to largest, bottom right to top left.
s: Sum the results, 324. Printing is implicit.

CJam, 23 bytes
q~$_,mQ,A\f#2m*::+$.*:+

Try it online. Generates the weights for each cell and  assigns the highest digits to the highest weights.
An alternative 23:
q~$_,mQ_,A\f#*_$.+$.*:+

CJam, 25 bytes
q~_e!\,mqf/{_z+Afb:+}%$W=

Pretty straight forward approach. Generate all combinations, get the sum, print largest.
Try it online here

Vyxal G, 8 bytes
Ṗƛ²:∩J⌊∑

Try it Online!
Brute force, so pretty slow.
Ṗƛ²:∩J⌊∑
Ṗ          # get all permutations
 ƛ         # map over them:
  ²        #  format as a square (returns a list of strings)
   :∩J     #  append the transpose to itself
      ⌊     #  convert each string to an integer
       ∑   #  sum
           # G flag gets the maximum

Husk, 16 bytes
▲moS(ṁd+)TSCo√LP

Try it online!
Husk, 16 bytes
Σz*O¹OmΣπ2↑:1İ⁰L

Try it online!
same idea as isaacg's answer.
Somehow both of these are still 1 byte more than Pyth.

Japt -x, 13 bytes
Tried a few different approaches with permutations and partitions but, in the end, an adaptation of isaacg's solution ended up being the shortest.
ñ í*¡ApYÃï+ ñ

Try it or run all test cases
ñ í*¡ApYÃï+ ñ     :Implicit input of array U
ñ                 :Sort
  í               :Interleave with
   *              :And reduce each pair my multiplication
    ¡             :  Map each 0-based index Y in U
     A            :    10
      pY          :    Raised to the power of Y
        Ã         :  End map
         ï        :  Cartesian product with itself
          +       :  Reduce each pair by addition
            ñ     :  Sort
                  :Implicit output of sum of resulting array


text:
Simple single-player board game, expected score distribution
This is the first problem I've posted here; please post criticisms in comments.
Summary
A game board consists of a starting space, an ending space, and between them are N spaces, each with an instruction. You begin on the starting space with 0 points to your credit. Flip a coin or roll a die to choose the number 1 or 2. Move forward that many spaces. Now look at the instruction on the space you landed on. The possible instructions consist of "Do nothing", "Score x points", and "Move forward y spaces and obey the instruction there". x and y are positive. After obeying the instruction, go back to the coin flip. When you land on or pass the ending square, the game is over.
Given a description of a game board (number of squares, instruction on each space) your code should calculate the probability distribution of possible ending scores. It's irrelevant how many turns are taken before the end.
Input

An unambiguous representation (in whatever format you desire, though numbers should be human-readable) of the instruction on each space. Numbers should be human-readable.

Output

A list of pairs of each possible score and the probability of obtaining that score (either an exact fraction or a real number accurate to at least four decimal places). Can be returned or output. It's optional to include scores that have 0 probability of occurring.

Scoring the entries

They must be correct to be considered; wrong answers don't count.
Code size. If you golf it please also post an ungolfed version; if you use a golfing language please post a good explanation.

Examples
Easy

Input
3

1
F2
1

Output
0 0.5    // rolled a 2 on first turn, game over
1 0.25   // rolled a 1 then a 1
2 0.25   // rolled a 1 then a 2

Complex

Input
16

2
1
0
5
10
F3
5
15
1
0
3
F3
5
0
0
5

Output
7   0.0234375
8   0.0078125
9   0.01171875
10  0.03515625
11  0.01171875
12  0.048828125
13  0.015625
14  0.015625
15  0.0732421875
16  0.0322265625
17  0.06005859375
18  0.015625
19  0.01171875
20  0.087890625
21  0.046875
22  0.0654296875
23  0.009765625
24  0.0107421875
25  0.064453125
26  0.0380859375
27  0.0380859375
28  0.001953125
29  0.0029296875
30  0.044677734375
31  0.023681640625
32  0.0281982421875
33  0.00390625
34  0.0029296875
35  0.015869140625
36  0.017333984375
37  0.0177001953125
38  0.0078125
39  0.0087890625
40  0.013916015625
41  0.015625
42  0.0096435546875
43  0.00390625
44  0.009033203125
45  0.0155029296875
46  0.010009765625
47  0.00567626953125
49  0.003662109375
50  0.0067138671875
51  0.003662109375
52  0.00274658203125

While not exactly the same, this is similar to the recent Snakes and Ladders.

Indeed, but there are key differences: this game is single-player, and the final score is what matters, not the number of turns. Also, all motion is forward, which makes calculating an exact solution feasible.

I tried adding together all the probabilities in your output for the "Complex" example, and I got 0.983215334, not the expected 1.0. Would you mind double-checking this, please?

@mathmandan thanks...looks like something is wrong with my reference program! I'll get it fixed.

Stax, 56 55 bytesCP437
üZÄ^3Γ╥£X╜T∩L╖á↨→╘Oïë╢Δ╥∙Eü╦5├jC╩XpN◘╘♥«╟╝☻y╞╘wé↔Ioÿ≈⌐─

Run and debug online!
Warning: Takes a long time (around 5 minutes in my box) to run the large example.
Credits to the almighty rubber duck for -1 byte.
Input is a list of numbers. Scoring x points is represented by -x, and Move y steps forward and follow the instruction there is represented by y. So for example the small test case will be represented as [-1,2,-1].
Outputs in rational number, the output for the large case is like this:
7 3/128
8 1/128
9 3/256
10 9/256
11 3/256
12 25/512
13 1/64
14 1/64
15 75/1024
16 33/1024
17 123/2048
18 1/64
19 3/256
20 45/512
21 3/64
22 67/1024
23 5/512
24 11/1024
25 33/512
26 39/1024
27 39/1024
28 1/512
29 3/1024
30 183/4096
31 97/4096
32 231/8192
33 1/256
34 3/1024
35 65/4096
36 71/4096
37 145/8192
38 1/128
39 9/1024
40 57/4096
41 1/64
42 79/8192
43 1/256
44 37/4096
45 127/8192
46 41/4096
47 93/16384
49 15/4096
50 55/8192
51 15/4096
52 45/16384

Alternative version
Calculates the probability recursively instead of enumerating every possibility. Much faster. Not really golfed.
00\sn+~]]01\]]+Yd;%{;%=zi^]?i]+ys@iXd{{dx2<;x|i-v@1<+!C_E2u*s;x@0|m-s\mm:f;i({i+|i=!Ci2+mys@{{B;x@0|m-+rm+F{o{h}/{hh0_{H+F\m]ys+YdFUUv\ys@:fo{h}/mhh0_{H+F\J
Try and debug online!
The two different algorithms give the same result.
Explanation
Uses the unpacked version to explain. The size of the game board is stored in register x. The current position on the board is stored in register y. There is an extra flag (boolean) denoted bFlip that is stored on the stack, used to indicate the type of last instruction.
The complete unpacked version is 66 bytes.
X|2{v:Bx)0Y1~s{^,*y+Ycx>{d1~}{v;@c1<c~{-}{y+Yd}?}?F,dmo|RmNx|2u*+J

I will explain it part by part.
X|2{v:Bx)0Y1~s{     F,dm
X|2                        `2^x`
   {v                  m    For `[0..2^x-1]` do the following
     :Bx)                   Binary representation of the current loop index
                            Padded with zeros to make the length `l`.
                            Each binary represents a sequence of coin flip outcomes
         0Y1~s              Initialize `y` and current score to `0`, and `bFlip` to true
              {     F       Play the game as indicated by the sequence of coin flip outcomes
                     ,d     Clean up: remove `bFlip` from the stack.

The block that plays the game:
{^,*y+Ycx>{d1~}{v;@c1<c~{-}{y+Yd}?}?F
{                                   F    The loop as stated above
 ^                                       Increment current flip result
                                         Map the original [0,1] to [1,2], denote this as `n`.
  ,*                                     If last instruction is of the type `Score k points` (`k` may be `0`)
    y+Y                                      Move forward `n` steps and save the new current position to register `y`.
       cx>{   }{                  }?     If already moved past the end
           d1~                               Mark this instruction as `Score 0 points` (or `Do nothing`)
                                         Else
                v;@                          Get current instruction
                   c1<c~                     Get the type of current instruction and remember it
                        { }{    }?           If the current instruction is `Score k points`
                         -                       Score `k` points
                                             Else
                            y+Yd                 Move forward as the instruction indicates

After executing this, we have a list with 2^x elements containing the scores of all possible coin flips, with equal probabilities. The rest of the program is just converting them to the output.
o|RmNx|2u*+J
o|R             Convert to a list of pairs of [element, count of appearance]
   m            Map the array elements with the rest of the program, output the results on separate lines
    Nx|2u*+     Divide the count of appearance by `2^x` to get probability
           J    Join the two elements with a space

Perl 5, -a0 111 108 bytes
Input format: Give the instructions separated by white-space (newline works) on STDIN including the starting cell represented by 0. The jump is indicated by an F after the number. So the example input becomes:
0
1
2F
1

With correct output
0 0.5
1 0.25
2 0.25

#!/usr/bin/perl -a0
@1=1;$n++,map{$i=0;for$a(@$n){${$n+$_>@F?z:$n+$_}[$i+++$']+=$a/2}}/F/?($`)x2:(/|/,2)for@F;say$z++," $_"for@z

Try it online!


text:
My Squiggly Lamp
While moving, I broke my lamp. Now, I need a new one. It's your job to make me a lamp! I'm not sure what size I want, though I know I want a squiggly one.
Your program/function must take in a number input, and print out a lamp with that many squiggles/bumps.
Examples:
Input:2
Output:

/--\
 ()
 ()
/__\

Input:3
Output:

/--\
 ()
 ()
 ()
/__\

Input:5
Output:

/--\
 ()
 ()
 ()
 ()
 ()
/__\

Rules:

0 & negative numbers don't matter
To give the lamps (an this challenge) more of a variety, you must change the lamp shade.

They must be 4 characters wide and 1 character high.
They can be in any shape, including non-lamp-shade shapes.
They must not contain whitespace.
The base must stay the same.

You must show an example input & output with your lamp shade.
Shortest code wins!

But it doesn't squiggle at all!. Would have loved if inputs > 5 made it squiggle.

@Optimizer I think "bumpy" would be a better word for it, but "squiggly" sounds fun :3

Does space count as a character for lamp shade ?

@Optimizer No, forgot to add that in.

Wait do I have to change the shade per input, or just make it different from the input?

@Maltysen The shade must be different from the examples provided, and must stay the same between inputs.

I downvoted. I think this is a boring ASCII art. There's a repeated section in the middle and no overlap between the parts, which are also too short to compress. It just has form ABBB..BBBC. The requirement to change a section just means people will use a short built-in string.

You can all stop downvoting already! I think OP got the message.

@xnor I feel sorry for the poor guy. This is probably one of the most downvoted questions ever :/ http://i.stack.imgur.com/T4A7X.jpg

@BetaDecay ;__;

Not voted in any way myself, but given the similarity with Draw an ASCII Lightning Bolt, I can understand the downvoters. Some little twist like having larger base for higher lamp, or having a repeated decoration only on each nth squiggle would made it a little bit different.

Pyth - 16 bytes
Uses quotes for the shade since N is preinitialized to that.
*N4VQ+d`();"/__\

Try it online here.
* 4            String repetition 4x, implicit print
 N             Preinitialized to Quote
VQ             For N in range(Q)
 +             String concat
  d            Space
   `()         Repr of empty tuple
;              Close for loop
"/__\          Implicitly print string, implicit close quote

Sample for 5:
""""
 ()
 ()
 ()
 ()
 ()
/__\

Snowman 0.2.0, 42 chars
)vg10sB]"[--]
"sP:" ()
"sP;bR"/__"sP92wRsP

Sample run:
llama@llama:...Code/snowman/ppcg53483lamp$ snowman lamp.snowman
5
[--]
 ()
 ()
 ()
 ()
 ()
/__\

So I only noticed that I forgot to implement the ability to escape backslashes within strings when I solved this challenge. That's definitely going to be a thing in the next version, but for now, here's what I did to print the final line:
"/__"sP92wRsP

92 is the ASCII code for a backslash, wR wraps it in an array, and I can now print it with sP because "strings" in Snowman are actually just arrays of numbers.

Do you want to build a snow lamp?

><>, 43 41 38 bytes
"\__/"aiv
"&-1v!?:<&a" ()
~"!_\
?!;o>l

Input via a code point, e.g. space is 32. This uses part of the program's own code as the lampshade, resulting in something that looks like a satellite dish:
~\_!
 ()
 ()
 ()
 ()
 ()
/__\

(Suggestion thanks to @randomra)
For three more bytes, we can change the third line to add a bit more customisation:
"\__/"aiv
"&-1v!?:<&a" ()
__\"\~"/
?!;o>l

This produces one of those lamps which shoot light upwards, for lack of a better way of putting it:
\__/
 ()
 ()
 ()
 ()
 ()
/__\

R, 54 52 46 bytes
cat("RRRR",rep(" ()",scan()),"/__\\",sep="\n")

In this version, input and output are almost mixed together :
{in/out}PUT :
> cat("RRRR",rep(" ()",scan()),"/__\\",sep="\n")
1: 4
2:
Read 1 item
RRRR
 ()
 ()
 ()
 ()
/__\

EDIT 1 : -2 bytes thanks to @manatwork comment.
EDIT 2 : -6 bytes. Full credit goes to @manatwork again

Changes nothing but the look: " /_\\" should be "/__\\". BTW, is that \r necessary?

@manatwork It did change the shape of the lamp's foot, making it more stable + your remark about \r saved me two bytes ! Should have re-read my code ! Thanks !

Hmm… Weird tool. Can't make it to work non-interactively. Anyway, cat("RRRR",rep(" ()",scan()),"/__\\",sep="\n") seems to work.

@manatwork : well... I've never thought that this could work ! It's indeed a nice solution. R is full of surprises !

Bonjour Frédéric, if you're still active on PPCG you can save 5 bytes

Straw, 26 bytes (non-competing)
<#~('--'
)>( ()
)-*>(/__\)>

Use '--' as lamp shade, take input in unary now in decimal

How does this work?

@BetaDecay *therefore noncompeting

CJam, 18 bytes
"/__\
"" ()
"ri*1$

Sample run for input 5:
/__\
 ()
 ()
 ()
 ()
 ()
/__\

Try it online here

JavaScript ES6, 34 bytes
i=>`|==|
${` ()
`.repeat(i)}/__\\`

The newlines are significant
Example with input of 5:
|==|
 ()
 ()
 ()
 ()
 ()
/__\

sed, 28 bytes
s#.# ()\n#g
s#^\|$#/__\\\n#g

Takes input in unary. The shade is the obvious selection (same as the base).
Test run
$ echo -n 111 | sed -f lamp.sed
/__\
 ()
 ()
 ()
/__\

05AB1E, 17 15 13 11 bytes
„ (и„/_.ø)˜∞

-2 bytes (17 → 15) thanks to @EriktheOutgolfer.
-2 byte (13 → 11) after being inspired by @dzaima's Canvas answer.
Cap is the same as the base (/__\).
Explanation:
„ (            # Literal string " ("
   и           # Repeat " (" the input amount of times
               #  i.e. " (" and 3 → [' (',' (',' (']
    „/_        # Literal string "/_"
       .ø      # Surround the list of " (" with "/_" on both ends
               #  i.e. [' (',' (',' ('] → ['/_',[' (',' (',' (',' ('],'/_']
         ˜     # Flatten this list
               #  i.e. ['/_',[' (',' (',' ('],'/_'] → ['/_',' (',' (',' (','/_']
          ∞    # Mirror each item
               #  i.e. ['/_',' (',' (',' (','/_'] → ['/__\',' () ',' () ',' () ','/__\']
               # And output the list new-line delimited (implicitly due to the mirror)

Old 13 bytes answer:
„/_D„ (Iиs)˜∞

Try it online.

1+, 114 bytes
11+""*+"*";";";;1.1##(A|11+""""**+;)"""*"**;""*""*+*";1+;"\"1+/<1+#(A)11+"*(|1+"1+")1+*+;1()"*"1+*++";;1()*"1+*+;

You all! Stop complaining about the length, this is the best I could do! Go blame Parcly Taxel for designing such a bowly language!
Shade is $$$$.

Throwing shade I see

@Razetime What do you mean

Python 2, 36 bytes
print"-"*4+"\n ()"*input()+"\n/__\\"

For input 4:
----
 ()
 ()
 ()
 ()
/__\

Note that for Python that any lamp shade using pipes is a byte less.
-1 bytes thanks to @Alex!

I think if you change the lampshade to a single character and multiply it by 4 you can save one byte: print"-"*4+"\n ()"*input()+"\n/__\\"

jq: 30 characters
(29 characters code + 1 character command line option.)
8888,(range(.)|" ()"),"/__\\"

Sample run:
bash-4.3$ jq -r '8888,(range(.)|" ()"),"/__\\"' <<< 3
8888
 ()
 ()
 ()
/__\

On-line test (Passing -r through URL is not supported – check Raw Output yourself.)

Gema: 30 characters
*=gema\n@repeat{*;\ ()\n}/__\\

Sample run:
bash-4.3$ gema '*=gema\n@repeat{*;\ ()\n}/__\\' <<< 3
gema
 ()
 ()
 ()
/__\

C, 54 bytes
Call f() with the desired height of the lamp.
f(n){for(puts("||||");n--;puts(" ()"));puts("/__\\");}

Try it on ideone.
Example output for 5:
||||
 ()
 ()
 ()
 ()
 ()
/__\

Pyke, 15 bytes
" ()"~mQAD"/__\

Try it here!
     ~m         - 1000
" ()"           -  " ()"
       QAD      - duplicate(^) input times
          "/__\ - "/__\"

Outputs:
1000
 ()
 ()
/__\

PowerShell 5.1, 28 26 Bytes
Thanks Mazzy for 2 bytes
8008;," ()"*"$args";"/__\"

Since the shade can be any 4 characters, using a number saves a pair of quotes. The hardest part was finding a nice looking shade.
Output:
PS C:\Users\ItsMe\Desktop> .\scratch.ps1 4
8008
 ()
 ()
 ()
 ()
/__\

nice lamp shade )

try this 8008;," ()"*"$args";"/__\"

Kotlin, 36 bytes
{"|MM|\n${" ()\n".repeat(it)}/__\\"}

Try it online!

Canvas, 8 bytes
(×_¶/ｅ⟳║

Try it here!
Explanation:
(×        repeat "(" input times
  _¶/e    encase it on both sides in "_\n/"
          the 1st line is surrounded in "_" and the second ends and starts with "/"
      ⟳   rotate the string clockwise without changing characters
       ║  palindromize horizontally with 0 overlap

Whitespace, 169 bytes
[S S S N
_Push_0][T  N
T   T   _Read_STDIN_as_integer][S S S T S T T   T   S S N
_Push_92_\][S S S T S T T   T   T   T   N
_Push_95__][S N
S _Duplicate_95__][S S S T  S T T   T   T   N
_Push_47_/][N
S S N
_Create_Label_LOOP][S S S N
_Push_0][T  T   T   _Retrieve_at_address_0][S S S T N
_Push_1][T  S S T   _Subtract][S N
S _Duplicate][S S S N
_Push_0][S N
T   _Swap_top_two][T    T   S _Store_at_address_0][N
T   T   S N
_If_neg_Jump_to_Label_PRINT][S S S T    S T S N
_Push_10_newline][S S S T   S T S S T   N
_Push_41_)][S S S T S T S S S N
_Push_40_(][S S S T S S S S S N
_Push_32_space][N
S N
N
_Jump_to_Label_LOOP][N
S S S N
_Create_Label_PRINT][S S S T    S T S N
_Push_10_newline][S S S T   S S S S T   N
_Push_33_!][S N
S _Duplicate_33_!][S N
S _Duplicate_33_!][S N
S _Duplicate_33_!][N
S S T   N
_Create_Label_LOOP_2][T N
S S _Print_as_character][N
S N
T   N
_Jump_to_Label_LOOP_2]

Letters S (space), T (tab), and N (new-line) added as highlighting only.
[..._some_action] added as explanation only.
Try it online (with raw spaces, tabs and new-lines only).
Explanation in pseudo-code:
Pushes all characters in reversed order to the stack, and then prints them in a loop.
Integer i = STDIN as input
Push "\__/" to the stack
Start LOOP:
  i = i - 1
  if(i is negative):
    Go to function PRINT
  Push "\n)( " to the stack
  Go to next iteration of LOOP

function PRINT:
  Push "\n!!!!" to the stack
  Start LOOP_2:
    Print top as character to STDOUT
    Go to next iteration of LOOP_2

NOTE: i in the pseudo-code above is stored back in the heap in every iteration of LOOP, because we don't want to leave it on the stack to be printed at the end.

Excel, 31 bytes
An anonymous worksheet function that takes input as a numeric from range [A1] and outputs to the calling cell.
This lamp is musical - and will help to liven and lighten up your day.
="/\
"&REPT(" ()
",A1)&"/__\"

Output

Japt, 17 bytes
Æ` ()`Ãi¥² p"/__\

Try it online!
Output for 5 is:
====
 ()
 ()
 ()
 ()
 ()
/__\

Nice trick with the ¥.

@Shaggy Thank you! :D

MAWP, 65 61 bytes
@95W2M!;2A!!;;2W2M;[25W;84W;85W!;1M;1A]25W;95W2M!;2W1M!!;;3A;

I'm sure it can be golfed by a few more bytes when displaying characters.
Try it!

Why? :( (15 chars)

gimme 1+ answer

Ok workin' on it

...done. Almost two times as long as your program...

Vyxal j, 15 bytes
×d?(‛ ()‛/_WvøṀ

Try it Online!
Example output:
****
 ()
 ()
 ()
 ()
/__\

I kinda golfed the shade.
×d              # two asterisks
  ?(   )        # Input times...
    ‛ (         # Push the two-char ` (`
        ‛/_     # Push the two-char `/_`
           W    # Push the entire stack
            vøṀ # Ascii-art mirror each item.

Pascal, 118 characters
Strings consist of char values.
The available char values beyond the bare minimum (i. e. necessary to write Pascal language elements) are implementation-defined.
Provided that all char values present are available in your implementation, you can write:
program p(input,output);var l:integer;begin
read(l);writeLn('‥〜');for l:=1 to l do
writeLn(' ()');write('/__\')end.

Input:
4

Output (pun intended):
‥〜
 ()
 ()
 ()
 ()
/__\

This lamp grants you a wish if you rub it.

SWI-Prolog, 73 60 bytes
a(X):-write(golf),writef("%r",["\n ()",X]),write("\n/__\\").

a(5). outputs
golf
 ()
 ()
 ()
 ()
 ()
/__\

Julia, 36 bytes
n->print("|~~|\n"*" ()\n"^n*"/__\\")

This creates an unnamed function that takes an integer as input and prints to stdout.
Example:
julia> f(4)
|~~|
 ()
 ()
 ()
 ()
/__\

Java 7 11, 84 83 37 bytes
n->"i!!i\n"+" ()\n".repeat(n)+"/__\\"

Try it online. (NOTE: Java 11 isn't supported on TIO yet, so String.repeat(int) has been emulated with repeat(String,int) for the same byte-count.)
Uses i!!i as cap. ¡!!¡ looks better, but is two bytes more.
Explanation:
n->                    // Method with integer parameter and String return-type
  "i!!i\n"             //  Return the cap + new-line
  " ()\n".repeat(n)    //   appended with " ()" and a new-line `n` amount of times
  "/__\\"              //   append with "/__\"

PyMin, 24 bytes / 17 characters
»ƒ+ѿ+" ø\n"*¬+ɓ+ѿ

Output for 5:
Fizz
 ()
 ()
 ()
 ()
 ()
Buzz

Shorter version with v0.5:
21 bytes / 13 characters
»ƒƜ+" ø¶"¯+ɓƜ

The base of the lamp must be /__.

Neoscript, 28 bytes
{n|"[~~]
"+" ()
"*n+"/--\\"}

Bash + coreutils, 37 bytes
yes ' ()'|sed '1i####
'$1'{a/__\\
q}'

The newlines are necessary and counted in the bytes total. GNU sed is required.
Run:
./squiggly_lamp.sh 2

Output:
####
 ()
 ()
/__\

Ruby, 42 bytes
i=gets.to_i
puts "|--|\n#{" ()\n"*i}/__\\"

Ahead, 38 bytes
I"|MM|"Wr
~W" ()"oN<s!:-1~
@W"/__\"oN<

Try it online!
Samples
1
|MM|
 ()
/__\

2
|MM|
 ()
 ()
/__\

3
|MM|
 ()
 ()
 ()
/__\

Could you maybe provide a link to an online testing environment so one can easily run your submission?

@JonathanFrech TIO link now available

Perl 5, 24 bytes
$_=$<.'
 ()'x$_.'
/--\
'

Try it online!
Uses 1000 as the cap.

Noether, 26 bytes
"-"4*P?I(" ()"P?!i)"/__\"P

Try it online!

Befunge-93, 50 bytes
"\__/"&v
0-1_v#:<g00" ()"*25p0
*25$<>:#,_@#::::"_"

Try it online!
Example with Input 3
____
 ()
 ()
 ()
/__\

PHP, 38 bytes
/--\<?while($argn--)echo"
 ()"?>

/__\

Save to file; run as pipe with -nF or try it online.

Charcoal, 16 12 10 bytes
8Ｅ⊕Ｎ(←_/‖Ｍ

-4 bytes thanks to @ASCII-only.
-1 byte thanks to @Neil by using a Map.
Try it online (verbose) or try it online (pure).
Uses 8()8 as cap, but the 8 can be any character from Charcoal's code-page that isn't used as a command/operator.
Explanation:
Print 8:
Print("8");
8

Print ( the input+1 amount of times downwards:
Print(Map(Incremented(InputNumber()), "("));
Ｅ⊕Ｎ(

Then after that print _/ in a left direction:
Print(:Left, "_/");
←_/

And finally mirror everything vertically:
ReflectMirror();
‖Ｍ

12?

@ASCII-only Thanks! Forgot about Print(... Time(...));, and smart way of using Move(:DownLeft); so regular Prints instead of MultiPrints can be used and the space at " (" can be saved at the same time.

You can save a byte here using Map too, although you'll need to rewrite the way you print the {8 so that you don't have to explicitly move to the next line.

@Neil I've found a few 12-byte alternatives with Map, but not 11 yet. Alternative 1; Alternative 2.

Alternative 2 is closer, but you can print those two characters in 3 bytes and still end up with the cursor in the correct place.

@Neil Still not sure how to do {8 in 3 bytes while moving the cursor at the same time, but I've been able to golf 2 bytes instead of 1 by using 8( instead of {8 as lamp shade. Still curious how to do the {8 in 3 bytes through. :)

Print("{"); Print(:Down, "8");

@Neil Ah, of course! So simple now that I see it..

Brain-Flak, 164 bytes
({}<((((((((((()()){}()){})()){}()){}())){}()))[[]]()){({}<>)<>}<>>()){({}[()]<(((((((()()){}()){}){}){}())[()])[(()()()()){}])((()()()()()){})>)}(((({}{}{}{}{}))))

Try it online!
Output for 5:
{{{{
 ()
 ()
 ()
 ()
 ()
/__\