Hello World in Multiple Languages Task

Create a program or a function that is valid in multiple programming languages, and when compiled/interpreted as a different language outputs "Hello, World!" in a different natural language.

For example, a valid solution might output Hello World! (English) when compiled and run as C, Hallo Welt! (German) when compiled and run as C++ and 你好世界！ (Chinese) when run as Python.

Rules

To avoid ambiguity about the validity of an answer, below is a list of allowed versions of the phrase in several languages. The list consists of the phrase in languages for which Google Translate has a community-verified translation of the phrase (as of this writing).*

The accuracy of these translations is debatable, but they are what this challenge will use. The printed strings must follow exactly the format below (with the exception of leading or trailing whitespace).

Afrikaans:    Hello Wêreld!
Albanian:     Përshendetje Botë!
Amharic:      ሰላም ልዑል!
Arabic:       مرحبا بالعالم!
Armenian:     Բարեւ աշխարհ!
Basque:       Kaixo Mundua!
Belarussian:  Прывітанне Сусвет!
Bengali:      ওহে বিশ্ব!
Bulgarian:    Здравей свят!
Catalan:      Hola món!
Chichewa:     Moni Dziko Lapansi!
Chinese:      你好世界！
Croatian:     Pozdrav svijete!
Czech:        Ahoj světe!
Danish:       Hej Verden!
Dutch:        Hallo Wereld!
English:      Hello World!
Estonian:     Tere maailm!
Finnish:      Hei maailma!
French:       Bonjour monde!
Frisian:      Hallo wrâld!
Georgian:     გამარჯობა მსოფლიო!
German:       Hallo Welt!
Greek:        Γειά σου Κόσμε!
Hausa:        Sannu Duniya!
Hebrew:       שלום עולם!
Hindi:        नमस्ते दुनिया!
Hungarian:    Helló Világ!
Icelandic:    Halló heimur!
Igbo:         Ndewo Ụwa!
Indonesian:   Halo Dunia!
Italian:      Ciao mondo!
Japanese:     こんにちは世界！
Kazakh:       Сәлем Әлем!
Khmer:        សួស្តីពិភពលោក!
Kyrgyz:       Салам дүйнө!
Lao:          ສະບາຍດີຊາວໂລກ!
Latvian:      Sveika pasaule!
Lithuanian:   Labas pasauli!
Luxemburgish: Moien Welt!
Macedonian:   Здраво свету!
Malay:        Hai dunia!
Malayalam:    ഹലോ വേൾഡ്!
Mongolian:    Сайн уу дэлхий!
Myanmar:      မင်္ဂလာပါကမ္ဘာလောက!
Nepali:       नमस्कार संसार!
Norwegian:    Hei Verden!
Pashto:       سلام نړی!
Persian:      سلام دنیا!
Polish:       Witaj świecie!
Portuguese:   Olá Mundo!
Punjabi:      ਸਤਿ ਸ੍ਰੀ ਅਕਾਲ ਦੁਨਿਆ!
Romanian:     Salut Lume!
Russian:      Привет мир!
Scots Gaelic: Hàlo a Shaoghail!
Serbian:      Здраво Свете!
Sesotho:      Lefatše Lumela!
Sinhala:      හෙලෝ වර්ල්ඩ්!
Slovenian:    Pozdravljen svet!
Spanish:      ¡Hola Mundo!         // Leading '¡' optional
Sundanese:    Halo Dunya!
Swahili:      Salamu Dunia!
Swedish:      Hej världen!
Tajik:        Салом Ҷаҳон!
Thai:         สวัสดีชาวโลก!
Turkish:      Selam Dünya!
Ukrainian:    Привіт Світ!
Uzbek:        Salom Dunyo!
Vietnamese:   Chào thế giới!
Welsh:        Helo Byd!
Xhosa:        Molo Lizwe!
Yiddish:      העלא וועלט!
Yoruba:       Mo ki O Ile Aiye!
Zulu:         Sawubona Mhlaba!

So there are 74 languages that can be used.

Winning Criterion

The solution that can output the phrase in the greatest number of languages wins. In case of a tie, the shorter solution (in bytes) wins.

*The translations for Malagasy and Maltese were marked community-verified, but were clearly incorrect (one was just "Hello World!" and the other "Hello dinja!", but "Hello!" alone translates to "Bongu!"). These were excluded. Also some languages (Arabic, Hebrew, Pashto, Persian and Yiddish) read from right to left on Google Translate, but when copied here they read from left to right. I hope that's okay.

16 languages, 1363 bytes
 #define ip"MemuL tulaS",,,,,,,,,,"!",@++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.@,kc"Kaixo Mundua!"v#!
#define print(A,B,C)main(){printf("Helo Byd!");}//ss                                                                          ;ooooooooooooooooooo"Moni Dziko Lapansi!"<[-
#ifdef __cplusplus//p                                                                                ;;];;
#include<cstdio>//ffffffffff?
#define print(A,B,C)int main(){printf("Halo Dunya!");}//ssp
#endif//;  [;;;;;;;;;     "!etejivs vardzoP"]
#ifdef __OBJC__//;;;;;
#define print(A,B,C)main(){printf("Hallo Welt!");}//ss
#endif//\
"""echo" "Salom Dunyo!";"exit";puts"Moien Welt!";\
__END__
#define B//\
"""#;;;;;
print(["Hai dunia!","Hej Verden!","Halo Dunia!"][(int(1>0)is 1)+~int(-1/2)*2])
#define s eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeejeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeejiiiiiiiijeeeeeeeeeeeeeejiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiijeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeejeejijiiiiiiiiiijeeeeeeeeeeejiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiij
#define U   !"!dlereW ollaH"<           ;
#define T@,kc"Sannu Duniya!?%?"

Try it online!
(use "switch languages" to change language)

Python 3 = Halo Dunia! (Indonesian)

Python 2 = Hej Verden! (Danish)

Python 1 = Hai dunia! (Malay)

C (gcc) = Helo Byd! (Welsh)

C++ (gcc) = Halo Dunya! (Sundanese)

Objective C (clang) = Hallo Welt! (German)

Brainfuck = Hello World! (English, obviously)

Befunge-93 = Salut Lume! (Romanian)

Ruby = Moien Welt! (Luxemburgish)

Bash = Salom Dunyo! (Uzbek)

Befunge-98 (PyFunge) = Kaixo Mundua! (Basque)

Unefunge-98 (PyFunge) = Sannu Duniya! (Hausa)

Cardinal = Hallo Wereld! (Dutch)

Alphuck = Ciao mondo! (Italian)

><> = Moni Dziko Lapansi! (Chichewa)

Fission = Pozdrav svijete! (Croatian)

Any golfing tips are welcome (especially on the Brainfuck)!!
Thanks to @JonathanFrech for -1 byte! Also, thanks to @ovs for -40 bytes!
How (general ideas, I actually forgot specifics)??
The languages can be put into four groups:

Macro: C, C++, Objective C
Comment: Python3, Python2, Python1, Ruby, Bash
Dimensional: Befunge-93, Befunge-98, Unefunge-98, Cardinal, ><>, Fission
Vulgar: Brainfuck, Alphuck

The Macro languages see # as the start of a preprocessor directive. These are used for three reasons: to house code for other groups, to distinguish among Macro languages, and to actually define a macro. All three use // as comment, so after that we store code for the other groups. Also, the backslash continues the comment in these languages.
The Comment languages see # as the start of a comment. The quirk here is the triple quotes, which distinguish the Pythons from Ruby from Bash. And to distinguish Python 1 from 2 from 3, we use a distinguishing feature in all three, along with an array of outputs. Oh yeah, there's also that __END__. This is used to end the code for some (can't remember exactly which ones) of the Comment languages.
The Dimensional languages are distinguished in a way that is hard to explain. One has to know the specifics of each language to figure it out. For example, # is only a skip in the fungeoids, while it does various different things in the other languages. The code is strewn about everywhere for these languages.
And finally, we arrive at the Vulgar languages. These two ignore everything that isn't in their set of valid characters. A balancing act has to be played with these languages and the others, as the code already contains characters in the character sets.
Edit: Wow... Somehow I only now realized Brainfuck did not seem to work, so that's fun!


Shortest universal maze exit string A maze on an N by N grid of square cells is defined by specifying whether each edge is a wall or not a wall. All outer edges are walls. One cell is defined as the start, and one cell is defined as the exit, and the exit is reachable from the start. The start and exit are never the same cell.

Note that neither the start nor the exit need to be on the outer border of the maze, so this is a valid maze:

A string of 'N', 'E', 'S' and 'W' indicates attempting to move North, East, South and West respectively. A move that is blocked by a wall is skipped without movement. A string exits a maze if applying that string from the start results in the exit being reached (regardless of whether the string continues after reaching the exit).

Inspired by this puzzling.SE question for which xnor provided a provable method of solving with a very long string, write code that can find a single string that exits any 3 by 3 maze.

Excluding invalid mazes (start and exit on the same cell, or exit not reachable from start) there are 138,172 valid mazes and the string must exit each of them.

Validity

The string must satisfy the following:

It is composed of only the characters 'N', 'E', 'S' and 'W'.
It exits any maze it is applied to, if started at the start.

Since the set of all possible mazes includes each possible maze with each possible valid starting point, this automatically means that the string will exit any maze from any valid starting point. That is, from any starting point from which the exit is reachable.

Winning

The winner is the answer that provides the shortest valid string and includes the code used to produce it. If more than one of the answers provide a string of this shortest length, the first to post that string length wins.

Example

Here is an example string 500 characters long, to give you something to beat:

SEENSSNESSWNNSNNNNWWNWENENNWEENSESSNENSESWENWWWWWENWNWWSESNSWENNWNWENWSSSNNNNNNESWNEWWWWWNNNSWESSEEWNENWENEENNEEESEENSSEENNWWWNWSWNSSENNNWESSESNWESWEENNWSNWWEEWWESNWEEEWWSSSESEEWWNSSEEEEESSENWWNNSWNENSESSNEESENEWSSNWNSEWEEEWEESWSNNNEWNNWNWSSWEESSSSNESESNENNWEESNWEWSWNSNWNNWENSNSWEWSWWNNWNSENESSNENEWNSSWNNEWSESWENEEENSWWSNNNNSSNENEWSNEEWNWENEEWEESEWEEWSSESSSWNWNNSWNWENWNENWNSWESNWSNSSENENNNWSSENSSSWWNENWWWEWSEWSNSSWNNSEWEWENSWENWSENEENSWEWSEWWSESSWWWNWSSEWSNWSNNWESNSNENNSNEWSNNESNNENWNWNNNEWWEWEE

Thanks to orlp for donating this.

Leaderboard

Equal scores are listed in order of posting of that score. This is not necessarily the order that the answers were posted since the score for a given answer may be updated over time.

Judge

Here is a Python 3 validator that takes a string of NESW as a command line argument or via STDIN.

For an invalid string, this will give you a visual example of a maze it fails for.

C++, 97 95 93 91 86 83 82 81 79 characters

  NNWSWNNSENESESWSSWNSEENWWNWSSEWWNENWEENWSWNWSSENENWNWNESENESESWNWSESEWWNENWNEES

My strategy is fairly simple - an evolution algorithm that can grow, shrink, swap elements of and mutate valid sequences. My evolution logic is now nearly the same as @Sp3000's, as his was an improvement over mine.

However, my implementation of the maze logic is rather nifty. This allows me to check if strings are valid at blistering speed. Try to figure it out by looking at the comment, do_move and the Maze constructor.

#include <algorithm>
#include <bitset>
#include <cstdint>
#include <iostream>
#include <random>
#include <set>
#include <vector>

/*
    Positions:

        8, 10, 12
        16, 18, 20
        24, 26, 28

    By defining as enum respectively N, W, E, S as 0, 1, 2, 3 we get:

        N: -8, E: 2, S: 8, W: -2
        0: -8, 1: -2, 2: 2, 3: 8

    To get the indices for the walls, average the numbers of the positions it
    would be blocking. This gives the following indices:

        9, 11, 12, 14, 16, 17, 19, 20, 22, 24, 25, 27

    We'll construct a wall mask with a 1 bit for every position that does not
    have a wall. Then if a 1 shifted by the average of the positions AND'd with
    the wall mask is zero, we have hit a wall.
*/

