text:
Stacking blocks
Given an input of a list of blocks to drop at certain points, output the height
of the resulting "tower."
The best way to explain this challenge is by example. The input will be a list
of 2n integers representing n blocks. The first integer is the block's x
position, 0-indexed, and the second is how wide the block is. For example, an
input of 2 4 represents the block (with x coordinates labeled below):
  ####
0123456789

Now, let's say the input is 2 4 4 6. That is, one block at x=2 with a width
of 4, and one at x=4 with a width of 6:
    ######
  ####

Note that a.) blocks always "drop" from the very top of the tower and b.)
blocks will never "fall over" (i.e. they will always balance). So, an input of
2 4 4 6 12 1 represents:
    ######
  ####      #

Note that the final block has fallen all the way to the "ground."
Your final output should be the maximum height of the tower at each x-value up
to the largest. Hence, the input 2 4 4 6 12 1 should result in output
0011222222001:
    ######
  ####      #
0011222222001

Input may be given as either a whitespace-/comma-separated string, an array of
integers, or function/command line arguments. The block positions (x values)
will always be integers 0 or greater, the width will always be an integer 1 or
greater, and there will always be at least one block.
Output may be given as a single string separated by non-numerical characters
(ex. "0, 0, 1, ..."), a single string listing all the digits (ex.
"001..."—the maximum height is guaranteed to be 9 or less), or an array of
integers.
Since this is code-golf, the shortest code in bytes will win.
Test cases:
In                                   Out
---------------------------------------------------------
2 4 4 6 12 1                         0011222222001
0 5 9 1 6 4 2 5                      1133333222
0 5 9 1 2 5 6 4                      1122223333
0 5 2 5 6 4 9 1                      1122223334
20 1 20 1 20 1                       00000000000000000003
5 5                                  000011111
0 2 1 2 2 2 3 2 4 2 5 2 6 2 7 2 8 4  123456789999

Can we take input as an array of 2-tuples?

@ThomasKwa No, the input must be a 1-dimensional array.

CJam, 34 30 bytes
Lq~2/{eeWf%e~_2$:).*:e>f*.e>}/

Input as a CJam-style array, output as a string of digits.
Run all test cases.
Here are two variants of another idea, but it's currently 2 bytes longer:
Lq~2/{_:\3$><0+:e>)aeez.*e_.e>}/
LQ~2/{_:\3$><0+:e>)aeez.+e~.e>}/

Python 3, 89
def f(a):
 h=[]
 while a:x,w,*a=a;h[:x+w]=(h+[0]*x)[:x]+[max(h[x:x+w]+[0])+1]*w
 return h

Try it online.
The function takes and returns a list of integers.
def f(a):                       # input as list of integers
  h=[]                          # list of heights
  while a:                      # while there's input left
    x,w,*a=a;                   # pop first 2 integers as x and w

    h[:x+w]=                    # change the heights between 0 and x+w
      (h+[0]*x)[:x]+            # left of x -> unchanged but padded with zeros
      [max(h[x:x+w]+[0])+1]*w   # between x and x+w -> set to the previous max + 1

  return h                      # return the list of heights

Ruby, 88 87 bytes
f=->i{o=[]
(s,l,*i=i
r=s...s+l
o[r]=[([*o[r]]+[0]).max+1]*l
o.map! &:to_i)while i[0]
o}

Try it online.
Inspired by grc's answer, but in a different language and just slightly shorter.
Explanation:
f=->i                        # lambda with parameter i, expects array of ints
{
    o=[]                     # output
    (
        s,l,*i=i             # pop start and length
        r = s...s+l          # range is used twice, so shorten it to 1 char
        o[r] =
            [(
                    [*o[r]]  # o[r] returns nil if out of bounds, so splat it into another array
                    +[0]     # max doesn't like an empty array, so give it at least a 0
            ).max+1]*l       # repeat max+1 to fill length
        o.map! &:to_i        # replace nil values with 0
    ) while i[0]             # i[0] returns nil when i is empty, which is falsy
    o                        # return o
}

APL, 79 bytes
{⊃{o←(z←(≢⍵)⌈a←+/⍺)↑⍵⋄e←(z↑(-a)↑⍺[1]⍴1)⋄o+0⌈o-⍨e×e⌈.+e×o}/⌽(⊂⍬),↓(⌽2,0.5×≢⍵)⍴⍵}

Input as an APL Array, output as an APL array of digits.

{⊃{o←⍵↑⍨z←(≢⍵)⌈a←+/⍺⋄e←z↑(-a)↑⍺[1]⍴1⋄o+0⌈o-⍨e×e⌈.+e×o}/⌽(⊂⍬),↓⍵⍴⍨⌽2,.5×≢⍵} (My god, learn to use ⍨ right)

Please, be careful with your words... You don't seem to know the difference between ⊃ and 1↑ and because of this you give suggestions that cause the updated program to give the wrong result but I don't patronise you.

Yeah, I get like that sometimes when I see a bunch of things able to be golfed. But the other golfs should still apply, though.

They all do. And I've integrated your suggestions, hopefully with proper credits.

-- Did you? -- 0.5

I should have written "I've integrated most of your suggestions". At a certain point life took over...

Java 1.8, 351 329 bytes
Not thrilled with this first attempt - I'm sure the double looping, and all those Integer.valueOf's can be golfed some more.
interface B{static void main(String[]x){Byte b=1;int i=0,s,c,m=0,h,a=x.length,t[];for(;i<a;){s=b.valueOf(x[i++]);c=b.valueOf(x[i++]);m=m>s+c?m:s+c;}t=new int[m];for(i=0;i<a;){h=0;s=b.valueOf(x[i++]);c=b.valueOf(x[i++]);for(m=s;m<s+c;m++)if(t[m]>=h)h=t[m]+1;for(m=s;m<s+c;)t[m++]=h;}for(i=0;i<t.length;)System.out.print(t[i++]);}}

Ungolfed
interface B {
static void main(String[]x){
    int start, count, maxWidth=0, height, args=x.length, totals[];
    Byte b=1;
    for (int i=0; i<args;){
        start = b.valueOf(x[i++]);
        count = b.valueOf(x[i++]);
        maxWidth = maxWidth>start+count ? maxWidth : start+count;
    }
    totals=new int[maxWidth];
    for (int i=0; i<args;){
        height=0;
        start = b.valueOf(x[i++]);
        count = b.valueOf(x[i++]);
        for (int j = start; j<start+count; j++) {
            if (totals[j]>=height) {
                height=totals[j]+1;
            }
        }
        for (int j = start; j<start+count; j++) {
            totals[j] = height;
        }
    }
    for (int i=0;i<totals.length; i++){
        System.out.print(totals[i]);
    }
}
}


text:
Implement an encoder for RFC 1924 IPv6 Addresses
Introduction
Everyone should know IPv6 by now. IPv6 has very long, cumbersome addresses.
In 1996 some very intelligent people created a scheme to encode them much better in RFC 1924. For reasons I cannot understand, this hasn't been widely adopted. To help adoption, it is your task to implement a converter in the language of your choice.
Because storage is very expensive, especially in source code repositories, you obviously have to use as little of it as possible.
Challenge
Write an encoder for the address format specified in RFC1924. The input is a IPv6 address in the boring standard format.
Stolen from Wikipedia this is:

An IPv6 address is represented as eight groups of four hexadecimal digits, each group representing 16 bits (two octets). The groups are separated by colons (:). An example of an IPv6 address is:

2001:0db8:85a3:0000:0000:8a2e:0370:7334

The hexadecimal digits are case-insensitive, but IETF recommendations suggest the use of lower case letters. The full representation of eight 4-digit groups may be simplified by several techniques, eliminating parts of the representation.

Leading zeroes

Leading zeroes in a group may be omitted. Thus, the example address may be written as:

2001:db8:85a3:0:0:8a2e:370:7334

Groups of zeroes

One or more consecutive groups of zero value may be replaced with a single empty group using two consecutive colons (::). Thus, the example address can be further simplified:

2001:db8:85a3::8a2e:370:7334

The localhost (loopback) address, 0:0:0:0:0:0:0:1, and the IPv6 unspecified address, 0:0:0:0:0:0:0:0, are reduced to ::1 and ::, respectively. This two-colon replacement may only be applied once in an address, because multiple occurrences would create an ambiguous representation.

You must handle omitted zeroes in the representation correctly!
The output is a IPv6 address in the superior RFC1924 format.
As in the RFC this is:

The new standard way of writing IPv6 addresses is to treat them as a
128 bit integer, encode that in base 85 notation, then encode that
using 85 ASCII characters.
The character set to encode the 85 base85 digits, is defined to be,
in ascending order:

         '0'..'9', 'A'..'Z', 'a'..'z', '!', '#', '$', '%', '&', '(',
         ')', '*', '+', '-', ';', '<', '=', '>', '?', '@', '^', '_',
         '`', '{', '|', '}', and '~'.

The conversion process is a simple one of division, taking the
remainders at each step, and dividing the quotient again, then
reading up the page, as is done for any other base conversion.

You can use the suggested conversion algorithm in the RFC or any other you can think of. It just has to result in the correct output!
Example Input and Output
Here is the one from the RFC:
Input:

1080:0:0:0:8:800:200C:417A
or
1080::8:800:200C:417A

Output:

4)+k&C#VzJ4br>0wv%Yp

Your program can take input and return the output in any standard way. So it is ok to read from stdin and output to stdout or you can implement your code as a function that takes the input as argument and returns the output.
Winning criteria
As always standard loopholes are disallowed
This is code-golf so shortest correct code in bytes wins!
This is my first challenge, so please do notify me about any problems/ambiguities in the description.

Is inet_pton allowed?

Functions from the standard library of your language are allowed. I guess that qualifies, so yes it is allowed.

Related

Out of curiousity, is For reasons I cannot understand intended to be sarcastic or genuine?

@NotthatCharles it is intended to be sarcastic. Most people will understand why that's not widely used after seeing one address in that format and I am one of them. I also understand why IPoAC is not widely used, but I would like it to be. In general, I just think the first of April RFCs are great.

Pyth, 93 91 bytes
Ks[jkUTrG1G"!#$%&()*+-;<=>?@^_`{|}~")$from ipaddress import*;z=int(ip_address(z))$sm@Kdjz85

Second submission in Pyth!
Can't try online because $ is unsafe.
When tested against the example, produces the expected result:
$ pyth -c 'Ks[jkUTrG1G"!#$%&()*+-;<=>?@^_`{|}~")$from ipaddress import *$$z=int(ip_address(z))$sm@Kdjz85'
1080::8:800:200C:417A
4)+k&C#VzJ4br>0wv%Yp

Edits:

Saved two bytes by replacing $$ with ; and removing space before *

Explanation
First part creates the mapping string and assigns it to K:
0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~

This is done as follows:
Ks[jkUTrG1G"!#$%&()*+-;<=>?@^_`{|}~")
K                                       implicitly assign to K
 s[                                 )   the string joined from the following list
     UT                                 range [0..9]
   jk                                   joined with the empty string: 0123456789
       rG1                              capitalized version of the string G (whole alphabet)
          G                             G itself
           "!#$%&()*+-;<=>?@^_`{|}~"    all other symbols (shorter to declare than generate)

Then, the second part is two pieces of normal python amounting to 47 bytes, to convert the input ipv6 address to a number (because z is accessed later in the code, it is first implicitly assigned to any input value before running the Python code)
*from ipaddress import *$$z=int(ip_address(z))$

Then, the last part converts the resulting number to base 85 as a list and maps every value to the mapping string K:
sm@Kdjz85
     jz85  convert z to base 85
 m         map over the converted number with lambda d:
  @Kd      K[d]
s          join as a string and implicitly print

Pure Pyth, 100 bytes
Ks[jkUTrG1G"!#$%&()*+-;<=>?@^_`{|}~")IgJx=zcz\:kZ=z-z]k=z.n++<zJ]*-8lz]\0>zJ)=zimid16z65536sm@Kdjz85

You can try it here
In order to support leading/middle/trailing ::, I must insert a list of missing zeroes in the correct position in the ip once converted to a list of hex numbers, which takes up more space than the inline Python version. There's room for improvement but I doubt it can beat the other version!
63 bytes version
Doesn't support the :: notation to skip zeroes:
Ks[jkUTrG1G"!#$%&()*+-;<=>?@^_`{|}~")=zimid16cz\:65536sm@Kdjz85

