Plus one sheep minus one sheep Once upon a time long long ago... when there was no money or stocks yet, people were trading sheep. Even before (but close to) the invention of abacus, the great-grandfather of Warren Buffet decided it was hard to keep track of sheep. He wanted to collect all his belongings and clear all his debt, so that he could invest in a new counting machine he heard that his friend, great-grandfather of Bill Gates was building from sticks and beads. All his trades were atomic i.e. he was either supposed to give exactly one sheep to someone or get exactly one sheep. Of course Grandpa Buffet has more sheep to get then to give. Actually he exactly had 749 sheep to collect and he owed 250 sheep, so he was up by 499 sheep. Because of that he built a barn exactly for 499 sheep beforehand. Then he called all 999 people and told them to get into a queue. The very first man, wanted his sheep but there was no sheep in the barn yet. He didn't like this order and wanted everyone to get in order again but first the givers and then the collectors now. At the 500th men there were no space for new sheep in the barn but there were still 250 to collect before starting to give. He gave all the collected sheep back and make them get in a queue again and went to Grandpa Gates to help him ordering. Somehow they figured out and with the help of 499 sheep, they built a lot of Abacus and lived happily ever after.

Years later, yesterday Bill Gates and Warren Buffet met in a Giving Pledge meeting. They told this story and laughed a lot. Then Gates told Buffet: "You know what, I don't know how my great-grandpa ordered 999 people but I know there are so many ways. Actually I can tell you how many if you let me...". Then he went to his room to write a code to calculate the number of possible orderings that always guarantee there is always sheep or space in the barn until the queue is empty. And he did so but being Bill Gates he has written a recursive function which solves the problem correctly but slowly. So everybody still waits for his answer. Buffet is bored, can you write a better and faster function?

p = 749
n = 250
orderings(p,n) = ?

Shortest code wins, but it must finish in minutes, not hours or days.

Pyth, 33 bytes

M?+&<HGgtGH&+-499GHgGtHH1g749 250

Try it online: Pyth Compiler/Executor. Takes about 3 seconds on my laptop. The online compiler is a bit slower, but also computes the answer in about 15 seconds.

The answer is:

160547283350099323317963999889002394629262478407796913030854915361460989263675794524349914992326520887556329626280682363011590724268659750627030457440692447081328860242720905181098211539560301455338502543318855115593179999323115473879753632000

Explanation:

First some pseudo-code of the recursive function. This is quite easy to write.

function g(p, n):
   if (p > 0 and n > 0):
      count = 0
      if (occupied_places_in_barn < 499):
         count += g(p-1, n)
      if (occupied_places_in_barn > 0):
         count += g(p, n-1)
      return count
   else:
      return 1 # only one way possible

And the Pyth translation:

M                                  def g(G,H): return _
    <HG                               H < G
   &   gtGH                                 and g(G-1,H)
            +-499GH                   499-G+H
           &       gGtH                       and g(G,H-1)
  +                                   return sum of these two numbers
 ?                     H1             if H else 1
                         g749 250  call g(749,250) and print

Why is this recursive code so fast? Doesn't the function g iterate over all 1.6*10^199 possibilities?

No it doesn't. The key here is dynamic programming. We store known results in a cache and lookup the results, when we call the function with the same parameters again. One really cool feature of Python is the @lru_cache decorator, which does all the work for you. No need to manually generate such a cache and handle stuff like lookup, storing results, ... And in Pyth it's even simpler, since each function automatically uses such a cache. So in total the function g gets executed only 125499 times. Way less than 1.6*10^199 times.


CodeGolf - Ignore the noise #1 Instructions

Barry is a not so good backend developer in charge of a small API that should give you information about purchases made in a client's shop. However, he hasn't done a great job and your boss tells you to fix it client-side instead. Ideally you should receive comma-separated values such as 927,2,45,90 which correspond to something like item_id,item_amount,unit_price,total

In this first puzzle we only care about item_id and item_amount but we need the other fields in place to present the problem. Barry sometimes gets things mixed up and returns noise as part of the output, he also gets the order wrong, returning noise, noise, unit_price, total, item_id, item_amount.

Your Task

You need to store in a map (or similar structure) the pairs of item_id and item_amount regardless of whether Barry returns them correctly or not and print each element in a new line in the least number of characters possible. (Storing is not mandatory, we just care about the output)

Sample input (mixed correct and messy formats)

103,2,50,100
106,1,900,900
459,40,150,300,67,2
4,20,30,6000

In other words input will be either a,b,x,x or x,x,x,x,a,b where what we care about is a & b. You need to provide code assuming we have a variable called G (or any other name) with all the lines of csv.

Sample output

103,2
106,1
67,2 //This one was messy
4,20

Tolerance

There is a certain margin for tolerance when it comes to the answer. Answers in similar formats but adhering to the correct values, will also be accepted. Formats like [a,b],(a,b) or {a,b} are valid, but a,b is preferred.

  Although the first puzzle had mixed acceptance due to the fact that it
  was easy and fast to solve, I also felt that some people liked that
  too. So I'm going to continue making quickgolfs for now

Pyth, 10 bytes

FNG<.<N4 2

Try it online: Pyth Compiler/Executor

(The first 4 chars =G.Q reads all the data and stores it in G)

Explanation

FNG              for row N in G:
    .<N4            cyclic leftshift by 4
   <     2          print the first two elements


Code-generator with unique characters Challenge

Your task is to write a piece of code that outputs another piece of code. That code must in turn output yet another code until the final code outputs the integer 1. The chain ends the first time 1 is outputted.

None of your programs may share any characters (there's one exception in the Rules-section).

The winning submission will be the submission with the longest chain. The tie-breaker will be shortest total code-length.

Rules:

You may use both functions, programs and snippets. You may assume a REPL environment.
All functions must be written in the same language
Symbol independent languages are disallowed. This includes partially symbol independent languages such as Headsecks.
Default output formatting may optionally be disregarded in a function's output. This includes trailing newlines, ans = etc.
You may reuse the space character (ASCII code point 32), but note the following:

You may use as many space characters as you like in one of the functions, but restrict it to maximum 5 in all other functions
You may not reuse any characters if code point 32 is not space in your language.

None of the programs may take input
The chain must be at least two programs long.

Example:

Your initial code is abc+cab+bac. This outputs: foofoo*123, which in turn outputs disp(~0), which outputs 1. This is a chain of 3 programs, with a combined length of 29 (tie breaker).


Make a move on a Go board You are given a board position for a Go game and a move to play. You need to output whether the move is legal or not, and the new board position if it is legal.

A brief explanation of Go moves: the game consists of alternatively placing black and white pieces ("stones") in empty places on a square board. Sets of pieces of the same color that are connected to each other (4-way) are called groups. Empty places on the board that are adjacent to a group (also 4-way) are considered to be that group's "liberties". A group with 0 liberties is captured (removed from the board). A move that would cause its own group to be captured ("suicide") is illegal, unless it is capturing one or more opponent's groups (gaining liberties in the process so it is not actually captured).

For those concerned, you don't need to deal with ko (and superko), i.e. you can assume a ko capture is legal. If you don't know what that means, just follow the rules above and it will be fine.

Input: a number n between 2 and 19 (inclusive) representing the board size, followed by n lines of n numbers between 0 and 2 (inclusive) representing the board position, followed by 3 numbers separated by space, representing the move to make. In the board position, 0 means empty place, 1 means black stone and 2 means white stone. The move gives the column, the row and the color (1 or 2) of the stone to place. The column and row are 0-based, ranging from 0 to n-1 (inclusive) and counted in the same order as the board input.

You can assume that the given board position is legal (all groups have at least one liberty).

Output: a line containing 1 or 0 (or true/false if you prefer) if the move is legal or not, followed (only in case of a legal move) by the new board position in the same format as the input.

Score: Number of bytes of the complete source code, smaller is better. 20% additional penalty for use of non-ascii characters, and 20% additional penalty if your code can't be tested in Linux using freely available software.

Rules: No network connections and no 3rd party libraries. Your program should use the standard input and output streams, or the standard equivalent for your programming language.

Examples:

1) Input:

2
10
01
1 0 2

Output:

0

2) Input:

2
10
11
1 0 2

Output:

1
02
00

3) Input:

5
22122
22021
11211
02120
00120
2 1 1

Output:

1
00100
00101
11011
02120
00120

4) Input:

6
000000
011221
121121
122221
011110
000000
4 0 1

Output:

1
000010
011221
121121
122221
011110
000000

Python 3 (557 504 488)

import sys
s=sys.stdin
M=int(next(s))+1
j=Z=M*M-M
S=s.read(Z)
P=0
b=[0]*3
while j>0:j-=1+(j%M<1);b[int(S[j])]|=1<<j;P|=1<<j
N=lambda x:(x<<1|x>>1|x<<M|x>>M)&P&~x
def h(a,b):t=a|N(a)&b;return h(t,b)if t!=a else a
c,r,m=map(int,next(s).split())
o=m%2+1
p=1<<M*r+c
b[m]|=p
for n in(p<<1,p>>1,p<<M,p>>M):
 e=h(n&P,b[o])
 if~b[m]&N(e)<1<=n&b[o]:b[o]&=~e
_,B,W=b
g=~b[o]&N(h(p,b[m]))>=1>~_&p
print(+g)
q=''
while j<Z:
 r=1<<j
 if g*j%M>M-2:print(q);q=''
 else:q+='012E'[(r&B>0)+(r&W>0)*2]
 j+=1

Uses 3 bitfields to represent the board - one each for black, white, and empty spaces. Makes the find neighbors N and get chain h operations very concise.

An ungolfed version with lots of comments:
https://gist.github.com/airfrog/8429006


Mortarboard Challenge Challenge

Given a user's ID, determine how many times they have hit the repcap.

Specs

On a given day, let's a user has hit the repcap if they had reputation that wasn't gained due to the repcap. Essentially, on any given day, if the user's net reputation change as calculated without any cap was different from their actual observed reputation change, then they hit the repcap.

Input/Output

Input will be a single integer, the user's ID.
Output will be a single integer, indicating the number of days for which they had reputation that was "lost".
I/O can be in any reasonable format.

Test Cases

Feel free to add your own ID and stats here. The brackets indicate which user it is, but that isn't part of the output. Don't include it.

input -> output (username)
42649 -> 0 (HyperNeutrino)
41723 -> 7 (Fatalize)
46271 -> 0 (Riker) (This user has obtained 200 rep twice, but never over)

JS ES6, 360 bytes

f=(i,p=1,d=[])=>fetch(`https://api.stackexchange.com/2.2/users/${i}/reputation?site=codegolf&pagesize=100&page=${p}`).then(x=>x.json()).then(j=>(q=d.concat(j.items),j.has_more?f(i,p+1,q):(r=[],q.map(s=>(r[d=new Date(s.on_date*1000),i=d.getDate()+d.getMonth()*32+d.getYear()*365]?r[i]+=s.reputation_change:r[i]=s.reputation_change)),r.filter(x=>x>200).length)))

Call it like f(user id). Returns a promise that resolves with the number of days that rep was lost.

Ungolfed:

f=(i,p=1,d=[])=>fetch(`https://api.stackexchange.com/2.2/users/${i}/reputation?site=codegolf&pagesize=100&page=${p}&key=kAc8QIHB*IqJDUFcjEF1KA((`).then(x=>x.json()).then(j=>{
    return (q=d.concat(j.items),
    j.has_more?
        f(i,p+1,q)

        :(r=[],
            q.map(s=>(r[d=new Date(s.on_date*1000),
                i=d.getDate()+d.getMonth()*32+d.getYear()*365]?
                    r[i]+=s.reputation_change

                    :r[i]=s.reputation_change)),
            r.filter(x=>x>200).length
        )
    )
});


The Eyes are Following You This is inspired by the excellent Visualize Visual Eyes challenge. It is posted with permission from and credit to @Jordan

