Make a hammer animation The goal is to make a two frame animation with ASCII art of a hammer smacking a table.

Trailing white-space is allowed and the frames need to repeat continuously. The program should iterate over both frames with a time of 0.5 seconds between frames.

Lowest byte count wins for each language!

Sample:

Animation Frames:

Frame 1:
 -------------------
|                   |
|                   |
|                   |
 -------------------
         /  /
        /  /
       /  /
      /  /
     /  /
    /  /
   /  /
  /  /
 /  /
 \ /

                        ---------------------------
                       |                           |

Frame 2:

                                        ----------
                                       |          |
                                       |          |
                                       |          |
 --------------------------------------|          |
|                                      |          |
 --------------------------------------|          |
                                       |          |
                                       |          |
                                       |          |
                                        ----------
                                  -------------------------------
                                |                                |

Python 3, 337  331 319 bytes

-12 bytes thanks to Amphibological

import os,time
t,e,q,p='- \n|'
j=e+t*19+q
L=p+e*19+p+q
l=j+3*L+j
for i in range(9):l+=e*(9-i)+'/  /'+q
l+=' \\ /'+3*q+e*24+t*27+q+e*23+p+27*e+p+q
c=39*e
C=p+10*e+p+q
m=10*t+q
R=e+38*t+C
f=(c+C)*3
r=q+c+e+m+f+R+p+38*e+C+R+f+c+e+m+34*e+31*t+q+32*e+p+32*e+q
b=0
while 1:print([r,l][b]);time.sleep(.5);os.system('cls');b=~b

Try it online!

It uses 'cls', so will only work on Windows, use 'clear' for Linux with +2 bytes.

Will add a gif later.


Write your own Death Note Kira needs your help!

Input format:

Date [and/or Time]
Name
Gender
Reason

Output format:

<Last Name, First Name> <will die/died> on the <DD><st/nd/rd/th> of <MMM, YYYY> [at <hh:mm:ss TT>].
<He/She> <will die/died> of <Reason>.

Details, Details:

Your program should account for at least the following date input formats:

9 November 2003
9/11/2003
November 9, 2003

Time formats:

hh tt
hh TT
hh:mm tt
hh:mm TT
hh:mm:ss tt
hh:mm:ss TT
HH
HH:mm
HH:mm:ss

The following name input formats:

first        // Stephen
last         // Harper
first last   // Stephen Harper
last, first  // Harper, Stephen

Test cases:

Input:

2 September 1973
J.R.R. Tolkien
Male
pneumonia

Output:

  Tolkien, J.R.R. died on the 2nd of
  September, 1973.

  He died of pneumonia.

DISCLAIMER: If he actually dies on this date, it's Kira's fault, not mine.

UPDATE: Stephen Harper did not die on the listed date

Input:

21/12/12 23:59:59             // DD/MM/YY HH:mm:ss
Harper, Stephen               // Last, First
Unknown                       // Gender
a heart attack for no reason  // Reason

Output:

  Harper, Stephen will die on the 21st
  of December, 2012 at 11:59:59 PM.

  Harper, Stephen will die of a heart
  attack for no reason.

Bonus:

July 21, 1969 02:56:15 GMT
Armstrong, Neil
Male
poisoned moon cheese

--

January 19, 2038 03:14:08 GMT
Everyone
Unknown
Y2K38

Add <st/nd/rd/th> at the end of DD for input.

Javascript (561)

This can probably be reduced significantly, but here goes:

i=i.split("\n");d=new Date(i[0]);t=d.getDate();z=t%10;t+=z==1?"st":z==2?"nd":z==3?"rd":"th";m=['January','February','March','April','May','June','July','August','September','October','November','December'][d.getMonth()];y=d.getFullYear();a=d.getHours();b=d.getMinutes();c=d.getSeconds();l=a&&b&&c?" at "+a+":"+b+":"+c:"";g=d>new Date()?"will die":"died";n=i[1].split(" ");n[1]?n[0][n[0].length-1]==","?n=i[1]:n=n[1]+", "+n[0]:n[0];s=i[2]=="Male"?"He":i[2]=="Female"?"She":n;document.write(n+" "+g+" on the "+t+" of "+m+", "+y+l+".<br>"+s+" "+g+" of "+i[3]+".");

Sample I/O:

2 September 1973
J.R.R. Tolkien
Male
pneumonia

  Tolkien, J.R.R. died on the 2nd of September, 1973.
  He died of pneumonia.

January 19, 2038 03:14:08 GMT
Everyone
Unknown
Y2K38

  Everyone will die on the 18th of January, 2038 at 21:14:8.
  Everyone will die of Y2K38.

Try it out on JsFiddle.


How to slow down a drunkard on his way home Consider a square n by n grid graph that looks like this.

It is important to notice that this graph is 11 by 11.

At any given point a man stands at an intersection and he only ever moves vertically or horizontally by one step at a time to the next intersection.  Sadly he has drunk a little too much so he chooses the direction he moves randomly from the up to 4 possible directions (up, down, left, right). This is up to 4 as if he is standing at a wall he has only 3 options of course and in a corner he only has 2.

He starts in the bottom left hand corner and his goal is to get home which is the top right hand corner.  The time is simply the number of steps it takes him.

However, you are a malicious adversary who  wants him to get home as slowly as possible. You can delete any number of edges from the graph at any time during during his walk.  The only restriction is that you must always leave some way for him to get home and you can't delete an edge he has already used.

  The challenge is to devise as malicious an adversary as possible and
  then test it on a 100 by 100 20 by 20 graph with a random drunken walker. Your
  score is simply the average time it takes the random walker to get
  home over 10 1000 runs.

You can use any language and libraries you like as long as they are freely available and easily installable in Linux.

What do I need to implement?

You should implement code for the random walker and also for the adversary and the code should be combined so that the output when run is simply the average of 1000 runs using your adversary code.  The random walker code should be very simple to write  as he just chooses from (x-1, y), (x+1, y), (x, y-1), and (x, y+1) making sure that none of those have been deleted or are out of range.

The adversary code is of course more difficult and also needs to remember which edges the drunkard has already traversed so he doesn't try to delete any of them and to make sure there is still a route home for the drunkard, which is a little trickier to do quickly.

Addendum  10 runs isn't really enough but I didn't want to punish people who managed to get really long walks.  I have now increased it to 1000 due to popular request.  However, if your walk is so long you can't do 1000 runs in a realistic amount of time, please just report for the maximum number of runs you can.

High score table for 100 by 100.

976124.754 by Optimizer.
103000363.218 by Peter Taylor.

Edit 1. Changed the graph size to 20 by 20 to help the running time of people's tests. I will make a new high table score for that size as people submit the scores.

High score table for 20 by 20.

230,794.38 (100k runs) by justhalf
227,934 by Sparr
213,000 (approx) by Peter Taylor
199,094.3 by stokastic
188,000 (approx) by James_pic
 64,281 by Geobits

227934 (20x20)

My third attempt. Uses the same general approach as @stokastic with two paths to the exit. When the walker reaches the end of one path, it closes, requiring him to return to get to the end of the other path to exit. My improvement is to generate the paths as the walker progresses, so that whichever path he is progressing further along in the first half of the process will end up being longer than the other path.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#include <iostream>

#define DEBUG 0
#define ROUNDS 10000

#define Y 20
#define X 20
#define H (Y*2+1)
#define W (X*2+1)

int maze[H][W];
int scores[ROUNDS];

int x, y;

void print_maze(){
    char line[W+2];
    line[W+1]=0;
    for(int row=0;row<H;row++) {
        for(int col=0;col<W;col++) {
            switch(maze[row][col]) {
                case 0:
                    line[col]=' ';
                    break;
                case 1:
                    line[col]=row%2?'-':'|';
                    break;
                case 8:
                    line[col]=(row==y*2+1&&col==x*2+1)?'@':'?';
                    break;
                case 9:
                    line[col]=(row==y*2+1&&col==x*2+1)?'@':'*';
                    break;
            }
        }
        line[W]='\n';
        printf("%s",line);
    }
    printf("%d %d\n",y,x);
}

