In-between fractions In-between fractions

The challenge:

You will need to create code that takes atleast 3 inputs; 2 integers and "a fraction representation" - whichever type suits your language for representing the fraction increments) ie. If you choose string the input would be "1/4" or you could choose 2 extra integer inputs or a tuple or w/e.

Input can be anywhere reasonable (STDIN, function arguments, from a file, etc.), and so can output (STDOUT, function return value, to a file, etc.)

Rules:

The input "fraction" will always be a valid fraction, less than 1; example "1/4"
The second input integer will always have a higher value than the first integer. I.E the first input integer will always have a lower value than the second.
The input integers can be negative.
Outputted fractions should be reduced as much as possible (simplified)

The code will need to output every "fraction step" between the 2 numbers in increments of the input fraction.

The code should be a program or function as stated here

Example 1:

Input: -2,3,"1/2"

Output:

 -2
 -3/2
 -1
 -1/2
  0
  1/2
  1
  3/2
  2
  5/2
  3

Example 2:

Input: 1,2,"2/3"

Output:

1
5/3
2

or

1
4/3
2

Note: Counting can start from either direction (thank you @Mego)

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

Mathematica, 16 bytes

Range@##⋃{#2}&

An unnamed function that takes two integers and a rational number and returns a list of numbers, e.g.:

Range@##⋃{#2}&[-2, 3, 1/2]
(* {-2, -(3/2), -1, -(1/2), 0, 1/2, 1, 3/2, 2, 5/2, 3} *)

Mathematica's Range does exactly what the challenge asks, except that it omits the upper bound if the difference between lower and upper bound isn't exactly a multiple of the step size. Therefore we take the Union (using ⋃) with the list containing only the upper bound which ensures that it appears exactly once. Note that Union will sort the result but we want it sorted anyway, since the step size is always positive. Also since we're working with rationals, they're automatically reduced as much as possible.


Circular shift an arbitrary byte-array bitwise Given an arbitrary array of octets, and an offset measured in bits, the goal is to bitwise left rotate the array by the specified number of bit positions as if the entire array were a single contiguous number. Byte order is big-endian.

As an example, given the (not zero terminated) ASCII string abcd and a shift of 5 bits. we turn this array of bytes:

01100001 01100010 01100011 01100100

into this one:

00101100 01001100 01101100 10001100

Notice that the bits propagate to the left from byte to byte and that they wrap back around.

Now that I think you've all got the idea, the rules:

Your program should accept an arbitrary unsigned integer ("number of bits to shift" non-negative, possibly zero, limited only by the size of the standard integer type) and a raw stream of octets of arbitrary length (you may assume the length is strictly positive). How you accept these is up to you (file,stdin,parameter are all acceptable). Your program should output the shifted bytes in an analogous manner (i.e. file,stdout,return value).
"Cut-and-paste" style code is not allowed. That is, you can't rely on your user to set the value of a certain variable before calling your code.
The byte ordering is big-endian.
Shortest code wins.

EDIT: It's clear now I should have restricted the input output format a bit more. The solutions that are using ASCII 0s and 1s directly aren't very interesting unfortunately.

C 89

Shifting is done in-place in *s array. l is array length and f is number of bits to shift.

void f(char*s,l,f){while(f--)for(int i=0,j,c=*s<0;s[j=i++]<<=1,s[j]+=i%l?s[i]<0:c,i<l;);}


Upper or Lower Wythoff? First, let's talk about Beatty sequences. Given a positive irrational number r, we can construct an infinite sequence by multiplying the positive integers to r in order and taking the floor of each resulting calculation. For example,

If r > 1, we have a special condition. We can form another irrational number s as s = r / (r - 1). This can then generate its own Beatty sequence, Bs. The neat trick is that Br and Bs are complementary, meaning that every positive integer is in exactly one of the two sequences.

If we set r = ϕ, the golden ratio, then we get s = r + 1, and two special sequences. The lower Wythoff sequence for r:

1, 3, 4, 6, 8, 9, 11, 12, 14, 16, 17, 19, 21, 22, 24, 25, 27, 29, ...

and the upper Wythoff sequence for s:

2, 5, 7, 10, 13, 15, 18, 20, 23, 26, 28, 31, 34, 36, 39, 41, 44, 47, ...

These are sequences A000201 and A001950 on OEIS, respectively.

The Challenge

Given a positive input integer 1 <= n <= 1000, output one of two distinct values indicating whether the input is in the lower Wythoff sequence or the upper sequence. The output values could be -1 and 1, true and false, upper and lower, etc.

Although your submitted algorithm must theoretically work for all inputs, in practice it only has to work with the first 1000 input numbers.

I/O and Rules

The input and output can be given by any convenient method.
The input and output can be assumed to fit in your language's native number type.
Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
Standard loopholes are forbidden.
This is code-golf so all usual golfing rules apply, and the shortest code (in bytes) wins.

JavaScript (ES6), 50 35 bytes

f=(n,s="1",t=0)=>s[n-1]||f(n,s+t,s)
<input type=number min=1 oninput=o.textContent=this.value&amp;&amp;f(this.value)><pre id=o>

Outputs 1 for lower and 0 for upper. Explanation: Partial lists of boolean values can be constructed using a Fibonacci-like identity: given two lists, starting with 1 and 10, each subsequent list is the concatenation of the previous two, resulting in 101, 10110, 10110101 etc. In this case it's slightly golfier to have a fake 0th entry of 0 and use that to construct the second element of the list.


Ways of specifying random generation in challenges Note: As per consensus on Meta, challenge-writing questions are on topic here.

In light of this "thing to avoid when writing challenges", I started to think about challenges involving random generation of certain kinds of objects.

It sometimes happens that I want to post a code-golf challenge that involves randomly generating a foo, where

it's very easy to check whether a given thing is a foo, and
it's a little harder to quickly generate a "good-quality" random foo.

As an example, a foo might be a binary matrix where there are no segments of 4 equal bits in any direction.
It's easy to check whether a given binary matrix is a foo, but generating a random foo with a nicely spread distribution seems to require a backtracking algorithm or something similar.

Anyway, now I'll need to objectively specify what qualifies as a random foo, and I'd like it to be "unpredictable" in the intuitive sense that when I run the program several times, the results always look different.
The most restrictive approach is to require that the output is uniformly random: all valid foos have the same probability of being generated.
This is usually too restrictive, because I have no idea how to do it save for generating all valid foos, removing duplicates and choosing one, which is boring and slow.

My next idea is to require that all valid foos have a positive probability of being generated.
However, this means that the following approach is valid: generate a random foo-like thing (in our example, a random binary matrix), if it's a foo then return it, otherwise return a hard-coded foo (say, the identity matrix).
This is also somewhat boring, since it's basically just a recognizer of foos tacked to a random matrix generator.

Could there be a nice general definition for an unpredictably random foo?

TL;DR

Is there a good way for specifying an "unpredictable" randomly generated object that doesn't fix the distribution but discourages hard-coding?

Return a thousand different foos

This makes it impossible to return hardcoded values and have a half decent golf. However, a legit foo generator does have a small chance of outputting duplicate foos unless it is actually checking them. To remove the burden of checking, an empirically tested failure rate, say 10%, could be specified as acceptable.

Be aware of the birthday paradox, that the probability of duplicates may be higher than you think. If there are only a million possible foos, a thousand random foos will have a probability of about 0.6 that there is a duplicate in there somewhere, and that's assuming that foo generation is completely uniform. If this could be an issue, require say 900 unique foos for every 1000 generated, which is far more generous for a genuine foo generator but still impractical for hardcoding.

This also allows you to repeatedly generate foo-like things and check fooness until you get foos. I think this is a valid solution myself, but if you don't like it:

Do it quickly

The chances of a completely random foo-like thing being foo are probably quite low, so specifying a time limit is likely to force a genuine attempt at foo generation.

To accomodate the speed differences between different languages, you may want to have different time limits depending on the language like Hackerrank: https://www.hackerrank.com/environment . However if you specify large enough foos the probability of random foo-like things being foo might be really low, so a "before the heat death of the Universe" rule might be sufficient.


Hyperprogramming: N+N, N×N, N^N all in one Write a program that takes in a number N from 1 to 9 inclusive. In its native form your program should output N+N. E.g. output 2 if N is 1, 4 if N is 2, 6 if N is 3, and so on.
When every character in your program is duplicated in place, then it should be a program that takes in N (still from 1 to 9) and outputs N×N. E.g. output 1 if N is 1, 4 if N is 2, 9 if N is 3, and so on.
When every character in your program is triplicated in place, then it should be a program that takes in N (still from 1 to 9) and outputs N^N. E.g. output 1 if N is 1, 4 if N is 2, 27 if N is 3, 387420489 if N is 9, etc.
Numbers above 9 aren't required because 10^10 is outside of many language's usual integer range.
Example
If your initial program was
My_Program!
Exit();

Then it should be capable of taking in N and outputting N+N.
Additionally, the program
MMyy__PPrrooggrraamm!!

EExxiitt(());;

should take in N and output N×N.
Finally, the program
MMMyyy___PPPrrrooogggrrraaammm!!!

EEExxxiiittt((()));;;

should take in N and output N^N.
Quadrupled-character programs and beyond are not required.
Rules

Input and output should be plain, normally formatted decimal numbers. You may answer using a different base to show off your code but then your answer is non-competitive.

Windows users may treat \r\n as one character since things like \r\r\n\n wouldn't make sense or perhaps even work.

The shortest native program (the N+N one) in bytes wins.

Jelly, 12 bytes

N+N

“(ẹ+)‘FQṖṪỌv

Try it online!

N×N

““((ẹẹ++))‘‘FFQQṖṖṪṪỌỌvv

Try it online!

N^N

“““(((ẹẹẹ+++)))‘‘‘FFFQQQṖṖṖṪṪṪỌỌỌvvv

Try it online!

How it works

Jelly has several different types of string literals; all of them start with a “. If the literal contains more than one “, a string array is returned, and “ separates the strings from each other.

For example, “abc“def” yields ['abc', 'def'].

Depending on the last character of the literal (any of ”«»‘’, where « is currently unimplemented), one can choose between the different types of literals. For ‘, we get the code points in Jelly's code page instead of the corresponding Unicode characters.

For example, “abc“def‘ yields [[97, 98, 99], [100, 101, 102]].

The three literals in the programs correspond to the following code point arrays.

“(ẹ+)‘           -> [40, 214, 43, 41]
““((ẹẹ++))‘      -> [[], [40, 40, 214, 214, 43, 43, 41, 41]]
“““(((ẹẹẹ+++)))‘ -> [[], [], [40, 40, 40, 214, 214, 214, 43, 43, 43, 41, 41, 41]]

N+N

“(ẹ+)‘FQṖṪỌv                          Main link. Argument: n

“(ẹ+)‘                                As before.
      F                               Flatten the array. Yields an integer array.
       Q                              Unique; deduplicate the integers.
                                      This yields [40, 214, 43, 41].
        Ṗ                             Pop; remove the last element.
         Ṫ                            Tail; extract the last element.
                                      This yields 43, the Unicode code point of +.
          Ọ                           Unordinal; cast to character.
           v                          Eval; execute the character as a Jelly
                                      program with argument n.

N×N

““((ẹẹ++))‘‘FFQQṖṖṪṪỌỌvv              Main link. Argument: n

““((ẹẹ++))‘                           As before.
           ‘                          Increment all integers.
            FF                        Flatten the array. Yields an integer array.
              QQ                      Unique; deduplicate the integers.
                                      This yields [41, 215, 44, 42].
                ṖṖ                    Pop twice; remove the last two elements.
                  ṪṪ                  Tail; extract the last element.
                                      This yields 215, the Unicode code point of ×.
                    ỌỌ                Unordinal; cast to character.
                      v               Eval; execute the character as a Jelly
                                      program with argument n.
                       v              Eval; convert the return value (n×n) to a
                                      string and execute that string as a Jelly
                                      program with argument n. Since the string
                                      consists of a single integer literal, that
                                      integer is returned, ignoring the argument.

Note that F, Q, Ṫ, and Ọ do not alter 1D arrays, arrays without duplicates, integers, and characters (respectively).

N^N