You can try it here
The different part here is converting the ipv6 to a number using base conversions:
=zimid16cz\:65536
         z          read string from input and assign it to z
        c \:        split it at columns
   m                map over the split list with lambda d:
    id16            convert d from base 16 to 10
  i         65536   convert list of ints from base 65536 to 10
=z                  assign result back to z

Pip, 108 bytes
YaR"::""*:"YyR"*"":0"X7-(":"Ny)Yy^":"Fiy{W#i<4iPU0bPBi}((J,t).AZ.z."!#$%&()*+-;<=>?@^_`{|}~")@((Jb)FB16TD85)

Remains fairly competitive without an IP address class/library
Try It Online!

GCC C (functions) on x86, 240 bytes
This uses a couple of GCC specials:

128 bit integers
Byte-swapping builtin

#define U unsigned __int128
#define b(n) y[n&1]=__builtin_bswap64(y[n]);
g(U x){x?g(x/85),x%=85,putchar(x>9?x<36?x+55:x<62?x+61:"!#$%&()*+-;<=>?@^_`{|}~"[x-62]:x+48):0;}
f(char *a){long long y[3];inet_pton(10,a,&y[1]);b(2);b(1);g(*(U *)y);}

Explanation

f() is the entry point.  It takes a single char *
inet_ntop() converts full or compressed string representation of input address to the elements 1 and 2 of a 64-bit integer array
Output from inet_ntop() is in network order (big endian), but the integer is needed in host order (little endian on x86) in order to perform arithmetic required for base conversion.  Unfortunately gcc does not provide a __builtin_bswap128().  Instead the element 2 of the 64-bit integer array is bswap64()ed to the element 0 and the element 1 is bswap64()ed to itself.  Elements 0 and 1 of the array now contain the address correctly in a host order 128-bit integer.
Standard successive div/mod by 85 is used to present the integer in base 85.  Because the first div/mod yields the last base 85 digit (and so on), the function g() performs this conversion recursively.  The digits are effectively pushed to the stack and then output in the correct order.
Conversion of digit value to ASCII character is a little messy.  This is probably golfable.

Test driver
Mildly ungolfed for readability.
Compile with make ipv6enc or gcc ipv6enc.c -o ipv6enc:
#define U unsigned __int128
#define b(n) y[n&1]=__builtin_bswap64(y[n]);
g(U x){
  if(x){
    g(x/85);
    x%=85;
    putchar(x>9?x<36?x+55:x<62?x+61:"!#$%&()*+-;<=>?@^_`{|}~"[x-62]:x+48):0;
  }
}
f(char *a){
  long long y[3];
  inet_pton(10,a,&y[1]);
  b(2);
  b(1);
  g(*(U *)y);
}

int main (int argc, char **argv) {

    f("1080::8:800:200C:417A");

    return 0;
}

To do - Big endian version, 165 bytes
Find a big-endian platform where I can use the gcc 128-bit integers, so I can get rid of all the byte swapping stuff.  The code should look like this, but right now this is untested on a big-endian platform:
#define U unsigned __int128
g(U x){x?g(x/85),x%=85,putchar(x>9?x<36?x+55:x<62?x+61:"!#$%&()*+-;<=>?@^_`{|}~"[x-62]:x+48):0;}
f(char *a){U y;inet_pton(10,a,&y);g(y);}

For the big-endian version, my first attempt was to run raspbian under qemu.  Unfortunately compilation yields error: ‘__int128’ is not supported for this target.  Perhaps GCC will only do int128 on 64-bit targets?  Perhaps this next?

226 bytes

Ruby -ripaddr, 109 bytes
->s{IPAddr.new(s).to_i.digits(85).reverse.map{([*0..9,*?A..?Z,*?a..?z]*""+"!#$%&()*+-;<=>?@^_`{|}~")[_1]}*""}

Attempt This Online!

source: Stack Exchange

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

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

sort: votes


text:
A Peak Experience: Quickly Visit All the Peaks
I am standing at point (0,0) in a H x W map where the altitude is represented by digits, for example:
1132
2221
1230    # H = 3, W = 4

I'd like to experience the views from every peak, which in this case are the areas with altitude 3. However, climbing up hills is not an easy task, and I am also running out of time.
Challenge
The challenge is to find the quickest path to visit all the peaks and come back.
Shortest program wins.
Input

H, W - height and width of the map (Integers) (optional, may be a list/tuple or two separate integer inputs)
The map, given as H sets of W digits (0-9), in any convenient format (2D list, string separated by newlines, etc.)

Output

Shortest time taken to visit every peak and come back to your starting point (Integer)

Conditions

The altitude of a given area is represented by a digit from 0 to 9.
The "peak" is defined by the area with the highest altitude.
The path must both begin and end at the top-left (0,0) area.
You can only move to areas adjacent to your current area, and you may not move diagonally.

It takes 3 minutes to move from one area to another if there is no change in altitude.
It takes 11 minutes to climb up; that is, moving from one area to another area that is exactly 1 unit higher.
It takes 2 minutes to climb down; that is, moving from one area to another area that is exactly 1 unit lower.
You cannot move to areas that are more than 1 unit higher or lower than where you are. (You cannot go from an area with altitude 1 to an adjacent area with altitude, say, 3)

A path to all the peaks is guaranteed
Maximum number of peaks is 15.

Samples
Input
4 5
32445
33434
21153
12343

Output
96

Explanation
You start at the top-left 3. You have to visit the two 5s that are located at (0,4) and (3,3) and come back to the 3 at (0,0) in the shortest time possible.
3  2  4->4->5
V     ^
3->3->4  3  4

2  1  1  5  3

1  2  3  4  3    # 3 + 3 + 11 + 3 + 3 + 11 = 34 minutes to visit 1st peak

3  2  4  4  5
            V
3  3  4  3  4
            V
2  1  1  5  3
         ^  V
1  2  3  4<-3    # 2 + 2 + 3 + 11 + 11 = 29 minutes to visit 2nd

3  2  4  4  5
^
3  3  4  3  4
^
2  1  1  5  3
^        V
1<-2<-3<-4  3    # 2 + 2 + 2 + 2 + 11 + 11 + 3 = 33 minutes to come back

# 34 + 29 + 33 = 96 minutes total is the answer

Input
2 7
6787778
5777679

Output
75

Welcome to PPCG, and great first question! I highly recommend changing this to a code golf question, since there has to be an objective winning criterion to score answers.

Thank you for the recommendation, I read the rules in the help center and edited the question

Perhaps your challenge would receive more hits if the title were improved.  "Mountain climbing challenge"  perhaps.

cozyconemotel, I suggested a shorter, perhaps more attractive title for your challenge.  Please feel free to change it back to the original if you wish. (There have been 245 viewings since your submission.)

@DavidC I totally agree. Thank you for the edit.

Mathematica 745 681 bytes
The basic idea is to make a weighted graph of possible moves. Weights are the time it takes to move from one place to the next.  The path with the least weight will be the quickest.
The input digits are placed in an r by c (rows by columns) rectangular array and then three distinct representations come into play: (1) an r by c grid graph, where each vertex corresponds to a cell in the array, (2) (rc) by (rc) weighted adjacency matrix that holds weights corresponding to the time it takes (2, 3, or 11 minutes) to move from one location (in the grid graph) to another, and (3) a directed, weighted adjacency graph constructed from the matrix.
The grid graph helps determine which cells (i.e. which vertices) are possibly reachable from each vertex--"possibly reachable" because a neighboring cell must not only be right, left, above or below a given cell.  It's value must also be within 1 unit of distance from the neighbor (e.g., a 3 does not connect to a  neighboring 5 or a 1).  If vertex a is not connected to vertex b then the adjacency matrix cells {a,b} and {b,a} will have a value of ∞.  Accordingly, the weighted adjacency graph will not have an edge from a to b, nor from b to a.
The weighted adjacency graph serves to determine the minimum distance (GraphDistance) and shortest route between any vertices.  The optimal path must begin with 1, touch each of the peaks, and return to 1.  In this case, "shortest route" is not necessarily the one with the fewest moves.  It is the one with the shortest overall time, measured in edge weights.

Golfed
o=Sequence;v[a_<->b_,z_]:=(m_~u~q_:={Quotient[m-1,q[[2]]]+1,1+Mod[m-1, q[[2]]]};j=z[[o@@u[a,i=Dimensions@z]]];k=z[[o@@u[b,i]]];Which[j==k,{{a,b}->3,{b,a}->3},j==k-1,{{a,b}->11,{b,a}->2},j==k+1,{{a,b}->2,{b,a}->11},2<4,{{a,b}->∞, {b, a}->∞}]);w@e_:=Module[{d,x,l,y},x=Map[ToExpression,Characters/@Drop[StringSplit@e,2],{2}];d_~l~c_:=d[[2]](c[[1]]-1)+c[[2]];g_~y~p_:=(Min[Plus@@(GraphDistance[g,#,#2]&@@@#)&/@(Partition[#,2,1]&/@({1,o@@#,1}&/@Permutations@p))]);y[WeightedAdjacencyGraph[ReplacePart[ConstantArray[∞,{t=Times@@(d=Dimensions@x),t}],Flatten[#~v~x &/@Union@Flatten[EdgeList[GridGraph@Reverse@d,#<->_]&/@Range@(Times@@d),1],1]]], l[Dimensions@x, #] & /@ Position[x, Max@x]]

Longer, more readable form
(*determines a weight (number of minutes) to go from vertex a to b and from b to a*)
weight[a_ <-> b_, dat_]:=
  Module[{cellA,cellB,dim,valA,valB,vertexToCell},

  (*Convert graph vertex index to cell location*)
  vertexToCell[m_,dimen_]:={Quotient[m-1,dim[[2]]]+1,1+Mod[m-1,dimen[[2]]]};
     dim=Dimensions[dat];
     cellA = vertexToCell[a,dim];
     cellB = vertexToCell[b,dim];
     valA=dat[[Sequence@@cellA]];
     valB=dat[[Sequence@@cellB]];
     Which[
       valA==valB,{{a,b}-> 3,{b,a}-> 3},
       valA==valB-1,{{a,b}-> 11,{b,a}-> 2},
       valA==valB+1,{{a,b}-> 2,{b,a}-> 11},
       2<4,{{a,b}->∞,{b,a}->∞}]];

(* weights[] determines the edge weights (times to get from one position to the next), makes a graph and infers the shortest distance
from vertex 1 to each peak and back.  It tries out all permutations of peaks and
selects the shortest one. Finally, it returns the length (in minutes) of the shortest trip. *)

weights[str_]:=
  Module[{d,dat,neighbors,cellToVertex,peaks,z,gd},
  dat=Map[ToExpression,Characters/@Drop[StringSplit[str],2],{2}];
  cellToVertex[dim_,cell_]:=dim[[2]] (cell[[1]]-1)+cell[[2]];
  peaks[dat_]:= cellToVertex[Dimensions[dat],#]&/@Position[dat,peak =Max[dat]];

     (* to which cells should each cell be compared? neighbors[] is a function defined within weights[]. It returns a graph, g, from which graph distances will be derived in the function gd[] *)
  neighbors[dim_]:=
  Union@Flatten[EdgeList[GridGraph[Reverse@dim],#<->_]&/@Range@(Times@@dim),1];
    d=Dimensions[dat];
    m=ReplacePart[ConstantArray[∞,{t=Times@@d,t}],
     (*substitutions=*)
    Flatten[weight[#,dat]&/@neighbors[d],1]];
    g=WeightedAdjacencyGraph[m,VertexLabels->"Name",ImageSize->Full,GraphLayout->"SpringEmbedding"];

    (* finds shortest path.  gd[] is also defined within weights[] *)
  gd[g3_,ps_]:=
    Module[{lists,pairs},
    pairs=Partition[#,2,1]&/@({1,Sequence@@#,1}&/@Permutations@ps);
    Min[Plus@@(GraphDistance[g3,#,#2]&@@@#)&/@pairs]];

  gd[g,peaks[dat]]]

Tests
weights["4 5
 32445
 33434
 21153
 12343"]

96.

weights@"2 7
 6787778
 5777679"

75.

weights@"3 4
 1132
 2221
 1230"

51.

Explanation
Think of lines 2-5 of the  following input
"4 5
 32445
 33434
 21153
 12343"

as representing an array with 4 rows and 5 columns:

where each vertex corresponds to a digit from the input array: 3 is at vertex 1, 2 is at vertex 2, 4 is at vertex 3, another 4 at vertex 4, 5 at vertex 5, etc. The grid graph is only a rough approximation of the graph we are aiming for. It is undirected. Furthermore, some of the edges will be unavailable. (Remember: we cannot move from a position to another that is more than 1 height unit above or below the current one.)  But the grid graph let's us easily find those vertices that are next to any chosen vertex.  This reduces the number of edges we need to consider, in the first example (a 4 by 5 grid), from 400 (20 * 20) to 62 (31 *2 is the number of edges in the grid graph).  In the same example, only 48 of the edges are operative;  14 are not.
The following 20 by 20 weighted adjacency matrix represents the distance between all pairs of vertices from the grid graph.
The key code which decides on which number to assign is below.
Which[
      valA==valB,{{a,b}-> 3,{b,a}-> 3},
      valA==valB-1,{{a,b}-> 11,{b,a}-> 2},
      valA==valB+1,{{a,b}-> 2,{b,a}-> 11},
      2<4,{{a,b}->∞,{b,a}->∞}]

Cell {1,2}--in one-indexing-- contains the value 2 because the move from vertex 1 to vertex 2 is downhill.
Cell {2,1} contains 11 because the move from vertex 2 to vertex 1 is uphill.
The 3's in cells {1,6} and {6,1} signify that the movement is neither up nor down.
Cell {1,1} contains ∞ because it is not connected to itself.

The following graph shows the structure underlying the above input.  The colored arrows show the optimal path from vertex 1 to the peaks (at 5 and 14) and back to 1.  Blue arrows correspond to moves at the same level (3 min); red arrows mean ascent (11 min.) and green arrows indicate descent (2 min).

The path from vertex 1 (cell {1,1} to the two peaks and back to vertex 1:
3 + 3 + 11 + 3 + 3 + 11 + 2 + 2 + 3 + 11 + 11 + 2 + 2 + 2 + 2 + 11 + 11 + 3

96

Pyth, 92 bytes
hSms@Lu.dm,bhS,@Gb+@G,hbH@G,HebG[FQ.dm,(Fb?|tsaMCb>.aJ-F@LQb1.n4@[3hT2)J*QQC.<B+]hSQd1.p.M@Q

The input format is a dict mapping coordinates to heights: {(0, 0): 3, (0, 1): 2, (0, 2): 4, …}.  This finds the fastest paths between all pairs of points using the Floyd–Warshall algorithm, then minimizes the total time of the desired cycle over all permutations of peaks.
Try it online

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


text:
Imposters at the Zoo
You want to open a new zoo. It'll be amazing. But being the cheapskate that you are, you only want to afford three-letter animals (everyone knows that an animal's cost is proportional to the length of its name). There goes your dream of making people pay to see an elephant. But suddenly you have a brilliant idea. If you just place the animals correctly in the pen, you can create the optical illusion of an elephant! Here is a top-down view of your new "elephant compound":
elk
  eel
   pig
    hog
     ant

--------  (fence)
    ^
    | viewing direction

Haha, those gullible visitors!
Yes, this is how perception works.
The Challenge
Given a non-empty word consisting only of lowercase English letters, determine if it can be formed from overlapping the following 30 three-letter animal words:
ant ape asp ass bat bee boa cat cod cow
dab dog eel elk emu fly fox gnu hog ide
jay kea kob koi olm owl pig rat ray yak

Yes, there are more than 30, but that's a nice round number.
You may optionally receive this list as input (in any reasonable list or string format, as long as it's not pre-processed). You'll probably want to do this, unless reading and processing this input list is much more expensive than hardcoding and compressing it in your language of choice. Note that even if you take the list as input you may assume that it will always be exactly this list, so if your code relies on the passed list being 30 elements long and not containing a word with z, that's fine.
Each word can be used multiple times. Animals cannot be cut off at the ends, only partially hidden by other animals. So ox is not a possible string, even though we have fox.
Output should be truthy if this is possible, and falsy otherwise.
You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument and outputting the result via STDOUT (or closest alternative), function return value or function (out) parameter.
Your code should handle any of the test cases in a few seconds.
Standard code-golf rules apply.
More Examples

Any one- or two-letter word is obviously falsy.
So is any three-letter word which is not in the above list.
Even though we have gnu and rat, gnat is falsy since there's no way to arrange them such that you only see two letters of each (we don't want to cut animals into thirds).

Some truthy examples:
pigment

    ant
  bee
 olm
pig

antioxidant

   fox
 koi  ide
ant     ant

Test Cases
Most of the test cases were taken from running a reference implementation against a dictionary. The last few "words" were generated randomly and are just there to ensure that submissions are sufficiently efficient.
Truthy:
ant
owl
bass
pride
bobcat
peafowl
elephant
hedgehogs
crocodile
antidemocrat
aspidoganoidei
biodegradability
angioelephantiasis
propreantepenultimate
acategnukeaidabeleenaspcodcoidyakwakoasshogattkjaypigkobolcodidaskearaywelkwboaxbeeuflapaspoapemaassaaspeewoglmabiemuwjadogacagnuepigjaycownbatjaemuifoxkeaeekekeagratsseeluejdoghogaolmgpigbeaeelemulasphogjaydabemukgnunueifoasdoglrayyadogpewlayroassasslgnuaspyyakkbokeaodxilopgnuasppigkobelratelkolmakob
koigdgaspslycoyakehrdabowbatdkkeapogkobelrowlyarpidepetlfoxeboaiderbeefoxbgnuapeocowgiecowlkoieeltbategspemuideatdogbeeecatgeaoccattbbeassgnasolkeaflyelkaognubeeabrratoccolmobodoglyelraywelkoxantowleedrayflypeappigogatraoyakccpiganaaspkobabjaspkointantybjbeeanolmuijaylratojaynueidflyjarayabatmmpigtfly
eolmantjkobeeaorayogaowldfoxayeassapibatmflylyraelaspsseolmbelkkaoantlmufodasgnueantaidenthyakcodoxuepigodggnuantatlcatnuuelkpemucbapeeoiahdogplkowletbatdrayarayoaelkgrayodcatgkantewkobeljaybeeyfkobtbdabadoghbatfoxtflygaspdeidogtowlkeaolmyraelfleelejayehogowlccatoxeabiemkobpigolmdkobrcidekyakabboyidep

Falsy:
a
ox
ram
bear
koala
antelope
albatross
zookeeper
salamander
caterpillar
hippopotamus
koigdgaspslycoyakehrdabowbatdkkeapogkobelrowlyarpidepetlfoxeboaiderbeefoxbgnuapeocowgiecowlkoieeltbategspemuideatdogbeezcatgeaoccattbbeassgnasolkeaflyelkaognubeeabrratoccolmobodoglyelraywelkoxantowleedrayflypeappigogatraoyakccpiganaaspkobabjaspkointantybjbeeanolmuijaylratojaynueidflyjarayabatmmpigtfly
koigdgaspslycoyakehrdabowbatdkkeapogkobelrowlyarpidepetlfoxeboaiderbeefoxbgnuapeocowgiecowlkoieeltbategspemuideatdogbeeecatgeaoccattbbeassgnasolkeaflxelkaognubeeabrratoccolmobodoglyelraywelkoxantowleedrayflypeappigogatraoyakccpiganaaspkobabjaspkointantybjbeeanolmuijaylratojaynueidflyjarayabatmmpigtfly
beyeodpgspeclxlkbkaylldnceepkocbdmymsaogsowpbawbauaioluaaagaetdoaoialeoxaagspoelegflpylptylnolnatrjabaorkdteeydloiebbptatdtfdfgoodtbkoafmounbduaffcrfelcnawmxaskgaoenaattbaobgbgabnhkesbgaaaaotafkiiieatworginaeowaehuddegooaalowaoososaksahoimkulbtoadyyelkcmkacbuostadppcuglbnmotedfgfkoleldonknemomnmoutykg

I'm still taking suggestions for a better title...

You may optionally receive this list as input - does that mean it doesn't count towards the score, whereas hard-coding it would?

@marinus Yes. So you'll probably want to take it as additional input, unless reading more than one string on input is really cumbersome in your language of choice. (I don't want to allow hardcoding + "if you do, subtract it from your score", because then you'll get people hardcoding and compressing it in, which would essentially give them a bonus to their score.)

Does "function (out) parameter" include parameters by reference?

@mınxomaτ Yes it does.

What do you have against rams?

@Luke "Yes, there are more than 30, but that's a nice round number." ;) (Specifically, I deliberately left out names for female, male and young animals like ram, ewe, doe, cub as well as lesser known animals like dzo... and yes I did include the female "cow", but that's widely used as a synonym for "cattle".)

I can't believe I missed the "round number" comment in the sandbox. Shame on you, sir! Around these parts 32 is a round number, not 30. (And it's not entirely try that you left out names for male animals - see hog).

@PeterTaylor oh, I thought hog referred to wild pigs, not male pigs. Well...

"Animal Magic"?

"Animal Ambigrams" as a title.

Japt, 51 48 45 36 33 19 bytes
Saved 9 bytes thanks to @PeterTaylor
;!UeVrE"[$& ]" S² x

Test it online!
Takes input as the string to test, followed by the list of three-letter words, delimited with |. Note: this doesn't work in the latest version of the interpreter, so please use the link instead of copy-pasting the code.
How it works
The basic idea is to take the input string and repeatedly replace any of the 30 words in it with two filler chars. I use a space as the filler char. Also, we want to replace the ant in elephant, the a   in ela   , the  nt in e   nt, etc. So what we want to do is to change the 30-word string to a regex that matches any of these combinations:
ant|ape|asp|...
Becomes:
[a ][n ][t ]|[a ][p ][e ]|[a ][s ][p ]|...

We can do this pretty easily:
;VrE"[$& ]"
          // Implicit: V = "ant|ape|asp|..."
;         // Set the vars A-J to various values. E is set to "[a-z]".
VrE       // Take V and replace each lowercase letter with:
"[$& ]"   //  "[" + the char + " ]".

However, this has the undesired effect of also matching three spaces, which has no effect on the result and thus ends the recursive replacement. We can get around this by replacing the match with two spaces instead of three:
Ue    S²  // Take U, and recursively replace matches of the regex with " ".repeat(2).

Here's a basic demonstration of how and why this works (using . in place of a space):
First match at the end:
eleant
ele..   (ant)
el..    (eel)
...     (elk)
..      (...)
true

First match at the beginning:
antmua
..mua   (ant)
...a    (emu)
..a     (...)
..      (boa)
true

First match in the middle:
cantay
c..ay   (ant)
..ay    (cat)
...     (jay)
..      (...)
true

For truthy test-cases, this leaves us with a string of all spaces. For falsy test-cases, we have some letters left in the mix. This can be translated to true/false like so:
     x   // Trim all spaces off the ends of the resulting string.
!        // Take the logical NOT of the result.
         // Empty string -> true; non-empty string -> false.

And that's about it! A bonus of this method is that even the largest test cases finish in under 5 milliseconds. (Tested here)

"This is not an easy thing to with regex alone" - what's wrong with (?!,,,)?

@PeterTaylor facepalm Thanks, that saves about 10 bytes...

@PeterTaylor I've found a much shorter method: simply replace with two spaces instead of three. Down to 19 bytes!

Another facepalm moment then?

@Neil Yep, pretty much. I'd thought about trying two spaces instead of three, but I didn't realize it would work so well until this morning when thinking through many alternate strategies.

GNU grep, 62 + 1 = 63 bytes
^(((.+)(?=.*!\3))*(...)(?=.*\4!)((.+)(?=.*\6!))*([^qvz]\B)?)+

This requires the P option. The input is expected to be the animal to be synthesized, followed by a space, followed by the list of 3-letter animals opened, closed, and delimited by exclamation marks. Example usage (assuming the program is saved as zoo):
> grep -Pf zoo
hippopotamus !ant!ape!asp!ass!bat!bee!boa!cat!cod!cow!dab!dog!eel!elk!emu!fly!fox!gnu!hog!ide!jay!kea!kob!koi!olm!owl!pig!rat!ray!yak!

For a true input, the input line is echoed back. For a false input, there is no output.
Thanks to Martin for spotting a bug and alerting me to the existence of \B for word non-boundary.

Does grep not have non-word-boundaries \B so you can get rid of the last lookahead? (If it doesn't, switching to Retina would save a few bytes. Actually I think it would save a byte anyway, because it doesn't need the P option.)

I can't test with grep right now, but does this actually handle the large falsy test cases in a few seconds? In Retina the backtracking takes quite a while.

@MartinBüttner For the last couple of falsy cases, it actually gave up and printed grep: exceeded PCRE's backtracking limit.

Using GNU something to solve this seems highly appropriate.

ES6, 122 121 119 104 bytes
I had worked out how to do this as far as ETHproduction's answer but couldn't think of how to handle the ,,,* problem, so naturally when I saw Peter Taylor's comment it all became clear. Then ETHproductions managed to find a better way to handle the problem which helpfully saves 15 bytes.
Input is the target word and an array of animal words.
(s,a)=>[...s].map(_=>s=s.replace(RegExp(a.map(a=>a.replace(/./g,"[&$&]")).join`|`),'&&'))&&!/\w/.test(s)

Edit: Saved 1 byte 3 bytes thanks to @ETHproductions.
*Except I used &s because it looks nicer in my replace.

Very nice! Would any of these things work: 1) using (`(?!&&&)(${a.map...})`) as the string, 2) removing the parentheses after doing that, 3) using eval`/(?!&&&).../` ?

@ETHproductions I made the mistake of removing the outer ()s which doesn't work; with the () it works and saves me a byte. eval also needs the ()s so it doesn't save anything further, sorry.

I think you also have an extra pair of parentheses around a.replace(...).

You can save a bunch: s=s.replace(RegExp(a.map(a=>a.replace(/./g,"[&$&]")).join`|`),'&&') Replacing with two chars instead of three removes the possibility of getting stuck replacing the same three chars over and over.

JS ES6, 77 bytes
s=>/^(((.+)(?=.*!\3))*(...)(?=.*\4!)((.+)(?=.*\6!))*([^qvz][^\b])?)+/.test(s)

(this is anonymous fn)
Input is the same as the above grep example input

If you're taking input with prompt() shouldn't you output using alert()? (Alternatively just make this a function.)

@Neil thanks, i used anon. fn


text:
Solve an 0h n0 board
0h n0 is a very simple and enjoyable game, a bit like Sudoku or minesweeper.
Game rules
(I recommend using the tutorial in the game if you can, it is very simple and useful)
The puzzle starts with an n * n board containing some fixed pieces and some empty cells, and the solver must find a way to fill the empty cells with pieces and satisfy all of the constraints imposed by the fixed pieces. Here are the piece types we will be using with the abbreviation:

# Red piece (blocks view of a blue piece)
O Blue piece
. Empty location
number Numbered blue piece (number is a one digit number >0)

All the numbered pieces must see exactly the same amount of blue pieces as the number. For example:
#1O#O
...O.

The 1 piece can see only one other blue piece.
How pieces see each other
Two blue pieces can see each other if they are in the same row or column and no red piece is between them. Example:
(S is a location that the O piece can see, X can't be seen)
   S
   S
X#SOSS
   #
   X

Each blue piece must see at least one other blue piece:
#O#

Wont work, but:
#OO

Or:
###

Do work.
Demo board solve
.1..
..1.
....
22#2

The right bottom 2 can only see above itself, so they must be blue, and the top right must be red.
.1.#
..1O
...O
22#2

Since the 1 is filled, we can surround it with red pieces.
.1##
.#1O
..#O
22#2

The top left 1 can only see in one direction now, so we can fill it in.
O1##
.#1O
..#O
22#2

Now about those last 2s. We can put 2 blue pieces over them.
O1##
.#1O
OO#O
22#2

The last one will be filled with #
O1##
##1O
OO#O
22#2

Input
Input is a multi-line string. The size will be 9x9 without trailing space. It has the following piece types:

. Empty
# Preset red, cannot be changed
number Preset number, cannot be changed

(Note that blue will not ever be in the input)
Output
Output is the same as input, with the change that empty (.) is replaced with either a red or a blue to solve the board, and numbers are replaced with blue pieces (O).
Examples
(Note that multiple solutions may be possible for each puzzle, but you only need to show one of them)
Input:
........4
...3.1...
45...2.3.
..9......
1..6#44..
....4..5.
....4.36.
2.......6
1....4...

Output:
OOO###OOO
OOOO#O#OO
OOO#OO#OO
#OOOO#O##
O#OO#OOOO
O#OOOO#OO
#OOOO#OOO
OO#O#OOOO
O#OOOO#O#

Input:
..7..#...
#...8..11
2....5...
..5...48.
...#...4.
.5...6...
...1.2...
2.....6.8
.7..#....

Output:
OOOOO####
##OOOO#OO
O#OOOO###
OOO#OOOOO
OO##O##O#
#O##OOOOO
#O#O#O#OO
OO#OOOOOO
OOO###O#O

Input:
5.3..33..
...4...23
.6.6.34..
...3#....
....5..4.
.5....3..
7.98.6#.3
.5.6..2..
..6...2..

Output:
OOOOO####
##OOOO#OO
O#OOOO###
OOO#OOOOO
OO##O##O#
#O##OOOOO
#O#O#O#OO
OO#OOOOOO
OOO###O#O

Thanks to @PeterTaylor and @apsillers for all their help in the sandbox!

I made just a very minor edit to the title because "an" sounds better if the following word begins with a vowel -- I don't expect non-native english speakers or even native speakers to bother with it, but it's grammatical.

Haskell, 224 bytes
Not fully tested, because it's so slow (at least O(n*2^n^2)).
t=1<2
x!p|p<0=0|t=mod(div x$2^p)2
l#x=[[sum$map(p&)[-1,1,l+1,-l-1]|p<-[q..q+l]]|q<-[0,l..l*l],let i&v|x!i<1=0|t=x!(i+v)+(i+v)&v]
b%v|b<1=t|t=b==v
s b|l<-length b-1=[l#x|x<-[0..2^l^2],and.map and$zipWith(zipWith(%))b(l#x)]!!0

Explanation:
Basic idea is to represent a board of Red, Blue pieces as a list of lists of 0, 1, where the list of lists is packed into a single integer for easier enumeration. All such integers for the board size are generated and converted to a form with neighbor counts. The first such board that is a valid solution of the input is returned.
-- integer x at position p with out of bounds defined to be 0 (so no bounds checking)
(!) :: (Integral b, Integral r) => r -> b -> r
x ! p | p < 0     = 0
      | otherwise = mod (div x (2^p)) 2

-- Sum of values from position p along vector v (x is implicit)
-- Note that a cartesian vector (x,y) in this representation is (l*x + y)
(&) :: (Integral a, Integral b) => b -> b -> a
p & v | x ! p == 0 = 0
      | otherwise  = x ! (p+v)  +  (p+v) & v

-- Value of board at position p (implicit x, l)
value :: Integral a => a -> a
value p = sum $ map (p&) [-1, 1, l+1, -l-1]

-- Integer to board, where l is length, x is input integer
(#) :: (Integral t, Integral a) => a -> t -> [[t]]
l # x = [[sum $ map (p&) [-1,1,l+1,-l-1] | p <- [q..q+l-1]] | q <- [0,l..l*l]]

-- Comparison operator, to see whether a solved board is a solution of the input
(%) :: (Num a, Ord a) => a -> a -> Bool
b % v | b == 0    = True
      | otherwise = b == v

-- Check one possible solution
check :: Integral a => [[a]] -> Int -> [[a]] -> Bool
check b l x = (and . (map and)) zipWith(zipWith (%)) b (l # x)

-- Solver
solve :: Integral t => [[t]] -> [[t]]
solve b = [l # x | x <- [0..2^l^2], check b l x]
  where
    l = length b

The part that could probably be most golfed is: and.map and$zipWith(zipWith(%)). Otherwise, I caught a few off-by-one errors that added length and could probably be golfed more.

Python3 1244 bytes
Very long, but optimized to crunch all the test cases (and some others) in ~0.5 seconds.
E=enumerate
from itertools import*
M=[(0,1),(0,-1),(-1,0),(1,0)]
def T(v,D,d):
 s,c=[],0
 for l,X,Y in D.pop(1):s+=[(l[0][1],X,Y)];c+=len(l[0][1]);D[0]+=[(l[1:],X,Y)]
 if c>v:return
 q=[(D[0],c,s)]
 while q:
  O,c,s=q.pop(0)
  if c==v:yield s;continue
  if[]==O:continue
  q+=[(O[1:],c,s)]
  L,X,Y=O[0]
  for i,(_,U)in E(L):
   if 0==i%2:
    for I in range(1,len(U)+1):
     if len(Q:=[j for k in L[:i]for j in k[1]]+U[:I]+(L[i+1][1]if I==len(U)and L[i+1:]else[]))+c<=v:q+=[(O[1:],c+len(Q),s+[(Q,X,Y)])]
def B(x,y,v,d):
 q=[(x,y,X,Y,[])for X,Y in M]
 while q:
  x,y,X,Y,p=q.pop(0)
  if not(V:=d.get(g:=(x+X,y+Y)))or'#'==V:yield([(a,[*b])for a,b in groupby(p,key=lambda x:d[x]!='.')],X,Y);continue
  q+=[(*g,X,Y,p+[g])]
def f(b):
 d={(x,y):v for x,r in E(b)for y,v in E(r)}
 q=[([(i,d[i])for i in d if d[i].isdigit()],d)]
 while q:
  o,d=q.pop(0)
  if[]==o:return d
  W=[]
  for(x,y),v in o:
   D={0:[],1:[]}
   for V,X,Y in B(x,y,v,d):
    if V:D[V[0][0]]+=[(V,X,Y)]
   W+=[((x,y),v,[*T(int(v),D,d)])]
  if all(i[2]for i in W):
   (x,y),v,L=W[0]
   for w in L:
    D={**d}
    for l,X,Y in w:
     for j,k in l:D[(j,k)]='O'
     if(j+X,k+Y)in D:D[(j+X,k+Y)]='#'
    for X,Y in M:
     if'.'==D.get(H:=(x+X,y+Y)):D[H]='#'
    q+=[(o[1:],D)]

Try it online!

You can add a semicolon to shorten by 1 byte like d={(x,y):v for x,r in E(b)for y,v in E(r)};q=[([(i,d[i])for i in d if d[i].isdigit()],d)]. Too long to paste the link here.

haha, I didn't expect to see new answers to any of my questions. brings back old memories before college

@JAtkin It is a wonderful challenge! I thought it deserved more attention :)

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


text:
Are there brackets in disguise?
Someone's given us a string, but all bracket-like characters have been changed into normal ones, and we don't know which, or even how many there were. All we know is that if L1,L2,L3,...,LN were different kinds of left brackets and R1,R2,R3,...,RN were different corresponding kinds of right brackets, all being distinct (2N distinct bracket characters), a string would be valid iff it is one of (+ is normal string concatenation):

L1+X+R1,L2+X+R2,...,LN+X+RN, where X is a valid string,
X+Y, where X and Y are valid strings,
Any single character that is not a bracket character.
The empty string

We know they started out with a valid string before they changed the brackets, and they didn't change them into any characters that already existed in the string. At least one pair existed for each bracket as well. Can you reconstruct which characters were originally left and right bracket pairs (find the Li and Ri following the given conditions)?
Output the pairs of characters that were brackets. For example, if (){}[] were actually bracket characters, you might output (){}[] or {}[]() or [](){}, etc. There may be multiple ways to do this for a string, you only need to return one such that there is no bracket assignment with more pairs (see examples). Note that the output string should always have an even length.
Examples:
abcc - c cannot be a bracket, since there is no other character with two occurrences, but ab can be a bracket pair, so you would output exactly ab.
fffff - any string with at most one character cannot have brackets, so you would return the empty string or output nothing.
aedbedebdcecdec - this string cannot have any brackets because there is 1 a, 2 bs, 3 cs, 4 ds, and 5 es, so no two characters occur the same number of times, which is a requirement to have brackets.
abcd -  possible assignments are ab, cd, abcd, cdab, adbc, bcad, ac, ad, bc and bd, (as well as the empty assignment, which all of them have) but you must return one of the longest assignments, so you must return abcd, cdab, adbc, or bcad.
aabbcc,abc - these both have ab, ac, and bc as valid pairs. You must return one of these pairs, doesn't matter which.
abbac - a and b have the same character count,  but they can't actually work, since one of them occurs to both the left and right of all occurrences of the other. Return nothing.
aabcdb - cd and ab are the exact two bracket pairs, so output either cdab or abcd.
abcdacbd - only one pair can be achieved at once, but ab,ac,bd,cd, and ad are all of the possible pairs you can return. No matter which pair you choose, it has an instance where a single other character is within it, which prohibits any other pairs, except in the case of ad, where the other pairs bc and cb are not possible alone either, and so can't be possible with ad.
This is code golf, so shortest code in bytes wins. Input is from STDIN if possible for your language. If it isn't possible, indicate the input method in your answer.

for input abcd, the output adbc would also be acceptable, right?

Yes, I've added it to the example.

Ruby, 373 bytes
i=gets.chomp
b=[*(i.chars.group_by{|x|x}.group_by{|x,y|y.size}.map{|x|s=x[1].size
x[1][0...s-s%2].map{|x|x[0]}*''}*'').chars.each_slice(2)]
puts [*[*b.size.downto(1).map{|n|b.combination(n).map{|t|[t*'',(h=Hash[t]
s=[]
o=1
i.each_char{|c|s.push(c)if h.keys.include?c
(o=false if s.empty?||!h[s.pop].eql?(c))if h.values.include?c}
o ?s.empty?: o)]}}.find{|x|x[0][1]}][0]][0]

This uses a golfed version of the stack parser here.
It can probably be simplified further, but I don't think my brain can handle any more.
All test cases: http://ideone.com/gcqDkK
With whitespace: http://ideone.com/pLrsHg
Ungolfed (mostly): http://ideone.com/oM5gKX


text:
Show the Top Five Comment Scores on a SE Post
A Stack Exchange script determines which five comments on questions or answers are initially seen on the main page of sites through the number of upvotes on them; the five comments with the highest number of votes are displayed. Your task is to recreate this behavior.
Write a full program or function taking input through STDIN, command-line args, or function arguments and prints or returns the top five comment scores. Input will be an array of integers representing the number of upvotes on the comments of some post. For instance, an input of
0, 2, 5, 4, 0, 1, 0

means that the first comment has no votes, the second one has two votes, the third has five, the fourth had four, etc. The order of the comment scores should remain the same in the output.
If the input contains five or fewer comment scores, then the output should contain nothing more than the ones given. If two or more comment scores are the same, the first score(s) should be displayed. You may assume that the input array will contain at least one comment score.
The numbers in the output should be easily distinguished (so 02541 for case 1 is invalid). Otherwise there are no restrictions on output format; the numbers may be separated by a space or newline, or they may be in list format, etc.
Test cases:
[0, 2, 5, 4, 0, 1, 0] -> [0, 2, 5, 4, 1]
[2, 1, 1, 5, 3, 6] -> [2, 1, 5, 3, 6]
[0, 4, 5] -> [0, 4, 5]
[1, 1, 5, 1, 1, 5] -> [1, 1, 5, 1, 5]
[0, 2, 0, 0, 0, 0, 0, 0] -> [0, 2, 0, 0, 0]
[0, 0, 0, 0, 1, 0, 0, 0, 0] -> [0, 0, 0, 0, 1]
[5, 4, 2, 1, 0, 8, 7, 4, 6, 1, 0, 7] -> [5, 8, 7, 6, 7]
[6, 3, 2, 0, 69, 22, 0, 37, 0, 2, 1, 0, 0, 0, 5, 0, 1, 2, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 2] -> [6, 69, 22, 37, 5]

The last example was taken from this Stack Overflow question.
If possible, please provide a link in your post where your submission can be run online.
This is code golf, so the shortest code in bytes wins. Good luck!

Must we retain order?

@CᴏɴᴏʀO'Bʀɪᴇɴ Yes. The order in which the integers appear should not change.

Jelly, 6 bytes
NỤḣ5Ṣị

Try it online! or verify all test cases at once.
How it works
NỤḣ5Ṣị    Main link. Input: A (list)

N         Negate (multiply by -1) all elements of A.
 Ụ        Grade the result up.
          This consists in sorting the indices of A by their negated values.
          The first n indices will correspond to the n highest vote counts,
          tie-broken by order of appearance.
  ḣ5      Discard all but the first five items.
    Ṣ     Sort those indices.
          This is to preserve the comments' natural order.
     ị    Retrieve the elements of A at those indices.

Python 2, 58 bytes
x=input()[::-1]
while x[5:]:x.remove(min(x))
print x[::-1]

Test it on Ideone.
How it works
list.remove removes the first occurrence if its argument from the specified list. By reversing the list x, we essentially achieve that it removes the last occurrence instead.
Thus, it suffices to keep removing the comment with the minimal amount of upvotes until a list of no more than five comments is reached. Afterwards, we reverse the list once more to restore the original order.

Pyth, 11 bytes
_.-_Q<SQ_5

We calculate the multiset intersection of the input (Q) with the five greatest elements in Q (in the order they appear in Q), then take the first five of those.
_ .-           Reverse of multiset difference
     _ Q       of reversed Q
     <         with all but last 5 elements of sorted Q
       S Q
       _ 5

Try it here.

<5SQ is equivalent to <SQ_5, which saves 1 byte.

Nope.

Interesting. I wonder why it's not implemented as b[:-a]... I think it even might've been that at some point.

Python 3, 76
Saved 9 bytes thanks to Kevin reminding me that I can abuse if statements in a list comp.
Saved 5 bytes thanks to DSM.
Pretty simple solution right now. Grab the top 5 scores and then parse through the list adding them to the result as we find them.
def f(x):y=sorted(x)[-5:];return[z for z in x if z in y and not y.remove(z)]

Here are my test cases if anyone wants them:
assert f([0, 2, 5, 4, 0, 1, 0]) == [0, 2, 5, 4, 1]
assert f([2, 1, 1, 5, 3, 6]) == [2, 1, 5, 3, 6]
assert f([0, 4, 5]) == [0, 4, 5]
assert f([0, 2, 0, 0, 0, 0, 0, 0]) == [0, 2, 0, 0, 0]
assert f([0, 0, 0, 0, 1, 0, 0, 0, 0]) == [0, 0, 0, 0, 1]
assert f([5, 4, 2, 1, 0, 8, 7, 4, 6, 1, 0, 7]) == [5, 8, 7, 6, 7]
assert f([6, 3, 2, 0, 69, 22, 0, 37, 0, 2, 1, 0, 0, 0, 5, 0, 1, 2, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 2]) == [6, 69, 22, 37, 5]

MATL, 16 bytes
tn4>?t_FT#S5:)S)

This uses current release (10.2.1), which is earlier than this
challenge.
Try it online!
Explanation
          % implicitly get input
t         % duplicate
n         % number of elements
4>?       % if greater than 4...
  t       % duplicate
  _       % unary minus (so that sorting will correspond to descending order)
  FT#S    % sort. Produce the indices of the sorting, not the sorted values
  5:)     % get first 5 indices
  S       % sort those indices, so that they correspond to original order in the input
  )       % index the input with those 5 indices
          % implicitly end if
          % implicitly display

JavaScript, 74 65 62 61 bytes
3 bytes off thanks @user81655. 1 byte off thanks @apsillers.
f=a=>5 in a?f(a.splice(a.lastIndexOf(Math.min(...a)),1)&&a):a

f=a=>5 in a?f(a.splice(a.lastIndexOf(Math.min(...a)),1)&&a):a

document.write('
' +
  '[0, 2, 5, 4, 0, 1, 0] -> ' + f([0, 2, 5, 4, 0, 1, 0]) + '
' +
  '[2, 1, 1, 5, 3, 6] -> ' + f([2, 1, 1, 5, 3, 6]) + '
' +
  '[0, 4, 5] -> ' + f([0, 4, 5]) + '
' +
  '[1, 1, 5, 1, 1, 5] -> ' + f([1, 1, 5, 1, 1, 5]) + '
' +
  '[0, 2, 0, 0, 0, 0, 0, 0] -> ' + f([0, 2, 0, 0, 0, 0, 0, 0]) + '
' +
  '[0, 0, 0, 0, 1, 0, 0, 0, 0] -> ' + f([0, 0, 0, 0, 1, 0, 0, 0, 0]) + '
' +
  '[5, 4, 2, 1, 0, 8, 7, 4, 6, 1, 0, 7] -> ' + f([5, 4, 2, 1, 0, 8, 7, 4, 6, 1, 0, 7]) + '
' +
  '[6, 3, 2, 0, 69, 22, 0, 37, 0, 2, 1, 0, 0, 0, 5, 0, 1, 2, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 2] -> ' + f([6, 3, 2, 0, 69, 22, 0, 37, 0, 2, 1, 0, 0, 0, 5, 0, 1, 2, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 2]) + '
' +
'
')

05AB1E, 12 11 bytes
Code:
E[Dg6‹#Rß\R

Explanation:
E           # Evaluate input
 [          # Infinite loop
  D         # Duplicate top of the stack
   g        # Get the length
    6‹#     # If smaller than 6, break
       R    # Reverse top of the stack
        ß\  # Extract the smallest item and remove it
          R # Reverse top of the stack
            # Implicit, print the processed array

Uses CP-1252 encoding.

CJam, 16 bytes
{ee{1=~}$5<$1f=}

An unnamed block (function) that takes an array and returns an array.
Test suite.
Explanation
ee   e# Enumerate the array, pairing each number with its index.
{    e# Sort by...
 1=  e#   The original value of each element.
 ~   e#   Bitwise NOT to sort from largest to smallest.
}$   e# This sort is stable, so the order tied elements is maintained.
5<   e# Discard all but the first five.
$    e# Sort again, this time by indices to recover original order.
1f=  e# Select the values, discarding the indices.

PowerShell v4, 120 97 bytes
param($a)$b=@{};$a|%{$b.Add(++$d,$_)};($b.GetEnumerator()|sort Value|select -l 5|sort Name).Value

Experimenting around, I found an alternate approach that golfed off some additional bytes. However, it seems to be specific to PowerShell v4 and how that version handles sorting of a hashtable -- it seems, by default, that in v4 if multiple Values have the same value, it takes the one with a "lower" Key, but you're not guaranteed that in v3 or earlier, even when using the ordered keyword in v3. I've not fully vetted this against PowerShell v5 to say if the behavior continues.
This v4-only version takes input as $a, then creates a new empty hashtable $b. We loop through all the elements of the input $a|%{...} and each iteration add a key/value pair to $b (done by pre-incrementing a helper variable $d as the key for each iteration). Then we sort $b based on Value, then select the -last 5, then sort by Name (i.e., the key), and finally output only the .Values of the resultant hash.
If fewer than 5 elements are entered, it will just sort on value, select the last five (i.e., all of them), re-sort on key, and output.

Older, 120 bytes, works in earlier versions
param($a)if($a.Count-le5){$a;exit}[System.Collections.ArrayList]$b=($a|sort)[-5..-1];$a|%{if($_-in$b){$_;$b.Remove($_)}}

Same algorithm as Morgan Thrapp's answer, which is apparently an indication that great minds think alike. :)
Takes input, checks if the number of items is less-than-or-equal-to 5, and if so outputs the input and exits. Otherwise, we create an ArrayList $b (with the exorbitantly lengthy [System.Collections.ArrayList] cast) of the top five elements of $a. We then iterate over $a and for each element if it's in $b we output it and then remove it from $b (and here's why we need to use ArrayList, as removing elements from an Array isn't a supported feature in PowerShell, since they're technically fixed size).
Requires v3 or greater for the -in operator. For an answer that works in earlier versions, swap $_-in$b for $b-contains$_ for a total of 126 bytes.

Bash + GNU utilities, 36
nl|sort -nrk2|sed 5q|sort -n|cut -f2

I/O formatted as newline-separated lists via STDIN/STDOUT.
Try it online.

Python, 68 bytes
lambda l,S=sorted:zip(*S(S(enumerate(l),key=lambda(i,x):-x)[:5]))[1]

Example run.
A lump of built-ins. I think the best way to explain is to run through an example.
>> l
[5, 4, 2, 1, 0, 8, 7, 4, 6, 1, 0, 7]
>> enumerate(l)
[(0, 5), (1, 4), (2, 2), (3, 1), (4, 0), (5, 8), (6, 7), (7, 4), (8, 6), (9, 1), (10, 0), (11, 7)]

enumerate turns the list into index/value pairs  (technically an enumerate object).
>> sorted(enumerate(l),key=lambda(i,x):-x)
[(5, 8), (6, 7), (11, 7), (8, 6), (0, 5), (1, 4), (7, 4), (2, 2), (3, 1), (9, 1), (4, 0), (10, 0)]
>> sorted(enumerate(l),key=lambda(i,x):-x)[:5]
[(5, 8), (6, 7), (11, 7), (8, 6), (0, 5)]

The pairs are sorted by greatest value first, keeping the current order of index for ties. This puts at the front the highest-scored comments, tiebroken by earlier post. Then, the 5 best such comments are taken.
>> sorted(_)
   [(0, 5), (5, 8), (6, 7), (8, 6), (11, 7)]
>> zip(*sorted(_))[1]
   (5, 8, 7, 6, 7)

Put the top five comments back in posting order, and then remove the indices, keeping only the scores.

PHP 5, 107 102
Saved 5 bytes thanks to @WashingtonGuedes
function p($s){uasort($s,function($a,$b){return$a<=$b;});$t=array_slice($s,0,5,1);ksort($t);return$t;}

Ungolfed
function p($scores) {
    // sort the array from high to low,
    // keeping lower array keys on top of higher
    // array keys
    uasort($scores,function($a, $b){return $a <= $b;});
    // take the top 5
    $top_five = array_slice($scores,0,5,1);
    // sort by the keys
    ksort($top_five);
    return $top_five;
}

Try it.

For 1 1 5 1 1 5, your submission produces an output of 1 5 1 1 5 instead of the correct 1 1 5 1 5.

It seems to behave differently for PHP 7.X, switch the PHP version to 5.6 or below.

Gotcha, didn't notice the version number. :)

I didn't either at first. I'm not sure why that doesn't save what version used as well as the code. I'm also not sure why it doesn't work correctly on 7.X.

@WashingtonGuedes Removing spaces saved me 5 bytes, but I'm not seeing any unnecessary semicolons that wouldn't throw an error?

I'm not sure about the semicolons because I don't know much of PHP, but at least in javascript you can use instead of ;} just }

Haskell, 62 bytes
import Data.List
map snd.sort.take 5.sortOn((0-).snd).zip[0..]

Usage example: map snd.sort.take 5.sortOn((0-).snd).zip[0..] $ [5, 4, 2, 1, 0, 8, 7, 4, 6, 1, 0, 7] -> [5,8,7,6,7].
How it works: augment each element with it's index, sort descending, take first 5 elements, sort by index and remove index.

Ruby, 82 87 89 bytes
$><<eval($*[0]).map.with_index{|x,i|[i,x]}.sort_by{|x|-x[1]}[0,5].sort.map(&:last)
to call:
ruby test.rb [1,2,2,3,4,5]
original submission - 56 bytes but fails on certain test cases & didn't support $stdin and $stdout
_.reduce([]){|a,x|a+=_.sort.reverse[0..4]&[x]if !a[4];a}
Explanation
$><<               # print to stdout
eval($*[0])        # evals the passed in array in stdin ex: [1,2,3,4]
.map.with_index    # returns an enumerator with indices
{|x,i|[i,x]}       # maps [index,value]
.sort_by{|x|-x[1]} # reverse sorts by the value
[0,5]              # selects the first 5 values
.sort              # sorts item by index (to find the place)
.map{|x|x[1]}      # returns just the values

Nice program.  You might have to ask the OP about that though.  I am not sure the input format is okay.

@RikerW it actually fails when there is a duplicate top # in the last indice, I'm modifying it now

@RikerW its fixed now, and it supports stdin and writes to stdout.

Okay.  I like the input method though.  I was just saying to ask @TNT about it.

Julia, 48 bytes
!x=x[find(sum(x.<x',2)+diag(cumsum(x.==x')).<6)]

Try it online!
How it works
The comment c1 has higher precedence than the comment c2 iff one of the following is true:

c1 has more upvotes than c2.
c1 and c2 have the same amount of upvotes, but c1 was posted earlier.

This defines a total ordering of the comments, and the task at hand is to find the five comments that have the highest precedences.
Instead of sorting the comments by precedence (which would alter their order, for each comment c, we count the comments that have a greater or equal precedence. We keep c if and only if this count is 5 or less.
To partially sort the comments by number of upvotes, we do the following. Let x be the column vector containing the vote counts. Then x' transposes x ‐ thus creating a row vector ‐ and x.<x' creates a Boolean matrix that compares each element of x with each element of xT.
For x = [0, 2, 5, 4, 0, 1, 0], this gives
<     0      2      5      4      0      1      0
0 false   true   true   true  false   true  false
2 false  false   true   true  false  false  false
5 false  false  false  false  false  false  false
4 false  false   true  false  false  false  false
0 false   true   true   true  false   true  false
1 false   true   true   true  false  false  false
0 false   true   true   true  false   true  false

By summing across rows (via sum(...,2)), we count the number of comments that have strictly more upvotes than the comment at that index.
For the example vector, this gives
4
2
0
1
4
3
4

Next, we count the number of comments with an equal amount of upvotes have been posted earlier than that comment. We achieve this as follows.
First we build an equality table with x.==x', which compraes the elements of x with the elements of xT. For our example vector, this gives:
=     0      2      5      4      0      1      0
0  true  false  false  false   true  false   true
2 false   true  false  false  false  false  false
5 false  false   true  false  false  false  false
4 false  false  false   true  false  false  false
0  true  false  false  false   true  false   true
1 false  false  false  false  false   true  false
0  true  false  false  false   true  false   true

Next, we use cumsum to calculate the cumulative sums of each columns of of the matrix.
1  0  0  0  1  0  1
1  1  0  0  1  0  1
1  1  1  0  1  0  1
1  1  1  1  1  0  1
2  1  1  1  2  0  2
2  1  1  1  2  1  2
3  1  1  1  3  1  3

The diagonal (diag) holds the count of comments that have an equal amount of upvotes and occur no later than the corresponding comment.
1
1
1
1
2
1
3

By adding the two row vectors we produced, we obtain the priorities (1 is the highest) of the comments.
5
3
1
2
6
4
7

Comments with priorities ranging from 1 to 5 should be displayed, so we determine their indices with find(....<6) and retrieve the corresponding comments with x[...].

Java 7, 155 bytes
import java.util.*;List c(int[]f){LinkedList c=new LinkedList();for(int i:f)c.add(i);while(c.size()>5)c.removeLastOccurrence(Collections.min(c));return c;}

Ungolfed & test-code:
Try it here.
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

class Main{
    static List c(int[] f){
        LinkedList c = new LinkedList();
        for (int i : f){
            c.add(i);
        }
        while(c.size() > 5){
            c.removeLastOccurrence(Collections.min(c));
        }
        return c;
    }

    public static void main(String[] a){
        System.out.println(Arrays.toString(c(new int[]{ 0, 2, 5, 4, 0, 1, 0 }).toArray()));
        System.out.println(Arrays.toString(c(new int[]{ 2, 1, 1, 5, 3, 6 }).toArray()));
        System.out.println(Arrays.toString(c(new int[]{ 0, 4, 5 }).toArray()));
        System.out.println(Arrays.toString(c(new int[]{ 1, 1, 5, 1, 1, 5 }).toArray()));
        System.out.println(Arrays.toString(c(new int[]{ 0, 2, 0, 0, 0, 0, 0, 0 }).toArray()));
        System.out.println(Arrays.toString(c(new int[]{ 0, 0, 0, 0, 1, 0, 0, 0, 0 }).toArray()));
        System.out.println(Arrays.toString(c(new int[]{ 6, 3, 2, 0, 69, 22, 0, 37, 0, 2, 1, 0, 0, 0, 5, 0, 1, 2, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 2 }).toArray()));
    }
}

Output:
[0, 2, 5, 4, 1]
[2, 1, 5, 3, 6]
[0, 4, 5]
[1, 1, 5, 1, 5]
[0, 2, 0, 0, 0]
[0, 0, 0, 0, 1]
[6, 69, 22, 37, 5]

Python 3.5, 68 bytes
f=lambda x,*h:x and x[:sum(t>x[0]for t in x+h)<5]+f(x[1:],*h,x[0]+1)

No match for my Python 2 answer, but only three bytes longer than its port to Python 3, and I think it's different enough to be interesting.
I/O is in form of tuples. Test it on repl.it.


text:
Split, flip and recombine integers
Background
It's well known in mathematics that integers can be put into a one-to-one correspondence with pairs of integers.
There are many possible ways of doing this, and in this challenge, you'll implement one of them and its inverse operation.
The task
Your input is a positive integer n > 0.
It is known that there exist unique non-negative integers a, b ≥ 0 such that n == 2a * (2*b + 1).
Your output is the "flipped version" of n, the positive integer 2b * (2*a + 1).
You can assume that the input and output fit into the standard unsigned integer datatype of your language.
Rules and scoring
You can write either a full program or a function.
The lowest byte count wins, and standard loopholes are disallowed.
Test cases
These are given in the format in <-> out, since the function to be implemented is its own inverse: if you feed the output back to it, you should get the original input.
1 <-> 1
2 <-> 3
4 <-> 5
6 <-> 6
7 <-> 8
9 <-> 16
10 <-> 12
11 <-> 32
13 <-> 64
14 <-> 24
15 <-> 128
17 <-> 256
18 <-> 48
19 <-> 512
20 <-> 20
28 <-> 40
30 <-> 384
56 <-> 56
88 <-> 224
89 <-> 17592186044416

Leaderboard
Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.
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

If you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:
## Perl, 43 + 2 (-p flag) = 45 bytes

You can also make the language name a link which will then show up in the leaderboard snippet:
## [><>](http://esolangs.org/wiki/Fish), 121 bytes

var QUESTION_ID=70299,OVERRIDE_USER=32014;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="
"+e.body.replace(OVERRIDE_REG,"")+"
")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
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

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

Funny, this problem was posted on anarchy golf last week

@feersum Oh, I wasn't aware. What a coincidence.

Obligatory https://xkcd.com/153/

Jelly, 17 16 15 bytes
BUi1µ2*³:2*×Ḥ’$

Try it online!
How it works
BUi1µ2*³:2*×Ḥ’$    Main link. Input: n

B                  Convert n to base 2.
 U                 Reverse the array of binary digits.
  i1               Get the first index (1-based) of 1.
                   This yields a + 1.
    µ              Begin a new, monadic chain. Argument: a + 1
     2*            Compute 2 ** (a+1).
       ³:          Divide n (input) by 2 ** (a+1).
                   : performs integer division, so this yields b.
         2*        Compute 2 ** b.
              $    Combine the two preceding atoms.
            Ḥ      Double; yield 2a + 2.
             ’     Decrement to yield 2a + 1.
           ×       Fork; multiply the results to the left and to the right.

Wait, are you implementing operators in Jelly to suit the problem? In that case LOL

I am not. The only commit to Jelly after this challenge was posted was an update of the documentation, and all the operator used in this answer have been implemented for at least a month. Feel free to verify

No worries, I'm not familiar with the rules or anything, I just thought it was cool that golfing has come to people inventing their own languages!

And there's a lot of them. Check out What programming languages have been created by PPCG users?.

Pyth, 16 15 bytes
*hyJ/PQ2^2.>QhJ

1 byte thanks to Dennis
Test suite
Explanation:
*hyJ/PQ2^2.>QhJ
                    Implicit: Q = eval(input())
     PQ             Take the prime factorization of Q.
    /  2            Count how many 2s appear. This is a.
   J                Save it to J.
  y                 Double.
 h                  +1.
          .>QhJ     Shift Q right by J + 1, giving b.
        ^2          Compute 2 ** b.
*                   Multiply the above together, and print implicitly.

Python 2, 39 bytes
lambda n:2*len(bin(n&-n))-5<<n/2/(n&-n)

n & -n gives the largest power of 2 that divides n. It works because in two's-complement arithmetic, -n == ~n + 1. If n has k trailing zeros, taking its complement will cause it to have k trailing ones. Then adding 1 will change all the trailing ones to zeroes, and change the 2^k bit from 0 to 1. So -n ends with a 1 followed by k 0's (just like n), while having the opposite bit from n in all higher places.

can you shortly explain how does n&-n work ? i see what this trick do but not how :(

n&-n returns the highest power of 2 that divdes n.

@Erwan I explained about n & -n.

I had gotten the corresponding program on Anarchy golf n=1;exec"c=n&-n;print n,':',2*len(bin(c))-5<<n/2/c;n+=1;"*100, but it's two chars behind the best solution.

@xnor Hint: the 59-byte solution (well, mine at least) does not work for all values of n.

MATL, 22 bytes
Yft2=XK~)pq2/2w^Ks2*Q*

Try it online!
Explanation
Yf      % factor
t       % duplicate
2=      % compare to 2 (yields a logical array)
XK      % save a copy of that to variable K
~)      % keep only values != 2 in the factors array
p       % multiply that factors
q2/     % product - 1 / 2
2w^     % 2^x

K       % load variable K (the logical array)
s       % sum (yields the number of 2s)
2*Q     % count * 2 + 1

*       % multiply both values

Very nice! You can use Q for 1+ (this has been introduced recently) and q for 1-. That also saves a space (which you could save with H anyway). See here

@LuisMendo Thanks. Didn't know that feature.

Well done beating Luis using MATL!

MATL, 25 26 bytes
:qt2w^w!2*Q*G=2#f2*q2bq^*

This uses current release (10.2.1) of the language/compiler.
Try it online!
Explanation
Pretty straightforward, based on brute force. Tries all combinations of a and b, selects the appropriate one and does the required computation.
:q          % implicit input "n". Generate row vector [0,1,...,n-1], say "x"
t2w^        % duplicate and compute 2^x element-wise
w!2*Q       % swap, transpose to column vector, compute 2*x+1
*           % compute all combinations of products. Gives 2D array
G=2#f       % find indices where that array equals n
2*q2bq^*    % apply operation to flipped values

Hah! :-P Beaten in your own language... first time?

@StewieGriffin Yep! A nice milestone :-)

Julia, 41 bytes
n->2^(n>>(a=get(factor(n),2,0)+1))*(2a-1)

This is an anonymous function that accepts an integer and returns an integer. To call it, assign it to a variable.
We define a as 1 + the exponent of 2 in the prime factorization of n. Since factor returns a Dict, we can use get with a default value of 0 in case the prime factorization doesn't contain 2. We right bit shift n by a, and take 2 to this power. We multiply that by 2a-1 to get the result.

Perl 5, 40 bytes
38 bytes plus 2 for -p
$i++,$_/=2until$_%2;$_=2*$i+1<<$_/2-.5

-p reads the STDIN into the variable $_.
$i++,$_/=2until$_%2 increments $i (which starts at 0) and halves $_ until $_ is nonzero mod 2. After that, $_ is the odd factor of the original number, and $i is the exponent of 2.
$_=2*$i+1<<$_/2-.5 — The right-hand side of the = is just the formula for the number sought: {1 more than twice the exponent of 2} times {2 to the power of {half the odd factor minus a half}}. But "times {2 to the power of…}" is golfed as "bit-shifted leftward by…". And that right-hand side is assigned to $_.
And -p prints $_.

JavaScript ES6, 36 33 bytes
n=>63-2*Math.clz32(b=n&-n)<<n/b/2

My understanding is that Math.clz32 is going to be shorter than fiddling around with toString(2).length.
Edit: Saved 3 bytes thanks to @user81655.

Nice. You could also save a few bytes by setting n&-n to a variable: n=>63-2*Math.clz32(x=n&-n)<<n/x/2

@user81655 Thanks; I only wish I could have used n&=-n, but I need n again...

C, 49 bytes
a;f(n){for(a=0;n%2-1;a++)n/=2;return 2*a+1<<n/2;}

Vyxal, 13 bytes
2Ǒ:£E/‹½E¥d›*

Try it Online!
2Ǒ            # Multiplicity by 2 = a
  :£          # Store a copy to the register
     /        # Divide the input by...
    E         # 2 ** A
      ‹½      # Decrement and halve = b
        E     # 2 ** b
            * # Multiplied by
         ¥    # a (register)
          d›  # Doubled and incremented

PARI/GP, 38 bytes
f(n)=k=valuation(n,2);(2*k+1)<<(n>>k\2)

Note that >> and \ have the same precedence and are computed left-to-right, so the last part can be n>>k\2 rather than (n>>k)\2. The ungolfed version would make k lexical with my:
f(n)=
{
  my(k=valuation(n,2));
  (2*k+1) << ((n>>k)\2);
}

Pip, 24 23 18 bytes
Wa/2=HV:ai+:2Ui*Ea

Try It Online!
Loops, halving a and incrementing i by 2, until a halved (int division) is different from a/2 (float division), thus indicating a had become odd. The way the loop is set up, a is now half of that odd number, rounded down: i.e., if the odd factor of the original input is \$2k+1\$, a is now \$k\$. Meanwhile, if the largest power-of-two factor of the original input is \$2^n\$, then i is now \$2n\$. It remains only to increment i to \$2n+1\$ and multiply that by \$2^k\$.

The new U, E, and HV operators make a big difference for this one. Here's the original 23-byte version in Pip Classic:
Wa/2=Ya//:2i+:2++i*2**a

Try it online!

HBL, 22 bytes
1(1.)(1.).
?(%.)(1(12(/.2))?)(()(?(/.2
+(().

Try it here!
Ungolfed/explanation
Here's the same thing in HBL's companion language Thimble:
'(cons (head arg1) (head arg1) arg1)

'(cond (odd? arg1)
   (cons
     (pow 2 (div arg1 2))
     nil)
   (prev
     (recur (div arg1 2))))

'(sum (prev arg1))

The first line is a helper function that takes a list and prepends two copies of its first element to it.
The second function does most of the work. If the argument is odd (base case):

Int-divide it by 2
Raise 2 to that power
Return that value wrapped in a singleton list

If the argument is even (recursive case):

Int-divide it by 2
Recurse
Apply the helper function to the resulting list

Thus, given \$n = 2^p \cdot (2k + 1)\$, this function returns a list containing \$2p + 1\$ copies of \$2^k\$.
The third function passes its argument to the second function and then simply sums the result.

05AB1E, 14 bytes
Ò2¢©o/<;§o®·>*

Port of @emanresuA's Vyxal answer.
Should have been 13 bytes, but there is a bug in 05AB1E's o with certain decimal values.
Try it online or verify all test cases.
Explanation:
Ò            # Get all prime factors of the (implicit) input
 2¢          # Count how many 2s are in this list
   ©         # Store it in variable `®` (without popping)
    o        # Pop it, and push 2 to the power this value
     /       # Divide the (implicit) input by this value
      <      # Decrease it by 1
       ;     # Halve it
        §    # (Cast it to a string - bugfix)
         o   # Pop it, and push 2 to the power this (strinified) decimal
      ®      # Push variable `®`
       ·     # Double it
        >    # Increase it by 1
          *  # Multiply the two together
             # (which is output implicitly as result)


text:
Zeroes in interval
Your task is to write a function or program that takes two non-negative integers i and k (i ≤ k), and figure out how many zeroes you'd write if you wrote all whole numbers from i to k (inclusive) in your base of choice on a piece of paper. Output this integer, the number of zeroes, to stdout or similar.
-30% if you also accept a third argument b, the integer base to write down the numbers in. At least two bases must be handled to achieve this bonus.

You may accept the input in any base you like, and you may change the base between test cases.
You may accept the arguments i, k and optionally b in any order you like.
Answers must handle at least one base that is not unary.

Test cases (in base 10):
i k -> output
10 10 -> 1
0 27 -> 3
100 200 -> 22
0 500 -> 92

This is code-golf; fewest bytes win.

If you can go with whatever base you'd like from case to case, couldn't you do each in base k and print 0 or 1, depending on whether i = 0?

You might want to exclude unary as a base, or else this problem is trivial: get inputs, print 0.

Can you add some test cases for other bases?

I think this would be more interesting if the base argument were required. "Base of your choice" is weird to me.

Yes, @AlexA. but too late to change that now, 10 answers in.

Can we get input in unary?

@ThomasKwa yes, unary input is ok

@Mego According to Wikipedia, "in order to represent a number N, an arbitrarily chosen symbol representing 1 is repeated N times". It would actually make the most sense to use 0, since there is no 2 symbol in base 2, no 3 in base 3, etc. So it makes sense that base 1 has no 1.

Jelly, 1 byte
¬

This uses base k+2, in which case there's a single 0 iff i is 0. It takes two arguments, but applies the logical NOT to only the first one.
If we don't want to cheat:
7 bytes - 30% = 4.9
-1.1 points by @Dennis
rb⁵$¬SS

This gets the bonus.
             dyadic link:
r            inclusive range
 b⁵$           Convert all to base input.
    ¬          Vectorized logical NOT
     S         Sum up 0th digits, 1st digits, etc.
      S        Sum all values

This is the second Jelly program I've written on my phone.

Damn, 1 byte?  Give us a chance.

This can be easily done in very few bytes in any other language. I say stick to the non-cheating version.

@ETHproductions The rules of the question explicitly allow doing this. Cheaty or not, it's the answer the rules call for.

Python 2, 36 bytes
lambda a,b:`range(a,b+1)`.count('0')

Credit to muddyfish for the `` trick.

Welcome to Programming Puzzles & Code Golf! This is a nice first answer. :)

Wow! I didn't know it's working!

05AB1E, 3 1 byte
Uses base k+2 like the Jelly answer, Code:
_

Explanation:
_  # Logical NOT operator

3 byte non-cheating version:
Code:
Ÿ0¢

Explanation:
Ÿ    # Inclusive range
 0¢  # Count zeroes

The bonus gives me 3.5 bytes due to a bug:
ŸB)0¢

Explanation:
Ÿ      # Inclusive range
 B     # Convert to base input
  )    # Wrap into an array (which should not be needed)
   0¢  # Count zeroes

Uses CP-1252 encoding.

How does this work?

@ThomasKwa Explanation added

Japt, 3 bytes
+!U

Uses base k+2, as the Jelly answer. There is a zero iff i==0. Test it online!
Better version, 10 8 bytes
UòV ¬è'0

This one uses base 10. Test it online!
Bonus version, 14 12 bytes - 30% = 8.4
UòV msW ¬è'0

Sadly, with the golfing I did, the bonus is no longer worth it... Test it online!
How it works
UòV msW ¬è'0   // Implicit: U = start int, V = end int, W = base
UòV            // Create the inclusive range [U..V].
    msW        // Map each item by turning it into a base-W string.
        ¬      // Join into a string.
         è'0   // Count the number of occurances of the string "0".

ES6, 91 86 - 30% = 60.2 bytes
(i,k,b=10)=>([...Array(k+1-i)].map((_,n)=>(i+n).toString(b))+'0').match(/0/g).length-1

Or save 3 (2.1) bytes if b doesn't need to default to 10.
Best non-bonus version I could do was 65 bytes:
(i,k)=>([...Array(k+1).keys()].slice(i)+'0').match(/0/g).length-1

Edit: Saved 5 bytes by using @edc65's zero-counting trick.

As I don't manage to get votes for my answer, I'll upvote yours (at least there my name inside)

Seriously, 10 bytes
'0,,u@xεjc

Explanation:
'0,,u@xεjc
'0,,u       push "0", i, k+1
     @x     swap i and k+1, range(i, k+1)
       εjc  join on empty string and count 0s

Try it online!
With bonus: 11.9 bytes
'0,,u@x,╗`╜@¡`Mεjc

Try it online!
Explanation:
'0,,u@x,╗`╜@¡`MΣc
'0,,u@x             push "0", range(i, k+1)
       ,╗           push b to register 0
         `   `M     map:
          ╜@¡         push b, push string of a written in base b
               Σc   sum (concat for strings), count 0s

Ruby, 46 - 30% = 32.2 bytes
You could probably golf this more, but at least I get the 30% bonus!
->i,k,b{((i..k).map{|a|a.to_s b}*"").count ?0}

...or without the bonus (27 bytes.)
->i,k{([*i..k]*"").count ?0}

Tips are welcome, still learning this whole "Ruby" thing.

Nice answer, you don't need the splat operator when using map, this could save 1 byte. (i..k) is as good as [*i..k] in the first case.

CJam, 12 10 3 bytes
li!

This uses the shortcut @ThomasKwa does.
If this is not allowed, then here is a 10 byte answer.
q~),>s'0e=

Nice and short! Works like @Mego's Seriously answer.
Thanks @Dennis!
Had fun writing my first CJam answer!
Try it here!

T-SQL, 394 Bytes (No bonus)
I figure 'why not', right?
DECLARE @i INT, @k INT SET @i = 100 SET @k = 200  WITH g AS (SELECT @i AS n UNION ALL SELECT n+1 FROM g WHERE n+1<=@k ) SELECT LEN(n) AS c FROM (SELECT STUFF((SELECT REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(n, 1, ''), 2, ''), 3, ''), 4, ''), 5, ''), 6, ''), 7, ''), 8, ''), 9, ''), ' ', '') FROM g FOR XML PATH ('')) ,1,0,'') n ) a OPTION (maxrecursion 0)

And the friendly one:
-- CG!

DECLARE @i INT, @k INT
SET @i = 100
SET @k = 200

WITH g AS
(
    SELECT @i AS n
    UNION ALL
    SELECT n+1 FROM g WHERE n+1<=@k
)

SELECT LEN(n) AS c FROM
(
    SELECT
        STUFF((SELECT REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(n, 1, ''), 2, ''), 3, ''), 4, ''), 5, ''), 6, ''), 7, ''), 8, ''), 9, ''), ' ', '')
