Help johnny to solve this Puzzle Scenario

Little Johnny wants to play with his friends today. But his babysitter won't let him go! After a lot of begging, the heartless nanny gives him her brand new electronic puzzle and says: "If you solve the puzzle then you are free to go". Not being aware of Little Johnny's IT skills, the nanny leaves the kid alone.
Rapidly, Little Johnny sends you an e-mail asking for your help.
The puzzle consists of three hexagons as shown in the figure. Each vertex is painted black or white. Some of them belong to just one hexagon and some of them belong to more than one. Exactly four of them are painted black, and the other nine are white. The goal is to make the shared vertexes black by means of allowed moves: rotating a hexagon 60 degrees clockwise or counter-clockwise.
Can you help Little Johnny?

Input

  Input starts with an integer T, the number of puzzles to solve
  (1<=T<=100). T lines follow, each one having 13 binary digits,
  corresponding to the top-down, left to right labeling of the vertexes
  in the puzzle. A '0' means the i-th vertex is painted white, while a
  '1' means it is painted black.

output

  For each test case output M on a single line, the minimum number of
  moves required to solve the puzzle. Then print M lines, each one
  describing a move in the following manner: two space separated
  integers H and C, the rotated hexagon (upper left is 0, upper right
  is 1, lower one is 2) and the direction (0 for counter-clockwise, 1
  for clockwise). If there is more than one solution, any will suffice.

Example

Input sample:

1
0000000101011

output sample:

3

2 0

2 0

1 1

source Limit

50000 Bytes

time limit

1 sec

Winning constrain

shortest code with specified time limit wins!

I leave the question for five days to decide winner future answers after five days too welcome

Python, 307 chars

S={'0001001011000':[]}
for i in[0]*7:
 for s in dict(S):
  for m in range(6):S.setdefault(''.join(s[int(x,16)]for x in['2150483769abc','3106428759abc','0326159487abc','0421753986abc','01234587a6c9b','012345976b8ca'][m]),[m]+S[s])
for j in[0]*input():
 L=S[raw_input()];print len(L)
 for m in L:print m/2,m%2

Computes S which is a mapping from a state (a string just like the input) to a list of move numbers which solve the state.  Generates a complete S on startup (only 715 states), then looks up each input and prints the answer.

Moves are implemented using a string of hex digits indicating where each result vertex comes from.

Takes about 0.15 seconds regardless of how big the input is.


Golf me the Schlosberg Numbers Schlosberg Numbers

In issue 5 of Mathematical Reflections, Dorin Andrica proposed the problem of characterising the positive integers n such that  is an even integer. Eight people submitted correct solutions showing that these are the integers n for which  is even. The published solution was by Joel Schlosberg, so I call them the Schlosberg numbers.

These numbers may be found in OEIS as sequence A280682.

Your challenge is: given n, output the nth Schlosberg number. (0 or 1 indexed)

The first 50 Schlosberg numbers are:
0
4
5
6
7
8
16
17
18
19
20
21
22
23
24
36
37
38
39
40
41
42
43
44
45
46
47
48
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
100
101
102
103
104

Normal rules and the shortest code wins!

Haskell, 32 bytes

(filter(even.floor.sqrt)[0..]!!)

Try it online!


Become the Hydra Slayer You are the best and most famous hero of the area.  Lately there have been rumors that a Hydra has been hanging out in a nearby ravine. Being the brave and virtuous hero that you are you figure you'll go check it out sometime later today.

The problem with hydrae is that every time you try to cut off their heads some new ones grow back.  Luckily for you you have swords that can cut off multiple heads at once.  But there's a catch, if the hydra has less heads than your sword cuts, you wont be able to attack the hydra.  When the hydra has exactly zero heads, you have killed it.

There is also a special sword called The Bisector that will cut off half of the Hydra's heads, but only if the number of heads is even.  The Bisector cannot be used at all when the number of heads is odd.  This is different from cutting off zero heads.

So you have decided you will write a computer program to figure out the best way to slay the hydra.

Task

You will be given as input

the number of heads the Hydra starts with
the number of heads the Hydra regrows each turn
a list of swords available for use each (each either is a bisector or cuts a fixed number of heads each turn)

You should output a list of moves that will kill the hydra in the least number of turns possible.  If there is no way to kill the hydra you must output some other value indicating so (and empty list is fine if your language is strongly typed).  If there are multiple optimal ways to kill the hydra you may output any one of them or all of them.

This is a code-golf question so answers will be scored in bytes, with fewer bytes being better.

Test Cases

More available upon request

5 heads, 9 each turn,  [-1,-2,-5] -> [-5]
12 heads, 1 each turn, [/2,-1] -> No solution
8 heads, 2 each turn,  [-9, -1] -> [-1,-9]
3 heads, 23 each turn, [/2,-1,-26] -> [-1,-1,-26,-26,-26,-26,-26,-26,-26,-26]
16 heads, 1 each turn, [/2, 4, 2] -> [/2,-4,/2,-4]

  This question is a simplified version of the main mechanic of HydraSlayer. If you like this type of puzzle I recommend checking it out, its pretty fun.  I do not have any affiliation with the game.


Improvise a Hardware Random-Number Generator Your task is to improvise a hardware random-number generator with whatever hardware you have lieing around.
Challenge
Write a program with the following properties:

It prints either 0 or 1 (and nothing else).
The output depends on a physical process and not just the internal state of the computer.
There is no relation between outputs of subsequent runs (one minute apart).
The output is not predictable with any realistic effort.
The probability of the output being 0 is between 0.2 and 0.8.
It runs in less than a minute with a reasonably high probability.

You must explain why your program has these properties, if it is not obvious.
Clarifications and Restrictions
The following may seem like an awful lot of restrictions for a popularity contest, but ultimatively it’s all to ensure that the program remains within the spirit of the question, somewhat works and to avoid solutions which are popular due to being a total overkill but are ultimatively rather boring.

The system time does not count as a physical process.
You may use any consumer-grade hardware you like from 8-inch floopy-disk drives to a USB rocket launcher to headphones – unless it is intended for random-number generation. A piece of hardware is consumer-grade, if it is mass-produced and costs less than 1000 $/€/£, so you cannot use radio telescopes, the CERN, MRIs or your home-built particle detector.
You can only make the most basic assumptions on the state and alignment of the hardware such as being switched on (if it has a power switch) and being properly installed and functional. For example you can assume a CD drive to be generally capable of reading a disk and not to be jammed, but you cannot assume it to be open or closed or to contain a disk. In another example you cannot assume two pieces of hardware to be aligned to allow for a special interaction, but you can assume them to be in the same room.
You may leave the hardware in any state you like, unless you break it.
You can and must assume the hardware to be in a natural environment, but nothing more. For example you can assume that the hardware is not positioned in a in tank of liquid helium nor in an extremely sound- and lightproof room nor in space. However, you cannot assume any sound- and lightsources to be present except those that are only avoidable with radical efforts.
Your program must run on a standard desktop computer with a non-esoteric operating system of your choice. You may employ any software that is not specifically designed for random-number generation.
You cannot assume Internet access.
You can neither assume humans to be present nor absent, but you can assume that nobody intentionally interfers with your program, e.g., by manually stopping a fan or running a program that does nothing but switching off the microphone as often as possible.
You can only make the most basic assumptions about the software settings. For example, you can assume drivers to be installed and activated but you must be prepared for the sound to be muted.
You may leave the software settings in any state you like.

Bonus
A special bounty was awarded to a particularly short solution. This was rather by numbers of instructions and similar than by characters. The winners were (tied according to my criteria):

This answer by Franki.
This answer by Tejas Kale.

I could only award one answer and Tejas Kale’s answer won by lot.

Shell
Reads a single sample from the microphone stream and prints its least-significant bit, which should be dominated by noise.
EDIT: Changed to unmute the microphone ... and everything else too!
# Warning - unmutes EVERYTHING!
for DEV in `amixer | grep Simple | sed -e "s/.*'\(.*\)'.*/\\1/" -e "s/ /~/g"`
do
    amixer -q -- sset "`echo $DEV | sed 's/~/ /g'`" unmute 100% 2>/dev/null
done

echo $(( `od -N1 -d < /dev/dsp | head -n1 | sed 's/.* //'` & 1 ))


What code compiles in the most number of languages? Excluding trivial programs, what code compiles in the most number of languages?

(By "trivial" I mean to exclude answers such as the empty program or text that will be echoed directly.)

The following code apparently compiles in all of the following programming languages (and prints something different in each one):
C, C++, Perl, TeX, LaTeX, PostScript, sh, bash, zsh and Prolog.

%:/*:if 0;"true" +s ||true<</;#|+q|*/include<stdio.h>/*\_/
{\if(%)}newpath/Times-Roman findfont 20 scalefont setfont(
%%)pop 72 72 moveto(Just another PostScript hacker,)show((
t)}. t:-write('Just another Prolog hacker,'),nl,halt. :-t.
:-initialization(t). end_of_file. %)pop pop showpage(-: */
int main(){return 0&printf("Just another C%s hacker,\n",1%
sizeof'2'*2+"++");}/*\fi}\csname @gobble\endcsname{\egroup
\let\LaTeX\TeX\ifx}\if00\documentclass{article}\begin{doc%
ument}\fi Just another \LaTeX\ hacker,\end{document}|if 0;
/(J.*)\$sh(.*)"/,print"$1Perl$2$/"if$_.=q # hack the lang!
/
sh=sh;test $BASH_VERSION &&sh=bash;test $POSIXLY_CORRECT&&
sh=sh;test  $ZSH_VERSION && sh=zsh;awk 'BEGIN{x="%c[A%c[K"
printf(x,27,27)}';echo "Just another $sh hacker," #)pop%*/

That's 10 different languages.  I found it via pts oldalai (who also has a magnificent Christmas poem written in C, C++, Perl and TeX).  Can anyone do better?

3 Languages - C, C++, and Python

#ifdef _cplusplus
    #include <iostream>
    #define print() int main(){cout << "Hello world! -- from C++" << endl;}
#elif (defined __STDC__) || (defined __STDC_VERSION__)
    #include <stdio.h>
    #define print() int main(){printf("Hello world! -- from C\n");}
#else
import builtins
print = lambda : builtins.print("Hello world! -- from Python")
#endif

print()

Something different is printed in each language. In C & C++, lines starting with '#' are preprocessing directives, but those same lines are comments in Python.


Make your keyboard into a keyboard Task

You should write a program that when a button is pressed, it outputs a different sound for each key.

The keys that you will use are:

1!2"34$5%6^78*9(0qQwWeErtTyYuiIoOpPasSdDfgGhHjJklLzZxcCvVbBnm

The notes begin at C and each key above adds one semitone.

Lets make it slightly easier for you though. You can choose between 2 similar tasks,

  1) Output a different note when a key is pressed that continues until another key is pressed. This program runs indefinitely

  2) Take a string as input that only contains the characters above that will output each note for exactly 1 second (0.05 second variation allowed)

Input

A key being pressed
A single string containing only the symbols above

Output

A single musical note that sounds until another key is pressed
A series of notes, each one 1 second long

Notes