“““(((ẹẹẹ+++)))‘‘‘FFFQQQṖṖṖṪṪṪỌỌỌvvv  Main link. Argument: n

“““(((ẹẹẹ+++)))‘                      As before.
                ‘‘                    Increment all integers twice.
                  FFF                 Flatten the array. Yields an integer array.
                     QQQ              Unique; deduplicate the integers.
                                      This yields [42, 216, 45, 43].
                        ṖṖṖ           Pop thrice; remove the last three elements.
                           ṪṪṪ        Tail; extract the last element.
                                      This yields 42, the Unicode code point of *.
                              ỌỌỌ     Unordinal; cast to character.
                                 v    Eval; execute the character as a Jelly
                                      program with argument n.
                                  vv  Eval twice. See N×N.


Spanning paths in a tournament on n nodes The goal of this challenge is to extend the On-Line Encyclopedia of Integer Sequences (OEIS) sequence A038375.

  Maximal number of spanning paths in tournament on n nodes.

A tournament on \$n\$ vertices is a directed graph where for each pair of vertices \$(v_i, v_j)\$ there is either a directed edge \$v_i \rightarrow v_j\$ or a directed edge \$v_j \rightarrow v_i\$.

A spanning path or Hamiltonian path is an ordering of all of the vertices of a graph, \$(v_1, v_2, ..., v_n)\$ such that there is an edge \$v_i \rightarrow v_{i+1}\$ for all \$i<n\$.

Example

In the above tournament, there are five Hamiltonian paths:

\$(1,2,4,3)\$
\$(1,4,3,2)\$
\$(2,4,3,1)\$
\$(3,1,2,4)\$
\$(4,3,1,2)\$

Moreover, it is not possible to construct a tournament on four vertices with more than five Hamiltonian paths, so \$A038375(4) = 5\$.

The way to win this fastest-code challenge is to write a program that can compute the largest value of A038375 deterministically in under 10 minutes on my machine, a 2017 MacBook Pro with 8GB RAM and a 2.3 GHz i5 processor.

In the case of a tie at the end of ten minutes, the winning code will be the one that got its final value fastest.

C++ (gcc), \$N=10\$

#include <algorithm>
#include <iostream>
#include <vector>
#include <cstring>
#include <ctime>
//a rewrite for vector<int>
struct vi
{
	int l,a[9];
	const int& operator[](int u) const {return a[u];}
	int& operator[](int u) {return a[u];}
};
bool operator < (const vi&a,const vi&b)
{
	for(int i=0;i<a.l;++i) if(a[i]!=b[i]) return a[i]<b[i];
	return 0;
}
bool operator == (const vi&a,const vi&b)
{
	for(int i=0;i<a.l;++i) if(a[i]!=b[i]) return 0;
	return 1;
}
std::vector<vi> g[13];
void dfs(int x,int u,const vi&c,int*w)
{
	++w[u];
	if(c[x]&u)
		for(int o=c[x]&u;o;o^=o&-o)
			dfs(__builtin_ctz(o),u^(o&-o),c,w);
}
void dfsf(int x,int u,const vi&c,int*w)
{
	++w[u];
	if((~c[x])&u)
		for(int o=(~c[x])&u;o;o^=o&-o)
			dfsf(__builtin_ctz(o),u^(o&-o),c,w);
}
int main()
{
	g[0].push_back(vi());
	for(int i=0;i<9;++i)
	{
		for(auto t:g[i])
		{
			int m1=0,m=0;
			for(int j=0,r;j<i;++j)
			{
				if((r=__builtin_popcount(t[j]))>m1) m=0,m1=r;
				if(r==m1) m|=1<<j;
			}
			for(int e=0;e<(1<<i);++e) if(__builtin_popcount(e)>m1
			||(__builtin_popcount(e)==m1&&((e&m)==m))) //ensure the node has the highest degree
			{
				vi u; u.l=i+1;
				for(int p=0;p<=i;++p) //enumerate position
				{
					bool s=(p==0); int x;
					#define yield(l,c) do{if((x=(c))>u[l]&&!s) goto skip; else s|=x<u[l],u[l]=x;}while(0)
					for(int a=0;a<p;++a)
						yield(a,((t[a]>>p)<<(p+1))|(t[a]&((1<<p)-1))|((!((e>>a)&1))<<p));
					yield(p,((e>>p)<<(p+1))|(e&((1<<p)-1)));
					for(int a=p;a<i;++a)
						yield(a+1,((t[a]>>p)<<(p+1))|(t[a]&((1<<p)-1))|((!((e>>a)&1))<<p));
					skip:;
					#undef yield
				}
				g[i+1].push_back(u);
			}
		}
		std::sort(g[i+1].begin(),g[i+1].end());
		g[i+1].erase(std::unique(g[i+1].begin(),g[i+1].end()),g[i+1].end());
		int sz=g[i+1].size();
		std::vector<vi> h(sz);
		#pragma omp parallel for
		for(int w=0;w<sz;++w)
		{
			vi u=g[i+1][w],v;
			auto sw=[&](int x,int y) {
				std::swap(v[x],v[y]);
				for(int s=0;s<v.l;++s)
				{
					int&o=v[s];
					if(((o>>x)^(o>>y))&1) o^=(1<<x)|(1<<y);
				}
			};
			for(int x=0;x<=i;++x)
				for(int y=x+1;y<=i;++y)
				{
					{v=u;sw(x,y);u=std::min(u,v);}
					for(int z=y+1;z<=i;++z)
					{
						{v=u;sw(x,y);sw(y,z);u=std::min(u,v);}
						{v=u;sw(x,y);sw(x,z);u=std::min(u,v);}
						{v=u;sw(y,z);sw(x,z);u=std::min(u,v);}
						{v=u;sw(y,z);sw(x,y);u=std::min(u,v);}
						{v=u;sw(x,z);sw(x,y);u=std::min(u,v);}
						{v=u;sw(x,z);sw(y,z);u=std::min(u,v);}
					}
					{v=u;sw(x,y);u=std::min(u,v);}
				}
			h[w]=u;
		}
		std::sort(h.begin(),h.end());
		h.erase(std::unique(h.begin(),h.end()),h.end());
		g[i+1]=h;
	}
	std::cout<<"pre ("<<clock()*1./CLOCKS_PER_SEC<<"s)\n";
	for(int o=0;o<=9;++o)
	{
		int mx=0;
		const int s=g[o].size();
		#pragma omp parallel for reduction(max:mx)
		for(int t=0;t<s;++t)
		{
			int a[9<<9],b[9<<9];
			memset(a,0,sizeof(int)*(o<<o));
			memset(b,0,sizeof(int)*(o<<o));
			for(int i=0;i<o;++i)
				dfs(i,((1<<o)-1)^(1<<i),g[o][t],a+(i<<o)),
				dfsf(i,((1<<o)-1)^(1<<i),g[o][t],b+(i<<o));
			int r[9][9],c=(1<<o)-1,vx[1<<9];
			for(int p=0;p<o;++p)
			{
				int*A=a+(p<<o),vn=0;
				for(int x=0;x<=c;++x) if(A[x]) vx[vn++]=x;
				for(int q=0;q<o;++q) if(p!=q)
				{
					int*B=b+(q<<o),su=0;
					for(int u=0;u<vn;++u)
						su+=A[vx[u]]*B[c^vx[u]];
					r[p][q]=su;
				}
			}
			int m1=0,m=0;
			for(int j=0,pc;j<o;++j)
			{
				if((pc=__builtin_popcount(g[o][t][j]))>m1) m=0,m1=pc;
				if(pc==m1) m|=1<<j;
			}
			for(int i=0;i<(1<<o);++i) if(__builtin_popcount(i)>m1
			||(__builtin_popcount(i)==m1&&((i&m)==m)))
			{
				int tot=(o==0);
				for(int j=0;j<o;++j)
					if(i&(1<<j))
					{
						tot+=a[j<<o];
						for(int ii=c^i;ii;ii^=ii&-ii)
							tot+=r[j][__builtin_ctz(ii)];
					}
					else tot+=b[j<<o];
				mx=std::max(mx,tot);
			}
		}
		std::cout<<"a("<<o+1<<") = "<<mx<<" ("<<clock()*1./CLOCKS_PER_SEC<<"s)\n";
	}
}

Try it online!

Compile with g++ and -Ofast -funroll-all-loops -ffast-math -fno-stack-protector -march=native -fopenmp. Note that OpenMP is used for parallelism.

Output on my modest computer:

pre (5.217s)
a(1) = 1 (5.218s)
a(2) = 1 (5.218s)
a(3) = 3 (5.219s)
a(4) = 5 (5.221s)
a(5) = 15 (5.221s)
a(6) = 45 (5.222s)
a(7) = 189 (5.223s)
a(8) = 661 (5.225s)
a(9) = 3357 (5.318s)
a(10) = 15745 (18.634s)

The run time may differ a lot because of the use of OpenMP parallelism.

Explanation for \$N=9\$ version:

This code is two-fold. First, it will try to generate all tournament graphs up to isomorphism. Then, it will count the number of hamilton paths on these generated graphs. Adjacency matrices of graphs are stored as arrays of bitmasks (i.e. arrays of uint) for performance reasons.

The second part is relatively easier. We can just use depth-first-search to search for all possible paths and use bitmasks to speed up. The time complexity is \$O(\text{no. of paths in all graphs})\$. It's also possible to use bitmask dynamic programming to do it, with \$O(2^NN^2)\$. The above code used the former while the latter one should be faster when N goes higher. OpenMP parallelization is used to speed it up.

The first part is harder. My approach is incremental: first generating all tournament graphs of \$t\$ nodes, then add one node to be tournament graphs of \$t+1\$ nodes. The trick here is to find an order for adding nodes. Here, instead of adding any node, we restrict the added node to have the greatest degree in the result graph. Therefore, a graph won't be generated too many times.

Graph-isomorphism isn't a easy thing to check too. Therefore we're not really trying to make every graph unique, but to have some degree of tolerance. I have two strategies used here. First, the newest \$t+1\$-th node won't be directly assigned number \$t\$. Instead, we try all the possible numbers from \$0\$ to \$t\$ and take the result graph with the smallest lexicographic order (you can use early-stopping when comparing lexicographic order, so not much overhead). After generating all \$t+1\$-node graphs in this way, we remove the found duplicates by sorting and making them unique. This alone can cut down the number of found graphs for \$N=9\$ to around \$3\times 10^6\$.

The second strategy is that, after found such candidates, we further try to remove duplicates by trying to swap every two nodes and see if we can get a graph with smaller lexicographic order. We then proceed by sorting and making them unique. These two strategies cut down the number of found graphs for \$N=9\$ to around \$10^6\$. (This strategy alone is more powerful than I thought, cutting down to around \$1.1\times 10^6\$)

Explanation for \$N=10\$ version:

Some improvements are made upon the \$N=9\$ version. First, instead of swapping two positions, three positions are swapped to achieve a better result. This successfully cut the number of graphs generated at \$N=9\$ to less than \$5 \times 10^5\$ (~50% improvement). OpenMP parallelization is also introduced here to speed up.

Generating all graphs for \$N=10\$ sounds unfeasible, so instead I try to expand the last step. We still try to add one node for graphs with \$9\$ nodes, but instead of actually generating these new graphs, we can actually count the hamilton paths in them directly!

Consider the relationship between a hamilton path and the new node. The new node can be the first end of the path so we need to find an edge from the new node and continue the path from that node. The new node can also be the second end so we can find an edge to the new node and trace back the path starting from that node.

Of course, the new node can be in the middle of the path. In this case, we can enumerate the two nodes in front and on the back of it. We can then enumerate the subset of nodes both halves of the path contain and then multiply them to get the result.

Notice that the contribution is the same for every pair of nodes adjacent to the new node regardless of other edges to the new node, so we can get that precalculated for every two nodes.