FROM g FOR XML PATH ('')) ,1,0,'') n
) a

OPTION (maxrecursion 0)

that's dedication.

Pyth, 6.3 bytes, with bonus (9 bytes - 30%)
/sjRQ}EE0

Explanation:
  jRQ     - [conv_base(Q, d) for d in V]
     }EE  - inclusive_range(eval(input), eval(input))
 s        - sum(^, [])
/       0 - ^.count(0)

Try it here
Or 7 bytes without the bonus:
/`}EE\0

Explanation:
  }EE   - inclusive_range(eval(input), eval(input))
 `      - repr(^)
/    \0 - ^.count("0")

Try it here
Or use a test suite

I think getting the bonus is worth it: /sjRQ}EE0

Ehh, it's the same code with a base conversion, I'm pretty sure you know what you're doing, just the problem of a bonus forcing you to try different stuff and count... :P

Brachylog, 26 bytes
,{,.e?}?:1frcS:0xlI,Sl-I=.

Takes input as a list [i,k].
Explanation
,{    }?:1f                § Unify the output with a list of all inputs which verify the
                           § predicate between brackets {...} with output set as the input
                           § of the main predicate

  ,.e?                     § Unify the input with a number between i and k with the ouput
                           § being the list [i,k]

           rcS             § Reverse the list and concatenate everything into a single
                           § number (we reverse it to not lose the leading 0 if i = 0 when
                           § we concatenate into a single number). Call this number S.

              :0xlI        § Remove all occurences of 0 from S, call I the length of this new
                           § number with no zeros

                   ,Sl-I=. § Output the length of S minus I.