Letter | Note
-------+-------
   1   |  C
   !   |  C#
   2   |  D
   "   |  D#
   3   |  E
   4   |  F
   $   |  F#
   5   |  G
   %   |  G#
   6   |  A
   ^   |  A#
   7   |  B
   8   |  C
   *   |  C#
   9   |  D
   (   |  D#
   0   |  E
   q   |  F
   Q   |  F#
   w   |  G
   W   |  G#
   e   |  A
   E   |  A#
   r   |  B
   t   |  C    <-- middle C
   T   |  C#
   y   |  D
   Y   |  D#
   u   |  E
   i   |  F
   I   |  F#
   o   |  G
   O   |  G#
   p   |  A
   P   |  A#
   a   |  B
   s   |  C
   S   |  C#
   d   |  D
   D   |  D#
   f   |  E
   g   |  F
   G   |  F#
   h   |  G
   H   |  G#
   j   |  A
   J   |  A#
   k   |  B
   l   |  C
   L   |  C#
   z   |  D
   Z   |  D#
   x   |  E
   c   |  F
   C   |  F#
   v   |  G
   V   |  G#
   b   |  A
   B   |  A#
   n   |  B
   m   |  C

Rules

You may choose between the tasks but please say which one in your answer
You are given a ±0.05 second variation in task 2
Each symbol along increments the tone by 1 semitone.
The individual notes are shown above
This is a code-golf so shortest code wins

This was originally taken from here with caird coinheringaahing's consent

Python 3, 154 140 bytes

from winsound import*
for i in input():Beep(int(65.406*2**('1!2"34$5%6^78*9(0qQwWeErtTyYuiIoOpPasSdDfgGhHjJklLzZxcCvVbBnm'.find(i)/12)),999)

I chose the second task type.

The loop passes through each character and looks for the index of this element in the string. This index is the number of semitone up from Low C ('1'). Calculation of the desired frequency is made by this formula.

P.S. This library works only in Windows.

-13 bytes thanks to ovs.

-1 byte thanks to Jonathan Allan.


Quickly divide in Manufactoria Background

Manufactoria has been marketed as a game, but we code-golfers can see it for what it really is: a two-dimensional programming language.  The Manufactoria programming language is based around a single queue, which contains a series of colorful markers.  The instruction pointer moves around the game board using conveyor belts, and it encounters a series of writers and branches which read from and write to the queue.

The language is very easy to understand, so the quickest way to learn it is to play the first few levels of the game (linked above).

Challenge

Your challenge is to create a program that can divide one number by another number in the least amount of time.

The input to the program will be a string of X blue markers followed by Y red markers.  The required output will be a string of red markers with a length of X/Y.

The game board to be used is found in this official contest level:

http://pleasingfungus.com/Manufactoria/?ctm=Divide_and_Conquer;Input_will_be_X_blues_followed_by_Y_reds,_output_X/Y_reds;bbbbbbrr:rrr|bbbrrr:r|bbbbr:rrrr|r:|bbbbbbbbbbbbrrrr:rrr|bbbbbbbbbbbbrrr:rrrr|bbbbbbbbbrrr:rrr|bbbbbbbbbbrr:rrrrr;13;3;0

It is 13x13 (the maximum size) and it is pre-equipped with the correct tests (see the scoring section).

Scoring

The score of your program is the total amount of time that it takes for the program to pass all of the tests in the official contest level.  The total time is given on the level-complete screen.

While running the tests, you will most likely have to use the 50x accelerate slider in the bottom left in order to receive the results quickly (time acceleration does not affect the score).

Here is a list of division problems that are involved in the tests:

 6/2 = 3
 3/3 = 1
 4/1 = 4
 0/1 = 0
12/4 = 3
12/3 = 4
 9/3 = 3
10/2 = 5

Example I/O

12/3=4
in:  BBBBBBBBBBBBRRR
out: RRRR

10/2=5
in:  BBBBBBBBBBRR
out: RRRRR

9/3=3
in:  BBBBBBBBBRRR
out: RRR

0/1=0
in:  R
out:


Who won a Game of Bar Dice? Challenge

Bar Dice is a simple game played in a Bar with Dice (hence the name). You roll 5 six-sided dice and attempt to make the best hand.

  Scoring is based on amassing the largest number of dice with the same digits. Each hand must include at least a single "Ace", or one, in order to be a valid hand; Aces act as "wilds", and can be paired with any other digit. The strength of a player's hand depends first on the number of digits and then value of those digits. As an example, a hand (counting wilds) with four 3's is better than a hand with three 5's, but not better than a hand with five 2's.
  Taken from the Wikipedia article

This means the highest ranked hand is made entirely of 6's and 1's, and the lowest ranked is any hand without a 1.

Your challenge is to take two hands and return which player won, or if they tied.

Input

Two unsorted lists of 5 numbers, ranging from 1 to 6. Each list represents a player's hand. The input format is flexible.

Output

Any three distinct but consistent, static values (ranges are not allowed) signifying whether player 1 or player 2 won, or if it was a tie. Please state in your answer what values you are using for what. For example, you can return -1 if P1 wins, 0 if it's a tie, and 1 if P2 wins.

Rules

Input will always be valid
Only the best possible score of each hand is used to determine a winner. There are no tie-breakers. E.g., [1,4,4,3,3] will tie [1,4,4,2,2] instead of using the 3's and 2's as a tie-breaker.
Output must be one of the 3 chosen values every time. Simply mapping all negative numbers to P1 Wins is not allowed and must be normalized.
Invalid hands, i.e. those with no 1's, lose to all valid hands but tie with all other invalid hands. E.g., [2,2,2,2,2] ties [3,3,3,3,3].
A hand of [1,1,1,1,1] counts as a valid set of 6's for ranking purposes.
This is code-golf so shortest byte count wins.

Examples

#You guys are pretty good at finding edge-cases that break things. Good job!
Input:  [2,1,5,6,6], [6,2,6,6,6]
Output: P1 Wins

Input:  [2,4,5,6,6], [6,2,6,6,6]
Output: Tie

Input:  [1,2,3,4,5], [5,4,3,2,1]
Output: Tie

Input:  [1,5,5,3,2], [5,4,1,6,6]
Output: P2 Wins

Input:  [3,2,2,2,1], [4,1,3,6,6]
Output: P1 Wins

Input:  [1,1,1,1,1], [6,1,1,6,6]
Output: Tie

Input:  [1,3,3,4,4], [1,2,2,5,5]
Output: P2 Wins

Input:  [1,3,3,5,5], [1,3,3,2,2]
Output: P1 Wins

Input:  [1,3,3,3,4], [1,1,3,3,3]
Output: P2 Wins

Input:  [2,2,2,6,1], [5,3,3,1,2]
Output: P1 Wins

Input:  [5,5,5,1,5], [1,1,1,1,1]
Output: P2 Wins

Input:  [1,1,1,1,1], [1,1,5,1,1]
Output: P1 Wins

Jelly, 17 14 bytes

ċⱮ6Ḣ©+$®aĖUṀ)M

Try it online!

A monadic link that takes a list of the two lists as its argument and returns [1] for player 1 wins, [2] for player 2 wins and [1, 2] for a tie. TIO link tidies this up for display.

Thanks to @JonathanAllan for saving 3 bytes!

Explanation

            )   | For each input list (e.g. of one list 1,1,3,3,4)
ċⱮ6             | - Count each of 1..6 (e.g. 2,0,2,1,0,0)
      $         | - Following as a monad:
   Ḣ            |   - Head (number of 1s)
    ©           |   - Copy to register
     +          |   - Add (e.g. 2,4,3,0,0)
       ®a       | - Register logical and with this
         Ė      | - Enumerate (e.g. [1,2],[2,4],[3,3],[4,0],[5,0])
          U     | - Reverse each (e.g. [2,1],[4,2],[3,3],[0,4],[0,5])
            Ṁ   | - Max (e.g. 4,2)
              M | Index/indices of maximal score


Smallest multiple being run of 9 followed by optional run of 0 Given a positive integer, find its smallest positive integer multiple which is a run of 9 followed by an optional run of 0. In other words, find its smallest positive integer multiple which is matched by the regex /^9+0*$/.

For example, if the given positive integer is 2, then return 90, since 90 is a positive integer multiple of 2 and is the smallest which is matched by the regex /^9+0*$/.

Test cases:

n  f(n)
1  9
2  90
3  9
4  900
5  90
6  90
7  999999
8  9000
9  9
10 90
11 99
12 900
13 999999
14 9999990
15 90
16 90000

This is code-golf. Shortest answer in bytes wins. Standard loopholes apply.

Jelly, 13 11 bytes

ṚḌ‘DS=ḍ@ð1#

Try it online!

How it works

ṚḌ‘DS=ḍ@ð1#  Main link. Argument: n

        ð    Start a dyadic chain with arguments n and n.
         1#  Execute the chain to the left with left argument k = n, n+1, n+2, ...
             and right argument n until 1 match has been found. Return the match.
Ṛ                Get the decimal digits of k, reversed.
 Ḍ               Convert from base 10 to integer.
                 This essentially removes trailing zeroes. As a side effect, it
                 reverses the digits, which doesn't matter to us.
  ‘              Increment the resulting integer. If and only if it consisted
                 entirely of 9's, the result is a power of 10.
   DS            Compute the sum of the digits. The sum is 1 if and only if the
                 integer is a power of 10. Note that the sum cannot be 0.
      ḍ@         Test k for divisibility by n.
     =           Compare the results.


Collatz Graph Plotting Write a program that outputs a graph of the collatz sequence any way you want (ASCII Image Video etc). You have to implement it that way that you can adjust the size of the graph by either the maximum number of nodes or highest number in graph. A boring example here.

Try to present the graph in a creative / insightful way, this is a popularity contest!

Please comment your code / algorithm and post at least one example output in your answer.

Background: Collatz sequence

The Collatz sequence is defined for any natural number n > 0 by the recursion:

The Collatz conjecture states that the sequence ends in the cycle 1,4,2

Python+Graphviz

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import networkx as nx
import os

"""Tool to generate collatz sequence graphs."""

def collatz_one(x):
    """Make a single step in the collatz sequence."""
    if x % 2 == 0:
        x = x/2
    else:
        x = 3*x + 1
    return x

def main(max_collatz=20):
    """Create the collatz graph. """
    G = nx.DiGraph()
    seen = [1]
    G.add_node("1")
    edges = []

    for i in range(1, max_collatz):
        while i != 1:
            if i not in seen:
                seen.append(i)
                G.add_node(str(i))
                j = collatz_one(i)
                edges.append((str(i), str(j)))
                i = j
            else:
                i = 1

    for i, j in edges:
        G.add_edge(i, j)
    nx.write_dot(G, 'test.dot')
    os.system("dot -Tpng test.dot -o test.png")

if __name__ == '__main__':
    from argparse import ArgumentParser
    parser = ArgumentParser(description=__doc__)
    parser.add_argument("-m", dest="m",
                        help=("The first 1..m elements are guaranteed "
                              "to be included"),
                        default=20,
                        type=int)

    args = parser.parse_args()
    main(args.m)

Image

Created with dot and m=20:


Plot a centered circle Intro
Given radius \$r\$, draw a circle in the center of the screen.
Sandbox.
The Challenge
Here is a simple challenge.
Plot a circle using the formula \$x^2+y^2=r^2\$, or any other formula that will plot a circle according to the given parameters.
You may use any units that your language provides, so long as they are well defined and give consistent output.
The circle must have it's center at the center of the canvas, and must have a padding of 5 units or more on all sides.
The circle can have any fill that does not match the outline.
You may have axes in the background of your plot.
The outline of the circle must be solid (no gaps), and it must be visible.  Here is an example:

Input can be taken in any acceptable form. (function params, variables, stdin...)
Output can be in the form of a separate window, or an image format.
Standard loopholes and rules apply.
Example Code (Java + Processing)
// Modified from the C language example from
// https:// en.wikipedia.org/wiki/Midpoint_circle_algorithm
int r = 70; //radius
void settings() {
  size(2*r+10, 2*r+10);
}

void draw() {
  background(255);
  drawCircle(width/2, height/2, r, 60);
  save("Circle.png");
}