In order to get the number of paths starting and ending on each node covering a certain subset of nodes, we can use depth-first-search from each starting and ending point. (A bitmask dynamic programming could work too, but I guess it's slower)


Tips for golfing in Scala 3 What general tips do you have for golfing in Scala 3? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Scala 3 (e.g. "remove comments" is not an answer). Please post one tip per answer.
Also see Tips for golfing in Scala

Use parameter untupling
Parameter untupling allows you to write functions accepting a single tuple as input as if they were functions accepting 2 parameters. Basically, you can replace these
list.map{case(a,b)=>a+b}
//and
list.map{case(a,b)=>Seq(a,b)}
//or
list.map(t=>t._1+t._2)
//and
list.map(t=>Seq(t._1,t._2))

with this, which is both shorter and more beautiful.
list.map(_+_)
//and
list.map(Seq(_,_))


Covering a Skyline with brush strokes Given a non-negative integer skyline height list, answer how many uninterrupted 1-unit-high horizontal brush strokes are needed to cover it.

[1,3,2,1,2,1,5,3,3,4,2], visualised as:

      5
      5  4
 3    5334
 32 2 53342
13212153342

needs nine brush strokes:

      1
      2  3
 4    5555
 66 7 88888
99999999999

Examples

[1,3,2,1,2,1,5,3,3,4,2] → 9

[5,8] → 8

[1,1,1,1] → 1

[] → 0

[0,0] → 0

[2] → 2

[2,0,2] → 4

[10,9,8,9] → 11

JavaScript (Node.js), 38 bytes

a=>a.map(v=>(n+=v>p&&v-p,p=v),p=n=0)|n

Try it online!

Simply a greedy algorithm which scan from left to right, only draw lines if needed, and draw it as long as possible.

Thanks Arnauld, save 2 3 bytes


Densely packed decimal (DPD) to decimal, with logic gates Inspired by recent popularity of nandgame on TNB, and my own previous challenge.

Background

Densely packed decimal (DPD) is a way to efficiently store decimal digits in binary. It stores three decimal digits (000 to 999) in 10 bits, which is much more efficient than naive BCD (which stores one digit in 4 bits).

Conversion table

DPD is designed to easily convert between the bits and the digits by simple pattern matching from top to bottom. Each bit pattern defines how many high digits (8-9) the number has, where they are, and how to move the bits to form the decimal representation.

The following is the conversion table from 10 bits of DPD to three decimal digits. Each decimal digit is represented as 4-bit binary (BCD). Both sides are written left to right from the most significant digit to the least.

Bits                 =>  Decimal         (Digit range)

a b c d e f 0 g h i  =>  0abc 0def 0ghi  (0-7) (0-7) (0-7)

a b c d e f 1 0 0 i  =>  0abc 0def 100i  (0–7) (0–7) (8–9)
a b c g h f 1 0 1 i  =>  0abc 100f 0ghi  (0–7) (8–9) (0–7)
g h c d e f 1 1 0 i  =>  100c 0def 0ghi  (8–9) (0–7) (0–7)

g h c 0 0 f 1 1 1 i  =>  100c 100f 0ghi  (8–9) (8–9) (0–7)
d e c 0 1 f 1 1 1 i  =>  100c 0def 100i  (8–9) (0–7) (8–9)
a b c 1 0 f 1 1 1 i  =>  0abc 100f 100i  (0–7) (8–9) (8–9)
x x c 1 1 f 1 1 1 i  =>  100c 100f 100i  (8–9) (8–9) (8–9)

Notations

The lowercase letters a to i are the bits that are copied to the decimal representation.
0 and 1 are the exact bits in the input or output bit patterns.
x bits are ignored in the conversion.

Task

Build a logical circuit using two-input NAND gates to convert 10 bits of DPD to 12 bits of BCD.

Examples

Emphasized bits are the pattern-matching bits.

DPD                    Decimal  BCD
0 0 0 0 0 0 0 1 0 1    005      0000 0000 0101
            ^
0 0 0 1 1 0 0 0 1 1    063      0000 0110 0011
            ^
0 0 0 1 1 1 1 0 0 1    079      0000 0111 1001
            ^ ^ ^
0 0 0 0 0 1 1 0 1 0    090      0000 1001 0000
            ^ ^ ^
0 0 0 1 0 1 1 1 1 0    098      0000 1001 1000
      ^ ^   ^ ^ ^
1 0 1 0 1 1 1 0 1 0    592      0101 1001 0010
            ^ ^ ^
0 0 1 1 0 0 1 1 0 1    941      1001 0100 0001
            ^ ^ ^
1 1 0 0 1 1 1 1 1 1    879      1000 0111 1001
      ^ ^   ^ ^ ^
1 1 1 0 0 0 1 1 1 0    986      1001 1000 0110
      ^ ^   ^ ^ ^
0 0 1 1 1 1 1 1 1 1    999      1001 1001 1001
      ^ ^   ^ ^ ^
1 1 1 1 1 1 1 1 1 1    999      1001 1001 1001
      ^ ^   ^ ^ ^

Scoring & winning criterion

The score is the number of two-input NAND gates used in your circuit. The lowest score wins.

You may define small components in terms of two-input NAND gates, and then use them in your final construction. If a component X includes N two-input NAND gates, each usage of X adds N to your score. For basic logic gates, this means:

NOT: +1
2-input AND: +2
2-input OR: +3
2-input XOR: +4

45 NANDs (or 43)
45 seems to be the absolute minimum, but it is possible to reach 43 NANDs by a trick: By assuming that the largest numbers are correctly encoded.
888, 889, 898, 899, 988, 989, 998, 999 are to be encoded
with the 2 MSB as 00, requiring just 43 NANDs for decoding.
However, in the specification for decoding, they are specified to be ignored, meaning they can be anything. It is a reasonable assumption that this freer specification could require even fewer gates, but the opposite is true. 45 gates are required for this. This saving could give real benefits for real circuits.
I also found circuits that were significantly more efficient and faster, containing a few more gates.
No pencil drawn image of the circuit this time. Perhaps later.
The circuit is presented in obvious Verilog code, ready for running with test included.
Verilog code:
// Densely packed decimal (DPD) to decimal, circuit in Verilog.
// 45 NANDs only, which seems to be minimal.
//
// By Kim Øyhus 2019 (c) into (CC BY-SA 3.0.)
// This work is licensed under the Creative Commons Attribution 3.0
// Unported License. To view a copy of this license, visit
// https://creativecommons.org/licenses/by-sa/3.0/
//
// This is my entry to win this Programming Puzzle & Code Golf
// at Stack Exchange:
// https://codegolf.stackexchange.com/questions/176557/densely-packed-decimal-dpd-to-decimal-with-logic-gates
//
// TASK:
// 3 decimal digits are stored in 10 bits in the DPD format,
// and this circuit transforms them into 3 decimal digits in
// 4 bits each, BCD format.
//
// 45 gates seem to be the smallest possible NAND circuit there is
// for this task, but I can get even lower by a trick, to 43:
// I assume that the largest numbers are correctly encoded.
//   888, 889, 898, 899, 988, 989, 998, 999 are to be encoded
// with the 2 MSB as 00, requiring just 43 NANDs for decoding.
//
//   However, in the specification for decoding, they are specified
// to be ignored, meaning they can be anything. It is a reasonable
// assumption that this freer specification could require even fewer
// gates, but the opposite is true. 45 gates are required for this.
// This saving could give real benefits for real circuits.
//
//   This DPD format seems to be used a lot for storing decimal numbers
// in computers and IO for ALUs, even though it is stored as 12 bits
// per 3 digits inside the ALUs and for other calculations.
// It is also used in many patents.

module decode1000 ( in_000, in_001, in_002, in_003, in_004, in_005, in_006, in_007, in_008, in_009, out000, out001, out002, out003, out004, out005, out006, out007, out008, out009, out010, out011 );
  input  in_000, in_001, in_002, in_003, in_004, in_005, in_006, in_007, in_008, in_009;
  output out000, out001, out002, out003, out004, out005, out006, out007, out008, out009, out010, out011;
  wire   wir000, wir001, wir002, wir003, wir004, wir005, wir006, wir007, wir008, wir009, wir010, wir011, wir012, wir013, wir014, wir015, wir016, wir017, wir018, wir019, wir020, wir021, wir022, wir023, wir024, wir025, wir026, wir027, wir028, wir029, wir030, wir031, wir032;

  nand gate000 ( wir000, in_007, in_007 );
  nand gate001 ( wir001, in_003, in_001 );
  nand gate002 ( wir002, in_002, in_003 );
  nand gate003 ( wir003, wir001, in_006 );
  nand gate004 ( wir004, wir002, in_001 );
  nand gate005 ( wir005, wir001, wir001 );
  nand gate006 ( wir006, in_005, in_001 );
  nand gate007 ( wir007, wir006, in_003 );
  nand gate008 ( out008, wir000, wir000 );
  nand gate009 ( wir008, wir004, wir007 );
  nand gate010 ( wir009, wir005, in_006 );
  nand gate011 ( wir010, wir007, wir007 );
  nand gate012 ( wir011, wir009, in_002 );
  nand gate013 ( wir012, wir011, wir009 );
  nand gate014 ( wir013, wir011, wir011 );
  nand gate015 ( wir014, in_008, wir013 );
  nand gate016 ( wir015, in_009, wir013 );
  nand gate017 ( wir016, wir010, wir014 );
  nand gate018 ( wir017, wir014, wir005 );
  nand gate019 ( wir018, wir015, wir015 );
  nand gate020 ( wir019, wir011, wir008 );
  nand gate021 ( wir020, wir019, wir006 );
  nand gate022 ( wir021, wir010, wir018 );
  nand gate023 ( wir022, wir020, wir004 );
  nand gate024 ( wir023, wir016, wir008 );
  nand gate025 ( out001, wir023, wir023 );
  nand gate026 ( out003, wir022, wir022 );
  nand gate027 ( wir024, wir005, wir008 );
  nand gate028 ( wir025, wir012, wir002 );
  nand gate029 ( wir026, wir019, in_003 );
  nand gate030 ( wir027, in_004, in_004 );
  nand gate031 ( out007, wir024, wir009 );
  nand gate032 ( out011, wir026, wir026 );
  nand gate033 ( wir028, wir017, in_005 );
  nand gate034 ( wir029, in_000, in_000 );
  nand gate035 ( wir030, wir026, in_008 );
  nand gate036 ( out005, wir028, wir028 );
  nand gate037 ( out009, wir030, wir030 );
  nand gate038 ( out000, wir029, wir029 );
  nand gate039 ( wir031, wir026, in_009 );
  nand gate040 ( out004, wir027, wir027 );
  nand gate041 ( out010, wir031, wir031 );
  nand gate042 ( wir032, out003, wir018 );
  nand gate043 ( out006, wir003, wir032 );
  nand gate044 ( out002, wir025, wir021 );
endmodule

module test;
   reg  [ 9:0] AB; // input DPD
   wire [11:0] C; // output BCD

  decode1000 U1 (
  .in_000 (AB[ 0]),
  .in_001 (AB[ 1]),
  .in_002 (AB[ 2]),
  .in_003 (AB[ 3]),
  .in_004 (AB[ 4]),
  .in_005 (AB[ 5]),
  .in_006 (AB[ 6]),
  .in_007 (AB[ 7]),
  .in_008 (AB[ 8]),
  .in_009 (AB[ 9]),
  .out000 ( C[ 0]),
  .out001 ( C[ 1]),
  .out002 ( C[ 2]),
  .out003 ( C[ 3]),
  .out004 ( C[ 4]),
  .out005 ( C[ 5]),
  .out006 ( C[ 6]),
  .out007 ( C[ 7]),
  .out008 ( C[ 8]),
  .out009 ( C[ 9]),
  .out010 ( C[10]),
  .out011 ( C[11])
  );

   initial  AB=0;  //unary=0;  binary=0
  always  #1  AB = AB+1;
  initial  begin
    $display("\t\ttime,\tinn 10bit   \tout 3x4bit");
    $monitor("%d,\t%b %b %b\t%b %b %b\t %d%d%d",$time, AB[9:7],AB[6:4],AB[3:0], C[11:8], C[7:4], C[3:0],  C[11:8], C[7:4], C[3:0]);
  end
  initial  #1023  $finish;
endmodule

// How I run and test it:
// iverilog -o decode1000 decode1000.v
// vvp decode1000


The Camouflage Color Changing Chameleon Challenge Chameleon challenges are a bad thing, apparently. Too bad, chameleons are beautiful creatures. Time for a change!

As we all know, many chameleons posses a remarkable ability to blend in with their surroundings by changing the color of their skin. Which is also the objective of this challenge.

Challenge

Imagine a square of nine pixels. Eight pixels are the surroundings. At the center is the chameleon.

Like this:

The chameleon naturally tries to blend in with its surroundings. It does so by changing its color to the average of that of the surrounding pixels. So, in this case, the chameleon would change its color to .

Objective

Given the colors of the surrounding pixels, output the color of the chameleon.

The color of the chameleon is defined as the total of all red, green and blue in the pixels ÷ 8.

Input

An array of color values for the eight surrounding pixels, starting at the top left and continuing clockwise, like this:

[[<red>,<green>,<blue>],[<red>,<green>,<blue>],[<red>,<green>,<blue>],[<red>,<green>,<blue>],[<red>,<green>,<blue>],[<red>,<green>,<blue>],[<red>,<green>,<blue>],[<red>,<green>,<blue>]]

You may choose to receive input in a different form, as long as it consists of eight triples of decimal numbers 0-255.

If you receive input in a different form, numbers must either be of a consistent length or have a non-numeric separator between them. Triples must have a separating character unless they are 0-padded to 9 digits. (E.g. 044200255044200255044200255044200255044200255044200255044200255044200255 is valid, so are 44 200 255 44 200 255 44 200 255 44 200 255 44 200 255 44 200 255 44 200 255 44 200 255 and 44?200?255$44?200?255$44?200?255$44?200?255$44?200?255$44?200?255$44?200?255$44?200?255, but 4420025544200255442002554420025544200255442002554420025544200255 is not.)

Output

An array / string / etc. containing the colors of the center pixel (in decimal), like this:

[<red>,<green>,<blue>]

In case you output something other than an array: Numbers must either be of a consistent length or have a non-numeric separator between them. (E.g. 044200255 is valid, so is 44 200 255, but 44200255 is not.)

The numbers may not contain decimal points, so e.g. 44.0 200 255.0 is invalid.

Rounding

Output must be rounded to the nearest integer. (Halves must be rounded up.) E.g., if the sum of all red is 1620, you must output 203, not 202 or 202.5.

Examples

Pictures are for illustration only. The middle pixel is the output, the surrounding pixels are the input.

Input:

[[200,200,200],[200,200,200],[200,200,200],[200,200,200],[200,200,200],[200,200,200],[200,200,200],[200,200,200]]

Output:

[200,200,200]

Input:

[[0,0,0],[255,255,255],[0,0,0],[255,255,255],[255,255,255],[0,0,0],[255,255,255],[0,0,0]]

Output:

[128,128,128]

Input:

[[0,200,200],[200,0,200],[200,200,0],[60,200,0],[200,0,200],[0,200,220],[2,200,0],[0,0,0]]

Output:

[83,125,103]

Input:

[[0,56,58],[65,0,200],[33,200,0],[60,33,0],[98,0,200],[0,28,220],[2,200,0],[99,0,5]]

Output:

[45,65,85]

Submissions can be a full program or a function. Standard I/O and loophole rules apply.

Python, 38 bytes

lambda l:[sum(r)+4>>3for r in zip(*l)]

Rounds the average (towards the nearest integer, with halves rounding up) by adding 4 to the sum, then floor-dividing by 8 via the bit-shift >>3.


Let's draw the flag of Nepal Nepal’s flag (Wikipedia, Numberphile) looks very different from any other. It also has specific drawing instructions (included in the Wikipedia article). I want you guys to make a program which will draw the flag of Nepal.

The user inputs the requested height of the flag (from 100 to 10000 pixels) and the program outputs the flag of Nepal. You can choose any way to draw the flag: everything from ASCII art to OpenGL.

This is a popularity contest, so the winner will be the highest voted answer on the 1st of February, so don’t worry about length of code, but remember that shorter code may get more up-votes.

There is only one requirement: you are not allowed to use web resources.

Have fun :)


