Generate a Rectangle from a Specification Introduction

This challenge is inspired by Grime, my 2D pattern matching language.
Basically, you are given a "grammar" that describes two-dimensional grids of characters, and your job is to generate a grid according to the grammar.
In addition, the grid should be as small as possible in a certain weak sense.

Input

Your input is a string containing lowercase ASCII characters and the symbols | and -.
For simplicity, the input does not contain repeated lowercase characters.
The string is a specification for a class of rectangular grids of characters, and it is parsed from left to right using a stack as follows.

Given a lowercase character c, push to the stack an m×n grid of the character c, for any m, n ≥ 1.
Given a pipe |, pop two grids A and B from the stack (B was on top), and push the grid AB obtained by concatenating B to the right of A. This requires that A and B have equal height.
Given a hyphen -, pop two grids A and B from the stack (B was on top), and push the grid A/B obtained by concatenating B to the bottom of A. This requires that A and B have equal width.

It is guaranteed that for some choices of m and n made during the parsing process (which may be different for each letter), the input specification correctly describes some rectangle, which is left on the stack at the end.

Output

Your output is a rectangular grid of characters specified by the input.
The grid must be minimal in the sense that removing any row or column would make it invalid.
You can return a newline-separated string (with or without a trailing newline), a 2D array of characters, or an array of strings, whichever is the most convenient format.

Note that you are not required to process the input exactly as described above; the only important thing is that your output is correct.

Example

Consider the specification

par-s||e-

First, we choose to push a 1×2 rectangle of p, and 1×1 rectangles of a and r (the reason for this will be clear later).
Then, we pop the a and r rectangles, and push their vertical concatenation

a
r

Next, we push a 1×2 rectangle of s, pop it and the above rectangle, and push their horizontal concatenation

as
rs

Then we pop that rectangle and the p rectangle, and push their concatenation

pas
prs

Finally, we push a 3×1 rectangle of e, pop it and the above rectangle, and push the vertical concatenation

pas
prs
eee

This is the output of the program, or at least one of the possibilities. Notice that even though

ppas
ppas
pprs
eeee

is also generated by the specification, it is not a valid output, since many of the rows and columns could be removed.

As a more subtle example, consider

co|m|p|il|e|r|-

This specification generates the rectangle

comp
iler

which is a valid output. However, it also generates

commp
iiler

which is valid too, since no single row or column can be removed without invalidating it.

Rules

You can give a full program or a function.
The lowest byte count wins, and standard loopholes are disallowed.

Extra Test Cases

You can use these to test your program.

Input:
a
Output:
a

Input:
co|mp|l|-ex|i|f|-y|
Example output:
cccoy
mplly
exify

Input:
ja-r|g-o|ni-|ze|d-|
Example output:
jronze
arondd
ggoidd

Input:
un|co|p-yr|i|gh-t-ab|-|le-||-
Example output:
unnnnnnn
coyriggl
ppyrihhe
ppyritte
ppyriabe

K, 123 110 bytes

I used a similar approach to cardboard_box's solution.