void drawCircle(int x0, int y0, int radius, int angle) {
  int circCol = color(0, 0, 0);
  float limit = radians(angle);
  int x = radius;
  int y = 0;
  int err = 0;

  while (x >= y && atan2(y, x) < limit) {
    set(x0 + x, y0 + y, circCol);
    set(x0 + y, y0 + x, circCol);
    set(x0 - y, y0 + x, circCol);
    set(x0 - x, y0 + y, circCol);
    set(x0 - x, y0 - y, circCol);
    set(x0 - y, y0 - x, circCol);
    set(x0 + y, y0 - x, circCol);
    set(x0 + x, y0 - y, circCol);

    y += 1;
    if (err <= 0) {
      err += 2*y + 1;
    }
    if (err > 0) {
      x -= 1;
      err -= 2*x + 1;
    }
  }
}

Scoring
This is a graphical-output question. No ascii art.
This is code-golf. shortest answer in each language wins.

R, 74 70 68 65 54 bytes
Edit: -11 bytes thanks to Giuseppe

function(r)plot(r*1i^(1:1e3/99),,"l",l<-c(-r-5,r+5),l)

Try it at rdrr.io
I propose 3 possible answers to this challenge in R, of decreasing length but with increasing caveats.
My favourite answer (above, using plot) is the middle shortest one of the 3.  It plots a circle by calculating the complex coordinates of powers of i, using 396 points (with a bit of wrap-around).  Here's an image of the output from plot_circle(5):

For a 'true' circle (rather than an almost-circle with tiny straight-lines connecting the data points), we can use the curve function with a formula, but unfortunately we need to draw the positive & negative halves separately, so it ends up longer:
R, 86 84 bytes

function(r){curve((r^2-x^2)^.5,xli=l<-c(-r-5,r+5),yli=l)
curve(-(r^2-x^2)^.5,add=T)}

Try it at rdrr.io

The shortest (that I can think of) Previously the shortest, but - thanks to Giuseppe now no longer so - is to use the circles option of the symbols function, for only 56 bytes.  However, this has the caveat that the circle symbols are always circular even if the plot is re-sized, and so may no-longer line-up with the y-axis.
R, 62 58 56 bytes

function(r)symbols(x=1,c=r,i=F,xli=l<-c(-r-4,r+6),yli=l)

Try it at rdrr.io


Find the Wavy Words! (Note: this is an easier spin-off of my previous challenge Find the Infinity Words!, which is a spin-off of my other previous challenge Find the Swirling Words! :) )

Definition of a Wavy Word:

If you connect with curves all the characters of a Wavy Word on the alphabet (A-Z) you obtain the path of a wave continuously going toward right or toward left and never changing direction, like in the diagrams below.
A Wavy Word can be:

Raising if each consecutive character is at the right (on the alphabet) of the previous one.
Decreasing if each consecutive character is at the left (on the alphabet) of the previous one.

All the even connection must be down, all the odd connections must be up.
You can ignore upper/lowercase or consider/convert all to upper case or all to lower case.
The input words are only characters in the alphabet range of A-Z, no spaces, no punctuation, or symbols.
If a word has double characters, like "SPOON", you must collapse the doubles to one character: "SPOON" > "SPON" (because if you go from O to O is zero distance).
The Wavy Words will contain at least 3 distinct characters (even after doubles collapsing).

Here there are some examples:

Task:

Write a full program or function that will take a word from standard input and will output if it is a Wavy Word or not, and in positive case, output if it is raising or decreasing. The output can be True/False/Null, 2/1/0, 1/Null/0, -1/0/1, NO/WR/WD, etc, you decide how to represent it.

Test cases:

WAVY WORDS:
  ADEPT, BEGIN, BILL, BOSS, BOOST, CHIMP,
  KNOW, SPONGE, SPOON, TROLL, WOLF

ADEPT  > YES > RAISING
BEGIN  > YES > RAISING
BILL   > YES > RAISING
BOSS   > YES > RAISING
BOOST  > YES > RAISING
CHIMP  > YES > RAISING
KNOW   > YES > RAISING
SPONGE > YES > DECREASING
SPOON  > YES > DECREASING
TROLL  > YES > DECREASING
WOLF   > YES > DECREASING

NOT WAVY WORDS:
  WATCH, EARTH, NINON, FOO, BAR, WAVE, SELECTION,
  YES, NO, DEFINITION, WATER, WINE, CODE, AAAHHHH, I, MM, ABCA

Rules:

Shortest code wins.

Optional Task:

Find, as a list, as many Wavy Words as you can in an English dictionary, and the longest as well. You can take for example as reference the complete list of English words here.

05AB1E, 11 9 bytes (Thanks to Adnan)

Dg2›iÇü‹Ù

Try it online!

Wavy Cases:

0 - Decreasing Wavy

1 - Increasing Wavy

Not Wavy Cases:

[0,1] - Not wavy, initially decreasing, but then has an increase/equality that broke the pattern.

[1,0] - Not wavy, initially increasing, but then has a decrease/equality that broke the pattern

Input String - Not possible to be wavy in the first place due to length.

Explanation:

Dg2›iÇü‹Ù   # Full program

D           # Push 2 copies of input.
 g2›i       # If length is greater than 2.
     Ç      # Push ASCII values for all characters in the string.
      ü     # Push pairwise array.
       ‹    # Vectorize 1 if negative difference, 0 if positive difference.
        Ù   # Uniquify using right most unique values first.
            # Else just print the string back, letting them know it's not valid input.


Roman numeral converter function Create the shortest function to convert a string of Roman numerals to an integer.

The rules for each letter can be found at the Wikipedia page.  Letters above 1,000 will have parentheses placed around them to signal their higher value.

Requirements:

Must convert Roman numerals 1 to 500,000
Must complete in less than a minute
Does not use built-in functions that could provide an advantage (Ex: A function that converts Roman numerals to integers)
Is a function

The function does not need to support fractions.  Any invalid input should return the number 0.

Shortest function wins.  In the case of a tie, the one with the most votes wins.

Test Cases

Input

III

Output

3

Input

IIII

Output

0

Input

XVI

Output

16

Input

(C)(D)(L)MMI

Output

452001

C++: 914 855 chars
#include<map>
#include<string>
#include<iostream>
#include<sstream>
#define I istream
#define T(C) if(C)throw int(1);
#define X(c,v,f,m) D[c]=v;P[c]=D[f];M[c]=m;
#define S second
using namespace std;typedef map<char,int>R;R D,P,M;struct U{U():t(0),l(0),a(0){}int t,l,a;operator int(){return t+l;}I&d(I&s){char c,b;s>>c;if(c=='('){s>>c>>b;T(b!=')')c+=32;}if(s){R::iterator f=D.find(c);T(f==D.end())if(P[c]==l){l=f->S-l;a=0;}else{T(l&&(f->S>l))a=l==f->S?a+1:1;T(a>M[c])t+=l;l=f->S;}}return s;}};I&operator>>(I&s,U&d){return d.d(s);}int main(){D[' ']=-1;X(73,1,32,3)X(86,5,73,1)X(88,10,73,3)X(76,50,88,1)X(67,100,88,3)X(68,500,67,1)X(77,1000,67,3)X(118,5000,77,1)X(120,10000,77,3)X(108,50000,120,1)X(99,100000,120,3)X(100,500000,99,1)X(109,1000000,99,3)string w;while(cin>>w){try{stringstream s(w);U c;while(s>>c);cout<<c<<"\n";}catch(int x){cout<<"0\n";}}}

It could be compressed further.
> ./a.exe
III
3
IIII
0
XVI
16
(C)(D)(L)MMI
452001

Slightly nicer formatting: 1582 char
#include<map>
#include<string>
#include<iostream>
#include<sstream>
#define I istream
#define T(C) if(C)throw int(1);
#define X(c,v,f,m) D[c]=v;P[c]=D[f];M[c]=m;
#define S second
using namespace std;

typedef map<char,int>      R;

R     D,P,M;

struct U
{
    U(): t(0), l(0), a(0) {}

    int  t,l,a;

    operator int()
    {
        return t + l;
    }
    I& d(I& s)
    {
        char c,b;
        s >> c;
        if (c == '(')
        {
            s >> c >> b;
            T(b != ')')
            c = tolower(c);
        }
        if (s)
        {
            R::iterator f = D.find(c);
            T(f == D.end())

            if (P[c] == l)
            {
                l = f->S - l;
                a = 0;
            }
            else
            {
                T(l&&(f->S > l))
                a=l==f->S?a+1:1;
                T(a>M[c])
                t   += l;
                l     = f->S;
            }
        }

        return s;
    }

};

I& operator>>(I& s,U& d)
{
    return d.d(s);
}

int main()
{
    D[' ']=-1;
    X(73,1,32,3)
    X(86,5,73,1)
    X(88,10,73,3)
    X(76,50,88,1)
    X(67,100,88,3)
    X(68,500,67,1)
    X(77,1000,67,3)
    X(118,5000,77,1)
    X(120,10000,77,3)
    X(108,50000,120,1)
    X(99,100000,120,3)
    X(100,500000,99,1)
    X(109,1000000,99,3)

    string w;
    while(cin >> w)
    {
        try
        {
            stringstream s(w);
            U    c;
            while(s >> c);
            cout << c << "\n";
        }
        catch(int x)
        {
            cout << "0\n";
        }
    }
}


Find Recursively Prime Primes The Recursively Prime Primes is are sequence of primes such that
p(1) = 2
p(n) = the p(n-1)th prime

Here is an example of how one might calculate the 4th Recursively Prime Prime.
p(4) = the p(3)th prime
p(3) = the p(2)th prime
p(2) = the p(1)th prime
p(1) = 2
p(2) = the 2nd prime
p(2) = 3
p(3) = the 3rd prime
p(3) = 5
p(4) = the 5th prime
p(4) = 11

You should write a program or function that when given n, outputs the nth Recursively Prime Prime.
You may choose to use 0 based indexing if you wish in which case you must indicate so in your answer.
This is code-golf so the goal is to minimize your byte count.

Test Cases
1 -> 2
2 -> 3
3 -> 5
4 -> 11
5 -> 31
6 -> 127
7 -> 709
8 -> 5381
9 -> 52711

Relevant OEIS entry: OEIS A007097

Oasis, 3 bytes

The program is 0-indexed. Code:

<q2

Uses the formula: a(n) = nth_prime(a(n-1) - 1), with the base case a(0) = 2.

Code explanation:

  2   = a(0)

<     # Decrement a(n - 1) to get a(n - 1) - 1
 q    # prime(a(n - 1) - 1)

Try it online!


Minimal maximum byte for Turing Completeness Summary
We already have a challenge for the minimal number of characters for Turing completeness. But what about the minimal maximum byte?
Challenge
For a language of your choice, find a subset of characters that allows your language to be Turing complete with the minimal maximum byte value.
Example
If your language is using the UTF8 code page and Turing complete using only the characters abcd(), these characters have the byte values 97, 98, 99, 100, 40, 41, and the maximum there is d = 100, so your score would be 100.
Scoring
Your score is the maximum byte value of your Turing complete subset, expressed in the code page of your language's interpreter. For most languages this will be either LATIN-1 or UTF8, but if your language uses a different code page (such as Jelly) use that to score instead.
In the unlikely event that you require multibyte characters to be Turing complete, just use the maximum byte in the multibyte sequence to score. For example, if your UTF8 language required Ȧ, this is encoded as the literal byte sequence 200, 166, so it would score 200.
The lowest score wins.
Notes

The minimum score is 0, the maximum is 255.
For some languages (cough) this challenge will be trivial to score low on. I urge you to upvote interesting answers over trivial ones.
Provide an explanation of why your subset is Turing complete.
Your subset only needs to be Turing complete, it does not need to be able to use every feature of the language.