We are going to create an ASCII art approximation of the Xeyes challenge but without worrying about the actual mouse movements. Just the positions.

EDIT

I thought about whether this could be seen as a duplicate but I don't believe it is.

The previous question required detecting mouse movement. This does not and so is open to many more languages.This is simple interactive ASCII art which can be attempted in any language.
While the algorithm for the eye movement may be similar, this is in many ways simpler to achieve.
I'm not convinced that any answer given so far to the previous question could be trivially ported to this.
I don't think I am good enough at languages that could answer the previous question to attempt it. I would have a try at this one.

If consensus is that I am wrong then I am happy to delete the question.

I have removed the comment about "interesting answer" as this is intended to be code golf.

Overview

In all cases the mouse position will be represented by an X.

Here are the eyes with no mouse position (cursor is off screen):

/---\ /---\
|   | |   |
| O | | O |
|   | |   |
\---/ \---/

Now let's say your mouse is to the right of the eyes:

/---\ /---\
|   | |   |
|  O| |  O|X
|   | |   |
\---/ \---/

and now at the bottom left:

 /---\ /---\
 |   | |   |
 |   | |   |
 |O  | |O  |
 \---/ \---/
X

and now at the top:

     X
/---\ /---\
| O | | O |
|   | |   |
|   | |   |
\---/ \---/

From this we can see that (in it's simplest case - we could make it a lot more complicated but let's not do that for now) there are 9 different positions for the eyes and nine different positions for the cursor as shown below:

1     2     3
 /---\ /---\
 |123| |123|
4|456| |456|6
 |789| |789|
 \---/ \---/
7     8     9

Position 5 represents no cursor (off screen). The eyes are both looking forward.

The Challenge

Take an integer (or any representation of an integer) between 1 and 9 inclusive and output the eyes if the cursor was in the position of that integer. You must include the X as the position of the cursor (except when it is off screen i.e. the eyes are looking forward - no X).

Rules

Input format is your own choice.
Program or function.
Any amount of leading or trailing whitespace is allowed.
Output must consist only of the characters /\-| and either upper or
lowercase x and o.
Assume that the input will always be valid, i.e. an integer between
1 and 9 inclusive.
Feel free to change the order of the integers if it helps i.e. 2 does
not have to be top and 5 does not have to be no cursor.
Standard loopholes prohibited as usual.
This is code golf. Shortest answer wins.

Test Cases

Note: All test cases use the numbering sequence detailed in the explanation. As stated in the rules, you do not have to use the same number sequence.

Input = 5

/---\ /---\
|   | |   |
| O | | O |
|   | |   |
\---/ \---/

Input = 6

/---\ /---\
|   | |   |
|  O| |  O|X
|   | |   |
\---/ \---/

Input = 2

     X
/---\ /---\
| O | | O |
|   | |   |
|   | |   |
\---/ \---/

Input = 7

 /---\ /---\
 |   | |   |
 |   | |   |
 |O  | |O  |
 \---/ \---/
X

This challenge has been in the sandbox for the last week.


Parallel projected voxel terrain generator Your job is to generate a heightmap and show it as a parallel projected, voxel landscape. The rules are the following:

The (heightmap of the) landscape has to be randomly generated
You also have to describe how the algorithm you are using works, so everyone can learn something new here
You have to also either generate an image or display the generated landscape on the screen
The resulting image has to be paralell projected (so not perspective), and it can only contain voxels (so it has to be made out of small boxes)
This is a popularity contest, so you might want to add some additional features to your program to get more upvotes.
The winner is the most upvoted valid answer 7 days after the last valid submission. All valid submissions need to follow the rules, including the description of the used algorithm. You can add additional features which do not follow some of the rules (like adding a perspective mode), but in this case they have to be optional features (e.g. when turning them off the result should follow all of the rules)
My submission doesn't count as valid.

An example result image is the following:

Image taken from here

If you need some algorithms check here

Python2 3D Function Plotter Voxel Edition

This is my entry in this competition:

import math
import random
import Image

terrain=""
randA=(random.random()*4+5)
randB=(random.random()*4+10)
randC=(random.random()*4+1)
randD=(random.random()*4+1)
im = Image.new("RGBA", (1248, 1000), "black")
tile=[Image.open("voxel/1.png"),Image.open("voxel/2.png"),Image.open("voxel/3.png"),Image.open("voxel/4.png"),Image.open("voxel/5.png"),Image.open("voxel/6.png"),Image.open("voxel/7.png"),Image.open("voxel/8.png"),Image.open("voxel/9.png")]

for y in range (-40,40):
        for x in range (-10, 10):
                val=int(1+abs(4+2.5*(math.sin(1/randA*x+randC)+math.sin(1/randB*y+randD))))
                if (val<9):
                        terrain+=str(val)
                else:
                        terrain+="9"
print terrain

for i in range (0,80*20):
        if((i/20)%2==0):
                shift=0
        else:
                shift=-32
        im.paste(tile[int(terrain[i])-1],((i%20)*64+shift,((i/20)*16-(32*(int(terrain[i])-1)))-32),tile[int(terrain[i])-1])

im.show()

As clearly stated in the title it works as a 3D function plotter, but since this competition requires the terrain to be randomly generated it this random sine function 1.5*(math.sin(1/randA*x+randC)+math.sin(1/randB*y+randD)) That depends on 4 random variables. This creates terrains like this:

We can ofcourse replace this random function by any 2 variable function, for example sin(sqrt((x/2)²+(y/2)²))*3 gives this terrain:

and -x*y*e^(-x^2-y^2) gives this:

(the plots on the right are computed by wolfram alpha)

And while we're at it, Riemann zeta along the critical strip:

For the people who aren't familiar with it, as you can see these pools of water (wich represent the zero's of the function) all lie on a straight line (real part = 0.5). If you can prove this, you will get $1000000! See this link.

I hope you like it!


Chinese Zodiac of the year 2015 was the year of the goat! In this challenge, you will figure out which animal represents the year. To avoid making this challenge to complex you won't need to calculate Chinese new year.

Because they are only 12 animals in the Zodiac, your code will need to be as short as possible.

Examples

Your program must get the system year, the first line is just for reference

2015
Goat

1924
Rat

1923
Pig

2008
Rat

Specification

The order of the Zodiac is:

Rat, Ox, Tiger, Rabbit, Dragon, Snake, Horse, Goat, Monkey, Rooster, Dog, Pig

Rat starts at 2008, Pig is 2007, Ox at 2009, etc. at the end this loops back around.

Output must be correctly capitalized.

Pyth - 65 bytes
@c." y=CÅQ¯@îR
°©ÀáëªfÞ#[õNqÀN8Ô'¼ô,n7Ë¶~fB").d3

Try it online here.
@                     Modular indexing
 c           )        Split string, use default of spaces
  ."ajs&^asd"         Packed string to compress space separated zodicas
 .d3                  Current year


One more LUL and I'm out Challenge description

On some channels on a popular streaming site twitch.tv a common message people tend to spam in chats to bait people into spamming "LUL" is

One more LUL and I'm out

LUL is a popular emote used to express that something funny happened on stream.

Soon dank memes showed their potential and a parody of the copy-pasta ensued:

One more "One more LUL and I'm out" and I'm out

Which is the same message nested in itself. Given a non-negative integer N, output the LUL-pasta nested N times in itself following the pattern below.

Standard code-golf rules apply, the shortest code in bytes wins.

Sample input / output

0: One more LUL and I'm out
1: One more "One more LUL and I'm out" and I'm out
2: One more "One more "One more LUL and I'm out" and I'm out" and I'm out
...
7: One more "One more "One more "One more "One more "One more "One more "One more LUL and I'm out" and I'm out" and I'm out" and I'm out" and I'm out" and I'm out" and I'm out" and I'm out

Notes

Leading/trailing newlines are allowed
Capitalization must be preserved
Your code may be a full program or a function
Instead of printing, you may return a string or its equivalent in your language of choice
You may index from 1 instead of 0

Python 2, 56 bytes

lambda x:('"One more '*x+'LUL'+' and I\'m out"'*x)[1:-1]

Try it online!
It is 1-indexed


Tension on a Graph, Part II: A Rubber Band This is the second of two challenges about "pulling functions taut". Here is the slightly simpler Part I.

Let's drive m nails into a board at positions (x1, y1) to (xm, ym). Tie a rubber band to the first and last of those and stretch around the other nails, such that the band traverses all nails in order. Note that the rubber band now describes a piecewise linear parameterised function (x(t), y(t)) in 2D space.

Now drive another n nails into the board, at positions (x1, y1) to (xn, yn). If we now remove all of the original m nails except the first and last one (which the ends of the rubber is tied to), the rubber band will shorten until it's lying taut around the new nails, yielding another piecewise linear function.

As an example, take m = 12 initial nails at positions (0, 0), (2, -1), (3/2, 4/3), (7/2, 1/3), (11/2, 16/3), (1, 16/3), (0, 1), (7, -2), (3, 4), (8, 1), (3, -1), (11, 0), and n = 10 further nails at positions (1, 1), (3, 1), (4, 4), (1, 3), (2, 2), (5, -1), (5, 0), (6, 2), (7, 1), (6, 0). The following three plots show the process described above:

For larger version: Right-click --> Open in new tab

And here is an animation of the rubber band tightening if you have some difficulty visualising it:

The Challenge

Given two lists of "nails", plot the taut rubber band around the second list if it starts from the shape traversing all the nails in the first list.

You may write a program or function and take input via STDIN, ARGV or function argument. You can either display the result on the screen or save an image to a file.

If the result is rasterised, it needs to be at least 300 pixels on each side. The final rubber band and nails must cover at least 75% of the horizontal and vertical extent of the image. The length scales of x and y have to be the same. You need to show the nails in the second set (using at least 3x3 pixels) and the string (at least 1 pixel wide). You may or may not include the axes.

Colours are your choice, but you need at least two distinguishable colours: one for the background and one for the nails and the string (those may have different colours though).