int main(){
    srand (time(NULL));
    long long total_turns = 0;
    for(int round=0;round<ROUNDS;round++) {
        for (int r=0;r<H;r++) {
            for (int c=0;c<W;c++) {
                maze[r][c]=0;
            }
        }
        maze[1][1]=9;
        maze[1][2]=1;
        maze[2][1]=1;
        maze[1][3]=8;
        maze[3][1]=8;
        int progress_l = 0;
        int progress_r = 0;
        int side = 0;
        int closed_exit = 0;
        x=0;
        y=0;
        if (DEBUG) print_maze();
        long long turn = 0;
        int in = 0;
        while (x!=X-1||y!=Y-1) {
            turn++;
            int r = y*2+1;
            int c = x*2+1;
            int dx=0, dy=0;
            if (DEBUG) {
                std::cin>>in;
                switch(in) {
                    case 0:
                        dy=-1; dx=0; break;
                    case 1:
                        dy=0; dx=1; break;
                    case 2:
                        dy=1; dx=0; break;
                    case 3:
                        dy=0; dx=-1; break;
                    default:
                        dy=0; dx=0; break;
                }
            } else {
                int exits = maze[r-1][c] + maze[r][c+1] + maze[r+1][c] + maze[r][c-1];
                int exit_choice = -1;
                do {
                    if (rand()%exits == 0) {
                        exit_choice = exits;
                        break;
                    } else {
                        exits--;
                    }
                }while(exits);

                --exits;

                if (maze[r-1][c]&&!dx&&!dy) {
                    if (exits) {
                        --exits;
                    } else {
                        dy = -1;
                        dx = 0;
                    }
                }
                if (maze[r][c+1]&&!dx&&!dy) {
                    if (exits) {
                        --exits;
                    } else {
                        dy = 0;
                        dx = 1;
                    }
                }
                if (maze[r+1][c]&&!dx&&!dy) {
                    if (exits) {
                        --exits;
                    } else {
                        dy = 1;
                        dx = 0;
                    }
                }
                if (maze[r][c-1]&&!dx&&!dy) {
                    if (exits) {
                        --exits;
                    } else {
                        dy = 0;
                        dx = -1;
                    }
                }
            }

            x+=dx;
            y+=dy;

            if(x==X-1 && y==Y-1) continue;

            if (x==0&&y==1) side=-1;
            if (x==1&&y==0) side=1;
            if (maze[y*2+1][x*2+1]==8) { // room needs another exit, maybe
                if (side==-1) { // left half of maze
                    if (y==1) { // top of a column
                        if (x%2) { // going up, turn right
                            maze[y*2+1][x*2+2]=1;
                            maze[y*2+1][x*2+3]=8;
                        } else { // going right, turn down
                            maze[y*2+2][x*2+1]=1;
                            maze[y*2+3][x*2+1]=8;
                        }
                    } else if (y==Y-1) { // bottom of a column
                        if (x%2 && x<(X-progress_r-3)) { // going right, turn up if there's room
                            maze[y*2+0][x*2+1]=1;
                            maze[y*2-1][x*2+1]=8;
                            progress_l=x+1;
                        } else { // going down or exiting, go right
                            if (x!=X-2 or closed_exit==1) {
                                maze[y*2+1][x*2+2]=1;
                                maze[y*2+1][x*2+3]=8;
                            } else {
                                closed_exit = -1;
                            }
                        }
                    } else { // in a column
                        if (maze[y*2+0][x*2+1]) { // going down
                            maze[y*2+2][x*2+1]=1;
                            maze[y*2+3][x*2+1]=8;
                        } else { // going up
                            maze[y*2+0][x*2+1]=1;
                            maze[y*2-1][x*2+1]=8;
                        }
                    }
                } else { // right half of maze
                    if (y==0) { // top row
                        if (x<X-1) { // go right
                            maze[y*2+1][x*2+2]=1;
                            maze[y*2+1][x*2+3]=8;
                        } else { // go down
                            maze[y*2+2][x*2+1]=1;
                            maze[y*2+3][x*2+1]=8;
                        }
                    } else if (y==Y-2) { // heading right to the exit
                        if (x<X-1) { // go right
                            maze[y*2+1][x*2+2]=1;
                            maze[y*2+1][x*2+3]=8;
                        } else { // go down
                            if (x!=X-1 or closed_exit==-1) {
                                maze[y*2+2][x*2+1]=1;
                                maze[y*2+3][x*2+1]=8;
                            } else {
                                closed_exit = 1;
                            }
                        }
                    } else if (y==Y-3) { // bottom of a column
                        if (x>progress_l+1) { // do we have room for another column?
                            if (!(x%2)&&y>1) { // going left, turn up
                                maze[y*2+0][x*2+1]=1;
                                maze[y*2-1][x*2+1]=8;
                            } else { // going down, turn left
                                maze[y*2+1][x*2+0]=1;
                                maze[y*2+1][x*2-1]=8;
                                progress_r=X-x-1;
                            }
                        } else { // abort, move down to escape row
                            maze[y*2+2][x*2+1]=1;
                            maze[y*2+3][x*2+1]=8;
                        }
                    } else if (y==1) { // top of a column
                        if (!(x%2)) { // going up, turn left
                            maze[y*2+1][x*2+0]=1;
                            maze[y*2+1][x*2-1]=8;
                        } else { // going left, turn down
                            maze[y*2+2][x*2+1]=1;
                            maze[y*2+3][x*2+1]=8;
                        }
                    } else { // in a column
                        if (maze[y*2+0][x*2+1]) { // going down
                            maze[y*2+2][x*2+1]=1;
                            maze[y*2+3][x*2+1]=8;
                        } else { // going up
                            maze[y*2+0][x*2+1]=1;
                            maze[y*2-1][x*2+1]=8;
                        }
                    }

                }
                maze[y*2+1][x*2+1]=9;
            }

            if (DEBUG) print_maze();
        }
        // print_maze();
        printf("turns:%lld\n",turn);
        scores[round] = turn;
        total_turns += turn;
    }
    printf("%d rounds in a %d*%d maze\n",ROUNDS,X,Y);
    long long avg = total_turns/ROUNDS;
    printf("average: % 10lld\n",avg);
    long long var = 0;
    for(int r=0;r<ROUNDS;r++){
        var += (scores[r]-avg)*(scores[r]-avg);
    }
    var/=ROUNDS;
    // printf("variance: %lld\n",var);
    int stddev=sqrt(var);
    printf("stddev:  % 10d\n",stddev);

}

output (with time):

...
turns:194750
turns:506468
turns:129684
turns:200712
turns:158664
turns:156550
turns:311440
turns:137900
turns:86948
turns:107134
turns:81806
turns:310274
100000 rounds in a 20*20 maze
average:     227934
stddev:      138349
real    10m54.797s
...

example of my maze, with roughly equal length halves to the path, showing the left/lower path cut off from the exit (bottom right):

  _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
 |  _   _   _   _   _   _   _   _   _  |
 | | | | | | | | | | | | | | | | | | | |
 | | | | | | | | | | | | | | | | | | | |
 | | | | | | | | | | | | | | | | | | | |
 | | | | | | | | | | | | | | | | | | | |
 | | | | | | | | | | | | | | | | | | | |
 | | | | | | | | | | | | | | | | | | | |
 | | | | | | | | | | | | | | | | | | | |
 | | | | | | | | | | | | | | | | | | | |
 | | | | | | | | | | | | | | | | | | | |
 | | | | | | | | | | | | | | | | | | | |
 | | | | | | | | | | | | | | | | | | | |
 | | | | | | | | | | | | | | | | | | | |
 | | | | | | | | | | | | | | | | | | | |
 | | | | | | | | | | | | | | | | | | | |
 | | | | | | | | | | | | | | | | | | | |
 | | | | | | | | | | |_| |_| |_| |_| |_|
 | | | | | | | | | |_ _ _ _ _ _ _ _ _ _
 |_| |_| |_| |_| |_ _ _ _ _ _ _ _ _ _  !

PS: I am aware of a very minor improvement to this algorithm that requires more clever code to generate a different shape for the two paths, staircases instead of consistent height zig zags.


Parse Query Parameters The challenge is this:

You are given a url that is as follows:

http://sub.example.com/some/dir/file.php?action=delete&file=test.foo&strict=true

There can be either http or https, there can be any number of subdomains or directories, and the end file can have any name.

You are to create a full program (that can be compiled/interpreted) that when given a key will return the correct value and if no key is found it will return an empty string.

For example:

> https://example.com/index.php?action=delete
...> get(action) #=> delete
> https://this.example.com/cat/index.php?action=delete
...> get(action) #=> delete
> http://example.com, https://action.example.com/actionscript/action.jpg
...> get(action) #=> none
> https://example.com/index.php?genre=action&reaction=1&action=2
...> get(action) #=> 2

There are no language restrictions and score is calculated a 1 point for every byte. Smallest score wins.

To clarify:

You do not need to handle URL encoding
The script only needs to run once and produce a result
The script can take any input form: STDIN, Prompt, even passed as a function argument

Example:

Javascript, 101 105 bytes

function p(k){var m;return((m=location.href.match(new RegExp('.*[&\?]'+k+'=([^&]*).*')))!==null?m[1]:'');}

Retina, 30 27 bytes

!`(?<=^\1 .*[?&](.*)=)[^&]+

This is a full program that expects the key and the URL to be space-separated on STDIN, e.g.

action http://sub.example.com/some/dir/file.php?action=delete&file=test.foo&strict=true

This is essentially just a (.NET-flavoured) regex, which matches the correct value by checking that the preceding key is equal to the first string in the input (using a backreference). The only thing that's a bit odd about the regex is that .NET matches lookbehinds from right to left, which is why the "backreference" actually references a group that appears later in the pattern. The !` instructs Retina to print the actual match (if there is one) instead of the number of matches.

For those who don't regex, here is an annotated version. Read the lookbehind from the bottom up, because that's how it's processed:

(?<=        # A lookbehind. Everything we match in here will not be returned as part of
            # actual match. Start reading this from the corresponding parenthesis.
  ^         # Ensure we're at the beginning of the input, so that we've checked
            # against the entire input key.
  \1        # Backreference to the key to check that it's the one we've asked for.
  [ ]       # Match a space.
  .*        # Consume the rest of the URL.
  [?&]      # Match a ? or a & to ensure we've actually captured the entire key.
  (         # End of group 1.
    .+      # Match the key.
  )         # Capturing group 1. Use this to keep track of the key.
  =         # Make sure we start right after a '='
)           # Start reading the lookbehind here.
[^&]+       # Match the value, i.e. as many non-& characters as possible.


Eternal 2014 — PCG.SE New Year’s Puzzle 2015 So, now that it's 2015, and a bunch of answers from last year's puzzle are now starting to produce invalid output, it's time for a question involving the number 2015.

Except... why? Wouldn't you like it if your date-based answers to last year's problem were to stay valid? Why don't we change our calendar so that it's never 2015, and we simply continue living in 2014, forever and ever?

Let's define a new date notation, called Eternal 2014 notation, as follows:

  For dates 2014 and before, the dates will be the same as in the proleptic Gregorian calendar.
  For dates in years 2015 and onward, the year will stay 2014, and the month will be the number it would be if the same month cycle in 2014 were to continue forever past month 12. So 2015-02-08 would be 2014-14-08, and 2020-12-31 would be 2014-85-02. Note that leap days are not accounted for because 2014 is not a leap year.

Your task is to build a program or function that will take a Julian astronomical date as input and return a string with the date corresponding to that Julian date in Eternal 2014 notation, in either YYYY-MM-DD or DD/MM/YYYY format.

You may assume that the Julian day entered will always be an integer from 1721426 (January 1, 1) to 2914695 (January 23, 3268) inclusive. Years may contain leading zeros to pad to 4 digits or not, but months and days must always have leading zeros to pad to two digits (and years may not contain leading zeros to pad to any number of digits other than 4).

Here are some example inputs and their outputs, in all acceptable formats:

> 1721426
1-01-01
01/01/1
0001-01-01
01/01/0001

> 2086302
999-12-31
31/12/999
0999-12-31
31/12/0999

> 2456659
2014-01-01
01/01/2014

> 2456789
2014-05-11
11/05/2014

> 2457024
2014-13-01
01/13/2014

> 2457389
2014-25-01
01/25/2014

> 2469134
2014-411-07
07/411/2014

> 2567890
2014-3657-29
29/3657/2014

> 2914695
2014-15059-23
23/15059/2014

You may not use any built-in date processing libraries in your language. All calculations must be done algorithmically within the program's source code itself.

The shortest program (in bytes) to achieve this in any language wins.