Julia, 48 bytes - 30% = 33.6
f(i,k,b)=sum(j->sum(c->c<49,[base(b,j)...]),i:k)

This is a function that accepts three integers and returns an integer. One of the arguments specifies the base, so this qualifies for the bonus.
Ungolfed:
function f(i, k, b)
    # For each j in the inclusive range i to k, convert j to base
    # b as a string, splat the string into a character array, and
    # compare each character to the ASCII code 49 (i.e. '1'). The
    # condition will only be true if the character is '0'. We sum
    # these booleans to get the number of zeros in that number,
    # then we sum over the set of sums to get the result.
    sum(j -> sum(c -> c < 49, [base(b, j)...]), i:k)
end

Implementing the bonus yields a score just barely better than the not implementing it (34 bytes):
f(i,k)=sum(c->c<49,[join(i:k)...])

Seriously, 2 bytes
This might be taking the Jelly answer trick to the limit, but here is a simple 2 byte Seriously answer.
,Y

Try it online!

JavaScript (ES6), 50 (71 - 30%)
(n,k,b)=>eval("for(o=0;n<=k;++n)o+=n.toString(b)").match(/0/g).length-1

No bonus, base k+2 is 10 bytes (i,k)=>+!i
No bonus, unary is 8 bytes (i,k)=>0
TEST