r:{y,x#,*|y};h:{t:(#x)|#y;r[t-#x;x],'r[t-#y]y};a:{(,x .|2#y),2_ y};*(){(a[{+h[+x;+y]}]x;a[h]x;(,,y),x)"-|"?y}/

This program is a series of helper definitions followed by a tacit function which takes a string as a right argument. Reformatting for readability and assigning the final function as f:

r: {y,x#,*|y};                           / repeat last row x times
h: {t:(#x)|#y;r[t-#x;x],'r[t-#y;y]};     / append horizontal
v: {+h[+x;+y]};                          / append vertical
a: {(,x[y@1;y@0]),2_ y};                 / pop two values, concat

f: *(){:[y="-";a[v;x]; y="|";a[h;x]; (,,y),x]}/;

Use example:

  f "ja-r|g-o|ni-|ze|d-|"
("jronze"
 "aroidd"
 "ggoidd")

Tested using Kona, but it will also work in oK if you replace the : in the definition of f with a $- k5 changed the syntax of "cond".

A key point is recognizing that doing a vertical append is the transpose of the horizontal append of the transpose of both matrices. (See definition v.) I think there's still room to squeeze out a few characters here and there. If anyone is interested in a more detailed explanation I can provide one.

edit:

Updated the program at the top of this entry. Ungolfed version:

r: {y,x#,*|y};                           / repeat row x times
h: {t:(#x)|#y;r[t-#x;x],'r[t-#y;y]};     / append horizontal
v: {+h[+x;+y]};                          / append vertical
a: {(,x .|2#y),2_ y};                    / apply a concat
f: *(){(a[v]x;a[h]x;(,,y),x)"-|"?y}/;

Notable length optimizations include the use of "dot apply" in a, replacing the "cond" with list indexing in f (less efficient, but shorter) and replacing terms of the form a[b;c] into a[b]c where permitted by grouping. Since I'm no longer using "cond" or any primitives which are different between k3 and k5 this version now works in oK without modification.


The Ever Amplifying Zigzag Write a program or function that takes in a positive integer N and outputs the first N numbers of this amplifying zigzag pattern, using only the lines needed:
                                         26
                                       25  27                                      .
         10                          24      28                                  .
        9  11                      23          29                              .
 2     8     12                  22              30                          44
1 3   7        13              21                  31                      43
   4 6           14          20                      32                  42
    5              15      19                          33              41
                     16  18                              34          40
                       17                                  35      39
                                                             36  38
                                                               37

So, if N is 1 the output is
1

If N is 2, the output is
 2
1

If N is 3 the output is
 2
1 3

If N is 4 the output is
 2
1 3
   4

If N is 10 the output is
         10
        9
 2     8
1 3   7
   4 6
    5

If N is 19 the output is
         10
        9  11
 2     8     12
1 3   7        13
   4 6           14
    5              15      19
                     16  18
                       17

and so on.
Notes

Each peak or trough of the zigzag reaches its point one more line away from the line with the 1 on it than the previous peak or trough.

N is not limited to 44. The zigzag grows in the same pattern and larger N should be supported.

Numbers with multiple digits should only "touch" at their corners, as depicted. Make sure this works when N is 100 and above.

There should be no empty (or space only) lines in the output except one optional trailing newline.

Any line may have any amount of trailing spaces.

Scoring
The shortest code in bytes wins. Tiebreaker is earlier answer.

Jelly, 41 37 29 bytes

RDµḌ’½Ċ-*_\x©L€Ṣ.ị®ạ€⁶ẋj"FZj⁷

Try it online!

How it works

RDµḌ’½Ċ-*_\x©L€Ṣ.ị®ạ€⁶ẋj"FZj⁷  Main link. Argument: n (integer)

R                              Range; yield [1, ..., n].
 D                             Decimal; yield A =: [[1], ..., [1, 0], ...].
  µ                            Begin a new, monadic chain. Argument: A
   Ḍ                           Undecimal; convert back to falt range.
    ’                          Decrement to yield [0, ..., n-1].
     ½Ċ                        Take the square root and round up (ceil).
       -*                      Elevate -1 to each rounded square root.
         _\                    Cumulatively reduce by subtraction.
                               This yields [1, 2, 1, 0, -1, 0, ...], i.e., the
                               vertical positions of the digits in A.
             L€                Compute the length of each list in A.
           x                   Repeat the nth position l times, where l is the
                               nth length.
            ©                  Copy the result to the register.
               Ṣ               Sort.
                .ị             At-index 0.5; yield the last and first element,
                               which correspond to the highest and lowest position.
                  ạ€®          Take the absolute difference of each position in the
                               register and the extrema.
                               This yields the number of spaces above and below
                               the integers in r as a list of pairs.
                     ⁶ẋ        Replace each difference with that many spaces.
                         F     Flatten the list A.
                       j"      Join the nth pair of strings of spacing, separating
                               by the nth digit in flat A.
                          Z    Zip/transpose the result.
                           j⁷  Join, separating by linefeeds.


Add All Permutations of a Number You have to make something that takes in one input from a default I/O method (as an integer), and prints out the sum of all the permutations of that number (not necessarily unique)

For example:

10 would return 11 because 10 can have 2 permutations (10 and 01), and the sum of those two numbers would be 11

202 would have 6 permutations (202, 220, 022, 022, 202, 220), so the sum would be 888.

The input is positive, and the input can be taken as any type, but your program's output must be a number.

Standard loopholes are not allowed, and as usual, since this is code golf, the shortest answer in bytes wins!

Japt -x, 1 byte
Takes input as a string.
á

Try it

Explanation
á     :Get permutations
      :Implicitly reduce by addition and output


Convert to and from the backwards-factorial number base I wanted to ask this question: Convert to and from the factorial number system but I'm a couple of years too late!

So, instead you must convert to and from the lairotcaf backwards-factorial number base! The way it works is that the first digit is always 0, the maximum value of the next digit is 1, then 2 and so on. If a number has n digits, then each place value is given by n!/i! where i is the digit position starting at 1 on the left. The highest digit position is on the right. This means that each length uses different place values!

There is a unique shortest way to represent each number, which is what you must output for a decimal number input. If an input number starts with a 0, convert it to decimal. If it starts with any other digit, convert it to the backwards-factorial number base.

0 is both valid and the same number in both bases. In the test data no input value will use, or produce a number with a digit higher than 9. Note that the shortest representation of some numbers starts with multiple 0s.

Digit position:   1   2   3   4   5   6
Place value:    720 360 120  30   6   1
                  0   0   2   2   3   3
                  0   0 240+ 60+ 18+  3=321

This is the shortest way to represent 321 because removing a digit makes the highest number possible only 119 (5! - 1).

Test data:

Input:      Output:
0           0
1           01
002         2
3           010
011         4
5           012
0012        6
21          0121
0130        24
01000       60
01234       119
001000      120
321         002233
011235      563
0010330     987
4321        0120252
54321       000325536
654321      0010135621
0112351713  2838883
7654321     00102603574

This is code-golf so the fewest bytes wins!

ES6, 135 108 bytes

s=>s<"1"?[...s].reduce((t,d,i)=>+d+t*++i):eval("for(i=j=k=1;i<=s;i*=++j);for(r='';k<=j;k++)r+=s%i/(i/=k)|0")

Converting from backwards-factorial is nice and easy. Converting to it... not so nice. I found a 119-byte version that doesn't use eval:

s=>s<"1"?[...s].reduce((t,d,i)=>+d+t*++i):(i=j=k=1,g=_=>s<i||g(i*=++j),g(),[...Array(j)].map(_=>s%i/(i/=k++)|0).join``)


First Last Last First Challenge

The task is simple. Given an array and a first and last value: Return the first of the last after the first, and the last of the first before the last.

Or simply: Given an array, var1, var2.

Example Array:

[ var2, , var1, , var2, , var2, var1, var2, ]

Return:

The index of the first var2 on the right side of the first var1 that appears in the array.

[ var2, , first var1, , first var2, , second var2, var1, third var2, ]

The index of the first var1 on the left side of the last var2 that appears in the array.

[ var2, , second var1, , var2, , var2, first var1,last var2, ]

Input

Two distinct positive integers

Array of positive integers

Output

Index of answers, in order

Rules

The array will contain at least one of each variable (minimum size of 2)

Assume inputs work

  Example: 0, 1 [1, 0] or similar would fail

IO is flexible

Examples

Input
First = 2; Last = 4; [0, 2, 4, 2, 3, 1, 4, 0, 1, 2, 4, 9]

Output
2, 9

Input
First = 4; Last = 2; [0, 2, 4, 2, 3, 1, 4, 0, 1, 2, 4, 9]

Output
3, 6

Input
First = 0; Last = 1; [0, 1]

Output
1, 0

JavaScript (ES6), 63 bytes

(x,y,a)=>a.map(P=(v,i)=>v-y?v-x?0:a=i:1/(p=a)?P=+P||i:0)&&[P,p]

Try it online!

Commented

(x, y, a) =>          // given the two integers x, y and the array a[]
  a.map(P =           // initialize P to a non-numeric value
            (v, i) => // for each value v at position i in a[]:
    v - y ?           //   if v is not equal to y:
      v - x ?         //     if v is not equal to x:
        0             //       do nothing
      :               //     else (v = x):
        a = i         //       save the current position in a
    :                 //   else (v = y):
      1 / (p = a) ?   //     update p to a (last position of x); if p is numeric (>= 0):
        P = +P || i   //       unless P is also already numeric, update it to i
                      //       (if P is numeric, it's necessarily greater than 0 because
                      //       we've also seen x before; that's why +P works)
      :               //     else:
        0             //       do nothing
  )                   // end of map()
  && [P, p]           // return [P, p]

Alternate versions

Using JS built-ins, a more straightforward answer is 79 bytes:

(x,y,a)=>[a.indexOf(y,a.indexOf(x)),a.slice(0,a.lastIndexOf(y)).lastIndexOf(x)]

which can be slightly compressed to 75 bytes:

(x,y,a)=>[a.indexOf(y,a.indexOf(x)),a.slice(0,a[L='lastIndexOf'](y))[L](x)]

Try it online!

Edit: @Neil managed to reduce it to a very nice 67-byte:

(x,y,a,f=s=>a[z=y,y=x,x=z,s+=`ndexOf`](x,a[s](y)))=>[f`i`,f`lastI`]

Try it online!


Shortest Identifying Substring This challenge is inspired by dmenu, the program I use to launch other programs on my Linux box. To start, for example, GIMP, I simply hit the keyboard shortcut I have assigned to dmenu, type "gimp" and hit enter. However, I don't have to type the whole name. On my machine, if I type "gim", that's enough. Here's how dmenu decides which program to launch when you hit enter1:

Find all program names that contain the input as a substring.
Sort this list alphabetically.
Take the items in the list that begin with the input, and (preserving their order) put them at the beginning.
Launch the first2 program in the list.

While this is usually quite convenient, it is sometimes annoying. For example, on my computer I have chromedriver and chromium. I never want to launch chromedriver, but it's earlier alphabetically than chromium is. If I start typing at the beginning of the word, like I naturally want to do, I have to type six characters to specify that I mean the latter.

However, we don't need to start typing at the beginning of the word! chromium is, alphabetically, the first program name containing the substring iu. I have no programs that start with iu. Therefore, I only need to type those two characters to unambiguously specify which program I want.

For this challenge, your program or function will receive at least two lines of input. No line will contain any whitespace characters (other than the newline, obviously) and the first line is guaranteed to be repeated somewhere in the remaining input. Your program or function will output (stdout, return, etc.) the shortest string that, using dmenu's rules, would find that first line in all the rest. If there are two or more that are tied for shortest, you may output whichever you like.

Examples

In:
bbbb
aaaa
bbbb
cccc

Out:
b

In:
bc
bc
aaaa
bbc

Out:
bc

1: I don't actually know this to be the case, but in my experience it seems to work this way.
2: When actually using dmenu, you can hit left and right to choose different items in the list, but that's irrelevant for this challenge.

Pyth, 22 21 bytes

hfqzho>xNT0Sf}TY.z.:z

isaacg and me got the same 21 solution more or less at the same time. So he deleted his solution.

Try it online: Pyth Compiler/Executor

Explanation

                         implicit:  z = first input line
                                   .z = all other input lines
 f                .:z   filter all substrings T of z, which satisfy:
            f   .z        filter .z for lines Y, which satisfy:
             }TY            T in Y
           S              sort these lines alphabetically
     o                    order these lines N by:
      >xNT0                 (index of T in N) > 0
                          (sorting in Pyth is stable, so this brings the lines,
                           which start with T, to the beginning
                           without messing up the alphabetically order)
  qzh                     z == first element of ...
h                       print first elment


Infinite Boolean Matrix It's geeky to see a Boolean Matrix animation, but a live one would be better. Echoing only 1s and 0s create a program that creates an infinite loop of integer matrix.

1s and 0s are randomly echoed like an error.

Like this?

PHP, 28 22

for(;;)echo rand(0,1);

For a better view:

<div style="width:800px;margin:0 auto;background-color:black;color:green;">
    <?php for(;;)echo rand(0,1); ?>
</div>


Digital River (Shortest And Fastest Solution) This is my first question, so I hope it goes well.

Background:

It's not the rivers that you might be thinking about. The question revolves around the concept of digital rivers. A digital river is a sequence of numbers where the number following n is n plus the sum of its digits.

Explanation:

12345 is followed by 12360 since 1+2+3+4+5=15 and so 12345 + 15 gives
12360. similarly 145 is followed by 155. If the first number of a digital river is M we will call it river M.

For e.g: River 480 is the sequence beginning {480,492,507,519....}, and river 483 is the sequence beginning {483,498,519,....}. Normal streams and rivers can meet, and the same is true for digital rivers. This happens when two digital rivers share some of the same values.

Example:

River 480 meets river 483 at 519. River 480 meets river 507 at 507 and never meets river 481. Every digital river will eventually meet river 1, river 3 or river 9.

Write a program that can determine for a given integer n the value where river n first meets one of these three rivers.

Input

The input may contain multiple test cases. Each test case occupies a separate line and contains an integer n (1 <= n <= 16384). A test case with value of 0 for n terminates the input and this test case must not be processed.

Output

For each test case in the input first output the test case number (starting from 1) as shown in the sample output. Then on a separate line output the line "first meets river x at y". Here y is the lowest value where river n first meets river x (x = 1 or 3 or 9). If river n meets river x at y for more than one value of x, output the lowest value. Print a blank line between two consecutive test cases.

Test case

Input:

86
12345
0

Output:

Case #1

first meets river 1 at 101

Case #2

first meets river 3 at 12423

Scoring:

The fastest algorithm wins. In case of tie. The one with shorter code will win.

Thanks to mbomb007 for pointing out my error.

p.s: I want to have the fastest solution rather than the smallest one.
I also have a solution of mine which is slow. For that look here.

Note:

I will be using this for code testing. And performance checking.

C, 320 294 bytes

Compile with -std=c99

#include<stdio.h>
int s(int i){for(int j=i;j;j/=10)i+=j%10;return i;}int main(){int c=0,i;while(scanf("%d",&i)){c++;if(!i)continue;int j,o[]={1,3,9},p[]={1,3,9};Q:for(j=0;j<3;j++){if(o[j]==i)goto D;else if(o[j]<i){o[j]=s(o[j]);goto Q;}}i=s(i);goto Q;D:printf("Case #%d\n\nfirst meets river %d at %d\n\n",c,p[j],o[j]);}}

Ungolfed:

#include <stdio.h>

int s(int i)
{
    for(int j = i; j; j /= 10)
        i += j % 10;
    return i;
}

int main()
{
    int c = 0, i;
    while(scanf("%d", &i))
    {
        c++;
        if(!i)
            continue;
        int j,o[]={1,3,9},p[]={1,3,9};
        Q: for(j = 0; j < 3; j++)
        {
            if(o[j] == i)
                goto D;
            else if(o[j] < i)
            {
                o[j] = s(o[j]);
                goto Q;
            }
        }
        i = s(i);
        goto Q;
        D: printf("Case #%d\n\nfirst meets river %d at %d\n\n", c, p[j], o[j]);
    }
}

Try it out!

Essentially, the "target" rivers are increased until they're greater than the river we're testing against, and afterwards the test river is increased. This is repeated until the test river is equal to some other river.

I'm not reading parameters from the command line in this program, and I'm not sure if you're supposed to. Now you can pass parameters to STDIN. You can terminate by passing a non-numeric input.

Also darn, beaten by half an hour.


Evaluating Dotty Strings Write a program that takes in an odd length string containing only the characters . and :. With the aid of an initially empty stack, generate a number from this string as follows:

For every character c in the string (going from left to right)...

If c is . and the stack has less than 2 elements, push 1 on the stack.
If c is . and the stack has 2 or more elements, pop the two top values off the stack and push their sum onto the stack.
If c is : and the stack has less than 2 elements, push 2 on the stack.
If c is : and the stack has 2 or more elements, pop the two top values off the stack and push their product onto the stack.

The resulting number is the value at the top of the stack. Your program should print this number to stdout (with an optional trailing newline).

(A little analysis shows that there is only ever one number left unless the string has even length, which is why we are ignoring those. In fact, the stack never has more than 2 elements.)

For example, the number for ::...:.:. is 9:

  2   1   2   2    /______ stack just after the character below is handled
2 2 4 4 5 5 7 7 9  \
: : . . . : . : .  <-- string, one character at a time

As a sanity check, here are the numbers for all strings of length 1, 3, and 5:

. 1
: 2
... 2
..: 1
.:. 3
.:: 2
:.. 3
:.: 2
::. 4
::: 4
..... 3
....: 2
...:. 4
...:: 4
..:.. 2
..:.: 1
..::. 3
..::: 2
.:... 4
.:..: 3
.:.:. 5
.:.:: 6
.::.. 3
.::.: 2
.:::. 4
.:::: 4
:.... 4
:...: 3
:..:. 5
:..:: 6
:.:.. 3
:.:.: 2
:.::. 4
:.::: 4
::... 5
::..: 4
::.:. 6
::.:: 8
:::.. 5
:::.: 4
::::. 6
::::: 8

The shortest program in bytes wins. Tiebreaker is earlier post.

You may assume the input is always valid, i.e. a string containing only . and : whose length is odd.
Instead of writing a program, you may write a function that takes in a valid string and prints or returns the generated number.

CJam, 27 24 23 22 bytes
q{i]_,+~3<-"1+2* "=~}/

Pretty straight forward. I use CJam's stack as the stack mentioned in the question ;)
Algorithm
First lets look at the ASCII code for . and :.
'.i ':ied

[46 58]

Since in CJam, index wraps around, lets see if we can use these values directly to get the desired operation ..
'.i4% ':i4%ed

[2 2]

So I cannot simply use the ASCII codes in a 4 length operation string. Lets try some other values
'.i 10% ':i 10%ed

[6 8]

which on a 4 length string boils down to

[2 0]

I can use this mod 10 operation but that will cost be 2 bytes. Lets try something else
'.i5% ':i5%ed

[1 3]

Nice!, now we just subtract 1 for the stack size condition to get the indexes 0, 1, 2 and 3 and use a 5 length array ("1+2* ") as a switch case. The last space is just a filler to make it of length 5. This is just 1 extra byte as compared to modding operation.
q{                  }/    e# parse each input character in this loop
  i]                      e# convert '. or ': into ASCII code and wrap everything
                          e# in stack in an array
    _,+                   e# Copy the stack array, take its length and add the length to
                          e# the stack array
       ~3<                e# unwrap the stack array and check if stack size is less than 3
                          e# 3 because either . or : is also on stack
          -               e# subtract 0 or 1 based on above condition from ASCII code
           "1+2* "        e# string containing the operation to perform
                  =~      e# chose the correct operation and evaluate it

Try it online here
1 byte saved thanks to cosechy


MQTT subscription topic match Background
MQTT (Message Queuing Telemetry Transport) is an ISO standard publish-subscribe-based messaging protocol (Wikipedia).
Each message has a topic, such as the following examples:

myhome/groundfloor/livingroom/temperature
USA/California/San Francisco/Silicon Valley
5ff4a2ce-e485-40f4-826c-b1a5d81be9b6/status
Germany/Bavaria/car/2382340923453/latitude

MQTT clients may subscribe to message topics using wildcards:

Single level: +
All levels onward: #

For example, the subscription myhome/groundfloor/+/temperature would produce these results (non-conformances in bold):
✅ myhome/groundfloor/livingroom/temperature
✅ myhome/groundfloor/kitchen/temperature
❌ myhome/groundfloor/livingroom/brightness
❌ myhome/firstfloor/livingroom/temperature
❌ garage/groundfloor/fridge/temperature
Whereas the subscription +/groundfloor/# would produce these results:
✅ myhome/groundfloor/livingroom/temperature
✅ myhome/groundfloor/kitchen/brightness
✅ garage/groundfloor/fridge/temperature/more/specific/fields
❌ myhome/firstfloor/livingroom/temperature
❌ myhome/basement/corner/temperature
More info here.
The Task
Implement a function/program accepting two strings and returning a boolean. The first string is the subject topic, the second is the criteria topic. The criteria topic uses the subscription syntax detailed above. The function is truthy when the subject matches the criteria.
Rules for this task:

Topics are ASCII
There are no criteria fields beyond the # wildcard
Wildcards do not appear in subject topics
Number of subject fields >= number of criteria fields
There are no 0-character fields nor leading or tailing forward slashes

Test cases
criteria1 = "myhome/groundfloor/+/temperature"
criteria2 = "+/groundfloor/#"
("abc", "ab") => false
("abc", "abc") => true
("abc/de", "abc") => false
("myhome/groundfloor/livingroom/temperature", criteria1) => true
("myhome/groundfloor/kitchen/temperature", criteria1) => true
("myhome/groundfloor/livingroom/brightness", criteria1) => false
("myhome/firstfloor/livingroom/temperature", criteria1) => false
("garage/groundfloor/fridge/temperature", criteria1) => false
("myhome/groundfloor/livingroom/temperature", criteria2) => true
("myhome/groundfloor/kitchen/brightness", criteria2) => true
("garage/groundfloor/fridge/temperature/more/specific/fields", criteria2) => true
("myhome/firstfloor/livingroom/temperature", criteria2) => false
("myhome/basement/corner/temperature", criteria2) => false
("music/kei$ha/latest", "+/kei$ha/+") => true

Jelly, 20 bytes

ṣ€”/ZṖF”#eƊ¿œiÐḟ”+ZE

A monadic Link accepting a list of lists of characters, [topic, pattern], which returns 1 or 0 for match or no-match respectively.

Try it online! Or see a test-suite.

How?

ṣ€”/ZṖF”#eƊ¿œiÐḟ”+ZE - Link: list of lists of characters, [topic, pattern]
 €                   - for each:
ṣ                    -   split at occurrences of:
  ”/                 -     '/' character
    Z                - transpose (any excess of topic is kept)
           ¿         - while...
          Ɗ          - ...condition: last three links as a monad:
       ”#            -   '#' character
         e           -   exists in:
      F              -     flatten
     Ṗ               - ...do: pop the tail off
              Ðḟ     - filter discard those for which:
            œi       -   first multi-dimensional index of: ([] if not found, which is falsey)
                ”+   -     '+' character
                  Z  - transpose
                   E - all equal?


Find the BCD difference of a number BCD difference

Given an integer n, convert it to BCD (binary-coded decimal)  by replacing each decimal digit with its 4-digit binary representation

 234 -> 0 0 1 0 0 0 1 1 0 1 0 0

Then rotate the list of binary digits in order to find the largest and smallest numbers, representable by this list without other rearrangements.

max: 1 1 0 1 0 0 0 0 1 0 0 0  (the entire list rotated left 6 times)
min: 0 0 0 0 1 0 0 0 1 1 0 1 (the entire list rotated right 2 times)

Convert these numbers back to decimal, treating the list of bits as regular binary and subtract the smallest from the largest:

1 1 0 1 0 0 0 0 1 0 0 0 -> 3336
0 0 0 0 1 0 0 0 1 1 0 1 -> 141

3336 - 141 -> 3195

The output is the difference of the largest and smallest numbers found.

Test cases:

234 -> 3195
1234 -> 52155
12 -> 135
975831 -> 14996295
4390742 -> 235954919
9752348061 -> 1002931578825

Wolfram Language (Mathematica), 89 88 bytes

Thanks to Jenny_mathy for saving 1 byte.

i=IntegerDigits;Max@#-Min@#&[#~FromDigits~2&/@NestList[RotateRight,Join@@i[i@#,2,4],#]]&

Try it online!

This is terribly inefficient, because it generates n rotations of the BCD of n, which is way more than we need. We can make this is a bit more efficient by saving the result of the Join@@ in k and replacing the # at the end with Length@k. That lets us generate a scatterplot quite easily:

I'm really intrigued by the contrast of local structure and overall chaos.


Up and down, up and down Challenge:

Given a positive integer input n, create a vector that follows this pattern:

0  1  0 -1 -2 -1  0  1  2  3  2  1  0 -1 -2 -3 -4 -3 -2 -1 ... ±(n-1) ±n

Or, explained with words: The vector starts at 0, and makes increments of 1 until it reaches the smallest odd positive integer that isn't part of the sequence, then it makes decrements until it reaches the smallest (in magnitude) even negative integer that isn't part of the sequence. It continues this way until n is reached. The sequence will end on positive n if n is odd, and negative n if n is even.

The output format is flexible.

Test cases:

n = 1
0  1
-----------
n = 2
0  1  0 -1 -2
-----------
n = 3
0  1  0 -1 -2 -1  0  1  2  3
-----------
n = 4
0  1  0 -1 -2 -1  0  1  2  3  2  1  0 -1 -2 -3 -4
-----------
n = 5
0  1  0 -1 -2 -1  0  1  2  3  2  1  0 -1 -2 -3 -4 -3 -2 -1  0  1  2  3  4  5

You may choose to take the n zero-indexed. n = 1 would then give 0  1  0 -1 -2.

This is code-golf, so the shortest code in each language wins! Explanations are encouraged as always!

R, 58 54 50 48 43 bytes

-2 bytes thanks to MickyT

function(n)diffinv(rep(1:n%%2*2-1,1:n*2-1))

Try it online!

function(n)
 diffinv(                           # take cumulative sum, starting at 0 of
             1:n%%2*2-1,            # a vector of alternating 1,-1
         rep(                       # repeated
                        1:n*2-1))   # 1, 3, 5, etc. times


Build a Mass Spectrometer! Challenge

Given the high resolution molecular mass of an organic molecule, output the molecule's molecular formula.

Explanation

The input will be a single number to three decimal places of precision, the relative molecular mass of the molecule.

Here, the molecular mass is defined as the sum of the masses of the atoms in the compound. Since you only are finding the molecular formulae of organic compounds, the atomic masses you need to know are:

C, Carbon: 12.011
H, Hydrogen: 1.008
O, Oxygen: 15.999
N, Nitrogen: 14.007

Your formula should only ever contain carbon, hydrogen, oxygen or nitrogen.

When writing the formula, it should take the form:

CaHbOcNd

Where the elements must be in that order (C -> H -> O -> N, so C2O8N4H6 should be C2H6O8N4) and a, b, c and d are numbers of the preceding element in the molecule (i.e. C2 means that there are two carbon atoms in the molecule).

If a, b, c or d are zero, that element should not be included in the formula (e.g. C2H6O2N0 should be C2H6O2). Finally, if a, b, c or d are one, you should not include the number in the formula (e.g. C1H4 should be CH4).

The input will always be valid (i.e. there will be a molecule with that mass). If the input is ambiguous (multiple molecules have the same mass), you must only output one of the molecules. How you choose this molecule is up to you.

Worked Example

Suppose the input is 180.156, there is only one combination of the elements which can have this molecular mass:

12.011*6 + 1.008*12 + 15.999*6 + 14.007*0 = 180.156

So there are:

6 Carbons
12 Hydrogens
6 Oxygens
0 Nitrogens

Therefore, your output should be:

C6H12O6

More Examples

Input -> Output

28.054 -> C2H4
74.079 -> C3H6O2
75.067 -> C2H5O2N
18.015 -> H2O

Winning

Shortest code in bytes wins.

Mathematica, 108 bytes

Print@@Join@@({Characters@"CHON",#}ᵀ/.a_/;Last@a<2:>Table@@a)&/@{12011,1008,15999,14007}~FrobeniusSolve~#&

Pure function expecting the input as an integer (1000 times the relative molecular mass); it prints all possible answers to STOUD (and returns an array of Nulls).

The heavy lifting is done by the builtin {12011,1008,15999,14007}~FrobeniusSolve~#, which finds all nonnegative integer combinations of the hardcoded weights that equal the input. {Characters@"CHON",#}ᵀ puts each such combination in a form like {{"C", 0}, {"H", 1}, {"O", 2}, {"N", 3}}. (ᵀ is actually the 3-byte private Mathematica character U+F3C7.)

The transformation rule /.a_/;Last@a<2:>Table@@a changes pairs of the form {x, 0} to {} and pairs of the form {x, 1} to {x} (and spits out errors as it tries to apply to the whole expression as well). Then Print@@Join@@ prints the result in the correct form, avoiding the need to cast the integers as strings and concatenate.


Sinusoidal ASCII-art animated text I somewhat miss those old demos showing the capabilities of computers when they were called x86 instead of i3, i5 and i7. One of the first I watched in my 386 was the Unreal demo from Future Crew that is now celebrating its 25th anniversary. At minute 0:43 the first part of the demo starts and we see a scrolling text following a sinusoidal path. Let's try to imitate that effect in ASCII art!

The challenge

Given this path:

***                                ***
   ***                          ***
      **                      **
        *                    *
         *                  *
         *                  *
          *                *
           **            **
             ***      ***
                ******

and an input text, draw the text following that path, like this:

Thi                                Golf!
   s i                          de       Yay
      s                       Co            !
        P
         r                  d
         o                  n
          g                a
           ra            s
             mmi      zle
                ng Puz

Note that the spaces count as characters in the path, and that the path repeats itself if the text is longer than the sample.

The animation part

Once you have drawn the text, wait for 100 ms (to create an animation of around 10 fps) and draw the text again but starting from the next position of the path. So, for frame #n, calculate n modulo 40 and start drawing in the following position of the path with the text always aligned to the left of the canvas:

***                                ***
|  ***                          ***  |
|     **                      **     |
|       *                    *       |
|        *                  *        |
|        *                  *        |
|         *                *         |
|          **            **          |
|            ***      ***            |
|               ******               |
Position 0                 Position 39

So for frame 10 we will have:

                           and Co
                        es       de
                      zl            Go
                     z                l
                    u                  f
T                   P                  !
 h
  is             ng                       Ya
     is       mmi                           y!
        Progra

Notes

Input will be a single string (or char array, whatever) with the text to animate, and will always have at least 1 character.
Valid characters to animate are those in the printable ASCII set.
The path to follow will be exactly as given.
Text will always be aligned to the left of the canvas, so the effect will be the text waving like a flag, with no text displacement. And by canvas I mean screen or whatever you will use to show the text. ;-)
Frames must be clear of any characters/pixels from previous frames unless the character/pixel is the same in both frames.
The speed of the animation does not matter as long as it runs smoothly or as fast as your device can (we can set a minimum of 5 fps, but this is not a requirement). Just adjust the speed to make it fluid and do not worry if the waiting times are not exactly the same.
The animation will loop endlessly.

This is code-golf, so may the shortest program or function capable of animating the text win!

HTML + ES6, 241 244 237 bytes
Breakdown:

HTML: 16 bytes
JS function: 221 bytes

let f =

s=>setInterval(_=>o.innerHTML=[...s].map((c,i)=>([j,y]=[...Array(40)].map((_,k)=>[j=k%20,y,y+=77732>>j&1?k<20||-1:0],y=0)[(i+p)%40],a[y]=a[y]||[...s].fill` `)[x]=(x+=j!=9,c),x=0,a=[],p++)&&a.map(r=>r.join``).join`
`,p=30)

f("This is Programming Puzzles and Code Golf! Yay!")

How?
Building the path
The following code builds the path:
[...Array(40)].map((_, k) =>
  [
    j = k % 20,
    y,
    y += 77732 >> j & 1 ? k < 20 || -1 : 0
  ],
  y = 0
)

This gives an array of arrays [j, y, z] where j is the position modulo 20, y is the y-coordinate at this position and z is not used later (it just happens to be computed here to save some bytes).
Because the path is symmetric, we only need to encode the 20 first positions. We do that by using a binary number where each 1 bit means that y must be updated (+1 for the first half, -1 for the second half).
001
   001
      01
        1
         1
         1
          1
           01
             001
                000

With the first position being mapped to the least significant bit, this gives:
00010010111110100100 as binary = 77732 as decimal

Because this binary number is itself also symmetric, we can read it in the same order for the 2nd half.
Hence the formula:
y += (77732 >> j) & 1 ? (k < 20 ? 1 : -1) : 0

which can also be written as:
y += (77732 >> j) & 1 ? k < 20 || -1 : 0

where k is the position and j is the position modulo 20.
Updating x is much easier: we just have one special case to detect by comparing the position modulo 20 with 9.
Drawing the text
In the following code, the path building code described above has been replaced by a path variable for readability.
s => setInterval(                       // set a periodic timer:
  _ =>                                  //   with an anonymous callback
    o.innerHTML =                       //   which updates the content of 'o'
      [...s].map((c, i) => (            //   for each character c of the string s
          [j, y] = path[(i + p) % 40],  //     retrieve j and y from the path
          a[y] = a[y] || [...s].fill` ` //     initialize a[y] if it's undefined
        )[x] = (x += j! = 9, c),        //     update a[y][x] / update x
        x = 0,                          //     initialize x
        a = [],                         //     initialize a[]
        p++                             //     increment the phase
      ) &&                              //   end of map()
      a.map(r => r.join``).join`\n`,    //   join everything together
  p = 30                                //   initial phase = interval period = 30
)                                       // end of timer definition


(Javascript) itertools.groupBy, e.g. [0,0,1,1,0] -> [[0,0],[1,1],[0]] (language-specific challenge)

Specification:

Language: ECMAScript, any version[1]

Challenge: Somewhat like python's itertools.groupBy: Your function Array.group(f) should take as input an "equivalence function" f whose output defines our notion of an "equivalence key" for array elements (like a sort key). The return value of .group(f) should be an array of arrays in the same order, split whenever the value of the keyfunc parameter changes (in the === sense).

Object.defineProperties(Array.prototype, {
    group: {
        value: function(f) {/*
            CODE GOES HERE
        */}
    }
});

Examples / test cases:

> ['a','c','E','G','n'].group(x => x==x.toUpperCase())
[['a','c'], ['E','G'], ['n']]

> [1,1,'1'].group(x=>x)
[[1,1],['1']]

> [3,1,'1',10,5,5].group(x=>x+2)
[[3], [1], ['1'], [10], [5,5]]

> [{a:1,b:2,c:3}, {b:2,a:1,c:0}, {c:5}].group(x => JSON.stringify([x.a, x.b]))
[[{a:1,b:2,c:3},{b:2,a:1,c:0}], [{c:5}]]

> [].group(x=>x)
[]

Scoring criteria:

score = # of characters that replace comment above (lower is better), with easements that:

whitespace and statement-separating semicolons don't count towards total[2]
variable names and keywords each count as exactly 1 characters towards total per use[3]; this includes builtins, so Array.map.apply would be 5 'characters' (however, builtins count their full length as tiebreakers)
-5 bonus points if f being undefined has same result as the identity function x=>x
you may modify the construct function(f) {...} for recursion/combinator purposes while keeping it as a function respecting rule #5, but must subtract from your score the extra characters incurred (i.e. imagine the scoring began earlier)

Disallowances:

no side-effects which affect anything other than your code (such as modifying this, window, the prototype, etc.); as a corollary, all definitions must stay local to the .group function (e.g. x=5 would be disallowed, but var x=5 is fine)

minor notes:

[1] draft specs fine if in any major browser, proprietary extensions fine if in 2+ major browsers;
[2] as long as you don't try to compile a few megabytes-long whitespace ;-)
[3] as long as reflection is not used to abuse code-in-variable-names ;-)

Errata:

Answer may do anything reasonable with regards to sparse arrays. e.g. arr=[1,1]; arr[4]=1; arr -> [1, 1, empty × 2, 1]. Possibilities include ignoring them (like .map and friends do), or treating them as undefined (like an incremental for-loop would), or anything reasonable. For example arr.group(x=>x) might return [[1,1],[undefined,undefined],[1]], or [[1,1,1]], or even more dubious things like [[1,1],null,[1]] if it makes sense. You may also assume sparse arrays do not exist.

edit: #2 now applies to keywords.

You may find the following snippet useful to estimate score (the rules supercede this snippet though):

var code = `......`;
console.log('score estimate:', code.replace(/\w+/g,'X').replace(/[\s;]/g,'').replace(/X(?=X)/g,'X ').length, '-5?');

JavaScript, 47 points (53 tiebreaker)

Array.prototype.group = function(f){
    const r = []
    let k = r
    for(const i of this)
        k !== (k = f ? f(i) : i) ? r.push(a = [i]) : a.push(i)
    return r
}

Body: +52
Identity comparison: -5
Full-length built-ins: +6

Try it:

Array.prototype.group = function(f){
    const r = []
    const k = r
    for(const i of this)
        k!==(k=f?f(i):i)?r.push(a=[i]):a.push(i)
    return r
}

console.log(
    ['a','c','E','G','n'].group(x => x==x.toUpperCase()),
    [1,1,'1'].group(x=>x),
    [3,1,'1',10,5,5].group(x=>x+2),
    [{a:1,b:2,c:3}, {b:2,a:1,c:0}, {c:5}].group(x => JSON.stringify([x.a, x.b])),
    [].group(x=>x)
)

JavaScript, 48 points (56 tiebreaker)

More traditional code golf-y solution.

Array.prototype.group = function(f,r=[],k=r){
    this.map(i=>k!==(k=f?f(i):i)?r.push(a=[i]):a.push(i))
    return r
}

Signature: +9
Body: +44
Identity comparison: -5
Full-length built-ins: +8

Try it:

Array.prototype.group = function(f,r=[],k=r){
    this.map(i=>k!==(k=f?f(i):i)?r.push(a=[i]):a.push(i))
    return r
}

console.log(
    ['a','c','E','G','n'].group(x => x==x.toUpperCase()),
    [1,1,'1'].group(x=>x),
    [3,1,'1',10,5,5].group(x=>x+2),
    [{a:1,b:2,c:3}, {b:2,a:1,c:0}, {c:5}].group(x => JSON.stringify([x.a, x.b])),
    [].group(x=>x)
)


No More Jockeys - CodeGolf Version This challenge is inspired by the game No More Jockeys.
The input is a list of tuples of natural numbers (potentially including 0), in some appropriate input format. Starting with player 0 and alternating with player 1, each player chooses some number which is contained within at least one remaining tuple, and all tuples containing that number will be removed from the list. The first player who has no possible moves loses.
Your challenge is to implement a function to calculate the minimax value of a given input. Return a truthy value if it is player 1 to win given optimal play by both players, and a falsy value if it is player 0 to win. The converse is also acceptable.
This is code-golf, so fewest bytes wins.
Test Cases
((), (0, 1, 3), (1,)) -> 0
() -> 1
((0,), (1, 3), (2,)) -> 0
((), (0, 1), (0, 1, 2), (0, 2), (1,)) -> 1
((0,), (0, 1, 3), (0, 3), (2,)) -> 0
((), (0, 1), (0, 2, 3), (1,), (2,), (3,)) -> 1
((0, 1), (1, 2), (2, 3), (3,)) -> 0
((0, 2), (1,), (1, 3), (3,), (4,)) -> 1
((0, 2, 3), (0, 3), (1,), (2,), (2, 3)) -> 0

Python 3, 62 bytes

f=lambda a:0in(f([x for x in a if{r}-{*x}])for r in sum(a,()))

Try it online!
Python 2, 61 bytes

f=lambda a:0in(f(filter({y}.__sub__,a))for x in a for y in x)

Try it online!
-5 bytes thanks to Unrelated String
-6 bytes thanks to dingledooper
-1 byte if we use Python 2 thanks to dingledooper
-2 bytes thanks to xnor
Outputs True for player 0 winning and False or () for player 1 winning (() is an empty tuple in Python, which is a falsey value in the language)


Source Code Metamorphosis mbomb007 asked us to make a self mutilating program.  Its an interesting challenge, but I personally don't like to encourage my programs to be self-mutilating.  I like to think that, at the heart of every program is a beautiful butterfly waiting to break out.

As such, for my first ever Code Golf challenge, I challenge Stack Exchange to metamorph a butterfly.  Your program should accept its own code as input and output I am a caterpillar! followed by the code for another program in the same language (you may put a divider between the outputs or not... but we're talking butterflies, so prettiness counts!). This second program should output I am a beautiful butterfly!

Metamorphosis: This program should modify itself, which is why it is being passed itself as input.  I don't want a boring nested program that is nothing but a print statement I am a caterpillar! followed by printing source code.  You have to metamorph the code itself, so the most boring acceptable answer is one which prints I am a caterpillar, then rips a string out of the input (which happens to be code) and prints that.  Of course, this is a very tricky little requirement to write, so it should be thought of as a "spirit of the challenge."  The formal requirement is going to be set at "If your program is given a random string of the same length as your program, there should be less than a 5% chance of printing I am a butterfly when the second program is run."

Summary:

Write a program which, when provided its own code as input, prints I am a caterpillar! followed by a block of source code (with a delimiter between them or not).
This second block of source code, when compiled/interpreted as the same language, prints I am a beautiful butterfly!
If your program is not fed its own source code as input, and is instead given a random string of characters that does not match its own code, the result must either fail to compile/interpret, or not print I am a butterfly! for at least 95% of random strings (spirit: you are expected to read your own source code from the input, and stitch it together into a butterfly).

I'm comfortable with you not proving this, so long as you're holding to the spirit of the metamorphosis idea, modifying your own code, but if you're trying to play loophole games to work around using your inputs, expect to have to prove it.

Standard loopholes apply

I'd like these to be judged by their beauty, but that's a decidedly non-quantitative approach, so the usual "number of bytes" route can be used to judge

Bonus: -20% - pick any 3 letter string that doesn't match the first 3 letters of your program.  If I run the caterpillar program, but modify the input so that the first 3 character are changed to the specified ones, print I am Batman! instead.   Always be Batman.  (Same random string rules apply for this... metamorphosis!)

Trivial example (python):

"""
    print "I am a beautiful butterfly!"
    #print "I am Batman!"
"""
import sys
code = sys.stdin.read()
if code.startswith("YYZ"):
   # swap the comments between the print statements
   code = code.replace("#print", "_a").replace("print", "#print").replace("_a", "print")
code = [3:] # remove """ or XYZ
code = code.split('"""')[0]
print "I am a caterpillar!"
print code

Befunge-98, 602 bytes
                                        "^@<"v@@
                                     "'I'"00v>00g::
                                   "@v"0v@@@>g::a">#"
                                 "a">v@@>      0g::'"1>                                 /
                             ":\"'"v@>            'm'"00g:a                       >"@v$"
 "lufituaeb"'"'v00ga"@v\"'":'b\00v@>                :'a\":*84>"00ga"\>@@@@_,#:>"00g:a'<'"
"et"'"'va'v'":'l\00g5k:'""y!">>v@>                    g::'''""ut"'"'>a'<'""fr"'"00g3k:'">
 "ma"00g>'I~48*-~48*-+#@_>:#,_@>                        '"aa"---"aa"!rallipretac"00g:'a\

Tested in PyFunge.
When run with a string not starting with 2 spaces (probability well over 95% when random) outputs nothing. This isn't exactly what the OP is looking for, but fits the specification.
When passed a string starting with 2 spaces (like itself) outputs this:
I am a caterpillar!

---

"!y"       "l"v
v"te"     "rf"<
>"tu"'   "b"\v@
 v"beautiful"<
  >:#,_@@@@>\
 >48*:"a"\:$v@
  "ma"   v@#>
   'I'   <@^

The lower part of that, in turn, outputs:
I am a beautiful butterfly!


Pangram "Hello, World!" Your challenge: The code must print "Hello, World!" and nothing else.
Your restrictions: Your program must satisfy these requirements:

The program must be a pangram.

It must use every character in printable ASCII, or, if you chose a particularly strange language, characters which are stored as one byte.
You are allowed to use other characters.

The program may not have unnecessary characters.

No subset of individual characters may be removed from the program while the program still outputs "Hello, World!"
For example, if code ABBC outputs Hello, World! then neither codes AC nor BC may output "Hello, World!", although code BA may.
This also means you cannot have a statement to print "Hello, World!" per se anywhere in your program, as everything other than that statement could be deleted and the program would do the same thing.

The program must not take input.

Your program does not create any errors.

You must not use any "Hello, World!" builtins.

Your score: Your score is calculated by [length of the program in characters] - [number of different characters]. Lowest score wins. (Tie-breakers are oldest post.)
Nota Bene: the second requirement is almost impossible to verify, so an answer is valid only after a week has passed for anyone who wishes to do so to be able to disprove the validity of your answer.

Ruby,  119  112 bytes / score 17

puts ["%x"%(("!\#&+,-01245:;<>?@ABDEFIJKLNOQRUVWXYZ`dflqnry{|}"=~/$/)^"s8j9bePwGp7SgMTCvznH".to_i(36))].pack'h*'

Try it online!


Generate a Pronounceable Nonsense Word \$n\$ syllables long Your task is to generate a nonsense word that is reasonably pronounceable with the specified number of 'syllables'. Each time the program is run possibly results in a different nonsense word.

Pronounceability

A pronounceable word is made up of syllables, which are in turn made up of a vowel group that is possibly sandwiched between two consonant groups. Not all sounds are pronounceable in all positions, and since this depends on the language, we'll use patterns understandable to English speakers

Starting consonant groups:

b
c
d
f
g
h
j
k
l
m
n
p
r
s
t
v
w
y
z
bl
br
ch
cl
cr
dr
fl
fr
gh
gl
gn
gr
kn
ph
pl
pr
qu
sc
sh
sk
sl
sm
sn
sp
st
th
tr
wh
wr
sch
scr
shm
shr
squ
str
thr

Vowel Groups:

a
e
i
o
u
ae
ai
ao
au
ea
ee
ei
eu
ia
ie
io
oa
oe
oi
oo
ou
ue
ui

Ending Consonant groups:

b
c
d
f
g
l
m
n
p
r
s
t
x
z
bt
ch
ck
ct
ft
gh
gn
lb
ld
lf
lk
ll
lm
ln
lp
lt
mb
mn
mp
nk
ng
nt
ph
pt
rb
rc
rd
rf
rg
rk
rl
rm
rn
rp
rt
rv
rz
sh
sk
sp
ss
st
zz
lch
lsh
lth
rch
rsh
rst
rth
sch
tch

Combining Syllables

Both starting and ending consonant groups are optional in general, however you cannot place a syllable ending with a vowel immediately before one starting with a vowel.

Disclaimer

In the interest of simplicity, certain English words can't actually be generated this way, such as vacuum, xylophone, mnemonic, pterodactyl, beautiful, blah, they, wow, and most plurals.

Overview

Possible syllable patterns using this key:

(SC) = starting consonant; (V) = vowel group; (EC) = ending consonant

For one syllable:

(SC)(V)(EC)
(V)(EC)
(SC)(V)
(V)

With two syllables:

(SC)(V)(EC)(SC)(V)(EC)
(SC)(V)(EC)(SC)(V)
(SC)(V)(EC)(V)(EC)
(SC)(V)(EC)(V)
(SC)(V)(SC)(V)(EC)
(SC)(V)(SC)(V)
(V)(EC)(SC)(V)(EC)
(V)(EC)(SC)(V)
(V)(EC)(V)(EC)
(V)(EC)(V)
(V)(SC)(V)(EC)
(V)(SC)(V)

... and so on

Examples

1 syllable

charst
tigh
shriegn
eess
shue
oo
cheezz

2 syllables

jazzcrap
whylprog
eating
umba
ola
have
ingsoc
greespheurz
bleuspoo

3 syllables

brokiompic
squirdshlicker
capital
opengtrass
doublethink
bigbrother
phoebliaptmoo
skolfblauquent

4 syllables

strawishoepick
patchworkzombie
prearneajoomie
slephotoschou
doubleplusgood

Coding

Input: an integer for the number of syllables to generate

Output: a (probably) nonsense word that many syllables long

Rules

Some form of (psuedo)randomness is required. All combinations of syllables should be (theoretically) possible to generate, though the distribution does not have to be uniform.

You may assume that your generator is aperiodic, so it doesn't have to be mathematically possible to generate every possible word (It might not have a long enough period in reality) and you don't need to provide any sort of proof that your generator can, in fact, produce every possible word.
Your generator must actually be able to produce at least 255 distinct values, so you can't just return 4 every time the generator is called.
What's ultimately important is that you somehow include all the above letter groups in your code, that each letter group has a nonzero probability of being picked, and each syllable pattern has a nonzero probability of occurring (if provided with true randomness).

You must support up to 16 syllable words
In addition to the rules on combining syllables, the output word must not have:

3 consecutive vowels (a e i o u; this can happen for qu words)
3 consecutive matching consonants

Good luck!

Note that this is distinct from Generate a pronounceable word for a few reasons:

Variable number of syllables specified by input rather than a strict 10-letter requirement.
This challenge adds non-exhaustive letter groups that must be (cleverly) encoded and allows for more variants of syllables, so code can't just be copied from the other challenge
Squirdshlicker. Need I say more?

I also forgot to dupe check, but it turns out this brings enough new to the table that it doesn't matter. After all, there are hundreds of quine variant challenges.


Least notes money exchange Suppose A and B are two good friends. A has borrowed \$n\$ dollar from B. Now B wants the money back from A and A is also ready to give it. But the problem is A has only \$x\$ dollar notes and B has \$y\$ dollar notes. They both want to keep the number of notes in exchange as low as possible.
As an example if \$n=37\$, \$x=5\$ and \$y=2\$, then the least amount of notes in exchange will be nine $5 notes from A and four $2 notes from B, which totals to $37.
Your input will be \$n, x, y\$ and your output should be the least of amount of notes possible for \$A\$ and \$B\$ such that \$B > 0\$. Input and output seperator can be anything, no leading zeros in input numbers, no negative numbers in input. Standard loopholes apply and shortest code wins.
Test Cases
37 5 2 -> 9 4
89 3 8 -> 35 2
100 12 7 -> 13 8
10 1 100 -> 110 1

Input will be always solvable.

Python 2, 51 bytes

n,x,y=input()
c=n+y
while c%x:c+=y
print(c-n)/y,c/x

Try it online!
-8 bytes thanks to Jonathan Allan


Three-pointer! But what kind? From http://en.wikipedia.org/wiki/Triangle:

Write a program that takes three 2d coordinate tuples (Cartesian), and classifies what shape these three points describe.
In almost all cases these points will describe a triangle of varying types.  In some degenerate cases, the points will either describe a singular point or a straight line.  The program will determine which of the following tags apply to the described shape:

Point         (3 points are co-incident)
Line          (3 points lie on a straight line - no more than 2 points may be co-incident)
Equilateral   (3 sides equal, 3 angles equal)
Isosceles     (2 sides equal, 2 angles equal)
Scalene       (0 sides equal, 0 angles equal)
Right         (1 angle exactly π/2 (or 90°))
Oblique       (0 angles exactly π/2 (or 90°))
Obtuse        (1 angle > π/2 (or 90°))
Acute         (3 angles < π/2 (or 90°))

Note that for some described shapes, more than one of the above tags will apply.  For example, any right-angled will also either be isosceles or scalene.
Input

The program may read the 3 input coordinates from STDIN, command-line, environment variables or whatever method is convenient for your language of choice.
The input co-ordinates my be formatted however is convenient for your language of choice.  It can be assumed that all input numbers are well-formed with respect to the datatypes you end up using.
Nothing can be assumed about the ordering of the input coordinates.

Output

The program will output to STDOUT, dialog box or whatever display method is convenient for your language of choice.
The output will display all the tags applicable to the shape described by the input coordinates.
Tags may be output in any order.

Other Rules

Your language's trigonometric libraries/APIs are allowed, but any APIs that specifically calculate triangle types are banned.
When determining equality of angles or lengths of sides, you will likely end up comparing floating-point values.  Two such values are to be considered "equal" if one is within 1% of the other.
Standard “loopholes” which are no longer funny
This is code-golf, so the shortest answer in bytes wins.

Examples
Input                   Output
(1,2) (1,2) (1,2)       Point
(1,2) (3,4) (5,6)       Line
(0,0) (1,1) (2,0)       Isosceles Right
(0,0) (2,1) (10,1)      Scalene Oblique Obtuse

C (451 bytes)

Uses only squared lengths and slopes.

p[2],q[2],r[2];z(c){char*y[]={"Line","Point","Isosceles ","Equilateral ","Scalene ","Right","Oblique ","Acute","Obtuse"};printf(y[c]);}d(int*a,int*b){int c=*a++-*b++,e=*a-*b;return c*c+e*e;}main(){scanf("%d%d%d%d%d%d",p,p+1,q,q+1,r,r+1);int a=d(p,q),b=d(q,r),c=d(r,p),e=!a+!b+!c,f=(a==b)+(b==c)+(c==a),g=a>b&&b>c?a:b>c?b:c,h=g^a?g^b?a+b:c+a:b+c;e?z(e/2):(1[q]-1[p])*(*r-*q)^(1[r]-1[q])*(*q-*p)?f?z(2+f/2),f-1&&z(2):z(4),h^g?z(6),z(7+(h<g)):z(5):z(0);}

Ungolfed (and ternary operator replaced with if/else):

int p[2],q[2],r[2];

void print(c){
    char *y[]={"Line","Point","Isosceles ","Equilateral ","Scalene ","Right","Oblique ","Acute","Obtuse"};
    printf(y[c]);
}
squared_distance(int *a,int *b){
    int c = *a++ - *b++, e = *a - *b;
    return c*c+e*e;
}
main(){
    scanf("%d%d%d%d%d%d",p,p+1,q,q+1,r,r+1); // read in coordinates
    int a = squared_distance(p,q),b = squared_distance(q,r),c = squared_distance(r,p),
    e=!a+!b+!c, // number of sides of length 0
    f=(a==b)+(b==c)+(c==a), // number of equal-length pairs
    g = a > b && b > c ? a : (b > c ? b : c), // longest side
    h = g != a ? g != b ? a + b : c + a : b + c; // sum of squares of length of other two sides
    if(e)
        print(e/2); // 1 side of len 0: line, 3 sides: point
    // comparing slopes PQ and QR
    else if((q[1]-p[1])*(*r-*q) != (r[1]-q[1])*(*q-*p)){ // not line
        if(f){
            print(2+f/2); // 1 pair of equal length sides: isosceles, 3: equilateral
            if(f-1) print(2); // equilateral therefore also isosceles
        }else print(4); // 0: scalene
        if(h!=g){ // a^2+b^2!=c^2: not right
            print(6); // oblique
            print(7+(h<g)); // a^2+b^2<c^2:obtuse, acute otherwise
        }else print(5); // right
    }else
        print(0); // line
}

Input (through stdin) Format: x y x y x y

ex. 0 0 1 1 2 0 for Isosceles Right


Let's Judge Some Books By Their Covers Everyone knows that the content makes the question. But a good title helps too, and that's the first thing we see. It's time to turn that first impression into a program, and figure out what kinds of titles get more upvotes.

You are hereby challenged to write a program or function that takes the title of a PPCG question as input, and returns a prediction of its score.

For instance, you might receive Counting Grains of Rice as an input, and you would be trying to return something close to the score, 59 in this case. Non-integer guesses are fine, but guesses at or below -20 are not.

Here is the data, for testing and scoring:

http://data.stackexchange.com/codegolf/query/244871/names-and-upvotes

Scoring: Your program will be run on every question in this site's (PPCG) history, not counting closed questions. The function ln(score + 20) will then be applied to each score, and to each guess. The root-mean-squared-error between the two resultant sets of values is your score. Lower is better.

For instance, a program that guessed 0 every time would score 0.577, while one that guessed 11 every time would score 0.362.

Please calculate your score and include it in the title of your answer. Please also include your program's prediction for how many upvotes this question will get.

Restrictions:

To prevent excessive hard-coding, no more than 1000 characters.
Must run on the entire data set above in under a minute on a reasonable machine.
Standard Loopholes are closed.

Here is a tester written in Python, for your use and/or to clear up ambiguities:

import sys
import math
import csv

scores_dict = {}

with open(sys.argv[1], 'r') as csv_file:
    score_reader = csv.reader(csv_file)
    for score, title in score_reader:
        if score == 'Score':
            continue
        scores_dict[title] = int(score)

def rate_guesses(guesser):
    def transform(score):
        return math.log(score + 20) if score > -20 else 0
    off_by_total = 0
    lines_count = 0
    for title in scores_dict:
        guessed_score = guesser(title)
        real_score = scores_dict[title]
        off_by_total += (transform(real_score) - transform(guessed_score)) ** 2
    return (off_by_total/len(scores_dict)) ** .5

def constant11(title):
    return 11

print(rate_guesses(constant11))

Javascript ES6

Score: 0.245663Length: 1000 bytesPredicts: 5

(I guess the question is due for an unexpected avalanche of downvotes. :P)

Minified

E="ABCDEFGHIJKLMNOPQRSTUVWXYZ";E=E+E.toLowerCase()+"0123456789!@#$%;*()";P="RCRHIFMGPGIDQKHMJLLRMLFJGKHEqHPOgJNKGPCHPJNUPOSGJQKKKMELMIJHLKIKNcKDOfSJLFHDILGKIOUKLMLLKMKIHGHJGIIJDGJKIHIIFIGMTIHFJMIKDJGQJKGMKJHPRJPLMGIOPIIIIPBYFMGLEIKIMMRUKFLFGJFKFTHPFODEQTGTHKIJDHNJGDGiHKNYLHHDLJHGILOEViKNEKGQZfHJMIISIJFRHKLJMLPIFJILKKKJKKJESHNLLIKIGKGJJJHKJRGULLSLRONJNEeLKIQGGPQIHPLEIHHIDXjQHNBKOGWWIENRbYoHINHNMKTNKHTGMIPXFJLLMLIHPPLDJJKFUMIQMOKJLJJKIJKNLHRILJIAIbJEZOGIELGHGLOINDPJMJeJWRIIJHSOZDOsOFRRIOIOTIJSGGJKFUIDOINGOcLQEJFEITLMNIIGIGIMG7LPSNLKVOKIFGHJITGOFUJIIRN";K={};"99r1501vz076mip077myv0733it280exx081gt9118i1g279dyx102uho203ejd07433z087uje097kdg1567ft2088rk275dmu1203ez106lih1763ei126f6q101aax084owh088aid161i9y179gvn236ptn3338vf132i55080fke101l4z3789ai281ulm081blm124euz074o5m07513z14117l095qdn092gl30757n5153".replace(/(...)(...)/g,(_,a,b)=>K[a]=1*b);D=40655;N=479;H=(s,T)=>(h=7,[...s].map(c=>h=~~(h*T+c.charCodeAt(0))),h);S=s=>(y=H(s,31),K[((y%D+D)%D).toString(36)]||E.indexOf(P[(H(s,48)%N+N)%N]));

Expanded

E = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
E = E + E.toLowerCase() + "0123456789!@#$%;*()";
K = {};
P = "RCRHIFMGPGIDQKHMJLLRMLFJGKHEqHPOgJNKGPCHPJNUPOSGJQKKKMELMIJHLKIKNcKDOfSJL" +
    "FHDILGKIOUKLMLLKMKIHGHJGIIJDGJKIHIIFIGMTIHFJMIKDJGQJKGMKJHPRJPLMGIOPIIIIP" +
    "BYFMGLEIKIMMRUKFLFGJFKFTHPFODEQTGTHKIJDHNJGDGiHKNYLHHDLJHGILOEViKNEKGQZfH" +
    "JMIISIJFRHKLJMLPIFJILKKKJKKJESHNLLIKIGKGJJJHKJRGULLSLRONJNEeLKIQGGPQIHPLE" +
    "IHHIDXjQHNBKOGWWIENRbYoHINHNMKTNKHTGMIPXFJLLMLIHPPLDJJKFUMIQMOKJLJJKIJKNL" +
    "HRILJIAIbJEZOGIELGHGLOINDPJMJeJWRIIJHSOZDOsOFRRIOIOTIJSGGJKFUIDOINGOcLQEJ" +
    "FEITLMNIIGIGIMG7LPSNLKVOKIFGHJITGOFUJIIRN";

   ("99r1501vz076mip077myv0733it280exx081gt9118i1g279dyx102uho203ejd07433z087u" +
    "je097kdg1567ft2088rk275dmu1203ez106lih1763ei126f6q101aax084owh088aid161i9" +
    "y179gvn236ptn3338vf132i55080fke101l4z3789ai281ulm081blm124euz074o5m07513z" +
    "14117l095qdn092gl30757n5153").
        replace( /(...)(...)/g, (_,a,b) => K[a] = 1*b );

D = 40655;
N = 479;
H = (s,T) => (
    h = 7,
    [...s].map( c => h = ~~(h*T + c.charCodeAt(0)) ),
    h
);

S = s => (
    y = H( s, 31 ),
    K[((y%D + D)%D).toString( 36 )] || E.indexOf( P[(H( s, 48 )%N + N)%N] )
);

The function S accepts a string (title) and returns its score.

Notes on Behaviour:

≤ 70 vote titles are handled separately from > 70 vote titles
≤ 70 vote titles are sorted into bins using a highly sophisticated holonomic keyword tracking potential optimization algorithm that in no way resembles a string hash function
after a bit of happy calculus it turns out that the optimal guess for each bin is simply the geometric average of the (votes + 20)'s for all titles in the bin, minus 20
the optimal guesses for all 479 bins are then encoded as a 479-character base-70 string
for > 70 vote titles, the titles are assigned unique 3-digit base-36 codes generated using a state-of-the-art hashing technique that guarantees no collisions with other > 70 vote titles and no false detections of ≤ 70 vote titles. This state-of-the-art technique in no way resembles trying random bin counts until one produces no collisions.
the > 70 vote title codes and their vote counts are encoded in a string (6 bytes per title), which is converted to a simple lookup table. The routine therefore has zero error for all > 70 vote titles.


Mr Seckington weights his ternᵃʳʸ Mr Seckington is a mobile grocer.  He drives his van door-to-door selling his produce all around the nearby villages.  Mr Seckington needs a method to weigh the produce he is selling so he knows how much to charge his customers.  Because space is at such a premium on his van, he uses an interesting sequence of weights on his scale that minimizes the amount weights he needs to measure any integer number of grams.

The weights (in grams) are all powers of 3, i.e 1, 3, 9, 27, 81...  He puts what he is weighing on the left side of the scale and he can put weights on either side of the scale to measure a desired weight with integer granularity.

For example if he wants to  weigh out 2 grams of peppercorns, he will put a 1g weight on the left side, a 3g weight on the right side, and then he can load the peppercorns onto the left side until the scale balances.

Similarly if he wants to weigh out 30g of chocolate chips, he'll put 3g + 27g weights on the right side and load chocolate chips onto the left side until the scale balances.

Given a positive integer weight as input, output two lists - one with the weights that must go on the left side of the scale and the other with the weights that must go on the right side.

It should be clear from the output which is the left-side list and which is the right-side list.  E.g. always ordering left, then right is fine.

The ordering within the lists doesn't matter.

You should be able to support inputs at least up to 88,573 (31+32+...+310).

Input -> Output
    1 -> {}, {1}
    2 -> {1}, {3}
    3 -> {}, {3}
    4 -> {}, {1 ,3}
    5 -> {1, 3}, {9}
    6 -> {3}, {9}
    7 -> {3}, {1, 9}
    8 -> {1}, {9}
    9 -> {}, {9}
   10 -> {}, {1, 9}
   13 -> {}, {1, 3, 9}
   14 -> {1, 3, 9}, {27}
   20 -> {1, 9}, {3, 27}
  100 -> {9}, {1, 27, 81}

Harold Seckington really did have a mobile grocery in the village that I grew up in.  However, I made up the bit about him using a ternary system of weights.

MATL, 39 bytes
`x3:H-@Z^3@:q^*!tXsG=~}1MZ)Xzt0>&)_Xh&D

The output lists are in reversed order. Each list is actually a column array of numbers (square brackets, semicolon as separator). In MATL, as in MATLAB and Octave, an array with a single number is the  same as a number, so in that case the corresponding list doesn't have enclosing brackets.
Try it online! Or verifiy all test cases.
How it works
This keeps testing sets of weights of increasing size: the set {1}, then {1, 3}, then {1, 3, 9}, ... This is done with a do...while loop.
For any such set, containing k different weights, all possible distributions of those weights are tested.
A distribution of weights is defined by a vector of k numbers, where each number may be -1, 0,  1, meaning that the corresponding weight is on the left side, unused, or on the right side. For each distribution, the sum is compared with the target weight. This is done in a vectorized manner, using 2D arrays.
If for a given set of weights there is a distribution of those weights that matches the target, the solution has been found.


Diamond with numbers Inspired by this, print an ascii diamond pattern built using 0-9.

Rules

Input n should be between 0-9, anything outside that range is undefined
The diamond should be padded with spaces
The middle line should always have no padding and be the only line to contain n, in the center
Print to stdout
As always, this is code-golf

Test Cases

n = 0

0

n = 1, print

 0
010
 0

n = 2, print

  0
 010
01210
 010
  0

n = 9, print

         0
        010
       01210
      0123210
     012343210
    01234543210
   0123456543210
  012345676543210
 01234567876543210
0123456789876543210
 01234567876543210
  012345676543210
   0123456543210
    01234543210
     012343210
      0123210
       01210
        010
         0

Vitsy, 50 bytes

I don't think I'm done golfing yet!

VVHr1mV{V2*1+\[2m]
:Xru
v&VvD([D\[' 'O]]-H1ml\NaOY

Explanation:

VVHr1mV{V2*1+\[2m]
V                  Pop n, set n as the global final variable (GFV).
 V                 Push the GFV to the current stack.
  H                Pop n, pop o, push each item of the range from o to n.
   r               Reverse the current program stack.
    1m             Call the method on line index 1.
      V{           Push the GFV to the bottom of the current stack.
        V2*1+      Push the GFV*2+1 to the stack.
             \[  ] Pop n, do the stuff in brackets n times.
               2m  Call the method on line index 2. Note that this is necessary due
                   to an unknown bug.

:Xru
:                  Clone the current stack, pushing a second stack to the stack
                   stack and jumping to it.
 X                 Pop n and discard.
  r                Reverse the current stack.
   u               Pop the current stack and concatenate it to the previous.

v&VvD([D\[' 'O]]-H1ml\NaOY
v                  Pop n, save as a temporary variable.
 &                 Push a new stack to the stack stack and jump to it.
  V                Push the GFV.
   v               Push the temp var, clear the temp var memory.
    D([        ]   If the top item is not zero, do the stuff in brackets.
                   This is necessary as all loops always apply once.
       D\[' 'O]    Peek n, output n spaces.
   -               Pop n, pop o, push o-n.
    H              Pop n, pop o, push each item of the range from o to n.
     1m            Call the method at line index 1.
       l\N         Output all numbers in this stack.
          aO       Output a newline.
            Y      Pop and discard the current stack from the stack stack.

Try it online!


Random point on a sphere The Challenge
Write a program or function that takes no input and outputs a 3-dimensional vector of length \$1\$ in a theoretically uniform random direction.
This is equivalent to a random point on the sphere described by $$x^2+y^2+z^2=1$$
resulting in a distribution like such

Output
Three floats from a theoretically uniform random distribution for which the equation \$x^2+y^2+z^2=1\$ holds true to precision limits.
Challenge remarks

The random distribution needs to be theoretically uniform. That is, if the pseudo-random number generator were to be replaced with a true RNG from the real numbers, it would result in a uniform random distribution of points on the sphere.
Generating three random numbers from a uniform distribution and normalizing them is invalid: there will be a bias towards the corners of the three-dimensional space.
Similarly, generating two random numbers from a uniform distribution and using them as spherical coordinates is invalid: there will be a bias towards the poles of the sphere.
Proper uniformity can be achieved by algorithms including but not limited to:

Generate three random numbers \$x\$, \$y\$ and \$z\$ from a normal (Gaussian) distribution around \$0\$ and normalize them.

Implementation example

Generate three random numbers \$x\$, \$y\$ and \$z\$ from a uniform distribution in the range \$(-1,1)\$. Calculate the length of the vector by \$l=\sqrt{x^2+y^2+z^2}\$. Then, if \$l>1\$, reject the vector and generate a new set of numbers. Else, if \$l \leq 1\$, normalize the vector and return the result.

Implementation example

Generate two random numbers \$i\$ and \$j\$ from a uniform distribution in the range \$(0,1)\$ and convert them to spherical coordinates like so:\begin{align}\theta &= 2 \times \pi \times i\\\\\phi &= \cos^{-1}(2\times j -1)\end{align}so that \$x\$, \$y\$ and \$z\$ can be calculated by \begin{align}x &= \cos(\theta) \times \sin(\phi)\\\\y &= \sin(\theta) \times \sin(\phi)\\\\z &= \cos(\phi)\end{align}

Implementation example

Provide in your answer a brief description of the algorithm that you are using.
Read more on sphere point picking on MathWorld.

Output examples
[ 0.72422852 -0.58643067  0.36275628]
[-0.79158628 -0.17595886  0.58517488]
[-0.16428481 -0.90804027  0.38532243]
[ 0.61238768  0.75123833 -0.24621596]
[-0.81111161 -0.46269121  0.35779156]

General remarks

This is code-golf, so the answer using the fewest bytes in each language wins.
Standard rules, I/O rules and loophole rules apply.
Please include a Try it Online-link or equivalent to demonstrate your code working.
Please motivate your answer with an explanation of your code.

Wolfram Language (Mathematica), 20 bytes

RandomPoint@Sphere[]

Try it online!

Does exactly what it says on the tin.


Climbing binomial tree to find the option value Background:

In finance, the binomial options pricing model (BOPM) is the simplest technique used for option pricing. The mathematics behind the model is relatively easy to understand and (at least in their basic form) it is not difficult to implement. This model was first proposed by Cox, Ross, and Rubinstein in 1979. Quoting Wikipedia:

  The binomial pricing model traces the evolution of the option's key underlying variables in discrete-time. This is done by means of a binomial lattice (tree), for a number of time steps between the valuation and expiration dates. Each node in the lattice represents a possible price of the underlying at a given point in time.

  Valuation is performed iteratively, starting at each of the final nodes (those that may be reached at the time of expiration), and then working backwards through the tree towards the first node (valuation date). The value computed at each stage is the value of the option at that point in time.

For this challenge's sake, we will create a simple model to predict potential future prices of the option(s) by creating a lattice or a tree as shown below (a picture is worth a thousand words):

where S is the option price today, p is the probability of a price rise, and t is the period of time or number of steps.

Challenge:

The challenge is to write either a program or a function which take S, p (in percent), and t as the inputs and give the binomial tree as the output. The output of the program or the function must follow the format above, but the boxes and the arrow lines are optional. For example, if the program take inputs S = 100, p = 10%, and t = 3, then its output may be in the following simple form:

                        133.1
                121
        110             108.9
100              99
         90              89.1
                 81
                         72.9

General rules:

This is code-golf, so the shortest answer in bytes wins the challenge.
Don't let esolangs discourage you from posting an answer with regular languages. Enjoy this challenge by providing an answer as short as possible with your programming language. If you post a clever answer and a clear explanation, your answer will be appreciated (hence the upvotes) regardless of the programming language you use.
Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/ method with the proper parameters, full programs, etc. The choice is yours.
Using a binomial tree built-in is forbidden.
If possible, your program can properly handle a large number of steps. If not, that will just be fine.

References:

Binomial options pricing model
Binomial tree option calculator


How many shapes are in this picture? Children are very good at classifying objects and counting them. Computers seem to have more trouble. This is a simplified version of this problem. Can you write a small program that can classify and count objects in an image?

The problem: Given an image containing one or more circles and rectangles, return 2 integers
with the count of circles and count of rectangles.

Rules

The input image will be black figures on a white background in any bitmap
format you choose.
The image width and height will be between 100 and 1000 pixels.
Figures will be fully contained within the image.
Figures will have 1 pixel line width.
Images will not use anti-aliasing. They will be black on white only.
Figures may touch, intersect, or be inside another figure.
Intersecting figures will have a maximum of 4 common pixels.
Circles will have a diameter of 20 pixels or more.
Rectangle sides will be 10 or more pixels long.
You may not use any built-ins or libraries that recognize shapes, or any other
function that makes this challenge trivial.
Return or print 2 integers with the counts of circles and rectangles.

Example 1

Answer: 3 4

Example 2:

Answer: 4 13

This is a code golf challenge, so the shortest program or function in each language will win.

PHP – 355 bytes
The byte count doesn't include '<image-url>'.
<?php
m('<image-url>');function m($f){$i=imagecreatefrompng($f);$r=f($i,17);$c=f($i,9);echo($c-$r).' '.$r."\n";}function f($i,$k){$w=imagesx($i);$h=imagesy($i);$r=0;for($y=0;$y<$h;$y++)for($x=0;$x<$w;$x++)if(!imagecolorat($i,$x,$y))$r+=g($i,$x,$y,$w,$k);return$r;}function g($i,&$x,$y,$w,$k){$l=$x;while(!imagecolorat($i,$x,$y)&&$x<$w)$x++;return($x-$l>$k)?1/2:0;}

In the two test cases, the URLs I used are http://i.stack.imgur.com/qnIFk.png and http://i.stack.imgur.com/HV9k3.png.
Counts horizontal lines and divides by two to get the number of shapes. Relies on the observation that circles have shorter horizontal segments and rectangles have longer horizontal segments.
Admitted hack, not guaranteed to work for anything other than the test cases!
I tried rotating the images by ± 45° and detecting for horizontal lines. This would be equivalent to checking for diagonal lines and would pick up the circles better, but I couldn't find an interpolation algorithm which left clean enough edges to work with. For example, they might smudge a line into two rows of pixels and mess up the count.