enum { N = -8, W = -2, E = 2, S = 8 };
static const int encoded_pos[] = {8, 10, 12, 16, 18, 20, 24, 26, 28};
static const int wall_idx[] = {9, 11, 12, 14, 16, 17, 19, 20, 22, 24, 25, 27};
static const int move_offsets[] = { N, W, E, S };

int do_move(uint32_t walls, int pos, int move) {
    int idx = pos + move / 2;
    return walls & (1ull << idx) ? pos + move : pos;
}

struct Maze {
    uint32_t walls;
    int start, end;

    Maze(uint32_t maze_id, int start, int end) {
        walls = 0;
        for (int i = 0; i < 12; ++i) {
            if (maze_id & (1 << i)) walls |= 1 << wall_idx[i];
        }
        this->start = encoded_pos[start];
        this->end = encoded_pos[end];
    }

    uint32_t reachable() {
        if (start == end) return false;

        uint32_t reached = 0;
        std::vector<int> fill; fill.reserve(8); fill.push_back(start);
        while (fill.size()) {
            int pos = fill.back(); fill.pop_back();
            if (reached & (1 << pos)) continue;
            reached |= 1 << pos;
            for (int m : move_offsets) fill.push_back(do_move(walls, pos, m));
        }

        return reached;
    }

    bool interesting() {
        uint32_t reached = reachable();
        if (!(reached & (1 << end))) return false;
        if (std::bitset<32>(reached).count() <= 4) return false;

        int max_deg = 0;
        uint32_t ends = 0;
        for (int p = 0; p < 9; ++p) {
            int pos = encoded_pos[p];
            if (reached & (1 << pos)) {
                int deg = 0;
                for (int m : move_offsets) {
                    if (pos != do_move(walls, pos, m)) ++deg;
                }
                if (deg == 1) ends |= 1 << pos;
                max_deg = std::max(deg, max_deg);
            }
        }

        if (max_deg <= 2 && ends != ((1u << start) | (1u << end))) return false;

        return true;
    }
};

std::vector<Maze> gen_valid_mazes() {
    std::vector<Maze> mazes;
    for (int maze_id = 0; maze_id < (1 << 12); maze_id++) {
        for (int points = 0; points < 9*9; ++points) {
            Maze maze(maze_id, points % 9, points / 9);
            if (!maze.interesting()) continue;
            mazes.push_back(maze);
        }
    }

    return mazes;
}

bool is_solution(const std::vector<int>& moves, Maze maze) {
    int pos = maze.start;
    for (auto move : moves) {
        pos = do_move(maze.walls, pos, move);
        if (pos == maze.end) return true;
    }

    return false;
}

std::vector<int> str_to_moves(std::string str) {
    std::vector<int> moves;
    for (auto c : str) {
        switch (c) {
        case 'N': moves.push_back(N); break;
        case 'E': moves.push_back(E); break;
        case 'S': moves.push_back(S); break;
        case 'W': moves.push_back(W); break;
        }
    }

    return moves;
}

std::string moves_to_str(const std::vector<int>& moves) {
    std::string result;
    for (auto move : moves) {
             if (move == N) result += "N";
        else if (move == E) result += "E";
        else if (move == S) result += "S";
        else if (move == W) result += "W";
    }
    return result;
}

bool solves_all(const std::vector<int>& moves, std::vector<Maze>& mazes) {
    for (size_t i = 0; i < mazes.size(); ++i) {
        if (!is_solution(moves, mazes[i])) {
            // Bring failing maze closer to begin.
            std::swap(mazes[i], mazes[i / 2]);
            return false;
        }
    }
    return true;
}

template<class Gen>
int randint(int lo, int hi, Gen& gen) {
    return std::uniform_int_distribution<int>(lo, hi)(gen);
}

template<class Gen>
int randmove(Gen& gen) { return move_offsets[randint(0, 3, gen)]; }

constexpr double mutation_p = 0.35; // Chance to mutate.
constexpr double grow_p = 0.1; // Chance to grow.
constexpr double swap_p = 0.2; // Chance to swap.

int main(int argc, char** argv) {
    std::random_device rnd;
    std::mt19937 rng(rnd());
    std::uniform_real_distribution<double> real;
    std::exponential_distribution<double> exp_big(0.5);
    std::exponential_distribution<double> exp_small(2);

    std::vector<Maze> mazes = gen_valid_mazes();

    std::vector<int> moves;
    while (!solves_all(moves, mazes)) {
        moves.clear();
        for (int m = 0; m < 500; m++) moves.push_back(randmove(rng));
    }

    size_t best_seen = moves.size();
    std::set<std::vector<int>> printed;
    while (true) {
        std::vector<int> new_moves(moves);
        double p = real(rng);

        if (p < grow_p && moves.size() < best_seen + 10) {
            int idx = randint(0, new_moves.size() - 1, rng);
            new_moves.insert(new_moves.begin() + idx, randmove(rng));
        } else if (p < swap_p) {
            int num_swap = std::min<int>(1 + exp_big(rng), new_moves.size()/2);
            for (int i = 0; i < num_swap; ++i) {
                int a = randint(0, new_moves.size() - 1, rng);
                int b = randint(0, new_moves.size() - 1, rng);
                std::swap(new_moves[a], new_moves[b]);
            }
        } else if (p < mutation_p) {
            int num_mut = std::min<int>(1 + exp_big(rng), new_moves.size());
            for (int i = 0; i < num_mut; ++i) {
                int idx = randint(0, new_moves.size() - 1, rng);
                new_moves[idx] = randmove(rng);
            }
        } else {
            int num_shrink = std::min<int>(1 + exp_small(rng), new_moves.size());
            for (int i = 0; i < num_shrink; ++i) {
                int idx = randint(0, new_moves.size() - 1, rng);
                new_moves.erase(new_moves.begin() + idx);
            }
        }

        if (solves_all(new_moves, mazes)) {
            moves = new_moves;

            if (moves.size() <= best_seen && !printed.count(moves)) {
                std::cout << moves.size() << " " << moves_to_str(moves) << "\n";
                if (moves.size() < best_seen) {
                    printed.clear(); best_seen = moves.size();
                }
                printed.insert(moves);
            }
        }
    }

    return 0;
}


Your Language in a Box Now with BONUS for run-time placement.

Write a program to fill a text box with the identifiers used in your program while keeping your program
small. With all the identifiers you have used (excluding those you created) in
your program, fill a 12x6 box with as many as you can. You get extra points for
identifiers that cross over (crossword style), but they can't join end to end.

Output

Your program should print (to stdout) a 12x6 character box with your packed identifiers and a # border. The
box should have columns labeled with letter A-L and the rows 1-6 (spaced like the example below). Then print a
line for each identifier used. Each line will have the location of the first
letter, the identifier itself, and the score. The score is equal to the number
of letters in the identifier with a possible '+bonus' added. The identifier gets
a 5 point bonus for each letter shared with a crossing identifier. The final
line reports 'TOTAL: ' and the sum of the identifier scores. An example output
for a possible Python program would look like this:

   ABCDEFGHIJKL
  ##############
1 #  pinsert   #
2 #  o         #
3 #  print     #
4 #    not     #
5 #            #
6 #import      #
  ##############
C1 pop 3+5
D1 insert 6
C3 print 5+10
E3 in 2+10
E4 not 3+5
A6 import 6
TOTAL: 55

Notes:

Identifiers can be unattached (like import above).
You cannot join pop and print inline with poprint.
The string in inside insert cannot be used. Joining words must be orthogonal.
Identifiers can be placed next to each other (like pop and insert above).

Your answer should include your program output with your source code and a title
consisting of the language name and your score.

Score

Your score for the challenge will the the puzzle score squared divided by the
size of your source code (in bytes). Eg: The puzzle above with a 300 byte
program would score 55*55/300 = 10.08. Highest score wins.

Rules

You can use any identifier in your program that is not defined by you.
Keywords, class names, method names, library names, and built-in function names are examples of eligible identifiers.
EDITED: You may only use standard libraries that are included with the minimum language release. Extended language packages and the use of external libraries (are now) forbidden. The huge range of libraries with extensive lists of identifiers would unbalance this challenge. If you are unsure of how this works with your language, please leave a question in the comments.
Identifiers must consist of [a-zA-Z_] characters only and have at least 2
characters.
You may only use each identifier once in the puzzle.
Identifiers can only be used left to right or downwards.

Dynamic Bonus!

If your code determines where to place identifiers at run time, the shared letter bonus will be 20 instead of 5. You may list which identifiers will used, but your code must decide where in the box to place them. Your code must also calculate and print the score list. If your placements depend on the ordering of the identifier list, hard-coded pairings, or other non-dynamic placement short-cuts, you are not eligible for the Dynamic Bonus.

In the example output above, the puzzle score for a run-time placement program would become 145. Then if the code was 800 bytes, the score would be 145*145/800 = 26.28.

The Dynamic Bonus is designed to reward clever algorithms instead of static hard-coded solution strings, and compensate for the larger resulting source code size.

EDITS:

Changed libraries used to only those in the minimum language release.
Added the dynamic bonus option.

Python, 1342 / 349 = 50.02

If I have understood the rules correctly, this should be a valid submission.

from sys import *
stdout.write("""   ABCDEFGHIJKL
  ##############
1 #from   f  i #
2 #  r   not t #
3 #      write #
4 #  s   import#
5 #  y   False #
6 #  stdout    #
  ##############
A1 from 4+5
C1 or 2+5
H1 format 6+25
K1 iter 4+10
G2 not 3+5
G3 write 5+10
C4 sys 3+5
G4 import 6+10
G5 False 5+5
C6 stdout 6+10
TOTAL 134
""".format(not False or iter([])))

You can really just keep incrementing your score by adding more identifiers: the size of the program increases linearly (by approx. twice the identifier length), while the score increases approximately by the square of the identifier length. Then the challenge becomes more how to cram most keywords into the square instead of how to write a short program to do it.


Can this value be made with unique coins and/or notes? Write a program which calculates if an inputted monetary value, as an integer, can be represented by a unique combination of coins and/or notes, that meaning the same coin/note cannot be used more than once.

Your program should take a value as input, and can take a list of coin/note values either via input or via your language's equivalent of an array. The list of coins/notes should be able to change, so make sure it's clear where this is defined if you're using a constant.

Your program should output any truthy/falsy value respectively.

Please note that outputting the list of coins/notes that make up the value is not required.

EXAMPLE

Using the UK pound, (£1.00 = 100 and £420.69 = 42069)

coins = [1, 2, 5, 10, 20, 50, 100, 200, 500, 1000, 2000, 5000]

The following will output true:

6 (1, 5)
15 (10, 5)
88 (1, 2, 5, 10, 20, 50)
512 (500, 10, 2)
7003 (5000, 2000, 2, 1)

The following will output false:

4
209
8889
4242424242
[ANYTHING ABOVE 8888]

ALTERNATIVE TEST DATA (US Dollar)

coins = [1, 5, 10, 25, 50, 100, 200, 500, 1000, 2000, 5000, 10000]

Good luck!

Brachylog 2 (TIO Nexus), 2 bytes

⊇+

Try it online!

Takes the list of coins either via standard input or via prepending it to the start of the program as an array literal (either will work, so it's up to you as to which you feel is "more legitimate"; the former is allowed by default PPCG rules, the latter specifically allowed by the question); and takes the value to produce as a command-line argument.

Explanation

This program makes use of implementation details of the way TIO Nexus's wrapper for Brachylog functions; specifically, it lets you give a command-line argument to give input via the Output. (This wasn't envisaged in the original design for Brachylog; however, languages are defined by their implementation on PPCG, and if an implementation comes along that happens to do what I need, I can therefore take advantage of it.) That means the program looks like this:

⊇+
⊇   Some subset of {standard input}
 +  sums to {the first command-line argument}

As a full program, it returns a boolean value; true. if all the assertions in the program can be simultaneously satisfied, or false. if they can't be.