f=(n,k,b)=>eval("for(o=0;n<=k;++n)o+=n.toString(b)").match(/0/g).length-1

function go() {
  var i=I.value.match(/\d+/g)
  R.textContent = f(i[0],i[1],i[2])
}

go()
i,k,b:<input id=I value='0,500,10' oninput="go()">

If you move the o='0' before the loop your code continues to work even when k<i.

@Neil nice, but the spec says (i ≤ k). Update I tried this but in fact it does not work for k<i

Well, it worked for me (and I know the spec guarantees that i <= k, but your code crashes when k < i; by comparison my code only crashes when k eval("for(n=i;n<=k;++n)o+=n.toString(b)").match(/0/g).length. In this case, var o needs to be undefined in the context of execution.

@ForcentVintier you need a 0 in the string to match, try calling the function with (1,9,10)

My bad then! Thanks for the explanation :)

@ForcentVintier anyway after your input I revised the code saving some bytes

PHP, 50 Bytes
supports decimal only
<?=substr_count(join(range($argv[1],$argv[2])),0);

supports decimal and binary with Bonus 63
<?=substr_count(join(array_map([2=>decbin,10=>""][$argv[3]],range($argv[1],$argv[2]))),0);

supports decimal,hexadecimal, octal and binary with Bonus 77.7
<?=substr_count(join(array_map([2=>decbin,8=>decoct,10=>"",16=>dechex][$argv[3]],range($argv[1],$argv[2]))),0);

