Smallest n-digit prime containing only these digits You will need to generate the smallest prime with n digits, and it will only contain digits specified in the list k.

Examples:

Input:

4
1 2

For this, you must generate the smallest prime with 4 digits, and that prime must only contain the digits 1 and 2.

Output:

2111

Input:

10
0 4 7

Output:

4000000007

Input:

6
5 5 5 5 5 5 5 5 5 5 1 5 5 5 5 5 5 5 5 5 5

Output:

115151

You can guarantee that the input will always be in the format you specify, and you can do anything if you get invalid input (such as the input being a single digit n, without k.)

If no such solution to an input exists, your program is allowed to do any of the following:

Print banana
Throw an error
Run forever
Anything else

Since this is code-golf, try to aim for the shortest code.

The input can be in any format you specify. For example, if you want your input to be like any of the following, that is fine.

4
[1, 2]

[1,2]4

1,2
4

4 12

You can either write a program or a function, and it must either return the correct value or print it.

Whitespace is allowed anywhere.

This challenge inspired by A036229.

Bash + bsd-games package, 28 bytes

18 bytes saved thanks to @Dennis.

primes 1|egrep -wm1 [$2]{$1}

Input given at the command-line as n followed by k as a non-delimited list of digits.
Try it online.


Random numbers with fixed sum Your task is to write a program or a function that outputs n random numbers from interval [0,1] with fixed sum s.

Input

n, n≥1, number of random numbers to generate

s, s>=0, s<=n, sum of numbers to be generated

Output

A random n-tuple of floating point numbers with all elements from the interval [0,1] and sum of all elements equal to s, output in any convenient unambiguous way. All valid n-tuples have to be equally likely within the limitations of floating point numbers.

This is equal to uniformly sampling from the intersection of the points inside the n-dimensional unit cube and the n-1-dimensional hyperplane that goes through (s/n, s/n, …, s/n) and is perpendicular to the vector (1, 1, …, 1) (see red area in Figure 1 for three examples).

Figure 1: The plane of valid outputs with n=3 and sums 0.75, 1.75 and 2.75

Examples

n=1, s=0.8 → [0.8]
n=3, s=3.0 → [1.0, 1.0, 1.0]
n=2, s=0.0 → [0.0, 0.0]
n=4, s=2.0 → [0.2509075946818119, 0.14887693388076845, 0.9449661625992032, 0.6552493088382167]
n=10, s=9.999999999999 → [0.9999999999999,0.9999999999999,0.9999999999999,0.9999999999999,0.9999999999999,0.9999999999999,0.9999999999999,0.9999999999999,0.9999999999999,0.9999999999999]

Rules

Your program should finish under a second on your machine at least with n≤10 and any valid s.
If you so wish, your program can be exclusive on the upper end, i.e. s<n and the output numbers from the half-open interval [0,1) (breaking the second example)
If your language doesn't support floating point numbers, you can fake the output with at least ten decimal digits after the decimal point.
Standard loopholes are disallowed and standard input/output methods are allowed.
This is code-golf, so the shortest entry, measured in bytes, wins.


How many partitions contain only perfect squares? Given a non-negative integer or a list of digits, determine in how many ways can the number be formed by concatenating square numbers, which may have leading zeroes.

Examples

input -> output # explanation
164 -> 2 # [16, 4], [1, 64]
101 -> 2 # [1, 01], [1, 0, 1]
100 -> 3 # [100], [1, 00], [1, 0, 0]
1 -> 1 # [1]
0 -> 1 # [0]
164900 -> 9 # [1, 64, 9, 0, 0], [1, 64, 9, 00], [1, 64, 900], [16, 4, 900], [16, 4, 9, 0, 0], [16, 4, 9, 00], [16, 49, 0, 0], [16, 49, 00], [16, 4900]

Rules

Standard Loopholes Apply
This is code-golf so the shortest answer in bytes wins


Calculate the average longest common substring exactly [Question inspired by Can you calculate the average Levenshtein distance exactly? . Thank you Anush. ]

The longest common substring between two strings is the longest substring which is common to both.  Please note this is not the same as the longest common subsequence whose fastest algorithm takes quadratic time.

The challenge is to compute the average length of the longest common substring between two independent and uniformly random chosen binary strings of length n each.  Your output must be exact but can be given in any easy to understand human readable form.

Examples for n = 1..12

1/2
9/8
7/4
295/128
361/128
6741/2048
15217/4096
8389/2048
291431/65536
2500643/524288
2657159/524288
22420789/4194304

Score

Your score is the highest value of  you can reach. I will run your code on my Linux machine for 1 minute and then kill the job to get the score.

I will maintain a leaderboard that shows the best score for each language used in an answer.

Worked example

Following a request, here is the full set of distances for n = 3. I have not include strings B and A if A and B are already listed. This is because the distance function is symmetric.

000 000 3
000 001 2
000 010 1
000 011 1
000 100 2
000 101 1
000 110 1
000 111 0
001 001 3
001 010 2
001 011 2
001 100 2
001 101 2
001 110 1
001 111 1
010 010 3
010 011 2
010 100 2
010 101 2
010 110 2
010 111 1
011 011 3
011 100 1
011 101 2
011 110 2
011 111 2
100 100 3
100 101 2
100 110 2
100 111 1
101 101 3
101 110 2
101 111 1
110 110 3
110 111 2
111 111 3

Leaderboard

n = 22 in C++ by my pronoun is monicareinstate.
n = 18 in Rust by Plasma_000.
n = 14 in C by Mitchel Spector.
n = 11 in Python with pypy 3 by Alex.

C++, n = 21 (40s on an AMD Ryzen 5 2500U)
This used to be a fast brute force answer that got up to n=17. That is currently preserved in the revision history.
#include <cstring>
#include <omp.h>
#include <iostream>
#include <vector>
#include <array>
#include <algorithm>
#include <map>
#include <unordered_map>
#include <bitset>
#include <random>

typedef unsigned uint;
typedef unsigned char byte;
const int threadnum = 8;
const int maxn = 22; //for 24 bytes total size of Row
struct Row; struct hasher { size_t operator ()(const Row& row) const; };
struct Row
{
    char max = 0;
    std::array<char, maxn+1> row {0};
    Row() { }
    Row(int nmax)
    {
        max = nmax;
    }
    bool operator ==(const Row& rhs) const
    {
        const uint64_t* x = reinterpret_cast<const uint64_t*>(this);
        const uint64_t* y = reinterpret_cast<const uint64_t*>(&rhs);
        return x[0] == y[0] && x[1] == y[1] && x[2] == y[2];
    }
};
uint64_t rotl(uint64_t x, char a)
{
    return (x << a) | (x >> (64 - a));
}
size_t hasher::operator() (const Row& row) const
{
    const uint64_t* mem = reinterpret_cast<const uint64_t*>(&row);
    //I tried really many different hashes...
    uint64_t h = mem[0]; h += rotl(h, 4);
    h         ^= mem[1]; h += rotl(h, 4);
    h         ^= mem[2]; h += rotl(h, 4);
    return h;
}
const short hashTableSize = 1009;
struct Map
{
    std::array<std::pair<Row, int>, hashTableSize> table {};
    Map()
    {
    }
    void add_or_add(const Row row, const int delta)
    {
        size_t hash = hasher()(row) % hashTableSize;
        while(table[hash].second != 0 && !(table[hash].first == row))
        {
            hash++;
            if(hash == hashTableSize) hash = 0; //just loop :)
        }
        if(table[hash].second == 0)
            table[hash].first = row;
        table[hash].second += delta;
    }
    void clear()
    {
        std::memset(table.data(), 0, sizeof(table));
    }
};

constexpr uint bitRev(uint n)
{
    n = ((n >> 1) & 0x55555555) | ((n << 1) & 0xaaaaaaaa);
        n = ((n >> 2) & 0x33333333) | ((n << 2) & 0xcccccccc);
        n = ((n >> 4) & 0x0f0f0f0f) | ((n << 4) & 0xf0f0f0f0);
        n = ((n >> 8) & 0x00ff00ff) | ((n << 8) & 0xff00ff00);
        n = ((n >>16) & 0x0000ffff) | ((n <<16) & 0xffff0000);
        return n;
}
constexpr bool is_substring(int target, char n, short subs, char m)
{
    //n=2, m=1 -> i from 0 to 1
    int max = n-m+1;
    bool flag = false;
    for(int i = 0; i < max; i++)
        flag |= (((target >> i) ^ subs) & ((1<<m) - 1)) == 0;
    return flag;
}
int supermax = 0;
int main()
{
    uint n; std::cin >> n;
    std::vector<uint64_t> sums(threadnum);
    uint64_t sum = 0;
#pragma omp parallel for num_threads(threadnum) schedule(dynamic)
    for(uint sa = 0; sa < 1<<~-n; sa++) //the second half is the bitwise complement of the first one
    {
        uint sb = bitRev(sa);
        sb ^= -(sb >> 31);
        sb >>= 32 - n;
        if(sb < sa) continue;
        //find a lower bound = len(the shortest non-substring of sa) - 1
        //if Row.max is immediately set to it, that reduces the number of states slightly
        char lb = 0; bool found = false;
        for(char len = 0; len < 10; len++)
        {
            for(short j = 0; j < (1<<len); j++)
                if(!is_substring(sa, n, j, len))
                {
                    lb = len - 1;
                    goto out;
                }
        }
        out:;
        Map dpcur;
        Map dpnext;
        dpcur.add_or_add(Row(lb), 1);
        int ans = 0;
        for(char j = 0; j < n; j++)
        {
            for(auto[row, cnt] : dpcur.table)
            {
                if(!cnt) continue;
                Row nr0 {}, nr1 {};
                nr0.max = nr1.max = row.max;
                for(char i = 0; i < n; i++)
                {
                    Row& r = (sa >> i)&1 ? nr0 : nr1;
                    r.row[i+1] = row.row[i] + 1;
                }
                char n0max = 0, n1max = 0;
                for(char i = 0; i < 23; i++)
                    n0max = std::max(n0max, nr0.row[i]);
                for(char i = 0; i < 23; i++)
                    n1max = std::max(n1max, nr1.row[i]);
                //possibly, cut an entire would-be branch that would never improve!
                if(n0max + n - j - 1 <= nr0.max)
                    ans += (cnt * nr0.max) << (n - j - 1);
                else
                    nr0.max = std::max(nr0.max, n0max), dpnext.add_or_add(nr0, cnt);
                if(n1max + n - j - 1 <= nr1.max)
                    ans += (cnt * nr1.max) << (n - j - 1);
                else
                    nr1.max = std::max(nr1.max, n1max), dpnext.add_or_add(nr1, cnt);
            }
            std::memcpy(dpcur.table.data(), dpnext.table.data(), sizeof(Map));
            dpnext.clear();
        }
        for(auto[row, cnt] : dpcur.table)
            ans += cnt * row.max;
        sums[omp_get_thread_num()] += ans;
        if(sb != sa)
            sums[omp_get_thread_num()] += ans;
    }
    for(uint64_t e : sums) sum += e;
    sum *= 2;
    printf("%ld\n", sum);
    uint64_t num = sum, denom = 1ll<<(2*n);
    while(num % 2 == 0) num /= 2, denom /= 2;
    printf("%ld/%ld\n", num, denom);
}