Crazy Librarian's Arithmetic Sequence of Primes Well, the librarian caught you cheating at your job by using your sorting algorithm, so now you're being punished. You've been ordered to create some code so the librarian can impress the object of their unrequited affection, the math teacher. So that's what "Other duties as assigned" means ...
Everyone is familiar with the natural number sequence in base 10, called \$\mathbb N\$:

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

From that, we can generate the prime number sequence, let's call it \$\mathbb P\$, such that every element in \$\mathbb P\$ has exactly two divisors in \$\mathbb N\$, namely 1 and itself. This sequence is:

2, 3, 5, 7, 11, 13, ...

OK, pretty routine so far.
The librarian thought of a nifty function \$F(x, y)\$ that takes a number \$x\$ from \$\mathbb N\$, with the condition \$0 \le x \le 9\$, and a number \$y\$ from \$\mathbb N\$, and inserts \$x\$ into \$y\$'s decimal expansion in every position (i.e., prepending, inserting, or appending \$x\$ into \$y\$), then returns the sorted set of new numbers.
For example, \$F(6, 127)\$ would result in

1267, 1276, 1627, 6127

That's still kinda boring, though. The librarian wants to spice things up a bit more by instead specifying a new function \$z \to \{p : p \in \mathbb P , F(z,p) \subset \mathbb P\}\$, sorted ascending.
For example, \$z(7)\$ would be

3, 19, 97, 433, 487, 541, ...

because \$37\$ and \$73\$ are both prime, \$719\$, \$179\$ and \$197\$ are all prime, etc.
Note that \$z(2)\$ is empty, because no prime that has a \$2\$ appended will ever still be prime. Similarly for \$\{0,4,5,6,8\}\$.
Your task is to write code that will generate and output the first 100 numbers in sequence \$z(x)\$ for a given \$x\$.
Input
A single integer \$x\$ such that \$0 \le x \le 9\$. Input can be via function argument, STDIN, or equivalent.
Output
A sequence of the first 100 numbers, delimited by your choosing, to STDOUT or equivalent, such that the sequence satisfies \$z(x)\$ as described above. If \$z(x)\$ is empty, as is the case for \$\{0,2,4,5,6,8\}\$, the words Empty Set should be output instead.
Restrictions

This is code-golf, since you'll need to transcribe this to an index card so the librarian can show the math teacher, and your hand cramps easily.
Standard loophole restrictions apply. The librarian doesn't tolerate cheaters.

Reference sequences
x=1 : A069246
x=3 : A215419
x=7 : A215420
x=9 : A215421
Related:
Find the largest fragile prime /
Find the smallest prime from a substring / Find largest prime which is still a prime after digit deletion

Pyth, 49 bytes

Like the Python3 and other Pyth answer, the runtime for finding 100 numbers is prohibitive. (test suite gives 10)

?}z"1379".f&!tPZ!|FmtPvjzc`Z]dhl`Z*TT3"Empty Set"

Try it online


The Cake Cutting Contest It's my 17th birthday and you're invited to my party!

And as always at parties, there will be cake.

One cake...

And you need as much of it as possible.

As this is a fair party, each of us will say how much of my cake we want and the person who said the smallest amount will get it. Then everyone else gets to repeat the process until the cake is gone.

Challenge

Given the input through command line arguments in the form of total-degrees degrees-left total-people people-left, output to standard output integer-bid-in-degrees.
If your bid was the lowest, you receive that amount of cake and are out for the round.
If your bid wasn't lowest, your bot gets to bid on the remaining cake.
In the case that the lowest bids are the same, the person removed will be chosen at random.
At the end of a round, once all the cake is gone or there is nobody left to bid on it, the person with the most cake wins!
In the case at the end of a round and two people have the same sized biggest slice, the winner is chosen at random from the drawing entries.

Gameplay

There will be 17 rounds, the overall winner will be the entry with the most wins overall.
In the case of a draw, rounds will be played until there is a clear winner.
Each day, I will update the current scores so that people can upgrade their entry.

Submission

You should write your entry as

  Bot Name, Language

Insert
Code
Here

  Explanation/Random stuff here

If your entry isn't formatted in this way, the controller will NOT be able to run your entry. If I find this has happened to your entry, I will either notify you in a comment, and/or edit the answer into the correct format.

Your entry and file storage

Your bot may store files in the ./data/ directory and nowhere else.

Not required but please store your files as botname*
You may not write files in this format if botname is not your entries name.
This means you are allowed to overwrite other files you find that don't appear in this format. You shouldn't do this deliberately, please be sporting.
Your bot must not assume that the files it requires are present but it can assume ./data/ exists.
This is because I occasionally wipe the ./data directory, I will do this when the rounds actually start. (But not between them)

Your bot may not delete files at all
Your bot is only allowed to read files in the ./data/ directory

This means you may look at other entries files

Results:

Meek won the contest! Well done @Cabbie407

And now for some random stats:

A list of positions each bot came in: (Well done to any bot appearing in this list, you came in the top 5 at least once!)

Meek, Meek, Eidetic, Eidetic, Meek, Eidetic, Eidetic, Meek, Meek, Meek, Saucy, Meek, Givemethecake, Givemethecake, Givemethecake, Meek, Eidetic
Eidetic, Eidetic, Meek, AlCakeSurfer, Eidetic, AlCakeSurfer, Meek, MyFairPlusAThird, Eidetic, Eidetic, Eidetic, Eidetic, MyFairPlusAThird, MyFairPlusAThird, Meek, MyFairPlusAThird, AlCakeSurfer
Reallythecake, AlCakeSurfer, AlCakeSurfer, Meek, AlCakeSurfer, Meek, AlCakeSurfer, AlCakeSurfer, Reallythecake, AlCakeSurfer, Meek, MyFairPlusAThird, Eidetic, Eidetic, Eidetic, Eidetic, Reallythecake
AlCakeSurfer, Reallythecake, MyFairPlusAThird, MyFairPlusAThird, MyFairPlusAThird, MyFairPlusAThird, MyFairPlusAThird, Eidetic, AlCakeSurfer, MyFairPlusAThird, MyFairPlusAThird, Relinquisher, Relinquisher, bill, bill, Relinquisher, MyFairPlusAThird
bill, MyFairPlusAThird, bill, bill, bill, bill, Relinquisher, Relinquisher, MyFairPlusAThird, Relinquisher, bill, Reallythecake, bill, ALittleOffTheTop, ALittleOffTheTop, bill, bill

The full log file for the cometition whilst running can be found here. Sorry about the format change partway through.

I will not be running the contest again, if you want to post more entries, you're welcome to do so, the controller can be found on my github repo for this contest.

Magician, Java

public class Magician{
    public static void main(String[] args){
        System.out.println(720);
    }
}

The number 720 is magical.

This is was meant to test the controller and is not a serious entry.


Hello, new world! again Objective:

  This code-golf is about creating 2 different sourcecodes that both outputs exactly: Hello, new world! again. without linefeed, and when combining the two sourcecodes into one sourcecode it should still output exactly: Hello, new world! again.

Rules:

Your programs should take no input (from user, filename, network or anything).
You can choose any combination of programming languages, from one language for all three sourcecodes to three different languages.
The combination of the two sourcecodes to create the third is done by putting alternating characters from both from start to end and fill up the third sourcecode from start to end.
You must choose 10 different characters that both sourcecodes may use (case sensitive). All other characters is mutual exclusive between the two sourcecodes. Characters may be re-used without restriction. Exactly all 10 characters choosen must be used in both sourcecodes atleast once.

Clarification example on sourcecode combination:

Javascript          sourcecode: console.log("Hello, new world! again.");
GolfScript          sourcecode: 'Hello, new world! again.'
Combined (unknown?) sourcecode: c'oHneslolloe,. lnoegw( "wHoerllldo!,  angeawi nw.o'rld! again.");

The above example does however violate rule #4 as more than 10 characters is "shared" in both sourcecodes. And the combined sourcecode does not output: Hello, new world! again.

Be sure to declare what programming languages is used (all three) and what 10 characters that is allowed in both sourcecodes.

This is code-golf, least bytes in combined sourcecode wins! Good luck, have fun!

C99 + sh + C11, 165 162 146 145 combined chars

Edit: using @flonk's trick I managed to put the "comment" in C (making use of C11's u"" Unicode literals).