(A reminder, or for people who don't already know: Brachylog 2 uses its own character encoding in which ⊇ is a single byte long.)


It's getting harder and harder to be composite these days Given a non-empty list L of integers greater than 1, we define d(L) as the smallest positive integer such that n + d(L) is composite for each n in L.
We define the sequence an as:

a0 = 2
ai+1 is the smallest integer greater than ai such that d(a0, ..., ai, ai+1) >  d(a0, ..., ai)

Your task
You may either:

Take an integer N and return the N-th term of the sequence (0-indexed or 1-indexed)
Take an integer N and return the first N terms of the sequence
Take no input and print the sequence forever

This is code-golf, so the shortest answer in bytes wins!
It's OK if your code is getting slow as N gets larger, but it should at least find the 20 first terms in less than 2 minutes.
First terms

a0 = 2 and d(2) = 2 (we need to add 2 so that 2+2 is composite)
a1 = 3 because d(2, 3) = 6 (we need to add 6 so that 2+6 and 3+6 are composite)
a2 = 5 because d(2, 3, 5) = 7 (we need to add 7 so that 2+7, 3+7 and 5+7 are all composite), whereas d(2, 3, 4) is still equal to 6
etc.

Below are the 100 first terms of the sequence (unknown on OEIS at the time of posting).
  2,   3,   5,   6,  10,  15,  17,  19,  22,  24,
 30,  34,  35,  39,  41,  47,  51,  54,  56,  57,
 70,  79,  80,  82,  92,  98, 100, 103, 106, 111,
113, 116, 135, 151, 158, 162, 165, 179, 183, 186,
191, 192, 200, 210, 217, 223, 226, 228, 235, 240,
243, 260, 266, 274, 277, 284, 285, 289, 298, 307,
309, 317, 318, 329, 341, 349, 356, 361, 374, 377,
378, 382, 386, 394, 397, 405, 409, 414, 417, 425,
443, 454, 473, 492, 494, 502, 512, 514, 519, 527,
528, 560, 572, 577, 579, 598, 605, 621, 632, 642

Pyth, 24 bytes

Pu+GfP_+Tf!fP_+ZYG)eGQ]2

Demonstration

Basically, we start with [2], then add elements 1 at a time by alternately finding d, then adding an element, and so forth. Outputs the first n elements of the sequence.

Contains a filter inside a first integer filter inside a first integer filter inside an apply repeatedly loop.

Explanation:

Pu+GfP_+Tf!fP_+ZYG)eGQ]2
 u                   Q]2    Starting with `[2]`, do the following as many times
                            as the input
         f        )         Starting from 1 and counting upward, find d where
          !f     G          None of the elements in the current list
            P_+ZY           plus d give a prime.
    f              eG       Starting from the end of the current list and counting
                            upward, find the first number which
     P_+T                   plus d gives a prime.
  +G                        Append the new number to the current list
P                           Trim the last element of the list

There's obvious repeated effort between the two "Add and check if prime" calls, but I'm not sure how to eliminate it.


Do you want to code a snowman? Here is a simple ASCII art snowman:

_===_
(.,.)
( : )
( : )

Let's make him some friends. This will be the general pattern for our ASCII art snowpeople:

 HHHHH
 HHHHH
X(LNR)Y
X(TTT)Y
 (BBB)

The leading spaces and the parentheses are always the same for all snowpeople. The different letters represent sections of the pattern that can individually change. Each section has exactly four presets for what ASCII characters can fill it.
By mixing and matching these presets for all eight sections, we can make a variety of snowpeople.

All Presets

(Notice that spaces are put on otherwise empty lines so the section shape is always correct.)

H is for Hat

Straw Hat

_===_
Mexican Hat

 ___
.....

Fez

  _
 /_\

Russian Hat

 ___
(_*_)

N is for Nose/Mouth

Normal ,
Dot .
Line _
None

L is for Left Eye

Dot .
Bigger Dot o
Biggest Dot O
Closed -

R is for Right Eye

(Same list as left eye.)

X is for Left Arm

Normal Arm

<
Upwards Arm

\

Downwards Arm

/
None

Y is for Right Arm

Normal Arm

>
Upwards Arm

/

Downwards Arm

\
None

T is for Torso

Buttons  :
Vest ] [
Inward Arms > <
None

B is for Base

Buttons  :
Feet " "
Flat ___
None

Challenge

Write a program that takes in an eight character string (via stdin or command line) in the format HNLRXYTB, where each letter is a digit from 1 to 4 that denotes which preset to use for the corresponding section of the snowperson. Print the full snowperson to stdout.

For example, the input 11114411 is the snowman at the top of the page. (First 1: he has a straw hat, second 1: he has a normal nose, etc.)

Another example, the snowperson for input 33232124:

   _
  /_\
\(o_O)
 (] [)>
 (   )

Details

Any amounts and combinations of leading/trailing spaces and leading/trailing newlines are allowed as long as...

the snowperson has all their sections arranged correctly with respect to one another, and
there are never more than 64 total whitespace characters (the general pattern is only 7×5, so you probably won't hit this limit).

You don't need to print rows/columns of the pattern if they only contain whitespace. e.g. the empty line of the straw hat is not required.
You must use the ordering of the parts as they are given above.
Instead of a program, you may write a function that takes the digit string as an argument. The output should be printed normally or returned as a string.
You may treat the input as an integer instead of a string if preferred.

Scoring

The shortest code in bytes wins.

Bonus question: Which of the 65536 distinct snowpeople is your favorite?

JavaScript ES6, 210 208 202 bytes

s=>` 0
8(213)9
4(6)5
 (7)`.replace(/\d/g,p=>`_===_1 ___
 .....1  _
  /_\\1 ___
 (_*_)1,1.1_11.1o101-1.1o101-1<11/11>11\\11 : 1] [1> <1   1 : 1" "1___1   11\\11 11/11 `.split(1)[s[p>7?p-4:p]-1+p*4]||' ')

This is an anonymous function; you use it by executing ([function code])('42232124'). The most aggravating part of this was the arms, which take up 2 lines, so I had to include code for both top and bottom.

The Stack Snippet below has ungolfed, un-ES6-ified, commented code. And you can use it to easily test the code and try out different combinations. Edit: I'm having way too much fun with this. I've added several new features, including a way to generate a random snowman.

Thanks to Yair Rand for saving six bytes.

var f=function(s){
  return' 0\n8(213)9\n4(6)5\n (7)' // Start with a placeholder string with all the static components
    .replace(/\d/g,function(p){ // Go through each placeholder number to replace it with its value
    // The massive string below holds all the possible body parts, separated by 1 for easy splitting.
    // The two at the end are for the top of the arms
    return'_===_1 ___\n .....1  _\n  /_\\1 ___\n (_*_)1,1.1_11.1o101-1.1o101\
-1<11/11>11\\11 : 1] [1> <1   1 : 1" "1___1   11\\11 11/11 '.split(1)
    [s[p>7?p-4:p]-1 // Get the value from the input string. If the current body part
                    // is the top of the two-line arms (8 or 9), drop it down to 4 or 5
                    // Subtract 1 to account for the 0-indexed array.
     +p*4] // multiply by 4 to skip to the relevant code
     ||' ' // To save bytes in the above string, spaces are empty strings, so replace them here
  })
}

// Code for the interactive version follows
// http://codepen.io/hsl/pen/bdEgej
function updateRadios(){$('input[type="radio"]').each(function(){if($(this).is(":checked")){var t=$(this).data("p"),i=$(this).data("v");input[t]=i}}),inputS=input.join(""),update()}var input=[],inputS=$("#code").val(),update=function(){$("#p").text(f(inputS)),$("#code").val(inputS)};$('input[type="radio"]').change(updateRadios),$("#code").keyup(function(){inputS=$(this).val(),update()}),updateRadios(),$("#random").click(function(){for(var t=0;8>t;t++)$("div:eq("+t+") input:eq("+Math.floor(4*Math.random())+")").prop("checked",!0);updateRadios()});
body{font-family:sans-serif}h2{font-size:18px;font-weight:400}label{display:block}div{display:inline-block;margin:0 10px}#code{width:70px}

Hat
<input type="radio" name="p1" data-p="1" data-v="1"> Straw hat<input type="radio" name="p1" data-p="1" data-v="2"> Mexican hat<input type="radio" name="p1" data-p="1" data-v="3"> Fez<input type="radio" name="p1" data-p="1" data-v="4" checked> Russian hat

Nose/mouth
<input type="radio" name="p2" data-p="2" data-v="1"> Normal<input type="radio" name="p2" data-p="2" data-v="2" checked> Dot<input type="radio" name="p2" data-p="2" data-v="3"> Line<input type="radio" name="p2" data-p="2" data-v="4"> None

Left eye
<input type="radio" name="p3" data-p="3" data-v="1"> Dot<input type="radio" name="p3" data-p="3" data-v="2" checked> Bigger dot<input type="radio" name="p3" data-p="3" data-v="3"> Biggest dot<input type="radio" name="p3" data-p="3" data-v="4"> Closed

Right eye
<input type="radio" name="p4" data-p="4" data-v="1"> Dot<input type="radio" name="p4" data-p="4" data-v="2"> Bigger dot<input type="radio" name="p4" data-p="4" data-v="3" checked> Biggest dot<input type="radio" name="p4" data-p="4" data-v="4"> Closed

Left arm
<input type="radio" name="p5" data-p="5" data-v="1"> Normal<input type="radio" name="p5" data-p="5" data-v="2" checked> Upwards<input type="radio" name="p5" data-p="5" data-v="3"> Downwards<input type="radio" name="p5" data-p="5" data-v="4"> None

Right arm
<input type="radio" name="p6" data-p="6" data-v="1" checked> Normal<input type="radio" name="p6" data-p="6" data-v="2"> Upwards<input type="radio" name="p6" data-p="6" data-v="3"> Downwards<input type="radio" name="p6" data-p="6" data-v="4"> None

Torso
<input type="radio" name="p7" data-p="7" data-v="1"> Buttons<input type="radio" name="p7" data-p="7" data-v="2" checked> Vest<input type="radio" name="p7" data-p="7" data-v="3"> Inward arms<input type="radio" name="p7" data-p="7" data-v="4"> None

Base
<input type="radio" name="p8" data-p="8" data-v="1"> Buttons<input type="radio" name="p8" data-p="8" data-v="2"> Feet<input type="radio" name="p8" data-p="8" data-v="3"> Flat<input type="radio" name="p8" data-p="8" data-v="4" checked> None

<button id="random">Randomize</button>

<input type="text" id="code">


Create a diagonal sudoku board A Diagonal Sudoku board is a special case of Latin squares. It has the following properties:

The board is a 9-by-9 matrix
Each row contains the numbers 1-9
Each column contains the numbers 1-9
Each 3-by-3 sub-region contains the numbers 1-9
Both diagonals contains the numbers 1-9

Challenge:

Create a program or function that outputs a complete board with all 81 numbers that complies with the rules above.

The number in at least one position must be random, meaning the result should vary accross executions of the code. The distribution is optional, but it must be possible to obtain at least 9 structurally different boards. A board obtained from another by transliteration is not considered structurally different. Transliteration refers to substituting each number x by some other number y, consistently in all positions of number x.

Hardcoding 9 boards is not accepted either.

Rules:

Output format is optional, as long as it's easy to understand (list of list is OK)
The random number can be taken as input instead of being created in the script, but only if your language doesn't have a RNG.

This is code golf so the shortest code in bytes win!

Example boards:

7   2   5  |  8   9   3  |  4   6   1
8   4   1  |  6   5   7  |  3   9   2
3   9   6  |  1   4   2  |  7   5   8
-------------------------------------
4   7   3  |  5   1   6  |  8   2   9
1   6   8  |  4   2   9  |  5   3   7
9   5   2  |  3   7   8  |  1   4   6
-------------------------------------
2   3   4  |  7   6   1  |  9   8   5
6   8   7  |  9   3   5  |  2   1   4
5   1   9  |  2   8   4  |  6   7   3

4   7   8  |  1   9   5  |  3   2   6
5   2   6  |  4   8   3  |  7   1   9
9   3   1  |  6   7   2  |  4   5   8
-------------------------------------
2   5   9  |  8   6   7  |  1   3   4
3   6   4  |  2   5   1  |  9   8   7
1   8   7  |  3   4   9  |  5   6   2
-------------------------------------
7   1   2  |  9   3   8  |  6   4   5
6   9   3  |  5   2   4  |  8   7   1
8   4   5  |  7   1   6  |  2   9   3

APL (Dyalog Unicode), 56 bytes

(,⊖⍣(?2)↑a(3+⍳3)(10-⌽a←3?3)){⍺ ⍺⌷9 9⍴∊⌽⍵∘.⌽⍵⊖¨⊂3 3⍴⍳9}⍳3

Try it online!

A full program that randomly gives a 9-by-9 matrix of digits.

By OP mentioning "it must be possible to obtain at least 9 structurally different boards", I believe it was to prevent using just trivial transformations like reflection and rotation. But there are more possible transformations than that. I use two kinds of transformations:

Permute R19C19, R28C28 and R37C37 (6 cases)

Example: Swap R19C19 and R28C28

a b c - - - A B C     e d f - - - D F E
d e f - - - D E F     b a c - - - A C B
g h j - - - G H J     h g j - - - G J H
- - - - - - - - -     - - - - - - - - -
- - - - - - - - - ==> - - - - - - - - -
- - - - - - - - -     - - - - - - - - -
k l m - - - K L M     l k m - - - K M L
n p q - - - N P Q     s r t - - - R T S
r s t - - - R S T     p n q - - - N Q P

Reverse the order of boxes in both dimensions (2 cases: reverse both or keep intact)

a b c - - - A B C     K L M - - - k l m
d e f - - - D E F     N P Q - - - n p q
g h j - - - G H J     R S T - - - r s t
- - - - - - - - -     - - - - - - - - -
- - - - - - - - - ==> - - - - - - - - -
- - - - - - - - -     - - - - - - - - -
k l m - - - K L M     A B C - - - a b c
n p q - - - N P Q     D E F - - - d e f
r s t - - - R S T     G H J - - - g h j

resulting in 12 structurally different boards. Note that, in both cases, the thing that changes on the diagonals is the order of the digits. Also, the center box is always intact, so no two boards are equivalent under transliteration.

Part 1: Construct a valid diagonal sudoku board

⍝ A 3x3 box of 1..9
⊂3 3⍴⍳9
┌─────┐
│1 2 3│
│4 5 6│
│7 8 9│
└─────┘

⍝ The box rotated upwards 1, 2, 3 times
(⍳3)⊖¨⊂3 3⍴⍳9
┌─────┬─────┬─────┐
│4 5 6│7 8 9│1 2 3│
│7 8 9│1 2 3│4 5 6│
│1 2 3│4 5 6│7 8 9│
└─────┴─────┴─────┘

⍝ The boxes rotated left 1, 2, 3 times
(⍳3)∘.⌽(⍳3)⊖¨⊂3 3⍴⍳9
┌─────┬─────┬─────┐
│5 6 4│8 9 7│2 3 1│
│8 9 7│2 3 1│5 6 4│
│2 3 1│5 6 4│8 9 7│
├─────┼─────┼─────┤
│6 4 5│9 7 8│3 1 2│
│9 7 8│3 1 2│6 4 5│
│3 1 2│6 4 5│9 7 8│
├─────┼─────┼─────┤
│4 5 6│7 8 9│1 2 3│
│7 8 9│1 2 3│4 5 6│
│1 2 3│4 5 6│7 8 9│
└─────┴─────┴─────┘

⍝ Horizontally reverse the boxes, keeping the contents inside the boxes
⌽(⍳3)∘.⌽(⍳3)⊖¨⊂3 3⍴⍳9
┌─────┬─────┬─────┐
│2 3 1│8 9 7│5 6 4│
│5 6 4│2 3 1│8 9 7│
│8 9 7│5 6 4│2 3 1│
├─────┼─────┼─────┤
│3 1 2│9 7 8│6 4 5│
│6 4 5│3 1 2│9 7 8│
│9 7 8│6 4 5│3 1 2│
├─────┼─────┼─────┤
│1 2 3│7 8 9│4 5 6│
│4 5 6│1 2 3│7 8 9│
│7 8 9│4 5 6│1 2 3│
└─────┴─────┴─────┘

⍝ Enlist the digits and reshape into 9x9 matrix
⍝ (Each box goes to each row)
9 9⍴∊⌽(⍳3)∘.⌽(⍳3)⊖¨⊂3 3⍴⍳9
2 3 1 5 6 4 8 9 7
8 9 7 2 3 1 5 6 4
5 6 4 8 9 7 2 3 1
3 1 2 6 4 5 9 7 8
9 7 8 3 1 2 6 4 5
6 4 5 9 7 8 3 1 2
1 2 3 4 5 6 7 8 9
7 8 9 1 2 3 4 5 6
4 5 6 7 8 9 1 2 3

Part 2: Generate permutation vector

,⊖⍣(?2)↑a(3+⍳3)(10-⌽a←3?3)
                    a←3?3   ⍝ Generate a permutation of 1 2 3
                            ⍝ ex) 2 3 1
        a(3+⍳3)(10-⌽a    )  ⍝ Permutation vector in chunks of 3
                            ⍝ ex) (2 3 1)(4 5 6)(9 7 8)
       ↑                    ⍝ Promote to matrix
 ⊖⍣(?2)                     ⍝ Reverse vertically 1 or 2 times
                            ⍝ ex) [9 7 8][4 5 6][2 3 1]