Haskell, score 61 (=)
Characters used: !#$%&()=
The SKI combinator calculus can be implemented in Haskell with nothing but basic function definition, using !#%& as identifiers. Infix function application $ is used to save on parentheses and strip down one character from both S and fix. Finally, K only takes two arguments and can be more shortly defined as an infix operator.
S combinator: s x y z = x z (y z)
(!)(#)(%)(&)=(#)(&)$(%)(&)

K combinator: k x y = x
(!)#($)=(!)

fix combinator: fix f = f (fix f)
(&)(!)=(!)$(&)(!)

Since Haskell is a strongly typed language, the fixed-point combinator fix is needed in order to make (typed) combinatory logic Turing-complete.
The I combinator is not strictly required since it is extensionally equivalent to SKK, but it can be defined as (*)(!)=(!).
Try it online!


Expand Sine and Cosine Trigonometry has LOTS of identities. So many that you can expand most functions into sines and cosines of a few values. The task here is to do that in the fewest bytes possible.

Identity list

Well, the ones we're using here.

sin(-x)=-sin(x)
sin(π)=0
cos(-x)=cos(x)
cos(π)=-1
sin(a+b)=sin(a)*cos(b)+sin(b)*cos(a)
cos(a+b)=cos(a)cos(b)-sin(a)sin(b)

For the sake of golfing, I've omitted the identities that can be derived from these. You are free to encode double-angles and such but it may cost you bytes.

Input

You should take in an expression as a string with an arbitrary number of terms consisting of a coefficient and some sine and cosine functions, each with an exponent and an arbitrary number of arguments.
Coefficients will always be nonzero integers.
Each argument will be a coefficient, followed by either a single latin letter or pi.
You can decide whether to take in pi as pi or π. Either way remember that you're scored in bytes, not characters.

Output

Output the same expression, but…

All trig functions are either sin or cos.
All arguments of trig functions are single variables, with no coefficients.
All like terms are combined.
Terms with a coefficient of 0 are removed.
All factors in the same term that are the same function of the same variable are condensed into a single function with an exponent.

Note: Leading + signs are allowed, but not required. a+-b is allowed, and equivalent to a-b. If there are no terms with nonzero coefficients, then output either 0 or an empty string.

Worked Example

We'll start with sin(-3x)+sin^3(x). The obvious first thing to do would be to deal with the sign using the parity identity, leaving -sin(3x). Next I can expand 3x into x+2x, and apply the sine additive identity recursively:

-(sin(x)cos(2x)+cos(x)sin(2x))+sin^3(x)
-(sin(x)cos(2x)+cos(x)(sin(x)cos(x)+sin(x)cos(x)))+sin^3(x)

Next, some distributive property and like terms:

-sin(x)cos(2x)-2cos^2(x)sin(x)+sin^3(x)

Now, I expand the cos(2x) and apply the same reduction:

-sin(x)(cos(x)cos(x)-sin(x)sin(x))-2cos^2(x)sin(x)+sin^3(x)
-sin(x)cos^2(x)+sin^3(x)-2cos^2(x)sin(x)+sin^3(x)
2sin^3(x)-3sin(x)cos^2(x)

And now, it's finished!

Test Cases

In addition to the following, all of the individual identities (above) are test cases. Correct ordering is neither defined nor required.

cos(2x)+3sin^2(x) => cos^2(x)+2sin^2(x)
sin(-4x) => 4sin^3(x)cos(x)-4sin(x)cos^3(x)
cos(a+2b-c+3π) => 2sin(a)sin(b)cos(b)cos(c)-sin(a)sin(c)cos^2(b)+sin(a)sin(c)sin^2(b)-cos(a)cos^2(b)cos(c)+cos(a)sin^2(b)cos(c)-2cos(a)sin(b)cos(b)sin(c)
sin(x+674868986π)+sin(x+883658433π) => 0 (empty string works too)
sin(x+674868986π)+sin(x+883658434π) => 2sin(x)

…and may the shortest program in bytes win.


Generate a grid of sums Generate a 7 by 7 grid, filled with random numbers. However, in cells with an odd row and column number (starting at 0), you must use the sum of the surrounding cells. Here's a small example with a 3 by 3 grid (sum-square bolded):

2 2  2
2 16 2
2 2  2

And here's an example 7 by 7 grid:

6 5  4 3  7 2  5
6 43 3 50 8 43 8
4 7  8 8  9 3  1
4 36 1 43 6 40 5
3 3  6 1  4 7  5
4 35 3 45 9 42 1
2 6  8 6  8 5  3

Rules

Numbers that are not sums must always be between 1 and 9 inclusive.
Grid must be randomly generated. For each non-sum, every digit must have an equal chance of appearing, regardless of which cell it is in.
Numbers must be aligned. This means that either the first or last digit of each number in a column must line up vertically. (You may assume that the middle numbers will always be two digits.)
Surrounding cells includes diagonals. Therefore, each sum square will have eight numbers surrounding it, which you must add.
Shortest code wins, since this is code-golf.

APL, 53 49 43 42 40 39 36

I managed to replicate J's ;. in APL, and used Gareth's approach, saving 13 chars.

{×5⌷⍵:5⌷⍵⋄+/⍵}¨3,⌿3,/×∘?∘9¨∘.∨⍨9⍴0 1

Sample run:

      {×5⌷⍵:5⌷⍵⋄+/⍵}¨3,⌿3,/×∘?∘9¨∘.∨⍨9⍴0 1
9  9 6  1 7  5 6
7 55 5 39 9 54 9
9  8 2  1 8  1 9
2 43 8 41 6 42 5
7  3 4  4 8  3 2
2 29 1 26 2 35 8
6  4 2  3 2  3 7

Explanation:

∘.∨⍨9⍴0 1 generates a bit mask.
×∘?∘9¨ multiplies each bit by a random value from 1 to 9 inclusive, generating a masked grid of random numbers.
3,⌿3,/ uses what can only be described as hackery to return all 3 by 3 overlapping boxes in the masked array. These are also flattened in the process.
{×5⌷⍵:5⌷⍵⋄+/⍵}¨ iterates over the array, assigning each element to ⍵. For each iteration, it takes the fifth (middle, remembering that APL indexing is 1-based), and returns its sign. In this case this is equivalent to testing if the number is greater than 0. If this returns 1 (for true), then return that element. Otherwise, return the sum of the elements in the flattened 3 by 3 box. It uses the :⋄ ternary operator, which is the equivalent of ?: in many languages.


A+B using C++ language I'm golfing a program to sum two numbers in C++.

Example:

10 3
13

I found out that this problem can be solved in 54 symbols (without spaces and so on) using C++.
My code (63 symbols):

#include <iostream>
main() {
    int a, b;
    std::cin >> a >> b;
    std::cout << a + b;
}

I have no idea how to make my program shorter. Can you help me, please?

48 bytes
How about...
#include<cstdlib>
main(){system("tr \\  +|bc");}

...not using C++?

The call to system runs commands on your shell (<cstdlib> declares system).
tr \\  + executes the command tr, translating spaces to + (so the input34 45 becomes 34+45).
| pipes tr's STDOUT into bc's STDIN.
bc performs equations in STDIN and prints the result to STDOUT.


Circles, where do you meet? Given 2 random circle sections, return how many times they intersect. Rules/clarifications are as below.

You are provided 10 total values,

The center (x,y) of the circle section
Angles of the circle (i.e. (0,90) would be a quarter circle "facing" the top-right corner.
The radius of the circle section

The circle sections are "drawn" on a 128 by 128 screen, with (0,0) being the center. They have a max radius of 64.
You don't need to draw the circles - the program should only print out the number of intersections.
You can choose to generate the values randomly, in-program, or have the user write it in at program start. (The latter is preferred, but not necessary.)

Below is an example case. As you can see, it has one intersect.

The output should look something like this:

$ run ./circle
input (circle 1 center)
input (circle 1 radius)
input (circle 1 angles)
input (more inputs...)
...
intersections

Heres the output for the example case (the prompts are optional):

$ run ./circle
c1center: (20,20)
c1radius: 40
c1angles: (210,150)
c2center: (-30,-30)
c2radius: 90
c2angles: (270,180
1

Anyway, best of luck! This is code golf, so the minimum number of bytes in any programming language wins!

Oh, and it'd be nice if you could provide a description/link to your program in the answer. Standard Loopholes are not allowed. If you find any errors in my explanation or want me to clarify, just ask. Thanks!

Python 3 + numpy, 310 291 bytes

 -19 bytes thanks to ovs!

v=lambda c,x,y:sin(arctan2(*c[::-1])-x)>sin(y-x)
def f(a,r,w,x,b,s,y,z):
 d=linalg.norm(b-a)
 if abs(r-s)<d<r+s:e=(r*r-s*s+d*d)/2/d;g=a+e*(b-a)/d;t=(sqrt(r*r-e*e)*(b-a)/d*[1,-1])[::-1];return int(v(g+t-a,w,x)and v(g+t-b,y,z))+int(v(g-t-a,w,x)and v(g-t-b,y,z))-(t==0).all()
from numpy import*

Try it online!

This is a horrible answer.

Takes angles in radians.


Compute the histogram entropy estimation of a string Write a program or function that estimates the Shannon entropy of a given string.

If a string has n characters, d distinct characters, xi is the i th distinct character, and P(xi) is the probability of that character occuring in the string, then our Shannon entropy estimate for that string is given by:

For the estimation in this challenge we assume that the probability of a character occurring in a string is simply the number of times it occurs divided by the total number of characters.

Your answer must be accurate to at least 3 digits after the period.

Test cases:

"This is a test.", 45.094
"00001111", 8.000
"cwmfjordbankglyphsvextquiz", 122.211
"             ", 0.0

Python 3.3+, 64 bytes

import math
lambda s:sum(math.log2(len(s)/s.count(c))for c in s)

Got math.log2 from mbomb007's solution.


Carrots. So. Many. Carrots Damn, that's a lot of carrots.

The Inspiration

The Task

You must create a program, that, in as many languages as possible, replaces every instance of ^ with a markdown formatted link (meaning that if I was to post it in an answer, it would automatically read it as an image and place the image instead of the words) of this upward facing carrot.

How to Use Said Formatting:

First, anywhere in the file, put in the link like so (this is what I did for this question):

[1]: http://i.stack.imgur.com/mecHl.png

And then, wherever you want it:

[![][1]][1]

Rules

Standard Loopholes apply.
Input will be through STDIN or equivalent.
Output will be through STDOUT or equivalent.
Your code must be a fully operating program in all languages that you use.
The URL that you use for your carrot does not have to be the one in this answer. This was just an example. You may use any URL, provided that SE's Markdown shows this specific carrot with it.
This is a polyglot challenge, so the answer with the greatest amount of carrots languages wins!

In the case of a tie, the shortest code size of the entries with the largest number of languages wins.

EDIT:

Also, do NOT use trivial derivatives of languages! This means using a substitution language (Brainfuck vs. ShadyAsFuck) and different language versions (Python 2 vs. Python 3).

  There's a lot trivial esolangs to fit... (including 9001 BF variants)

Don't be that guy.

Note: Yes, this program will be slightly trivial in languages with regex support. However, the competition is to see how many languages the competitors can use.

Minkolang 0.10, Befunge-93, ><>; 3 2D languages, 321 bytes
v[1]: http://i.stack.imgur.com/mecHl.png
v[![][1]][1]
>\$$>~:1+!#v_:"^"-#v_1>:34*`#v_v
//  ^             ,<0        <    >:0g,1+v
v#   ,,:*52<          ^+1  ,g1:<@_^#`*85:<1
>!v#(od"^"=,34*&34*[i1+1qO]!O$I)lO58*[i1+0qO].
  >i:0(?v:"^"-?v1>:34*)?vv
  ^           o<0       < > :0go1+v
  oo:*52<        ^+1og1: <^;?)*85:<1

Interpreters: Minkolang, Befunge-93, ><>.
I'll go into detail on each component if anyone wants, but what's important is that all of them read the first and second lines of the codebox and output the characters at the appropriate times. Also, I decide between Befunge and Minkolang/><> by the use of \, which swaps the top two values of the stack in the first and is a mirror in the other two. To separate Minkolang and ><>, I use !v#. ! is an unconditional trampoline in both languages, but # is an omni-directional mirror in ><> and a no-op in Minkolang. From then on, each language executes code in its own component.


Create a chain of spam generators in as many languages as possible The goal of a rosetta-stone challenge is to write solutions in as many languages as possible. Show off your programming multilingualism!

In this challenge, you will create a program that will generate spam messages, given an input seed-text. For example, given the input

[Thank you/Wow/Great], this [blog/post/writing] [gives/provides/delivers] [great/excellent/wonderful/superior] [content/information/data]. You [may/could] [find/get/retrieve] [similar/related] [content/information/data] at spammysite.com.

A possible output could be

Thank you, this writing delivers excellent data. You may find similar content at spammysite.com.

(idea from https://security.stackexchange.com/q/37436/29804)

There's a catch, though! You will also have to output a program in a different language. This program, when run, will also output the spam text and a program in a different language, which will also output the spam text and a program in a different language...

Your score will be character count / (number of languages ^ 2).

For example, I could have a Ruby program. It would take the input seed-text as input, and output the random spam text and a Python program.

Running this Python program (with no input), it would output another random spam text and a Perl program.

Running this Perl program (no input), it would output another random spam text.

In this example, my score would be the length of the original Ruby program divided by 9 (I have 3 languages, and 3 ^ 2 is 9).

Other miscellaneous things:

You must use at least 2 different programming languages.
Please list each program that is output. This way if someone doesn't have all of the languages, they can still see their sources. You may use this short example text: [Please/Kindly] [visit/see] my [site/blog]., or you may just use a placeholder (like {insert text here}).
You may assume that there will be no non-alphanumeric characters except []/.,, to simplify some things.
Different versions of languages do not count as different languages (ex. Python 2 == Python 3).
It must be fully random, i.e. not predictable and outputting a different combination every run. It must also be able to output every combination in an arbitrary amount of runs.
Since this is code-golf as well as rosetta-stone, the shortest overall score (charcount / (langs ^ 2)) will win.

PHP 5.5 -> Ruby 2.0 -> Python 2.7 -> Lua -> C# -> Java -> PdfTeX -> GolfScript 855 / 8^2 = 13.359375

The main ideas were:

Instead of actually creating the logic to create the n+1th language in all programming languages do this only one time, and only use the basic random and stdout writing facilities of each programming language
To shorten the template generator, just compress it with zLib. Make this generator the second language
Use PHP as the first language, as it has built-in zLib decompressor

So the initial code is:

<?php $x=file_get_contents("php://stdin");echo preg_replace_callback("/\[(.*?)\]/",function($m){$r=explode("/",$m[1]);return $r[array_rand($r)];},$x).gzuncompress("BINARY_DATA")."__END__\n".$x;

Where BINARY_DATA is the gzcompressed version of the template generator (e.g. the result of the php code, which is the ruby version)

The complete initial code in base64 (should be 855 bytes after decoding):

PD9waHAgJHg9ZmlsZV9nZXRfY29udGVudHMoInBocDovL3N0ZGluIik7ZWNobyBw
cmVnX3JlcGxhY2VfY2FsbGJhY2soIi9cWyguKj8pXF0vIixmdW5jdGlvbigkbSl7
JHI9ZXhwbG9kZSgiLyIsJG1bMV0pO3JldHVybiAkclthcnJheV9yYW5kKCRyKV07
fSwkeCkuZ3p1bmNvbXByZXNzKCJ42o2UwXKbMBCG7zyFZj0doElV55BLiNJmmump
7aHpTA+Yg4xErA6SGCQSZ4jevZIBx3biTHywzO6y/7+fYRm5uf5zjVtOGS5XWjbY
NLWwSZzHKVx4OTa06Z/oE51iRZw6XFzV1FquXiQ/+2TEMKflKsSbViiLfFx4OTbK
puYuajpr0OUlBDmIoqrVErVUMX8I2ejWXCIvL0oejVfm0USznk0y4Fx4YWaxsUx3
Fj+0wvJkKE9mPcVCmYaX1qUpuI+wUODlgvzwjeI4XHg5NtSu8CBnOGeJNthcbsmT
NN0ToWSnHbatx1DEp3Hv/GyZ0KMyzXfaJWen4Z6aqzu7cmmRZvseknQ8c0JyT2FZ
ixKVNTUGUdRPAWOp9ce9Fgz9pEIlqc/dPhrLJf49UGqJ4g9oL1x4OTak2a79Jfl0
JXs5eiHk7AuM5d+0Mrrm+O/G/8zXVKI19hlcXAYXICqUtPgXX9sb7V15OJdzfJ72
R3uYlah2ezheG97DyTKXxQk4D1wiW+YUs64pJiRceGFm9fohFA+THM19hTd5ycDr
1nrId3mBaHtnArx/9J7izop6n99h+N0Iw4M3/JELeAlwATsIlUf4vdbUHhA8bLHP
L7R4P8FtXHhhZloNI6wJUMjeGGS0fIFgMX5EpTp5Pp9fTYGGVZ0SlW4l4/eCWn42
n8/R1qqb6oJLNLmcgpXwbtdkjU1XXHg5Ntn0RlxcvULQW17AYnsj4xWafuvG+lEc
6mf9dnD3IVQHvgjgDQxceDAwLyi8audAq3e+MR3g+O7gXHgwMJ4fxgPMR1TZ8zLc
yiDIw17YJFx4OTZPEPuBXFwMG4FiZ2GEJUJceDAw+dHiEB1cXIx1x4zAdoTlI98U
uciNR1QQ4ndQ5HdeFFZt9B9+DwFHIikuIl9fRU5EX19cbiIuJHg7

Let's go through all of the languages with the test input string [Thank you/Wow/Great], this is [awesome/wonderful].

PHP

$ cat ti2 | php a.php
Great, this is wonderful.
d=DATA.read.chomp.split('[').map{|a|a.split(']')}.flatten.map{|a|a.split('/')}
d.each{|a|print a.sample}
puts <<"DATA"

from random import choice
import sys
#{d.map{|a|"sys.stdout.write(choice(#{a.inspect}))"}*"\n"}
print
print '''math.randomseed(os.time())
#{d.map{|a|"a=#{a.inspect.tr('[]','{}')};io.write(a[math.random(1,#{a.length})]);"}*"\n"}
print()
print([==[
public class a {
public static void Main() {
System.Random r=new System.Random();
#{d.map{|a|b=->m{m.length==1?"System.Console.Write(#{m.first.inspect});":"if (r.NextDouble()<0.5){System.Console.Write(#{m.shift.inspect});}else{"+b[m]+"};"};b[a.dup]}*"\n"}
System.Console.WriteLine();
System.Console.WriteLine(@"class a {
public static void main(String[] args) {
java.util.Random r=new java.util.Random();
#{d.map{|a|b=->m{m.length==1?"System.out.print(\"#{m.first.inspect}\");":"if (r.nextFloat()<0.5){System.out.print(\"#{m.shift.inspect}\");}else{"+b[m]+"};"};b[a.dup]}*"\n"}
System.out.println();
#{x="a";d.map{|a|b=->m{m.length==1?m.first: "\\\\\\\\ifnum500>\\\\\\\\pdfuniformdeviate1000 #{m.shift}\\\\\\\\else "+b[m]+"\\\\\\\\fi"};x=x.succ;a.length>1?"System.out.println(\"\"\\\\\\\\def \\\\\\\\opt#{x} {#{b[a.dup]}}%\"\");": ""}*"\n"}
System.out.println(""#{x="a";d.map{|a|x=x.succ;a.length>1?"\\\\\\\\opt#{x}{}": a.first}*""}"");
System.out.println();
System.out.println(""#{d.map{|a|a.length>1? "[#{a.map{|b|"'#{b}'"}*""}]#{a.length}rand=" : "'#{a.first}'"}*""}"");
System.out.println(""\\\\\\\\bye"");
}
}");
}
}
]==]);
'''
DATA
__END__
[Thank you/Wow/Great], this is [awesome/wonderful].

Ruby

$ ruby a.rb
Great, this is awesome.
from random import choice
import sys
sys.stdout.write(choice(["Thank you", "Wow", "Great"]))
sys.stdout.write(choice([", this is "]))
sys.stdout.write(choice(["awesome", "wonderful"]))
sys.stdout.write(choice(["."]))
print
print '''math.randomseed(os.time())
a={"Thank you", "Wow", "Great"};io.write(a[math.random(1,3)]);
a={", this is "};io.write(a[math.random(1,1)]);
a={"awesome", "wonderful"};io.write(a[math.random(1,2)]);
a={"."};io.write(a[math.random(1,1)]);
print()
print([==[
public class a {
public static void Main() {
System.Random r=new System.Random();
if (r.NextDouble()<0.5){System.Console.Write("Thank you");}else{if (r.NextDouble()<0.5){System.Console.Write("Wow");}else{System.Console.Write("Great");};};
System.Console.Write(", this is ");
if (r.NextDouble()<0.5){System.Console.Write("awesome");}else{System.Console.Write("wonderful");};
System.Console.Write(".");
System.Console.WriteLine();
System.Console.WriteLine(@"class a {
public static void main(String[] args) {
java.util.Random r=new java.util.Random();
if (r.nextFloat()<0.5){System.out.print(""Thank you"");}else{if (r.nextFloat()<0.5){System.out.print(""Wow"");}else{System.out.print(""Great"");};};
System.out.print("", this is "");
if (r.nextFloat()<0.5){System.out.print(""awesome"");}else{System.out.print(""wonderful"");};
System.out.print(""."");
System.out.println();
System.out.println(""\\\\def \\\\optb {\\\\ifnum500>\\\\pdfuniformdeviate1000 Thank you\\\\else \\\\ifnum500>\\\\pdfuniformdeviate1000 Wow\\\\else Great\\\\fi\\\\fi}%"");

System.out.println(""\\\\def \\\\optd {\\\\ifnum500>\\\\pdfuniformdeviate1000 awesome\\\\else wonderful\\\\fi}%"");

System.out.println(""\\\\optb{}, this is \\\\optd{}."");
System.out.println();
System.out.println(""['Thank you''Wow''Great']3rand=', this is '['awesome''wonderful']2rand='.'"");
System.out.println(""\\\\bye"");
}
}");
}
}
]==]);
'''

Python

$ python a.py
Great, this is wonderful.
math.randomseed(os.time())
a={"Thank you", "Wow", "Great"};io.write(a[math.random(1,3)]);
a={", this is "};io.write(a[math.random(1,1)]);
a={"awesome", "wonderful"};io.write(a[math.random(1,2)]);
a={"."};io.write(a[math.random(1,1)]);
print()
print([==[
public class a {
public static void Main() {
System.Random r=new System.Random();
if (r.NextDouble()<0.5){System.Console.Write("Thank you");}else{if (r.NextDouble()<0.5){System.Console.Write("Wow");}else{System.Console.Write("Great");};};
System.Console.Write(", this is ");
if (r.NextDouble()<0.5){System.Console.Write("awesome");}else{System.Console.Write("wonderful");};
System.Console.Write(".");
System.Console.WriteLine();
System.Console.WriteLine(@"class a {
public static void main(String[] args) {
java.util.Random r=new java.util.Random();
if (r.nextFloat()<0.5){System.out.print(""Thank you"");}else{if (r.nextFloat()<0.5){System.out.print(""Wow"");}else{System.out.print(""Great"");};};
System.out.print("", this is "");
if (r.nextFloat()<0.5){System.out.print(""awesome"");}else{System.out.print(""wonderful"");};
System.out.print(""."");
System.out.println();
System.out.println(""\\def \\optb {\\ifnum500>\\pdfuniformdeviate1000 Thank you\\else \\ifnum500>\\pdfuniformdeviate1000 Wow\\else Great\\fi\\fi}%"");

System.out.println(""\\def \\optd {\\ifnum500>\\pdfuniformdeviate1000 awesome\\else wonderful\\fi}%"");

System.out.println(""\\optb{}, this is \\optd{}."");
System.out.println();
System.out.println(""['Thank you''Wow''Great']3rand=', this is '['awesome''wonderful']2rand='.'"");
System.out.println(""\\bye"");
}
}");
}
}
]==]);

Lua

$ lua a.lua
Great, this is wonderful.
public class a {
public static void Main() {
System.Random r=new System.Random();
if (r.NextDouble()<0.5){System.Console.Write("Thank you");}else{if (r.NextDouble()<0.5){System.Console.Write("Wow");}else{System.Console.Write("Great");};};
System.Console.Write(", this is ");
if (r.NextDouble()<0.5){System.Console.Write("awesome");}else{System.Console.Write("wonderful");};
System.Console.Write(".");
System.Console.WriteLine();
System.Console.WriteLine(@"class a {
public static void main(String[] args) {
java.util.Random r=new java.util.Random();
if (r.nextFloat()<0.5){System.out.print(""Thank you"");}else{if (r.nextFloat()<0.5){System.out.print(""Wow"");}else{System.out.print(""Great"");};};
System.out.print("", this is "");
if (r.nextFloat()<0.5){System.out.print(""awesome"");}else{System.out.print(""wonderful"");};
System.out.print(""."");
System.out.println();
System.out.println(""\\def \\optb {\\ifnum500>\\pdfuniformdeviate1000 Thank you\\else \\ifnum500>\\pdfuniformdeviate1000 Wow\\else Great\\fi\\fi}%"");

System.out.println(""\\def \\optd {\\ifnum500>\\pdfuniformdeviate1000 awesome\\else wonderful\\fi}%"");

System.out.println(""\\optb{}, this is \\optd{}."");
System.out.println();
System.out.println(""['Thank you''Wow''Great']3rand=', this is '['awesome''wonderful']2rand='.'"");
System.out.println(""\\bye"");
}
}");
}
}

C#

$ mcs a.cs
$ mono a.exe
Thank you, this is wonderful.
class a {
public static void main(String[] args) {
java.util.Random r=new java.util.Random();
if (r.nextFloat()<0.5){System.out.print("Thank you");}else{if (r.nextFloat()<0.5){System.out.print("Wow");}else{System.out.print("Great");};};
System.out.print(", this is ");
if (r.nextFloat()<0.5){System.out.print("awesome");}else{System.out.print("wonderful");};
System.out.print(".");
System.out.println();
System.out.println("\\def \\optb {\\ifnum500>\\pdfuniformdeviate1000 Thank you\\else \\ifnum500>\\pdfuniformdeviate1000 Wow\\else Great\\fi\\fi}%");

System.out.println("\\def \\optd {\\ifnum500>\\pdfuniformdeviate1000 awesome\\else wonderful\\fi}%");

System.out.println("\\optb{}, this is \\optd{}.");
System.out.println();
System.out.println("['Thank you''Wow''Great']3rand=', this is '['awesome''wonderful']2rand='.'");
System.out.println("\\bye");
}
}

Java

$ javac a.java
$ java a
Wow, this is wonderful.
\def \optb {\ifnum500>\pdfuniformdeviate1000 Thank you\else \ifnum500>\pdfuniformdeviate1000 Wow\else Great\fi\fi}%
\def \optd {\ifnum500>\pdfuniformdeviate1000 awesome\else wonderful\fi}%
\optb{}, this is \optd{}.

['Thank you''Wow''Great']3rand=', this is '['awesome''wonderful']2rand='.'
\bye

PdfTeX

(the code will be inside a.pdf instead of the stdout. I hope this is still okay)

$ pdftex a.tex
This is pdfTeX, Version 3.1415926-2.4-1.40.13 (TeX Live 2012)
 restricted \write18 enabled.
entering extended mode
(./a.tex [1{/usr/local/texlive/2012/texmf-var/fonts/map/pdftex/updmap/pdftex.ma
p}] )</usr/local/texlive/2012/texmf-dist/fonts/type1/public/amsfonts/cm/cmr10.p
fb>
Output written on a.pdf (1 page, 15967 bytes).
Transcript written on a.log.
$ open a.pdf

Result:

In text:

Great, this is wonderful.
['Thank you''Wow''Great']3rand=', this is '['awesome''wonderful']2rand='.'

Golfscript

$ ruby golfscript.rb a.gs
Wow, this is awesome.

Notes

It seems PHP is quite forgiving with binary data in string literals, except for hex codes AF and 96. Don't ask why.
I could've probably added perl and C++11 code as well easily (as they both support raw string literals), but 8 is a more round number than 10 :)
The distribution of values is not uniform, as the first element comes more often than later ones. According to comments this should be okay.
The initial code was actually generated using the following PHP 5.5 code. orig.rb is actually the same as the Ruby code without the footer (__END__ and the appended data afterwards)

generator.php:

<?php
$d=file_get_contents('orig.rb');
$dc = gzcompress($d,9);
echo '<?php $x=file_get_contents("php://stdin");echo preg_replace_callback("/\\[(.*?)\\]/",function($m){$r=explode("/",$m[1]);return $r[array_rand($r)];},$x)';
?><?php
echo ".gzuncompress(\"";
for ($i=0;$i<strlen($dc);$i++) {
  switch($dc[$i]) {
  case '"':
    echo "\\\"";break;
  case "\n":
    echo "\\n";break;
  case '\\':
    echo "\\\\";break;
  case "\x00":case "\xaf":case "\x96":
    echo sprintf("\\x%02x",ord($dc[$i]));
    break;
  default:
    echo $dc[$i];
  }
}
echo "\").\"__END__\\n\".\$x;";

(you can potentially use this code to zLib encompress PHP solutions for other challenges)


Calculate hamming weight with low hamming weight Create a program that computes the hamming weight of a string. Winner is the program with the lowest hamming weight.

Rules:

Hamming weight for an ASCII character is defined as the total number of bits set to 1 in its binary representation.
Assume input encoding is 7-bit ASCII, passed through whatever input mechanism is normal for your language (e.g. stdin, args, etc.)
Output the result, as a number, to stdout or whatever default/normal output mechanism your language uses.
It should go without saying, but you have to be able to actually run the program, in real life, for it to be a valid solution.
Winner is the solution whose code has the lowest hamming weight.
Sorry, no solutions in whitespace for this one! Ok, you can code in whitespace now I've sorted out the rules :)

Per-character examples:

char |  binary  | weight
-----+----------+-------
a    | 01100001 | 3
x    | 01111000 | 4
?    | 00111111 | 6
\x00 | 00000000 | 0
\x7F | 01111111 | 7

J, weight 34

+/,#:a.i.

Usage - place the string to be measured in quotes at the end:

   +/,#:a.i.'+/,#:a.i.'
34

Alternatively, taking input from the keyboard (weight 54):

   +/,#:a.i.1!:1[1
hello
21


De-Parenthesizing a String Given a properly-parenthesized string as input, output a list of all nonempty substrings within matching parentheses (or outside of all parentheses), with nested parentheses removed. Each substring should be the sequence of characters in exactly the same matching parentheses. Substrings should be listed in order of depth, and substrings of the same depth should be listed in the order they occur in the string. Assume the input is always correctly parenthesized.

You may assume that the input contains only lower-case ASCII letters and parentheses.

Your answer should be a function that, when given a string, returns a list of strings.

Examples:

                   'a(b)c(d)e' -> ['ace', 'b', 'd']
                   'a(b(c)d)e' -> ['ae', 'bd', 'c']
                  'a((((b))))' -> ['a', 'b']
                        'a()b' -> ['ab']
                            '' -> []
                           'a' -> ['a']
          '(((a(b)c(d)e)f)g)h' -> ['h', 'g', 'f', 'ace', 'b', 'd']
'ab(c(((d)ef()g)h()(i)j)kl)()' -> ['ab', 'ckl', 'hj', 'efg', 'i', 'd']

Fewest bytes wins.

JavaScript ES6, 91 93 104 133 148

Edit2 2 bytes saved thx user81655

Edit Using more strings and less arrays

Test running the snippet below in an EcmaScript 6 compliant browser

f=s=>[...s].map(c=>l+=c<')'||-(o[l]=(o[l]||'')+c,c<'a'),o=[],l=0)&&(o+'').match(/\w+/g)||[]

// Less golfed

u=s=>{
  o=[]; l=0;
  [...s].map(c=>{
    if (c>'(') // letters or close bracket
      o[l]=(o[l]||'')+c, // add letter or close bracket to current level string
      l-=c<'a' // if close bracket, decrement level
    else
      ++l // open bracket, increment level
  })
  o = o+'' // collapse array to comma separated string
  return o.match(/\w+/g)||[] // fetch non empty strings into an array
}

// TEST
console.log=x=>O.innerHTML+=x+'\n'

;[ 'a(b)c(d)e'                    // ['ace', 'b', 'd']
 , 'a(b(c)d)e'                    // ['ae', 'bd', 'c']
 , 'a((((b))))'                   // ['a', 'b']
 , 'a()b'                         // ['ab']
 , ''                             // []
 , 'a'                            // ['a']
 , '(((a(b)c(d)e)f)g)h'           // ['h', 'g', 'f', 'ace', 'b', 'd']
 , 'ab(c(((d)ef()g)h()(i)j)kl)()' // ['ab', 'ckl', 'hj', 'efg', 'i', 'd']
].forEach(t=>console.log(t +" -> " + f(t)))


How drunk am I and when can I drive again? It's weekend and what are the cool guys doing on weekends? Drinking of course! But you know what's not so cool? Drinking and driving. So you decide to write a program that tells you how loaded you are and when you are gonna be able to drive again without getting pulled over by the cops and loosing your license.
The Challenge
Given a list of beverages you enjoyed this evening, calculate your blood alcohol level and the time you have to wait till you can hop into your car and get home.
Input
Input will be a list of drinks you had this night. This will look like this:

4 shots booze
1 glasses wine
2 bottles beer
3 glasses water

Containers will always be plural.
As you can see each entry consists of:

The type of drink (booze, wine, beer, water)
The container for the drink (shots, glasses, bottles)
The amount x of the drinks you had of that type as integer with x > 0,

Each drink type adds a certain amount of alcohol to your blood:

booze ->  0.5 ‰ / 100 ml
beer  ->  0.1 ‰ / 100 ml
wine  ->  0.2 ‰ / 100 ml
water -> -0.1 ‰ / 100 ml

Water is the exception here, since it thins your blood out and lowers your alcohol level (would be so nice if that actually worked...).
Each container has a certain volume:

shots   -> 20 ml
glasses -> 200 ml
bottles -> 500 ml

Output
You have to output two numbers:

The alcohol level in ‰
The time in hours you have to wait until you reached 0.5 ‰ or less, so you can drive again. You loose 0.1 ‰ per hour.

Notes

The alcohol level can never fall below zero.
Same goes for the waiting time. If you have 0.5 ‰ or less, output zero.
The order of drinks does not matter, so drinking water may lower the alcohol level below zero in the process of the calculation. If it remains there, you need to replace it with zero.

The alcohol level for the the example above would be calculated like this:

4 shots booze   -> 0.4 ‰
1 glasses wine  -> 0.4 ‰
2 bottles beer  -> 1.0 ‰
3 glasses water -> -0.6 ‰

=> 0.4 + 0.4 + 1 - 0.6 = 1.2 ‰

To reach 0.5 ‰ you need to loose 0.7 ‰. You loose 0.1 ‰ per hour, so you need to wait 7 hours to drive again.
Rules

You can take the input in any format you want, but you have to use the exact strings as given above. You may take the numbers as integers.
You can output the two numbers in any order, just make in clear which one you use in your answer.
You may assume that the input will always have at least one entry.
Function or full program allowed.
Default rules for input/output.
Standard loopholes apply.
This is code-golf, so lowest byte-count wins. Tiebreaker is earlier submission.

Test cases
Input as list of strings. Outputs alcohol level first, values seperated by a comma.

["4 shots booze","1 glasses wine","2 bottles beer","3 glasses water"] -> 1.2, 7
["10 shots booze", "1 bottle water"] -> 0.5, 0
["3 glasses wine", "2 bottles booze"] -> 6.2, 57
["6 shots beer", "3 glasses water"] -> 0, 0
["10 glasses beer"] -> 2.0, 15

Happy Coding!

TSQL, 301, 299, 219, 206 Bytes

Input goes into temp table #I (you said any format :)

SELECT * INTO #I FROM (
  VALUES
    (4,'shots','booze')
   ,(1,'glasses','wine')
   ,(2,'bottles','beer')
   ,(3, 'glasses','water')
) A (Q, V, N)

Code:

SELECT IIF(L<0,0,L),IIF(10*L-.5<0,0,10*L-.5)FROM(SELECT SUM(Q*S*P)L FROM(VALUES('bo%',.5),('be%',.1),('wi%',.2),('wa%',-.1))A(W,S),(VALUES('s%',.2),('g%',2),('b%',5))B(X,P),#I WHERE N LIKE W AND V LIKE X)A;

Thanks for the ideas to improve it, Micky T :)


The Traveling Toothbrush Introduction

Today's challenge is all about teeth. Specifically, how long it takes to brush from one tooth to another. Your challenge is, given the locations of two teeth, output the shortest amount of time possible to brush from the first to the second.

Challenge

For this challenge we will be using a layout of an average adult human mouth:

This diagram shows the widely used ISO numbering system. The system divides the mouth in four parts and assigns them each a number: upper right (1), upper left (2), lower left (3), and lower right (4). They then number the teeth of each section from the middle of the mouth out from 1-8. Therefore the fourth tooth from the center in the upper right side (section 1) is tooth number 14.

Let's assume brushing one tooth takes 1 unit of time.  Moving from one tooth to the next one sideways takes 0 units of time. You can also cross from a tooth to the tooth directly above or below it, which also takes 1 unit of time. So how long does it take you to brush from tooth 14 to tooth 31? By looking at the diagram above, you will see it takes 7 units of time. Here is how that's calculated:

Action : Unit of time
Brushing tooth 14 : 1 unit
Brushing tooth 13 : 1 unit
Brushing tooth 12 : 1 unit
Brushing tooth 11 : 1 unit
Brushing tooth 21 : 1 unit
Cross to bottom of mouth : 1 unit
Brushing tooth 31 : 1 unit
------------------------------
Total: 7 units

Note his is not the only route we could have took, but there are no shorter routes.

So your challenge is:

You will write a full program or function which accepts two arguments that are teeth numbers, and outputs (or returns) the shortest time to brush from one to the other.
You make take input as numbers or strings, and output how ever you wish (within acceptable methods).
Standard loopholes are forbidden by default.
This question is code-golf, so shortest bytecount wins.
Here are some testcases (Thanks Jonathan Allan):

14, 21 => 5
14, 44 => 3
14, 14 => 1
33, 37 => 5

Good luck!

JavaScript (ES6), 65 bytes

f=([s,t],[u,v])=>s<3^u<3?f(s+t,5-u+v)+2:s-u?t-+-v:t<v?++v-t:++t-v

for(i=1;i<5;i++)for(j=1;j<9;j++){let o=document.createElement("option");o.text=""+i+j;s.add(o);t.add(o.cloneNode(true));}

<select id=s></select><select id=t></select>
1

Takes input as strings.


A knight's graph on an N-by-N board In chess, a knight can only move to the positions marked with X relative to its current position, marked with ♞:

A Knight's Graph is a graph that represents all legal moves of the knight chess piece on a chessboard. Each vertex of this graph represents a square of the chessboard, and each edge connects two squares that are a knight's move apart from each other.

The graph looks like this for a standard 8-by-8 board.

Challenge:

Given an integer N, where 3 ≤ N ≤ 8, output an N-by-N matrix representing a board, where the number of possible moves from each position is shown. For N = 8, the output will be a matrix showing the values of each vertex in the graph above.

The output format is flexible. List of lists or even a flattened list etc. are accepted formats.

Complete set of test cases:

--- N = 3 ---
2 2 2
2 0 2
2 2 2
--- N = 4 ---
2 3 3 2
3 4 4 3
3 4 4 3
2 3 3 2
--- N = 5 ---
2 3 4 3 2
3 4 6 4 3
4 6 8 6 4
3 4 6 4 3
2 3 4 3 2
--- N = 6 ---
2 3 4 4 3 2
3 4 6 6 4 3
4 6 8 8 6 4
4 6 8 8 6 4
3 4 6 6 4 3
2 3 4 4 3 2
--- N = 7 ---
2 3 4 4 4 3 2
3 4 6 6 6 4 3
4 6 8 8 8 6 4
4 6 8 8 8 6 4
4 6 8 8 8 6 4
3 4 6 6 6 4 3
2 3 4 4 4 3 2
--- N = 8 ---
2 3 4 4 4 4 3 2
3 4 6 6 6 6 4 3
4 6 8 8 8 8 6 4
4 6 8 8 8 8 6 4
4 6 8 8 8 8 6 4
4 6 8 8 8 8 6 4
3 4 6 6 6 6 4 3
2 3 4 4 4 4 3 2

This is code-golf so the shortest solution in each language wins. Explanations are encouraged!

MATL, 17 16 bytes

t&l[2K0]B2:&ZvZ+

Try it online!

(-1 byte thanks to @Luis Mendo.)

The main part of the code is creating a matrix \$ K \$ for convolution:

$$ \mathbf{K} = \begin{pmatrix}0&1&0&1&0\\1&0&0&0&1\\0&0&0&0&0\\1&0&0&0&1\\0&1&0&1&0\end{pmatrix} $$

(Relative to the centre of the matrix, each 1 is a valid knight's move.)

t&l - Form a nxn matrix of all 1s (where n is the input). Let this be M.

[2K0] - Push an array containing [2, 4, 0] on stack

B  - Convert all to binary, padding with 0s as needed

0 1 0
1 0 0
0 0 0

2:&Zv - Mirror that on both dimensions, without repeating the final row/column ("symmetric range indexing").
This gives us the required matrix K.

0 1 0 1 0
1 0 0 0 1
0 0 0 0 0
1 0 0 0 1
0 1 0 1 0

Z+ - Perform 2D convolution of K over the earlier matrix M (conv2(M, K, 'same')),
summing up the 1s at legal knight move targets for each position

Result matrix is displayed implicitly.


What day is it (on Flooptonia)? You are a space tourist on your way to planet Flooptonia! The flight is going to take another 47,315 years, so to pass the time before you're cryogenically frozen you decide to write a program to help you understand the Flooptonian calendar.

Here is the 208-day long Flooptonian calendar:

Month       Days    Input Range
Qupu        22      [0-22)
Blinkorp    17      [22-39)
Paas        24      [39-63)
Karpasus    17      [63-80)
Floopdoor   1       [80]
Dumaflop    28      [81-109)
Lindilo     32      [109-141)
Fwup        67      [141-208)

Challenge

Your program, given an integer day in the year (range [0-208)) is to output the corresponding day of the month and name of the month (e.g. 13 Dumaflop).

There is an exception, however: Floopdoor a special time for Flooptonians that apparently deserves its own calendar page. For that reason, Floopdoor isn't written with a day (i.e. the output is Floopdoor, not 1 Floopdoor).

Test Cases

0   => 1 Qupu
32  => 11 Blinkorp
62  => 24 Paas
77  => 15 Karpasus
80  => Floopdoor
99  => 19 Dumaflop
128 => 20 Lindilo
207 => 67 Fwup

Rules

You must write a complete program.
You can assume that the input is always valid.
Your output may have a trailing newline but must otherwise be free of any extra characters. The case should also match the provided examples.
You may use date/time functions.
Code length is to be measured in bytes.

Python 3, 159 156 152 151 150 148 bytes

n=int(input())+1
for c,x in zip(b" C","Qupu Blinkorp Paas Karpasus Floopdoor Dumaflop Lindilo Fwup".split()):c>=n>0and print(*[n,x][-c:]);n-=c

The bytes object in the zip contains unprintable characters:

for c,x in zip(b"\x16\x11\x18\x11\x01\x1c C", ...): ...

(Thanks to @xnor for suggesting a for/zip loop for -3 bytes)


Square side pinpointing Welcome to my first code-golf challenge! :) Let's hop right into it.

Challenge:

Given two floating point vectors, O (origin) and T (target), you have to create a program to print the values L and R to STDOUT.

O is one corner of the square
T is one corner of the square that is located opposite to O
L is the 2D point (corner) that marks the other point of the uncomplete square
R is the 2D point (corner) that is opposite to L

Rules

Values for O and T have to be read from STDIN (see example inputs).
Again, L and R's values has to be printed to STDOUT.

Scoring and bonuses

Count the bytes of your program.
If your program draws lines that connect between O to L to T to R, subtract 15 bytes from the byte count.

Examples

First line covers inputs (first square brackets for O and next brackets for T) and other line represents expected output.

[0, 0] [3, 3]
Expected: [0, 3] [3, 0]
[0, 0] [-2, -2]
Expected: [-2, 0] [0, -2]
[1, -1] [4, 2]
Expected: [1, 2] [4, -1]
[0, -1] [0, 1]
Expected: [-1, 0] [1, 0]

NOTICE: inputs and outputs can be floating points!

Important information!

Values O and T can be taken in any format, as long as they come from STDIN (ex. Inside [] or ()...), use whatever format you want.
L and R can be printed in any order.
Remember: when (O->L->T->R->O) are connected, each side must have the same length!

Winning

This is code-golf so fewest byte answer wins!
Winner answer will be accepted at sunday 15.11.2015  20:00-22:00 (Finland time) (If I'm not wrong, that date is written like 11.15.2015 in the US, don't get confused).

Happy golfing!

Seriously, 11 bytes
A port of my TI-BASIC answer. Calculates mean(X)+i*(X-mean(X)).
,;Σ½;)±+ï*+

Explanation:
,           Read input
;           Duplicate
Σ½          Half the sum (the mean) of the top copy
;           Copy the mean
)           Rotate stack to the left
            Now there's a copy of the mean on the bottom