This uses OpenMP for multi-threading. To be compiled with clang++ -std=c++17 -Ofast -march=native -flto -fopenmp file.cpp.
Explanation I tried (please don't use it as a Rust translation guide)
The longest common substring can be found in \$O(n^2)\$ time via dynamic programming. That dynamic programming can be calculated (if the strings are \$s\$ and \$t\$) via the formula $$dp_{i,j} = \begin{cases}dp_{i-1,j-1} + 1& s_i = t_j\\0& \text{otherwise}\end{cases}$$
(and then the answer is just the highest value in \$dp\$). A naive solution would be to iterate over pairs of strings of length \$n\$ (resulting in \$O(4^n n^2)\$ time complexity). However, instead of simply doing that, my program only iterates over all possible values of the first string. Then, it simply does that, but instead of storing a proper dynamic programming array (that wouldn't be possible because there is no second string), it stores an array of all possible rows in it with counters of how many ways exist to reach this row. To calculate the next array of possible rows from the current array of possible rows, my program simply tries all of them with both possible values of the next bit in the second string. This leads to a speedup, because if two prefixes of the second string lead to the same state, they can be "merged" into one execution path.
I suspect this is similar to the optimization from the top answer in a similar challenge but for Levenshtein distance, but the explanation there is so bad I couldn't understand it at all.
The optimization that got this to 21: if at a certain point a possible row is encountered such that all its numbers are too small to ever improve the length of the longest substring in it, it can be directly calculated how much it will add to the answer.
Takes input as a single number from stdin. Outputs 734551/131072 for 13, 392340511/67108864 for 14, 1630366263/268435456 for 15, 6751032665/1073741824 for 16, 6967595579/1073741824 for 17, 114759115773/17179869184 for 18, 235733542633/34359738368 for 19, 1933121200141/27877906944 for 20 and 7912473298597/1099511627776 for 21.


Square, Circle, Triangle, ...Gear? Using Algodoo and Paint I made these six 300×300 monochromatic images of four convenient shapes:

This class of images has the following properties:

They are always 300×300 pixels, monochromatic (black and white only), and have exactly four white regions that correspond to a square, a circle, a triangle, and a gear.
The shapes never overlap or touch each other, nor do they touch the image border or go out of bounds.
The shapes always have the same size, but they may be rotated and positioned in any way.

(The shapes also have equal areas, though when rastered like this their pixel counts are unlikely to be exactly equivalent.)
Challenge
Write the shortest program or function possible that takes in the filename of such an image and turns all the white pixels...

red (255, 0, 0) if they are in the square.
blue (0, 0, 255) if they are in the circle.
green (0, 255, 0) if they are in the triangle.
yellow (255, 255, 0) if they are in the gear.

e.g.

Details
Your program should work for effectively all possible input images. (Only valid 300×300 monochromatic images will be input.) The six images I have provided are merely examples, you may not hardcode their output into your program.
You may not use computer vision libraries or functions, built-in or external. The point is to do this using your own pixel-level operations. You may use image libraries that simply let you open and modify images (e.g. PIL for Python).
You may use any common lossless image file formats for input and output as long as you stick to the color scheme.
You can take in the image filename as a function argument, from stdin, or from the command line. The output image can be saved to a new file, the same file, or simply displayed.
Scoring
The submission with the fewest bytes wins. I may test submissions with additional images to determine their validity.

Mathematica, 459 392 bytes

f=(d=ImageData@Import@#/.{a_,_,_}:>a;(For[a={};b={#&@@d~Position~1},b!={},c=#&@@b;b=Rest@b;d[[##&@@c]]=0;a~AppendTo~c;If[Extract[d,c+#]==1,b=b⋃{c+#}]&/@{e={1,0},-e,e={0,1},-e}];m=1.Mean@a;m=#-m&/@a;n=Count[Partition[Norm/@SortBy[m,ArcTan@@#&],300,1,1],l_/;l[[150]]==Max@l];(d[[##&@@#]]=Round[n^.68])&/@a)&/@Range@4;Image[d/.n_Integer:>{{0,0,0},,{0,1,0},{1,0,0},,,,{1,1,0},{0,0,1}}[[n+1]]])&

Ungolfed:

f = (
 d = ImageData@Import@# /. {a_, _, _} :> a;
 (
    For[a = {}; b = {# & @@ d~Position~1},
     b != {},
     c = # & @@ b;
     b = Rest@b;
     d[[## & @@ c]] = 0;
     a~AppendTo~c;
     If[Extract[d, c + #] == 1,
        b = b ⋃ {c + #}] & /@ {e = {1, 0}, -e, e = {0, 1}, -e}
     ];
    m = 1. Mean@a; m = # - m & /@ a;
    n =
     Count[Partition[Norm /@ SortBy[m, ArcTan @@ # &], 300, 1, 1],
      l_ /; l[[150]] == Max@l];
    (d[[## & @@ #]] = Round[n^.68]) & /@ a
    ) & /@ Range@4;
 Image[d /.
   n_Integer :> {{0, 0, 0}, , {0, 1, 0}, {1, 0, 0}, , , , {1, 1,
       0}, {0, 0, 1}}[[n + 1]]]
) &

I could save 6 more bytes by turning m=1.Mean@a;m=#-m&/@a; into m=#-Mean@a&/@a;, but that significantly blows up execution time, which is annoying for testing. (Note, that this is two optimisations: pulling out the computation of Mean@a out of loop and using exact symbolic types instead of floating point numbers. Interestingly, the use of exact types is a lot more significant than computing the mean in every iteration.)

So this is approach number three:

Detect areas by flood-fill.
Find approximate centre of each area by averaging all pixel coordinates.
Now for all pixels in the shape let's plot distance from vs angle to that centre:

The triangle has 3 clear maxima, the square 4, the gear 16, and the circle has tons, due to aliasing fluctuations about the constant radius.
We find the number of maxima by looking at slices of 300 pixels (ordered by angle), and count the slices where the pixel at position 150 is the maximum.
Then we just colour all pixels depending on the number of peaks (the circle is anything over 16, and usually yields around 20 peaks, due to the size of the slices).

Just for the record, if I use Ell's idea, and simply sort the regions by largest distance between any pixel and centre, I can do this in 342 bytes:

f=(d=ImageData@Import@#/.{a_,_,_}:>a;MapIndexed[(d[[##&@@#]]=#&@@#2)&,SortBy[(For[a={};b={#&@@d~Position~1},b!={},c=#&@@b;b=Rest@b;d[[##&@@c]]=0;a~AppendTo~c;If[Extract[d,c+#]==1,b=b⋃{c+#}]&/@{e={1,0},-e,e={0,1},-e}];a)&/@Range@4,(m=Mean@#;Max[1.Norm[#-m]&/@#])&],{2}];Image[d/.n_Integer:>{{0,0,0},{0,0,1},{1,1,0},{1,0,0},{0,1,0}}[[n+1]]])&

But I do not intend to compete with that, as long as everyone else is using their own original algorithms, instead of golfing down those of others.


Print an arch of ascending / descending numbers I figured an "arch" was the best way to describe this pattern of numbers:

1234567887654321
1234567  7654321
123456    654321
12345      54321
1234        4321
123          321
12            21
1              1

Formally defined, each line consists of the numbers 1 through 9-n, (n-1)*2 spaces, and the numbers 9-n through 1 (where n is the current line).

Your task is to write, using the shortest code possible, a small script/program that prints the above pattern subject to the following restrictions:

You may not hardcode the entire pattern. You may only hardcode a single line of the pattern at most.
Your program must print a newline (any combination of \n or \r) at the end of each line.

Ready... set.... go!

Python 2, 65 55 53 51

s=12345678
while s:r='%-8d'%s;print r+r[::-1];s/=10

Shortened using some of ugoren's ideas.


How many steps did I walk? A simple pedometer can be modeled by a pendulum with two switches on opposite sides—one at x=0 and one at x=l. When the pendulum contacts the far switch, the ambulator can be assumed to have taken half a step. When it contacts the near switch, the step is completed.
Given a list of integers representing positions of the pendulum, determine the number of full steps recorded on the pedometer.
Input

An integer l>0, the length of the track.

A list of integers representing the positions of the pedometer's pendulum at each time.

Output
The number of full steps measured. A step is taken when the pendulum contacts the far switch (x>=l) and then the near switch (x<=0).
Test cases
8, [8, 3, 0, 1, 0, 2, 2, 9, 4, 7]
1

The pendulum immediately makes contact with the far switch at x=8 at t=0. Then it touches the near switch at t=2 and t=4, completing one step. After that, it touches the far switch again at x=9 at t=8, but it never touches the near switch again.
1, [1, 5, -1, -4, -1, 1, -2, 8, 0, -4]
3

15, [10, -7, -13, 19, 0, 22, 8, 9, -6, 21, -14, 12, -5, -12, 5, -3, 5, -15, 0, 2, 11, -11, 12, 5, 16, 14, 27, -5, 13, 0, -7, -2, 11, -8, 27, 15, -10, -10, 4, 21, 29, 21, 2, 5, -7, 15, -7, -14, 13, 27]
7

7, [5, 4, 0]
0

7, [5, 8, 6, 1, 2]
0

CJam, 27 24 bytes

l~:Xfe<0fe>_[XT]:Y--Y/,(

Input format is the list of pendulum positions followed by l on a single line.

Test it here.

Explanation

l~     e# Read and evaluate input.
:X     e# Store track length in X.
fe<    e# Clamp each position to X from above.
0f>    e# Clamp each position to 0 from below.
_      e# Duplicate.
[XT]   e# Push the array [X 0].
:Y     e# Store it in Y.
-      e# Set subtraction from the clamped input list. This gives all the
       e# intermediate values.
-      e# Another set subtraction. Remove intermediate values from input list.
Y/     e# Split remaining list around occurrences of ...X 0...
,(     e# Count them and decrement. This is the number of times the pendulum
       e# moved from X to 0.


Make two numbers co-prime while preserving their least common multiple Given two positive integers a and b, output two positive integers c and d such that:

c divides a
d divides b
c and d are co-prime
the least common multiple of c and d equals the least common multiple of a and b.

If there are more than one possible answers, you can output only one or all of them.

Test cases:

 a  b  c  d
12 18  4  9
18 12  9  4
 5  7  5  7
 3  6  1  6 or 3 2
 9  9  9  1 or 1 9
 6 15  2 15 or 6 5
 1  1  1  1

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

Jelly, 21 13 bytes
ÆEz®0iṂ$¦€ZÆẸ

Try it online!

If a = 2A · 3B · 5C · … and b = 2α · 3β · 5γ · …, then we compute

c = 2A>α?A:0 · 3B>β?B:0 · 5C>γ?C:0 · …

d = 2A>α?0:α · 3B>β?0:β · 5C>γ?0:γ · …

Now lcm(c, d) = 2max(A>α?A:0, A>α?0:α) · … = 2max(A, α) · 3max(B, β) · … = lcm(a, b)
and gcd(c, d) = 2min(A>α?A:0, A>α?0:α) · … = 20 · 30 · 50 · … = 1.

In other words: start from (c, d) = (a, b). Then, for each prime, divide that prime all the way out of the factorization of either c or d: whichever has the smallest exponent for that prime. (In this implementation, in case of a tie, c loses its exponent.)
So if a = 2250 = 21 · 32 · 53 and b = 360 = 23 · 32 · 51,
then c = 20 · 30 · 53 = 125 and d = 23 · 32 · 50 = 72.
Jonathan Allan golfed down a whopping 8 bytes! Thank you~


Smoothing a pair of arrays Input

Two lists with binary values (list_a, list_b) of equal length=>3.

Output

Two lists with binary values (smoothed_a, smoothed_b) with minimal Forward Difference while keeping the same sum before and after processing sum(list_a) + sum(list_b) == sum(smoothed_a) + sum(smoothed_b).

Forward Difference being the absolute difference between items. For example:

[0, 1, 0] would be sum(abs([1, -1])) => 2
[1, 1, 1] would be sum(abs([0, 0])) => 0

Illustrative test cases

Formatted as (list_a, list_b) => (smoothed_a, smoothed_b)

([0, 0, 1, 0, 0],
 [1, 1, 0, 1, 1])
=>
([0, 0, 0, 0, 0],
 [1, 1, 1, 1, 1])

The sum of both arrays pairs is 5. The forward difference was minimized to 0.

([1, 0, 1, 0, 1],
 [0, 0, 0, 1, 0])
=>
([0, 1, 1, 1, 1],
 [0, 0, 0, 0, 0])

The sum of both arrays pairs is 4. The forward difference was minimized to 1.

Test cases

Formatted as (list_a, list_b): forward_diff => (smoothed_a, smoothed_b): min_diff where (smoothed_a, smoothed_b) are potential solutions.

([0, 0, 1],
 [0, 1, 0]): 3
([0, 0, 0],
 [0, 1, 1]): 1

([1, 1, 1],
 [0, 0, 0]): 0
([1, 1, 1],
 [0, 0, 0]): 0

([0, 1, 0],
 [1, 0, 1]): 4
([0, 0, 0],
 [1, 1, 1]): 0

([1, 1, 1, 1],
 [0, 0, 0, 0]): 0
([1, 1, 1, 1],
 [0, 0, 0, 0]): 0

([1, 0, 1, 1],
 [0, 0, 0, 1]): 3
([1, 1, 1, 1],
 [0, 0, 0, 0]): 0

([1, 0, 0, 1],
 [0, 0, 0, 1]): 2
([1, 1, 1, 0],
 [0, 0, 0, 0]): 1

([1, 1, 0, 1],
 [1, 0, 1, 0]): 3
([1, 1, 1, 1],
 [1, 0, 0, 0]): 1

Jelly, 3 bytes

FṢṁ

Try it online!

Explanation:

Flatten the list
Ṣort the flattened list
ṁold the sorted flatten list in the shape of the input.


Map inputted ASCII characters Be sure to see the other challenge, Reverse ASCII character map!

The ASCII charset (American Standard Code for Information Interchange) is the most widely-used character encoding standard. ASCII codes represent text in computers, telecommunications equipment, and other devices.

Challenge

Your challenge is to print a mapping of the ASCII character set as the user inputs them.  GIF:

After the user enters every ASCII character, the output should look like this:

Mapping

Each character has an assigned position on a 16x6 logical grid, starting with the space character in the top left position, and wrapping such that the digit 0 appears below it.

When printable ASCII input is received, print that ASCII character at its assigned screen location without deleting any of the characters currently onscreen.

Rules

Your program only needs to map out the printable ASCII characters, 0x20 to 0x7E.
Your program must not terminate and continue to map characters to the screen until all printable ASCII characters have been inputted. From here, your program can either terminate or run off into Neverland.
Your program can map characters any way you like, e.g. to a spreadsheet, table, console window, or a graphical window.
No matter how you display the mapping, it must be updated in realtime (as soon as it receives user input).
If your program does not read input silently, it must put the cursor out of the way, so the text won't get in the way of the map.

Help

Here is the pseudocode algorithm I used to generate the GIF:

loop forever
    c = input
    y_coord = c / 16
    x_coord = c - y * 16
    if c is printable
        print c at (x_coord * 2 + 1, y_coord + 1)
    end if
end loop

There may be another way to achieve the required output. You can choose to use my algorithm or your own, but the output must be the same regardless.

Here's a useful ASCII table reference.

Scoring

The answer with the least bytes in each language wins. Have fun!

JavaScript (ES6) + HTML, 114 + 16 = 130 bytes

Saved 16 bytes thanks to @Shaggy

a=Array(96).fill` `;onkeypress=k=>(a[k.key.charCodeAt()-32]=k.key,O.innerText=a.join` `.match(/.{1,32}/g).join`
`)

It's so unbelievably satisfying to just mash the keyboard...


I am passive aggressive and want to insult my boss without him finding out It's been a rough few months at work and I feel like I just want to scream right to my boss' face. I am, however, not one to directly confront people I have a problem with. I also don't want to lose my job.

So here's an idea: I want to be able to insult him, without him ever finding out. And I realized the perfect way: I need some sort of software that encodes an insult inside an otherwise perfectly fine message. And seeing as how he's known to not see forests for trees, I think I know just how:

Write me a program that takes as input a string of unknown length, but containing no line breaks. This will be the raw message I want to send.

If possible, return the string formatted such that the message "DIE IN A GREASE FIRE" makes up the entire left column. With new paragraphs where spaces in between words should go. Now, as I am very angry, it is equally important that every letter is in upper case.

You may not modify the string in any other way, i.e. you may not turn all of the string into upper case characters.

If the string in question cannot be formatted in this way, you are to return the original string. Read input from standard input.

Normal rules apply: No HTTP requests, no consulting Marvin from THGTTG, etc.

Example input:

  Dear Boss, how are things? It has come to my attention that I received
  all the blame for the mishap last Friday. Not just the majority of it.
  Every last bit of it. Is it wrong for me to think that the rest of the
  team were at least in part responsible? After all, all six of us were
  involved from the get-go. Not that I think I should stand without
  blame. Not at all. All I'm saying is this: I do my best. I try hard. I
  improve constantly. And I am constantly taking responsibility.
  Generally speaking, I am very okay with taking full responsibility for
  my actions. But after this spring, it seems I get more than I deserve.
  Remember the Flakenhauser contract? Everything went down just about as
  smooth as one could have hoped. Or so it seemed at first. It was just
  at the very last minute that things fell apart. All of the team agreed
  that it was more akin to a freak accident than sloppy planning or
  mismanaged resources. Still, I - alone - took blame for it. Even
  though I said nothing then, my tolerance level for taking the blame
  took a serious dent then. From that point on, I have felt it necessary
  to always try twice as hard, just to escape scrutiny. And still, here
  we are again. In spite of all my accomplishments. Right where we
  always seem to end up these days. Every single project. It's becoming
  unbearable.

Example output:

  Dear Boss, how are things?
  It has come to my attention that I received all the blame for the mishap last Friday. Not just the majority of it.
  Every last bit of it.

  Is it wrong for me to think that the rest of the team were at least in part responsible? After all, all six of us were involved from the get-go.
  Not that I think I should stand without blame. Not at all.

  All I'm saying is this: I do my best. I try hard. I improve constantly. And I am constantly taking responsibility.

  Generally speaking, I am very okay with taking full responsibility for my actions. But after this spring, it seems I get more than I deserve.
  Remember the Flakenhauser contract.
  Everything went down just about as smooth as one could have hoped. Or so it seemed at first. It was just at the very last minute that things fell apart.
  All of the team agreed that it was more akin to a freak accident than sloppy planning or mismanaged resources.
  Still, I - alone - took blame for it.
  Even though I said nothing then, my tolerance level for taking the blame took a serious dent then.

  From that point on, I have felt it necessary to always try twice as hard, just to escape scrutiny. And still, here we are again.
  In spite of all my accomplishments.
  Right where we always seem to end up these days.
  Every single project. It's becoming unbearable.

This is code golf. Shortest code wins.

CJam, 56 53 bytes

q_"DIEIINAAGGREASEFFIRE"{S@:A+S@+#:BA<AB>}%(!B)*\N*@?

Try it online!

How it works

q_                     Read all input from STDIN and push a copy.
"DIEIINAAGGREASEFFIRE" Push the characters we're searching for in form of a
                       string. We'll try to prepend a linefeed to all of them.
                       Some characters are duplicated to prepend two linefeeds.
{                      For every character C in that string:
  S@                   Push ' ' and rotate the string on the stack on top of it.
  :A                   Save the string (initially the input) in A.
  +                    Prepend the space to A.
  S@+                  Construct the string " C".
  #                    Compute the index of " C" in the modified A.
  :B                   Save the index in the variable B.
  A<                   Push the substring of A up to the index.
  AB>                  Push the substring of A after the index.
}%
(                      Shift the first element of the resulting array.
!                      Compute the logical NOT. This pushes 1 if and only if the
                       array's first element is an empty string, which is true
                       if and only if the input string started with a D.
B)                     Push the last value of B and increment. If the last match
                       was successful and, therefore, all matches were successful,
                       B != -1, so B + 1 != 0.
*                      Compute the product of the two topmost items on the stack.
\                      Swap the resulting Booleanr with the array of substrings.
N*                     Join the array, separating by linefeeds.
@                      Rotate the input string on top of the stack.
?                      Select the joined array if the Boolean is 1 and the input
                       string otherwise.


"Multiply" two strings This was inspired by a function I recently added to my language Add++. Therefore I will submit an  short answer in Add++ but I won't accept it if it wins (it wouldn't be fair)

Don't you hate it when you can multiply numbers but not strings? So you should correct that, right?

You are to write a function or full program that takes two non-empty strings as input and output their multiplied version.

How do you multiply strings? I'll tell you!

To multiply two strings, you take two strings and compare each character. The character with the highest code point is then added to the output. If they are equal, simply add the character to the output.

Strings are not guaranteed to be equal in length. If the lengths are different, the length of the final string is the length of the shortest string. The input will always be lowercase and may contain any character in the printable ASCII range (0x20 - 0x7E), excluding uppercase letters.

You may output in any reasonable format, such as string, list etc. Be sensible, integers aren't a sensible way to output in this challenge.

With inputs of hello, and world!, this is how it works

hello,
world!

w > h so "w" is added ("w")
o > e so "o" is added ("wo")
r > l so "r" is added ("wor")
l = l so "l" is added ("worl")
d < o so "o" is added ("worlo")
! < , so "," is added ("worlo,")

So the final output for hello, and world! would be worlo,!

More test cases

(without steps)

input1
input2 => output

programming puzzles & code golf!?
not yet graduated, needs a rehaul => prtgyetmirgduuzzlesneedsde rolful

king
object => oing

blended
bold => boln

lab0ur win.
the "super bowl" => the0usuwir.

donald j.
trumfefe! => trumlefj.

This is a code-golf so shortest code wins! Luok!

Haskell, 11 bytes

zipWith max

Try it online!

Nothing much to explain.


Ruby, 150 bytes

See revisions for previous byte counts.

->a,b,c,d,e,f,g,h,i,j{l=->s,t=c{Math.log(s,t)};y,z=l[l[g,b]]-d**e+l[h]*i**=j,l[l[a,f]*b**c,g];a>1?f<2?1:b<2||g<2?z>h:c<2||d<2?l[z,h]>i:y==0?a>f:y<0:p}

-10 bytes thanks to @ValueInk

+16 bytes thanks to @RosLuP for bugs.

Try it online.

Compare different base powers-towers (of 'height' five)?

Ungolfed code:

-> a, b, c, d, e, f, g, h, i, j {
    l =-> s, t = c {Math.log(s, t)}
    i **= j
    y = l[l[g, b]] - d ** e + l[h] * i
    z = l[l[a, f] * b ** c, g]
    if a == 1
        return p
    elsif f == 1
        return 1
    elsif b == 1 || g == 1
        return z > h
    elsif d == 1 || c == 1
        return l[z, h] > i
    elsif y == 0
        return a > f
    else
        return y < 0
    end
}

Code breakdown:

l =-> s, t = c {Math.log(s, t)}

This is the base t logarithm, which will be used to reduce the size of the numbers we are comparing. It defaults to base c when only one argument is given.

i **= j
y = l[l[g, b]] - d ** e + l[h] * i
z = l[l[a, f] * b ** c, g]

This updates i = i ** j since i never gets used on it's own, and y is the result of logging b^c^d^e == g^h^i(^j) twice and moving everything to one side. We then let z = l[a, f] * b ** c as the log base g of the log base f of a ** b ** c.

if a == 1
    return p
elsif f == 1
    return 1

1^b^c^d^e = 1 is never greater than f^g^h^i^j, and likewise, a^b^c^d^e is always greater than 1^g^h^i^j = 1 if a != 1. Note that return p returns nil, which is falsey, and return 1 returns 1, which is truthy.

elsif b == 1
    return z > h

If b == 1 or g == 1, then this reduces to comparing a ** b ** c to f ** g ** h, which is done with two logs to both sides.

elsif d == 1 || c == 1
    return l[z, h] > i

This compares a ** b ** c with f ** g ** h ** i by rearranging it as log[log[b ** c * log[a, f], g], h] compared to i. (Recall that i **= j in the beginning and z = log[b ** c * log[a, f], g].)

elsif y == 0
    return a > f
else
    return y < 0
end

This compares the 4 highest powers after logging both sides twice. If they are equal, it compares the base.


Approximate the Dottie number The Dottie number is the fixed point of the cosine function, or the solution to the equation cos(x)=x.1

Your task will be to make code that approximates this constant.  Your code should represent a function that takes an integer as input and outputs a real number.  The limit of your function as the input grows should be the Dottie number.

You may output as a fraction, a decimal, or an algebraic representation of a number.  Your output should be capable of being arbitrarily precise, floats and doubles are not sufficient for this challenge.  If your language is not capable of arbitrary precision numbers, then you must either implement them or choose a new language.

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

Tips

One way of calculating the constant is to take any number and repeatedly apply the cosine to it.  As the number of applications tends towards infinity the result tends towards the fixed point of cosine.

Here is a fairly accurate approximation of the number.

0.739085133215161

1: Here we will take cosine in radians

MATL, 34 30 19 bytes
11 bytes off thanks to Sanchises!
48i:"'cos('wh41hGY$

The last decimal figures in the output may be off. However, the number of correct figures starting from the left increases with the input, and the result converges to the actual constant.
Try it online!
Explanation
For input n, and starting at x=1, this applies the function
              x ↦ cos(x)
with n-digit variable-precision arithmetic n times.
48         % Push 48, which is ASCII for '1': initial value for x as a string
i:"        % Do n times, where n is the input
  'cos('   %   Push this string
  w        %   Swap. Moves current string x onto the top of the stack
  h        %   Concatenate
  41       %   Push 41, which is ASCII for ')'
  h        %   Concatenate. This gives the string 'cos(x)', where x is the
           %   current number
  GY$      %   Evaluate with variable-prevision arithmetic using n digits
           %   The result is a string, which represents the new x
           % End (implicit). Display (implicit). The stack contains the last x


Ants on a Natural Log This is a good beginner challenge and a good time killer.

I only said a -natural- log because the title was too short, this has nothing to do with logarithms.

Given 2 variables:

The number of ants n.
The width of the log w.

Output a log of width w with n ants (Example shown w=3, n=6)

|             |
| \O/ \O/ \O/ |
| -O- -O- -O- |
| /o\ /o\ /o\ |
|  ^   ^   ^  |
|             |
| \O/ \O/ \O/ |
| -O- -O- -O- |
| /o\ /o\ /o\ |
|  ^   ^   ^  |
|             |

A single ant looks like this:

\O/ # Upper-case O
-O- # Upper-case O
/o\ # Lower-case o
 ^

A few ant laws:

Ants may not touch each other nor the edge of the log directly, they
prefer to touch spaces.
Each row of ants must be w wide, with n/w rows of ants.
Ants always need a log, the log width is greater than 0, guaranteed.
Ants also... well, need ants, the number of ants is greater than 0, guaranteed.
Ants are also surprisingly well organized, they will fill a log from left to right, top to bottom; as if they were reading a book.

Ant-xamples

w=3, n=5

|             |
| \O/ \O/ \O/ |
| -O- -O- -O- |
| /o\ /o\ /o\ |
|  ^   ^   ^  |
|             |
| \O/ \O/     |
| -O- -O-     |
| /o\ /o\     |
|  ^   ^      |
|             |

w=1, n=1

|     |
| \O/ |
| -O- |
| /o\ |
|  ^  |
|     |

w=1, n=3

|     |
| \O/ |
| -O- |
| /o\ |
|  ^  |
|     |
| \O/ |
| -O- |
| /o\ |
|  ^  |
|     |
| \O/ |
| -O- |
| /o\ |
|  ^  |
|     |

This is code-golf, the person with the smallest bytecount wins.


Bernardino identifies unaltered dollar words Definition
A dollar word is a word where when each of its letters is given a cent value, from a = 1 to z = 26, and the letters are summed, the result is 100. Here is an example on CodeReview, and here is a list of dollar words I found online.
Input
Input will be alphabetical from a-z, in your one language's text datatypes (arrays are allowed). You do not need to account for any other input - there will be no spaces, apostrophes, or hyphens. You can take as lowercase, uppercase, or a combination. Trailing newlines are allowed.
Output
Output a truthy value if the input is a dollar word, and a falsey value if it is not.
Test Cases
Truthy:
buzzy
boycott
identifies
adiabatically
ttttt

Falsey:
zzz
zzzzzzz
abcdefghiljjjzz
tttt
basic

This is code-golf, so the shortest answer in bytes wins! Standard loopholes and rules apply. Tie goes to first poster.

Python, 39 38 bytes

lambda s:sum(ord(i)-96for i in s)==100

Try it online!

-1 byte thanks to @JonathanAllan


Is it a Munchausen Number? A Munchausen Number in base \$b\$, also known as a Perfect digit-to-digit invariant or PDDI is a peculiar type of positive integer where the sum of its base-\$b\$ digits raised to themselves is equal to the number itself. They are named for the fictional Baron Munchausen, who apparently hoisted himself up via his own ponytail to save himself from drowning. A related concept is Narcissistic numbers.

For instance, \$1\$ is trivially a Munchausen number in every base because \$1^1=1\$. Additionally, every positive integer is a base-1 Munchausen number by definition.

More interestingly, \$3435\$ is a base-10 Munchausen number because \$3^3+4^4+3^3+5^5=3435\$, and in fact is the only other base-10 Munchausen number.

A partial list of Munchausen numbers in every base up to 35 can be found on the OEIS as sequence A166623.

Given a positive integer \$n>0\$, determine if it is a Munchausen number in any base \$b\geq2\$.

Rules

Default I/O rules apply, so:

Full program or functions are acceptable.
Input can be from STDIN, as a function argument, and output can be to STDOUT, as a function return value, etc.

Default loopholes apply.
The output must be one of two distinct, consistent results. So TRUE is fine for truthy and FALSE is fine for falsy, but you can reverse that or return None for truthy and 1 for falsy or whatever. Please specify the selected results in your answer.
Your answer has to work at least theoretically for any positive integer.
Munchausen numbers use the convention \$0^0=1\$, so \$2\$ is a base-2 Munchausen number as \$1^1+0^0=2\$. Your code must follow this convention.
Explanations are strongly encouraged, even though submissions will most likely use the brute-force search method.
Using esoteric languages earns you brownie points since Munchausen was apparently a strange person.

Test Cases

Truthy
1 (all bases)
2 (base 2)
5 (base 3)
28 (base 9 and base 25)
29 (base 4)
55 (base 4)
3435 (base 10)
923362 (base 9)
260 (base 128)
257 (base 64 and base 253)

Falsy
3
4
591912
3163
17

This is code-golf, so the shortest answer in each language (in bytes) wins!

05AB1E, 7 bytes

LвDmOQZ

Try it online!

The larger test cases will time out on TIO.

Explanation

L         # push range [1 ... input]
 в        # convert input to a digit list in each of these bases
  Dm      # raise each digit to the power of itself
    O     # sum each
     Q    # check each for equality with input
      Z   # max


Factor a polynomial over a finite field or the integers Without using any built-in factoring/polynomial functions, factor a polynomial completely into irreducibles over the integers or a finite field.
Input
Your program/function will receive some prime (or zero) number n as input. The field/ring is the finite field of that order (ie Z/nZ), or just Z if n is 0. Your program may fail if n is not 0 or a prime. The polynomial will be in F[x].
Your program/function will also receive the polynomial as input.
There is some flexibility in the input, be sure to specify how you intend to receive input. For example, the polynomial could be input as a list of coefficients, or in the form most people expect (ex:50x^3 + x^2), or some other reasonable form. Or the format of inputting the field/ring could also be different.
Output
Your program/function will output the polynomial factored completely. You may leave multiple roots expanded (ie (x + 1)(x + 1) instead of (x + 1)^2). You may remove whitespace between binary operators. You may replace juxtaposition with *. You may insert whitespace in weird places. You may reorder the factors into whatever order you want. The x term could just be (x). x can be written as x^1; however the constant term may not have x^0. Extraneous + signs are allowable. You may not have a term with a 0 in front, they must be left out. The leading term of each factor must be positive, negative signs must be outside.
Test cases, your program should be able to produce output for each of these in reasonable time (say, <= 2 hours):
Input: 2, x^3 + x^2 + x + 1
Output: (x + 1)^3
Input: 0, x^3 + x^2 + x + 1
Output: (x + 1)(x^2 + 1)
Input: 0, 6x^4 – 11x^3 + 8x^2 – 33x – 30
Output: (3x + 2)(2x - 5)(x^2 + 3)
Input: 5, x^4 + 4x^3 + 4x^2 + x
Output: x(x + 4)(x + 4)(x + 1)

Input: 0, x^5 + 5x^3 + x^2 + 4x + 1
Output: (x^3 + 4x + 1)(x^2 + 1)
Special thanks to Peter Taylor for critiquing my test cases

GolfScript (222 bytes)

~.@:q@.0\{abs+}/2@,2/)?*or:^{\1$^base{^q- 2/-}%.0=1=1$0=q>+{{:D[1$.,2$,-)0:e;{.0=0D=%e|:e;(D(@\/:x@@[{x*~)}%\]zip{{+}*q!!{q%}*}%}*e+])0-{;0}{@;@\D.}if}do}*;\).^3$,)2/?<}do;][[1]]-{'('\.,:x;{.`'+'\+'x^'x(:x+x!!*+\!!*}%')'}/

Online demo

Notes

The input format is n followed by a GolfScript array of coefficients from most to least significant. E.g. 0, x^5 + 5x^3 + x^2 + 4x + 1 should be formatted as 0 [1 0 5 1 4 1].
Over a finite field, there are only finitely many polynomials of sufficiently small degree to be relevant. However, this is not the case over Z. I handle Z by using a relaxed form of Mignotte's height bound. A great paper on height bounds in factoring is Bounds on Factors in Z[x], John Abbott, 2009 (link is to arxiv preprint; his CV says that it has been accepted by the Journal of Symbolic Computation). The most relaxed form given there is in terms of the L-2 norm, but to save bytes I relax further and use the L-1 norm instead. Then it's a case of brute forcing by trial division.
Over a finite field, every polynomial is a constant times a monic polynomial, so I only do trial division by monic polynomials and save a reciprocal in the field. However, Z is only a ring and so it's necessary to do trial division by non-monic candidate factors. I manage to get away with not implementing rational numbers by doing a leading factor division test and accumulating an "error" flag in e.
Both points 2 and 3 imply that the case of factoring over Z is generally slower, and can't be tested with the online demo. However, the slowest of the official test cases takes 10 minutes, which is well within the "reasonable" time limit.


Alphabet Position Finder Inspired by the Codewars Kata.

Your goal is to take an input string such as this one:

"'Twas a dark and stormy night..."

and return a string containing the position of each character in the alphabet, separated by spaces and ignoring non-alphabetical characters, like this:

"20 23 1 19 1 4 1 18 11 1 14 4 19 20 15 18 13 25 14 9 7 8 20"

For an additional challenge, you can replace any numerical characters in the original string with themselves + 27. For example, "25" would become "29, 32". This is completely optional.

You must use 1-indexing ('a'==1, 'b'==2, etc)

Additional rules:

You must return a string, not an array.
Trailing whitespace is OK.

The winner has the lowest byte count.

Good luck!

05AB1E, (5?) 7 bytes
Rightmost two bytes are output formatting
áÇ32%ðý

A port of my Jelly answer, but O5AB1E is more terse for the alphabet filtering.
Try it online!
How?
áÇ32%ðý - take input implicitly
á       - filter keep alphabetical characters
 Ç      - to ordinals
  32    - thirty-two
    %   - modulo (vectorises)
     ð  - push a space character
      ý - join


Let's play Peg Solitaire Peg solitaire is a popular game usually played alone. The game consists of some number of pegs and a board which is divided into a grid - usually the board is not rectangular but for this challenge we will assume so.

Each valid move allows one to remove a single peg and the goal is to play in a way, such that there is a single peg left. Now, a valid move has to be in a single direction (north, east, south or east) and jump over one peg which can be removed.

Examples

Let . be empty spaces on the board and numbers are pegs, the following move will move 1 one to the right and remove 2 from the board:

.....     .....
.12..  -> ...1.
.....     .....

A move will always have to jump over a single peg, so the following is not valid:

......    ......
.123.. -> ....1.
......    ......

Here are some valid configurations after one move each:

...1...        ...1...        ..71...        ..71...
.2.34.5  --->  .24...5  --->  .2....5  --->  ......5
.678...  (4W)  .678...  (7N)  .6.8...  (2S)  ...8...
.......        .......        .......        .2.....

Challenge

Given an initial board configuration and some other configuration, output whether the other configuration can be reached by successively moving pegs around as described above.

Rules

Input will be a \$n \times m\$ matrix/list of lists/... of values indicating an empty space (eg. zero or false) or pegs (eg. non-zero or true)

you may assume \$n \geq 3\$ and \$m \geq 3\$
you may use true/non-zero to indicate empty spaces and vice-versa if it helps

Output will be two distinct (one of the values might differ) values indicating whether the end-configuration can be reached (eg. falsy/truthy, []/[list of moves] ..)

Test cases

initial  goal -> output
[[1,0,0],[1,1,0],[0,1,0]]  [[0,0,0],[0,1,0],[1,1,0]] -> True
[[1,0,0],[1,1,0],[0,1,0]]  [[0,0,1],[0,1,1],[0,0,0]] -> False
[[0,0,0],[1,0,0],[0,0,0]]  [[0,0,0],[0,0,1],[0,0,0]] -> False
[[0,0,0],[1,1,0],[0,0,0]]  [[0,0,0],[0,1,1],[0,0,0]] -> False
[[0,0,0,0],[1,1,1,0],[0,0,0,0]]  [[0,0,0,0],[0,0,0,1],[0,0,0,0]] -> False
[[1,0,0],[1,1,0],[1,1,1],[1,1,1]]  [[0,0,1],[0,1,0],[1,0,0],[0,0,1]] -> True
[[1,0,0],[1,1,0],[1,1,1],[1,1,1]]  [[1,0,0],[0,0,0],[0,0,0],[0,0,0]] -> False
[[1,0,1,1],[1,1,0,0],[1,1,1,0],[1,0,1,0]]  [[0,0,1,0],[1,0,0,0],[1,0,1,0],[1,0,0,1]] -> True
[[1,0,1,1],[1,1,0,0],[1,1,1,0],[1,0,1,0]]  [[0,0,0,0],[0,0,0,0],[0,0,1,0],[0,0,0,0]] -> False
[[1,0,0,0],[1,1,0,0],[1,1,1,0],[1,0,1,0]]  [[0,0,0,0],[0,0,0,0],[0,0,1,0],[0,0,0,0]] -> True
[[0,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,0]]  [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,1]] -> False
[[0,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,0]]  [[1,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]] -> False
[[0,0,0,1,0,0,0],[0,1,0,1,1,0,1],[0,1,1,1,0,0,0],[0,0,0,0,0,0,0]]  [[0,0,0,1,0,0,0],[0,1,0,1,1,0,1],[0,1,1,1,0,0,0],[0,0,0,0,0,0,0]] -> True
[[0,0,0,1,0,0,0],[0,1,0,1,1,0,1],[0,1,1,1,0,0,0],[0,0,0,0,0,0,0]]  [[0,0,0,1,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,0,0]] -> True
[[0,0,1,1,1,0,0],[0,0,1,1,1,0,0],[1,1,1,1,1,1,1],[1,1,1,0,1,1,1],[1,1,1,1,1,1,1],[0,0,1,1,1,0,0],[0,0,1,1,1,0,0]]  [[0,0,1,1,1,0,0],[0,0,1,1,1,0,0],[1,1,1,1,1,1,1],[1,1,1,1,0,0,1],[1,1,1,1,1,1,1],[0,0,1,1,1,0,0],[0,0,1,1,1,0,0]] -> True
[[0,0,1,1,1,0,0],[0,0,1,1,1,0,0],[1,1,1,1,1,1,1],[1,1,1,0,1,1,1],[1,1,1,1,1,1,1],[0,0,1,1,1,0,0],[0,0,1,1,1,0,0]]  [[0,0,0,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,1,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,0,0]] -> True

JavaScript (ES6),  184 178  173 bytes
Takes input as (initial_board)(target_board). Returns \$0\$ or \$1\$.

a=>g=b=>a+''==b|a.some((r,y)=>r.some((v,x,A,X,R)=>[-1,0,1,2].some(h=>(A=a[y+(R=~-h%2)]||0)[X=x+(h%=2)]&v>(R=a[y+R*2]||0)[h+=x+h]&&g(b,A[X]=r[x]=R[h]++)&(A[X]=r[x]=R[h]--))))

Try it online!
(removed the last two test cases that take too much time for TIO)
Commented
a =>                             // main function taking the initial board a[]
  g = b =>                       // g = recursive function taking the target board b[]
    a + '' == b |                // yield a truthy result if a[] is matching b[]
    a.some((r, y) =>             // for each row r[] at position y in a[]:
      r.some((v, x, A, X, R) =>  //   for each value v at position x in r[]:
        [-1, 0, 1, 2]            //     list of directions (West, North, East, South)
        .some(h =>               //     for each direction h:
          ( A =                  //       A = a[y + dy]
            a[y + (R = ~-h % 2)] //       R = dy
            || 0                 //       use a dummy row if we're out of the board
          )[X = x + (h %= 2)]    //       h = dx, X = x + dx
          &                      //       yield 1 if there's a peg on the skipped cell
          ( R =                  //       R = target row
            a[y + R * 2]         //         = a[y + 2 * dy]
            || 0                 //       use a dummy row if we're out of the board
          )[h += x + h]          //       h = x + 2 * dx = target column
          < v                    //       yield 1 if there's no peg on the target cell
          &&                     //       and there's a peg on the source cell (0 < 1)
          g(                     //       if the above result is true, do a recursive call:
            b,                   //         pass b[] unchanged
            A[X] = r[x] =        //         clear the source and skipped cells
            R[h]++               //         set the target cell
          ) & (                  //       and then restore the board to its initial state:
            A[X] = r[x] =        //         set the source and skipped cells
            R[h]--               //         clear the target cell
          )                      //
        )                        //     end of some() over directions
      )                          //   end of some() over columns
    )                            // end of some() over rows


Python 2, 32 bytes

exec"print'x'"+".join('{^_}')"*5

Try it online!


Ninja Assassins - which ninja stays alive? Ninja Assassins - which ninja stays alive

some basic information

given an int N as the number of ninjas, return the number of the winning ninja.
At the end only 1 ninja survives,the question is which one? what was his number?.
Each ninja kills the ninja who stands after him. Afterwards, he passes the sword to the first alive ninja who stood after the killed one.

Explenation - How the Game Works

The ninjas are numbered from 1 to N and stand in a circle according to the numbers. The circle goes clockwise: ninja 2 is left to ninja 1, ninja 3 is left to ninja 2, ninja 4 is left to ninja 3.... ninja 1 is left to ninja N.
Ninja 1 gets a sword and the game begins:
Each ninja (starting from ninja 1) kills the closest and alive ninja he has to the left (clockwise) . Afterwards, he passes the sword to the 2nd closest and alive ninja he has to the left.The 2nd ninja does the same (kills and passes) (as an example: N=3(we have 3 ninjas), ninja 1 kills ninja 2 and gives the sword to ninja 3. Ninja 3 has ninja 1 as his closest and alive ninja to the left(clockwise - its a circle) so he kills ninja 1, stays the last ninja alive and wins (so the output\return is 3, as the number of the ninja)).
A more detailed example below

Example - Word-detailed scenario

N = 7 (we got 7 ninjas) :

1 2 3 4 5 6 7 (L=alive, D=dead)
L D L L L L L The first ninja gets the sword and kills the 2nd ninja.
              The first ninja passes the sword to the 3rd ninja.
L D L D L L L The 3rd ninja gets the sword and kills the 4th ninja.
              The 3rd Ninja passes the sword to the 5th ninja.
L D L D L D L The 5th ninja gets the sword and kills the 6th ninja.
              The 5th Ninja passes the sword to the 7th ninja.
D D L D L D L The 7th ninja gets the sword and kills the first(1st) ninja.
              The 7th ninja passes the sword to the 3rd ninja.
D D L D D D L The 3rd ninja gets the sword and kills the 5th ninja.
              The 3rd ninja passes the sword to the 7th ninja.
D D D D D D L The 7th ninja gets the sword and kills the 3rd ninja,
              stays as the last one alive and wins (the final result /
              the output is 7).

More scenarios without words

N=3 : 1 2 3 - 1 3 - 3 wins
N=4 : 1 2 3 4 - 1 3 - 1 wins
N=5 : 1 2 3 4 5 - 1 3 5 - 3 5 - 3 wins
N=6 : 1 2 3 4 5 6 - 1 3 5 - 1 5 - 5 wins
N=7 : 1 2 3 4 5 6 7 - 1 3 5 7 - 3 7 - 7 wins

Scoring is based on the least number of bytes used, as this is a code-golf question.

Python 2, 30 bytes

lambda n:int(bin(n)[3:]+'1',2)

Takes the binary expansion of n and moves the initial 1 to the end.


Unvisualize Parsons code Introduction

The Parsons code is just a simple way to describe pitch variations in a piece of music, whether a note is higher or lower than the previous one.

Even if you suck at remembering tunes, you can still pretty much remember if a note goes up or down, thus the Parsons code can help you to identify a music using a search engine.

Description

Each variation is represented by a single character, which is one of the following:

R if the note is the same than the previous one (stands for "Repeat")
U if the note is higher than the previous one (stands for "Up")
D if the note is lower than the previous one (stands for "Down")

The initial note is written as *.

Example

Here is an example of Parsons code (beginning of "Ode to Joy"):

*RUURDDDDRUURDR

You can actually visualize it, like this:

      *-*
     /   \
    *     *
   /       \
*-*         *         *-*
             \       /   \
              *     *     *-*
               \   /
                *-*

We'll call that a contour from now on.

The rules for drawing such countours are considered self-explained by the above example.

Challenge

Now comes the real challenge.

Write a program that, given a contour as input, outputs its corresponding Parsons code.

You are not asked to draw the contour, but the opposite actually.
From the contour, find the original Parsons code.

Rules

The usual rules for code golfing apply
The shortest program in number of bytes wins
The input is a contour, and the output shall be a valid Parsons code
Details about extra whitespace for the input are irrelevant, do whatever works best for you
You are not allowed to hardcode, one way or another, parts of the output and / or the program using extra whitespace because of the previous rule

Notes

This might be useful for testing
The corresponding Parsons code for * is *
An empty string is not a valid contour
A Parsons code always starts with *

CJam, 21 bytes
qN/:.e>(o2%:i"DRXU"f=

Fold the lines (:) by vectorizing (.) a character-wise maximum operation e>. Since there is only one non-space character in each column, this one will be the result, as space has a smaller ASCII code than all printable non-space characters.
Unshift and print the first asterisk (o, then map every other (2%) remaining char to UDR using modular indexing.
Old solution (29 bytes)
'*qN/z2%'*f#0+2ew);::-"RDU"f=

qN/ gets input lines. z transposes this character matrix. 2% drops every odd row. '*f# finds the index of the asterisk in each row. 0+2ew); gets all successive pairs of indices. ::- computes their differences, and "RDU"f= maps them to letters (via modular indexing: 0 → R, 2 → U, -2 ≡ 1 → D). The leading '* prepends the asterisk.
EDIT: I changed 2ew to 0+2ew); to work around CJam not handling ew (successive slices) on lists that are too short. This makes the code work for the input string *.
Try it here, or watch it in action:


Guess my password (cops' thread) Inspired by this challenge, which got closed. This is meant to be an easier, but no less interesting version of that.
This is the cops thread of a cops-and-robbers challenge. For the robbers thread, see here.
Cops will provide a program/function and a flag. Robbers will try to guess a password such that, when the password is given to the cop's program, the flag is outputted.
Basic rules

The language used should be provided.
The flag, which can be an integer, string, or value of any other type, should be provided.
The flag may be printed to STDOUT, returned from a function, or outputted using any of the other standard output methods, as long as you specify how it will be outputted.
The program/function can take the password through STDIN, as a function argument, or using any of the other standard input methods, as long as you specify how the it will be inputted.
A free online compiler/interpreter should also be linked, preferably with the cop's code already pasted in and ready to run.

Some more rules

There must be at least one valid password that causes your program to return the flag, and you should know at least one of those passwords when posting your answer.
In case of a function submission, the cop should also include a full runnable program including the function either in the answer or in the linked online compiler/interpreter.
If it is at all ambiguous what the type of the flag is, it must be specified.
If a cop's description of the output is ambiguous (e.g. "HashSet(2, 1) should be printed"), robbers are allowed take advantage of that (e.g. print the string "HashSet(2, 1)" instead of an actual hashset)
Forcing robbers to simply brute force the password is not allowed.
The program must take input, and must output the flag when given the correct password. When not given the correct password, you are free to error, output something else, or immediately terminate. If your program never halts if given the wrong password, you must tell robbers of this behavior so no one waits around for the program to output something.

Cops's score will be the number of bytes their code takes up.
Cop answers will be safe if they haven't been cracked for two weeks.
Example
Cop:

Scala, 4 bytes
x=>x

Flag: Yay, you cracked it! (an object of type String is returned from the lambda above)
Try it online!

Robber:

Password: the string "Yay, you cracked it!"
Try it online!

Find Uncracked Cops

PHP, 89 bytes, cracked by Benkerd22

<?php
$x=file_get_contents('php://stdin');
if(!preg_match('/.*golf.*/',$x))echo trim($x);

Try it online!
Outputs golf, exactly.


Write the shortest text getter/setter on an element for the DOM Just like jQuery's $.fn.text, write one or two functions that can get and set the text on an element.

You can't use textContent or innerText, and even less innerHTML.

Plain javascript. No DOM library. It has to work on major browsers. (No need to care about old IE.)

Shortest code wins.

Enjoy!

JavaScript (167)

function t(e,h,f){if(h||h==''){while(f=e.lastChild)e.removeChild(f);e.appendChild(document.createTextNode(h))}h=e.data||'';for(c in f=e.childNodes)h+=t(f[c]);return h}

Usage :

var textContent = t(yourElement); // get the text content
t(yourElement, ''); // clear
t(yourElement, newText); // sets a new text

Note that there is no pollution of the global namespace

Demonstration, with a multi-level DOM tree and a few tests


The fastest square root calculator Write a program which outputs the square root of a given number in the shortest time possible.

Rules

It may not use any builtins or powering with non-integers.

Input format

as a function argument
as a command line argument
as a direct input on stdin or a window

Your entry hasn't to be a complete program, it may be a function or a snippet.
It doesn't need to be exact; a one percent margin of error is allowed.
The test cases will only be positive integers, but your program should output/return floats.
It may return the square root as function return value, print it to stdout or write in a consistent file, which is readable by the user..Each program should specify the compiler/interpreter it should be run on and compiler flags. If they aren't specified, I'll use the following implementations: (just talking about mainstream langs):

C/C++: gcc/g++ on Linux, no flags
Java: OpenJDK on Linux, no flags
Python: CPython
Ruby: MRI
Assembler: x86 Linux
JS: Node.js

Examples

Input    Output
4        2 (or something between 1.98 and 2.02)
64       8 (between 7.92 and 8.08)
10000    100 (between 99 and 101)
2        bewteen 1.40001 and 1.428

Scoring

Your programs on the same computer with same conditions (Terminal and Iceweasel with this tab open).
This question has the tag "Fastest code", so the program, which calculates the square root of a (not yet given) random integer between 1 and 10^10 as fast as possible will win!

C

Since input is limited to positive integers between 1 and 1010, I can use a well-known fast inverse square root algorithm to find the inverse square root of the reciprocal of the input.

I'm not sure what you mean by "only Xfce and the program and a terminal running" but since you stated that functions are acceptable, I provide a function in C that will take an integer argument (that will be casted to float automatically) and outputs a float as the result.

float f(float n) {
    n = 1.0f / n;
    long i;
    float x, y;

    x = n * 0.5f;
    y = n;
    i = *(long *)&y;
    i = 0x5f3759df - (i >> 1);
    y = *(float *)&i;
    y = y * (1.5f - (x * y * y));

    return y;
}

The following is a program that makes uses of the function above to calculate the square roots of the given test cases and compares them to the values given by the sqrtf function in math.h.

Ideone


Determine if Strings are equal Your task is simple. Determine if one string equals the other (not address, the value) without the use of equality operators (such as ==, ===, or .equal()) or inequality (!=, !==) anything similar for other languages. This means anywhere! You may not use these operators anywhere in the code. You may however, you use toggles such as !exp as you're not directly comparing the exp != with something else.

In addition, you may not use any functions such as strcmp, strcasecmp, etc.

As for comparison operators (>=, <=, >, <), they are also disallowed. I realize that some answers include this, but I'd really like to see more answers that don't borderline the equality operator.

An example using PHP is shown:

<?php

$a = 'string';
$b = 'string';

$tmp = array_unique(array($a, $b));

return -count($tmp) + 2;

Simply return true or false (or something that evaluates in the language to true or false like 0 or 1) to indicate if the strings match. The strings should be hardcoded seen in the above example. The strings should not be counted in the golf, so if you declare the variable before hand, don't count the declaration.

Python 49 45 18 22 15 14
( + 3 if string variables are considered)
print{a:0,b:1}[a]

The string should be hard coded at the two occurrences of a and one occurrence of b surrounded by quotes.
a and b should be pre-initialized to the strings.

Python shell, 9
( + 3 if string variables are considered)
{a:0,b:1}[a]

Output in shell
>>> a = 'string'
>>> b = 'string'
>>> {a:0,b:1}[a]
1
>>> a = 'string'
>>> b = 'stringgg'
>>> {a:0,b:1}[a]
0
>>> {'string':0,'string':1}['string']
1
>>> {'stringggg':0,'string':1}['stringggg']
0
>>>

Explanation
Creates a dict(hash table) with the key of first and second string.
If second string is the same, the value of first is replaced by that of second.
Finally, we print the value of first key.
EDIT: OP allowed 0/1 instead of False/True as well as using pre-initialized variables.


Follow the Path, but is it valid? Follow the Path

I got directions to my friend's house, but it looks like his map might have some mistakes. He's expecting me soon, so I need some short code to figure out if I can get there.

The Challenge

The code should, when given an ASCII representation of a path as input, traverse from the start to the end, and output depending on whether there is a valid path.

Input

Input is an ASCII representation of a map. It will use only the following symbols:

Character = Meaning
(space) = Blocked area
| = Vertical Path
- = Horizontal Path
+ = Intersection
^ or v = Horizontal Bridge
< or > = Vertical Bridge
$ = Start Location
# = End Location

Traversal Rules

Execution always starts on $ and will end when all paths are blocked, an infinite loop, or the pointer hits #. It is guaranteed that input will have exactly 1 of each.
The pointer starts moving to the right and down.
Vertical paths will only connect to vertical paths, vertical bridges, or intersections.
Horizontal paths will only connect to horizontal paths, horizontal bridges, or intersections.
If a vertical and horizontal path meet at a non-bridge, it is considered blocked at that point.
Bridges function according to the following:

 |      |
-^- OR -v- = Horizontal path going over a vertical path
 |      |

 |      |
-<- OR ->- = Vertical path going over a horizontal path
 |      |

When the pointer hits an intersection, movement precedence is in the clockwise direction (up, right, down, left). The pointer will not go back the way it came.
The program must detect/calculate infinite loops and branching paths from +.

Output

The length of the path, or -1, according to the following conditions:

If the program reaches #, output the path length.
If the program detects only blocked paths, return -1.
If the program detects an infinite loop, return -1.

Scoring

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

Test Cases

   $
   |
 +-|
#+-+
= 6 (going north at `#+-` will lead to a blocked path, but going to the west is a valid path)

#-+-+
  | |
$-^-+
  +-+
= -1 (Will infinitely loop)

$#
= 1

#^^^^+
     >
$----^-+
     > +
     +-+
= 20

$------+
|-----+|
 --#--+|
+--+---+
+------+
= 23

$ #
= -1 (Blocked by the space)

$|#
= -1 (Can't go onto a vertical path from the sides)

$
-
#
= -1 (Can't go onto a horizontal path from the top or bottom)

$|#
|--|
++++
= -1 (No valid paths exist)

JavaScript (ES6), 219 bytes
Takes input as a list of lists of characters.
a=>((g=(X,Y,D,n=o=0)=>!(a+0)[n++]|a.some((r,y)=>r.some((c,x)=>D=='975'[i='-| #+$'.indexOf(c),x-X+1]-'450'[y-Y+1]?i-3?i-2?i>3?[3,0,7,4].some(d=>D^d^4&&g(x,y,d,n)):~i&&i^D&1?0:g(x,y,D,n):0:o=-n:X+1|i<5?0:g(x,y,2))))(),~o)

Try it online!
How?
Because they need to be tried in a specific order, the way the directions are handled in this code is a bit unusual.
Given a direction \$D\$ and the source coordinates \$(X,Y)\$, we want to figure out which target coordinates \$(x,y)\$ correspond to a move by one square along \$D\$.
We use the following test for each candidate pair \$(x,y)\$:
D == '975'[x - X + 1] - '450'[y - Y + 1]

This test always fails if \$|x-X|>1\$ or \$|y-Y|>1\$ because we get an undefined value from at least one of the 2 lookup strings.
Otherwise, we have the following table:
$$\begin{array}{r|c|ccc}
&x-X&-1&0&+1\\
\hline
y-Y&&9&7&5\\
\hline
-1&-4&5&3&1\\
0&-5&4&2&0\\
+1&-0&9&7&5
\end{array}$$
Because diagonal moves are not used, our final compass looks as follows:
$$\begin{array}{cccc}
&&3\\
&&↑\\
4&←&2&→&0\\
&&↓\\
&&7
\end{array}$$
The lookup values were chosen in such a way that we end up with some handy properties:

Opposite directions can be detected by testing if \$d\operatorname{xor}d'=4\$. Hence the code to try all directions in clockwise order except the one that would make us going back the way we came:
    [3, 0, 7, 4].some(d => D ^ d ^ 4 && g(x, y, d, n))

Vertical moves are connected to odd values.

Horizontal moves are connected to even values (except direction \$2\$, for no move at all, which is only used at the beginning of the process when the starting point has been identified).


Count of relatively prime partitions The partitions of an integer N are all the combinations of integers smaller than or equal to N and higher than 0 which sum up to N.
A relatively prime partition is an integer partition, but whose elements are (overall) coprime; or in other words, there is no integer greater than 1 which divides all of the parts.
Task
Given an integer as input, your task is to output the count of relatively prime partitions it has. Rather not surprised that there is an OEIS sequence for this. The aim is to shorten your code as much as possible, with usual code golf rules.
Also, you don't have to worry about memory errors. Your algorithm must only theoretically work for an arbitrarily big values of N, but it is fine if your language has certain limitations. You can assume that N will always be at least 1.
Test cases and Example
Let's take 5 as an example. Its integer partitions are:
1 1 1 1 1
1 1 1 2
1 1 3
1 2 2
1 4
2 3
5

From this, the first 6 only are relatively prime partitions. Note that the last one (formed by the integer in question only) must not be taken into account as a relatively prime partition (except for N=1) because its GCD is N.
N -> Output

1  -> 1
2  -> 1
3  -> 2
4  -> 3
5  -> 6
6  -> 7
7  -> 14
8  -> 17
9  -> 27
10 -> 34


Is this word Lexically Ordered? Given an input string S, return truthy if all the letters in S are Lexically Ordered: their ASCII values need to be in either ascending or descending order. Return falsy in other cases.
Input

Input will be in the same case (all upper- or all lowercase). Your submission should be able to handle both.
Input will consist of ASCII in the range [A-Za-z] only
Input length will be at least 1, up to whatever maximum your language supports.
Input is a string - not a list of characters, not an array of ASCII-codepoints.

Output

Output should be true or false, or 0/1, or any other distinct true / false style output your language can provide.
All true cases need to have the same output, as well as all the false cases. No "False is 0, true is 1, 2, or 3".

Additional rules

Standard loopholes are forbidden
Answer must be a full program or a function, not a snippet or a REPL-entry.
code-golf, shortest answer in bytes wins.

Test cases
Truthy
"ABCDEF"
"ZYX"
"no"
"tree"   --> the multiple 'e's don't break the order
"q"

Falsy
"ABCDC"
"yes"
"deed"

Invalid
"Hello" --> invalid input - mixed case-, does not have to be handled
""      --> invalid input - length 0-, does not have to be handled
"\n
  "     --> invalid input - newline is not in range [A-Za-z]-, does not have to be handled

Python 2, 53 44 40 39 bytes

lambda a:`sorted(a)`[2::5]in(a,a[::-1])

Try it online!


Wrong keyboard position You are in fact writing an interpreter for the language "Wrong keyboard position". You can pretend that you are not doing this and just follow the instructions below.

I typr re;atively accuratrly, but so,etimes I made a whole nlock of text illegible by shifting a key right. So I need a program that corrects my text back to its original meaning.

Rules

You have to left shift on a standard English QWERTY keyboard.
Whitespace do not count for the procedure before left-shifting and are kept as-is in a standard left-shifting procedure. If the key is the leftmost letter/symbol on a keyboard(i.e. The ~key, Q key, A key, Z key.), the key is kept as-is. If you reach a control character while left-shifting (Caps lock and Shift), their effects will not be triggered and the character before left-shifting is kept.
This is a code-golf contest; the shortest answer wins.
Both the input and the output shall be given via our default methods.

Representation of a subset of the QWERTY keyboard that you will need

The two lines connected are possible values of the key: shifted/unshifted.

~!@#$%^&*()_+
`1234567890-=

QWERTYUIOP{}|
qwertyuiop[]\

ASDFGHJKL:"
asdfghjkl;'

ZXCVBNM<>?
zxcvbnm,./

(Space)
(Space)

Input

The input will always be a non-empty string conforming the rules above.

Output

The output will be the input string corrected to the originally intended meaning.

Examples:

Yjod ,sfr yjr, imjsppu/ -> This made them unhaooy.
vpfr hp;g -> code golf

05AB1E, 59 bytes

-1 byte thanks to Kevin Cruijssen

žVDu«1ú`žhÀ“~!@#$%^&*()_+ `ÿ-=ÿ<>?ÿ:"ÿ{}|ÿ,./ÿ;'ÿ[]\“#vy¦y‡

Try it online!


Pixel art, episode 2: Display the map 1-1 of Super Mario Bros Last challenge (Pixel-art, episode 1: display Super Mario) was just a training... (and you completed it in amazing ways, thanks!)

This time, you have to work a little bit more. You have to display all the first overworld map of Super Mario bros on NES, without enemies, and without Mario.

Your program or function must display all the pixels of the following image OR produce an image file similar to it (BMP, PNG, or GIF).

Your program must not access the internet in any way.

The output can be zoomed if you want, and the pixels can be ASCII or HTML elements if you want, as long as they have the right color.

Here's the model you have to follow:

The whole image: http://i.stack.imgur.com/2kfVc.png

The tileset (if you need it): http://img.ctrlv.in/img/14/10/19/5443f44c7eb78.png

You can produce your own tileset, subset or superset of this one.
You can use your tileset as a separate image file or include it in your code (for example, in base64). If it's separate, add its size in bytes to your score.
The map with coordinates: http://goo.gl/c8xJIx or http://img.ctrlv.in/img/14/10/19/544373adc9f64.png

The colors:

Sky blue: #5C94FC
Black: #000000
Pink: #FCBCB0 (for the blocks and the castle)
Brown: #C84C0C (for the blocks and the castle)
Orange: #FC9838 (for the "?" block)
Light green: #80D010 (for bushes, mountains, flagpole, warp)
Dark green: #00A800 (for bushes, mountains, flagpole, warp)
White: #FCFCFC (clouds)
Light blue: #3CBCFC (clouds)

Shortest answer wins.

EDIT: There will be two score boards, one where scores are counted in bytes and one where they are counted in characters.

Good luck!

P.S: Here are some notes that could help you optimizing your program:

Clouds, bushes and mountains have a repeating pattern (every 48 columns)
Flying blocks are only present on lines 4 and 8
Each tile or sprite of the map uses at most 4 colors (including blue or transparent, depending on how you see it)
Bushes are just "top of clouds" with a diferent color palette
Single, double and triple bushes/clouds can easily be formed using the same mini set of 16x16px pieces. This is also true for the single and triple mountains

x86 Machine Code, 1729 1619 1468 1382 Bytes

How it works: Tiles are generated by a combination of RLE compression, 2bit images, and procedural code. Once the tiles are generated in memory, the program then creates a matrix of tile indexes. This is first loaded with the repeating background. After that, the pipes, floating blocks, pyramids, and the flag pole are drawn procedurally. The pipes, hills, bushes, and pyramids can extend below the ground, but are covered up when the rock tiles get written next. Finally, the castle tile values are simply copied into the correct location.
To generate the image file, the BMP header and palette is stored in the file as data, and is written first. The program then runs through the matrix, writing the appropriate row from the corresponding tile for each position.

Usage: Run mario.com, it will generate "m.bmp", a standard BMP image file. The file is created as a hidden file, since that ended up being less bytes.

Download a ZIP file containing the source code and binary, plus output.

Assembly code to generate the executable file:

org 100h
code_start:

;xor    cx,cx
mov    cx,12+14+256*3
mov    dx,filename
mov    ah,0x3c
int    21h
mov    bx,ax
push   ax

;mov    dx,BITMAPFILEHEADER
inc    dx
inc    dx
mov    ah,0x40
int    21h

mov di,tiles
xor ax,ax
mov ch,48
rep stosw

cwd             ; load the cloud sprite
mov si,cloud
call    DrawSprite
call    DrawHill

mov dx,14*256+12*16
PipeTileLoop:                ;Pipe
mov si,pipe0
call    DrawSprite
sub dh,2
jns PipeTileLoop

mov dx,32+12*16
call    DrawSprite
mov dh,13
;mov     si,pipe2
call    DrawSprite

cwd
xor ax,ax                ; move to the tile array
mov cl,6
MoveTileLoop:
call    MoveTile
loop    MoveTileLoop
mov word [BITMAPFILEHEADER+5+2],0x607     ; bushes
sub dl,3*16
mov cl,13
jnc MoveTileLoop

mov dx,0x1004
mov si,ball
call    DrawSprite
mov dl,0
call    MoveTile

xor bx,bx       ; pole
pole:
mov word[bx+tiles+22*256+7],0x707
add bl,16;
jnc pole

mov word [BITMAPFILEHEADER+5+2],0x805      ; qbrick
mov si,qbrick
call    DrawSprite
call    MoveTile

mov byte[BITMAPFILEHEADER+5+3],4

mov al,1            ; bricks & castle
call    Clear
mov al,23
call    MoveTile        ; black door
mov dx,0x800+64
BrickLoop:
xor dh,8
mov si,bricks
call    DrawSprite
sub dl,dh
jg  BrickLoop

cwd
call    MoveTile         ; left window
call    MoveTile         ; castle brick
mov al,3
mov di,image+15*256+16
mov cl,16
rep stosb
mov al,26
mov dl,16
call    MoveTile         ; reg brick

;mov     dl,32
;mov     si,door
call    DrawSprite
;mov     dl,32
call    MoveTile        ; door top
mov dx,48 +8*256
;mov     si,cren
call    DrawSprite
push    si

mov dh,0
call    MoveTile        ; crenulation 1
mov si,image+48+256  +4
mov di,image+48+256*9+4
mov bl,7
CrenLoop:
mov cl,7
rep movsb
mov dl,256-7
add si,dx
add di,dx
dec bx
jnz CrenLoop
mov dl,3*16
call    MoveTile        ; crenulation 2

pop si
mov cl,3
jmp skip
LastLoop:
;call    MoveTile        ; right window
                 ; block
                 ; rocks
call    DrawSprite
skip:
call    MoveTile
loop    LastLoop

xor ax,ax              ; Begin drawing world using the tiles
call    Clear
mov bl,48*4
BackgroundLoop:
lea di,[bx+image+2*256]
SmallHill:
mov al,10
mov cl,5
HillRow0:
stosb
inc ax
loop    HillRow0
mov dword [di+256-4],10+11*256+256*256*14
mov byte [di+512-3],15
sub di,256-10
cmp di,image +256
ja  SmallHill

mov si,fluff         ; draw clouds, bushes
FluffDrawLoop:
lodsw
add ax,bx
add ax,image
xchg    ax,di
lodsb
aam
mov cl,ah
;call    DrawFluff;

mov ah,1
FluffLayer2:
stosb
inc ax
push    cx
rep stosb
inc ax
stosb
pop cx
add di,256-2
sub di,cx
inc ax
dec ah
jns FluffLayer2

cmp si,pa
jl  FluffDrawLoop

sub bl,48
jnc BackgroundLoop

;mov     si,pa
mov cl,6
PipePlace:
lodsw
xchg    bx,ax
mov di,image
mov word [bx+di],18+19*256
PipeLoop:
dec bh
mov word[bx+di],16+17*256
jnz PipeLoop
loop    PipePlace

;mov     si,dba          ; draw the various floating blocks
mov cl,4
DrawBlockLoop:
lodsw
xchg    ax,bx
mov ah,bl

cwd
lodsb
BlockLoop:
mov bl,al
mov byte [bx+di],ah
lodsb
cmp al,dh
mov dh,al
ja  BlockLoop

dec si
loop    DrawBlockLoop

mov bx,198+256*12
FlagPole:             ; Draw flag pole
mov byte [bx+di],22
dec bh
jg  FlagPole
inc si
;mov     si,pyr            ; pyramid blocks
mov cl,8
PyrMainLoop:
lodsw
shr ah,1
cwd
inc dx
jnc NoNeg
neg dx
NoNeg:
mov bx,ax
PyrDrawLoop:
mov byte [bx+di],32
dec bh
jnz PyrDrawLoop
add ax,dx
dec ah
jnz NoNeg
loop    PyrMainLoop

;mov     si,ground        ; ground blocks
;mov     di,image
mov bl,4
push    di
GroundLoop:
lodsb
xchg    ax,cx
mov al,33
rep stosb
lodsb
add di,ax
dec bx
jnz GroundLoop
push    si
inc ch
mov si,di
sub si,cx
rep movsb

pop si
pop di
;push    di
;mov     si,copy         ; Draw Castle, flag ball
mov  dl,6
CopyLoop:
lodsw
mov cx,ax
shr cx,12
and ah,15
xchg    bx,ax
CopyRun:
lodsb
mov [bx+di],al
inc bx
loop    CopyRun
dec dx
jnz CopyLoop;

xor ax,ax
xor bx,bx ; image y        ; write the image to file
pop dx
WriteTileStep:
WriteRowStep:
mov bl,0 ; image x
WriteStep:
pusha
mov ah,[bx+di]
mov bx,dx
add ax,tiles
xchg    ax,dx
mov cl,16
mov ah,0x40
int 21h
popa
inc bx
cmp bl,212
jb  WriteStep
add al,16
jnz WriteRowStep
inc bh
cmp bh,14
jl  WriteTileStep
;pop     bx
;mov     ah,0x3e
;int     21h

;ret

DrawSprite: ; dx=x,y, si=data
pusha
mov bp,dx
;cwd
mov di,temp
push    di
lodsw              ; w, h*2+flag
mov dl,al
shr ah,1
pushf
mul ah
xchg    bx,ax
popf
jc  BitMapped
RunLoop:
lodsb
mov cl,al
shr cx,2
sub bx,cx
rep stosb
jnz RunLoop
jmp MoveData
BitMapped:
BitMappedLoop:
lodsb
mov cl,4
BitMappedQuad:
stosb
shr ax,2
loop    BitMappedQuad
sub bx,4
jg  BitMappedLoop
MoveData:
mov bx,sp
mov [bx+4],si
pop si
mov bx,di
lea di,[bp+image]
mov dh,-1
MoveLoop:
mov cl,dl
rep movsb
sub di,dx
cmp si,bx
jl  MoveLoop
popa
ret

MoveTile: ; dx =x,y, bx=y,ax=t-1
inc ax
pusha
mov si,dx

xchg    al,ah
xchg    di,ax
mov ax,16
TileLoop:
mov cl,16
TileTrans:
mov bx,[si+image]
inc si
and bx,3
mov bl,[bx+BITMAPFILEHEADER+5]
mov [di+tiles],bl
inc di
loop    TileTrans
add si,256-16
dec ax
jnz TileLoop
popa
add dl,16
ret

Clear: ; al = value
mov di,image
mov ch,48
rep stosb
ret;

DrawHill:
pusha
xor bx,bx
mov al,3
HillLoop:
lea di,[bx+image+6*16]
inc byte [di]
inc di
mov cl,16*5-2
sub cl,bl
sub cl,bl
rep stosb
inc byte [di]
inc bx
inc bh
cmp bl,16
jl  HillLoop

mov si,spot
push    si
mov dx,32-7+256*8 + 6*16
call    DrawSprite
mov dl,32+17    + 6*16
pop si
call    DrawSprite
mov dx,5*16      + 6*16
call    DrawSprite
popa
ret

filename: db 'm','.'
BITMAPFILEHEADER: db 66,77,'P',0,12,0,1,2,3,0,26,3,0,0
BITMAPCOREHEADER: db 12,0,0,0,64,13,224,0,1,0,8,0
colors: db 252,148,92,0,0,0,252,252,252,252,188,60,176,188,252,12,76,200,0,168,0,16,208,128,56,152,252

;pal: db 0,1,2,3
cloud: db 88,32,224,5,114,5,228,5,122,5,224,5,122,5,228,9,106,5,6,5,240,102,5,4,5,240,5,86,5,10,5,252,5,78,5,4,5,6,5,252,4,13,66,5,8,5,92,13,16,17,136,5,14,7,42,5,100,9,14,5,4,9,18,9,4,9,120,5,14,11,14,7,18,5,96,5,26,5,34,5,10,9,116,5,26,7,22,5,84,13,18,11,18,15,34,9,108,5,38,5,6,5,84,5,22,27,6,23,38,108,5,34,5,4,5,88,5,10,19,14,19,18,7,34,5,108,9,26,5,92,5,10,7,10,7,26,7,54,5,120,5,18,5,92,5,10,7,46,7,46,5,128,17,56
spot: db 6,17,245,95,255,245,93,87,127,245,87,127,245,223
hilltop: db 16,3*2,0x9, 0x33, 0x9, 0x8, 0xD, 0x1B, 0xD, 0x1C, 0x19, 0x14
ball: db 8,17,80,5,244,31,253,127,253,127,249,127,249,127,228,31,80,5
pipe0: db 64,5,0x90,0xFA,0xAA,0xAE,0xFF,0xFF,0xBB,0x06,0xA9,0xAF,0xAA,0xEB,0xFF,0xFF,0xBB,0x6B,0x90,0xFA,0xAA,0xAE,0xFF,0xFF,0xAE,0x06,0xA9,0xAF,0xAA,0xEB,0xFF,0xFF,0xEF,0x6A
pipe1:db 32,4,8,113,8,129
pipe2:db 32,12,5,23,26,79,9,122,133
qbrick: db 16,33,85,85,85,85,254,255,255,127,222,255,245,119,254,191,246,127,254,191,254,127,254,255,245,127,254,191,246,127,254,191,86,127,254,215,106,127,254,218,107,127,254,218,107,127,254,90,233,127,254,171,250,127,222,255,255,119,254,255,255,127,168,170,170,42
bricks: db 8,16,33,14,5,30,5,30,5,18,33,30,5,30,5,30,5
door: db 16,32,0xFD, 0xFD, 0x89, 0x6, 0x39, 0xA, 0x39, 0x6, 0x41, 0xA, 0x31, 0x6, 0x5, 0xE, 0x29, 0xA, 0x5, 0x16, 0x19, 0x12, 0x5
cren: db 16,17,213,255,255,85,234,0,192,170,234,0,192,170,234,0,192,170,234,0,192,170,234,0,192,170,234,0,192,170,255,0,192,255
block: db 16,32,61,6,7,53,6,5,11,45,6,9,15,37,6,13,19,34,17,19,34,17,19,34,17,19,34,17,19,34,17,19,34,17,19,34,17,19,34,17,15,6,35,17,11,6,43,13,7,6,51,9,6,59,5
rocks: db 16,33,86,149,87,149,171,106,171,90,171,127,171,106,251,85,171,106,95,170,173,106,165,170,173,106,171,170,182,106,171,170,182,106,171,170,182,106,171,170,246,127,171,170,102,149,171,170,118,106,171,170,182,106,171,170,182,106,171,170,182,106,254,255,231,191
fluff: db 8,10,11,     19,11,11,       27,10,31,       36,11,21,    11,1,34,    23,1,14,       41,1,24
pa: db 28,3,38,4,46,5,57,5,163,3,179,3
dba:db 21,5
qb: db 16,21,23,78,106,109,112,170, 21,9
qb2: db 22,94,109,129,130, 27,5
ba: db 20,22,24,77,79,94,100,101,118,129,130,168,169,171  , 27,9
ba2: db 80,81,82,83,84,85,86,87,91,92,93,121,122,123,128,131,0
pyr: db 137,5*2+1,140,5*2,151,5*2+1,152,5*2+1,155,5*2,188,9*2+1,189,9*2+1,198,4
ground: db 69,2,86-69-2,3,153-86-3,2,256-153-2,0
copy: db 202,2+5*16,26,26,24,26,26,   202,3+5*16,26,26,28,26,26,    202,4+5*16,29,30,30,30,29,   203,5+3*16,31,26,25,  203,6+3*16,29,29,29, 198,12+16,20
temp: rb 256*48
tiles: rb 34*16*16
image:


Is the DAG a transitive reduction? The goal of this challenge is given a finite directed acyclic graph (DAG), determine if the graph is a transitive reduction.

A brief explanation of what a DAG and transitive reductions are:

A DAG is a graph with directed edges (i.e. you can only travel in one direction on that edge) such that given any starting node on the graph, it is impossible to return to the starting node (i.e. there are no cycles).

Given any starting node, if it is possible to travel to another ending node in the graph via any arbitrary positive number of edges, then that ending node is defined as reachable from the starting node. In a general DAG, there might be multiple paths which can be taken from a starting node to a target ending node. For example, take this diamond graph:

To get to node D from A, you could take the path A->B->D or A->C->D. Thus, D is reachable from A. However, there is no path which can be taken to get to node B starting from node C. Thus, node B is not reachable from node C.

Define the reachability of the graph as the list of reachable nodes for every starting node in the graph. So for the same example diamond graph, the reachability is:

A: [B, C, D]
B: [D]
C: [D]
D: []

Another graph which has the same reachability as the above graph is shown below:

However, this second graph has more edges than the original graph. The transitive reduction of a graph is a graph with the least number of edges and same reachability of the original graph. So the first graph is the transitive reduction of the second one.

For a finite DAG, the transitive reduction is guaranteed to exist and is unique.

Input

The input is a "list of lists", where the external list has the length of the number of vertices, and each internal list is the length of the number of edges leaving the associated node, and contains the indices of destination nodes. For example, one way to describe the first graph above would be (assuming zero based indexing):

[[1, 2], [3], [3], []]

You may begin indexing of the first node at any arbitrary integer value (e.g. 0 or 1 based indexing).

The input may come from any input source desired (stdio, function parameter, etc.). You are free to choose the exact input format as long as no additional information is given. For example, if you want to take input from stdio, you could have each line be a list of edges for the associated node. Ex.:

1 2
3
3
'' (blank line)

The indices in each adjacency list is not necessarily sorted, and there could be multiple edges connecting two nodes (ex.: [[1,1],[]]). You may assume the input graph is weakly connected, and contains no cycles (i.e. it is a DAG).

Output

The output is truthy if the given input DAG is a transitive reduction, and a falsy value otherwise. This may be to any sink desired (stdio, return value, output parameter, etc.)

Examples

All examples use 0-based indexing.

[[1,2],[3],[3],[]]
true

[[1,2,3],[3],[3],[]]
false

[[1,1],[]]
false

[[1,2,3,4],[5,6,7],[5,8,9],[6,8,10],[7,9,10],[11,12],[11,13],[12,13],[11,14],[12,14],[13,14],[],[],[],[]]
true

[[5,6,7],[2,3,0,4],[5,8,9],[6,8,10],[7,9,10],[11,12],[11,13],[12,13],[11,14],[12,14],[13,14],[],[],[],[]]
true

[[5,6,7],[2,3,0,4,14,5,7],[5,8,9],[6,8,10],[7,9,10],[11,12],[11,13],[12,13],[11,14],[12,14],[13,14],[],[],[],[]]
false

[[5,6,7],[2,3,0,4],[5,8,9],[6,8,10],[7,9,10,14],[11,12],[11,13],[12,13],[11,14],[12,14],[13,14],[],[],[],[]]
false

[[1,3],[2],[3],[]]
false

Scoring

This is code golf; smallest code in bytes wins. Your code should complete in a reasonable amount of time (10 minutes max on whatever hardware you have). Standard loopholes apply. You may use any built-ins desired.

Ruby, 101 97 bytes
Simple approach that calculates the reach from each node and considers if a child node can be reached via any of the other nodes. Seemingly fails on cyclic graphs, but the definition of a DAG implies that it shouldn't be cyclic anyways.
Try it online!
->g{r=->i{i|i.map{|j|r[g[j]||[]]}.inject([],:|)}
g.all?{|e|e==e&e&&e.none?{|i|r[e-[i]].index i}}}


Determining part of speech of most words Write a program to output the part of speech of any word inputted to it.  I doubt that anyone could get a perfect algorithm, so I will give the code a batch of words in order to ascertain what algorithm is the best.

Weighted Scoring:
+10pts for each word identified correctly: http://www.englishclub.com/grammar/parts-of-speech_1.htm (out of 100 randomly selected words)
-1pt for each byte
+5pts for each upvote on your answer

Rules:
no using external resources (unless they are counted in the size)

UPDATE: Due to the need for a standardized word list for testing purposes, I will be using the list provided in the response to this question. http://www-personal.umich.edu/~jlawler/wordlist  It seems to be a fairly complete list, and will make this a challenge more than a guessing game.

Mathematica

Mathematica has a native database of words (called up by the simple command WordData ) that includes, among other properties, the parts of speech.  Without this database, it would be impossible for me to answer the question.

The word list from here was downloaded.
Once stored, it is called up as follows:

words = Import["wordlist.txt", "Table"];
Length[words]

  69905

Forty words are randomly chosen from the list:

list = Flatten@RandomSample[words, 40]

  {"mealtime", "deride", "cricketground", "torpedinidae", "rosefish",
  "akron", "sloppy", "deaden", "assaultive", "mick",
  "unperceptiveness", "skeg", "pad", "mane", "carvel-built",
  "night-stop", "monarchy", "corking", "backlog", "scaphopoda",
  "bagman", "phrthe", "wholesome", "proprietress", "hortus",
  "unreliable", "farthermost", "fearfulness", "malposed", "stoke",
  "affiche", "lunatic", "holcus", "devoutness", "macaque", "zenithal",
  "poetry", "precipitate", "agoraphobic", "snapper"}

The following asks Mathematica to return the parts of speech for the list of 40 words.
The parts of 31 words are identified. 9 words are not recognized.

(s = Select[Flatten@{{#}, WordData[#, "PartsOfSpeech"]} & /@
     list, ! MatchQ[#, {_, WordData[_, _]}] &]) // TableForm
Length[s]


Is it a noun or not? Given a string as input, determine whether it is a noun or not.

You will be scored on the 1000 most common English words, by how many you correctly label as a noun or not.

The program or function which correctly classifies the most of those words in 50 bytes or less will win.

Nouns

A noun is a word that represents a thing, typically. It gets more complex, but that's the basic idea.

In cases where a word could either be a noun or some other part of speech, I classified it as a noun, even if that's a rare usage. Or actually, I let this site do it for me.

The words you'll be scored on are these 1000 common words, which are from simple Wikipedia, with "two" and "once" added. Of those, these are the 586 nouns, and these are the 414 non-nouns. You can find all three lists here. Note that all of these inputs are in lower case. These lists are final - don't try to argue grammar.

Your program will be considered correct if it outputs a truthy result on an input which is a noun, and a falsy result on an input which is not a noun.

Subtleties:

Programs must have a deterministic output. If you want to use randomness, seed it. Programs are not allowed to use built-in noun lists or other built-in part-of-speech functionality.

Examples:

a: noun
act: noun
active: noun
about: non-noun
above: non-noun
across: non-noun

Please indicate what your program's success rate is in your answer. The program or function of at most 50 bytes with the highest success rate wins. In case of a tie, lowest byte count will determine a winner. Good luck!

JavaScript (ES6), 43 bytes, 622 630 633

Just to get the ball rolling. Returns 1 for nouns, 0 for non-nouns.

s=>2552>>s.length&/^[bcdf-mp-tvwy]/.test(s)

How?

We bet on noun if both following conditions are met:

The word length is 3, 4, 5, 6, 7, 8 or 11. This is done by right-shifting the binary number 100111111000 (2552 as decimal).
The word starts with one of these letters: bcdfghijklmpqrstvwy


Output source file name Write a program that prints the name of its source file. REPL environments are not allowed for this challenge. Your code must work in any file that your language's interpreter will accept. Your answer must also be a full program, not just a function. The source code's file extension must be printed. Leading or trailing newline are both optional. This is a code golf, so shortest answer wins. The winner will be chosen on September 2nd, 2016.

V, 3 bytes

"zp

Try it online!

This actually does work in the online interpreter somehow. ¯\_(ツ)_/¯

Explanation:

The 'z' register is predefined to the source file of the program, and p pastes from whatever register you tell it to. P would also work, and not cause any different output.


Find the number of integers in the range from 1 to N that ends with 2 Task

As input you have:

a positive integer N

And you should output:

The number of integers in \$[1,N]\$ (an inclusive range) which end with the digit \$2\$ in base ten.

Test cases

1 -> 0
2 -> 1
5 -> 1
10 -> 1
12 -> 2
20 -> 2
30 -> 3
54 -> 6
97 -> 10
100 -> 10

Rules

It is a code-golf so the lowest score in bytes wins!

Python 2, 17 bytes

lambda n:(n+8)/10

Try it online! Uses Python 2's integer division. In Python 3 would be a byte longer with lambda n:(n+8)//10.