,                           ⍝ Flatten ex) 9 7 8 4 5 6 2 3 1

Part 3: Permute the rows and columns

⍝ Permute both rows and columns of the matrix through indexing function
perm perm⌷mat
⍝ Using the example permutation above, the sudoku board is:
3 1 2 7 8 9 5 6 4
9 7 8 4 5 6 2 3 1
6 4 5 1 2 3 8 9 7
8 9 7 6 4 5 1 2 3
5 6 4 3 1 2 7 8 9
2 3 1 9 7 8 4 5 6
4 5 6 2 3 1 9 7 8
1 2 3 8 9 7 6 4 5
7 8 9 5 6 4 3 1 2


The 9 Billion Names of God The 9 Billion Names of God is a short story by Arthur C. Clarke. It's about a group of Tibetan monks whose order is devoted to writing down all the possible names of God, written in their own alphabet. Essentially, they are devoted to writing every possible permutation of their alphabet, restricted by a few rules. In the story, the monastery hires some engineers to write a program to do all the work for them. Your goal is to write that program.

Rules:

The monk's alphabet uses 13 characters (according to my estimations). You may use ABCDEFGHIJKLM or some other set of 13 characters.
The minimum length of a possible name is 1 character. The maximum length is 9 characters.
No character may repeat more than 3 times in succession. AAABA is a valid name, but AAAAB is not.
Your program should print out (to a file) every possible name in sequence from A to MMMLMMMLM, separated by any character not in the alphabet (newlines, semi-colons, whatever).
This is code-golf, and you can use any language. The shortest solution by June 1st 2014 wins.

Edit: The names should start with A and end with MMMLMMMLM, progressing through all the billions of names sequentially. But the particular sequence is up to you. You can print out all the 1-letter names first, then all the 2-letter names, etc. Or you can print all the names starting with A, then all the ones starting with B, or some other pattern. But a human should be able to read through the file and confirm they are all there and in whatever logical order you choose, assuming they have the time.

Ruby, 46

?A.upto(?M*9){|s|s[/(.)\1{3}|[N-Z]/]||puts(s)}