You may assume that all nails in the second list are at least 10-5 units away from initial shape of the rubber band (so that you don't need to worry about floating-point inaccuracy).

This is code golf, so the shortest answer (in bytes) wins.

More Examples

Here are two more examples:

{{1, 1}, {3, 3}, {2, 4}, {1, 3}, {4, 0}, {3, -1}, {2, 0}, {4, 2}}
{{2, 1}, {3, 2}, {1, 2}, {4, 1}}

{{1, 1}, {3, 1}, {3, 3}, {1, 3}, {1, 5}, {3, 5}, {-1, 3}, {-1, 0}, {3, 4}, {5, 1}, {5, -1}, {7, -1}, {3, 7}, {7, 5}}
{{0, 0}, {0, 2}, {0, 4}, {0, 6}, {2, 0}, {2, 2}, {2, 4}, {2, 6}, {4, 0}, {4, 2}, {4, 4}, {4, 6}, {6, 0}, {6, 2}, {6, 4}, {6, 6}}

And here is one example that shows the significance of two of the initial nails remaining. The result should be b and not a:

{{0, 0}, {0, 1}, {-1, 1}, {-1, -1}, {1, -1}, {1, 0}}
{{-0.5, 0.5}}

Thanks to Ell for providing this example.

Python + matplotlib, 688

from pylab import*
C=cross
P,M=eval("map(array,input()),"*2)
P,N=[[P[0]]+L+[P[-1]]for L in P,M]
W=[.5]*len(P)
def T(a,c,b):
 I=[(H[0]**2,id(n),n)for n in N for H in[(C(n-a,b-a),C(n-b,c-b),C(n-c,a-c))]if(min(H)*max(H)>=0)*H[1]*H[2]]
 if I:d=max(I)[2];A=T(a,c,d);B=T(d,c,b);return[A[0]+[d]+B[0],A[1]+[sign(C(c-a,b-c))]+B[1]]
 return[[]]*2
try:
 while 1:
    i=[w%1*2or w==0for w in W[2:-2]].index(1);u,a,c,b,v=P[i:i+5];P[i+2:i+3],W[i+2:i+3]=t,_=T(a,c,b);t=[a]+t+[b]
    for p,q,j,k in(u,a,1,i+1),(v,b,-2,i+len(t)):x=C(q-p,c-q);y=C(q-p,t[j]-q);z=C(c-q,t[j]-q);d=sign(j*z);W[k]+=(x*y<=0)*(x*z<0 or y*z>0)*(x!=0 or d*W[k]<=0)*(y!=0 or d*W[k]>=0)*d
except:plot(*zip(*P))
if M:scatter(*zip(*M))
show()

Reads two lists of points from STDIN.

Example

[(0, 0), (2, -1), (3.0/2, 4.0/3), (7.0/2, 1.0/3), (11.0/2, 16.0/3), (1, 16.0/3), (0, 1), (7, -2), (3, 4), (8, 1), (3, -1), (11, 0)]
[(1, 1), (3, 1), (4, 4), (1, 3), (2, 2), (5, -1), (5, 0), (6, 2), (7, 1), (6, 0)]

How it works

The key to the solution is to work in small, incremental steps.
Instead of trying to figure out what happens when we remove all the nails at once, we concentrate on the direct effects of removing just a single nail.
We can then remove the nails one by one in an arbitrary order.

Working incrementally means that we must keep track of the intermediate state of the rubber band.
Here's the tricky part: merely keeping track of which nails the band runs through is not enough.
During the process of removing nails the band can get wound and later unwound around a nail.
Therefore, when the band interacts with a nail we must keep track of how many times and in what direction it wraps around it.
We do it by assigning a value to each nail along the band like so:

Note that:

We start counting as soon as the band is tangent to the nail, even though the nail doesn't strictly affect its shape.
Recall that, unlike the illustration, our nails are dimensionless.
Therefore, if the band becomes tangent to a nail we can't tell which side of the band the nail is on by its position alone---we must keep track of where it used to be relative to the band.
We keep around nails with a value of zero, that is, nails that used to, but no longer hold the band, instead of removing them right away.
If we did, it could trigger an unwelcomed chain reaction, while we're trying to keep the effects of each step localized.
Instead, nails with a value of zero are considered eligible for removal as part of the bigger process.

Now we can describe what happens at each step:

We select a nail to remove from the band's current path.
A nail is eligible for removal if it's part of the first set of nails (save for the endpoints) or if its value is zero.
Pretending that the two neighboring nails are fixed, we figure out which nails from the second set or the pair of endpoints the band is going to run through once the selected nail is removed (we don't bother with the rest of the nails from the first set, since they'll eventually all be removed.)
We do it in a similar fashion to the solution to Part I.
All these nails are on the same side of the band, hence we assign to all of them a value of 1 or -1, depending on the side.
We update the value of the two neighboring nails to reflect the changes to the band's path (easily the trickiest part!)

This process is repeated until there are no more nails to remove:

And here's a more complicated example illustrating the band wrapping around a nail several times:


Display powers of Phi with Fibonacci precision Write some code that takes a single non-negative integer \$n\$ and outputs the \$n\$th power of phi (\$\phi\$, the Golden Ratio, approximately 1.61803398874989) with the same number of decimal digits as the \$n\$th Fibonacci number.
Your code must produce the correct sequence of digits for all inputs up to at least 10 (55 decimal digits). The output must be human-readable decimal. You may choose whether to round the last digit to the closest value, or truncate the value. Please specify which one your code uses.
\$n\$ and output, up to 10, rounding down:
 0   1
 1   1.6
 2   2.6
 3   4.23
 4   6.854
 5  11.09016
 6  17.94427190
 7  29.0344418537486
 8  46.978713763747791812296
 9  76.0131556174964248389559523684316960
10 122.9918693812442166512522758901100964746170048893169574174

\$n\$ and output, up to 10, rounding to the closest value:
 0   1
 1   1.6
 2   2.6
 3   4.24
 4   6.854
 5  11.09017
 6  17.94427191
 7  29.0344418537486
 8  46.978713763747791812296
 9  76.0131556174964248389559523684316960
10 122.9918693812442166512522758901100964746170048893169574174

The 7th Fibonacci number is 13, so the output for \$n=7\$, \$\phi^7\$, has 13 decimal places. You must not truncate trailing zeros that would display too few digits; see output for 6 in the first table, which ends in a single zero to keep the decimal precision at 8 digits.
Maybe as a bonus, say what the highest number your program can correctly output is.

dc, 26 bytes

99k5v1+2/?^d5v/.5+0k1/k1/p

Due to the initial precision of 99 digits after the comma, this will work up yo input 11. A dynamic (or higher static) precision is possible, but would elevate the byte count.

Test cases

$ for ((i = 0; i < 11; i++)) { dc -e '99k5v1+2/?^d5v/.5+0k1/k1/p' <<< $i; }
1
1.6
2.6
4.23
6.854
11.09016
17.94427190
29.0344418537486
46.978713763747791812296
76.0131556174964248389559523684316960
122.9918693812442166512522758901100964746170048893169574174

How it works

Since the desired output is φn, we can calculate the the Fibonacci number F(n) as ⌊φn ÷ √5 + 0.5⌋ with little additional effort.

99k                         Set the precision to 99.
   5v                       Compute the square root of 5.
     1+                     Add 1.
       2/                   Divide by 2.
                            This pushes the golden ratio.
         ?                  Read the input from STDIN.
          ^                 Elevate the golden ratio to that power.
           d                Push a copy.
            5v/             Divide it by the square root of 5.
               .5+          Add 0.5.
                  0k        Set the precision to 0.
                    1/      Divide by 1, truncating to the desired precision.
                            This pushes F(n).
                      k     Set the precision to F(n).
                       1/   Divide by 1, truncating to the desired precision.
                         p  Print.


Filter a large file in small memory The challenge is a follow-up to Filter a large file quickly  which had two submissions where were as fast as wc!  This time the difficulty is that RAM is severely restricted which means that new methods will have to be used.

Input: Each line has three space separated positive integers.
Output: All input lines A B, Tthat satisfy either of the following criterion.

There exists another input line C, D, U where D = A and 0 <= T - U < 100.
There exists another input line C, D, U where B = C and 0 <= U - T < 100.

To make a test file use the following python script which will also be used for testing. It will make a 1.3G file. You can of course reduce nolines for testing.

import random
nolines = 50000000 # 50 million
for i in xrange(nolines):
    print random.randint(0,nolines-1), random.randint(0,nolines-1), random.randint(0,nolines-1)

Rules. Your code must use no more than 200MB of RAM.  I will enforce this using ulimit -v 200000.    Your code must therefore also run on ubuntu using only easily installable and free software.

Score. You can report your unofficial score by testing on your machine as (the time in seconds needed by Keith Randall's submission from Filter a large file quickly divided by the time in seconds taken by your submission )*100 .

Winning criterion. The winner will be the one with the highest score when I test the code on my computer using a file created by the sample python code.  I will first run

sync && sudo bash -c 'echo  3 > /proc/sys/vm/drop_caches'

before each test run.

The deadline is one week from the time of the first correct entry.

My Machine The timings will be run on my machine. This is a standard 8GB RAM ubuntu install on an AMD FX-8350 Eight-Core Processor.  This also means I need to be able to run your code.

Some relevant timing information

largefile.file is a file created using the sample python code.

sync && sudo bash -c 'echo  3 > /proc/sys/vm/drop_caches'

time wc largefile.file

real    0m26.835s
user    0m18.363s
sys     0m0.495s

time sort -n largefile.file  > /dev/null

real    1m32.344s
user    2m9.530s
sys     0m6.543s

Tcl with SQLite, score less than 0.05

Shove the lines into an SQL database, then make SQLite do the work.  Requires the Tcl bindings for SQLite 3, OpenBSD package sqlite3-tcl, Ubuntu package libsqlite3-tcl.

Usage: tclsh filter.tcl <input.txt >output.txt

package require sqlite3

sqlite3 db ""
db eval {
    begin transaction;
    create table lines(i integer primary key,
               a integer, b integer, t integer);
}
while {[gets stdin line] >= 0} {
    lassign [split $line] a b t
    db eval {insert into lines values(null,$a,$b,$t)}
}
db eval {
    create view pairs as
      select first.i, second.i as j
      from lines as first, lines as second
      where first.a == second.b and
        first.t - second.t between 0 and 99 and
        first.i != second.i;
    select a, b, t from lines
      where i in (select i from pairs union select j from pairs);
} {
    puts "$a $b $t"
}
db close

Comparison of time

The motto of SQLite is, "Small. Fast. Reliable. Choose any three," but my SQL query is not fast. My program took more than six hours with my slow hard disk. I compare times for three programs:

cfilter is the large-memory C program by Keith Randall
hfilter is the large-memory C program by James_pic
filter.tcl is my small-memory Tcl program

With 50 million lines of input, cfilter and hfilter both crash because my data size limit is only 1 GB. (The default limit in OpenBSD is 512 MB.) If I raise my limit to 8 GB with ulimit -Sd 8388608, then I can run both cfilter and hfilter. I also lower my physical memory limit with -m 3000000 so that other programs stay in RAM, not in swap space. I have only 4 GB of RAM.

$ ulimit -Sd 8388608 -m 3000000
$ time ./cfilter input.txt >output.txt
    0m9.03s real     0m5.17s user     0m1.97s system
$ ln -sf input.txt test.file
$ time ./hfilter >output2.txt
    0m25.62s real     0m22.08s user     0m2.04s system
$ time tclsh8.6 filter.tcl <input.txt >output3.txt
^Z  371m19.57s real     0m0.00s user     0m0.00s system
[1] + Suspended            tclsh8.6 filter.tcl < input.txt > output3.txt

I suspended filter.tcl after more than 6 hours. top shows that filter.tcl used less than 15 MB of memory and less than 12 minutes of processor time. Most of the 6 hours went to wait for my slow hard disk (5400 rpm).

For score, 10 seconds for cfilter, divided by more than 6 hours for filter.tcl, times 100, equals less than 0.05.

Comparison of results

The different filters do not select the same lines!  Consider these 6 lines of input:

$ cat example.txt
1 801 33
802 1 33
2 803 499
804 2 400
805 2 400
3 3 555

My filter.tcl outputs five lines, all except 3 3 555.

$ tclsh8.6 filter.tcl <example.txt
1 801 33
802 1 33
2 803 499
804 2 400
805 2 400

But cfilter only outputs three lines:

$ ./cfilter example.txt
804 2 400
805 2 400
2 803 499

cfilter seems to have a bug when T - U == 0. It fails to output the lines 1 801 33 and 802 1 33, though I believe them to be a matching pair.

Now for hfilter and the Scala program by the same author:

$ ln -sf example.txt test.file
$ ./hfilter
804 2 400
2 803 499
805 2 400
2 803 499
3 3 555
3 3 555
$ scala Filterer example.txt /dev/stdout
804 2 400
2 803 499
802 1 33
1 801 33
805 2 400
2 803 499
3 3 555
3 3 555

hfilter also misses the lines 1 801 33 and 802 1 33, but the Scala version finds them. Both programs output 2 803 499 twice (because it is in two matching pairs), but I might ignore such duplication. Both programs also output 3 3 355. This line is in a pair with itself because A = B. This is only correct if the phrase "another input line" includes the same line.

When the input is the random 50 million lines from the Python script, these differences might disappear. The probability that any matching pair has T - U = 0, or any line has A = B, is close to zero when the input has random numbers up to 50 million.


Physics golf: inclined shooting "And now for something, completely different."

An angry bird is shot at an angle β to the horizontal at a speed u. The ground is steep, inclined at an angle α. Find the horizontal distance q that the bird traveled before it hit the ground.

Make a function f(α, β, u) that returns the length q: the horizontal distance that the bird traveled before it hit the ground.

Constrains and notes:

-90 < α < 90.
0 < β < 180.
α is always smaller than β.
0 <= u < 10^9.
Assume acceleration due to gravity g = 10.
You may use radians instead of degrees for α, β.
Dimensions of u are irrelevant as long as they are consistent with g and q.
No air resistance or anything too fancy.

Shortest code wins.

See the wikipedia article on projectile motion for some equations.

Samples:

f(0, 45, 10) = 10
f(0, 90, 100) = 0
f(26.565, 45, 10) = 5
f(26.565, 135, 10) = 15

Java

Works for radians only
double q(double a, double b, double u){
          return (Math.abs(((-Math.tan(a)+(Math.tan(b)))*(u*u)*(0.2*(Math.cos(b)*Math.cos(b))))));
      }

Golfed Version (Thanks to Peter)
double z=u*Math.cos(b);return(Math.tan(b)-Math.tan(a))*z*z/5;

Maths Used:
q=u Cos(B) t
q tan(A) = u sin (B) t - .5 * 10 * t^2

- tan (A)  + tan(B) = 5q/u^2 sec^2 (B)
q =  [ - tan(A) + tan (B) ] u^2
    ---------------------
    sec^2(B)*5


Draw the Heart Shape Challenge
Draw a Heart shape

...as ASCII art!
Your art doesn't have to look exactly like mine, but it has to look like a Heart Shape.
The inside of of the heart has to contain the words "Love" at least 20 times
Rules

The program must write the art to the console.
Shortest code (in bytes, any language) wins.

The winner will be chosen on February 14th on Valentines Day

JavaScript [160 bytes]

The following code seems to be 160 bytes unformatted.

   ('l2v2l6v2'+  'e1l1v3l2'+
 'v3e1v7e1v7e1v7e1l2v6e1l4v5'+
'e1l6v4e1l8v3e1l7l3v2e1l9l3v1')
 .replace(/[lve]\d/g,function
   (c){return Array(-~c[1]).
      join({l:' ',v:'Love'
         ,e:'\n'}[c[0
             ]])})

Simply run this in the browser console (e.g. in Firebug or Chrome Dev Tools).


Create a Y2K disaster Your program can do anything you want. The only condition is that it perform as expected if the date is before 2000, and fails spectacularly afterward. Define spectacularly however you'd like.

For all those people who missed the first Y2K, here's your chance!

Answer with highest score wins.

Python

Real Y2K bugs are about the year being represented as a 2-digit number. And doing something wrong when that number overflows to 0. Such as this nuclear missile watchdog, launching all ICBMs if we haven't received a heartbeat message from HQ in 60 seconds.

import datetime, select, socket, sys

launch_icbm = lambda: (print("The only winning move is not to play"), sys.exit(11))
now  = lambda: int(datetime.datetime.now().strftime("%y%m%d%H%M%S"))
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(('0.0.0.0', 1957))
last_message_received = now()

while True:
    r, w, e = select.select([sock], [], [], 10)
    if sock in r:
        msg = sock.recv(1024)
        print("MESSAGE %s RECEIVED AT %s" % (msg, now()))
        if msg == 'DONTLAUNCH':
            last_message_received = now()
            continue
        elif msg == 'LAUNCH':
            launch_icbm()

    # Is HQ dead?
    abs(now() - last_message_received) > 60 and launch_icbm()


Create a Twitter Parser Introduction

You use Twitter (let's pretend, if not), where you are limited to 140 characters per individual tweet you care to share with the world. If you wanted to tweet to your followers Abraham Lincoln's Gettysburg Address, then you would need to break up the text into multiple 140-character chunks in order to get the whole message out. However, those chunks should not always be exactly 140 characters long. Say for example, we broke the speech into 17-character chunks, we'd end up with these tweets:

FOUR SCORE AND SE
VEN YEARS AGO OUR
FATHERS BROUGHT
FORTH ON THIS CON
TINENT A NEW NATI
ON CONCEIVED IN L
(and so on)

That's no good! When individual words are broken up, then it can get difficult to understand what you are trying to say. Also, in the twitterverse, one of your followers may come across a specific tweet and not realize that there's more to the message, so you'll want to number your tweets so they have some context to work with (still using 17-character chunks):

(1/7) FOUR SCORE AND
(2/7) SEVEN YEARS AGO
(3/7) OUR FATHERS
(4/7) BROUGHT FORTH ON
(5/7) THIS CONTINENT A
(6/7)  NEW NATION
(7/7) CONCEIVED IN...

You could manually figure out the best configuration for your tweets by hand, but that's what we have computers for!

Challenge

In the shortest code possible, parse the Gettysburg Address (or any text, but we'll stick with this one as an example) into a set of tweets consisting of no more than 140 characters (assume ASCII, since our example text should not have any uncommon/unusual bits in it).

Details

Your function/program/etc should take in a single string argument and output one line of text for each tweet.

Assume this input will never result in more than 99 total tweets when parsed, regardless of how you choose to parse (so long as that choice still fits the other points of the challenge).

Tweets need to include a tweet number of total tweets indicator in the format "(x/y)" preceding the body of the tweet.

This count will take up part of your 140-character space!

Tweet chunks may only be split on newlines or spaces.

No hyphens, periods, commas or other punctuation is allowed, unless immediately preceded or followed by a space or newline.

Tweets should consist of as many complete words as possible.

This constraint is a little flexible, e.g. when your final tweet only has one word

This is code golf, so the shortest code wins.

Full Text of Gettysburg Address

(Your code should still be able to handle any ASCII string passed to it.)

  FOUR SCORE AND SEVEN YEARS AGO OUR FATHERS BROUGHT FORTH ON THIS CONTINENT A NEW NATION CONCEIVED IN LIBERTY AND DEDICATED TO THE PROPOSITION THAT ALL MEN ARE CREATED EQUAL.
  NOW WE ARE ENGAGED IN A GREAT CIVIL WAR TESTING WHETHER THAT NATION OR ANY NATION SO CONCEIVED AND SO DEDICATED CAN LONG ENDURE. WE ARE MET ON A GREAT BATTLEFIELD OF THAT WAR. WE HAVE COME TO DEDICATE A PORTION OF THAT FIELD AS A FINAL RESTING PLACE FOR THOSE WHO HERE GAVE THEIR LIVES THAT THAT NATION MIGHT LIVE. IT IS ALTOGETHER FITTING AND PROPER THAT WE SHOULD DO THIS. BUT IN A LARGER SENSE WE CAN NOT DEDICATE, WE CAN NOT CONSECRATE, WE CAN NOT HALLOW, THIS GROUND. THE BRAVE MEN LIVING AND DEAD WHO STRUGGLED HERE HAVE CONSECRATED IT FAR ABOVE OUR POOR POWER TO ADD OR DETRACT. THE WORLD WILL LITTLE NOTE NOR LONG REMEMBER WHAT WE SAY HERE BUT IT CAN NEVER FORGET WHAT THEY DID HERE. IT IS FOR US THE LIVING RATHER TO BE DEDICATED HERE TO THE UNFINISHED WORK WHICH THEY WHO FOUGHT HERE HAVE THUS FAR SO NOBLY ADVANCED. IT IS RATHER FOR US TO BE HERE DEDICATED TO THE GREAT TASK REMAINING BEFORE US, THAT FROM THESE HONORED DEAD WE TAKE INCREASED DEVOTION TO THAT CAUSE FOR WHICH THEY GAVE THE LAST FULL MEASURE OF DEVOTION, THAT WE HERE HIGHLY RESOLVE THAT THESE DEAD SHALL NOT HAVE DIED IN VAIN, THAT THIS NATION UNDER GOD SHALL HAVE A NEW BIRTH OF FREEDOM, AND THAT GOVERNMENT OF THE PEOPLE BY THE PEOPLE FOR THE PEOPLE SHALL NOT PERISH FROM THE EARTH.

Python, 140

^ 140 chars was actually a coincidence.

def f(s):
 s=s.split();i=0;l=[]
 while s:
  i+=1;t='(%d/%%d)'%i
  while s and len(t+s[0])<140:t+=' '+s.pop(0)
  l+=[t]
 for t in l:print t%i

While there are words left, the solution will create new tweets from the supply of words and append them to a list. For each tweet, it will keep trying to add words until the tweet's length reaches over 140 characters. Two characters are reserved for the total tweets, which are filled in later as each tweet in the list is printed.

Example output:

(1/11) FOUR SCORE AND SEVEN YEARS AGO OUR FATHERS BROUGHT FORTH ON THIS CONTINENT A NEW NATION CONCEIVED IN LIBERTY AND DEDICATED TO THE
(2/11) PROPOSITION THAT ALL MEN ARE CREATED EQUAL. NOW WE ARE ENGAGED IN A GREAT CIVIL WAR TESTING WHETHER THAT NATION OR ANY NATION SO
(3/11) CONCEIVED AND SO DEDICATED CAN LONG ENDURE. WE ARE MET ON A GREAT BATTLEFIELD OF THAT WAR. WE HAVE COME TO DEDICATE A PORTION OF THAT
(4/11) FIELD AS A FINAL RESTING PLACE FOR THOSE WHO HERE GAVE THEIR LIVES THAT THAT NATION MIGHT LIVE. IT IS ALTOGETHER FITTING AND PROPER
(5/11) THAT WE SHOULD DO THIS. BUT IN A LARGER SENSE WE CAN NOT DEDICATE, WE CAN NOT CONSECRATE, WE CAN NOT HALLOW, THIS GROUND. THE BRAVE
(6/11) MEN LIVING AND DEAD WHO STRUGGLED HERE HAVE CONSECRATED IT FAR ABOVE OUR POOR POWER TO ADD OR DETRACT. THE WORLD WILL LITTLE NOTE NOR
(7/11) LONG REMEMBER WHAT WE SAY HERE BUT IT CAN NEVER FORGET WHAT THEY DID HERE. IT IS FOR US THE LIVING RATHER TO BE DEDICATED HERE TO THE
(8/11) UNFINISHED WORK WHICH THEY WHO FOUGHT HERE HAVE THUS FAR SO NOBLY ADVANCED. IT IS RATHER FOR US TO BE HERE DEDICATED TO THE GREAT
(9/11) TASK REMAINING BEFORE US, THAT FROM THESE HONORED DEAD WE TAKE INCREASED DEVOTION TO THAT CAUSE FOR WHICH THEY GAVE THE LAST FULL
(10/11) MEASURE OF DEVOTION, THAT WE HERE HIGHLY RESOLVE THAT THESE DEAD SHALL NOT HAVE DIED IN VAIN, THAT THIS NATION UNDER GOD SHALL HAVE
(11/11) A NEW BIRTH OF FREEDOM, AND THAT GOVERNMENT OF THE PEOPLE BY THE PEOPLE FOR THE PEOPLE SHALL NOT PERISH FROM THE EARTH.


Pascal's Pyramid and Higher Dimensions Pascal's Triangle is a familiar mathematical construct with many interesting properties.  It is constructed by starting with a 1 on top, and generating the numbers in the next row from the sum of the number to the left and right in the row above (with implied 0's around the boundary):

    1
   1 1
  1 2 1
 1 3 3 1
1 4 6 4 1

The Triangle can be expanded into N dimensions by using the same rules. For example, the 3-D Pascal's Triangle would be a pyramid with each row being a cross-section of the pyramid, i.e., a triangle.  Each triangle's entry is generated by adding the three numbers in the "row" above forming a triangle directly above that entry.  An example of the first four "rows" is shown below:

1

 1
1 1

  1
 2 2
1 2 1

   1
  3 3
 3 6 3
1 3 3 1

The 4-D Pascal's Triangle would have a 3-D Pascal's Triangle for the cross section, and so forth.

Your task is to write a program that takes as input the dimension of the Pascal's Triange, and a row index to display.  The row index starts at 0, so row 0 is 1 for every dimension.  Your program should abide by the following specifications:

Take input N = dimension number, R = row number (0-based). The input can be either command-line arguments or from stdin.  N >= 2, R >= 0
Output the R'th row in the N-dimensional Pascal's Triangle, by displaying each row or triangle on a separate line as in the above example.
The format can vary as long as it is 'triangle-like' and obvious where each row and entry in the row belongs with respect to other rows.

Here is some sample output (I believe these are correct):

>./pascal 2 5
1 5 10 10 5 1
>./pascal 3 4
        1
      4   4
    6  12   6
  4  12  12   4
1   4   6   4   1
>./pascal 4 3
1

 3
3 3

  3
 6 6
3 6 3

   1
  3 3
 3 6 3
1 3 3 1
>./pascal 5 2
1

2

 2
2 2

1

 2
2 2

  1
 2 2
1 2 1

Bonus: What is the significance of each "row" in an N-dimensional Pascal's triangle?  I can think of at least three interesting facts.


Find the C-factor of a vote In this challenge you will be determining how controversial a vote is, given an array of other votes, by figuring out a number called the C-factor. What is the C-factor, you ask?
Well, imagine you've got multiple votes on an election. We'll use 1 and 0 for the sake of the challenge to represent two different candidates in an election. Here's the ten votes in our sample election:
0110111011

Now, say we want to find the C-factor of any vote for candidate 0. We can do that with the following function:
$$
f(o,v) = abs(o-mean(v))
$$
In \$f\$, o is the vote we want to determine the C-factor for, and v is an array of votes. So, using our function, to get the C-factor of any vote for candidate 0:
$$
f(0, [0,1,1,0,1,1,1,0,1,1]) = 0.7
$$
A lower C-factor shows that the vote was less controversial in comparison to the other votes. So, a vote for candidate 0 is more different from the other votes than a vote for candidate 1. In comparison, the C-factor for a candidate 1 vote is \$0.3\$, so it is less controversial because it is more like the other votes.
The Challenge
Write a function \$f(o,v)\$ to determine the C-factor of a vote o given results of a vote v.

o must be an integer, either 0 or 1.

v must be an array (or similar container type depending on language specifications) of arbitrary length containing zeroes and ones.

The function should return or print to the console the resulting C-factor given the function parameters, using the formula above or a modified method.

Good luck! The least bytes wins (winner chosen in five days).

R, 23 bytes

function(o,v)mean(o!=v)

Try it online!

The challenge boils down to computing the proportion of values in v different from o (i.e. mean(xor(o,v))). We can therefore avoid using abs.


Build a "BizzFuzz" program In traditional FizzBuzz, you are asked to print the numbers from 1 to 100, but replacing every multiple of 3 with "Fizz", every multiple of 5 with "Buzz", and every multiple of both 3 and 5 (i.e. 15) with "FizzBuzz".

However, as an evil interviewer, I've invented my own twisted version of FizzBuzz, which I've decided to name BizzFuzz and give to you in a coding interview.

The rules of the game are:

Print each number from 1 to 100, except if the number meets one of the conditions below.

If the number is divisible by 4, print "Fizz".
If the number is divisible by 5, print "Buzz".
If the number is divisible by 4, but the number immediately after it is divisible by 5, print "FizzBuzz" instead of "Fizz", and print the next number regularly.
If the number is divisible by 5, but the number immediately after it is divisible by 4, print "BuzzFizz" instead of "Buzz", and print the next number regularly.
If the number is immediately before a number divisible by both 4 and 5, print "Bizz".
If the number is immediately after a number divisible by both 4 and 5, print "Fuzz".
If the number is divisible by both 4 and 5, print "BizzFuzz".

The shortest code to implement all these rules in any language wins.

Python, 114
a='Fizz'
b='Buzz'
c='Bizz'
d='Fuzz'
e=c+d
f=a+b
g=b+a
i=1
exec"print eval('ediifiiiaibiaiigiiic'[i%20]);i+=1;"*100

Original solution (131):
f='Fizz'
for i in range(1,101):x=i%20;print('Bizz'*(x%19<1)+'Fuzz'*(x<2)or(i%4<1)*f+'Buzz'*(i%5<1or x==4)+f*(x==15)or i,i)[x%11==5]


Where are the runs in this infinite string? (CCCCCC Found!) Starting with the string ABC, consider the result of repeatedly appending the last half of itself to itself (using the larger half if the length is odd).
We get the progression:
ABC
ABCBC
ABCBCCBC
ABCBCCBCCCBC
ABCBCCBCCCBCBCCCBC
etc...

Let S represent the resulting infinite string (or sequence) that results as this procedure is repeated forever.
Goal
The goal in this code challenge is to find the index of the first occurrence of runs of C's in S.
It's easy at first: C first occurs at index 2, CC at 4, CCC at 7, CCCC at 26, but CCCCC is all the way at index 27308! After that my memory runs out.
The winner will be the submission that correctly generates the most run indices (in order, starting at C). You can use any sort of algorithm but be sure to explain it if you aren't using basic brute force. The input and output can be in any easy to understand format.
Important Note: I do not officially know whether or not S actually contains all runs of C's. This question is derived from this one on the Mathematics Stack Exchange, in which the author hasn't found CCCCCC either. I'm curious if anyone here can.  (That question is in turn based on my original question on the topic.)
If you can prove that not all runs of C occur in S then you will win automatically since this question will no longer be valid. If no one can prove that nor find CCCCCC then the winner will be the person who can get the highest lower bound on the index of CCCCCC (or whatever the largest unsolved run is if CCCCCC is found).
Update: Humongous kudos to isaacg and r.e.s. who have found CCCCCC at the astronomical index of 2.124*10^519. At this rate I can't imagine finding CCCCCCC with any method that relies on brute force. Good work guys!

CCCCCC found at 2.124*10^519.
Precise index is 2124002227156710537549582070283786072301315855169987260450819829164756027922998360364044010386660076550764749849261595395734745608255162468143483136030403857241667604197146133343367628903022619551535534430377929831860918493875279894519909944379122620704864579366098015086419629439009415947634870592393974557860358412680068086381231577773140182376767811142988329838752964017382641454691037714240414750501535213021638601291385412206075763857490254382670426605045419312312880204888045665938646319068208885093114686859061215
Found by r.e.s., using the (old version of) code below, after 3.5 hours of searching.
Around that index, the string is: ...BCCBCBCCCBCCCCCCBCCB...
To verify, change the indicated line in the code below to start at 2946, instead of 5. Verification takes 20 seconds.
Update: Improved program. Old program searched ~10x more locations than necessary.
New version finds the CCCCCC in only 33 minutes.
How the code works: Basically, I only look at the regions which correspond to the ends of incremental strings, and calculate the letters by looking recursively back to the original string. Note that it uses a memo table, which may fill up your memory. Put a cap on the length of the memo table if necessary.
import time
import sys
sys.setrecursionlimit(4000)
ULIMIT=4000
end_positions=[]
current_end=2
while len(end_positions)<ULIMIT+3:
    end_positions.append(current_end)
    next_end=((current_end+1)*3+1)//2-1
    current_end=next_end
memo={}
def find_letter(pos):
    if pos in memo:
        return memo[pos]
    if pos<3:
        return 'ABC'[pos]
    for end_num in range(len(end_positions)-1):
        if pos>end_positions[end_num] and pos<=end_positions[end_num+1]:
            delta=end_positions[end_num+1]-end_positions[end_num]
            if len(memo)>5*10**6:
                return find_letter(pos-delta)
            memo[pos]=find_letter(pos-delta)
            return memo[pos]
time.clock()
for end_num in range(5,ULIMIT+1): # This line.
    diff = 1 # Because end_num is guaranteed to be a C
    while True:
        last_letter=find_letter(end_positions[end_num]+diff)
        if not last_letter=='C':
            break
        diff+=1
    if end_num%100==0:
        pos_str=str(end_positions[end_num])
        print(end_num,'%s.%s*10^%i'%(pos_str[0],pos_str[1:5],len(pos_str)-1),
        len(memo),diff,time.clock())
    if diff>=6:
        print(end_num,end_positions[end_num],diff,time.clock())

Current max searched to: 4000 iterations
CCCCCC found at iteration(s):
2946


Counterfeit Coins on a Pointer Scale You sell gold coins. Each gold coin you sell is supposed to be 1 ounce. However, you find out that one of your coin suppliers is cheating you. By alloying the gold material with something else, their coins weigh only 0.9 ounces. With a help of a pointer scale (one that shows the exact weight of a quantity of matter set on it), you want to determine which of your coin suppliers is selling you the counterfeit coins.

Apparently, you are not the only one to have this problem - lots of gold sellers buy coins from this supplier, and the supplier knows that it is being dodgy and is changing their branding accordingly. All of these sellers have the same problem - 1 ounce coins that end up being 0.9 ounces from this supplier - and need to solve it, fast! How can you determine, out of n suppliers, which one is the cheating supplier with the minimum number of weighings on the pointer scale?

Your task is to write a program function that can solve this problem automatically for n suppliers. It's input includes:

an integer number of suppliers, n,
an oracle function that represents weighing a set of coins on the balance scale

It must take this information, calling this function a minimum number of times and returning, as output, the index number of the cheating supplier.

The oracle function has the following specifications:

It takes as input an int->int mapping (as an array or dictionary, whichever your language prefers) mapping each supplier index (from 0 to n-1) to a number of gold coins that you want to try weighing on the scale.
The returned output is the total weight, in ounces, of the coins put on the scale.
The function is in whatever format your language prefers for passing procedures as data. For instance, functional languages will pass lambdas, C will take a function pointer, Java 7 and earlier will take a functional interface. Languages that support none of these, but do support string execution, will take these as strings.
In those cases when the oracle can be stringified or otherwise inspected as data, you may assume that it is sufficiently obfuscated such that you cannot tell which supplier is cheating without executing it.

This is also code-golf: among the solutions that call the function the minimum number of times, the smallest solution in bytes is the winner!

NOTE: If your language does not support functions at all, but does support string execution, write your program as a standalone program - assume that the number of suppliers, followed by the oracle, will be passed into standard input. If your language does not support string execution, assume that a file path to a binary oracle will be provided instead.

Python, 33 bytes

lambda n,f:n*~-n*5-f(range(n))*10

Puts 0 coins from supplier 0, 1 coin from supplier 1, ... n-1 coins from supplier n-1. The deficit is then 0.1 for each coin sent to the cheating supplier, so i/10. We therefore subtract the oracle value from the fair sum n*(n-1)/2 and multiply by 10. Distributing the *10 saved on parens for a shorter expression.


Counting groups of a given size Groups
In abstract algebra, a group is a tuple \$(G,\ast)\$, where \$G\$ is a set and \$\ast\$ is a function \$G\times G\rightarrow G\$ such that the following holds:

For all \$x, y, z\$ in \$G\$, \$(x\ast y)\ast z=x\ast(y\ast z)\$.

There exists an element \$e\$ in \$G\$ such that for all \$x\$ in \$G\$, \$x\ast e=x\$.

For each \$x\$ in \$G\$, there exists an element \$y\$ in \$G\$ such that \$x\ast y=e\$.

The order of a group \$(G,\ast)\$ is defined as the number of elements of \$G\$.
For each strictly positive integer \$n\$, there exists at least one group of order \$n\$. For example, \$(C_n,+_n)\$ is such a group, where \$C_n=\{0,...,n-1\}\$ and \$x+_ny=(x+y)\mod n\$.
Isomorphic groups
Let \$G:=\{1,2\}\$ and define \$\ast\$ by \$x\ast y=(x\times y)\mod3\$. Then \$1\ast1=1=2\ast2\$ and \$1\ast2=2=2\ast1\$.
Likewise, \$0+_20=0=1+_21\$ and \$0+_21=1=1+_20\$.
Although the elements and operations of the groups \$(G,\ast)\$ and \$(C_2,+_2)\$ have different names, the groups share the same structure.
Two groups \$(G_1,\ast_1)\$ and \$(G_2,\ast_2)\$ are said to be isomorphic if there exists a bijection \$\phi:G_1\rightarrow G_2\$ such that \$\phi(x\ast_1y)=\phi(x)\ast_2\phi(y)\$ for all \$x,y\$ in \$G_1\$.
Not all groups of the same order are isomorphic. For example, the Klein group is a group of order 4 that is not isomorphic to \$(C_4,+_4)\$.
Task
Write a program or function that accepts a non-negative integer n as input and prints or returns the number of non-isomorphic groups of order n.
Test cases
Input   Output
0       0
1       1
2       1
3       1
4       2
5       1
6       2
7       1
8       5
9       2
10      2
11      1
12      5
13      1
14      2
15      1
16      14
17      1
18      5
19      1
20      5

(taken from OEIS A000001)
Additional rules

There are no limits on execution time or memory usage.

Built-ins that trivialize this task, such as Mathematica's FiniteGroupCount, are not allowed.

Standard code-golf rules apply.

CJam, 189 187 bytes

This one's gonna be tough to explain... Time complexity is guaranteed to be O(scary).

qi:N_3>{,aN*]N({{:L;N,X)-e!{X)_@+L@@t}%{X2+<z{_fe=:(:+}%:+!},}%:+}fX{:G;N3m*{_~{G@==}:F~F\1m>~F\F=}%:*},:L,({LX=LX)>1$f{\_@a\a+Ne!\f{\:M;~{M\f=z}2*\Mff==}:|{;}|}\a+}fX]:~$e`{0=1=},,}{!!}?

If you're brave enough, try it online. On my crappy laptop I can get up to 6 with the Java interpreter or 5 in the online interpreter.

Explanation

I don't have a big math background (just finished high school, starting CS at uni next week). So bear with me if I make mistakes, state the obvious, or do things in horribly inefficent ways.

My approach is a brute force, though I tried to make it a little more clever. The main steps are:

Generate all the possible operands ∗ for a group of order n (i.e., enumerate all groups of order n);
Generate all the possible bijections φ between two groups of order n;
Using the results from steps 1 and 2, determine all isomorphisms between two groups of order n;
Using the result from step 3, count the number of groups up to isomorphism.

Before looking at the how each step is done, let's get some trivial code out of the way:

qi:N_             e# Get input as integer, store in N, make a copy
     3>{...}    ? e# If N > 3, do... (see below)
            {!!}  e# Else, push !!N (0 if N=0, 1 otherwise)

The following algorithm doesn't work correctly with n < 4, the cases from 0 to 3 are handled with a double negation.

From now on, the elements of a group will be written as {1, a, b, c, ...}, where 1 is the identity element. In the CJam implementation, the corresponding elements are {0, 1, 2, 3, ...}, where 0 is the identity element.

Let's start from step 1. Writing all possible operators for a group of order n is equivalent to generating all the valid n×n Cayley tables. The first row and column are trivial: they are both {1, a, b, c, ...} (left-to-right, up-to-down).

      e# N is on the stack (duplicated before the if)
,a    e# Generate first row [0 1 2 3 ...] and wrap it in a list
  N*  e# Repeat row N times (placeholders for next rows)
    ] e# Wrap everything in a list
      e# First column will be taken care of later

Knowing that a Cayley table is also a reduced Latin square (due to the cancellation property) allows to generate the possible tables row-by-row. Starting from the second row (index 1), we generate all the unique permutations for that row, keeping the first column fixed to the value of the index.

N({                                 }fX e# For X in [0 ... N-2]:
   {                            }%      e#   For each table in the list:
    :L;                                 e#     Assign the table to L and pop it off the stack
       N,                               e#     Push [0 ... N-1]
         X)                             e#     Push X+1
           -                            e#     Remove X+1 from [0 ... N-1]
            e!                          e#     Generate all the unique permutations of this list
              {         }%              e#     For each permutation:
               X)_                      e#       Push two copies of X+1
                  @+                    e#       Prepend X+1 to the permutation
                    L@@t                e#       Store the permutation at index X+1 in L
                          {...},        e#     Filter permutations (see below)
                                  :+    e#   Concatenate the generated tables to the table list

Not all those permutations are valid, of course: each row and column must contain all the elements exactly one time. A filter block is used for this purpose (a truthy value keeps the permutation, a falsy one removes it):

X2+                 e# Push X+2
   <                e# Slice the permutations to the first X+2 rows
    z               e# Transpose rows and columns
     {        }%    e# For each column:
      _fe=          e#   Count occurences of each element
          :(        e#   Subtract 1 from counts
            :+      e#   Sum counts together
                :+  e# Sum counts from all columns together
                  ! e# Negate count sum:
                    e#   if the sum is 0 (no duplicates) the permutation is kept
                    e#   if the sum is not zero the permutation is filtered away

Note that I am filtering inside the generation loop: this makes the code a bit longer (compared to distinct generation and filtering), but greatly improves performance. The number of permutations of a set of size n is n!, so the shorter solution would require a lot of memory and time.

A list of valid Cayley tables is a great step towards enumerating the operators, but being a 2D structure, it can't check for associativity, which is a 3D property. So next step is filtering out non-associative functions.

{                                 }, e# For each table, keep table if result is true:
 :G;                                 e#   Store table in G, pop it off the stack
    N3m*                             e#   Generate triples [0 ... N-1]^3
        {                     }%     e#   For each triple [a b c]:
         _~                          e#     Make a copy, unwrap top one
           {    }:F                  e#     Define function F(x,y):
            G@==                     e#       x∗y (using table G)
                   ~F                e#     Push a∗(b∗c)
                     \1m>            e#     Rotate triple right by 1
                         ~           e#     Unwrap rotated triple
                          F\F        e#     Push (a∗b)∗c
                             =       e#     Push 1 if a∗(b∗c) == (a∗b)∗c (associative), 0 otherwise
                                :*   e#   Multiply all the results together
                                     e#   1 (true) only if F was associative for every [a b c]

Phew! Lots of work, but now we have enumerated all groups of order n (or better, the operations on it - but the set is fixed, so it's the same thing). Next step: find isomorphisms. An isomorphism is a bijection between two of those groups such that φ(x ∗ y) = φ(x) ∗ φ(y). Generating those bijections in CJam is trivial: Ne! will do it. How can we check them? My solution starts from two copies of the Cayley table for x ∗ y. On one copy, φ is applied to all elements, without touching the order of rows or columns. This generates the table for φ(x ∗ y). On the other one the elements are left as they are, but rows and columns are mapped through φ. That is, the row/column x becomes the row/column φ(x). This generates the table for φ(x) ∗ φ(y). Now that we have the two tables, we just have to compare them: if they are the same, we have found an isomorphism.

Of course, we also need to generate the pairs of groups to test isomorphism on. We need all the 2-combinations of the groups. Looks like CJam has no operator for combinations. We can generate them by taking each group and combining it only with the elements following it in the list. Fun fact: the number of 2-combinations is n × (n - 1) / 2, which is also the sum of the first n - 1 natural numbers. Such numbers are called triangular numbers: try the algorithm on paper, one row per fixed element, and you'll see why.

:L                          e# List of groups is on stack, store in L
  ,(                        e# Push len(L)-1
    {                  }fX  e# For X in [0 ... len(L)-2]:
     LX=                    e#   Push the group L[X]
        LX)>                e#   Push a slice of L excluding the first X+1 elements
            1$              e#   Push a copy of L[X]
              f{...}        e#   Pass each [L[X] Y] combination to ... (see below)
                            e#   The block will give back a list of Y for isomorphic groups
                    \a+     e#   Append L[X] to the isomorphic groups
                          ] e# Wrap everything in a list

The code above fixes the first element of the pair, L[X], and combines it with other groups (let's call each one of those Y). It passes the pair to a isomorphism test block that I'll show in a moment. The block gives back a list of values of Y for which L[X] is isomorphic to Y. Then L[X] is appended to this list. Before understanding why the lists are set up in such a way, let's look at the isomorphism test:

\_@                                      e# Push a copy of Y
   a\a+                                  e# L[X] Y -> [L[X] Y]
       Ne!                               e# Generate all bijective mappings
          \f{                    }       e# For each bijection ([L[X] Y] extra parameter):
             \:M;                        e#   Store the mapping in M, pop it off the stack
                 ~                       e#   [L[X] Y] -> L[X] Y
                  {     }2*              e#   Repeat two times (on Y):
                   M\f=                  e#     Map rows (or transposed columns)
                       z                 e#     Transpose rows and columns
                                         e#     This generates φ(x) ∗ φ(y)
                           \Mff=         e#   Map elements of L[X], generates φ(x ∗ y)
                                =        e#   Push 1 if the tables are equal, 0 otherwise
                                  :|     e#   Push 1 if at least a mapping was isomorphic, 0 otherwise
                                    {;}| e#   If no mapping was isomorphic, pop the copy of Y off the stack

Great, now we have a list of sets like [{L[0], Y1, Y2, ...}, {L[1], Y1, ...}, ...]. The idea here is that, by transitive property, if any two sets have at least one element in common then all the groups in the two sets are isomorphic. They can be aggregated into a single set. As L[X] will never appear in the combinations generated by L[X+...], after aggregating each set of isomorphisms will have one unique element. So, to get the number of isomorphisms, it's sufficient to count how many groups appear exactly once in all sets of isomorphic groups. To do this, I unwrap the sets so they look like [L[0], Y1, Y2, ..., L[1], Y1, ...], sort the list to create clusters of the same group and finally RLE-encode it.

:~            e# Unwrap sets of isomorphic groups
  $           e# Sort list
   e`         e# RLE-encode list
     {    },  e# Filter RLE elements:
      0=      e#   Get number of occurrences
        1=    e#   Keep element if occurrences == 1
            , e# Push length of filtered list
              e# This is the number of groups up to isomorphism

That's all, folks.


100 Prisoners and a light bulb 100 Prisoners and a light bulb

You may have seen this puzzle over on the puzzles exchange or perhaps heard it somewhere else. If you are unfamiliar with this puzzle check out:  100 Prisoners and a Light bulb

The gist of this puzzle is that there are 100 prisoners, each one is separated from one another and must go into a room one at a time. The prisoner selected to go into the room is selected uniformly at random each time. In this room there is a light bulb and a switch, the prisoner must either turn the light on, turn the light off, or do nothing. At any given time one of the prisoners may say that all 100 prisoners have been in the room at least once. If he is correct they are all freed, if they are incorrect they are all killed. Prior to being separated the group of prisoners may discuss a strategy and they may never communicate again.

One working strategy:

  The prisoners select one prisoner as the leader. When anyone else enters the room they do nothing unless it's the first time they enter the room and the light is off; in that case, they turn the light on. When the leader enters the room and the light is on then he turns the light off and maintains a counter, adding one to it. Once he counts 99 (the light has been turned on once for every other prisoner) he knows that all 100 (including himself) have been in the room, and he claims their freedom.

The code challenge:

Take no input into your program.

Simulate the strategy and output the number of times a prisoner entered the room before the leader claimed their freedom.

n represents the number of times a prisoner enters the room for the first time.
k represents the leader of the prisoners.
d represents a data structure holding boolean values for each prisoner.
l represents a boolean value to hold the state of the light bulb.
i represents the number of iterations of the puzzle before it ends.

Examples:

Randomly pick an element from d. if l is false and k[rand] is false then l is now true and d[rand] is true. i = i + 1

Randomly pick an element from d. if l is true and d[rand] is false then do nothing. i = i + 1

Randomly pick an element from d. if l is false and d[rand] is true then do nothing. i = i + 1

Randomly pick an element from d. if d[rand] = k and if l is false then do nothing. i = i + 1

Randomly pick an element from d. if d[rand] = k and if l is true, set l to false, add 1 to n. i = i + 1

Randomly pick an element from d. if d[rand] = k and if l is true and n = 99 then end puzzle.  i = i + 1 and output i.

this is code-golf so the shortest code wins. Have Fun!

Python 2, 133 bytes
I used binary operations to keep track. I had if(i<1)*b:... but I think that's an off-by-one error. Not sure.

from random import*
L=2**99-1
b=l=c=0
while l<99:
    i=randint(0,99)
    if(i>98)*b:b=0;l+=1
    elif(L&1<<i)*(b<1):b=1;L|=1<<i
    c+=1
print c

Try it online
Less golfed:
from random import*
L=[1for _ in range(100)]
b=l=c=0
while l<99:                         # check leader's count of prisoners
    i=randint(0,99)
    if b and i==99:b=0;l+=1         # if light on and leader, turn off and count
    elif L[i] and b<1:b=1;L[i]=0    # else if new prisoner and light off, turn on
    c+=1                            # iterations
print c


Evaluate modular power towers Given two numbers n and m, evaluate the infinite power tower:

  n^(n+1)^(n+2)^(n+3)^(n+4)^... mod m

Keep in mind that ^ is right-associative. So 2^3^4 = 2^(3^4). Now how can  you possibly assign a value to an infinite sequence of right-associative operators?

Define f(n,m,i) as the power tower containing the first i terms of the infinite power tower. Then there is some constant C such that for every i > C, f(n,m,i) = f(n,m,C). So you could say the infinite power tower converges on a certain value. We're interested in that value.

Your program must be able to compute n = 2017, m = 10^10 in under 10 seconds on a reasonable modern PC. That is, you should implement an actual algorithm, no bruteforcing.

You may assume that n < 230 and m < 250 for the numerical limits in your programming language, but your algorithm must theoretically work for any size n, m. However your program must be correct for inputs within these size limits, intermediate value overflows are not excused if the inputs are within these limits.

Examples:

2, 10^15
566088170340352

4, 3^20
4

32, 524287
16

Pyth, 23 bytes

M&tG.^HsgBu-G/GH{PGGhHG

Defines a function g, taking m and n in that order.

Try it online

How it works

M&tG.^HsgBu-G/GH{PGGhHG
M                         def g(G, H):
 &tG                        0 if G == 1, else …
                 PG         prime factors of G
                {           deduplicate that
          u-G/GH   G        reduce that on lambda G,H:G-G/H, starting at G
                              (this gives the Euler totient φ(G))
        gB          hH      bifurcate: two-element list [that, g(that, H + 1)]
       s                    sum
    .^H               G     H^that mod G

Python 2, 109 76 bytes

import sympy
def g(n,m):j=sympy.totient(m);return m-1and pow(n,j+g(n+1,j),m)

Try it online!

Why it works

We use the following generalization of Euler’s theorem.

Lemma. n2φ(m) ≡ nφ(m) (mod m) for all n (whether or not n is coprime to m).

Proof: For all prime powers pk dividing m,

If p divides n, then because φ(m) ≥ φ(pk) = pk − 1(p − 1) ≥ 2k − 1 ≥ k, we have n2φ(m) ≡ 0 ≡ nφ(m) (mod pk).
Otherwise, because φ(pk) divides φ(m), Euler’s theorem gives n2φ(m) ≡ 1 ≡ nφ(m) (mod pk).

Therefore, n2φ(m) ≡ nφ(m) (mod m).

Corollary. If k ≥ φ(m), then nk ≡ nφ(m) + (k mod φ(m)) (mod m).

Proof: If k ≥ 2φ(m), the lemma gives nk = n2φ(m)nk - 2φ(m) ≡ nφ(m)nk - 2φ(m) = nk - φ(m) (mod m) and we repeat until the exponent is less than 2φ(m).


Is it a valid consonant cluster in Lojban? .i xu .e'o lo zunsnagri cu drani loka jboge'a

Given an input of a string consisting of two characters, output whether it is a
valid consonant cluster in Lojban.

Here is a quote from CLL 3.6 detailing the
rules for a valid consonant cluster pair (or rather, an invalid one):

1) It is forbidden for both consonants to be the same, as this would
   violate the rule against double consonants.

2) It is forbidden for one consonant to be voiced and the other unvoiced.
   The consonants “l”, “m”, “n”, and “r” are exempt from this restriction.
   As a result, “bf” is forbidden, and so is “sd”, but both “fl” and “vl”,
   and both “ls” and “lz”, are permitted.

3) It is forbidden for both consonants to be drawn from the set “c”, “j”,
   “s”, “z”.

4) The specific pairs “cx”, “kx”, “xc”, “xk”, and “mz” are forbidden.

The quote references "voiced" and "unvoiced" consonants. Here is a table of the
unvoiced consonants and their voiced counterparts (also from CLL 3.6):

UNVOICED    VOICED
   p          b
   t          d
   k          g
   f          v
   c          j
   s          z
   x          -

Note that {x} has no voiced counterpart. For completeness, the remaining
consonants that are not on this list (which can be either voiced or unvoiced
for the purposes of the quote) are lmnr. (y is a vowel, and the letters
hqw are not used.)

The input must be a single string, but you may assume that it will always
consist of exactly two consonants, with optional trailing newline if you wish.
The output may be any truthy or falsy
value.

This is code-golf, so the shortest code in bytes wins.

Test cases (these are all possible input strings placed in the proper
categories):

Valid consonant clusters:
 bd bg bj bl bm bn br bv bz cf ck cl cm cn cp cr ct db dg dj dl dm dn dr dv
 dz fc fk fl fm fn fp fr fs ft fx gb gd gj gl gm gn gr gv gz jb jd jg jl jm
 jn jr jv kc kf kl km kn kp kr ks kt lb lc ld lf lg lj lk lm ln lp lr ls lt
 lv lx lz mb mc md mf mg mj mk ml mn mp mr ms mt mv mx nb nc nd nf ng nj nk
 nl nm np nr ns nt nv nx nz pc pf pk pl pm pn pr ps pt px rb rc rd rf rg rj
 rk rl rm rn rp rs rt rv rx rz sf sk sl sm sn sp sr st sx tc tf tk tl tm tn
 tp tr ts tx vb vd vg vj vl vm vn vr vz xf xl xm xn xp xr xs xt zb zd zg zl
 zm zn zr zv

Invalid consonant clusters:
 bb bc bf bk bp bs bt bx cb cc cd cg cj cs cv cx cz dc dd df dk dp ds dt dx
 fb fd ff fg fj fv fz gc gf gg gk gp gs gt gx jc jf jj jk jp js jt jx jz kb
 kd kg kj kk kv kx kz ll mm mz nn pb pd pg pj pp pv pz rr sb sc sd sg sj ss
 sv sz tb td tg tj tt tv tz vc vf vk vp vs vt vv vx xb xc xd xg xj xk xv xx
 xz zc zf zj zk zp zs zt zx zz

Pyth, 53 48 47 bytes
!}z+"mz"s.pMs[+VGGc"xcxkcsjz"2*"ptkfcsx""bdgvjz

This generates a list of all invalid pairs based on the rules above, then checks if the input is one of them.
! }                        A not in B
    z                      input
    +
      "mz"                  "mz"
      s                    flattened
        .pM                permutations of each:
            s [               flatten the three-element array:
                +V              Alphabet vectorized concat with itself.
                   G            That is, duplicate letters
                   G
                c"xcxkcsjz"2     That string chopped every 2
                *               outer product of
                  "ptkfcsx"      voiced letters
                  "bdgvjz        and unvoiced letters

Try it here.


Calculate the longest series of 1's in an integer's binary value Goal

Given a non-negative integer, create a function that returns the starting position of number of largest consecutive 1's in that integer's binary value.

When given an input 0, return 0.

If the number has multiple streaks of equal length, you must return the position of the last streak.

Input

An integer greater than or equal to 0.

Output

An integer calculated as explained below.

Rules

This is code-golf, so the shortest code in bytes in each language wins.
Standard loopholes are forbidden.

Examples and Test Cases

Example 1

Your function is passed the integer 142
142 is equal to 10001110 in binary
Longest streak is "111" (a streak of three ones)
The streak starts at the 2^1 position
Your function returns 1 as the result

Example 2

Your function is passed the integer 48
48 is equal to 110000 in binary
Longest streak is "11" (a streak of two ones)
The streak starts at the 2^4 position
Your function returns 4 as the result

Example 3

Your function is passed the integer 750
750 is equal to 1011101110 in binary
Longest streak is "111" (a streak of three ones)
Since there are two streaks of equal length, we return the later streak.
The later streak starts at the 2^5 position
Your function returns 5 as the result

JavaScript (ES6),  33  32 bytes
f=x=>x&(k=x>>1)?f(x&k):k&&1+f(k)

Try it online!

JavaScript (ES6),  41 40 36  34 bytes
Saved 4 bytes thanks to @ThePirateBay
f=x=>(k=x&x/2)?f(k):Math.log2(x)|0

Try it online!
How?
General case x > 0
We recursively AND the input x with x / 2 which progressively reduces the patterns of consecutive set bits until only the rightmost bit of the sequence remains. We keep a copy of the last non-zero value and determine the position of its most significant bit by floor-rounding its base-2 logarithm.
Below are the steps we go through for x = 750 (1011101110 in binary).
    1011101110 --.
,----------------'
'-> 1011101110
AND 0101110111
    ----------
=   0001100110 --.
,----------------'
'-> 0001100110
AND 0000110011
    ----------
=   0000100010 --.  --> output = position of MSB = 5  (0000100010)
,----------------'                                         ^
'-> 0000100010
AND 0000010001
    ----------
=   0000000000

Edge case x = 0
The special case x = 0 immediately leads to Math.log2(0) | 0. The logarithm of 0 evaluates to -Infinity and the binary bitwise OR forces a coercion to a 32-bit integer. In compliance with the specification of the abstract operation ToInt32, this gives the expected 0:

If number is NaN, +0, −0, +∞, or −∞, return
+0


Which Ubuntu versions are supported? Given an input date, your entry will output the full list of supported versions of the Ubuntu Linux distro on that date.
The full list of all releases is as follows:

Version    Code name         Release date  Supported until

4.10       Warty Warthog     2004-10-20    2006-04-30
5.04       Hoary Hedgehog    2005-04-08    2006-10-31
5.10       Breezy Badger     2005-10-13    2007-04-13
6.06 LTS   Dapper Drake      2006-06-01    2009-07-14  2011-06-01 (Server)
6.10       Edgy Eft          2006-10-26    2008-04-25
7.04       Feisty Fawn       2007-04-19    2008-10-19
7.10       Gutsy Gibbon      2007-10-18    2009-04-18
8.04 LTS   Hardy Heron       2008-04-24    2011-05-12  2013-05-09 (Server)
8.10       Intrepid Ibex     2008-10-30    2010-04-30
9.04       Jaunty Jackalope  2009-04-23    2010-10-23
9.10       Karmic Koala      2009-10-29    2011-04-30
10.04 LTS  Lucid Lynx        2010-04-29    2013-05-09  2015-04-30 (Server)
10.10      Maverick Meerkat  2010-10-10    2012-04-10
11.04      Natty Narwhal     2011-04-28    2012-10-28
11.10      Oneiric Ocelot    2011-10-13    2013-05-09
12.04 LTS  Precise Pangolin  2012-04-26    2017-04-26
12.10      Quantal Quetzal   2012-10-18    2014-05-16
13.04      Raring Ringtail   2013-04-25    2014-01-27
13.10      Saucy Salamander  2013-10-17    2014-07-17
14.04 LTS  Trusty Tahr       2014-04-17    2019-04
14.10      Utopic Unicorn    2014-10-23    2015-07-23
15.04      Vivid Vervet      2015-04-23    2016-01
15.10      Wily Werewolf     2015-10-22    2016-07
16.04 LTS  Xenial Xerus      2016-04-21    2021-04

Rules

For each supported version, the exact version string will be output, e.g. 4.10
For LTS (long-term support) versions, LTS will be appended to the version
The three oldest LTS versions come in two flavours - desktop and server.  If both of these LTS versions are supported on the given date, the output will simply be the version string as above.  However if only the server version is supported, then you must append -server to the end of the version string
At the time of writing, 4 of the recent versions only have YYYY-MM in their supported-until dates.  You must treat these dates as if they are the last day of the given month.  e.g. 2019-04 must be treated as 2019-04-30
There will be no output for dates outside of the full date range captured in the table
Input date formats are flexible, but must contain some enumeration of Year, Month and Day.  Number of days or seconds (or other units) from an epoch are not valid input formats.
Output lists may be given in whatever format is convenient for your language
You may use datetime functions from your language
You may assume all inputs are valid

Examples:

Input:        Output:

2000-01-01
2004-10-20    4.10
2005-05-05    4.10, 5.04
2006-06-06    5.04, 5.10, 6.06LTS
2010-10-10    6.06LTS-server, 8.04LTS, 9.04, 9.10, 10.04LTS, 10.10
2021-04-30    16.04LTS
2021-05-01


Score my golf round! Since this SE community is about golfing, I thought a golf-related challenge would be appropriate.

Explanation

Normally, the objective of golf is to finish a hole (and consequently, the entire round) with the least amount of strokes. This is a simple version of golf: Play until you hole the ball and sum up your score. Finally subtract it from the total par and the resulting number indicates your score: 0 if you played exactly par, positive if you played worse and negative if you played better.

But in 1898 a guy named Dr. Frank Barney Gorton Stableford devised a new system of playing which was designed to be more forgiving. This system awards a number of points to a player, based on a relative rating per hole, called the stroke index (SI) which is based on a player rating called handicap. This limits the amount of points a player can lose per hole. Additionally, the handiccp ensures fair competition between players despite skill difference.

This format isn't used in professional golf, but can be found almost anywhere in amateur golf.

The scoring algorithm

For anyone unfamiliar with golf, the algorithm for scoring a hole based version is as follows.

Beginning with the hardest hole (rating 1) to the easiest one (rating 18), increase the stroke index of that hole by 1 and decrement the handicap. If you exhaust the handicap, stop. If you hit the easiest hole you wrap around to the hardest and continue. (Ex: stroke index for hcp 24 and [1..18]: [2,2,2,2,2,2,1,1,1,1,1,1,1,1,1,1,1,1]).
For every score on a hole, subtract it from the sum of par and stroke index and add 2 (formula: (par + stroke index) - achieved score + 2). These are the stableford points received for that hole. Note that you cannot receive less than 0 points.
Sum up all the points. The resulting total is the total number of stableford points.

Thus, reaching 36 points is equivalent to playing exactly one's handicap, and more points are better.

Rules

Your task will be to calculate the total number of stableford points of an arbitrary golf round on an arbitrary golf course given a handicap.

You will be given a list of difficulty ratings, a list of pars, a list of scores and the handicap to use. You may order these arguments as you wish, but please state how you order them.

You may write a function ot program, input can be taken either as command line argument or function argument.

Output may either be printed to STDOUT or the return value of a function.

You may assume the following about the input:

Every list will contain exactly 18 elements.
The lists are orderd by hole: First element = info for first hole, etc.
The handicap will be an integer between 0 and 54 inclusive.
Pars will be between 3 and 7.
The score is always a positive integer.
The difficulty rating list will always be a permutation of [1..18].

This is code golf, so the shortest answer in bytes wins.

Examples

Input: hcp: 0
       difficulty: [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18]
       pars: [3,3,3,3,4,4,4,4,4,4,4,4,4,4,5,5,5,5]
       score: [3,3,3,3,4,4,4,4,4,4,4,4,4,4,5,5,5,5]
Output: 36

Input: hcp: 15
       difficulty: [9,3,1,13,11,17,15,7,5,18,14,10,4,6,12,16,8,2]
       pars: [4,4,4,3,5,4,3,4,4,4,3,4,4,4,5,3,5,4]
       score: [5,5,4,5,4,4,4,4,5,7,3,5,5,6,4,6,5,5]
Output: 38

Input: hcp: 28
       difficulty: [9,3,1,13,11,17,15,7,5,18,14,10,4,6,12,16,8,2]
       pars: [4,4,4,3,5,4,3,4,4,4,3,4,4,4,5,3,5,4]
       score: [5,5,5,6,3,7,3,6,5,8,4,6,7,8,4,7,6,5]
Outut: 37

Input: hcp: 54
       difficulty: [9,3,1,13,11,17,15,7,5,18,14,10,4,6,12,16,8,2]
       pars: [4,4,4,3,5,4,3,4,4,4,3,4,4,4,5,3,5,4]
       score: [9,10,9,10,9,10,9,10,9,10,9,10,9,10,9,10,9,10]
Output: 3

Happy golfing!


20 cards with no Set Background

Set is a card game. The deck consists of 81 unique cards that vary in four features: number of shapes (one, two, or three), shape (diamond, squiggle, oval), shading (solid, striped, or open), and color (red, green, or purple).

For convenience, let's write a card as a 4-tuple of numbers from 1 to 3, e.g.

1111 = one red solid diamond
1122 = one red striped squiggle
1223 = one green striped oval
2312 = two purple solid squiggle

Given several cards (usually 12), the objective of the game is to find a "set" of three cards such that

They all have the same number or have three different numbers.
They all have the same shape or have three different shapes.
They all have the same shading or have three different shadings.
They all have the same color or have three different colors.

i.e. the cards are either all the same or all different in each of the four features.

Here are some examples of sets:

1111, 1112, 1113
1111, 2222, 3333
2312, 3321, 1333

Here are some examples of non-sets:

1111, 1122, 1123
2131, 3221, 1213

A cap set is a collection of cards that doesn't contain any Set. It was proven in 1971 that the maximum number of cards without a Set is 20. Interestingly, finding the largest cap set for the generalized game of Set is still an open problem in mathematics.

The Wikipedia page shows an example of 20-cap set, and here is the 20 cards in the number notation:

1111, 1113, 1131, 1133,
1312, 1332, 1321, 1323,
3311, 3313, 3331, 3333,
3112, 3132, 3121, 3123,
1222, 2122, 2322, 3222

There are 682344 20-cap sets in total, but under affine transformations on 4-dimensional finite space, they all reduce to essentially one cap set.

Task

Output any of the 20-cap sets in the game of Set.

Input and output

Your program/function is not allowed to take input.

The output is a collection (list, set, ...) of 20 cards which is a cap set. Each card should be represented as a 4-tuple (or equivalent ordered collection) whose elements are one of three distinct values (not necessarily 1, 2, 3). Flexible output applies in the following ways:

Nested or flattened list
Ordering of cards doesn't matter
You may choose to output the same set or different set across runs
For string/text output, it's fine as long as we can clearly identify the structure (20 chunks of four items) of the output

Verification script example in Python using the example shown above.

Scoring and winning criterion

Standard code-golf rules apply. The shortest valid code in bytes wins.

Haskell, 62 bytes

tail[t|t@[a,b,c,d]<-mapM(:[1,2])[0,0,0,0],mod(a*a+b*b+c*d)3<1]

Try it online!

Defines a cap-set as all  \$(a,b,c,d)\$ from \$\{0,1,2\}^4\$ where $$a^2+b^2+cd=0\bmod3,$$ except not \$(0,0,0,0)\$.

I found this formula by looking at Wikipedia's example and coming up with progressively simpler formulas linking the allowed inner coordinates \$(a,b)\$ to the outer coordinates \$(c,d)\$.

Haskell, 46 bytes

[t|t<-mapM(:"12")"0000",sum[1|'0'<-t!!0:t]==2]

Try it online!

This uses a modified condition giving a different but equivalent cap set:

$$a^2+b^2+c^2 - d^2=0\bmod3,$$ still without \$(0,0,0,0)\$.

This is equivalent to \$a^2+b^2+c^2 + d^2 + d^2 =0\bmod3,\$, so we can duplicate an element and check that the give-element list of squares adds to zero modulo 3. Since squares modulo 3 are 0 or 1, this is further equivalent to this condition:

  There are exactly \$2\$ zeroes among \$[a,b,c,d,d]\$.

This automatically excludes the all-zero point. Of course, duplicating $d$ was arbitrary -- choosing another element gives a different but equivalent cap-set.


Is this a legal date? - April Fools' edition Task

A date can be compactly represented in a 6-character string in the format ddmmyy where the first two characters (dd) represent a day, the 3rd and 4th characters (mm) represent a month and the last two characters (yy) represent a 20XX year. Given a string with 6 characters in [0-9] determine if it represents a valid date. But because today (the day this was posted) is April Fools' day, we will have a twist in the way dates work:

April Fools' dates

We will pretend every 30-day month has 31 days and every 31-day month has 30 days. Furthermore, in years when February is supposed to have 29 days we will pretend February only has 28 days and in all the other years we will pretend February has 29 days; i.e.:

months 01, 03, 05, 07, 08, 10 and 12 have 30 days;
months 04, 06, 09 and 11 have 31 days;
February has 28 days if the year yy is a multiple of 4, otherwise February has 29 days (let us assume we are in the year 20yy);

Input

An integer in [0 - 311299] or a 0-padded string representation of such an integer.

Output

A Truthy value if the input corresponds to a date as per the April Fools' dates, Falsy otherwise.

Test cases

Python naïve implementation for your convenience.

"000511" -> False
"000611" -> False
"290200" -> False
"290204" -> False
"290208" -> False
"310004" -> False
"310005" -> False
"310104" -> False
"310105" -> False
"310204" -> False
"310205" -> False
"310304" -> False
"310305" -> False
"310504" -> False
"310505" -> False
"310704" -> False
"310705" -> False
"310804" -> False
"310805" -> False
"311004" -> False
"311005" -> False
"311204" -> False
"311205" -> False
"311304" -> False
"311305" -> False
"311404" -> False
"311405" -> False
"010694" -> True
"031288" -> True
"050199" -> True
"050298" -> True
"050397" -> True
"060496" -> True
"070595" -> True
"100793" -> True
"150892" -> True
"181189" -> True
"200991" -> True
"251090" -> True
"280200" -> True
"280201" -> True
"280202" -> True
"280203" -> True
"280204" -> True
"280205" -> True
"280206" -> True
"280207" -> True
"280208" -> True
"290201" -> True
"290202" -> True
"290203" -> True
"290205" -> True
"290206" -> True
"290207" -> True
"310404" -> True
"310405" -> True
"310604" -> True
"310605" -> True
"310904" -> True
"310905" -> True
"311104" -> True
"311105" -> True

This challenge was inspired by this one.

This is code-golf so shortest submission in bytes, wins! If you liked this challenge, consider upvoting it! If you dislike this challenge, please give me your feedback. Happy golfing!

JavaScript (ES6),  62 60  59 bytes
Takes input as a 0-padded string. Returns \$0\$ for false or a positive integer for true.

s=>(m=s[2]+s[3])<13&31-(m^2?~m%9%2:s%4?1:2)>(s/=1e4)&&~~s*m

Try it online!
or Check all possible outputs against an ungolfed implementation
Commented
s =>                // s = input string
  (m = s[2] + s[3]) // m = month, as a string
  < 13 &            // make sure that m is less than 13
  31 - (            // compute the upper bound for this month:
    m ^ 2 ?         //   if the month is not February:
      ~m % 9 % 2    //     use either 31 or 32
    :               //   else:
      s % 4 ?       //     if this is not a leap year:
        1           //       use 30
      :             //     else:
        2           //       use 29
  )                 // end of upper bound computation
  > (s /= 1e4)      // make sure that it's greater than the day
  && ~~s * m        // and finally make sure that day * month is not zero