supports base 2 - 36 with Bonus 78.4
<?=substr_count(join(array_map(function($i){return base_convert($i,10,$_GET[2]);},range($_GET[0],$_GET[1]))),0);

Nice collection! Care to do a version 3a including base 64? :D

@Titus How is the order of base 64? Why not https://en.wikipedia.org/wiki/Ascii85 or make a little more with all printable ascii chars

Python 3, 52.
Tried to implement the bonus, but it doesn't seem to be worth it.
lambda a,b:''.join(map(str,range(a,b+1))).count('0')

With test cases:
assert f(10, 10) == 1
assert f(0, 27) == 3
assert f(100, 200) == 22
assert f(0, 500) == 92

I literally never heard about the assert statement before this comment. Thanks mate!

Lua 74 bytes
z,c=io.read,""for a=z(),z()do c=c..a end o,b=string.gsub(c,"0","")print(b)

There's gotta be a more effective way to do this...
I thought I was really onto something here:
c,m,z=0,math,io.read for a=z(),1+z()do c=c+((m.floor(a/10))%10==0 and 1 or a%100==0 and 1 or a%10==0 and 1 or 0) end print(c)

But alas... It keeps getting longer and longer as I realize there's more and more zeroes I forgot about...

PowerShell, 56 54 51 48 42 bytes
param($i,$k)(-join($i..$k)-split0).count-1