My original, similar solution was longer and wrong (it output base13 numbers, which isn't quite all of them due to leading zeroes), but I'll leave it here because it got votes anyway.

1.upto(13**9){|i|(s=i.to_s 13)[/(.)\1{3}/]||puts(s)}


Build a 12-hour digital clock In my essay "Use the 24-hour clock", I claim that trying to represent the 12-hour clock directly in data is a terrible exercise in patchy, inelegant programming:

  "No problem, we'll just use computers to do these calculations for us." Yes, but computers need to be programmed. And trying to account for AM and PM directly in a computer program, especially the extremely tricky way we've encoded it, with 12 representing 0, is prone to bugs and programming mistakes, which can cost millions at the airport in scheduling mishaps. As it is, it's much easier for computers to work in 24-hour time in internal calculations, and then convert the times to 12-hour time for easy human reading, instead of having to deal with dozens of notational issues as would be the case when using 12-hour time directly. In which case, why not just get rid of the whole 12-hour conversion and work with 24-hour time in the first place?

Here's your chance to prove me wrong. Your task is to build a Clock class that supports the following functions:

addHours(x), that advances the clock by x hours (or moves back |x| hours if x is negative)
addMinutes(x), that advances the clock by x minutes.
diffMinutes(c1, c2) that gives the time difference from clock c1 to clock c2 in minutes (which always assumes that c1 and c2 are representing times in the same day). If c2 is earlier than c1, the time should be negative.

and has the following publicly accessible variables:

hours, which represents the hour digit of the clock, from 1 to 12.
minutes, which represents the minute digit of the clock, from 0 to 59.
ampm, which is true if the clock is AM and false if the clock is PM.

as well as a setter and getter method (e.g. setHours(hours) and getHours()) for each. (You may assume that the setters and getters will always be passed valid values.) The reason the variables must be publicly accessible is to ensure that the internal data representation of the clock is also in a 12-hour format, to fit the data representation of the clock described in the essay.

Your code must pass all the unit tests contained in this file (translated to the programming language of your choice) except for test 0.2, which should be removed for this problem. (If the descriptions of the corner cases and their resultant times start to make your head spin, that's good. It means that my point about the strangeness of the notation is verified. It certainly made my head spin trying to make sure I had all the corner cases covered.)

Your score is calculated based on the number of operators and function calls in your class code, rather than the number of characters (so don't golf your code, make it readable but still short). Lowest score wins, of course.

Note: This problem has a part 2, namely, to create a 12-hour clock that uses 24-hour time in its internal representation. If my hypothesis is true, the winner of that problem will have a much lower score than the winner of this problem.

Python (38)

Full code with tests here. A ton of the tests were wrong, so I modified them. Most of the changes are marked with the string "patch" in a comment, but I'm sure I forgot to mark some.

It was completely unclear if diffMinutes(a, b) was abs(a-b), a-b or b-a, so I went with b-a because I had to change less tests that way.

Also, ampm is a terrible variable name. isAM would be a far more readable name, and isPM would be preferable, as true and false are often associated with 1 and 0, and PM is a higher/later value.

The interesting part (getters and setters in the link above):

def getMinutesFromMidnight(clock):
    return clock.hours * 60 % 720 + 720 * (not clock.ampm) + clock.minutes

def diffMinutes(a,b):
    return getMinutesFromMidnight(b) - getMinutesFromMidnight(a)

class Clock(object):
    def __init__(self):
        self.hours = 12
        self.minutes = 0
        self.ampm = True

    def addHours(self, hours):
        self.addMinutes(hours * 60)

    def addMinutes(self, minutes):
        minutes = getMinutesFromMidnight(self) + minutes
        self.hours = minutes / 60 % 12 or 12
        self.minutes = minutes % 60
        self.ampm = minutes % 1440 < 720


Solve the eight queens problem at compile-time Can you solve the eight queens puzzle at compile-time?

Pick any suitable output format.

I'm particularly interested in a C++ template metaprogramming solution, but you can use languages that have similar constructs, like, for example, Haskell's type system.

Ideally your metaprogram would output all solutions. No hardcoding.

My meta-program finds all 92 solutions. They are printed as error messages:

error: ‘solution’ is not a member of ‘std::integral_constant<int, 15863724>’

This means the first queen should be placed at y=1, the second at y=5, the third at y=8 and so on.

The meta-program consists of two mutually recursive meta-functions put_queen and put_queens:

#include <type_traits>

template<int queens, int rows, int sums, int difs, int x, int y>
struct put_queen;

template<int queens, int rows, int sums, int difs, int x>
struct put_queens : std::integral_constant<int,
    // try all 8 possible values for y
       put_queen<queens, rows, sums, difs, x, 1>::value
     | put_queen<queens, rows, sums, difs, x, 2>::value
     | put_queen<queens, rows, sums, difs, x, 3>::value
     | put_queen<queens, rows, sums, difs, x, 4>::value
     | put_queen<queens, rows, sums, difs, x, 5>::value
     | put_queen<queens, rows, sums, difs, x, 6>::value
     | put_queen<queens, rows, sums, difs, x, 7>::value
     | put_queen<queens, rows, sums, difs, x, 8>::value
> {};

template<int queens, int rows, int sums, int difs, int x, int y>
struct put_queen : std::conditional<
    // if blocked
    rows & (1 << y)
 || sums & (1 << (x + y))
 || difs & (1 << (x - y + 8)),
    // then backtrack
    std::integral_constant<int, 0>,
    // else recurse
    put_queens<queens * 10 + y,
               rows | (1 << y),
               sums | (1 << (x + y)),
               difs | (1 << (x - y + 8)),
               x + 1
    >
>::type {};

The variable queens stores the y coordinates of the queens placed on the board so far.
The following three variables store the rows and diagonals that are already occupied by queens.
x and y should be self-explanatory.

The first argument to conditional checks whether the current position is blocked.
If it is, we backtrack by returning the (meaningless) result 0.
Otherwise, the queen is placed on the board, and the recursion continues with the next column.

When x reaches 8, we have found a solution:

template<int queens, int rows, int sums, int difs>
struct put_queens<queens, rows, sums, difs, 8> {
    // print solution as error message by accessing non-existent member
    enum { value = std::integral_constant<int, queens>::solution };
};

Since integral_constant has no member solution, the compiler prints queens as an error message.

To start the recursion, we inspect the value member of the empty board:

int go = put_queens<0, 0, 0, 0, 0>::value;

The complete program can be found at ideone.


Find whether a number is happy or not? A happy number is defined by the following process. Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers, while those that do not end in 1 are unhappy numbers (or sad numbers). Given a number print whether it is happy or unhappy.

Sample Inputs
7
4
13

Sample Outputs
Happy
Unhappy
Happy

Note: Your program should not take more than 10 secs for any number below 1,000,000,000.

Ruby, 77 characters

a=gets.to_i;a=eval"#{a}".gsub /./,'+\&**2'until a<5
puts a<2?:Happy: :Unhappy


Create a Scalable Valentine's Day Heart Happy Valentine's Day! To celebrate this day of love and happiness (or sadness and loneliness for those of us who are single...), let's write some code to create some hearts!

Specifically, if you take this challenge upon you, you are to write code to output a heart/hearts as an image file, with the ability to easily change the dimensions of the image (both width and height, separately). You could take input into your program to get the dimensions, or two simple variables that can be changed would be enough (or a couple constants). If you do opt for the variables, no more than two tokens of the program should be changed to adjust the size.

So for instance, you could write a program to output this image (with variable width and height, of course):

However, that heart isn't that interesting. It's just a plain heart. I challenge you to create the most creative and interesting heart that you can!

Bash: 16 characters
echo -e "\u2665"

output (when unicode supported)
♥

Ah wait, it must be an image?
ImageMagick: 137 characters
w=99
h=199
convert -size ${w}x$w -gravity center -font WebDings -fill red label:Y h.gif
convert h.gif -resize ${w}x$h\! h2.gif

output (when WebDings font installed)


Shifty Eyes Shifting I's Shifty-eyes ASCII guys like to shift ASCII Ii's:
>_> <_< >_< <_>

Given a string of shifty-guys, spaced apart or separate lines, shift the Ii's side to side, left the wall and right the skies:
Ii

The shortest shifter wins the prize.
Say What?
Write a program or function that takes in a string of an arbitrary list of these four ASCII emoticons, either space or newline separated (with an optional trailing newline):
>_>
<_<
>_<
<_>

For example, the input might be
>_> >_> <_>

or
>_>
>_>
<_>

(The method you support is up to you.)

Each emoticon performs a different action on the I and i characters, which always start like this:
Ii

>_> shifts I to the right by one, if possible, and then shifts i to the right by one.
<_< shifts I to the left by one, if possible, and then shifts i to the left by one, if possible.
>_< shifts I to the right by one, if possible, and then shifts i to the left by one, if possible.
<_> shifts I to the left by one, if possible, and then shifts i to the right by one.

I cannot be shifted left if it is at the left edge of the line (as it is initially), and cannot be shifted right if i is directly to its right (as it is initially).
i cannot be shifted left if I is directly to its left (as it is initially), but can always be shifted right.
Note that with these rules, I will always remain to the left of i, and I is attempted to be shifted before i for all emoticons.
Your program or function needs to print or return a string of the final Ii line after applying all the shifts in the order given, using spaces ( ) or periods (.) for empty space. Trailing spaces or periods and a single trailing newline are optionally allowed in the output. Don't mix spaces and periods.

For example, the input
>_>
>_>
<_>

has output
I...i

because the shifts apply like
start  |Ii
>_>    |I.i
>_>    |.I.i
<_>    |I...i

The shortest code in bytes wins. Tiebreaker is higher voted answer.
Test Cases
#[id number]
[space separated input]
[output]

Using . for clarity.
#0
[empty string]
Ii

#1
>_>
I.i

#2
<_<
Ii

#3
>_<
Ii

#4
<_>
I.i

#5
>_> >_>
.I.i

#6
>_> <_<
Ii

#7
>_> >_<
.Ii

#8
>_> <_>
I..i

#9
<_< >_>
I.i

#10
<_< <_<
Ii

#11
<_< >_<
Ii

#12
<_< <_>
I.i

#13
>_< >_>
I.i

#14
>_< <_<
Ii

#15
>_< >_<
Ii

#16
>_< <_>
I.i

#17
<_> >_>
.I.i

#18
<_> <_<
Ii

#19
<_> >_<
.Ii

#20
<_> <_>
I..i

#21
>_> >_> <_>
I...i

#22
<_> >_> >_> >_> <_> <_<
.I...i

#23
<_> >_> >_> >_> <_> <_< >_< <_< >_<
..Ii

#24
>_> >_< >_> >_> >_> >_> >_> >_> <_> <_> <_<
...I.....i

Perl, 59 56 54 bytes

Includes +1 for -p

Run with the input on STDIN, e.g. perl -p shifty.pl <<< ">_> <_< >_< <_>"

shifty.pl:

s%^|<|(>)%y/iI/Ii/or$_=Ii;$1?s/i |i$/ i/:s/ i/i /%reg

Explanation

The control string alternates instructions for i and I and the rule is the same for both of them if you formulate them as:

< Move left if there is a space to the left
> Move right if there is a space or end of string to the right

So I'm going to swap i and I in the target string at each step so I only need to apply the rule to one letter ever. This is the y/iI/Ii/

I will walk the control string looking for < and > using a substitution which is usually the shortest way in perl to process something character by character. To avoid having to write $var =~ I want the control string in the perl default variable $_. And I also want an easy way to distinguish < from >. All this can be accomplished using

s%<|(>)%  code using $1 to distinguish < from > %eg

The target string I also want to manipulate using substitutions and for the same reason I want that in $_ too. $_ being two things at once seems impossible.

However I can have my cake and eat it too because the $_ inside the body of a substitution does not have to remain the same as the $_ being substituded. Once perl started substituting a string this string will not change even if you change the variable the string originally came from. So you can do something like:

s%<|(>)% change $_ here without disturbing the running substitution %eg

I want to replace the original $_ by the initial "Ii" only the very first time the substitution body gets executed (otherwise I keep resetting the target string). This replacement however also has to happen for an empty control string, so even for the empty control string the body needs to be executed at least once. To make sure the substition runs an extra time at the start of the control string (even for empty control strings) I change the substitution to:

s%^|<|(>)% change $_ here without disturbing the running substitution %eg

I will run the y/iI/Ii/ as the first thing inside the substitution code. While $_ is still the control string this won't yet contain any Ii, so if the transliteration indicates nothing was changed that is my trigger initialize $_:

y/iI/Ii/or$_=Ii

Now I can implement the actual moving of the letters. Since I start with a swap all moves should be done on i, not I. If $1 is set move i to the right:

s/i |i$/ i/

If $1 is not set move i to the left

s/ i/i /

Notice that at the start of the control string when I match ^ $1 will not be set, so it tries to move i to the left on the initial string Ii. This won't work because there is no space there, so the intial string remains undisturbed (this is why I put the () around > instead of <)

Only one problem remains: at the end of the outer substitution $_ is set to result of the outer substitution regardless of what you did to $_ inside the substitution body. So the target string with the proper placement of i and I gets lost. In older perls this would be a fatal flaw. More recent perls however have the r modifier which means "make a copy of the original string, do your substitution on that and return the resulting string (instead of number of matches)". When I use that here the result is that the modified command string gets discarded while the original $_ is not disturbed by perl and left after the substitution. However the disturbing I do on $_ is still done after perl left $_ alone. So at the end $_ will be the proper target string.

The -p option makes sure the original string is in $_ and also prints the final $_.


Given r and n, find first n numbers of x where moving first digit of x to last gives x/r = y Objective

Given input r and n find the first n natural numbers x such that if we rotate the first digit to the last place we obtain x/r.

You may assume that 2 <= r <= 9 and 1 <= n <= 65535.

You may write a program which takes input from stdin or command-line arguments; or you may write a function which takes r and n as parameters. Output, however, should be to stdout. Output should be one line per value of x, formatted as x/r=y, in order of increasing x.

Your solution must be able to handle all valid cases within one minute on a reasonable desktop computer.

Test cases

Input: 4 5
Output:

102564/4=25641
205128/4=51282
307692/4=76923
410256/4=102564
512820/4=128205

Input: 5 1
Output: 714285/5=142857

This is code-golf, so least bytes win. Winning answer will be accepted 4 weeks from now (2014-09-19).

Credits for this question go to my colleague, who allowed me to post this question here :)

Haskell, 182 179

Second version, probably further golfable, but with "proper" algorithm this time.  In particular, it finishes within a few minutes with r=4 and n=65535, but then again my computer is neither reasonable nor a desktop, so chances are this stays within a minute on other machines.

n#r=take n$[s(10^k*a+d)++'/':s r++'=':s d++s a|k<-[0..],a<-[1..9],let(d,m)=divMod(a*(10^k-r))(10*r-1),m<1]
s=show
main=interact$unlines.(\(r:n:_)->n#fromIntegral r).map read.words

It is based on the idea that x=10^k*a + m, where its first digit 0≤a≤9 is moved to the end to obtain y=10*m+a.  A little maths reveals that m can be obtained as a*(10^k-r)/(10*r-1), so we simply scan a over [1..9] for every k from 0 to infinity, and keep and print the first n results for which the above expression for m is integral.

The fromIntegral is required because reading a list with n as one of its elements in main, in combination with the use of n in take, would force r to Int throughout, which results in nasty overflows with the big numbers in question.  I could have used genericTake, but that requires an import.

This code also has the benefit of being almost trivial to expand to bases other than 10.

Input is read from stdin, the two values can be separated by any whitespace.


Mutilating the Query I know you've always thought about the trials and tribulations of experiencing the joys of life as a web proxy. Honestly, who hasn't? Today you're tasked with realizing this goal (at least a part of it). Website X gets a lot of traffic on the daily and is looking for a PaaS (clearly this refers to Proxy as a Service) because of the large number of users who insist on passing sensitive information via query parameters (users are silly). Your task is to remove any and all sensitive query parameters from the request before forwarding the request through to its original destination.

Input

A well-formed absolute HTTP URL that follows the URI grammar in RFC3986 Section 3.

You can assume there is no fragment
Brief format example where anything in square brackets denotes optional: http[s]://[user:pass@]host.name.com[:port]/[?param1=value1&param2=value2...]

A list of query parameters to be removed.

Output

The modified HTTP URL without the parameters defined in the input list.

Examples

http://example.com/ [foo]
> http://example.com/

http://example.com/?foo=bar []
> http://example.com/?foo=bar

http://example.com/ []
> http://example.com/

http://example.com/?foo=1&bar=2&baz=3 [foo,baz]
> http://example.com/?bar=2

http://example.com/?foo=1&bar=2&baz=3 [foo,bar,baz]
> http://example.com/

http://example.com/?foo&bar=2&baz= [foo,baz]
> http://example.com/?bar=2

http://example.com/?abc=1&def=2&baz=foo [foo,bar]
> http://example.com/?abc=1&def=2&baz=foo

http://example.com/?foobar=baz [foo]
> http://example.com/?foobar=baz

http://foo:foo@foo.com:8080/?foo=1&bar=foo [foo]
> http://foo:foo@foo.com:8080/?bar=foo

Scoring

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

GNU sed 98 96 88 80 77 74 69 59 54 (48 + 1 for -r) 49

:;s,(.+)(=[^&]*[& ]|&)(.*)\1,\3 ,
t;s,[?&]? .*,,

The list of parameters to remove are separated by spaces.

$ echo 'http://example.com/?foo=1&bar=2&baz=3 foo bar baz' | sed -rf sed.txt
http://example.com/

$ echo 'http://example.com/?foo&bar=2&baz= foo baz' | sed -rf sed.txt
http://example.com/?bar=2

$ echo 'http://example.com/' | sed -rf sed.txt
http://example.com/


Simple State Sales Tax Calculator Sales taxes in the United States are complicated, to say the least. Generally, there's a state sales tax (there are a handful of states that do not collect a state sales tax), but there could also be a county sales tax, a school district sales tax, a municipal (city) sales tax, or a metropolitan area sales tax. There could even be different sales taxes in different parts of a city. For the purposes of this challenge, however, we're going to focus on just the state sales tax.

Given a U.S. dollar amount greater than zero (accurate to two decimal places) and a state (either the full name or the two-letter abbreviation, your choice, case doesn't matter), and using the below chart of sales tax percentages, output the corresponding state sales tax required to be collected for that particular sale, accurate and truncated to two decimal places. Please specify how your code handles rounding.

Edit: The abbreviation for Washington was listed incorrectly as WS instead of WA. Answers may use either abbreviation, since that was my goof.

State          Abbr   %
Alabama         AL  4.00%
Alaska          AK  0.00%
Arizona         AZ  5.60%
Arkansas        AR  6.50%
California      CA  6.00%
Colorado        CO  2.90%
Connecticut     CT  6.35%
Delaware        DE  0.00%
Florida         FL  6.00%
Georgia         GA  4.00%
Hawaii          HI  4.00%
Idaho           ID  6.00%
Illinois        IL  6.25%
Indiana         IN  7.00%
Iowa            IA  6.00%
Kansas          KS  6.50%
Kentucky        KY  6.00%
Louisiana       LA  5.00%
Maine           ME  5.50%
Maryland        MD  6.00%
Massachusetts   MA  6.25%
Michigan        MI  6.00%
Minnesota       MN  6.875%
Mississippi     MS  7.00%
Missouri        MO  4.23%
Montana         MT  0.00%
Nebraska        NE  5.50%
Nevada          NV  4.60%
New Hampshire   NH  0.00%
New Jersey      NJ  6.88%
New Mexico      NM  5.13%
New York        NY  4.00%
North Carolina  NC  4.75%
North Dakota    ND  5.00%
Ohio            OH  5.75%
Oklahoma        OK  4.50%
Oregon          OR  0.00%
Pennsylvania    PA  6.00%
Rhode Island    RI  7.00%
South Carolina  SC  6.00%
South Dakota    SD  4.50%
Tennessee       TN  7.00%
Texas           TX  6.25%
Utah            UT  4.70%
Vermont         VT  6.00%
Virginia        VA  4.30%
Washington      WA  6.50%
West Virginia   WV  6.00%
Wisconsin       WI  5.00%
Wyoming         WY  4.00%

Example for California at 6% state sales tax --

CA
1025.00

61.50

Example for Minnesota at 6.875% --

MN
123.45

8.49

Mathematica, 112 103 77 76 66 bytes
Mathematica has a builtin for everything
NumberForm[Interpreter["USState"][#]@"StateSalesTaxRate"#2,{9,2}]&

Takes a state name (any format; abbreviation or full name) and the dollar amount.
Try it on Wolfram Sandbox
Usage
f = NumberForm[Interpreter["USState"][#]@"StateSalesTaxRate"#2,{9,2}]&

f["CA", 1025.00]

61.50

f["miNnNesToA", 123.45]

8.49

Explanation
Interpreter["USState"][#]

Interpret the input as a US State name and generate an Entity.
... @"StateSalesTaxRate"

Get the sales tax rate.
... #2

Multiply that by the second input.
NumberForm[..., {9,2}]

Format the result into a number with 9 digits to the left of the decimal and 2 digits to the right.


Plot gif of 3 dimensional heart in R inspired by this blog: http://alstatr.blogspot.co.uk/2014/02/r-animating-2d-and-3d-plots.html I made a 2D gif of a heart with:

library(animation)
saveGIF({
for(i in 1:150){
dat<- data.frame(t=seq(0, 2*pi, by=0.1) )
xhrt <- function(t) 16*sin(t)^3
 yhrt <- function(t) 13*cos(t)-5*cos(2*t)-2*cos(3*t)-cos(4*t)
dat$y=yhrt(dat$t)
dat$x=xhrt(dat$t)
with(plot(x,y, type="l", xlim = c(-100  , i ^ 2 / 10 )) )
}
}, interval = 0.1, ani.width = 550, ani.height = 550)

I wonder if anyone out there could show me how to do this in 3D!

Mathematica
This is done in Mathematica, but it may give you some ideas as to how to implement it in R.
hearts = Table[
  With[{v = RotationTransform[\[Theta], {0, 0, 1}][{3, 0, -.2}]},
   ContourPlot3D[(2 (4/3 x)^2 + 2 y^2 + z^2 - 1)^3 - (4/3 x)^2 z^3/
       10 - y^2 z^3, {x, -2, 2}, {y, -2, 2}, {z, -2, 2},
    MaxRecursion -> 6, Mesh -> None,
    BoxRatios -> {.3, 1, 1},
    SphericalRegion -> True,
    Contours -> {0}, Boxed -> False, PlotRange -> All, Axes -> False,
    ViewPoint :> v, ContourStyle -> Red,
    ImageSize -> 300]], {\[Theta], 0, 2 Pi, Pi/24}]


CahartcreS awppnig (Character Swapping) Intro/Background

I was looking at "You Had One Job" pictures lately, and noticed an old favourite of mine:

And I said to myself: "I need a program that can generate text like that".
So I devised a set of rules for character swapping and wrote a CGCC challenge!

The Challenge

Given a single string as input, output a string with its inner characters swapped. This can be done by:

Leaving the first letter as is
Swapping each pair of characters thereafter
Leaving the last letter as is. If the string is of an odd length (i.e. the length of the string mod 2 is 1), leave the last two letters as they are.

Example Inputs/Outputs

School -> Shcool
Somebody -> Smobedoy
Character -> Cahartcer
CGCC -> CCGC
Stack Exchange! -> SatkcE cxahgne!
Never gonna give you up -> Nvereg noang vi eoy uup

Walkthrough on swapping

School (Length: 6)
S
 hc
   oo
     l
Shcool

Somebody (Length: 8)
S
 mo
   be
     do
       y
Smobedoy

Character (Length: 9)
C
 ah
   ar
     tc
       er
Cahartcer

Stack Exchange! (Length: 15)
S
 at
   kc
     E
       cx
         ah
           gn
             e!
SatkcE cxahgne!

Rules

Input/output can be taken/given in any convenient format
The input will not contain newlines
Minimum input length is 4
Input will only contain printable ASCII characters

Scoring

This is code-golf, so the answer with the lowest bytes wins.

Sorry about the last test case everyone. It's fixed now

Haskell, 31 bytes

f(a:b:c:d:e)=a:c:f(b:d:e)
f x=x

Try it online!

Avoids having to special-case omitting the first character by having extracting it be part of the recursive definition.


Golomb's wobbly sequence OEIS has a variation (A111439) on Golomb's sequence. As in Golomb's sequence, A(n) describes how often n appears in the sequence. But in addition, no two consecutive numbers may be identical. While building up the sequence, A(n) is always chosen as the smallest positive integer that doesn't violate these two properties. Due to disallowed consecutive identical numbers, the series wobbles slightly up and down as it grows. Here are the first 100 terms:
1, 2, 3, 2, 3, 4, 3, 4, 5, 6, 5, 6, 5, 6, 7, 6, 7, 8, 7, 8, 9, 8, 9, 8, 9,
10, 9, 10, 9, 10, 11, 10, 11, 10, 11, 10, 11, 12, 11, 12, 13, 12, 13, 12,
13, 12, 13, 12, 13, 14, 15, 14, 15, 14, 15, 14, 15, 14, 15, 14, 15, 16, 15,
16, 17, 16, 17, 16, 17, 16, 17, 16, 17, 18, 17, 18, 17, 18, 19, 18, 19, 18,
19, 18, 19, 18, 19, 18, 19, 20, 19, 20, 21, 20, 21, 20, 21, 20, 21, 20

The full list of the first 10,000 numbers can be found on OEIS.
The challenge is to write a program or function which computes A(n), given n. n is 1-based to ensure that the self-describing property works.
Rules
You may write a program or a function and use any of the our standard methods of receiving input and providing output.
You may use any programming language, but note that these loopholes are forbidden by default.
This is code-golf, so the shortest valid answer – measured in bytes – wins.
Test Cases
n     A(n)
1     1
4     2
10    6
26    10
100   20
1000  86
1257  100
10000 358

Mathematica, 69 68 bytes

Thanks to Martin Ender for finding an extra –1 byte for me!

Last@Nest[{##&@@#,1//.x_/;x==Last@#||#~Count~x==#[[x]]->x+1}&,{},#]&

Unnamed function taking a positive integer n as input and returning a positive integer. We construct the entire list of the first n elements of this sequence, then take the Last element. The list is constructed by starting with the empty list {} and operating on it with a function n times in a row (via Nest).

The function in question is {##&@@#,1//.x_/;x==Last@#||#~Count~x==#[[x]]->x+1}&, which takes a partial list of sequence values (essentially ##&@@#) and appends the next value to it. The next value is computed by starting with x=1, then repeatedly replacing x by x+1 as long as the condition x==Last@#||#~Count~x==#[[x]] is met—in other words, if either x is the previous element, or else x is already in the list the correct number of times. This function spits some errors, since (for example) we shouldn't be calling the xth element of the initial list {}; however, the values are all correct.


Regular ASCII Polygons There are 4 regular polygons that we can construct using ASCII art:

                              . . .
                  . . .      . . . .
  .     . . .    . . . .    . . . . .
 . .    . . .   . . . . .   . . . . .
. . .   . . .    . . . .    . . . . .
                  . . .      . . . .
                              . . .

That is, a triangle, a square, a hexagon and an octagon.

Your task is to take two inputs and produce the corresponding ASCII art polygon.

Input

The two inputs will be:

A string/list of printable ASCII characters (i.e. with code points in the range \$33\$ (!) to \$126\$ (~)
An indicator as to which polygon you should output. This indicator can be any \$4\$ distinct and consistent values (e.g. 1234, ABCD, etc.), but each must be only one character long, to avoid any exploitation of this input.

The string will be a perfect fit for the polygon, meaning that, if the shape to be outputted is:

A triangle, then the length of the string will be a triangular number
A square, then the length of the string will be a square number
A hexagon, then the length of the string will be a centered hexagonal number
An octagon, then the length of the string will be an octo number

The string may have repeated characters, but will always fit the appropriate lengths for the given shape/sequence, so there is no need to worry about too many/few characters.

Output

You should output a shape, indicated by the second input, in the format shown at the top of the challenge with the . replaced with the characters in the inputted string. Each character must be separated by a single space, and leading/trailing whitespace is acceptable, so long as the shape is preserved. The characters may be used in any order, but each character in the string must only appear once. For example, for a hexagon using ABCDABC, the following are valid:

 A B     B A
C D A   A B C
 B C     D C

as each character from the string is used once. However,

 A A    A B    AD
A A A  A B C   ABC
 A A    C A    BC

are not valid (the first only has A, the second doesn't have a D and the third doesn't have spaces between characters).

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

Test cases

These test cases use T, S, H and O to indicate which shape the output should be in. The string of characters is on the first line and the indicator on the second

i1+K8{^wsW
O

 i 1
+ K 8
{ ^ w
 s W

,r1~vi4l{W@+r<vzP;mq>:8gJcgg$j`$RFhDV
H

   , r 1 ~
  v i 4 l {
 W @ + r < v
z P ; m q > :
 8 g J c g g
  $ j ` $ R
   F h D V

0J++
S

0 J
+ +

Kn[Vyj
T

  K
 n [
V y j

#5~m
S

# 5
~ m

'*g(AUFV~Ou2n=172s'|S11q&j=+#
O

  ' * g
 ( A U F
V ~ O u 2
n = 1 7 2
s ' | S 1
 1 q & j
  = + #

Ruby, 139 138 bytes

->s,n{w=(((s=s.chars*' ').size/n=n.hex)**0.5).to_i+k=1&~n
(0..h=w+n/5*~-w).map{|i|s.slice!(0,[w+n/6*~-w,w**k+i,w+h+~i].min*2).center w*4}}

Try it online!

A function taking 2 arguments: a string s and a shape n as a single character in hexadecimal of value 1,2,6 or A. It returns an array of strings.

Explanation

The input string is converted to an array, then joined back into a string with spaces between the characters. The length of this combined string is twice the length of the original string, minus 1. This is divided by a constant, square rooted and rounded to determine the side length w of the polygon to be drawn. The value of the constant is per the table below. For triangles, the square root is rounded down. For others, it needs to be rounded up, so we round down then add k=1&~n to correct.

 Shape   Triangle  Square  Hexagon  Octagon
 n =     1         2       6        10

We iterate through h rows of output. For the triangle and square, h=w.  For the other shapes we need to add w-1 for the hexagon and twice this amount for the octagon. This is done by adding n/5*~-w.

Each line of output is centred and padded to w*4 characters which is enough for all cases. Chunks of s are removed using slice! and outputted. For the octagon the number of symbols to be outputted on each line is the minimum of three numbers: w+w-1 for the centre section, w+i for the top section and w+h-i-1 = w+h+~i for the bottom section. These formulas also work for the hexagon. Note that the numbers have to be multiplied by 2 to account for the spaces.

For the square and triangle, the width of the output is restricted to w. Therefore the formula for the centre section becomes w+n/6*~-w to cover all shapes . For the triangle, the width of the output is further restricted to 1+i. Therefore the formula for the top section becomes w**k+i to cover all shapes.


Calculate Wind Chill The Australian Apparent Temperature (aka, wind chill) in °C AT is given by this algorithm from the Australian Bureau of Meterology (wp, source):

AT = Ta + (0.33 * e) - (.7 * ws) - 4.0
Where:

Ta = Dry bulb temperature (°C)
e = Water vapour pressure (hPa)
ws = Wind speed (m/s) (at an elevation of 10 meters)

The water vapour pressure in hectoPascals e is given by this algorithm:

e = (rh / 100) * 6.105 * exp( ( 17.27 * Ta ) / ( 237.7 + Ta ) )
Where:

Ta = Dry bulb temperature (°C)
rh = Relative humidity [%]
exp  represents the exponential function

The domain of:

Ta is -273.15°C to 2e7°C.

e is the real numbers

ws is 0 m/s to 2e7 m/s

rh is 0% to 100%

For inputs outside these domains, your code can do anything, including give the right answer.

Output
Given a dry bulb temperature in °C, a wind speed in metres / second, and a relative humidity in %, your code should give the Apparent Temperature in °C, accurate to 0.1°C.
Assuming your platform or language can represent reals, for correct functions correct_func,

or in C, fabsl( correct_func(Ta, rH, ws) - expected ) < 0.1.
Test cases

1 value for Ta, rh, ws -> output

0 -> -4
2 -> -3.35346
4 -> -2.69275
6 -> -2.01507
8 -> -1.31719
10 -> -0.595428
12 -> 0.154404
14 -> 0.937065
16 -> 1.75793
18 -> 2.62308
20 -> 3.5393
22 -> 4.51423
24 -> 5.55638
26 -> 6.67525
28 -> 7.88137
30 -> 9.18643

49, 99, 67 -> 36.268

Repl.it for any test case: https://repl.it/H9xL/0
You can use a builtin function for the exponential function,
ex, if you like.
This is code-golf, so the shortest code wins!


dc - 21 chars

[3z202>xO200^|]dsxxrp

This takes about a minute on my computer, and would take lots longer for values larger than 200. It doesn't output leading zeroes.

Here's a slightly longer but faster version (26 chars):

[3rAz^|dz205>x]dsxxAz6-^%p
3[3rAz^|dz202>x]dsxxAz3-^%p # or an extra character for a few less iterations


Hacker Challenge: Guess the Correct Password In an attempt to “liberate” their fellow birds, a group of highly intelligent hens are
attempting to compromise the zoo’s security system. To get access to the zoo’s mainframe,
the hens first need to guess the administrative password. The hens know that the password
is a string built from up to 62 possible characters: a, b, c, ..., z, A, B, C, ..., Z, 0, 1, ... 9.
They also know that no character appears more than once in the password, which
means that it has a maximum length of 62 (and a minimum length of 1). The password
is case-sensitive.
We define a guess be close if and only if the real password can be obtained by inserting
additional characters among the letters and numbers of the original guess. In other words,
a guess is close if it is a (not necessarily contiguous) subsequence of the password. Every
time the hens guess a password, the zoo’s security system will do one of three things:

If the guess is exactly equal to the password, it will print ‘C’ and grant the hens
access to the mainframe.
If the guess close but not exactly equal to the password, it will print ‘Y’.
If the guess is neither close nor exactly equal to the password, it will print ‘N’.

The mainframe permits at most 750 guesses before it locks further attempts and alerts
the zoo officials of suspicious activity. The hens have hired you to guess the password
before you use all of your allotted attempts.
There will be no initial input. Every time your program makes a guess, the grader will
output ‘C’, ‘Y’, or ‘N’, which your program can then read via the usual input channel.
The grader will only respond to the first 750 guesses. Make sure that you end each
guess with a new line.
This question was adapted from the 2020 mBIT Computing Olympiad.
Test Program made by me in Python 3 (works):
from functools import cmp_to_key

def ask(s):
    print(s)
    c = input()
    if c == 'C':
        exit()
    return c == 'Y'

def cmp(a, b):
    return -1 if ask(a + b) else 1

ret = []
for i in range(48, 58):
    if ask(chr(i)):
        ret.append(chr(i))
for i in range(65, 91):
    if ask(chr(i)):
        ret.append(chr(i))
for i in range(97, 123):
    if ask(chr(i)):
        ret.append(chr(i))

ret = "".join(sorted(ret, key=cmp_to_key(cmp)))
print(ret)

I think it can be condensed even further, but that sample is just to show what the program is trying to ask. I do not own this question and all rights are to 2020 mBIT. The rules are simple. Do not just print answers and shortest one wins in any language.

Python 3.7, 162 bytes
import string as S,functools as F
A=lambda s:'N'!=Input(s+'\n')
print(''.join(sorted(filter(A,S.ascii_letters+S.digits),key=F.cmp_to_key(lambda a,b:1-2*A(a+b)))))

Tries characters one-by-one to see which ones are in the password. Then sorts those letters using a comparison function.  To compare 'A' and 'B', check to see if 'AB' returns 'Y'.  If is does, then 'A' comes before 'B', otherwise 'A' comes after 'B'.


Where can the knight be in N moves? This is Hole-3 from The Autumn Tournament of APL CodeGolf. I am the original author of the problem there, and thus allowed to re-post it here.

Given:

a number of turns (please state if no movements is 0, otherwise we'll assume it is called 1) and

a list of one or more starting positions (in any form, e.g. 0 or 1 indexed coordinates or 64 consecutive numbers/characters or A1–H8 – state which), on an 8-by-8 chessboard,

return (in any order) the list of unique positions (in the same format as the input) that knight(s) can be at after the given number of turns.

Each knight must move with every turn, but you do not have to worry about multiple knights occupying the same square.

A knight can only move to the positions marked with X relative to its current position, marked with ♞:

Examples (1-indexed coordinates)
1 move from [[1,1]]: [[2,3],[3,2]]
2 moves from [[1,1]]: [[1,1],[1,3],[1,5],[2,4],[3,1],[3,5],[4,2],[4,4],[5,1],[5,3]]
1 move from [[1,1],[5,7]]: [[2,3],[3,2],[3,6],[3,8],[4,5],[6,5],[7,6],[7,8]]
2 moves from [[1,1],[5,7]]: [[1,1],[1,3],[1,5],[1,7],[2,4],[2,6],[2,8],[3,1],[3,3],[3,5],[3,7],[4,2],[4,4],[4,6],[4,8],[5,1],[5,3],[5,5],[5,7],[6,4],[6,6],[6,8],[7,3],[7,7],[8,4],[8,6],[8,8]]
0 moves from [[3,4]]: [[3,4]]

Wolfram Language (Mathematica), 45 bytes

Because the other solution is incorrect (see Martin's comment below), so I decide to post my solution:

8~KnightTourGraph~8~AdjacencyList~#&~Nest~##&

Try it online!

Ultimate infix notation...

Takes 2 input, the first one is a list of numbers in range [1,64] describe the starting positions of the knight, the second one is the number of steps.

This solution relies on the extreme convenience of Mathematica builtin functions:

AdjacencyList may takes a list of vertices on its right side, and return a list of vertices adjacent to any of those, already removed duplicates and sorted.
KnightTourGraph is a builtin. Not surprise.
Nest takes arguments in order Nest[f, expr, n], which we can splat the ## over its right side as Nest[f, ##].
And finally, Mathematica parse a~b~c~d~e as (a~b~c)~d~e, so no square bracket is necessary. Without infix notation and flatten ##, it would be Nest[AdjacencyList[KnightTourGraph[8, 8], #] &, #, #2]&.


Fizz! Buzz! 'ave a banana! Here's one for fans of Cabin Pressure. There is an episode in which the characters devise a new version of Fizz Buzz, which is simplified to contain absolutely no mathematics.

It has these rules:

If someone says "fizz", you say "buzz".
If someone says "buzz", you sing "'ave a banana"
If someone says your name, you say "fizz".

The result is that whenever a name is uttered, that person says "fizz" and the sequence has to run to completion.

Let's write some code.

I'd like you to write a program/function/whatever which works thus:

It accepts one single string of text as input.
If the string equals the name of the language your code is written in, it outputs "fizz".
If the string equals "fizz", it outputs "buzz".
If the string equals "buzz", it outputs "'ave a banana" (note the apostrophe at the start).
If the input is not one of these things, it should terminate.
Here's the kicker: The output string must go to two places.

Output to be seen by the user

Back into your code as input

I don't really care if they are output in each iteration, or build a string for eventual output.
Outputs must be separated by new lines (in console or result string)

Rules

This is code golf, write in any language you like and attempt to make your code as small as possible.
Standard loopholes apply.
I'd like to see links to an online interpreter.
The language name can be a full name or common short-form of the language the answer is written in. E.g. JS is acceptable, but shortening Ruby to R is not).

Test Cases

Input

'buzz'

Output

'ave a banana

Input

'fizz'

Output

buzz
'ave a banana

Input

ruby # or the name of the language your answer is written in

Output

fizz
buzz
'ave a banana

Input

something else

No output

perl -M5.010 -n, 47 bytes

"Perl\nfizz\nbuzz\n'ave a banana"=~/\b$_/;say$'

Try it online!

Prints whatever is following the input, or nothing if there is no match. Assumes input is newline terminated.


Help! I have more homework! My teacher was more than unhappy with my Martian Homework. I followed all the rules, but she says that what I output was gibberish... when she first looked at it, she was highly suspicious. "All languages should follow Zipf's law blah blah blah"... I didn't even know what Zipf's law was!

It turns out Zipf's law states that if you plot the logarithm of the frequency of each word on the y axis, and the logarithm of the "place" of each word on the x axis (most common = 1, second most common = 2, third most commmon = 3, and so on), then the plot will show a line with a slope of about -1, give or take about 10%.

For example, here's a plot for Moby Dick:

The x axis is the nth most common word, the y-axis is the number of occurences of the nth most common word. The slope of the line is about -1.07.

Now we're covering Venutian. Thankfully, Venutians use the latin alphabet. The rules are as follows:

Each word must contain at least one vowel (a, e, i, o, u)
In each word there can be up to three vowels in a row, but no more than two consonants in a row (a consonant is any letter that's not a vowel).
No words longer than 15 letters
Optional: group words into sentences 3-30 words long, delimited by periods

Because the teacher feels that I cheated on my Martian homework, I've been assigned to write an essay at least 30,000 words long (in Venutian). She's going to check my work using Zipf's law, so when a line is fitted (as described above) the slope has to be at most -0.9 but no less than -1.1, and she wants a vocabulary of at least 200 words. The same word should not be repeated more than 5 times in a row.

This is CodeGolf, so shortest code in bytes wins. Please paste the output to Pastebin or another tool where I can download it as a text file.

Mathematica, 102 bytes

""<>RandomChoice[1/Range@215->Rest@Flatten@Outer[StringJoin,a={"v","a","e","i","o","u"},a,a,{" "}],8!]

Unnamed function taking no input and returning a string consisting of 40,320 three-letter Venusian words with trailing spaces.

Outer[StringJoin,a={"v","a","e","i","o","u"},a,a,{" "}] produces the 216 three-letter words possible using only the letters "vaeiou", each with its own trailing space. The first of these words, "vvv", is not valid Venusian, but Rest throws it away.

Then RandomChoice[1/Range@215->...,8!] makes 8! = 40,320 random choices from the resulting 215-word list, with frequency weights determined by the reciprocals of the first 215 integers (1/Range@215). Finally, <>""... concatenates the strings in the resulting list.

The output is far from deterministic; one run yielded this Venusian essay.

Mathematica, 129 bytes

#2&@@@Sort[Join@@Table[{i,Rest@Flatten@Outer[StringJoin,a={"v","a","e","i","o","u"},a,a,{" "}]~Part~j},{j,215},{i,0,1,j/7!}]]<>""

This one is deterministic. The base set of 215 words is the same, but now each word is repeated an exact number of times (word #j is repeated roughly 7!/j times) to force zipf's law to hold. Then the words are interleaved equally to avoid repetitions. (Imagine each word is laid out on a ruler, with all the copies of that word equally spaced; when all the words are read in order, no particular word will repeat much, perhaps not at all.) The result is a 30,117-word Venusian essay.


Exploded view of a string Don't you love those exploded-view diagrams  in which a machine or object is taken apart into its smallest pieces?

Let's do that to a string!

The challenge

Write a program or function that

inputs a string containing only printable ASCII characters;
dissects the string into groups of non-space equal characters (the "pieces" of the string);
outputs those groups in any convenient format, with some separator between groups.

For example, given the string

Ah, abracadabra!

the output would be the following groups:

!
,
A
aaaaa
bb
c
d
h
rr

Each group in the output contains equal characters, with spaces removed. A newline has been used as separator between groups. More about allowed formats below.

Rules

The input should be a string or an array of chars. It will only contain printable ASCII chars (the inclusive range from space to tilde). If your language does not support that, you can take the input in the form of numbers representing ASCII codes.

You can assume that the input contains at least one non-space character.

The output should consist of characters (even if the input is by means of ASCII codes). There has to be an unambiguous separator between groups, different than any non-space character that may appear in the input.

If the output is via function return, it may also be an array or strings, or an array of arrays of chars, or similar structure. In that case the structure provides the necessary separation.

A separator between characters of each group is optional. If there is one, the same rule applies: it can't be a non-space character that may appear in the input. Also, it can't be the same separator as used between groups.

Other than that, the format is flexible. Here are some examples:

The groups may be strings separated by newlines, as shown above.
The groups may be separated by any non-ASCII character, such as  ¬. The output for the above input would be the string:

!¬,¬A¬aaaaa¬bb¬c¬d¬h¬rr

The groups may be separated by n>1 spaces (even if n is variable), with chars between each group separated by a single space:

!  ,    A   a a a a a    b b  c       d   h  r r

The output may also be an array or list of strings returned by a function:

['!', 'A', 'aaaaa', 'bb', 'c', 'd', 'h', 'rr']

Or an array of char arrays:

[['!'], ['A'], ['a', 'a', 'a', 'a', 'a'], ['b', 'b'], ['c'], ['d'], ['h'], ['r', 'r']]

Examples of formats that are not allowed, according to the rules:

A comma can't be used as separator (!,,,A,a,a,a,a,a,b,b,c,d,h,r,r), because the input may contain commas.
It's not accepted to drop the separator between groups (!,Aaaaaabbcdhrr) or to use the same separator between groups and within groups (! , A a a a a a b b c d h r r).

The groups may appear in any order in the output. For example: alphabetical order (as in the examples above), order of first appearance in the string, ... The order need not be consistent or even deterministic.

Note that the input cannot contain newline characters, and A and a are different characters (grouping is case-sentitive).

Shortest code in bytes wins.

Test cases

In each test case, first line is input, and the remaining lines are the output, with each group in a different line.

Test case 1:

Ah, abracadabra!
!
,
A
aaaaa
bb
c
d
h
rr

Test case 2:

\o/\o/\o/
///
\\\
ooo

Test case 3:

A man, a plan, a canal: Panama!
!
,,
:
A
P
aaaaaaaaa
c
ll
mm
nnnn
p

Test case 4:

"Show me how you do that trick, the one that makes me scream" she said
""
,
S
aaaaa
cc
dd
eeeeeee
hhhhhh
ii
kk
mmmm
n
ooooo
rr
ssss
tttttt
u
ww
y

Python 3.5+, 77 46 44 41 bytes

lambda s:[a*s.count(a)for a in{*s}-{' '}]

Pretty simple. Goes through the unique characters in the string by converting it to a set (using Python 3.5's extended iterable unpacking), then uses a list comprehension to construct the exploded diagrams by counting the number of times each character occurs in the string with str.count. We filter out spaces by removing them from the set.

The order of the output may vary from run to run; sets are unordered, so the order in which their items are processed, and thus this answer outputs, cannot be guaranteed.

This is a lambda expression; to use it, prefix lambda with f=.

Try it on Ideone! Ideone uses Python 3.4, which isn't sufficient.

Usage example:

>>> f=lambda s:[a*s.count(a)for a in{*s}-{' '}]
>>> f('Ah, abracadabra!')
[',', 'A', 'aaaaa', 'd', '!', 'bb', 'h', 'c', 'rr']

Saved 3 bytes thanks to @shooqie!


Can You Spell This Word With These Dice? Letter dice are common in word games. It can be fun to try to spell funny words with boggle dice, for instance. If you grab a handful of dice, chances are you won't be able to spell certain words. This challenge is a generalization of that idea.
Challenge
Given a list of dice which each have at least 1 face and a word, your task is to determine if it is possible to spell that word using the given dice (in which case, it should return a truthy result). Only one letter from each die can be used and a die can be used only once. You do not need to use all of the given dice.
Examples
In a trivial example, with the dice [[A], [C], [T]] and the string CAT, the result is true. BAT would, of course, return false since there are no dice with B on them
If given [[A, E, I, O, U], [A, B, C, T], [N, P, R]] as the set of dice, you would return true for ART, TON, and CUR, but false for CAT, EAT, and PAN because those strings require reusing dice. It should also be fairly obvious that CRAB cannot be spelled with these dice since there are not enough dice.
If given [[A, B, C], [A, E, I], [E, O, U], [L, N, R, S, T]] as the set of dice, you would be able to spell CAT, BEE, BEAN, TEA, BEET, and BAN, but you would not be able to spell LONE, CAB, BAIL, TAIL, BAA, or TON
There may be multiples of the same die. If given [[A, B, C], [A, B, C], [A, B, C]], you would be able to spell CAB, BAA, AAA, etc... but obviously nothing without A, B, or C in it.
Rules

No exploiting standard loopholes
This is code-golf, so the shortest code wins.
You may assume that both words and dice will only be made up of capital letters.
You may assume that the word will always be at least 1 letter long and that there will always be at least 1 die.
You may assume that a die will never have more than one of the same letter.
Input and output may be in any convenient format.

Brachylog, 5 bytes
∋ᵐ⊇pc

Try it online!
We use the input variable for the dice and the output variable for the word. It outputs true. when it's possible to spell the word and false. otherwise.
Explanation
∋ᵐ        Map element: Take one side from each die
  ⊇       Subset
   p      Permute
    c     Concatenate into a string: will only succeed if it results in the output word


Build a poisoned wine testing scheduler Recently at Puzzling.SE, there was a problem that I wrote about determining which two bottles out of a larger number are poisoned when the poison only activates if both components are drunk. It ended up being quite the ordeal, with most people managing to get it down to 18 or 19 prisoners using completely different algorithms.
The original problem statement is as follows:

You are the ruler of a medieval kingdom who loves throwing parties. The courtier who tried to poison one of your wine bottles last time was furious to learn that you managed to identify which bottle he had poisoned out of 1,000 with just ten prisoners.
This time he's a bit craftier. He's developed a composite poison P: a binary liquid that's only deadly when two individually harmless components mix; this is similar to how epoxy works. He's sent you another crate of 1,000 wine bottles. One bottle has component C_a and another one has component C_b. (P = C_a + C_b)
Anyone who drinks both components will die on the stroke of midnight on the night they drank the final component, regardless of when in the day they imbibed the liquid. Each poison component stays in the body until the second component activates, so if you drink one component one day and another component the next, you will die on midnight at the end of the second day.
You have two days before your next party. What is the minimum number of prisoners you need to use for testing in order to identify which two bottles are tainted, and what algorithm do you need to follow with that number of prisoners?

Bonus
Additionally, suppose that you had a fixed limit of 20 prisoners at your disposal, what's the maximum number of bottles you could theoretically test and come to an accurate conclusion about which bottles were affected?

Your task is to build a program to solve the bonus problem. Given n prisoners, your program will devise a testing schedule that will be able to detect the two poisoned bottles among m bottles, where m is as large as possible.
Your program will initially take as input the number N, the number of prisoners. It will then output:

M, the number of bottles you will attempt to test. These bottles will be labelled from 1 to M.

N lines, containing the labels of the bottles each prisoner will drink.

Your program will then take as input which prisoners died on the first day, with the prisoner on the first line being 1, the next line being 2, etc. Then, it will output:

N more lines, containing the labels of the bottles each prisoner will drink. Dead prisoners will have blank lines.

Your program will then take as input which prisoners died on the second day, and output two numbers, A and B, representing which two bottles your program thinks contains the poison.
An example input for two prisoners and four bottles might go as such, if bottles 1 and 3 are poisoned:
> 2      // INPUT: 2 prisoners
4        // OUTPUT: 4 bottles
1 2 3    // OUTPUT: prisoner 1 will drink 1, 2, 3
1 4      // OUTPUT: prisoner 2 will drink 1, 4
> 1      // INPUT: only the first prisoner died
         // OUTPUT: prisoner 1 is dead, he can't drink any more bottles
3        // OUTPUT: prisoner 2 drinks bottle 3
> 2      // INPUT: prisoner 2 died
1 3      // OUTPUT: therefore, the poisoned bottles are 1 and 3.

The above algorithm may not actually work in all
cases; it's just an example of input and output.

Your program's testing schedule must successfully determine each possible pair of poisoned bottles in order for it to be a valid submission.
Your program will be scored on the following criteria, in order:

The maximum number of bottles it can discern for the case N = 20.

The number of bottles for the case N = 21, and successively higher cases after that.

The length of code. (Shorter code wins.)

Python 2.7.9 — 21 bottles

Assuming that ESultanik's speculation is right on what the input is when multiple prisoners die

r=raw_input;s=str;j=s.join;p=int(r());z=range;q=z(p);x=z(p+1)
print s(p+1)+"\n"+j("\n",(j(" ",(s(a) for a in x if a!=b)) for b in q))
v=r().split();d=[s(a) for a in q if s(a) not in v];d+=[p]if len(d)==1 else [];
print "\n"*p,;r();print j(" ",[s(a) for a in d])

Algorithm: every prisoner drinks from every bottle except their number (1st prisoner doesn't drink first bottle). If they don't die, their number bottle is poisoned. If only one prisoner survives, the extra bottle is poisoned.


“HHeelllloo,, EEaarrtthh!!” Much like this challenge, write a program or function that takes no input and prints or returns the string

Hello, Earth!

with an optional trailing newline.

The catch is that your program must be an even number of characters long, and each two character chunk of your program must consist of identical characters.

For example, a valid program might look like

AAbb==11++♥♥

[[--  2222]]

because every two character chunk (AA, bb, ==, 11, etc.) is made of two identical characters (even the newlines).

A program such as

AAbB==11++♥♥

[[--  2222]]

would not be valid because the bB chunk is not made of identical characters.

The only exception to the rule is that \r\n should be treated a single, generic "newline" character since replacing it with \r\r\n\n wouldn't work or make sense for some languages and systems.

The shortest code in bytes wins. The example is 30 bytes long (not 15, not 13).