±+          Negate mean and add to input list
ï*          Multiply by i
+           Add to mean

Input as a list of two complex numbers: [1-1j,4+2j], and output in the same format: [(4-1j), (1+2j)].


Convert between Music clefs Before you leave, you do not have to understand much musical notation to do this challenge.

EXPLANATION

In standard sheet music,  double clefs go across the page serving as reference points to the notes, letting you know what note should be played. If you are not already familiar with the treble and bass clef,  here is a description from Wikipedia:

  A clef is a musical symbol used to indicate the pitch of written notes. Placed on one of the lines at the beginning of the stave, it indicates the name and pitch of the notes on that line. This line serves as a reference point by which the names of the notes on any other line or space of the stave may be determined.

In the image above, the top half of the lines is the Treble clef, denoted with a

The bottom half is the Bass clef, denoted with a

As you can see on the treble clef a note on the bottom-most line is an E. (I am not counting notes outside of the clef lines for this challenge) On the bass clef, the lowest line is a G.
To complete this challenge, you must do the following:

CHALLENGE

Given an input in one of the following forms (your choice), convert it to the opposite clef. Whether it is the Treble or Bass clef can be a Truthey/Falsey value in your language (not just any two values), e.g.

F# T
or
F# True
or
F# Treble

but not

F# -1
or
F# 4