Python 2, 166 bytes

n=input()
d=m=y=1
M=([3]+[3,2]*3)*2
while n>1721426:
 n-=1;d+=1;M[2]=y%400<1or y%4<1<y%100
 if d>M[m%12]+28:m+=1;d=1
 if m>12<2014>y:y+=1;m=1
print'%02d/'*2%(d,m)+`y`

This cycles through every day from January 1, 1 (1721426) to the given date, incrementing the current day, month and year as it goes. The last test case takes about a second on my computer.

Output is printed in the second format:

01/01/1
31/12/999
23/15059/2014


Capitalize first letter of each word of input This is a relatively quick one, but I'm sure you'll like it.

Codegolf a program that will take input in the form of a sentence and then provide the output with the first letter capitalized in each word.

Rules:

Submissions may not be in the form of a function. So no:

function x(y){z=some_kind_of_magic(y);return z;} as your final answer... Your code must show that it takes input, and provides output.
The code must preserve any other capital letters the input has. So

eCommerce and eBusiness are cool, don't you agree, Richard III?

will be rendered as

ECommerce And EBusiness Are Cool, Don't You Agree, Richard III?

Some of you may be thinking, "Easy, I'll just use regex!" and so using the native regex in your chosen golfing language will incur a 30 character penalty which will be applied to your final code count. Evil laugh
A "word" in this case is anything separated by a space. Therefore palate cleanser is two words, whereas pigeon-toed is considered one word. if_you_love_her_then_you_should_put_a_ring_on_it is considered one word. If a word starts with a non-alphabetical character, the word is preserved, so _this after rendering remains as _this. (Kudos to Martin Buttner for pointing this test case out).

4b. There is no guarantee that words in the input phrase will be separated by a single space.

Test Case, (please use to test your code):

Input:

eCommerce rocks. crazyCamelCase stuff. _those  pigeon-toed shennanigans. Fiery trailblazing 345 thirty-two Roger. The quick brown fox jumped over the lazy dogs. Clancy Brown would have been cool as Lex Luthor. good_bye

Output:

ECommerce Rocks. CrazyCamelCase Stuff. _those  Pigeon-toed Shennanigans. Fiery Trailblazing 345 Thirty-two Roger. The Quick Brown Fox Jumped Over The Lazy Dogs. Clancy Brown Would Have Been Cool As Lex Luthor. Good_bye

This is code golf, shortest code wins...

Good luck...

CJam, 15 13 bytes

Lq{_eu?_S-}/;

Try it online in the CJam interpreter.

Pseudocode

L             e# B := ""
 q            e# Q := input()
  {       }/  e# for C in Q:
   _eu?       e#     C := B ? C : uppercase(C)
       _S-    e#     B := string(C).strip(" ")
            ; e# discard(B)

All modified characters C are left on the stack and, therefore, printed when exiting.


Find the largest number of distinct integers that sum to n The Task

Given an input positive integer n (from 1 to your language's limit, inclusively), return or output the maximum number of distinct positive integers that sum to n.

Test Cases

Let f define a valid function according to the task:

The sequence for f, starting at 1:

1, 1, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, ...

As a larger test case:

>>> f(1000000000) // Might not be feasible with brute-forcers
44720

Test Code

For any test cases not explicitly given, the output of your code should match the result of the following:

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int x = sc.nextInt();
        System.out.println((int) Math.floor(Math.sqrt(2*x + 1./4) - 1./2));
    }
}

Try it online!

05AB1E, 4 bytes

ÅTg<

Try it online!

Perfect tool for the job.

ÅT yields the list of Åll Triangular numbers up to and including N (unfortunately includes 0 too, otherwise it would be 3 bytes), g< gets the length and decrements it.


Implement the divisibility-by-7 rule To check whether a decimal number is divisible by 7:

  Erase the last digit. Multiply it by 2 and subtract from what is left. If the result is divisible by 7, the original number is divisible by 7.

(also described e.g. here)

This rule is good for manual divisibility check. For example:

  Is 2016 divisible by 7?

  Subtract 6*2 from 201; we get 189. Is this divisible by 7? To check it, let's apply the rule again.

  Subtract 9*2 from 18; we get 0. Therefore, 2016 is divisible by 7.

In this challenge, you should apply this rule until the divisibility status is obvious, that is, the number is not greater than 70 (however, see below for details). Make a function or a full program.

Input: a positive integer; your code should support inputs up to 32767 (supporting arbitrary-precision integers is a bonus; see below).

Output: an integer (possibly negative), not greater than 70, that is a result of applying the divisibility-by-7 rule zero or more times.

Test cases:

Input                   Output      Alternative output

1                       1
10                      10          1
100                     10          1
13                      13          -5
42                      42          0
2016                    0
9                       9
99                      -9
9999                    -3
12345                   3
32767                   28          -14

---------- Values below are only relevant for the bonus

700168844221            70          7
36893488147419103232    32          -1
231584178474632390847141970017375815706539969331281128078915168015826259279872    8

Where two possible outputs are specified, either result is correct: the second one corresponds to applying the rule one more time. It's forbidden to apply the rule on a single-digit number: if you erase the digit, nothing (not 0) is left.

Bonus: If your algorithm

Supports arbitrary-precision integers
Performs only one pass on the input
Has space complexity o(n) (i.e. less than O(n)); and
Has time complexity O(n),

where n is the number of decimal digits:

Subtract 50% from your code's byte count.

Real bonus:

In addition, if your algorithm reads the input in normal direction, starting from the most significant digit, subtract 50% once again - your score is 25% of your byte count (it seems possible, but I'm not absolutely sure).

Golfscript, 27 22 bytes

{.9>{.10/\10%2*-f}*}:f

You can use it this way:

1000f

Explanation

{.9>{.10/\10%2*-f}*}:f
{                  }:f    # Define block 'f' (similar to a function)
 .                        # Duplicate the first value of the stack
  9>{            }*       # If the value on top of the stack is greater than 9 then the block is executed
     .10/\10%2*-          # Same as nb/10 - (nb%10 * 2) with some stack manipulations '.' to duplicate the top of the stack and '\' to swap the the first and second element of the stack
                f         # Execute block 'f'

5 bytes saved thanks to Dennis !


Patterns in Permutations This fastest-code challenge is based partly on this MSE question and exists to extend some OEIS sequences, and create others. If I extend or create sequences based on this challenge, I'll link to this challenge so that folks can see where the values come from. If you'd like direct credit, include your first and last name so I can cite you on the entry.
These are now tables in the OEIS as A342840 (1342), A342860 (2413), A342861 (1324), A342862 (2143), A342863 (1243), A342864 (1432), and A342865 (1234).

Definition
Let \$\sigma \in S_n\$ be a permutation on \$n\$ letters, and let \$\tau \in S_m\$ be a permution on \$m \leq n\$ letters, both read as words: $$
  \sigma = \sigma_1\sigma_2 \dots \sigma_n \text{ and }   \tau = \tau_1\tau_2 \dots \tau_m
$$
The permutation statistic \$\operatorname{pat}_\tau(\sigma)\$ counts the number of length-\$m\$ subsequences of \$\sigma\$ that are in the same relative order as \$\tau\$.
Challenge
This fastest-code challenge will have you take a permutation \$\tau \in S_m\$ and an integer \$n \geq m\$ and return a (0-indexed) list where position \$i\$ has the number of permutations \$\sigma \in S_n\$ such that \$\operatorname{pat}_{\tau}(\sigma) = i\$. If done correctly, the list will sum to \$n!\$.
Scoring
I will run your code on each of the following for one minute each for increasing values of \$n\$:

the only pattern in \$S_1\$: \$\tau = 1\$;
essentially the only pattern in \$S_2\$: \$\tau = 12\$;
the two essentially different patterns in \$S_3\$: \$\tau \in \{123, 132\}\$; and
the seven essentially distinct patterns of \$S_4\$: \$ \tau \in \{1234, 1243, 1324, 1342, 1432, 2143, 2413\}\$.

Your score will be the largest value of \$n\$ that can be computed within a minute for every pattern.
For example, if you can compute up to

\$n = 1000\$ for \$\tau = 123\$ within a minute,
\$n = 10\$ for \$\tau = 1342\$ within a minute, and
\$n = 11\$ for \$\tau = 2413\$ within a minute,

then your score would be \$10\$.
Examples
Suppose that \$\sigma = 7532146\$ and \$\tau = 4213\$. Then $$
  \operatorname{pat}_{4213}(7532146) = 13
$$ because \$\sigma = 7532146\$ has thirteen subsequences that are in the same relative order as \$\tau = 4213\$, \$7536\$, \$7526\$, \$7516\$, \$7546\$, \$7324\$, \$7326\$, \$7314\$, \$7316\$, \$7214\$, \$7216\$, \$5324\$, \$5314\$, and \$5214\$.
Test Data
 n | tau   | target output
---+-------+--------------------------------------------------------------
 6 |  1234 | [513, 102, 63, 10,  6, 12, 8, 0, 0,      5, 0, 0, 0, 0, 0, 1]
 5 |   123 | [ 42,  27, 24,  7,  9,  6, 0, 4, 0,      0, 1]
 9 |     1 | [  0,   0,  0,  0,  0,  0, 0, 0, 0, 362880]
 5 |   132 | [ 42,  21, 23, 14, 12,  5, 3]
 6 |  4213 | [512,  77, 69, 30, 21,  5, 6]
 4 |    12 | [  1,   3,  5,  6,  5,  3, 1]
 6 | 53214 | [694,  18,  7,  0,  1]

Note: For \$\tau = 12\$, the target output should be the \$n\$-th row of OEIS sequence A008302. For \$\tau = 1\$, the target output should be \$n\$ \$0\$s followed by \$n!\$.

Rust, score ≈ 13
This enumerates permutations σ recursively, sharing as much computation as possible at branches of the search tree, so that only constant work is needed at each leaf.
Times in seconds measured on my Ryzen 7 1800X (8 cores/16 threads):
τ   n = 10    11    12     13      14       15
──────────────────────────────────────────────
1     0.00  0.02  0.25   2.93   38.72   660.86
12    0.00  0.04  0.47   5.89   79.08  1268.18
123   0.00  0.06  0.67   8.47  115.61  1836.36
132   0.01  0.10  1.18  15.50  218.39  3443.56
1234  0.00  0.05  0.59   7.65  104.88  1643.29
1243  0.00  0.06  0.81  10.72  152.60  2417.75
1324  0.01  0.09  1.10  14.52  208.59  3280.18
1342  0.01  0.10  1.21  16.59  242.01  3871.64
1432  0.01  0.09  1.19  16.21  237.93  3808.25
2143  0.00  0.06  0.81  10.72  151.09  2409.76
2413  0.01  0.09  1.20  16.07  232.74  3717.70
──────────────────────────────────────────────
max   0.01  0.10  1.21  16.59  242.01  3871.64

Build and run with:
cargo build --release
target/release/permutations 11 '1 3 4 2'

Or try it online!
(But note, the TIO version lacks parallelism and many other optimizations, so it’s much slower, due to being unable to use external crates.)
All outputs for n = 0…15.
Cargo.toml
[package]
name = "permutations"
version = "0.1.0"
authors = ["Anders Kaseorg <andersk@mit.edu>"]
edition = "2018"

[dependencies]
rayon = "1.5.0"
thread_local = "1.1.3"
typed-arena = "2.0.1"

[profile.release]
lto = "y"
panic = "abort"

src/main.rs
use rayon::prelude::*;
use std::cell::Cell;
use std::env;
use std::iter::Zip;
use std::slice;
use thread_local::ThreadLocal;
use typed_arena::Arena;

enum UpdateIterator<'a> {
    Leave(u16, slice::Iter<'a, (u16, u16)>),
    Take(
        u16,
        u16,
        Zip<slice::Iter<'a, (u16, u16)>, slice::Iter<'a, u16>>,
    ),
}

impl Iterator for UpdateIterator<'_> {
    type Item = (u16, u16);

    fn next(&mut self) -> Option<(u16, u16)> {
        match *self {
            UpdateIterator::Leave(i, ref mut bounds) => bounds
                .next()
                .map(|&(low, high)| (low + (low > i) as u16, high + (high >= i) as u16)),
            UpdateIterator::Take(i, tau0, ref mut zip) => {
                zip.next().map(|(&(low, high), &tau1)| {
                    if tau0 < tau1 {
                        (low.max(i) + 1, high + (high >= i) as u16)
                    } else {
                        (low + (low > i) as u16, high.min(i))
                    }
                })
            }
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        match self {
            UpdateIterator::Leave(_, bounds) => bounds.size_hint(),
            UpdateIterator::Take(_, _, zip) => zip.size_hint(),
        }
    }
}

fn update(
    tau: &[u16],
    remaining: usize,
    states: &[(&[(u16, u16)], isize)],
    i: u16,
    mut callback: impl FnMut(UpdateIterator, isize),
) {
    for &(bounds, count) in states {
        if bounds.len() < remaining {
            callback(UpdateIterator::Leave(i, bounds.iter()), count);
        }

        if let Some((&(low0, high0), bounds1)) = bounds.split_first() {
            if low0 <= i && i <= high0 {
                callback(
                    UpdateIterator::Take(
                        i,
                        tau[tau.len() - bounds.len()],
                        bounds1.iter().zip(&tau[tau.len() - bounds.len() + 1..]),
                    ),
                    count,
                );
            }
        }
    }
}

fn search_step(
    tau: &[u16],
    remaining: usize,
    states: &[(&[(u16, u16)], isize)],
    arena_len: usize,
    i: u16,
    search: impl FnOnce(&[(&[(u16, u16)], isize)], usize),
) {
    let arena = Arena::with_capacity(2 * arena_len + 1 - states.len());
    let mut new_states = Vec::with_capacity(states.len() * 2);
    update(tau, remaining, states, i, |bounds, count| {
        new_states.push((&*arena.alloc_extend(bounds), count))
    });
    new_states.sort_by_key(|&(bounds, _)| bounds);
    new_states.dedup_by(|(bounds0, count0), (bounds1, count1)| {
        bounds0 == bounds1 && {
            *count1 += *count0;
            true
        }
    });
    search(&new_states, arena.len());
}

fn search(
    n: usize,
    tau: &[u16],
    k: usize,
    states: &[(&[(u16, u16)], isize)],
    arena_len: usize,
    output: &[Cell<u64>],
) {
    if n - k == 1 {
        let mut deltas = vec![0; n + 1];
        let mut total = 0;
        for &(bounds, count) in states {
            match bounds {
                [] => total += count,
                &[(low, high)] => {
                    deltas[low as usize] += count;
                    deltas[high as usize + 1] -= count;
                }
                _ => {}
            }
        }
        for delta in &deltas[..n] {
            total += delta;
            output[total as usize].set(output[total as usize].get() + 1);
        }
    } else if n - k == 2 {
        for i in 0..=k as u16 {
            let mut deltas = vec![0; n + 1];
            let mut total = 0;
            update(tau, n - k, states, i, |mut bounds, count| {
                if let Some((low, high)) = bounds.next() {
                    deltas[low as usize] += count;
                    deltas[high as usize + 1] -= count;
                    debug_assert!(bounds.next().is_none());
                } else {
                    total += count;
                }
            });
            for delta in &deltas[..n] {
                total += delta;
                output[total as usize].set(output[total as usize].get() + 1);
            }
        }
    } else {
        for i in 0..=k as u16 {
            search_step(tau, n - k, states, arena_len, i, |states, arena_len| {
                search(n, tau, k + 1, states, arena_len, output)
            })
        }
    }
}

fn par_search(
    n: usize,
    tau: &[u16],
    k: usize,
    states: &[(&[(u16, u16)], isize)],
    arena_len: usize,
    comb: usize,
    outputs: &ThreadLocal<Vec<Cell<u64>>>,
) {
    if n - k <= 4 {
        search(
            n,
            tau,
            k,
            states,
            arena_len,
            outputs.get_or(|| vec![Cell::new(0); comb + 1]),
        );
    } else {
        (0..=k as u16).into_par_iter().for_each(|i| {
            search_step(tau, n - k, states, arena_len, i, |states, arena_len| {
                par_search(n, tau, k + 1, states, arena_len, comb, outputs)
            })
        });
    }
}

fn counts(n: usize, tau: &[u16]) -> Vec<u64> {
    if n > tau.len() {
        let mut comb = 1;
        for i in 0..tau.len() {
            comb = comb * (n - i) / (i + 1);
        }
        let outputs = ThreadLocal::new();
        par_search(
            n,
            &tau,
            0,
            &[(&vec![(0, 0); tau.len()], 1)],
            tau.len(),
            comb,
            &outputs,
        );
        let mut output = vec![0; comb + 1];
        for thread_output in outputs {
            for (x, y) in output.iter_mut().zip(thread_output) {
                *x += y.get();
            }
        }
        output.truncate(
            output
                .iter()
                .rposition(|&count| count != 0)
                .map_or(0, |i| i + 1),
        );
        output
    } else if n == tau.len() {
        vec![(1..=n as u64).product::<u64>() - 1, 1]
    } else {
        vec![(1..=n as u64).product()]
    }
}

fn main() {
    let args: Vec<String> = env::args().collect();
    if let [_, n, tau] = &*args {
        let n: usize = n.parse().unwrap();
        let tau: Vec<u16> = tau.split_whitespace().map(|n| n.parse().unwrap()).collect();
        for count in counts(n, &tau) {
            println!("{}", count);
        }
    } else {
        panic!("usage: permutations n 'τ₁ τ₂ … τₘ'")
    }
}


Generalized FiveThirtyEight Sequences Adapted from this FiveThirtyEight riddle.
Background
Examine the following infinite sequence:
3 3 3 2 3 3 3 2 3 3 3 2 3 3 2 3 3 3 2 ...

Let's say the sequence is 1-indexed. The ith number in the sequence determines how many 3s there are before the ith 2 and following any previous 2s. So since the sequence starts with a 3 the sequence must begin 3 3 3 2 and since there are three 3s at the beginning of the sequence the subsequence 3 3 3 2 must repeat itself three times. After that you reach 3 3 2 because the fourth number in the sequence is 2.
The FiveThirtyEight riddle asks for the limit of the ratios of threes to twos (which I won't spoil here) but you can also ask what the cumulative ratio is after index i. For example the ratio at i=4 is 3/1 = 3 and at i=15 it's 11/4 = 2.75.
Let's get general
Given numbers n and k we can make a similar sequence that starts with n and just like the original sequence described the number at index i determines how many ns show up before the ith k and following any previous ks.
Examples:
n=2, k=5 gives the sequence 2 2 5 2 2 5 2 2 2 2 2 5 2 2 5 ...
n=3, k=0 gives 3 3 3 0 3 3 3 0 3 3 3 0 0 3 3 3 0 ...
n=1, k=3 gives 1 3 1 1 1 3 1 3 1 3 1 3 1 1 1 3 1 ...
The Challenge
Write a function/program and with it do the following. Take as input:

a positive integer n
a nonnegative integer k ≠ n
a positive integer i > n

The first two inputs n and k determine a sequence as described above and i is an index. I am using 1-indexing in the examples but you have the freedom to use 0- or 1-indexing. If 0-indexed then the restriction on i is i ≥ n.
With the three numbers output the ratio of ns to ks in the sequence up to and including the number at the index i. The format of the output can either be a decimal value with at least 5 digits of precision or an exact value as a ratio like 3524/837 or 3524:837.
In decimal form, the last digit can be rounded however you like. Trailing zeros and whitespace are allowed.
In either of the string forms the two numbers need to be normalized so that they are coprime. For example if the ratio was 22/4, 11/2 and 11:2 are acceptable but 22/4 is not.
Examples
n   k   i      output
2   4   15     2.75     or   11/4
6   0   666    5.1101   or   557:109
50  89  64     63       or   63:1
3   2   1000   2.7453   or   733/267
9   12  345    9.4545   or   104/11

This is code golf per language, so shortest code in each language is the winner.

Husk, 16 bytes

¤/#ωȯ↑⁰J¹`C∞²N¹²

Try it online!

Takes inputs in the same order as the test cases.
Outputs a rational number.
I feel like this has too many superscripts, but I don't know how to get rid of them...

Explanation

¤/#ωȯ↑⁰J¹`C∞²N¹²  Inputs are n, k, i.
             N    Starting with the natural numbers [1,2,3..
   ωȯ             do this until a fixed point is reached:
                    Argument is a list s.
           ∞²       Take the infinite list [n,n,n..
         `C         and split it to the lengths in s.
       J¹           Join the resulting blocks with k.
     ↑⁰             Take the first i elements.
                  Call the result x.
¤             ¹²  For each of n and k,
  #               count their number of occurrences in x
 /                and perform exact division on the results.


Visualize a Nim board like an expert Background
In the game of Nim, players alternate removing "stones" from "piles": on each turn, a player must remove between one and all stones from a single pile.  The object of Nim is to take the last stone or, in the misere variant, to force your opponent to do so -- however, it turns out the strategies are nearly identical.
Nim makes a fun bar game. You can use matchsticks or coins for the "stones," and the "piles" are typically arranged in a line.  Below is a classic setup with piles of 1, 3, 5, and 7:

If you've never played Nim before, you might try your hand at it before attempting this challenge.  Here's a version called "Pearls Before Swine".
Strategy
Optimal strategy in Nim is tricky enough that most lay people lose consistently to an expert, but simple to describe with binary arithmetic.
Doing mental binary XOR operations, however, is tough, so luckily there is an  equivalent way to visualize the correct strategy which is easier to implement in real time, even when drunk.
There are only three steps:

Mentally group the "stones" in each line into subgroups whose sizes are powers of 2, starting with the largest possible size: 8, 4, 2, and 1 are sufficient for most games.
Try to match each group with a twin in another line, so that every group has a pair.
If this isn't possible, remove unpaired "stones" from a single line (this will always be possible - see the Wikipedia link for why) so that step 2. becomes possible.

Or, said another way: "Remove some stone(s) from a single pile such that if you then group the piles into powers of 2 all groups may be paired with a group in some other pile."  With the caveat that you cannot break up larger powers of 2 into smaller ones -- eg, you cannot group a line with 8 stones into two groups of 4.
For example here's how you'd visualize the board above:

This board is perfectly balanced, so you'd want your opponent to move first.
The Challenge
Given a list of positive integers representing the size of Nim "piles", return a plain text visualization of the Nim board as seen by an expert.
What constitutes a valid visualization is best explained by example, but you must:

Assign a distinct character to each "power-of-2 subgroup" and its pair (unpaired subgroups do not qualify), and use that character to represent the "stones" in both subgroup and pair.
Represent any unpaired "stones" (ie, the ones an expert would remove when playing normal -- not misere -- Nim) using a hyphen: -.

There will be multiple ways to achieve a valid visualization, and all are valid.  Let's work through some test cases:
Test Cases
Input: 1, 3, 5, 7
Possible Output 1:
A
BBA
CCCCD
CCCCBBD

You may optionally include spaces between the characters, as well as blank lines between the rows:
Possible Output 2:
A

B B A

C C C C D

C C C C B B D

Input: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
The order and choice of characters can be whatever you like:
Possible Output 1:
G
E E
E E G
C C C C
C C C C F
B B B B D D
B B B B D D F
H H I - - - - -
A A A A A A A A I
A A A A A A A A H H

Unicode symbols are ok too:
Possible Output 2:
◎
◈  ◈
◈  ◈  ◎
△  △  △  △
△  △  △  △  ◉
◐  ◐  ◐  ◐  ◀  ◀
◐  ◐  ◐  ◐  ◀  ◀  ◉
▽  ▽  ◒  -  -  -  -  -
▥  ▥  ▥  ▥  ▥  ▥  ▥  ▥  ◒
▥  ▥  ▥  ▥  ▥  ▥  ▥  ▥  ▽  ▽

Input: 7
From the rules it follows that any "single pile" must be completely removed.
Possible Output 1:
-------

Possible Output 2:
- - - - - - -

Input: 5, 5
Possible Output:
A A A A B
A A A A B

Additional Rules

This is code golf with standard rules.  Shortest code wins.
Input is flexible, and may be taken in whatever list-ish form is convenient to you.
Output is flexible too, as the above examples illustrate.  Most reasonable variations will be allowed.  Ask if you're unsure about something.

Python 2, 150 196 206 bytes

def f(p):
 c=48;s=[l*'.'for l in p];m=2**len(bin(l))
 while m:
  if sum(m*'.'in l for l in s)>1:
   for i,l in enumerate(s):s[i]=l.replace('.'*m,chr(c)*m,`s`.count(chr(c)*m)<2)
   c+=1
  else:m/=2
 return s

Try it online!


Minimise the count of prime factors through insertion Given two positive integers A and B, return the position p that minimises the number of prime factors (counting multiplicities) of the resulting integer, when B is inserted in A at p.
For example, given A = 1234 and B = 32, these are the possible insertions (with p being 0-indexed) and the corresponding information about their prime factors:

p | Result | Prime factors         | Ω(N) / Count

0 | 321234 | [2, 3, 37, 1447]      | 4
1 | 132234 | [2, 3, 22039]         | 3
2 | 123234 | [2, 3, 19, 23, 47]    | 5
3 | 123324 | [2, 2, 3, 43, 239]    | 5
4 | 123432 | [2, 2, 2, 3, 37, 139] | 6

You can see that the result has a minimal number of prime factors, 3, when p is 1. So in this particular case, you should output 1.
Specs

If there are multiple positions p that minimise the result, you can choose to output all of them or any one of them.

You may choose 0-indexing or 1-indexing for p, but this choice must be consistent.

A and B can be taken as integers, strings or lists of digits.

You can compete in any programming language and can take input and provide output through any standard method, while taking note that these loopholes are forbidden by default. This is code-golf, so the shortest submission (scored in bytes) wins!

Test cases

A, B -> p (0-indexed) / p (1-indexed)

1234, 32           -> 1 / 2
3456, 3            -> 4 / 5
378, 1824          -> 0 / 1
1824, 378          -> 4 / 5
67, 267            -> Any or all among: [1, 2] / [2, 3]
435, 1             -> Any or all among: [1, 2, 3] / [2, 3, 4]
378100, 1878980901 -> Any or all among: [5, 6] / [6, 7]

For convenience, here is a list of tuples representing each pair of inputs:
[(1234, 32), (3456, 3), (378, 1824), (1824, 378), (67, 267), (435, 1), (378100, 1878980901)]

Husk, 16 bytes

§◄öLpr§·++⁰↑↓oΘŀ

Expects input as strings, try it online!

Explanation

§◄(öLpr§·++⁰↑↓)(Θŀ)  -- input A implicit, B as ⁰ (example "1234" and "32")
§ (           )(  )  -- apply A to the two functions and ..
  (ö          )      --   | "suppose we have an argument N" (eg. 2)
  (    §      )      --   | fork A and ..
  (         ↑ )      --     | take N: "12"
  (          ↓)      --     | drop N: "34"
  (     ·++⁰  )      --   | .. join the result by B: "123234"
  (   r       )      --   | read: 123234
  (  p        )      --   | prime factors: [2,3,19,23,47]
  ( L         )      --   | length: 5
  (öLpr§·++⁰↑↓)      --   : function taking N and returning number of factors
                            in the constructed number
               ( ŀ)  --   | range [1..length A]
               (Θ )  --   | prepend 0
               (Θŀ)  --   : [0,1,2,3,4]
 ◄                   -- .. using the generated function find the min over range


Print My Block Schedule My high school, and many others implement a type of schedule called a Rotating Block Schedule. This is a way for people to have 8 classes, but on have 6 periods in a school day.

There are four days in a block schedule that repeat over and over, and have nothing to do with the actual days of the week. Each are assigned a number [1-4].

The way the schedule works is that you list all your morning classes, periods 1-4: [1, 2, 3, 4]. This is your schedule for the first day, or Day 1. The rest of the days just rotate the list: [2, 3, 4, 1] , [3, 4, 1, 2], [4, 1, 2, 3].

However, the last period in the morning is "dropped" and you don't see that teacher that day. Hence the days are: [1, 2, 3], [2, 3, 4], [3, 4, 1], [4, 1, 2].

The afternoon is the same, except that it uses periods 5-8 instead: [5, 6, 7], [6, 7, 8], [7, 8, 5], [8, 5, 6].

Your task

All this rotating is hard to keep track of, so you have to write a program to print out my schedule given what day it is as input. Your code has to place Homeroom and Lunch in the correct spots. Here is the exact output your code needs to have for inputs 1-4:

Homeroom    Homeroom    Homeroom    Homeroom
Period 1    Period 2    Period 3    Period 4
Period 2    Period 3    Period 4    Period 1
Period 3    Period 4    Period 1    Period 2
Lunch       Lunch       Lunch       Lunch
Period 5    Period 6    Period 7    Period 8
Period 6    Period 7    Period 8    Period 5
Period 7    Period 8    Period 5    Period 6

But Wait - One more thing!

Sometimes, on the first day of school, or on other special days, my school has a "Day 0". This just means that I will have all my classes that day along with homeroom and lunch. Your code will have to deal with Day 0's. Here is the output for a Day 0:

Homeroom
Period 1
Period 2
Period 3
Period 4
Lunch
Period 5
Period 6
Period 7
Period 8

This is code-golf so shortest code in bytes wins!

Snowman 1.0.2, 190 bytes

}vg10sB*:#NdE*!1*"Homeroom
"sP0vn3nR:|%+#nA4NmO'"Period "sP'!#nAtSsP"
"sP|%;ae|"Lunch
"sP5*|ae;:"Homeroom
"sP0vn4nR*#:`"Period "sP`NiNtSsP"
"sP;aE"Lunch
"sP#:`"Period "sP`5nAtSsP"
"sP;aE;#bI

That leftmost column actually looks pretty nice, doesn't it?

...

... who am I kidding, I'd rather program in PHP than this.

"Readable" version:

}vg10sB*   // store day # in permavar
// big if statement coming up, depending on whether the input (n) is 0 or not

// THE FOLLOWING BLOCK IS FOR N != 0
:

#NdE*      // decrement number (because we like 0-based indeces) and re-store
!1*        // store the number 1 in permavar ! for later
"Homeroom
"sP        // print "Homeroom"
0vn3nR     // generate [0 1 2]
// for each element in this array...
:
    |%            // shuffle around some variables so we have room
    +#nA          // add day number (in permavar +)
    4NmO          // modulo by 4
    '"Period "sP  // print "Period "
    '!#nAtSsP     // add whatever is in permavar ! and print
    "
"sP               // print a newline
    |%            // return variables to their original state
;ae
// this is a rare occasion in which we use "ae" instead of "aE"
// we use non-consume mode here because we need the block again
// since we've used a permavar ! to determine what to add to the period number,
//   we can set the permavar to 4 more than it used to be and run the same
//   exact block
|"Lunch
"sP        // print "Lunch"
5*         // store the number 5 in permavar !, as described above
|ae        // run the same block over the same array again

;

// THE FOLLOWING BLOCK IS FOR N == 0

:

// after much frustration, I have determined that the easiest way to go about
//   this is to simply code the "day 0" separately
// yes, snowman is *that* bad
"Homeroom
"sP           // you know the drill
// for each number in [0 1 2 3]
0vn4nR*#:
    `"Period "sP
    `NiNtSsP  // increment and print
    "
"sP
;aE
"Lunch
"sP           // same stuff from here
// only interesting thing is we saved the range from before with *#, so we can
//   get it back easily
#:`"Period "sP`5nAtSsP"
"sP;aE

;

#bI

Thoughts and musings:

Firstly, I definitely need to implement a prettier way of printing newlines. Because strings with newlines in an indented block are super ugly.
I like my trick with ae—you rarely see the ae operator without the E capitalized in real Snowman code. (You also rarely see Snowman code that's not written by me, but that's besides the point.)

For the uninitiated, Snowman has two ways to call operators. "Consume" mode, and "non-consume" mode. "Consume" mode will call the operator with the variables requested and then discard the variables. Non-consume mode will call the operator and still leave the variables intact.

Which is usually not what you want with ae (array-each), because the block you're calling on each element will stay there and get in your way, using up a precious one of the eight variables.

However, this is a rare situation in which ae is actually what we want (see the comments in the code for further explanation).
I'm really, really starting to think that Snowman needs more than two modes, other than just "consume" and "do-not-consume." For example, with aa (basically array indexing), you only get two ways to call it:

["foo" 0] -> ["f"]
["foo" 0] -> ["foo" 0 "f"]

(Snowman doesn't use a stack/array structure, but that's simply being used for clarity here.)

It's pretty common that you want ["foo" "f"] (i.e. consume the index variable, but not the original one). It's a super convoluted process to get rid of that annoying 0 if you use "do-not-consume" mode.

A similar thing happens when you call "array-each" in "do-not-consume" mode, as is done here. The array and the block stick around, even during the execution of said block. Which is... really, really weird.

Then again, the design goal of Snowman is to be as confusing as possible, so I'm not sure whether this is a problem at all.


Solving Mastermind in 6 or less moves Your goal is to write a program that will solve any Mastermind puzzle in 6 or less moves.

Background

Mastermind is a board game. The goal of the game is to exactly guess the combination (colours and order) of 4 coloured pegs hidden by the other player. When a guess is made, the other player responds with between 0 and 4 white and or red pegs. A red peg is where the colour and location are correct. A white peg is where the colour is represented in the remaining pieces, but is in the incorrect location. If there are duplicate colours in the guess, there will only be one peg awarded per corresponding colour in the secret. (So - if the secret contained 1 Blue, and the guess had 2 blues with one in the correct location, there would be one red peg given). There are 6 different colors, and duplicates may be used.

So for instance, a game might go as follows:
(Assuming the solution is Red Green Green Blue)

1:  Blue Purple Black Green - 2 white pegs
2:  Green Red Black Blue    - 2 white pegs, 1 red peg
3:  Green Green Green Blue  - 3 red pegs
4:  Red Green Green Blue    - 4 red pegs

The rules are expanded on Wikipedia

Requirements

The program must read from stdin, and write to stdout
I will be using numbers for simplicity instead of colors. The combination to guess will be 4 numbers between 1 and 6
They must output their guesses as a series of 4 space separated numbers from 1 to 6 concluding with a newline. For instance:

1 5 2 2 \n
The program will subsequently receive as input after its guess 2 integers between 0 and 4 separated by a space and concluding with a newline. The first will be the amount of white pegs, the second the amount of red pegs.
On an input of "0 4" (4 red pegs), the program must terminate
The program must be able to solve any puzzle in less then 6 turns (your program giving output, followed by the response input is 1 turn). There is no bonus (due to complexity of proof) for being able to solve it in less.
The solution must be completely internal and included in the source. Standard Libraries only are permitted. The solution may therefore not rely on any other files (such as dictionaries), or the internet.

Example Input/Output

> is your programs output
< is the responding input
Solution is 1 5 6 6

> 1 2 3 4
< 0 1
> 4 1 6 6
< 1 2
> 1 6 5 6
< 2 2
> 1 5 6 6
< 0 4

Scoring

This is pure and simple Code Golf. The shortest solution in bytes wins.

This is my first Code Golf question. My apologies if I have done something wrong, but I've attempted as well as possible to ensure that there is absolutely no ambiguity, and prevent as much rules lawyering as possible. If I have been ambiguous or unclear, please feel free to ask questions.

Python 2 Python 3, 359 365 338 chars

from itertools import*
from collections import*
m=h=set(product(*['123456']*4))
def f(g,k):b=sum(x==y for x,y in zip(g,k));return'%s %s'%(sum(min(g.count(c),k.count(c))for c in set(g))-b,b)
while len(m)>1:g=min(h,key=lambda g:max(Counter(f(g,k)for k in m).values()));print(*g);s=input();m=set(x for x in m if s==f(g,x))
print(*(m.pop()))

Funny, it took me many edits to realize I had a five character variable name.

I do not like the long imports.  It feels like I should be able to implement a replacement for collections.Counter that would save the import.

I also do not like the print(*(m.pop())) at the end.  It feels like it should disappear into the while loop, but I can't find a way to do it without making it longer.


Find the index of reflection of a substring of a palindrome Problem Statement:
You will receive a substring of a palindromic string. You must return the index of the substring which marks the point of reflection of the original string. You are only provided the substring, which is not necessarily a palindrome because it is not necessarily centered about the middle of the original palindromic string.
Input: Substring of length 2n + 1,  1 <= n <= 1000, which encompasses the center of reflection of some larger palindromic string.
Output: Return the index of the substring which marks the point of reflection. May be 0-indexed or 1-indexed.
Test cases (character at desired index is bold to show the desired output more clearly):
Input

manaplanacanalpan
caroracati
wlatemymeta
nasanita

Output

9 (the full string was “a man a plan a canal panama”, with spaces removed)
4 (the full string was “was it a car or a cat i saw”, with spaces removed)
6 (the full string was “mr owl are my metal worm”, with spaces removed)
2 (the full string was “oozy rat in a sanitary zoo”, with spaces removed)

Winning Criterion: This is code-golf Shortest code in bytes wins.
Assumption: Assume there is just a single candidate palindrome
Restriction:0 and 2n (last index) are invalid output.

J, 26 25 bytes
[:(-:@i.>./)[:(*/*#)/.=/~

Try it online!
how
=/~ creates a function table comparing all possible pairs of characters.  Taking 'nasanita' as an example:
1 0 0 0 1 0 0 0
0 1 0 1 0 0 0 1
0 0 1 0 0 0 0 0
0 1 0 1 0 0 0 1
1 0 0 0 1 0 0 0
0 0 0 0 0 1 0 0
0 0 0 0 0 0 1 0
0 1 0 1 0 0 0 1

Notice the /-direction diagonals.  If one of those is all ones, it corresponds to an embedded palindrome.
J has an adverb /. which lets us to apply a verb to each diagonal.
We choose the verb (*/*#) -- the sum multiplied by the length.  Thus it will be the length of the diagonal if it's all ones, and 0 otherwise:
1 0 0 0 5 0 0 0 0 0 0 0 0 0 1

i.>./ Find the index of the max element within that list.  In this case the index of 5 is 4.
-:@ And divide it by 2.


Recover the power from the prime power It seems that many people would like to have this, so it's now a sequel to this challenge!

Definition: a prime power is a natural number that can be expressed in the form pn where p is a prime and n is a natural number.

Task: Given a prime power pn > 1, return the power n.

Testcases:

input output
9     2
16    4
343   3
2687  1
59049 10

Scoring: This is code-golf. Shortest answer in bytes wins.


Those Greedy Romans! Given a strictly positive integer, return the shortest possible Roman numeral using only the additive rule. Output must consist of zero or more of each of the characters MDCLXVI in that order. The number 14 must therefore give XIIII rather than XIV.
The characters' numeric values are M=1000, D=500, C=100, L=50, X=10, V=5, I=1.
Examples
3 → III
4 → IIII
9 → VIIII
42 → XXXXII
796 → DCCLXXXXVI
2017 → MMXVII
16807 → MMMMMMMMMMMMMMMMDCCCVII

Plain English, 1059 1025 678 641 451 399 bytes

Saved 34 bytes by removing an error trap.  Then saved 384 bytes by golfing.  Then saved 190 bytes by combining the division operation with the append operation ("z") into a new operation ("p").  Then saved 52 bytes by golfing.

A s is a string.
To p a r remainder a s a x string a n number:
If the x is "", exit.
Divide the r by the n giving a q quotient and the r.
Fill a t s with the x's first's target given the q.
Append the t to the s.
To convert a r number to a s:
p the r the s "M" 1000.
p the r the s "D" 500.
p the r the s "C" 100.
p the r the s "L" 50.
p the r the s "X" 10.
p the r the s "V" 5.
p the r the s "I" 1.

Here is the ungolfed version of the final code, plus an error trap for a negative number:

A roman numeral is a string.

To process a remainder given a roman numeral and a letter string is a number:
  If the letter is "", exit.
  Divide the remainder by the number giving a quotient and the remainder.
  Fill a temp string with the letter's first's target given the quotient.
  Append the temp string to the roman numeral.

To convert a number to a roman numeral:
  If the number is negative, exit.
  Put the number in a remainder.
  Process the remainder given the roman numeral and "M" is 1000.
  Process the remainder given the roman numeral and "D" is  500.
  Process the remainder given the roman numeral and "C" is  100.
  Process the remainder given the roman numeral and "L" is   50.
  Process the remainder given the roman numeral and "X" is   10.
  Process the remainder given the roman numeral and "V" is    5.
  Process the remainder given the roman numeral and "I" is    1.


Countdown and recycle Countdown

Your goal for this code-golf challenge is to count down and meanwhile recycle numbers. Let me explain.

First your application reads a number, either as program argument or using stdin.
Next you'll simply need to count down like this:
10 9 8 7 6 (in descending order)

But wait, there is more!

Recycling

There are situations where we can print every number, but don't list every number, we can do recycling! Let me give a quick example:

Input: 110

Output:   11091081071061051041031021010099... etc
Recycled:  10                        1

We've now still listed all the numbers, 110, 109, 108, but we've recycled a 0 and a 1.

Another example:

Input: 9900

Output:   9900989989897989698959894... etc
Recycled:        9 98

Code-golf challenge

Read a number (argument or stdin)
Output the countdown in descending order while recycling all possible numbers (to stdout or file)
Stop when you reach 1 OR the moment you've recycled 0 to 9 (whatever happens first)

Simple example (until 1 reached):

Input: 15
Output: 15141312110987654321

(Notice the 110 instead of 1110)

More advanced example (all recycled):

Input: 110
Output:   110910810710610510410310210100998979695949392919089887868584838281807978776757473727170696867665646362616059585756554535251504948474645443424140393837363534332313029282726252423221
Recycled:  10                            9                    8                    7                    6                    5                    4                    3                    2

(We've recycled all 0-9)

T-SQL - 291 277 267 217 199 191 166 158 153 145 142 128 117
After approaching this in a new way, I managed to get down to 145(142 after a couple minor tweaks), not too shabby. That means I might be able to compete for silver or bronze. ^^
DECLARE @ INT=100;WITH N AS(SELECT 1A UNION ALL SELECT A+1FROM N WHERE A<@)SELECT LEFT(A,LEN(A)-1+A%11)FROM N ORDER BY-A

This doesn't print a list, it selects the results. The question never gave specifics about output, so this should be fine. This still has the same limit of 100 on the input, partly because I'm abusing the fact that every 11th term under 100 loses a character and partly because of the default 100 recursion limit on common table expressions.
DECLARE @ INT=100;

WITH N AS
(
    SELECT 1A
    UNION ALL
    SELECT A+1
    FROM N
    WHERE A<@
)

SELECT LEFT(A,LEN(A)-1+A%11)
FROM N
ORDER BY-A


Display a Lemniscate (∞) The infinity symbol is also called a lemniscate. Your program must draw a lemniscate with text via standard out (formatted with newline feeds) or graphically.

The infinity symbol (by my standards) must be continuous (that is, every non-whitespace character must be touching two other non-whitespace characters diagonally or orthogonally). It must also have two and no more than two gaps of enclosed whitespace (connectivity for whitespace is only orthogonal). Thus, the following output fails:

   ooo   ooo
 o    o o    o
o      o      o
 o    o o    o
   ooo   ooo

A correct version the above example might be

  oooo   oooo
 o    o o    o
o      o      o
 o    o o    o
  oooo   oooo

or

  ooo   ooo
 o   o o   o
o     o     o
 o   o o   o
  ooo   ooo

The size of the ∞ is unimportant. The orientation of the ∞ is unimportant. Symmetry is also unimportant. Graphical displays are accepted as well. Appropriate newline feeds are required in the output.

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

Desmos, 22 bytes

r=\sqrt{\sin 2\theta }

Try it here! Desmos is a graphing tool. This plots the polar equation:

which draws a lemniscate shape.


Is this square symmetrical? Write a program or function that takes in a 4×4 text grid consisting of exactly 4 A's, 4 B's, 4 C's, and 4 D's, such as:

ACDC
BBCA
BADD
ABCD

The ABCD's may be in any arrangement but there will always be 4 of each. You can assume the input is valid. If desired you can also assume it has a trailing newline and/or that it comes as one line in reading order, e.g. ACDCBBCABADDABCD. You may also replace the characters ABCD with 0123 or 1234 respectively, if desired (but that's all).

Output a truthy value if the text grid has any form of reflective or rotational symmetry. Specifically:

If there is a central horizontal line of symmetry. e.g.

BACD
BACD
BACD \___ bottom mirrors top
BACD /

If there is a central vertical line of symmetry. e.g.

BCCB
DAAD
CAAC
BDDB
  \/___ right mirrors left

If there is a diagonal line of symmetry (in either direction). e.g.

     ___ diagonally mirrored
    /
ABDC
BACD
DCAB
CDBA
    \___ diagonally mirrored

If there is 90° rotational symmetry. e.g.

BDAB
ACCD    same if rotated 90 degrees (or 180 or 270)
DCCA
BADB

If there is 180° rotational symmetry. e.g.

DBCA
BDCA    same if rotated 180 degrees
ACDB
ACBD

(Note that translational symmetry doesn't come into play here.)

Output a falsy value if the grid doesn't have one of the symmetries mentioned above. e.g. the very first example grid.

The shortest code in bytes wins.

CJam, 16 bytes

{{z_W%_}4*;])e=}

An unnamed block which expects the input as a list of four strings on top of the stack and leaves a 0 (falsy) for asymmetric inputs and a positive integer (truthy) for symmetric inputs.

Test it here. Or run a full test suite.

Explanation

The symmetries of the square are the elements of the dihedral group of order 8 (which are just the 4 rotations of the square and the same 4 rotations of some reflected version of the square). It's not possible to generate this group from repeated application of a single permutation. But two reflections always give some rotation. Hence, the entire group can be generated by alternating between two reflections four times. (We just need to make sure that the two reflections give the 90 degree or 270 degree rotation, not 0 or 180.)

The challenge asks whether the input square is equal to any of the other 7 symmetries. So this answer just generates all of them and then checks whether the input is among the others.

{      e# Run this block 4 times.
  z_   e# Transpose the grid and duplicate it. (This is one type of reflection.)
  W%_  e# Reverse the lines and duplicate it. (This is another type of
       e# reflection. Together they rotate the grid by 90 degrees.)
}4*    e# The last element will be the original grid again.
;      e# Discard one copy of that original grid.
]      e# Wrap all symmetries in a list.
)      e# Pull off the original grid.
e=     e# Count how many times it appears among the other symmetries.

To see how the repeated application of z and W% generates all symmetries, have a look at this "diagram":

     0123
     4567
     89ab
     cdef

     original

 z   048c       W%       37bf
-->  159d  ----------->  26ae
     26ae                159d
     37bf                048c

     diag. refl.         rot. 90 degrees ccw

 z   3210       W%       fedc
-->  7654  ----------->  ba98
     ba98                7654
     fedc                3210

     vert. refl.        rot. 180 degrees

 z   fb73       W%       c840
-->  ea62  ----------->  d951
     d951                ea62
     c840                fb73

     antidiag. refl.     rot. 270 degrees ccw

 z   cdef       W%       0123
-->  89ab  ----------->  4567
     4567                89ab
     0123                cdef

     horiz. refl.        original


Convert a program to a palindromic program A palindrome is a string that is the same forwards and backwards, such as "racecar".

Write a program in some language L, that takes any program P1 in language L as input, and outputs a palindromic program P2 in language L that does the same thing as P1.

You do not need to worry about handling input programs with syntax errors.

This is code golf, so the solution with the fewest number of bytes wins.

Perl, 55 54 bytes

undef$/;$a=<>."\n__END__\n";print$a,scalar reverse$a;

Reads program source from stdin and writes to stdout.

Result of running on itself:

undef$/;$a=<>."\n__END__\n";print$a,scalar reverse$a;

__END__

__DNE__

;a$esrever ralacs,a$tnirp;"n\__DNE__n\".><=a$;/$fednu


Find the sets of sums I've enjoyed reading this site; this is my first question. Edits are welcome.
Given positive integers \$n\$ and \$m\$, compute all ordered partitions of \$m\$ into exactly \$n\$ positive integer parts, and print them delimited by commas and newlines. Any order is fine, but each partition must appear exactly once.
For example, given \$m=6\$ and \$n=2\$, possible partitions are pairs of positive integers that sum to 6:
1,5
2,4
3,3
4,2
5,1

Note that [1,5] and [5,1] are different ordered partitions. Output should be exactly in the format above, with an optional trailing newline. (EDIT: The exact order of the partitions does not matter). Input/output are via standard code-golf I/O.
Another example output for \$m=7, n=3\$:
1,1,5
1,2,4
2,1,4
1,3,3
2,2,3
3,1,3
1,4,2
2,3,2
3,2,2
4,1,2
1,5,1
2,4,1
3,3,1
4,2,1
5,1,1

The smallest code in bytes after 1 week wins.
Again, please edit if necessary.
Addendum:
@TimmyD asked what size of integer input the program has to support. There is no hard minimum beyond the examples; indeed, the output size increases exponentially, roughly modelled by: lines = \$e^{(0.6282 n - 1.8273)}\$.
n | m | lines of output
2 | 1 | 1
4 | 2 | 2
6 | 3 | 6
8 | 4 | 20
10 | 5 | 70
12 | 6 | 252
14 | 7 | 924
16 | 8 | 3432
18 | 9 | 12870
20 | 10 | 48620
22 | 11 | 184756
24 | 12 | 705432

Pyth, 14 bytes

V^SQEIqsNQj\,N

Try it online: Demonstration or Test Suite

Explanation:

V^SQEIqsNQj\,N   implicit: Q = first input number
  SQ             create the list [1, 2, ..., Q]
    E            read another number
 ^               cartesian product of the list
                 this creates all tuples of length E using the numbers in SQ
V                for each N in ^:
     IqsNQ          if sum(N) == Q:
          j\,N         join N by "," and print


Print the British Flag! Inspired by Print the American Flag! this is a direct copy but with the British flag as it has some symmetries but is still quite complex!

Your challenge is to produce the following ASCII-Art in as few bytes as possible! Turn your head/screen (not both!) by 90 degrees to view it properly.

 __________________________________________
|\  \XXXXXXXXXXXX  000000  XXXXXXXXXXXX//0/|
|0\  \XXXXXXXXXXX  000000  XXXXXXXXXXX//0/ |
|\0\  \XXXXXXXXXX  000000  XXXXXXXXXX//0/  |
|\\0\  \XXXXXXXXX  000000  XXXXXXXXX//0/  /|
|X\\0\  \XXXXXXXX  000000  XXXXXXXX//0/  /X|
|XX\\0\  \XXXXXXX  000000  XXXXXXX//0/  /XX|
|XXX\\0\  \XXXXXX  000000  XXXXXX//0/  /XXX|
|XXXX\\0\  \XXXXX  000000  XXXXX//0/  /XXXX|
|XXXXX\\0\  \XXXX  000000  XXXX//0/  /XXXXX|
|XXXXXX\\0\  \XXX  000000  XXX//0/  /XXXXXX|
|XXXXXXX\\0\  \XX  000000  XX//0/  /XXXXXXX|
|XXXXXXXX\\0\  \X  000000  X//0/  /XXXXXXXX|
|XXXXXXXXX\\0\  \  000000  //0/  /XXXXXXXXX|
|XXXXXXXXXX\\0\    000000  /0/  /XXXXXXXXXX|
|XXXXXXXXXXX\\0\   000000  0/  /XXXXXXXXXXX|
|XXXXXXXXXXXX\\0\  000000  /  /XXXXXXXXXXXX|
|XXXXXXXXXXXXX\\0  000000    /XXXXXXXXXXXXX|
|XXXXXXXXXXXXXX\\  000000   /XXXXXXXXXXXXXX|
|                  000000                  |
|000000000000000000000000000000000000000000|
|000000000000000000000000000000000000000000|
|000000000000000000000000000000000000000000|
|                  000000                  |
|XXXXXXXXXXXXXX/   000000  \\XXXXXXXXXXXXXX|
|XXXXXXXXXXXXX/    000000  0\\XXXXXXXXXXXXX|
|XXXXXXXXXXXX/  /  000000  \0\\XXXXXXXXXXXX|
|XXXXXXXXXXX/  /0  000000   \0\\XXXXXXXXXXX|
|XXXXXXXXXX/  /0/  000000    \0\\XXXXXXXXXX|
|XXXXXXXXX/  /0//  000000  \  \0\\XXXXXXXXX|
|XXXXXXXX/  /0//X  000000  X\  \0\\XXXXXXXX|
|XXXXXXX/  /0//XX  000000  XX\  \0\\XXXXXXX|
|XXXXXX/  /0//XXX  000000  XXX\  \0\\XXXXXX|
|XXXXX/  /0//XXXX  000000  XXXX\  \0\\XXXXX|
|XXXX/  /0//XXXXX  000000  XXXXX\  \0\\XXXX|
|XXX/  /0//XXXXXX  000000  XXXXXX\  \0\\XXX|
|XX/  /0//XXXXXXX  000000  XXXXXXX\  \0\\XX|
|X/  /0//XXXXXXXX  000000  XXXXXXXX\  \0\\X|
|/  /0//XXXXXXXXX  000000  XXXXXXXXX\  \0\\|
|  /0//XXXXXXXXXX  000000  XXXXXXXXXX\  \0\|
| /0//XXXXXXXXXXX  000000  XXXXXXXXXXX\  \0|
|/0//XXXXXXXXXXXX__000000__XXXXXXXXXXXX\__\|

The block is 44 x 42 characters. Note that the first line ends with a single space! No other trailing spaces are allowed but a trailing new line is allowed on the last line.

I'm not aware of any date significance for the UK at the moment!


Box-256 Assembly - BIG SQUARE II I'd like to start a series of challenges for http://box-256.com/ starting with the first challenge, “BIG SQUARE II”. After this one I'll add another for "CHECKERBOARD" and so on.

Rules:

Complete the BIG SQAURE II challenge in the Box-256 emulator (either on the website or download the program if you run Windows)
Post back here a screenshot of your working answer
You MUST include the code in plain text so that others can easily copy and very it’s operation.

Scoring:

The winner will be the least amount of instructions used (just the instruction calls, either by name or opcode, the arguments to them are not counted as JMP takes one argument but MOD can take three).

I think in the future contests we can add some additional bonus points for use of coding tricks and we could include the argument count too. I wanted to start basic to get the ball rolling.

Winning

I think we should put a stake in the ground and say two weeks from today we announce the winner(s, there maybe be mutliple entries with the same instruction count).

8 instructions

My smallest solution to the Big Square II challenge is 8 lines of code. There's a simple loop which cycles through a table of 8 pixel locations.

; Big Square II in 0x08h instructions
; John Metcalf

PIX @18 002 000
ADD @16 @18 @18
MOV @18 @20 001
MOV @19 @18 008
FLP @16 @17 001
JMP @00 001 010
011 031 021 032
0D3 01D 0E3 01E


Making a Mountain out of a Molehill You are given a string of terrain, with molehills and mountains:

                        /\
                       /  \
              _/\__   /    \
          ___/     \_/      \_
____/\___/                    \___

Your job is to replace every molehill in the string with an equivalent mountain centered in the same column. The rest of the string must be unaffected. This may require additional lines at the beginning of the string.

A molehill consists of adjacent columns where the terrain goes up, immediately followed by adjacent columns where the terrain goes down. The shortest side must be exactly one column wide.

These are all molehills:

_____/\______

   /\________
__/

________/\
          \__

\           /
 \         /
  \       /
   \     /
    \/\_/

These are not molehills:

    /\
___/  \______

      ___
_____/   \___

____  _______
    \/

A mountain is like a molehill, but the shortest side is four lines high instead of one.

Examples

                  /\
                 /  \
           ->   /    \
____/\____    _/      \_

                       /\
                      /  \
                     /    \
           __ ->    /      \__
_     /\__/      __/
 \___/

                         /\
                        /  \
               ->      /    \
  /\                /\/      \
_/  \__/\_____    _/          \_

_                _    _                _
 \              /      \      /\      /
  \            /        \    /  \    /
   \          /          \  /    \  /
    \        /     ->     \/      \/
     \      /
      \    /
       \/\/

                             /\      /\
                            /  \    /  \
                           /    \  /    \
_                     -> _/      \/      \
 \                                        \
  \                                        \
   \/\______/\_______                       \_

                        /\                           /\       /\
                       /  \               /\        /  \     /  \
              _/\__   /    \       ->    /  \      /    \   /    \
          ___/     \_/      \_          /    \  __/      \_/      \_
____/\___/                    \___    _/      \/                    \___

Additional Rules

Standard loopholes are forbidden.
Input and output can be in any reasonable format.
You may assume the presence or absence of trailing whitespace in the input string.
There will always be enough space in the sides of the string as well as between molehills for any mountains you might need.
If replacing the molehills with mountains creates additional molehills, you do not need to turn those molehills into mountains.
The terrain cannot go both up and down in the same column. If this happens, the terrain does not move.
If a particular column does not become part of a mountain, its height must remain unchanged.

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

Python 2, 509 495 480 bytes

def f(S):
 B='\\';F='/';s=''.join(map(max,*S.split('\n')));t=list(re.sub(r'..((./\\[^\\])|([^/]/\\.))..',r'////\\\\\\\\',s));C=s.count;D=t.count;d=C(F)-D(F)+D(B)-C(B);m=[{'_':F,B:'_'},{'_':B,F:'_'}][d<0];d=abs(d);i=1
 while d:
	if s[i]!=t[i]:i+=7
	elif t[i]in m:d-=1;t[i]=m[t[i]]
	i+=1
 return'\n'.join(u for u in map(''.join,zip(*[u.ljust(2*len(S))for u in reduce(lambda (a,p),c:(a+[' '*[p,p-1][c==B]+c],p+[[0,-1][c==B],1][c==F]),t,([],len(t)))[0]]))[::-1]if u.strip())
import re

Try it online!
Still not clear what the actual rules are; but here are the additional constraints that are enforced above and beyond the rule that molehills shall be turned into mountains:

The first and last terrain characters of the output must be _, just as they must be for valid inputs.
The vertical difference between the first _ and the last _ must be maintained between the input and output.
After substitutions from turning molehills into mountains, some other characters might need to be changed in order to maintain said vertical difference; but the characters changed must not be any of the characters that are part of mountains that were created from molehills.
And when accomplishing these changes, the number of additional characters changed must be minimal.

Ungolfed Algorithm:
def f(s):
    s = ''.join(map(max,*s.split('\n'))) # flatten into a single line
    t = re.sub(r'..((./\\[^\\])|([^/]/\\.))..',r'////\\\\\\\\',s) # replace molehills with mountains
    d = s.count('/')-t.count('/')+t.count('\\')-s.count('\\') # are the two strings equally balanced?
    m=[{'_':'/','\\':'_'},{'_':'\\','/':'_'}][d<0] # make an appropriate mapping...
    d=abs(d);i=1 # skip over leading '_'...
    while d: # while still unbalanced...
        if s[i]!=t[i]:i+=7 # skip over any created mountains (7+1==8)
        elif t[i] in m:d-=1;t = t[:i]+m[t[i]]+t[i+1:] # if can replace, do replace
        i += 1 # next char
    t = reduce(lambda (a,p),c:(a+[' '*[p,p-1][c=='\\']+c],p+[[0,-1][c=='\\'],1][c=='/']),t,([],len(t)))[0]  # pad spaces at left side
    t = map(''.join,zip(*[u.ljust(max(map(len,t))) for u in t])) # rotate
    return '\n'.join(u for u in t[::-1] if u.strip()) # reverse and join into lines.
import re


Every Possible Cycle Length A function (or program) which takes inputs and provides outputs can be said to have a cycle if calling the function on its own output repeatedly eventually reaches the original number. For instance, take the following function:

Input:  n    1 2 3 4 5 6
Output: f(n) 5 7 1 3 4 9

If we start with n=1, f(n)=5, f(f(n))=f(5)=4, f(f(f(n)))=f(4)=3, f(f(f(f(n))))=f(3)=1.

This is written (1 5 4 3). Since there are 4 unique numbers in this loop, this is a cycle of length 4.

Your challenge is to write a program or function which has cycles of every possible length. That is, there must be a cycle of length 1, of length 2, and so on.

In addition, your function/program must be from the positive integers to positive integers, and it must be bijective, meaning that there must be a exactly one input value for every possible output value, over all positive integers. To put it another way, the function/program must compute a permutaion of the positive integers.

Details: Any standard input/output system is allowed, including STDIN, STDOUT, function argument, return, etc. Standard loopholes prohibited.

You do not need to worry about the limitations of your data types - the above properties need only hold under the assumption that an int or float can hold any value, for instance.

There are no restrictions on the behavior of the function on inputs which are not positive integers, and those inputs/outputs will be ignored.

Scoring is code golf in bytes, shortest code wins.

Pyth, 11 8 bytes
.<W-0zz1

A lot more boring than my previous answer.
Every number that contains a 0 digit maps to itself. Any other number maps to the number that has its digits rotated by 1. So for example:
1 -> 1
10 -> 10
15 -> 51 -> 15
104 -> 104
123 -> 231 -> 312 -> 123