Common characters are: acehinortu.

hello.c (106):

*a="\2+++++++++++++++++++++++++++++++++";i;main(){for(;i<24;)putchar("Lipps0$ri{${svph%$ekemr2"[i++]+~3);}

hello.sh (39):

true
echo -n 'Hello, new world! again.'

hello-combined.c (145):

*tar=u"e\
2e+c+h+o+ +-+n+ +'+H+e+l+l+o+,+ +n+e+w+ +w+o+r+l+d+!+ +a+g+a+i+n+.+'";i;main(){for(;i<24;)putchar("Lipps0$ri{${svph%$ekemr2"[i++]+~3);}

Here are some utilities that might prove useful for other participants.

combine.c:

#include <stdio.h>
int main(int argc, char *argv[]) {
  FILE *f1 = fopen(argv[1], "r"), *f2 = fopen(argv[2], "r");
  while (!feof(f1) || !feof(f2)) {
    int c1 = fgetc(f1), c2 = fgetc(f2);
    if (c1 != EOF) putchar(c1);
    if (c2 != EOF) putchar(c2);
  }
  return 0;
}

char-check.{ba,z}sh:

comm -12 <(grep -o . "$1" | sort | uniq) \
         <(grep -o . "$2" | sort | uniq) | tr -d '\n'