Takes input, creates a range with $i..$k then -joins that together into a string, followed by a regex -split command that separates the string into an array by slicing at the 0s. We encapsulate that with ().count-1 to measure how many zeros. That's left on the pipeline, and output is implicit.
Saved 6 bytes thanks to @ConnorLSW
Try it online!

Base-handling in PowerShell is limited and doesn't support arbitrary bases, so I'm not going for the bonus.

param($i,$k)(-join($i..$k)-split'0').Length-1 works for me, -3, or use .Count-1 to save even more, haven't tested that yet though.

@ConnorLSW Thanks! Don't need the quotes around '0', so that trimmed off a few more.

nice one, I always forget powershell handles numbers like that.

Jolf, 7 bytes
Replace ♂ with \x11. Try it here!
Zl♂sjJ0
   sjJ  inclusive range between two numeric inputs
  ♂      chopped into single-length elements
Zl    0  and count the number of zeroes
        implicitly printed

APL, 22 bytes
{+/'0'⍷∊0⍕¨(⍺-1)↓⍳⍵}

This is a monadic function that accepts the range boundaries on the left and right and returns an integer.
Ungolfed:
           (⍺-1)↓⍳⍵}  ⍝ Construct the range ⍺..⍵ by dropping the first
                      ⍝ ⍺-1 values in the range 1..⍵
       ∊0⍕¨           ⍝ Convert each number to a string
{+/'0'⍷               ⍝ Count the occurrences of '0' in the string

Try it here

Haskell, 29 bytes
i#k=sum[1|'0'<-show=<<[i..k]]

I'm using base 10.
Usage example: 100 # 200 -> 22
How it works: turn each element in the list from i to k into it's string representation, concatenate into a single string, take a 1 for every char '0' and sum those 1s.

MATL, 7 (10 bytes − 30% bonus)
2$:i:qYA~z

Try it online!
This works in release 11.0.2, which is earlier than this challenge.
Explanation
2$:      % implicitly input two numbers and generate inclusive range
i:q      % input base b and generate vector [0,1,...,b-1]
YA       % convert range to base b using symbols 0,1,...,b-1. Gives 2D array
~        % logical negation. Zeros become 1, rest of symbols become 0
z        % number of nonzero elements in array

Mathematica, 39 bytes, 27.3 with bonus
Count[#~Range~#2~IntegerDigits~#3,0,2]&

Matlab: 27 bytes
@(q,w)nnz(num2str(q:w)==48)

creates a vector from lower number to larger one, then converts all numbers to string and counts all the '0' symbols.

Perl 6, 23 bytes
{+($^i..$^k).comb(/0/)}

creates a Range ( $^i..$^k )
joins the values with spaces implicitly ( .comb is a Str method )
creates a list of just the zeros ( .comb(/0/) )
returns the number of elems in that list ( + )

Usage:
my &zero-count = {…}

for (10,10), (0,27), (100,200), (0,500), (0,100000) {
  say zero-count |@_
}

1
3
22
92
38895

You know, that comment at the end of your code makes it seem longer...

@ETHproductions I usually do that so that if I come up with more than one way to do things that I can see if it is shorter than others. I just keep adding more ways to do it until I come up with what I think is the shortest way.

C# 112 Bytes
int z(int i,int k)=>String.Join("",Enumerable.Range(i,k-i+1)).Count(c=>c=='0')

Create a string with numbers from the first number up to the last number
Count the zero characters in the string

Welcome to PPCG! I'm not super familiar with C# but I think you could probably save a few bytes if you removed some of the spaces.

thank you 0, you are right but only a couple bytes. I believe my edited answer removes all the spaces I can. :)

PHP, 84 bytes *.7=58.8 (bases 2 to 36)
for(;($v=$argv)[2]>$a=$v[1]++;)$n+=substr_count(base_convert($a,10,$v[3]),0);echo$n;

or
for(;($v=$argv)[2]>$v[1];)$n+=substr_count(base_convert($v[1]++,10,$v[3]),0);echo$n;

takes decimal input from command line arguments; run with -r.

For fun: <?=0 supports unary and alphabetic. ;)

Java 8, 102 bytes - 30% = 71.4
Why not.
(i,k,b)->{int j=0;for(;i<=k;i++)for(char c:Integer.toString(i,b).toCharArray())if(c==48)j++;return j;}

Without the bonus, 96 bytes (so the bonus actually improves my score!):
(i,k)->{int j=0;for(;i<=k;i++)for(char c:String.valueOf(i).toCharArray())if(c==48)j++;return j;}

This implements the following:
interface Function {
    public int apply(int i, int k, int b);
}

@mbomb007 The problem is that formatting it this way renders the answer as 102 bytes on the Leaderboard in the question.

That's a flaw with the leaderboard, not the post. Look at how most of the other answers are doing it the same way.

@mbomb007 I'm looking at the answers and I see a ton of different formats, some of which work with the leaderboard, some of which don't.

Clojure, 50 49 bytes
#(count(re-seq #"0"(apply str(range %(inc %2)))))

Oh regex is shorter than filtering. Original:
#(count(filter #{\0}(apply str(range %(inc %2)))))

Very basic, uses the set of character \0 to remove others and counts how many were found.