Spaces and capitalization are optional, Flats will not appear, and trailing whitespace is not allowed.

Input          Expected Output
E   Treble     G
F   Treble     A
F#  Treble     A#
G   Treble     B
G#  Treble     C
A   Treble     C
A#  Treble     C#
B   Treble     D
C   Treble     E
C#  Treble     F
D   Treble     F
D#  Treble     F#
E   Treble     G
F   Treble     A
F#  Treble     A#
G   Bass       E
G#  Bass       F
A   Bass       F
A#  Bass       F#
B   Bass       G
C   Bass       A
C#  Bass       A#
D   Bass       B
D#  Bass       C
E   Bass       C
F   Bass       D
F#  Bass       D#
G   Bass       E
G#  Bass       F
A   Bass       F
A#  Bass       F#

Be forewarned, this is not a trivial constant difference challenge. Look closely at the inputs and outputs. If you look at a piano,

the black keys are sharps, denoted by #. Note that there is not an E# or a B#. This means that if you are given G# on the Bass clef, instead of returning E#, you need to return F

This is code-golf, so the smallest byte-count wins.

Befunge, 70 64 bytes
~0~:70p##~+2%00p+"A"-~7%2++7%:3%2%00g*:10p+"A"+,00g!10g+#@_"#",@

Try it online!
The input should be in the form C# Treble or F Bass, although the clef can simply be the first letter (i.e. T or B), since the rest of the input is ignored anyway.
Explanation
~0        Read the note and push a zero (the purpose of this will become apparent later).
~:70p     Read the following sharp or space and write that out as the next instruction.