Here's a variation that unfortunately ended up (considerably) longer, but it's pretty cool in how it works.  (I didn't bother getting the intersection between the sets of characters down to 10, since it ended up longer anyway.)

hello.c (113):

*a="\5Lipps0$ri{${svph%$ekemr2+++++++++++",*b=&a,c=6;i;main(){char*p=*b;for(i=c/8;p[i]-50;)putchar(p[i+=c/4]-4);}

hello.sh (51):

true
echo -n 'Hello, new world! again.' #     tr  1

hello-combined.c (164):

*tar=u"e\
5eLcihpop s-0n$ r'iH{e$l{lsov,p hn%e$we kweomrrl2d+!+ +a+g+a+i+n+.+'+ +#" , * b = &tar, c =16;i;main(){char*p=*b;for(i=c/8;p[i]-50;)putchar(p[i+=c/4]-4);}

This one is fun, because it doesn't just "comment out" a bunch of characters, but actually stores the characters it prints inside the string literal and accounts for the extra characters in the for-loop of the generated program.


Generate a 6 character string from a 15 character alphabet In one of our projects at work, we recently discovered a particularly large method for generating a 6 character string from a 15 character alphabet. A few of us claimed "I bet we can get that in one line" which started a little internal game of code golf.

Your task is to beat us, which I have no doubt won't take long!

The original algorithm used the alphabet 0-9A-E, but we've experimented with other alphabets. There are therefore three subtasks.

Generate a 6 character string randomly selecting from an arbitrary hardcoded 15 character alphabet like ABC123!@TPOI098. (This is just an example, and should be customizable without affecting the byte count.)
Generate a 6 character string randomly selecting from a 15 character alphabet 0123456789ABCDE.
Generate a 6 character string randomly selecting from a 15 character alphabet of your choice (printable characters only please).

Each character should have equal chance of selection and repetition should be possible.

The best we have been able to manage for each of the subtasks is:

"ABC123!@TPOI098" - 24 bytes
"0123456789ABCDE" - 21 bytes
Custom alphabet   -  13 bytes

Your score is the sum of the bytes in each subtask's solution. i.e. our score is currently 58.

We've attempted using among others, CJam and Ruby. The original was in C#. Use any language you like, but we'll be interested to see solutions in these languages particularly

CJam (23 + 14 + 10 = 47 bytes)

Arbitrary alphabet: 23 bytes (online demo)

{"ABC123!@TPOI098"mR}6*

Hexadecimal alphabet: 14 bytes (online demo)

{FmrAbHb'0+}6*

Custom alphabet: ABCDEFGHIJKLMNO, 10 bytes (online demo)

{Fmr'A+}6*

Dissection

The hexadecimal one is the interesting one:

{      e# Loop...
  Fmr  e#   Select a random number from 0 to 14
  AbHb e#   Convert to base 10 and then to base 17
       e#   (i.e. add 7 if the number is greater than 9)
  '0+  e#   Add character '0' (i.e. add 48 and convert from integer to character)
       e#   Note that 'A' - '0' = 17
}6*    e# ...six times

The six characters are left on the stack and printed automatically.


Generate ladder of integers using the least number of unique characters (in C++) I am new to the sport of code golf. I am trying to generate a ladder of integers using the least number of unique characters in C++.

Let's say we are given an integer 4.

We will generate the following ladder:

1
1 2
1 2 3
1 2 3 4

In short, my program will read a positive integer from stdin and print this ladder to the output. I am trying to do so with the least number of unique characters possible.

My program is as follows:

#include<iostream>

int i;
int ii;
int iii;
int iiii;

main() {
    std::cin >> i;
    for(ii++; ii <= i; ii++) {
        int iii = iiii;
        for(iii++; iii <= ii; iii++) {
            std::cout << iii << " ";
        }
        std::cout << std::endl;
    }
}

Here's the checker that I used to check the number of unique characters in my program:

#include <cstdio>
#include <cstring>
using namespace std;
int check[300],diffcnt=0,cnt=0,t;
char c;
double score;
int main(){

    memset(check,0,sizeof(check));
    FILE *in=fopen("ans.cpp","r");
    while(fscanf(in,"%c",&c)!=EOF){
        cnt++;
        if(!check[c]){
            check[c]=1;
            if(c=='\r'||c=='\n') continue;
            diffcnt++;
        }
    }
    if(diffcnt<25) printf("100\n");
    else if(diffcnt<30){
        printf("%.3lf\n",20.0*100.0/cnt+20.0*(29-diffcnt));
    }
    else{
        score=20.0;
        for(int x=95;x<cnt;x++) score*=0.9;
        printf("%.3lf\n",score);
    }
    printf("Unique Characters: %d\n", diffcnt);
    printf("Total Characters: %d\n", cnt);
    return 0;
}

Preferably I wish to use less than 25 unique characters to complete this program (excluding newline characters but including whitespace). Currently, my program uses 27. I am not sure how to optimize it further.

Could someone please advise me on how to optimize it further (in terms of the number of unique characters used)? Please note that only C++ can be used.

I believe I managed to remove the = character from your code, although it now is significantly slower

#include<iostream>

int i;
int ii;
int iii;
int iiii;

int main() {
    std::cin >> i;
    i++;
    for(ii++; ii < i;) {
    for(;iii>iiii;iii++);
    for(;iii<iiii;iii++);
    ii++;
        for(iii++; iii < ii; iii++) {
            std::cout << iii << " ";
        }
        std::cout << std::endl;
    }
}

Its not pretty, but by abusing integer overflow we can get back to 0 without using =

Also we had to change the guards a little. Unfortunately because of the include I couldn't get rid of all new line characters (although its close) so that may be the next avenue for investigation.

Edit: Run out of time for now, but if you include and use strstream and various other libraries, I think you may be able to remove the " character too, again using integers to arrive at the correct character for space and passing it into the strstream


PCM Wave time stretch Write the smallest program performs a time stretch operation on a PCM Wave (.wav) file.

Rules:

Parameter input will by via whatever standard argument mechanism your language comes with, e.g. argv in C/C++, $_GET in PHP. Hard coded paths are not allowed.
First parameter will be a decimal value that represents the stretch coefficient. 1 means don't stretch, 2 means twice the length, 0.5 means half the length, 0.333 means one third the length. An example might be stretch.exe 1.5 c:\sound.wav
The time stretch operation does not need to perform pitch correction.
You must not drop samples to fit a compression (i.e. stretch < 1). You should use interpolation, weighted mean, or a similar method.
Assume a WAVE PCM file with a RIFF header.
Assume 16-bits per sample (bonus if your code works for 8-bit and 24-bit audio)
You must handle any number of audio channels.
You must at least handle 11025, 22050 and 44100Hz sample rates, though the ability to handle arbitrary rates would be a bonus! :)
Your output file must keep the same sample rate, sample size and channel count as the input file.
The output file must be named "stretch.wav"
You may not use any 3rd party libraries or built-in functions for audio processing. The parsing of the WAV file and the time stretch operation must be your own code.

On Windows, the C:\Windows\Media directory contains plenty of WAV files to test with.

Ruby, 220 characters
s,n=$*
w=IO.binread(n).unpack r='s<*'
x=[];t=[g=0]*c=w[11]
w[u=22..-1].each_slice(c){|f|g+=v=1.0/s.to_f
c.times{|h|t[h]+=f[h]*v}
(c.times{|h|x<<=m=t[h]/g;t[h]-=m};g-=1)until 1>g}
w[u]=x;IO.binwrite'stretch.wav',w.pack(r)

This version works with ruby 1.9.3 with basic 16 bit files (e.g. no additional chunks) for any sample rate or number of channels.


Divisibility of numbers Challenge
HP is doing research in mathematics . After doing lots of research, she struck in a problem . She found four numbers n,a, b and c .Now, She wants to know how many number exists which are less than or equal to n and are divisible by a ,b or c .
Input :
4 integers denoting n,a,b and c separated by space
Output :
intger which denotes the count of the numbers which are divisible a,b,c
Scoring:
This is code-golf, shortest code in bytes wins.

Python 2, 72 65 bytes

Note: This solution works for positive integers:

lambda a,b,c,n:len([x for x in range(1,n+1)if x%a*(x%b)*(x%c)<1])

Try it online!


Plot the Gaussian Distribution in 3D In probability theory, the normal (or Gaussian) distribution is a very common continuous probability distribution. Normal distributions are important in statistics and are often used in the natural and social sciences to represent real-valued random variables whose distributions are not known.

The challenge

Your challenge is to plot the probability density of the Gaussian Distribution on a 3-dimensional plane. This function is defined as:

Where:

A = 1, σx = σy = σ

Rules

Your program must take one input σ, the standard deviation.
Your program must print a 3D plot of the Gaussian Distribution in the highest quality as your language/system allows.
Your program may not use a direct Gaussian Distribution or probability density builtin.
Your program does not have to terminate.
Your plot may be in black and white or color.
Your plot must have grid lines on the bottom. Grid lines on the sides (as shown in the examples) are unnecessary.
Your plot does not need to have line numbers next to the grid lines.

Scoring

As usual in code-golf, the submission with the least bytes wins! I may never "accept" an answer using the button, unless one is incredibly small and intuitive.

Example output

Your output could look something like this:

Or it could look like this:

More valid outputs. Invalid outputs.


Primes other than Optimus Challenge

Given an input integer n > 0, output the number of primes (other than n, if n itself is prime) that can be produced by altering one digit in the decimal expansion of n (without changing the number of digits).

Examples

For example, n = 2. By altering one digit in the decimal expansion of 2, we can come up with three additional prime numbers, 3, 5, 7, so a(n) = 3.

For another example, n = 13. By altering one digit, you can get primes 11, 17, 19, 23, 43, 53, 73, 83, so a(13) = 8.

For a final example, n = 20. By altering one digit, you can get primes 23, 29, so a(20) = 2.

Sequence

Here are the first 20 terms to get you started. This is OEIS A048853.

4, 3, 3, 4, 3, 4, 3, 4, 4, 4, 7, 4, 8, 4, 4, 4, 7, 4, 7, 2

Rules

The input and output can be assumed to fit in your language's native integer type.
The input and output can be given in any convenient format.
Ignore leading zeros (for example, 03 is not a prime number under this formulation).
Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
If possible, please include a link to an online testing environment so other people can try out your code!
Standard loopholes are forbidden.
This is code-golf so all usual golfing rules apply, and the shortest code (in bytes) wins.

05AB1E, 17 16 14 11 bytes

ā°`<Ÿʒ.L}pO

Explanation:

ā             Push inclusive range from 1 to the length of the input
 °            Raise 10 to the power of each element
  `           Push each element to the stack
   <          Decrement the topmost element
    Ÿ         Inclusive range
              For 13, this creates an array like [10 11 12 13 14 .. 98 99]
     ʒ.L}     Only keep elements with a levenshtein distance to the input of
              exactly one
         p    Check each element for primality
          O   Sum

Try it online! or up to 100.


Now we're thinking in n dimensions! The question: Given an a number n ≥ 2, how many distinct pairs of points on an n-dimensional n x n x n x n x n x n ... x n lattice, where the coordinates range from 0 to n - 1, are a distance at least n apart? The pairs {(2,1,3,1), (3,2,1,3)} and {(3,2,1,3), (2,1,3,1)} are not considered distinct from each other, as they consist of the same two points in reverse order. Note that the total number of pairs grows very rapidly. The number of total pairs goes 6, 351, 32 640, 4 881 250, 1 088 367 840, etc.

Test cases:

2 -> 0 (all pairs are at most a distance of sqrt(2) < 2 apart)
3 -> 28 (They must either be (2,2,1) or a permutation apart, or (2,2,2) apart. Each corner
has three non-corner (2,2,1) points corresponding to it. And each corner is associated
with a corner pair that is a (2,2,2). Thus. 3.5 * 8 = 28.
4 -> 4,888
5 -> 1,501,948
6 -> 486,039,360 (I would like someone to verify this if possible)

Your code should work for n <= 5, at least in theory. Don't hardcode it, that's a standard loophole.

MATL, 12 bytes
tt:Z^tZPR>~z

Try it online!
Explanation
tt   % Implicit input n. Duplicate twice
     % STACK: n, n, n
:    % Range [1 2 ... n]
     % STACK: n, n, [1 2 ... n]
Z^   % Cartesian power. Gives an n^n × n matrix C where each row is a Cartesian tuple
     % STACK: n, C
t    % Duplicate
     % STACK: n, C, C
ZP   % Euclidean distance. Gives an n^n × n^n matrix D of pairwise distances
     % STACK: n, D
R    % Upper triangular part: sets elements below the main diagonal to 0. Call that U
     % STACK: n, U
>~   % Less than or equal? Element-wise. Gives a true-false matrix B
     % STACK: n, B
z    % Number of nonzeros. Implicitly display
     % STACK: number of entries in B that equal true


Write The Shortest Program To Check If A Binary Tree Is Balanced For each node in a balanced binary tree, the maximum difference in the heights of the left child subtree and the right child subtree are at most 1.

The height of a binary tree is the distance from the root node to the node child that is farthest from the root.

Below is an example:

           2 <-- root: Height 1
          / \
         7   5 <-- Height 2
        / \   \
       2   6   9 <-- Height 3
          / \  /
         5  11 4 <-- Height 4

Height of binary tree: 4

The following are binary trees and a report on whether or not they are balanced:

The tree above is unbalanced.

The above tree is balanced.

Write the shortest program possible that accepts as input the root of a binary tree and returns a falsey value if the tree is unbalanced and a truthy value if the tree is balanced.

Input

The root of a binary tree. This may be in the form of a reference to the root object or even a list that is a valid representation of a binary tree.

Output

Returns truthy value: If the tree is balanced

Returns falsey value: If the tree is unbalanced.

Definition of a Binary Tree

A tree is an object that contains a value and either two other trees or pointers to them.

The structure of the binary tree looks something like the following:

typedef struct T
{
   struct T *l;
   struct T *r;
   int v;
}T;

If using a list representation for a binary tree, it may look something like the following:

[root_value, left_node, right_node]

Jelly, 11 bytes

ḊµŒḊ€IỊ;ß€Ạ

Try it online!

The empty tree is represented by [].


Output the spoken names of numbers used on planet Flapus The residents of Flapus use a base-8 number system. The numbers are:

0 - Kuzla
1 - Ponara
2 - Boqkel
3 - Colopee
4 - Vruenat
5 - Foham
6 - Stikty
7 - Kricola

For numbers over 7, the full name of the last digit comes first, followed by apostrophe and the first characters of the other digit(s), up to and including the first vowel:

11 - Ponara(1)'po(1)
13 - Colopee(3)'po(1)
64 - Vruenat'sti
55 - Foham'fo
47 - Kricola'vru

As the numbers go up, the formula stays the same - the full name last digit comes first, followed by an apostrophe and the first characters of the other digits, up to and including the first vowel. Note that apart from the final digit (first word), the order remains the same.

123 - Colopee(3)'po(1)bo(2)
205 - Foham(5)'bo(2)ku(0)
1123 - Colopee'popobo
7654 - Vruenat'kristifo

The exception to the rule is for numbers ending in 0. Here the word begins with Ku and is completed with the first letters of the other digits, up to and including the first vowel. No apostrophe is used.

10 - Kupo
70 - Kukri
350 - Kucofo
630 - Kustico
1000 - Kupokuku

Challenge

Write a program or function that accepts a valid base-8 number, and outputs the spoken equivalent. You may assume you will always receive a valid number. Trailing whitepace / single newline after your answer is ok. The first character needs to be upper-case, as per examples.

This is code-golf. Shortest code in bytes wins. Standard loopholes apply. Answers whose lengths are converted and additionally submitted in Flapussian get extra cookies.

Test cases

0 -> Kuzla
1 -> Ponara
2 -> Boqkel
3 -> Colopee
4 -> Vruenat
5 -> Foham
6 -> Stikty
7 -> Kricola
10 - > Kupo
11 -> Ponara'po
23 -> Colopee'bo
56 -> Stikty'fo
70 -> Kukri
100 -> Kupoku
222 -> Boqkel'bobo
2345 -> Foham'bocovru

Retina, Colopee'pokri, 165 157 143 127 123 bytes

(.+)(.)
$2'$1
0
Kuzla
1
Ponara
2
Boqkel
3
Colopee
4
Vruenat
5
Foham
6
Stikty
7
Kricola
(?<='.*[iou])[a-z]+

T`L`l`'.+
zla'

The trailing linefeed is significant.

Try it online!

Explanation

(.+)(.)
$2'$1

We start by bringing the trailing digit to the front and inserting an apostrophe after it. Note that this leaves single-digit numbers unchanged, since the regex doesn't match - so those never get an apostrophe in the first place.

0
Kuzla
1
Ponara
2
Boqkel
3
Colopee
4
Vruenat
5
Foham
6
Stikty
7
Kricola

This replaces each digit with its full name, regardless of where it appears.

(?<='.*[iou])[a-z]+

This shortens all the digit names that appear after an apostrophe. Note that only the vowels iou appear first in a digit name, so we check a position that is right after one of those, and after an apostrophe and then match (and remove) all lower case letters that follow that position. Since we've inserted the digit names in title case, this will stop before the next digit.

T`L`l`'.+

This uses transliteration to turn all upper case characters, L, into their lower case counterpart, l, provided they are found in a match that starts with ' (in order to leave the leading capital untouched).

zla'

The only thing that's left is correctly handling multiples of (octal) 10. In that case, we'll have a result starting with Kuzla', which we want to start with Ku instead. So we simply remove all occurrences of zla'.


->The Tragedy of Macbeth<- The Setup

Here you can find the full text of The Tragedy of Macbeth.  If you view the source, and save it as text, you will notice it comes out to 206,244 total characters (including the whitespace at the end of the html).

The Challenge

Write a program which compresses the text linked above into the smallest possible text file which can then reproduce the original text exactly (including the whitespace).

The Rules

Your program cannot have any prior knowledge of the text it is compressing.  The goal however is still to compress this specific text, so don't worry if it sucks at other text as long as it does the best job possible on Macbeth.

The program must take either "compress" or "decompress" as the first parameter and the text file as the second command line parameter.  The compressed output has to be a text file, and it has to be UTF16.  The compressed output when decompressed must match exactly the original file in a character for character comparison.

The program needs to finish in a reasonable amount of time.  If it takes longer than a few seconds, please list the average running time with your submission.

The Scoring

The only score is the number of characters in the compressed output.  The score only counts if the decompress matches the original in a character for character comparison.

Pseudo-code, compresses Macbeth to 0 bytes

Counter-example (yeah, almost joke) submission intended to point out the flaws with the question.  (the C# was a bit long both in source size and resulting output)

if argument is "compress"
  compare entire input file to the Tragedy of Macbeth
  if equal, then output empty file
  else if input is non-empty,
    then RLE-encode input stream on chr(127) only and output that
  else [if input is empty]
    then RLE-encode a string of zero times chr(127)
else if argument is "decompress"
  if input is empty
  then output the Tragedy of Macbeth
  else RLE-decode input file on chr(127) only and output back

With this approach, Macbeth is brought down to as short a file as possible. Other text input is usually passed untouched, at worst gains a byte per chr(127) which tend not to occur in actual text.


The Top Ten Elements You Won't BELIEVE Are In This Array AKA: Generate Clickbait From an Array.

Given an array of integers, generate some cringe-worthy clickbait based on its arrangement and length:

If it's 20 elements or less, you can make a Top X List. Parameters: length of the array.
Prime numbers are celebrities, so anytime two of them are next to each other it'll pass as gossip. Parameters: the two adjacent primes in the order they appear in the array.
If any number appears twice or more in the array, then it's shocking and unbelievable and everyone needs to hear about it. If multiple numbers appear twice, make a news story for each one. Only print this once per unique number. Parameters: occurrence of the number measured by total appearance.
If you see 3+ elements in sorted monotonically increasing order, followed by a sudden decrease, then tell of how they're sorted and tease about what happens next. Only do this once per straight. Parameters: length of the straight.

These are the respective clickbaits you should use:

The Top {{N}} Array Elements
{{N1}} And {{N2}} Were Spotted Together, You Won't Believe What They Did
These {{N}} Elements Will Blow Your Mind
{{N}} Elements Sort Themselves, Find Out What Comes Next

Remember, you represent a cheap media company, so you'll need to milk this and print every possible title. If there are 2 identical titles, print them both.

For example, if you're given this array…

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

You should output all of these, in arbitrary order:

The Top 9 Array Elements
2 And 3 Were Spotted Together, You Won't Believe What They Did
These 2 Elements Will Blow Your Mind
These 3 Elements Will Blow Your Mind
4 Elements Sort Themselves, Find Out What Comes Next

Note the lack of this title:

3 Elements Sort Themselves, Find Out What Comes Next

As code golf, the shortest answer in bytes wins.

Jelly, 142 bytes

I>-ṣ0ṖS€ỊÐḟ‘ɓĠL€ḟ1,ɓ¹ƝÆPẠ$ÐfW;ɓLẋ<¥21W;ż@€"“æƥu®ụ³Km&|°ẓz“ṿ$¥{d3ɓFȤSJẎVḍnṃ*¹0Ḟ¬ȤɲƝċƲạB'ɼɓ.€⁺Ƒ“¢ßUṡʠx\~⁻ḅėʠAƓḳ¶e<“½ė!Ƙ¥Ḍ3]⁷ṀƭȮþċ⁽?ṫĠƁÆȦØ⁾Ż»ṣ€⁷¤

A monadic link accepting a list of integers, returning a list of lists of clickbaits (each of which is a list of characters and integers). For a full program printing line-feed separated clickbaits just add ẎY to the end.

Try it online! (Footer makes a single list of clickbaits and then separates them with new-lines.)
...or see the example given in the question.

How?

The 99 right-most bytes of this Link form a nilad (a function with zero arguments, i.e. a constant):

“...“...“...“...»ṣ€⁷¤
                    ¤ - nilad followed by link(s) as a nilad:
“...“...“...“...»     - list of compressed strings (the four clickbait-texts with the
                      -   integers replaced with line-feed characters)
                   ⁷  - literal line-feed character
                 ṣ€   - split-at for €ach (read to interweave with the integers)

Let's label these text-parts as X, now the Link is:

I>-ṣ0ṖS€ỊÐḟ‘ɓĠL€ḟ1,ɓ¹ƝÆPẠ$ÐfW;ɓLẋ<¥21W;ż@€"X - Link: list of integers Z
                                             - # get the monotonically increasing runs:
I                                            - incremental differences of Z
 >-                                          - greater than -1 (vectorises)
   ṣ0                                        - split at zeros
     Ṗ                                       - pop (discard final run)
      S€                                     - sum each (length - 1 for all runs)
         Ðḟ                                  - filter discard if:
        Ị                                    -   insignificant (discard any 0s or 1s)
           ‘                                 - increment (yielding all run-lengths >= 3)
            ɓ                                - new dyadic chain with that on the right
                                             - # get the multiplicities:
             Ġ                               - group indices of Z by value
              L€                             - length of €ach
                ḟ1                           - filter discard 1s
                  ,                          - pair with right (the run-lengths)
                   ɓ                         - new dyadic chain with that on the right
                                             - # get the prime-pairs
                     Ɲ                       - for each pair in Z
                    ¹                        -   identity (do nothing)
                          Ðf                 - filter keep if:
                         $                   -   last two links as a monad:
                      ÆP                     -     is prime? (vectorises)
                        Ạ                    -     all?
                            W                - wrap in a list
                             ;               - concatenate with right ([multiplicities,runs])
                              ɓ              - new dyadic chain with that on the right
                                             - # get top count as a list
                               L             - length
                                   21        - literal 21
                                  ¥          - last two links as a dyad
                                 <           -   less than? (1 if 20 or less, else 0)
                                ẋ            -   repeat ([length] if 20 or less, else [])
                                     W       - wrap in a list (i.e. [[length]] or [[]])
                                      ;      - concatenate with right ([[prime pairs],[multiplicities],[run-lengths]])
                                             - ...now we have [[length],[prime pairs],[multiplicities],[run-lengths]]
                                          "X - zip with X (the text-parts)
                                         €   -   for each (item in the current list):
                                       ż@    -     interleave with swapped arguments


Numbers Decrease while Letters Increase Randomly inspired by Numbers Increase While Letters Decrease

Given a list of mixed letters and integers (e.g., ['a', 2, 3, 'b']) increase the letters by one position in the alphabet (wrapping at z to a) and decrease the numbers by 1. For the above example, the output should be ['b', 1, 2, 'c'].

The input can be a mixed-type list, a delimited string, a list of strings, etc.
z wraps to a, but 1 goes to 0, and 0 goes to -1, etc.
The input will only ever be [a-z] and integers. You can choose capital letters [A-Z] as input if that's easier for you.
The input is guaranteed non-empty.
The input may contain only numbers or only letters.

Examples:

Input
Output

['a', 2, 3, 'b']
['b', 1, 2, 'c']

['a', 'b', 'z']
['b', 'c', 'a']

[-1, 0, 257, 'x']
[-2, -1, 256, 'y']

[0, 3, 1, 20382876]
[-1, 2, 0, 20382875]

Rules and Clarifications

Input and output can be given by any convenient method.
You can print the result to STDOUT or return it as a function result.
The output doesn't have to be the same format as the input (e.g., you could take input as a string and output as a list).
Either a full program or a function are acceptable.
If applicable, you can assume the input/output integers fit in your language's native int range.
Standard loopholes are forbidden.
This is code-golf so all usual golfing rules apply, and the shortest code (in bytes) wins.

05AB1E, 5 bytes

<AAÀ‡

Try it online!

<          # decrement the numbers
 A         # constant "abcdefghijklmnopqrstuvwxyz"
  AÀ       # same, but rotated left ("bcd...yza")
    ‡      # transliterate


Print a physical multiplication table Rectangles have this nice property - an \$n \times m\$ rectangle consists of exactly \$n \times m\$ characters!

A.. more interesting property is that the rectangles can be aligned nicely in a multiplication table - for example, a \$3 \times 3\$ table:

# ## ###

# ## ###
# ## ###

# ## ###
# ## ###
# ## ###

Your challenge is to, given a number \$n\$ (\$ n > 1\$), output a formatted \$n \times n\$ multiplication table.

Rules

You can take the input one above or below \$n\$
Default I/O rules apply
You can choose any non-whitespace character to represent the blocks; every other character (though newlines are special) is considered whitespace. The chosen character can be different for different inputs, but must be the same throughout the input
The result can have unneeded characters, as long as the table aligns up and there are no occurrences of the chosen character that aren't part of the required output
The separators must be 1 character wide/tall, and the rectangles must be packed (i.e. no separators between their characters)
The empty lines can be empty, padding isn't required
The result can be a string, matrix, vector of lines, array of character arrays, or anything 2Dish
You may alternatively output a matrix/vector-of-vectors/anything 2Dish of numbers, but the background & foreground must be 2 distinct numbers (which can vary input to input, but not throughout an output) and no other numbers can be present. Extra surrounding characters are allowed with this format too (though they must match the background number)
This is code-golf, shortest answer in bytes, per-language, wins!

Examples

For the input 2, a valid ascii-art output, with the character ∙, is:

        ∙ ∙∙

Result: ∙ ∙∙.
        ∙ ∙∙

yes the period is there just to confuse you
Another valid answer as a number matrix, with 2 being the background number and 9 the foreground:

[[9,2,9,9,2,2],
 [2,2,2,2,2,2],
 [9,2,9,9,2,2],
 [9,2,9,9,2,2]]

An invalid output example would be

#  # #

#  # #

#  # #

as the rectangles have separators in between them.

Example outputs for \$4 \times 4\$:

# ## ### ####

# ## ### ####
# ## ### ####

# ## ### ####
# ## ### ####
# ## ### ####

# ## ### ####
# ## ### ####
# ## ### ####
# ## ### ####

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

Haskell, 43 bytes

f n=map=<<flip(map.max)$show.(10^)=<<[1..n]

Try it online!

A clever approach by Ørjan Johansen outputting with 0's and 1's, generating each 10...00 part as the string representation of a power of 10.

111111111
101001000
111111111
101001000
101001000
111111111
101001000
101001000
101001000

Haskell, 49 bytes

f n=map=<<flip(map.max)$[0^i|x<-[1..n],i<-[0..x]]

Try it online!

Generates a pattern like [1,0,1,0,0,1,0,0,0,...], then makes a 2D by taking the min of pairs. The pointfree weirdness saves 2 bytes over the more readable:

f n|l<-do x<-[1..n];0:(1<$[1..x])=[[a*b|a<-l]|b<-l]

Try it online!


How to golf string output in Chef I'm attempting to solve a programming golf style programming puzzle. I need to write an 18 character phrase in Chef in less than 32 "lines" of code. In this case, a line counts as an ingredient or an instruction.

The most straightforward way of doing this is to declare an ingredient for each character and put each ingredient into a baking dish. Unfortunately for what I'm trying to do, that takes too many "lines" of code. (I'm limited to 32 and I want to print a 18 character phrase. 18*2 + title + serves command + headers = 40).

Here are things I tried:

So I had the idea of just using large numbers that would span multiple unicode chars. But when I print it out, I get garbage. So then I had the idea to just stream my characters by reading off each byte of a large number at a time and popping them into a baking dish in a loop. Unfortunately, there doesn't seem to be a way to do with the operators I have (the basic four arithmetic operators). I tried taking a number, dividing by 256, multiplying by 256, and subtracting that from my original number to get the least significant byte, but then discovered that Chef uses floating point (that is the number doesn't change).

There are no logical operators. There's no comparison operators. Any idea on what I can try next to print out an 18 character phrase in less than 32 "lines" of code? (Putting commands on the same line doesn't help. It still counts the same).

Chef has no string types, so the ingredients are positive integers. 0 is used to separate the starting list from used ingredients and to end the used ingredients list.

A, B: stack
    T, J, IN: int
    T = 1
    A.push(0) // used as the marker for the bottom of the stack
    IN = input() // input the first list
    while(IN):
        A.push(IN)
        IN = input()
    IN = input() // for each used ingredient
    while(IN):
        B.push(0)
        while(T): // move all ingredients up to and including the one we are moving right now to the second stack
            T = A.peek() - IN
            B.push(A.pop())
        A.push(B.pop())
        if(A.peekUnderTop() != 0):
            A.swapTopTwoItems()
        T = B.pop() // move the ingredients from the second stack back to the first
        while(T):
            A.push(T)
            T = B.pop()
        T = IN // to make it non-zero for next iteration
        IN = input(0
    print(A.inverted())


Make the Mexican Wave In as few bytes as possible, write a program or function that outputs the following:

Abcdefghijklmnopqrstuvwxyz
aBcdefghijklmnopqrstuvwxyz
abCdefghijklmnopqrstuvwxyz
abcDefghijklmnopqrstuvwxyz
abcdEfghijklmnopqrstuvwxyz
abcdeFghijklmnopqrstuvwxyz
abcdefGhijklmnopqrstuvwxyz
abcdefgHijklmnopqrstuvwxyz
abcdefghIjklmnopqrstuvwxyz
abcdefghiJklmnopqrstuvwxyz
abcdefghijKlmnopqrstuvwxyz
abcdefghijkLmnopqrstuvwxyz
abcdefghijklMnopqrstuvwxyz
abcdefghijklmNopqrstuvwxyz
abcdefghijklmnOpqrstuvwxyz
abcdefghijklmnoPqrstuvwxyz
abcdefghijklmnopQrstuvwxyz
abcdefghijklmnopqRstuvwxyz
abcdefghijklmnopqrStuvwxyz
abcdefghijklmnopqrsTuvwxyz
abcdefghijklmnopqrstUvwxyz
abcdefghijklmnopqrstuVwxyz
abcdefghijklmnopqrstuvWxyz
abcdefghijklmnopqrstuvwXyz
abcdefghijklmnopqrstuvwxYz
abcdefghijklmnopqrstuvwxyZ
abcdefghijklmnopqrstuvwxYz
abcdefghijklmnopqrstuvwXyz
abcdefghijklmnopqrstuvWxyz
abcdefghijklmnopqrstuVwxyz
abcdefghijklmnopqrstUvwxyz
abcdefghijklmnopqrsTuvwxyz
abcdefghijklmnopqrStuvwxyz
abcdefghijklmnopqRstuvwxyz
abcdefghijklmnopQrstuvwxyz
abcdefghijklmnoPqrstuvwxyz
abcdefghijklmnOpqrstuvwxyz
abcdefghijklmNopqrstuvwxyz
abcdefghijklMnopqrstuvwxyz
abcdefghijkLmnopqrstuvwxyz
abcdefghijKlmnopqrstuvwxyz
abcdefghiJklmnopqrstuvwxyz
abcdefghIjklmnopqrstuvwxyz
abcdefgHijklmnopqrstuvwxyz
abcdefGhijklmnopqrstuvwxyz
abcdeFghijklmnopqrstuvwxyz
abcdEfghijklmnopqrstuvwxyz
abcDefghijklmnopqrstuvwxyz
abCdefghijklmnopqrstuvwxyz
aBcdefghijklmnopqrstuvwxyz
Abcdefghijklmnopqrstuvwxyz

A trailing newline is permitted. You can find a reference ungolfed Python implementation here.

Pyth, 12 bytes

V+Gt_GXGNrN1

Demonstration.

In Pyth, G is the lowercase alphabet. +Gt_G is abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba, the character that needs to be uppercased in each row.

V sets up a for loop over this string, with N as the loop variable.

In the body, XGNrN1 is a string translation function. X translates G, the alphabet, replacing N with rN1, the uppercase version of N. r ... 1 is the uppercase function. This gives the desired output.


print "Hello, World!" Yes, really.  Print it with a hardware printer  to create a hard copy.

Send the necessary commands/data to your printer such that the following text is printed on a piece of paper:

  Hello, World!

You may use any local- or network-connected printer that is available to you.

If your printer allows, you should use 8pt or greater text in black ink on white paper.

The text should appear on its own line.  It may be left or right positioned as you wish.

Digital photographic/video/GIF evidence of submissions will be helpful.

If your hardware cannot do paper, but allows other exotic hardcopy production such as 3D printing, CNC machining, or printing at the atomic level, then I will happy to accept such interesting submissions.

To clarify, the question asks "Send the necessary commands/data to your printer".  The implication of this is that no further user input should be required.  Opening a print dialog is not sufficient.  Existing answers that do this as of 10:48am PST 31st Dec 2016 will be grandfathered (but not upvoted by me).

Bash, 21 19 bytes
lp<<<Hello,\ World!

And there it is.
2 bytes saved thanks to Dennis!


Output the ALONED numbers Consider the natural sequence up-to 6 (disregard 1):

2,3,4,5,6

We start scanning from the left (in this case from 2), search for a number divisible by 2 (here 4) and then remove both the numbers from the list (here 2 & 4), such that the list reduces to:

3,5,6

We continue the same process, here leftmost is 3, so we search for number divisible by 3. 6 is surely that number and thus 3 and 6 are removed,

5

Now, no further such searches can be made Thus, this becomes the list of ALONED numbers for n=6.

OBJECTIVE

Given a number n greater than 1, print all the corresponding aloned numbers.

INPUT

2
6
15
20
22

OUTPUT

2
5
8,9,11,12,13,15
11,12,13,15,17,19,20
12,13,15,17,19,20,21

YET ANOTHER WORKED OUT EXAMPLE

For n= 22

=>2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22
=>3,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22 (remove 2 & 4)
=>5,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22 (remove 3 & 6)
=>7,8,9,11,12,13,14,15,16,17,18,19,20,21,22 (remove 5 & 10)
=>8,9,11,12,13,15,16,17,18,19,20,21,22 (remove 7 & 14)
=>9,11,12,13,15,17,18,19,20,21,22 (remove 8 & 16)
=>11,12,13,15,17,19,20,21,22 (remove 9 & 18)
=>12,13,15,17,19,20,21 (remove 11 & 22) (OUTPUT)

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

Python 2, 90 79 73 bytes

-6 bytes thanks to xnor

L=range(2,input()+1)
while L[0]*2<=L[-1]:L.remove(L[0]*2);L=L[1:]
print L

Takes the input number on stdin. Ideone it!

Explanation

We construct the initial list from the input number and store it in L. Next, loop while the last number is greater than or equal to 2 times the first number and remove 2 times the first number from the list. This will always be the next number divisible by L[0]. L=L[1:] takes off the first number as well. When the condition is no longer true, no further removals can be made, and the list is printed.


Cops: Make a regex - Make a snake This is the cop's thread. The robber's thread is here.

Write a code that takes an input n and creates a n-by-n "snake matrix".

A snake matrix is a matrix that follows this pattern:

3-by-3:

1  2  3
6  5  4
7  8  9

and 4-by-4:

1   2   3   4
8   7   6   5
9   10  11  12
16  15  14  13

The exact output format is optional. You may for instance output [[1 2 3],[6 5 4],[7 8 9]], or something similar.

You must provide the language name, and a regex that fully matches your code. You can choose how detailed your regex should be. In the extreme, you can write a regex that matches every possible string, in which case it will be very easy to crack your code. You must also provide the output for n=4, so that robbers know the exact format you have opted for.

You may use one of the regex-flavors that are available on regex101.com, or the Ruby flavor.

PCRE (PHP)
Javascript
Python
Golang
Ruby

You must specify which one you are using.

Notes:

You must support any reasonably large n. You may assume it won't overflow the datatype or memory. If the default datatype is 8-bit signed integers, then you can assume n<=11, if it's unsigned 8-bit integers, then you can assume n<=15.
The robbers have to match the submission's output format, except leading/trailing spaces and newlines, since that might have been stripped away by the SE formatting.

Winning criterion:

The winner will be the uncracked submission with the shortest regex, measured in number of characters.

If your post has remained uncracked for 7 days, then you may post the intended solution and mark your submission as safe.

05AB1E, Cracked by mbomb007
Hopefully fun to crack and not too obvious.
Regex (PCRE):
^\w*[+\-*\/%]*\w*.{0,2}$

Output n=4:
[[1, 2, 3, 4], [8, 7, 6, 5], [9, 10, 11, 12], [16, 15, 14, 13]]

Original solution
UXFXLNX*+NFR}ˆ


KeyPad Code to Text! Given a String and an Array as input, your task is to output the text the input String will print when typed on a typical Mobile Keypad. In a Mobile Keypad, a letter is typed by pressing a button n times, where n is the position of where the letter is at on the button's label. So, 22 should output b.

Rules

The Helper Array will contain the Character Map (["  ",".,!","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"]). This will be given to save you some bytes.
The # symbol will toggle case. Initial Case will be lower. So 2#3 should output aD.
The 0 will add a space. So, 202 should output a a.
There will be a space () in the input String to start a new letter that is on the same numeric button. For Example to type aa, the input String will be 2 2.
It is guranteed that the input String will always be a valid KeyPad Code.

Input

You can take input in whatever way your language supports.

Output

You can output the result in any way you want. Function return is also allowed.

Test Cases

#4440555#666888330#999#66688111 -> "I Love You!"
#6#33777 7779990#222#4477744477778627777111 -> "Merry Christmas!"
#44#27 79990#66#3390#999#332777111 -> "Happy New Year!"

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

Pyth - 31 bytes
The new key thing cost me too much.
ss.emr!FZk@@QsedthdfndeTrb8cz\#

Test Suite.


A completely fake reboot This challenge is simple.  Write code that produces what looks exactly like a full reboot of the computer. It must not show anything on the screen that indicates it is not a real reboot and should finish at the normal log in screen you would get after rebooting.

Rules.

You can choose any OS you like to imitate. For example you can reboot into Linux from Windows or any other combination you choose.
The code should display the full shut down/reboot sequence full screen with no signs that it isn't real.
This is a popularity contest so the cooler the better.
The code must in reality be completely harmless, perform no rebooting and b easy to quit at any point.
If you need to use external images to make the reboot look more realistic then your code should grab those automatically from the web.
Your code should be self contained, only relying on standard freely available libraries or tools, and easily executable by following the instructions you provide.
Good luck!

As it is a popularity contest, I will award the win to the answer with the highest number of votes on June 1, 2014.

Following a request to narrow the question, here is an additional rule.

The system should imitate any version of Windows or the Mint, Ubuntu, Debian, Fedora, Archlinux or Mageia distributions of Linux or OS X. For extra coolness, you should shut down in one and open in the other.

Interested people may want to look at Pitch dark (Earth Hour remembrance) where a number of ways are suggested for using the full screen even when starting in an xterm.

zsh + coreutils + unclutter + amixer + xterm (Arch Linux)

I took the answer by @TheDoctor and ran with it. This version has many improvements, and is 99% convincing to an experienced user (me) on my Arch Linux system. I use Zsh since it has good array and floating-point number support.
Dependencies: feh, unclutter, amixer, zsh, xterm

Improvements:

1) Use the number printed in the first column by dmesg, which is the time since boot, (e.g. [    0.000000] ) to determine the time to sleep. Without this it looks very unrealistic on my machine. These times are parsed before the loop (in an early call to sleep) since parsing inside the loop is too slow.