As a result of this code modification, the next sequence of instructions will take one of two forms:
##~       The first # jumps over the second, and thus we perform the read instruction.
 #~       But if there's only one #, we'll ending up skipping the read instruction.

At this point the stack either contains note,0,sharp,space or note,0,space.
+2%       Add the top two stack items mod 2, returning 1 if we read a sharp, else 0 if not.
00p       Save this 'sharp' boolean for later use.

At this point the stack either contains note,0 or just note (with an implicit zero below).
+         By adding the top two items, we combine the 0 (if present) onto the note below.
"A"-      We can then subtract 'A' to convert the note into a number in the range 0 to 6.
~7%2+     Read the T/B clef, then mod 7 and add 2, returning 2 or 5 (the conversion offset).
+7%       Add that offset to our note number, then mod 7, to get the converted note number.
:3%2%     Make a dup, and calculate mod 3 mod 2 to determine the special cases (B# or E#).
00g*      Multiply that by the 'sharp' boolean, since we only care if the input was sharp.
:10p      Duplicate and save this special case boolean for later.
+         Now add it to the note number, since the special cases need to be offset by 1.
"A"+,     Then we can finally convert the number back into a character and output it.
00g!10g+  Now we check if the original note was not sharp, or if this was a special case.
#@_       If so, we exit immediately.
"#",@     Otherwise, we output a '#'.


Generating combinations without recursion Given a list of strings and a length, give all combinations of that list with the given length. The problem is: your code must not be recursive. Yes, it can be done. I have done it myself, when I had no clue what this "recursion" was.

Input: A list of strings of an undefined length, and an integer defining the length of the combination. The strings will be at least one character long, and will only contain letters or numbers. The way of input will be specified by you, the programmer.

Output: A list of possible combinations as strings, not necessarily distinct (although you can make it that way, if you like). You do not have to sort the list.

Test Cases:
As said before, the method of input will be specified by you.
[a,b] 3 -> Nothing
[1,0,0] 2 -> 10 10 00, or 00 10 if distinct.
[abc,bcd,cde] 2 -> abcbcd abccde bcdcde

If you even manage to do this, I will commend you. As always, shortest code wins. Good luck.

GolfScript (44 42 32 chars)

n%){\,=}+[[]]@1/{`{1$+}+%}%;\,n*

This takes input on stdin as a list of newline-separated strings followed by a line containing the desired subset size. It assumes that none of the input strings is empty. It takes some inspiration from Howard's solution, and can be shortened by two chars if using his input format:

~{\,=}+[[]]@1/{`{1$+}+%}%;\,n*