2) Don't print lines where time since boot is larger than 16 seconds. This specific number is machine-dependent, but the point is to avoid printing later dmesg-stuff that comes from inserting/removing usb sticks, etc. and is unrelated to booting.

3) Do all this in a fullscreen terminal window with black background and white text. Kudos to Mechanical Snail for this trick used in: Make a PNG image with "Hello World!" with programming APIs, in the shortest code possible

4) Mute the audio on shutdown, restore volume when script finishes.

5) Hide the mouse cursor, restore when script finishes.

6) Show BIOS and Syslinux splash screens.

Run with: xterm -fu -fg white -bg black -e '/usr/bin/zsh fake-reboot.sh'

Code:

#!/usr/bin/zsh
# Remove (undisplay) the mouse pointer
unclutter -idle 0 -jitter 255 &
# Since there is no easily-accessible (i.e. without being root) shutdown log, we
# fake these messages.
echo "The system is going down for maintenance NOW."
sleep 2.0
echo "[21656.404742] systemd[1]: Shutting down."
echo "[21656.404742] systemd[1]: Stopping Session 1 of user `id -u -n`."
echo "[21656.404742] systemd[1]: Stopped Session 1 of user `id -u -n`."
echo "[21656.404742] systemd[1]: Stopping Sound Card."
# For added effect, store volume and then mute sound
volume=`amixer -- sget Master | awk -F'[][]' 'END{print $2}'`
amixer -- sset Master 0% &> /dev/null
echo "[21656.404742] systemd[1]: Stopped target Sound Card."
sleep 0.5
echo "[21656.919792] systemd[1]: Stopping system-systemd\x2dfsck.slice."
echo "[21656.919792] systemd[1]: Removed slice system-systemd\x2dfsck.slice."
echo "[21656.919792] systemd[1]: Stopping system-netctl\x2difplugd.slice."
echo "[21656.919793] systemd[1]: Removed slice system-netctl\x2difplugd.slice."
echo "[21656.919793] systemd[1]: Stopping User Manager for UID `id -u`..."
sleep 0.7
echo "[21657.624741] systemd[1]: Stopping Graphical Interface."
echo "[21657.624742] systemd[1]: Stopped target Graphical Interface."
echo "[21657.624745] systemd[1]: Stopping Multi-User System."
sleep 0.9
echo "[21658.606561] systemd[1]: Stopped target Multi-User System."
echo "[21658.606562] systemd[1]: Stopping Paths."
echo "[21658.606562] systemd[1]: Stopped D-Bus System Message Bus."
echo "[21658.606562] systemd[1]: Stopped target Paths."
echo "[21658.606568] systemd[1]: Stopping Timers."
echo "[21658.606568] systemd[1]: Stopped target Timers."
echo "[21658.606568] systemd[1]: Stopping Sockets."
echo "[21658.606568] systemd[1]: Stopped target Sockets."
echo "[21658.606568] systemd[1]: Starting Shutdown."
echo "[21658.606571] systemd[1]: Reached target Shutdown."
echo "[21658.606571] systemd[1]: Starting Exit the Session..."
echo "[21658.606571] systemd[1]: Received SIGRTMIN+26 from PID 10988 (kill)."
echo "[21658.606571] systemd[1]: Deactivated swap."
sleep 0.4
echo "[21659.001741] systemd[1]: Starting Unmount All Filesystems."
echo "[21659.001742] systemd[1]: Unmounted /home."
echo "[21659.001742] systemd[1]: Reached target Unmount All Filesystems."
echo "[21659.001742] systemd[1]: Stopping Remount Root and Kernel File Systems..."
echo "[21659.001742] systemd[1]: Stopped Remount Root and Kernel File Systems."
echo "[21659.001743] systemd[1]: Reached target Shutdown."
echo "[21659.001743] systemd[1]: Starting Final Step."
echo "[21659.001743] systemd[1]: Reached target Final Step."
echo "[21659.001754] systemd[1]: Shutting down."
sleep 0.3
echo "[21659.304341] systemd-journal[250]: Journal stopped"
sleep 0.2
echo "System halted."
sleep 2
clear
sleep 1
# Get the BIOS splash screen and display it
wget http://pvv.ntnu.no/~asmunder/bios.jpg  &> /dev/null
feh -Z -x -F -N --force-aliasing bios.jpg &
pid=$! # Store PID of Feh, so we can kill it later
# While showing the BIOS splash, use the time to parse dmesg output into arrays
tim=`dmesg | awk '{print $2}' | sed 's/]//' | grep "[0-9][0-9][0-9][0-9][0-9]"`
tim=($=tim)
dmsg=("${(@f)$(dmesg)}")
sleep 2.5
kill $pid
sleep 0.5
# Get the Syslinux splash and display it
wget http://pvv.ntnu.no/~asmunder/syslinux.png  &> /dev/null
feh -Z -x -F -N --force-aliasing syslinux.png &
pid=$!
sleep 1.3
kill $pid
# Loop through the arrays we created. Calculate the time we have to wait before
# displaying this line. If the wait time is less than 0.1 sec, we skip waiting.
T1=0.0
T2=0.0
n=0
for d in $dmsg; do
  T1=$T2
  T2=${tim[$n]}
  ((dT = $T2-$T1))
  if (( $dT > 0.1));then
    sleep $dT
  fi
  echo $d
  if (( $T2 > 16.0 )); then
    break
  fi
  ((n=$n+1))
done
sleep 1
clear
# It's normally agetty that parses /etc/issue and handles escape codes in a
# special way. Thus we skip the first line of /etc/issue and do that manually.
echo "Arch Linux "`uname -r`" (tty1)"
tail -n +2 /etc/issue
echo `hostname`" login:"
sleep 10
# Reset the mouse pointer so it is visible again
unclutter -idle 5 -jitter 0 &
# Reset the audio volume
amixer -- sset Master $volume &> /dev/null