Output is a newline separated list of concatenations.

E.g.

$ golfscript.rb subcombo.gs <<END
> a
> b
> c
> 2
> END
ab
ac
bc

Note: this uses a horribly inefficient algorithm. A much nicer implementation in terms of performance is (62 61 chars)

n%)~\:S;2\?({2S,?<}{:s.~)&.s+.s^@4*/|}/{:x;S{;x.2/:x;1&},}%n*

which uses Gosper's hack.


Simple single-player board game, expected score distribution This is the first problem I've posted here; please post criticisms in comments.

Summary

A game board consists of a starting space, an ending space, and between them are N spaces, each with an instruction. You begin on the starting space with 0 points to your credit. Flip a coin or roll a die to choose the number 1 or 2. Move forward that many spaces. Now look at the instruction on the space you landed on. The possible instructions consist of "Do nothing", "Score x points", and "Move forward y spaces and obey the instruction there". x and y are positive. After obeying the instruction, go back to the coin flip. When you land on or pass the ending square, the game is over.

Given a description of a game board (number of squares, instruction on each space) your code should calculate the probability distribution of possible ending scores. It's irrelevant how many turns are taken before the end.

Input

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

Output

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

Scoring the entries

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

Examples

Easy

Input

3

1
F2
1

Output

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

Complex

Input

16

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

Output

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

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

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

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

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

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

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


Finding n'th character in a Lucky String Lucky numbers are those numbers which contain only "4" and/or "5". For example 4, 5, 44, 54,55,444 are lucky numbers while 457, 987 ,154 are not.

Lucky number sequence is one in which all lucky numbers exist in increasing order for example       4,5,44,45,54,55,444,445,454,455...

Now we concatenate all the lucky numbers (in ascending order) to make a lucky string     "4544455455444445454455..."

Given n, your task is to find the nth digit of the lucky string. If the digit is 4 then you have to print "F" else you have to print "E".

1<=n<=10^15

JavaScript - 49

for(s=i=0;!(r=s[n+i++]);s+=i.toString(2));"FE"[r]

Execute this on a JavaScript console (tested on Node), with n set to the 1-based index of the digit you want.

Explanation:

The script builds a version of the lucky string, and stops when the character we're looking for exists.

Lucky string:        4 5 44 45 54 55
Generated string: 011011100101110111

The lucky string is equivalent to the concatenation of all binary numbers with the leading one stripped. We can get the index of the appropriate character in s from n by adding the number of leading ones in the string to skip, or, equivalently, how many binary numbers we generated. Luckily for us, we can just grab the current value of i.

It greatly helps to see the final values of s and i after running. For sake of brevity, I won't post a table here, but you can certainly check their values in the console.

Details:

s=i=0

Initializes s and i. s later becomes a string, but rather than initialize to "0", 0 works fine because of implicit type conversion.

i++

Increments i every iteration.

r=s[n+i++]

Gets the character of s at n+i (0 or 1) and stores it in r.

!(r=s[n+i++])

Loops while the character we are looking for is still undefined.

s+=i.toString(2)

Appends the next binary number in sequence to s.

"FE"[r]

Causes the expression to evaluate to F if r is 0, E if r is 1.


Peter is a picky eater! There is a boy named Peter. Peter is a picky eater and doesn't like to eat the same kind of cookie again on the same day.
Peter gets a present, The present is a box of cookies! The box contains \$K\$ types of cookies. Also, it contains different amount of each type of cookie.
Peter, being the picky eater he is, Wants to eat \$n\$ cookies, on each \$n^{th}\$ day. Also, he does not want to eat more than 1 cookie of the same kind on any given day.
i.e. He eats \$1\$ cookie on the \$1^{st}\$ day, \$2\$ cookies on the \$2^{nd}\$ day and so on.
If there is no possible way for Peter to eat \$n\$ cookies at day \$n\$, he gives up and dumps the box. He also dumps the box if it becomes empty.
Find the maximum number of days that the box will last for Peter.
Input
\$K\$ Positive Integers, specifying the number of cookies for each different kind.
Output
An Integer corresponding to how many days Peter keeps the box.
Test Cases
INPUT -> OUTPUT
1 2 -> 2
1 2 3 -> 3
1 2 3 4 4 -> 4
1 2 3 3 -> 3
2 2 2 -> 3
1 1 1 1 -> 2
11 22 33 44 55 66 77 88 99 -> 9
10 20 30 40 50 60 70 80 -> 8
3 3 3 3 3 3 3 3 3 3 3 -> 7
3 3 3 3 3 3 3 3 3 -> 6
9 5 6 8 7 -> 5
1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 5 5 5 5 6 6 6 6 6 6 6 6 6 6 6 6 7 7 7 7 7 7 7 7 7 7 7 7 8 8 8 8 8 8 8 8 8 8 8 8 9 9 9 9 9 9 9 9 9 9 9 9 10 10 10 10 10 10 10 10 10 10 10 10 -> 35
1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 -> 32

Gist for test cases
This is code-golf so the shortest code wins.

Perl 5, 79 77 76 75 69 (rip) 68 64 62 bytes
Credit to @Lynn for improving my answer by 4 bytes (68 to 64) and the explanation about the comma operator in scalar context here https://docstore.mik.ua/orelly/perl2/prog/ch03_18.htm
Thanks @Nahuel Fouilleul for the tip using anonymous functions to save 2 bytes (64 to 62) but if it's not allowed I'll revert back
sub{$^=0;++$^while(@_=sort{$b-$a}@_),!grep--$_[$_]<0,0..$^;$^}

Test Cases Here: Try it online!
Expanded:
sub {                       # Declare subroutine
    $^ = 0;                 # Set scalar caret variable to 0 (you can put this variable right next to if statements and for loops etc)
    ++$^ while              # Pre increment caret while the condition below is true
        (                   # Bracket used so that you can declare/reassign values in a conditional
            @_ = sort {     # Sort the default array and store result back to default array
                $b - $a     # Sort from greatest to least (scalar variables a and b are default variables that come with sort)
            }@_             # Add the default array as a parameter for the sort
        ),                  # End of bracket (in scalar context like in this solution it will only grab the right most argument of the array so the while loop is entirely dependent on the condition below)
        !grep               # Only save values if the below statement is true for each item in default array then reverse the boolean (will return false if the size of the array after grep is greater than 0)
            --$_[$_] < 0,   # Check whether the pre decrement of item (default is $_) at the index of default array is less than 0. If the caret is out of range of the array, it will default to undef which is treated as 0 in math operations)
        0 .. $^             # Add an array of range 0 to caret inclusive to the grep
    ;                       # End of the while loop statement modifier
    $^                      # Return caret variable
}                           # End of subroutine