We Are Number One, but … Task

Your task is to write a program that will take input, and then output the lyrics to We Are Number One, changing specific words. The input will contain both the words to be changed, and the replacement word.

Input

The input will be in the following format:

one, two\n
net, villain\n

(\n is a newline, it's not actually visible.) The input is assured to be this format, and the first word will always be a word the lyrics contains. But you can take input in whatever format you prefer the most.

Output

Your output will be the entire We Are Number One lyrics, but with the words that are given in the input swapped.

Original lyrics:Hey!
We are Number One
Hey!
We are Number One

Now listen closely
Here's a little lesson in trickery
This is going down in history
If you wanna be a Villain Number One
You have to chase a superhero on the run
Just follow my moves, and sneak around
Be careful not to make a sound
(Shh)
(CRUNCH)
(No, don't touch that!)

We are Number One
Hey!
We are Number One
We are Number One

Ha ha ha
Now look at this net, that I just found
When I say go, be ready to throw
Go!
(Throw it on him, not me!)
(Ugh, let's try something else)
Now watch and learn, here's the deal
He'll slip and slide on this banana peel!
(Ha ha ha, gasp! what are you doing!?)

Ba-ba-biddly-ba-ba-ba-ba, ba-ba-ba-ba-ba-ba-ba
We are Number One
Hey!
Ba-ba-biddly-ba-ba-ba-ba, ba-ba-ba-ba-ba-ba-ba
We are Number One
Ba-ba-biddly-ba-ba-ba-ba, ba-ba-ba-ba-ba-ba-ba
We are Number One
Hey!
Ba-ba-biddly-ba-ba-ba-ba, ba-ba-ba-ba-ba-ba-ba
We are Number One
Hey!
Hey!Source

Rules

The first word per input is assured to be in the lyrics.
Your code must be case-insensitve (one as input will replace One)
Trailing newlines are allowed.
The input may be lower and uppercase, and the resulting output must have the same casing as the provided input.
The input can try to replace e.g. one with one. If you replace it or not, is your choice.
"Words" are sequences of characters seperated by space or commas, not by anything else (e.g. Hyphens), therefore Ba is not a valid input, but Ba-ba-biddly-ba-ba-ba-ba is.

Example case

Input:

one, three
net, villain

Output:Hey!
We are Number three
Hey!
We are Number three

Now listen closely
Here's a little lesson in trickery
This is going down in history
If you wanna be a Villain Number three
You have to chase a superhero on the run
Just follow my moves, and sneak around
Be careful not to make a sound
(Shh)
(CRUNCH)
(No, don't touch that!)

We are Number three
Hey!
We are Number three
We are Number three

Ha ha ha
Now look at this villain, that I just found
When I say go, be ready to throw
Go!
(Throw it on him, not me!)
(Ugh, let's try something else)
Now watch and learn, here's the deal
He'll slip and slide on this banana peel!
(Ha ha ha, gasp! what are you doing!?)

Ba-ba-biddly-ba-ba-ba-ba, ba-ba-ba-ba-ba-ba-ba
We are Number three
Hey!
Ba-ba-biddly-ba-ba-ba-ba, ba-ba-ba-ba-ba-ba-ba
We are Number three
Ba-ba-biddly-ba-ba-ba-ba, ba-ba-ba-ba-ba-ba-ba
We are Number three
Hey!
Ba-ba-biddly-ba-ba-ba-ba, ba-ba-ba-ba-ba-ba-ba
We are Number three
Hey!
Hey!

Winner

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

PHP, 666 bytes
I suppose this is a rather appropriate code size for a song about Villains...
<?$s=gzinflate(base64_decode("zVLNitswEL4b/A6TUxLwPkNh99BkDynsT5ceJ9YkUjPWBEle47fvjJVCoWyh0EPRYMme8cz3ox3Nq7Z5I8BEcBiHIyX4Eqltdh8l6jrIBBxyoQg9Syae7ZdE6wyoiVKYgClniRAilBT6CyWtefEhg8ZZQjyDk2nJ68cilt6fYJYRJowR4ajD4WtgRi35FcI3LfH4TlAEeo/Z6vJ4peQpCejI4gnSGNvmccwFTsKscIcZBnmn3AFGBzkSXpScjNG1zT1Br0RPI0OUYn0HvCxta37z7P1Wt4en18PDzk4H6RR+XFvx2HsdiWW1reL8jZwfKLxDZahxU1pEseooUy9S6ZZxsIfvld+C8c2rGXvIOKu6namXCN1sZIpPMrXNZ1EMmxd7gVBMKB+GbmE8kIHfvJ59p74VtbGkWdkPpDPVKeJM2wpmwqJ8TUMmTLEDX3030R0hG9k1M2QO1yo1B0fVFoV/xKgLrkRsaH4S7eCM+bqCyYiZInYPnN2S1aebrPd4d9QIzvG8nG6hXPHut/iDDf+g0f+EpTay5w8="));foreach($argv as$a){@list($a,$b)=explode(",",$a);$s=str_ireplace($a,$b,$s);}echo $s;

Usage: php numberOne.php one,three net,villain


Need help golfing Python 3 code to calculate volume & surface of spheroids in <150 bytes I want to write a function golf(C, A) that takes the height (C = 2*c) and the width (A = 2*a) of an oblate (left image) or prolate (right image) spheroid or a sphere as parameters and returns the volume V and the surface area S of the shape as tuple. The output must be rounded to two decimal places.

All input and output numbers are floating point decimals.
The input numbers (A and C) are guaranteed to be greater than 0 and lower than 100.

Here are some example calls of the function (golf(C, A)) in Python 3 and the expected outputs given as test cases:

golf(4, 2)  # expected output (8.38, 21.48)
golf(2, 2)  # expected output (4.19, 12.57)
golf(2, 4)  # expected output (16.76, 34.69)

The challenge requires my code to be smaller than 150 characters.

I could not manage to solve it myself yet, my best solution in Python 3 still takes 220 characters:

from math import *
def golf(C,A):
 c,a,V=C/2,A/2,pi/6*A*A*C;F=c*c/a**2;E=sqrt(1-(F if a>c else 1/F));S=4*pi*a*a if a==c else 2*pi*a*a*(1+(((1-E**2)/E)*atanh(E)if a>c else(c/(a*E))*asin(E)))
 return round(V,2),round(S,2)

The necessary formulas are taken from Wikipedia: Spheroid, here's a summary:

Vall spheroids = 4 π/3 a²c = π/6 A²C as A=2a and C=2c.

This challenge was originally from checkio.org and got refactored into a code-golf challenge for empireofcode.com.

122 bytes

from cmath import*
def golf(C,A):e=sqrt(1-A*A/C/C);return round(pi/6*A*A*C,2),round(pi*A*abs(A+(e and C*asin(e)/e-A)/2),2)

The sphere can be special-cased by returning surface area πA² if e = 0.

While there are two different formulae for oblate and prolate spheroids, they are mathematically equivalent. If the involved operations support complex numbers, each formula can be used for both cases.

Since asin(e)/e will return a complex number of the form x+0j for prolate spheroids, abs can be used to turn it into the float x.


Generate numerical permutations with conditions and template metaprogramming This, but via template metaprogramming:

template <int n> struct insanity { int[][n] permutations; }

Generate all numbers with n digits (0-9) such that each digit is either:

Zero
The first digit
Already present
Greater than the maximum digit to the left

Don't worry about leading zeros either way.

Valid examples:

012333
012391

Invalid examples:

012945

(Is this even possible?)

Winning code will be explainable and concise, but I'll take a clear short answer over the shortest.

Clarification on conditions: Shortest code with a complete explanation for what's going on. "Complete" means: Explain it to someone who knows how templates work, but not how TMP works.

Success!!!! It only took me 3 hours or so. (Note: Requires C++11 support)

4,410 characters (including output functions)

Compiled on GCC 4.7.2 (Ideone)

#include<iostream>
#include<type_traits>

int constexpr powOf10(size_t power)
{
    return power == 0 ? 1 : 10 * powOf10(power - 1);
}

template<int... digits>
struct buildNumber;

template<int first, int... digits>
struct buildNumber<first, digits...> : std::integral_constant<int, first * powOf10(sizeof...(digits)) + buildNumber<digits...>::value>
{
};

template<>
struct buildNumber<> : std::integral_constant<int, 0>
{
};

template<int... digits>
struct areAllDigits;

template<int first, int... digits>
struct areAllDigits<first, digits...>
{
    static bool constexpr value = first > 0 && first < 10 && areAllDigits<digits...>::value;
};

template<int first>
struct areAllDigits<first>
{
    static bool constexpr value = first>0 && first < 10;
};

template<class T>
struct buildNumberT;

template<int... digits>
struct digitContainer
{

};

template<int... digits>
struct buildNumberT<digitContainer<digits...>> : buildNumber<digits...> {};

template<class T1, class T2>
struct concatCtr;

template<int... digits1, int... digits2>
struct concatCtr<digitContainer<digits1...>, digitContainer<digits2...>>
{
    typedef  digitContainer<digits1..., digits2...> type;
};

template<int number, size_t digit>
struct breakIntoDigits
{
    typedef typename concatCtr<digitContainer<number / powOf10(digit)>, typename breakIntoDigits<number % powOf10(digit), digit - 1>::ctr>::type ctr;
};

template<int number>
struct breakIntoDigits<number, 0>
{
    typedef digitContainer<number> ctr;
};

template<int needle, int... haystack>
struct contains;

template<int needle, int first, int... haystack>
struct contains<needle, first, haystack...>
{
    static bool constexpr value = needle == first || contains<needle, haystack...>::value;
};

template<int needle>
struct contains<needle>
{
    static constexpr bool value = false;
};

template<int... values>
struct max;

template<int first, int... rest>
struct max<first, rest...>
{
    static constexpr int value = first > max<rest...>::value ? first : max<rest...>::value;
};

template<>
struct max<>
{
    static int constexpr value = 0;
};

template<class container, int... digits>
struct ruleChecker;

template<int current, int... allPrevious, int... rest>
struct ruleChecker<digitContainer<allPrevious...>, current, rest...>
{
    static bool constexpr value = (current == 0 || sizeof...(allPrevious) == 0 || contains<current, allPrevious...>::value || current > max<allPrevious...>::value) && ruleChecker<digitContainer<allPrevious..., current>, rest...>::value;
};

template<class container>
struct ruleChecker<container>
{
    static bool constexpr value = true;
};

template<class ctr1, class ctr2>
struct ruleCheckerT;

template<class ctr1, int... set2>
struct ruleCheckerT<ctr1, digitContainer<set2...>> : ruleChecker<ctr1, set2...>{};

template<int number, int length>
struct isValidNumber : ruleCheckerT<digitContainer<>, typename breakIntoDigits<number, length>::ctr>
{
};

template<int number, int length>
struct generateList
{
    typedef typename std::conditional<number % powOf10(length) == 0,
        digitContainer<>,
        typename concatCtr<
            typename generateList<number + 1, length>::container,
            typename std::conditional<isValidNumber<number, length>::value,
                    digitContainer<number>,
                    digitContainer<>
                >::type
            >::type
        >::type container;
};

template<int number>
struct generateList<number, 1>
{
    typedef typename concatCtr<
        typename generateList<number + 1, 1>::container,
        typename std::conditional<isValidNumber<number, 1>::value,
                digitContainer<number>,
                digitContainer<>
            >::type
        >::type container;
};

#define DEFINE_ENDPOINT_FOR_LENGTH(length) template<> struct generateList<powOf10(length), (length)>{typedef digitContainer<> container;}

template<int length>
struct insanity
{
    static_assert(length > 0, "Length must be greater than 0.");
    typedef typename concatCtr<typename generateList<1, length>::container, digitContainer<0>>::type numberList;
};

template<int first, int... rest>
void outputContainer(digitContainer<first, rest...> values)
{
    std::cout<<first<<'\n';
    outputContainer(digitContainer<rest...>{});
}

void outputContainer(digitContainer<> empty)
{
    std::flush(std::cout);
}

Explanation

insanity is the entry point, as used in the OP.  buildNumber builds a number from a list of digits; breakIntoDigits does the opposite; it takes a number and breaks it into length digits.  areAllDigits is just a helper I used earlier.  It isn't used in the final code.  It's value property is true if all the numbers passed to it are base-10 digits.  It generates a list of valid numbers (validated by isValidNumber) and puts them in a digitContainer (originally I was only going to use this for digits, but I decided to use it for both things).

Limitations

It can only calculate up to the point the compiler errors out from template recursion depth.
You need to define an ending point for each length because otherwise it keeps instantiating templates up to the limit because of std::conditional. You define an ending point for each length by typing DEFINE_ENDPOINT_FOR_LENGTH(i) where i is the length.


Print the nth Fibonacci number containing the nth Fibonacci number! Challenge
You must write a program that takes a positive integer n as input, and outputs the nth Fibonacci number (shortened as Fib# throughout) that contains the nth Fib# as a subtring. For the purposes of this challenge, the Fibonacci sequence begins with a 1.
Here are some examples that you can use as test cases, or as examples to clarify the challenge (for the latter, please leave a comment down below explaining what you find unclear).
n=1
Fib#s: 1
       ^1 1st Fib# that contains a 1 (1st Fib#)
Output: 1

n=2
Fib#s: 1, 1
       ^1 ^2 2nd Fib# that contains a 1 (2nd Fib#)
Output: 1

n=3
Fib#s: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233
             ^1              ^2                   ^3 3rd Fib# that contains a 2 (3rd Fib#)
Output: 233

n=4
Output: 233

n=5
Output: 6765

n=6
Output: 28657

n=7
Output: 1304969544928657

n=8
Output: 14472334024676221

n=9
Output: 23416728348467685

n=10
Fib#s: 1, ..., 34, 55, 89, ..., 63245986, 102334155, 165580141, ..., 2880067194370816120, 4660046610375530309
                   ^1                     ^2         ^3                                   ^10 10th Fib# that contains a 55 (10th Fib#)
Output: 4660046610375530309

As always, this is code-golf, so go for the lowest byte count possible.
If something is confusing/unclear, please leave a comment.
(This challenge is based off another challenge I posted: Print the nth prime that contains n)

Haskell, 85 84 bytes

EDIT:

-1 byte: Laikoni shortened l.
Typo (x>=s for x<=s) in explanation.

f takes an Int and returns a String.

l=0:scanl(+)1l
m=show<$>l
f n|x<-m!!n=[y|y<-x:m,or[x<=s|s<-scanr(:)""y,x++":">s]]!!n

Try it online!

How it works

l is the infinite list of Fibonacci numbers, defined recursively as the partial sums of 0:1:l. It starts with 0 because lists are 0-indexed. m is the same list converted to strings.
In f:

n is the input number, and x is the (string of the) nth Fibonacci number.
In the outer list comprehension, y is a Fibonacci number tested for whether it contains x as a substring. The passing ys are collected in the list and indexed with the final !!n to give the output. An extra x is prepended to the tests to save two bytes over using !!(n-1) at the end.
To avoid counting ys several times, the tests of each y are wrapped in or and another list comprehension.
In the inner list comprehension, s iterates through the suffixes of y.
To test whether x is a prefix of s, we check whether x<=s and  x++":">s. (":" is somewhat arbitrary but needs to be larger than any numeral.)


It's fun to stay at the Y.M.C.A "Y.M.C.A." is a popular disco song by the Village People that has a well-known dance. Write the shortest program to output the capital letters "Y", "M", "C", and "A" synchronized to the song's chorus.

Generally, one letter goes on each line sent to standard output. This primarily is to simplify programs subject to the output buffering of the C standard library (printing a newline flushes the output buffer), so you may omit any or all of these newlines if such omission would make your program shorter.

Your program, which is started at the same time as the music, must output the letter "Y" within 0.125 s of each of these times after starting (in seconds; I determined these from the music video posted on YouTube).

 45.766   49.611   60.889
 64.661  109.816  113.591
124.810  128.687  173.830
177.620  188.950  192.724
204.013  207.739  219.057

The letters "M", "C", and "A" respectively come 0.930 s, 1.395 s, and 1.628 s after each "Y". For testing purposes, these relative times are converted into absolute times by adding them to the time of the preceding "Y".

I have written a test program and corresponding example program in C that assume a newline follows each letter (although this is not a rule of competition). It is written for Linux and will not work on Windows without using Cygwin. If you cannot test your submission using the test program, at least check your submission against the YouTube video.

If your submission requires a special command-line option to behave properly, that command-line option counts when calculating your score. However, any interpreter startup time does not count against you, and the test program can be modified to accommodate that if necessary.

Although I doubt one exists, I must say that using a programming language function or library designed specifically for this task is prohibited.


How related are two relatives? The coefficient of relationship refers to how much DNA two persons have in common. A parent has 50% common DNA with their child (unless the parents are related), so to calculate it we have to find all pairs of directed disjoint paths starting at same node (common ancestor) and ending at each of the two siblings, and sum 2^-(m+n) for all pairs of paths of length m and n.

Your program should accept a list of pairs of numbers (or names if you prefer) representing parent-child relations followed by another pair of number for which it should output the coefficient of relationship (either as a fraction, a decimal number, or a percentage).

For example:

Format: [list of parent-child relations] pair of relatives we want to compare -> expected output
-----------------------------------------------
[(1,2)] (1, 2) -> 50% (parent-child)
[(1,2), (2, 3), (3, 4)] (2, 3) -> 50% (still parent-child, make sure your path pairs are disjoint)
[(1,3), (2, 3)] (1, 2) -> 0% (not related, make sure your paths are directed)
[(1, 2), (2, 3)] (1, 3) -> 25% (grandparent-child)
[(1, 3), (1, 4), (2, 3), (2, 4)] (3, 4) -> 50% (siblings)
[(1, 2), (1, 3)] (2, 3) -> 25% (half-siblings)
[(1, 3), (1, 4), (2, 3), (2, 4), (3, 5)] (4, 5) -> 25% (aunt/uncle-nephew/niece)
[(1, 3), (1, 4), (2, 3), (2, 4), (3, 5), (4, 6)] (5, 6) -> 12.5% (cousins)
[(1, 3), (1, 4), (2, 3), (2, 4), (5, 7), (5, 8), (6, 7), (6, 8), (3, 9), (7, 9), (4, 10), (8, 10)] (9, 10) -> 25% (double cousins)
[(1, 3), (1, 4), (2, 3), (2, 4), (3, 5), (4, 5)] (3, 5) -> 75% (parent-(child-with-sibling) incest)
[(1, 2), (1, 3), (2, 3)] (1, 3) -> 75% ((parent-and-grandparent)-(child-with-child) incest)

No person will have more than two parents and there will be no cycles in it. You can also assume that the number is the order in which they were born (so a < b in all (a, b)).

Python 3, 259 247 226 bytes

lambda l,a,b:sum(2**-len({*m}^{*n})for v in{*sum(l,())}for m in p(v,a,l)for n in p(v,b,l)if not{*zip(m,m[1:])}&{*zip(n,n[1:])})
p=lambda i,j,l:sum([[[r+[i]for r in p(y,j,l)],[[y,x]]][j==y]for x,y in l if i==x],[])+[[i]]*(i==j)

Try it online!

This can probably be golfed down quite a bit, but for now I'm just happy it works.


CCC 2016: Circle of Life Before I begin, this challenge was not mine originally

Credits to The University of Waterloo. This came from the Canadian Computing Competition 2016, Senior Problem 5. Here is a clickable link to the contest PDF:

http://cemc.uwaterloo.ca/contests/computing/2016/stage%201/seniorEn.pdf

Here is a link to the site:

http://cemc.uwaterloo.ca/contests/past_contests.html

Challenge

Given a wrapping array of two constant values, determine the configuration after n evolutions for positive integer input n. These two values represent a living cell and a dead cell. Evolutions work like this:

Evolution!

After each iteration, a cell is alive if it had exactly one living neighbor in the previous iteration. Any less and it dies of loneliness; any more and it dies of overcrowding. The neighbourhood is exclusive: i.e. each cell has two neighbours, not three.

For example, let's see how 1001011010 would evolve, where 1 is a living cell and 0 is a dead cell.

(0) 1 0 0 1 0 1 1 0 1 0 (1)
    *   $         %

The cell at the * has a dead cell on both sides of it so it dies of lonliness.
The cell at the $ has a living cell on one side of it and a dead cell on the other. It becomes alive.
The cel at the % has a living cell on both sides of it so it stays dead from overcrowding.

Winning Criteria

Shortest code wins.

I/O

Input will be a list of the cell states as two consistent values, and an integer representing the number of inputs, in some reasonable format. Output is to be a list of the cell states after the specified number of iterations.

Test Cases

start, iterations -> end
1001011010, 1000 -> 1100001100
100101011010000, 100 -> 000110101001010
0000000101011000010000010010001111110100110100000100011111111100111101011010100010110000100111111010, 1000 -> 1001111111100010010100000100100100111010010110001011001101010111011011011100110110100000100011011001

Test Case
This test case froze hastebin and exceeded the size limit on pastebin

APL (Dyalog),14 bytes

Prompts for start state as Boolean list and then for number of iterations

(1∘⌽≠¯1∘⌽)⍣⎕⊢⎕

Try it online!

⎕ numeric prompt (for Boolean list of start state)

⊢ on that, apply

(…)⍣⎕ the following tacit function, numeric-prompt times

 ¯1∘⌽ the argument rotated one step right

 ≠ different from (XOR)

 1∘⌽ the argument rotated one step left


The Path to the Result Input:

A grid of varying size only containing numbers in the range 00-99, the following four characters: ^; >; v; <, and spaces to fill (and new-lines of course).

Output:

The result of the sum (integer) when you follow the path.

How does this work?

You start at the arrow with the highest number, and follow the path the arrows point to.
For each of the four arrows we'll do a different arithmetic calculation:

> = Addition (+);
< = Subtraction (−);
^ = Multiplication (* or × or ·);
v = Real / Calculator Division (/ or ÷);

(NOTE: The symbols between parenthesis are just added as clarification. If your programming language uses a completely different symbol for the arithmetic operation than the examples, then that is of course completely acceptable.)

Challenge rules:

You can choose the input (to some extent). A string-array would be most logical I think, but a symbol/newline-separated single string is also fine. (Full functions as input that are simply executed in the actual code snippet aren't allowed!)
Trailing spaces for the input are optional.
Numbers 0-9 will have a leading 0 so all numbers plus arrow are of an equal three-character length.
The number & arrow will always have the following format: DDA (D being a digit; A being one of the four arrows).
You use the current value with the previous arithmetic operation (the example below explains this better).
The final arithmetic operation can be ignored because of the rule above.
It is possible to have DDA's in the input-grid that aren't being used in the path to the resulting sum.
There won't be any test-cases for arrows that form a loop.
There won't be any test-cases for dividing by 0.
There won't be any test-cases where dividing creates a decimal sum-result. You only have to worry about integers.
EDIT: Since there weren't any answer yet, I decided to change the grids slightly to perhaps make it easier. I know this is usually not recommended to do with challenges, but since no answers were given yet, I think this will make it slightly easier, giving more (/any) answers:
The spaces between de DDA's are random. There could even be no spaces in between at all. All DDA's and spaces are grouped per three. Also, it is possible to have no spaces between DDA's at all.

Example:

Input:

94>      66v
   05v   08<
         43>
   03>   00^

Path it follows:

Path it follows   |   Current sum value
________________________________________
94>               |   94  (highest value)
66v               |   160 (+)
08<               |   20  (/)
05v               |   15  (-)
03>               |   5   (/)
00^               |   5   (+)
43>               |   215 (*)
                          '>' after 43 is ignored because it's the last number

Output: 215

General Rules:

This is code-golf, so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters, full programs. Your call.
Default Loopholes are forbidden.
If possible, please add a link with a test for your code.
Also, please add an explanation if necessary.

Test cases:

94>      66v           ->     215
   05v   08<
         43>
   03>   00^

77>   80v55^02<        ->     -19
      20>   14^

22>11>15>80>14v        ->     -16
18^17>      10v
00^   90v43^02v
07^11<15<22v01<

99>98>97>96>95>94v     ->     102
93>92>   91v   03<

Python 2, 409 390 377 bytes

def f(p):
 p=map(lambda s:map(lambda d:d==3*(' ',)and(0,-1)or(int(d[0]+d[1]),'><^v'.index(d[2])),zip(s[::3],s[1::3],s[2::3])),p);x,y=max([(x,y)for x in range(len(p[0]))for y in range(len(p))],key=lambda(x,y):p[y][x][0]);r=o=0
 try:
  while 1:
   1/(y*x>=0);d=p[y][x]
   if-1<d[1]:r=eval('r%sd[0]'%'+-*/'[o]);o=d[1];a=(-(o==1),1)[o<1];b=(-(o==2),1)[o>2]
   x+=a;y+=b
 except:print r

The second and third indent levels are a raw tab and a raw tab plus a space, respectively. Markdown mangles the raw tabs, so they've been replaced by two spaces.

Ungolfed:

def follow(path):
  # Split path's strs into DDAs ((0, -1) for blank, else (int, int))
  path = map(
    lambda s: map(
      lambda dda: (0, -1) if dda == (' ', ' ', ' ') else (int(dda[0] + dda[1]), '><^v'.index(dda[2])),
      zip(s[::3], s[1::3], s[2::3])
    ),
    path
  )

  # Find highest DDA
  x, y = max([(x, y) for x in range(len(path[0])) for y in range(len(path))], key=lambda (x, y): path[y][x][0])

  result = 0
  op = 0  # addition
  try:
    # Keep following the path until we get an IndexError
    while True:
      if y < 0 or x < 0: raise IndexError

      dda = path[y][x]
      if dda[1] != -1:
        # It's not empty - do the operation & change direction
        const = dda[0]

        result = eval('result %s const' % '+-*/'[op])

        op = dda[1]

        dx = 1 if op == 0 else -1 if op == 1 else 0
        dy = 1 if op == 3 else -1 if op == 2 else 0

      # Move to the next thing
      x += dx
      y += dy
  except IndexError:
    # We've exited the path - return
    print result

Ideone it! (all test cases)


Tips for golfing in Charcoal Charcoal is a language created by ASCII-only and DLosc that specialises in ASCII art challenges.

What tips do you have for golfing in Charcoal? Obviously I am looking for tips related specifically to Charcoal, not those which can be applied to most - if not all - languages.

Take advantage of the deverbosifier

Using the deverbosifier means you can write in ASCII (--dv or --deverbosify to deverbosify, -v or --verbose to execute as verbose code). Furthermore, it compresses strings for you, which can be useful in some ASCII-art challenges when the string to compress is too long.

@Neil recommends using -vl or -v --sl. This is short for --verbose --showlength, meaning it will be interpreted as verbose Charcoal, and the length of the normal Charcoal code will be shown. Also, when deverbosifying, check the output to make sure that the input has actually been parsed correctly, since Charcoal generally ignores parse errors. If there is a syntax error, use -a (--astify) or --oa (--onlyastify) to help figure out the problem.


Find Integral Roots of A Polynomial Challenge

The challenge is to write a program that takes the coefficients of any n-degree polynomial equation as input and returns the integral values of x for which the equation holds true. The coefficients will be provided as input in the order of decreasing or increasing power. You can assume all the coefficients to be integers.

Input And Output

The input will be the coefficients of the equation in decreasing or increasing order of power.  The degree of the equation, i.e, maximum power of x, is always 1 less than the total no of elements in the input.

For example:

[1,2,3,4,5] -> represents x^4 + 2x^3 + 3x^2 + 4x + 5 = 0 (degree = 4, as there are 5 elements)
[4,0,0,3] -> represents 4x^3 + 3 = 0 (degree = 3, as there are 3+1 = 4 elements)

Your output should be only the distinct integral values of x which satisfy the given equation. All the input coefficients are integers and the input polynomial will not be a zero polynomial. If there is no solution for the given equation, then the output is undefined.

If an equation has repeated roots, display that particular root only once. You can output the values in any order. Also, assume that the input will contain at-least 2 numbers.

Examples

[1,5,6] -> (-3,-2)
[10,-42,8] -> (4)
[1,-2,0] -> (0,2)
[1, 1, -39, -121, -10, 168] -> (-4, -3, -2, 1, 7)
[1, 0, -13, 0, 36] -> (-3, -2, 2, 3)
[1,-5] -> (5)
[1,2,3] -> -

Note that the equation in the second example also has the root 0.2, but it is not displayed as 0.2 is not an integer.

Scoring

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

MATL, 13 12 bytes
|stE:-GyZQ~)

Try it online!
This uses the fact that, for integer coefficients, the absolute value of any root is strictly less than the sum of absolute values of the coefficients.
Explanation
Consider input [1 5 6] as an example.
|    % Implicit input. Absolute value
     % STACK: [1 5 6]
s    % Sum
     % STACK: 12
t    % Duplicate
     % STACK: 12, 12
E    % Multiply by 2
     % STACK: 12, 24
:    % Range
     % STACK: 12, [1 2 ... 23 24]
-    % Subtract, elemet-wise
     % STACK: [11 10 ... -11 -12]
G    % Push input again
     % STACK: [11 10 ... -11 -12], [1 5 6]
y    % Duplicate from below
     % STACK: [11 10 ... -11 -12], [1 5 6], [11 10 ... -11 -12]
ZQ   % Polyval: values of polynomial at specified inputs
     % STACK: [11 10 ... -11 -12], [182 156 ... 72 90]
~    % Logical negation: turns nonzero into zero
     % STACK: [11 10 ... -11 -12], [0 0 ... 0] (contains 1 for roots)
)    % Index: uses second input as a mask for the first. Implicit display
     % STACK: [-3 -2]


Win 270 electoral college votes You are the electoral strategist for a sudden late entrant in the 2020 US presidental election.

Your task: print out the names of states* your candidate will win, totalling at least 270 electoral college votes.

Background

Each state (and Washington DC) in the US system has an arbitrary number of "electoral college votes". A candidate has to win a majority of the 538 votes available, so at least 270 votes.

The number of votes for each state is:

[['Alabama', 9], ['Alaska', 3], ['Arizona', 11], ['Arkansas', 6], ['California', 55], ['Colorado', 9], ['Connecticut', 7], ['Delaware', 3], ['Florida', 29], ['Georgia', 16], ['Hawaii', 4], ['Idaho', 4], ['Illinois', 20], ['Indiana', 11], ['Iowa', 6], ['Kansas', 6], ['Kentucky', 8], ['Louisiana', 8], ['Maine', 4], ['Maryland', 10], ['Massachusetts', 11], ['Michigan', 16], ['Minnesota', 10], ['Mississippi', 6], ['Missouri', 10], ['Montana', 3], ['Nebraska', 5], ['Nevada', 6], ['New Hampshire', 4], ['New Jersey', 14], ['New Mexico', 5], ['New York', 29], ['North Carolina', 15], ['North Dakota', 3], ['Ohio', 18], ['Oklahoma', 7], ['Oregon', 7], ['Pennsylvania', 20], ['Rhode Island', 4], ['South Carolina', 9], ['South Dakota', 3], ['Tennessee', 11], ['Texas', 38], ['Utah', 6], ['Vermont', 3], ['Virginia', 13], ['Washington', 12], ['Washington DC', 3], ['West Virginia', 5], ['Wisconsin', 10], ['Wyoming', 3]]

Input

None

Output

A list (or similar) containing just the names of the states in your winning strategy. If a string, there must be separators between state names. States must be capitalised as in the list provided above.

You must not output anything other than valid state names and separators. The number of states in your strategy is up to you.

Rules

You may not use any external (or built-in) list of US state names. Standard loopholes are forbidden.

This is code golf. Shortest code in bytes wins, with the electoral college score as a tie-breaker.

Since there is no input, your code can be a program/script/statement rather than a function.

If you are using space as a separator, then you can't include any states with spaces in the name. Or you would have to do something like enclosing each state name in double quotes. (A separator has to be something that could be used to automatically split the string up into the correct elements.)

* For the purpose of this challenge, Washington DC is considered a state.

Charcoal,  52 ... 45  42 bytes (270 votes)

A list of states that optimizes the compression with Brotli.

”}∧J⟧´⪫3⎚>↘≡ＶＮb7>¹l↙⁵Þ7/…ξ⌕↑τc<y\MΦＧＣ＆⸿Dρ~

Try it online!

Output

Texas
Pennsylvania
Georgia
Illinois
Washington
Indiana
California
Arizona
Michigan
Virginia
Florida
New York

Node.js script

The initial list was found with the following Node.js script that shuffles the 30 most efficient states, extracts the shortest leading sub-list with a score greater than or equal to 270, joins it with \r and invokes the Brotli compressor on the resulting string.

It was optimized some more by shuffling the most promising sub-list to find an order offering the best compression.

let states = [ ['Alabama', 9], ['Alaska', 3], ['Arizona', 11], ... ];

states =
  states.map(a => [a[0], a[1], a[1] / a[0].length])
  .sort((a, b) => b[2] - a[2])
  .slice(0, 30);

const zlib = require('zlib');

let bestLen = 1 / 0, bestScore = 1 / 0,
    list, score, str, pack;

while(1) {
  for(let i = states.length - 1; i > 0; i--) {
    let j = Math.floor(Math.random() * (i + 1));
    [ states[i], states[j] ] = [ states[j], states[i] ];
  }

  for(
    let n = 1;
    (score = (list = states.slice(0, n)).reduce((p, c) => p + c[1], 0)) < 270;
    n++
  ) {}

  str = list.map(s => s[0]).join('\r');
  pack = zlib.brotliCompressSync(Buffer(str));

  if(pack.length < bestLen || (pack.length == bestLen && score <= bestScore)) {
    bestLen = pack.length;
    bestScore = score;
    console.log(bestLen, bestScore, str.split('\r').join('\\r'));
  }
}


Rock Paper Scissors Meta-Gaming Tournament This is a rock paper scissors competition. Algorithms will face each other in 100 rounds of rock paper scissors. Except that the algorithms will also be able to read the source code of each other!
Leaderboard
1.  Chaos Bot (by Aiden4) - 27 Points, 168 bytes
2.  Anti-99%-of-posts (by Lyxal) - 24 Points, 489 bytes
3.  Psuedo-Hash Cycle (by qwatry) - 22 Points, 143 bytes
4.  If-If (by PkmnQ) - 20 Points, 63 bytes
5.  Biased-Cycler (by HighlyRadioactive) - 19 Points, 17 bytes
6.  Cycler (by petStorm) - 16 Points, 17 bytes
7.  Craker (by petStorm) - 16 Points, 58 bytes
8.  Lookup (by petStorm) - 16 Points, 61 bytes
9.  RadiationBot v0.1 (by HighlyRadioactive) - 16 Points, 121 bytes
10. Custom (by petStorm) - 15 Points, 56 bytes
11. Anti-Cycler (by Lyxal) - 14 Points, 17 bytes
12. Mr. Paper - 13 Points, 58 bytes
13. PseudoRandom (by HighlyRadioactive) - 12 Points, 89 bytes
14. Itna-Cycler (by petStorm) - 11 Points, 17 bytes
15. Mr. Rock - 11 Points, 57 bytes
16. Lycler (by petStorm) - 10 Points, 24 bytes
17. Mr. Scissors - 10 Points, 61 bytes

Submissions are graded automatically via an online judge
View Online Judge
The Competition
Your code will be a javascript anonymous function (sorry, other languages aren't supported!) that takes in two arguments:

The source code of your opponent AI (as a string)
The current round number

It should then return one of "R", "P", or "S", indicating that it will throw a rock, paper, or scissors for that round.
Your code must follow these rules, otherwise it will be disqualified:

Your code may not be longer than 500 bytes
Your function must be pure

That is, if your function is given the same set of arguments, your code must always return the same result
This is to ensure that the tournament results are consistent

eval() calls are banned!

If this were allowed, two submissions with eval() would end up calling each other in an endless loop which would never terminate.
(See the discussion in the comments for more details/reasoning)

Your code may not:

Access external resources (e.g. make web fetch/get requests)
Attempt to modify or tamper with the judge system code
Cause excessive lag or time delay
Modify any globals or object prototypes
Attempt to do an XSS attack or any other sketchy/illegal stuff

Example submission
(code, round) => {
  if (round === 1) {
    // Throw rock if it's the first round
    return "R";
  }
  else if (code.includes('"R"')) {
    // Throw paper if the opponent code includes "R"
    return "P";
  } else {
    // Otherwise throw scissors
    return "S";
  }
}

Tournament structure
Every submission will play rounds of rock paper scissors against every other submission. Each submission will play 100 rounds with each other submission.
To get the ball rolling, the following three functions will be submitted by default and will not be counted in the final leaderboard:
(code, round) => {
  // Always throw rock
  return "R";
}

(code, round) => {
  // Always throw paper
  return "P";
}

(code, round) => {
  // Always throw scissors
  return "S";
}

Scoring
A submission gains 2 points for winning against another submission, and 1 point for tying against another submission (no points are awarded for losses).
Rankings are ordered by most points. If two submissions have the same number of points, they will be ranked in order of least bytes. If two submissions have the same number of points and bytes, the older submission will be ranked higher.
Judging & Testing
Post your submissions here, I will periodically add submissions to the online judge which will automatically rank each algorithm.
You can also test your algorithms using the online judge testing area. A testing area is provided at the bottom to test different algorithms against each other.

Anti-99%-of-posts
(code,r)=>{var S="S";var R="R";var P="P";var x=S+R+P;var y=R+P+S;var z=P+S+R
if(code.includes("17")){return "P";}
else if(code.includes("[r%2]")){return"RR"[r%2]}
else if(code.includes("[r%3]")){
if (code.includes(x)){return (R+P+S)[r%3];}
else if(code.includes(y)){return (P+S+R)[r%3];}
else if(code.includes(z)){return (S+R+P)[r%3];}
}else{if(code.includes("scissors")){return "R"}else if (code.includes("rock")){return "P"}else if (code.includes("paper") ){return "S"}else{return "P"}}}

Haha. Testing it on submissions gives either a win or a tie.


Generate a one-path maze Given an odd integer N (5 <= N <= 51), generate a maze with side length N that follows the following requirements:

The maze must be composed of the characters  | - and +. It must use the | character as a vertical wall, the - character as a horizontal wall, and if that wall turns, the character + should be used.

The width of the path must be one character.

The maze must turn at least four times.

The maze must have outer walls, that break at two points: the start and the end.

The maze must consist of one non-breaking path, from the start to the end.

For example, the following is a valid maze: (N = 5)

+---+
|   |
| | |
  |
--+--

And for N = 7:

--+---+
  |   |
| | | |
| | | |
| | | |
|   |
+---+--

Remember, this is code-golf, so the code with the fewest number of bytes wins.

Jelly, 36 35 34 33 32 bytes

2*×5H_2Bị⁾ |
_3”-ẋ”+;;Çsẋ2U3¦ṁµY

TryItOnline!

Builds a nighter™ the other way around to the examples like:

+---- |
|     |
| ----+
|     |
+---- |
|     |
| ----+

How?

2*×5H_2Bị⁾ | - Link 1, pipes & spaces: n      e.g. 7
2*           - 2 raised to the nth power      e.g. 128
  ×5         - multiply by 5                  e.g. 640
    H        - halve                          e.g. 320
     _2      - subtract 2                     e.g. 318
       B     - convert to binary              e.g. [1,0,0,1,1,1,1,1,0]
        ị    - index into (1-based)
         ⁾ | - char list " |"                 e.g. " ||     |"

_3”-ẋ”+;;Çsẋ2U3¦ṁµY - Main link: n            e.g. 7
_3                  - n - 3                   e.g. 4
  ”-                - char list "-"
    ẋ               - repeat                  e.g. "----"
     ”+             - char list "+"
       ;            - concatenate             e.g. "+----"
         Ç          - call last link (1) as a monad
        ;           - concatenate             e.g. "+---- ||     |""
          s         - split into chunks of n  e.g. ["+---- |","|     |"]
           ẋ2       - repeat 2 times          e.g. ["+---- |",
                                                    "|     |",
                                              +-->  "+---- |",
                                              |     "|     |"]
              3¦    - apply to index 3:       |
             U      -    upend                +---  "| ----+"
                ṁ   - mould like n (i.e. repeat to fill)
                 µ  - monadic chain separation
                  Y - join with line feeds

(each byte saved involved fairly non-trivial changes, see the edit history if you're interested, although I just noticed that Link 1 is the same byte count as the more conventional repeat and join: _2⁶ẋ“ ||“|”j)


Print the Black Mirror episode title Given two integers, s and e, print the title of Black Mirror series #s episode #e.

Expected output is as below, case sensitive. Output for blank cells and invalid inputs is unspecified.

e↓s→                          1                  2                     3               4                              5
 1 | The National Anthem       | Be Right Back    | Nosedive            | USS Callister | Striking Vipers              |
 2 | Fifteen Million Merits    | White Bear       | Playtest            | Arkangel      | Smithereens                  |
 3 | The Entire History of You | The Waldo Moment | Shut Up and Dance   | Crocodile     | Rachel, Jack, and Ashley Too |
 4 |                           |                  | San Junipero        | Hang the DJ   |                              |
 5 |                           |                  | Men Against Fire    | Metalhead     |                              |
 6 |                           |                  | Hated in the Nation | Black Museum  |                              |

(The episode "White Christmas" is grouped with series 2 on Netflix, but originally aired as a standalone special, so it is not part of the challenge. The film Bandersnatch is likewise standalone and exempt.)

Husk, 162 bytes
!x'x!¶¨Σṅ←ÿ‼⌋xżFE«Ȯ⌊Żψ'xΣẏ>ï?₀fẏu₈eṙ‼ḂkxẇïBȦrxΣ«QẆḟṁŸ)⁶ıex₉?²tx«‼UÜUÄd□Δ'xS▲⌋ȷ9oxṀËäαγFxHȦ∂↕εṄ|≠USSχ⁷ıżxŻKȦ£Ġx£%Øx□´'ËDJxẎȦlḊh₈Ċż_ṀÿKi▼V₉→xSmi►&η$x£ƒ´,⌋ȷ@,Ädÿ¿◄θ⁰

Try it online!
A perfect task for Husk's string compression. Seasons are separated with newlines and episodes are separated with 'x'.
Then:
!x'x!¶¨...
      ¨...     Big compressed string
     ¶         Split on newlines
    !          Take the line corresponding to given season
 x'x           Split on 'x'
!              Take the title of the given episode


Levenshtein Your Source The Levenshtein edit distance between two strings is the minimum possible number of insertions, deletions, or substitutions to convert one word into another word. In this case, each insertion, deletion and substitution has a cost of 1.
For example, the distance between roll and rolling is 3, because deletions cost 1, and we need to delete 3 characters. The distance between toll and tall is 1, because substitutions cost 1.
Stolen from original Levenshtein question

Your task is to calculate the Levenshtein edit difference between an input string and your source. This is tagged quine, so cheating quines (for example, reading your source code) are not allowed.
Rules

The input will be non-empty and will be composed of ASCII, unless your source contains non-ASCII, in which case the input may include Unicode. Regardless, the Levenshtein distance will be measured in characters, not bytes.

The output is the minimum Levenshtein edit distance of the input and your source.

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

Python 2 + sequtils, 101 bytes

from sequtils import*;_='from sequtils import*;_=%r;print edit(_%%_,input())';print edit(_%_,input())


Humans hate pows and programmers hate humans - let's connect them! Background

The task is simple but every programmer has implemented it at least once. Stackoverflow has a lot of samples, but are they short enough to win?

Problem story

You're a grumpy programmer who was given the task of implementing file size input for the users. Since users don't use bytes everyone will just enter "1M", "1K", "3G", "3.14M" - but you need bytes! So you write a program to do the conversion.

Then your manager hands you dozens of user reports with complaints about weird large numbers in file size input. It seems you'll need to code the reverse conversion too.

What do you need to do?

Here's the trick: you should implement two-way conversion in single piece of code. Two separate functions used as needed? Nah, that's too simple - let's make one, short one!

For the purposes of this challenge, "kilobyte" means 1024 bytes, "megabyte" means 1024*1024 = 1048576 bytes, and "gigabyte" means 1024*1024*1024 = 1073741824 bytes.

Test data

Input   -> Output
5       -> 5
1023    -> 1023
1024    -> 1K
1K      -> 1024
1.5K    -> 1536
1536    -> 1.5K
1048576 -> 1M
1M      -> 1048576

Rules

Test value will not exceed 2*1024*1024*1024 or 2G
The following postfixes are used by users: K for kilobytes, M for megabytes, G for gigabytes
Code is not required to work with negative numbers
Do not use any external libraries (e.g. BCMath in PHP) besides bundled ones (e.g. math.h)
Standard loopholes are disallowed
Code should not produce anything on stderr
Your program can take input and produce output using [standard methods].(http://meta.codegolf.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods)

Python 2, 204 190 bytes
This is my first ever codegolf.
s=raw_input()
p=' KMG'
if s[-1]<='9':
 e=0;r=int(s)
 while r>=1024:r/=1024.0;e+=1
else:
 e=p.index(s[-1]);r=eval(s[:-1])
 while e>0:r*=1024;e-=1
print(`r`if r%1!=0 else`int(r)`)+p[e].strip()


Olympic Games Logo - Free Style Edition In a similar spirit as this question, your mission is to create the best-looking logo in at most 1K of code.

Rules:

At most 1K of code (inclusive), no external data.
The answer with the most upvotes wins.

Have fun!

SVG

1kB? Luxury. I can even pretty-print the output rather than removing all unnecessary whitespace. (The indentation does, of course, use tabs, which Markdown converts to spaces, so that's why the char count might seem higher than the actual 977. Removing unnecessary whitespace drops it to 861).

The overlaps are handled correctly by drawing the rings in one direction, then applying a clip and drawing them in the other direction. The colours and ratios are extracted from an official document which for some reason uses Bézier curves rather than circles.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="504" height="228">
    <defs>
        <clipPath id="t">
            <rect width="504" height="114" />
        </clipPath>
    </defs>
    <g fill="none" stroke-width="12">
        <g id="u" transform="translate(82,82)" stroke="#0b8ed8">
            <g id="O">
                <circle r="72" stroke="#fff" stroke-width="20" />
                <circle r="72" />
            </g>
        </g>
        <g id="y" transform="translate(167,146)" stroke="#f9a91f">
            <use xlink:href="#O" />
        </g>
        <g id="k" transform="translate(252,82)" stroke="#231f20">
            <use xlink:href="#O" />
        </g>
        <g id="g" transform="translate(337,146)" stroke="#009e59">
            <use xlink:href="#O" />
        </g>
        <g transform="translate(422,82)" stroke="#ee2049">
            <use xlink:href="#O" />
        </g>
        <g clip-path="url(#t)">
            <use xlink:href="#g" />
            <use xlink:href="#k" />
            <use xlink:href="#y" />
            <use xlink:href="#u" />
        </g>
    </g>
</svg>


Type out Green Eggs and Ham in vim The book Green Eggs and Ham by Dr. Seuss is famous for only having 50 different words in the entire story of the book.

Your task is to create a sequence of keystrokes that will result in the entire text of Green Eggs and Ham when applied to an empty file in the vim text editor, starting in normal mode with all default settings. Your keystrokes must not load any other files as part of their operation - all text must be generated within the editor itself.

Your final buffer must look exactly like this file, although it can remain in whichever mode it ends up being in (you don't have to have a final <Esc> to return it to normal mode).

Chorded keystrokes like <C-o> or using Shift to type a capital letter count as a single keystroke.

The sequence of the fewest keystrokes to achieve this goal wins.

1864 keystrokes

Somebody could probably write some code that produces a more optimal solution, but this beats the reference case for now. This is a damn mess, and I am ashamed I did it by hand.

First, we enter insert mode.

i

Then all this

That ]! That ]!
IDNlike that ]!

Do Y like$?

|;].
IDNlike$.

WPY LTB or tB?

IZ LTB or tB.
IZ LTanywB.
IDNlike$.
|;].

WPY LTin a h@?
WPY LT=a m@?

|in a h@.
|=a m@.
|B or tB.
|.
IDNlike$.
|;].

WPY ETin a box?
WPY ET=a fox?

Not_a box. Not =a fox.
Not_a h@. Not =a m@.
IZ ETB or tB.
IZ ETanywB.
IZ eat$.
|;].

WPY? CPY? In a car?
Eat them! Eat them! B they are.

IZ,X,_a car.

You may LT. You will see.
You may LTin a tree!

IZ,X_a tree.
Not_a car! You let me be.

|in a box.
|=a fox.
|in a h@.
|=a m@.
|B or tB.
|.
IDNlike$.
|;].

AQ! AQ! AQ! AQ!
CPY;wPY;on aQ?

Not_aQ! Not_a tree!
Not_a car! Sam! Let me be!

IZ,X,_a box.
IX,Z;=a fox.
:=a m@.
:in a h@.
:B or tB.
:anywB.
IDNlike$.
|;].

Say! In +? B_+!
WPY;cPY,_+?

IZ,X,_+.

WPY;cPY,_the rain?

IZ,X,_the rain.
Not_+. Not on aQ.
Not_a car. Not_a tree.
|;Sam;Y see.
Not_a h@. Not_a box.
Not =a m@. Not =a fox.
:B or tB.
|!

You do not like$?
|;].

CPY;wPY;=a g^?

IZ,X;=a g^!

WPY;cPY;on a b^?

IX,Z;on a b^.
IWN,WN;=a g^.

:in the rain.
:on aQ.
Not_+! Not_a tree!
Not_a car! You let me be!
|in a box.
|=a fox.
:in a h@.
|=a m@.
|B or tB.
|!

IDNlike$!
|;].

You do not LT. So Y say.
Try them! Try them! & Y may.
Try them and Y may;I say.

Sam! If Y will let me be,
I will try them. You will see.

Say! I like$!
I do! I LT;]!
& I wPETin a b^.
& I wPET=a g^.

!ETin the rain.
&_+. & on aQ.
&_a car. &_a tree.
They are so good;so good;Y see!

So I will ETin a box.
!ET=a fox.
!ETin a h@.
!ET=a m@.
!ETB and tB.
Say! I will ETanywB!

I do so like$!

Thank Y! Thank Y;]!

Hit escape to enter command mode. And unravel the compressed stuff. Order matters, as I've compressed some compressed text.

<Esc>
%s/|/|anywB/g
%s/:/IWNET/g
%s/|/IDNLT/g
%s/Z/ wPnot/g
%s/X/ cPnot/g
%s/&/And/g
%s/+/the dark/g
%s/@/ouse/g
%s/^/oat/g
%s/Y/you/g
%s/IDN/I do not /g
%s/LT/like them /g
%s/]/Sam-I-am/g
%s/ET/eat them /g
%s/WN/ will not/g
%s/$/ green eggs and ham/g
%s/P/ould /g
%s/!/And I will /g
%s/Q/ train/g
%s/B/here/g
%s/_/ in /g
%s/=/with /g
%s/;/, /g


add commas to Numbers without String manipulation This challenge consist in adding commas to numbers every 3 spaces like:

123456789 => 123,456,789

Specifications:

The possible inputs will be 1,000 <= input <= 100,000,000
You can ONLY use Mathematical Operators
(*) You can NOT do string, array, index or character manipulation
You can NOT use any kind of built-in functions that add these commas
The zeros should remain, ex 10000 => 10,000
You need to print/alert/log the output (so "the output is at x
var" is not allowed)

(*) the only exception is when forming/printing the output (but not in a manner that suggest cheating)

Examples

10100 => 10,100
120406 => 120,406
999999999 => 999,999,999

A basic idea on how to get numbers legally:

n = 123456;
m = roundDown(n / 10);//even if ends with .9
d = n - m;//we get the last number

You weren't very specific on the output format...

Haskell, 56

reverse.takeWhile(>0).map(`mod`1000).iterate(`div`1000)

example:

GHCi> reverse.takeWhile(>0).map(`mod`1000).iterate(`div`1000)$93842390862398
[93,842,390,862,398]


Check if string is a valid URL Your task is to write a program or function that checks if a string is a valid URL.

Given a string as input, you will output a truthy value if the input is a valid URL. If it is not, output a falsey value. An input string is considered a valid URL if all of the following criteria are met:

Begins with http:// or https://
At least one and up to 128 labels (parts of URL delimited by a period)

Labels delimited by a period
Contain only letters, digits, and hyphens
Do not start nor end with a hyphen
Third and fourth characters cannot be a hyphen, unless the first two characters are 'xn'
A label may contain zero to 63 characters

The length of the string does not exceed 253 characters

This is a code-golf, with standard rules.

https://en.wikipedia.org/wiki/Domain_Name_System#Domain_name_syntax

JavaScript, 114 bytes

x=>RegExp(`^(?!.*([./](-|(?!xn)[^/]{2}--)|-[./]|-$))https?://${a='[a-zA-Z0-9-]{0,63}'}(?:\\.${a}){0,127}`).test(x)

Hopes it works.

For real URLs, you should use:

x=>eval(`try{new URL(x)}catch(e){}`)

Thanks to ThePirateBay, construct regex from string save 3 bytes.


The bouncing sequence Let us define a sequence.  We will say that \$a(n)\$ is the smallest number, \$x\$, that has the following properties:

\$x\$ and \$n\$ are co-prime (they share no factor)
\$x\$ does not appear earlier in the sequence
\$|n - x| > 1\$

Unlike most sequences the domain and range of our sequence are the integers greater than 1.

Let us calculate the first couple of terms.

\$a(2)\$, must be at least 4, but 4 and 2 share a factor of 2 so \$a(2)\$ must be 5.

\$a(3)\$, must be at least 5 but 5 is taken by \$a(2)\$, so it is at least 6, but 6 shares a factor with 3 so it must be at least 7, 7 fulfills all three requirements thus \$a(3)=7\$.

\$a(4)\$

2 Shares a factor
3 Too close
4 Too close
5 Too close
6 Shares a factor
7 Taken by a(3)
8 Shares a factor
9 is good

\$a(5)\$

2 is good

Task

In this challenge you are to write a program that takes a number greater than 1 and returns \$a(n)\$.

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

Test Cases

Here are the first couple terms of the sequence (They are of course 2 indexed):

5,7,9,2,11,3,13,4,17,6,19,8,23,22,21,10,25,12,27,16,15,14

Bonus Fun fact

As proven by Robert Israel on Math.se (link) this sequence is its own inverse, that means that \$a(a(n)) = n\$ for all n.

OEIS

After asking this question I submitted this sequence to the OEIS and after a few days it was added.

OEIS A290151

Haskell, 61 bytes

f n=[i|i<-[2..],gcd i n<2,all((/=i).f)[2..n-1],abs(n-i)>1]!!0

Try it online!

I'm fairly new to Haskell, so any golfing tips are appeciated.

Thanks to Wheat Wizard for 2 bytes and nimi for 4 bytes

Explanation:

f n=[i|i<-[2..],gcd i n<2,all((/=i).f)[2..n-1],abs(n-i)>1]!!0
f n=                                                          -- define a function f :: Int -> Int
    [i|i<-[2..],                                              -- out of positive integers greater than two
                gcd i n<2,                                    -- gcd of i and n is 1
                          all((/=i).f)[2..n-1],               -- i isn't already in the sequence
                                               abs(n-i)>1]    -- and |n-i| > 1
                                                          !!0 -- take the first element


Bounce-modulo two numbers The graph of the modulo operation (\$y = x \mod k\$) looks like this:

This is a very useful function, as it allows us to create "wrapping" behavior. However, it is very cumbersome when I want to use it to create an appearance of "bouncing" between two walls. The graph of the "bounce" function (\$y = \text{bounce} (x, k)\$) looks like this:

The period of the graph of \$y = x \mod k\$ is \$k\$. The period of the graph of \$y = \text{bounce} (x, k)\$ is \$2k\$, because it moves upwards for \$k\$ units, and then moves downwards for another \$k\$ units, before returning to where it started. For both functions, the minimum value for \$y\$ is 0, and the maximum is \$k\$ (Actually, for the modulus function with integral inputs, it's \$k-1\$). In addition, for both functions, the value where \$x=0\$ is 0.

The challenge

Given an integer \$x\$ and a positive integer \$k\$, return an integer or floating-point approximation of \$y = \text{bounce} (x, k)\$.

This is code-golf, so the shortest valid submission (counted in bytes) wins.

Test Cases

  x,  k -> bounce(x, k)
  0, 14 ->            0
  3,  7 ->            3
 14, 14 ->           14
 15, 14 ->           13
-13, 14 ->           13 (12.999997 etc would be an acceptable answer)
-14, 14 ->           14
191,  8 ->            1
192,  8 ->            0

Bonus points for a Fourier-based approach in Fourier.

x86-64 Machine Code, 18 bytes
97
99
31 D0
29 D0
99
F7 FE
29 D6
A8 01
0F 45 D6
92
C3

This code defines a function in x86-64 machine language that computes bounce(x, k). Following the System V AMD64 calling convention used on Gnu/Unix systems, the x parameter is passed in the EDI register, while the k parameter is passed in the ESI register. As with all x86 calling conventions, the result is returned in the EAX register.
To call this from C, you would prototype it as follows:
int Bounce(int x, int k);

Try it online!
Ungolfed assembly mnemonics:
; Take absolute value of input 'x' (passed in EDI register).
; (Compensates for the fact that IDIV on x86 returns a remainder with the dividend's sign,
; whereas we want 'modulo' behavior---the result should be positive.)
xchg   eax, edi      ; swap EDI and EAX (put 'x' in EAX)
cdq                  ; sign-extend EAX to EDX:EAX, effectively putting sign bit in EDX
xor    eax, edx      ; EAX ^= EDX
sub    eax, edx      ; EAX -= EDX

; Divide EDX:EAX by 'k' (passed in ESI register).
; The quotient will be in EAX, and the remainder will be in EDX.
; (We know that EAX is positive here, so we'd normally just zero EDX before division,
; but XOR is 2 bytes whereas CDQ is 1 byte, so it wins out.)
cdq
idiv   esi

; Pre-emptively subtract the remainder (EDX) from 'k' (ESI),
; leaving result in ESI. We'll either use this below, or ignore it.
sub    esi, edx

; Test the LSB of the quotient to see if it is an even number (i.e., divisible by 2).
; If not (quotient is odd), then we want to use ESI, so put it in EDX.
; Otherwise (quotient is even), leave EDX alone.
test   al, 1
cmovnz edx, esi

; Finally, swap EDX and EAX to get the return value in EAX.
xchg   eax, edx
ret

Note that the first section (that takes the absolute value) could have equivalently been written:
; Alternative implementation of absolute value
xchg    eax, edi
neg     eax
cmovl   eax, edi

which is the exact same number of bytes (6). The performance should be similar, perhaps slightly faster (except on certain Intel chips, where conditional moves are slow).
XCHG is, of course, relatively slow and would not be preferred over MOV except in code golfing (that the former is 1-byte when one of the operands is the accumulator, whereas a register-register MOV is always 2 bytes).


3x3 Connected Components The Challenge

Consider the 3x3 king grid, as shown in the following ASCII graphic:

A--B--C
|\/|\/|
|/\|/\|
D--E--F
|\/|\/|
|/\|/\|
G--H--I

You are given as input a length-9 list of integers that represent a labeling of the nodes. For example, the input [0,1,1,2,1,0,5,5,1] represents the following labeling:

0--1--1
|\/|\/|
|/\|/\|
2--1--0
|\/|\/|
|/\|/\|
5--5--1

Your output is the set of integers in the input that form connected sets of nodes. More explicitly, the output should contain an integer n from the input if and only if the set of nodes with label n is connected. In this example, an acceptable output would be [1,2,5], since the two 0s are not connected. The lowest byte count wins.

Detailed rules

You can choose a fixed ordering for the nodes in your input list, and you should state this in your answer. In the order EFBDHCAGI, the above labeling would be given as [1,0,1,2,5,1,0,5,1].
You can write either a full program or a function. In the latter case, the output can be a set of integers if your language supports those.
The output list may contain duplicates, but its length must not exceed 9.
Standard loopholes are disallowed.

Test cases

These have single-digit numbers aligned to the grid; adjust them to your chosen order.

011
210 => 1 2 5
551

010
202 => 0 2
221

110
123 => 0 2 3
221

111
111 => 1
111

111
141 => 1 4
111

J, 54 bytes

#~3 :'0<*/,+/ .*/^:8~y#|:y#,/,"1/({0&,:)3 3$#:13'"1@e.

A function taking a list in the order ABCDEFGHI.

Given an adjacency matrix A of a graph of order n, the graph is connected if and only if all the entries of (A + I)n are nonzero, where I is the n×n identity matrix.

We start with the (fixed) adjacency-plus-identity matrix of the 3×3 king grid (in the order ABCDEFGHI,) namely:

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

.
For each label l, we select the rows and columns corresponding to the nodes of label l.
This gives us the adjacency-plus-identity matrix of the subgraph of l-labeled nodes.
We then use this matrix to test if the subgraph is connected, as described above.

We construct the above matrix by noting that if we let

    0 0 0
Z = 0 0 0
    0 0 0

and

    1 1 0
O = 1 1 1
    0 1 1

, then the matrix can be seen as the 3×3 block matrix

O O Z
O O O
Z O O

, which has the same pattern as O!
O is produced by repeating the pattern 1 1 0 1 in a 3×3 block.


Generate Linus Sequence Definition

From the description on OEIS A006345:

  To find a(n), consider either a 1 or a 2. For each, find the longest repeated suffix, that is, for each of a(n)=1,2, find the longest sequence s with the property that the sequence a(1),...,a(n) ends with ss. Use the digit that results in the shorter such suffix. a(1) = 1.

Worked-out Example

a(1)=1.

If a(2)=1, we will have the sequence 1 1 where the longest doubled substring from the end is 1. If a(2)=2 instead, then it would be the empty substring. Therefore a(2)=2.

When n=6, we choose between 1 2 1 1 2 1 and 1 2 1 1 2 2. In the first choice, 1 2 1 is doubled consecutively from the end. In the second choice, it is 2 instead. Therefore, a(6)=2.

When n=9, we choose between 1 2 1 1 2 2 1 2 1  and 1 2 1 1 2 2 1 2 2. In the first choice, the longest doubled consecutive substring is 2 1, while in the second choice 1 2 2 is doubled consecutively at the end. Therefore a(9)=1.

Task

Given n, return a(n).

Specs

n will be positive.
You can use 0-indexed instead of 1-indexed. In that case, please state so in your answer. Also, in that case, n can be 0 also.

Testcases

The testcases are 1-indexed. However, you can use 0-indexed.

n  a(n)
1  1
2  2
3  1
4  1
5  2
6  2
7  1
8  2
9  1
10 1
11 2
12 1
13 2
14 2
15 1
16 1
17 2
18 1
19 1
20 1

References

WolframMathWorld
Obligatory OEIS A006345


Hello World - but alphabetically This challenge sounds too simple to not already exist, so let me know if it is a duplicate.

The task

Print Hello, world!

The rules

Your code has to be in "byte order". This means that every character / byte has a higher or equal byte value than the preceding character / byte.

Exceptions to this rule are the whitespace characters, which may occur anywhere.

The usual loopholes are not allowed.

Edit: Using built-in functions / constants resolving to Hello, world! is not allowed.

Edit 2: The output may be a(n anonymous) function returning the string,  an expression resolving to the string, or any other way you think should be allowed.

example

HW is valid: 0x48 (H) <= 0x57 (W)
print is invalid: 0x72 (r) > 0x69 (i)
but PRint is valid: 0x50 (P) <= 0x52 (R) <= 0x69 (i) <= 0x6e (n) <= 0x74 (t)

The scoring

This is code-golf so the score is the number of characters / bytes. The lower the score, the higher the ranking.

WhiteSpace, 146 bytes

Since all whitespace may occur everywhere, this is is just the golfed Hello World program. Since whitespace doesn't show properly here, take the following program and replace all . by spaces, > by tabs and ; by newlines.

...;..>>..>.>.;..>>>>;...>;...>>>;...>..;..>>.>..;..>>..>.>>;..>>>>>>>;...>..;...>;.;...>>>.;..>>...>>;;..;.;.;>.>;...>>.>.>>;>...>;..;.;;;..>;;;;

Note

I didn't golf this, LukStorms did. His answer can be found here.


Can you handle the pub? Background

It's late Friday afternoon and you and your friends decide to hit the pub later that evening, but before going to the pub you figure you should have a few beverages.
However, things escalate quickly; your friend Shaddock Pamplemousse won the lottery earlier this week and decided to bring crates upon crates with different beverages.
The security at the pub is very strict, and if you overconsume before trying to enter the premises you are not allowed inside.
You are all programmers though - so you figure things will turn out great anyway.

Challenge

You need to program an alcohol meter which outputs truthy/falsy if you're above/below the reasonable pub limit.
Before you go down to the pub you enter the amount and beverage type you've consumed during the evening to stdin which your measurement program reads.
If it outputs truthy, you are above the pub limit and stay at home. If it outputs falsy, you're good to go.

Input

One integer greater than 0 which represents your body weight in kilograms followed by a newline.
This input is followed by a series of one digit amounts and beverages on the following form:

<amount><amount type>o<beverage type>

For one bottle of beer this will look like:

1Bob

Each input is separated by a space.

Input specification

Each beverage has a unit which correspond to the impact caused by it.
If you consume more units than your weight divided by two the pub is not an option anymore.

(This may or may not reflect reality)

The following are valid beverages and the corresponding alcoholic units of the beverage:

Beer: b, 1 unit
Energy drink: e, 0 units
Hot sauce: h, 2 units (strong stuff)
Juice (made of organic fruits etc): j, 0 units
Rum: r, 6 units
Tequila: t, 7 units
Vodka: v, 6 units
Wine: w, 3 units

There are different amount types:

Bottle: B
Crate: C
Glass: G
Keg: K
Sip: S

Each amount type has a multiplier which multiplies the alcoholic units of the beverage contained in it:

Bottle: 3
Crate: 25
Glass: 2
Keg: 50
Sip: 0.2

Output

Your program shall output truthy/falsy to stdout if the amount consumed is above/below your body weight divided by 2. If the amount consumed is equal to your weight divided by 2, you should output falsy.

Samples of possible input and output

Input

70
1Bob 3Soj

Output

False

Input

2
1Cov

Output

1

Input

50
1Cob

Output

0

Input

100
4Gow 1Koe 1Bov 1Gow 2Sot

Output

True

The shortest program in bytes wins!

Python 3, 131
Now we're golfing with snakes!
Saved 18 bytes thanks to shebang.
Saved 4 more bytes thanks to DSM.
Saved a lot of bytes thanks to tzaman.
Many thanks to tzaman for his brilliant trick of abusing .find() returning -1 if it doesn't find a value.
Currently this assumes this drink format is exactly the way it's stated in the challenge, eg, only 1 digit worth of each drink.
w=input()
print(sum([6,50,4,100,.4]['BCGKS'.find(b)]*int(a)*int('1267730'['bhrtvw'.find(v)])for a,b,_,v in input().split())>int(w))


Draw a Spinning Pinwheel Remember those fun pinwheels that you blow on and they spin round and round? Let's code one!

A pinwheel will have the set of characters \ | / _ drawing its center and arms. One possible pinwheel could look like this:

    |
    |
    |_ ___
 ___|_|
      |
      |
      |

But what's a pinwheel that doesn't spin? No fun! We can make it spin by rearranging the symbols:

      /
\    /
 \  /
  \/\
   \/\
   /  \
  /    \
 /

The challenge is to create a program that takes three integers and outputs a pinwheel as specified below. The first of these is the number of arms it has, the second is the length of the pinwheel's arms, and the third is the number of times it will spin one-eighth of a revolution clockwise.

You can assume the following:

The number of arms will always be 0, 1, 2, 4, or 8.
All the arms will be equally spaced apart from each other.
The initial position of the pinwheel will have its center like this:

 _
|_|

If the number of arms is 1, you may decide which direction the arm points.
If the number of arms is 2, you may decide to make the arms point vertically or horizontally.

You can write a full program that takes input through STDIN or command-line argument, or a function that takes input through function arguments. Your program must show a sequence of outputs that shows the pinwheel spinning, each separated by at least one empty line. The center of the pinwheel should not move by more than one space. You may output as many leading and trailing spaces as necessary.

Here are some examples:

0 2 1

 _
|_|

/\
\/

1 3 2

|
|
|_
|_|

   /
  /
 /
/\
\/

 _ ___
|_|

2 2 0

   _ __
__|_|

8 4 1

 \   |    /
  \  |   /
   \ |  /
    \|_/____
 ____|_|
     / |\
    /  | \
   /   |  \
  /    |   \

     |   /
 \   |  /
  \  | /
   \ |/
____\/\____
     \/\
     /| \
    / |  \
   /  |   \
  /   |

This is code golf, so shortest code wins. Good luck!

Python 2 535 517 473 468 bytes

Saved 5 bytes thanks to @Easterly Ink!

Input expected to be comma separated (i.e., numArms,armLength,numRots)

Golfed Version

n,l,t=input()
b=[7,3,1,5,0,4,2,6][:n]
w=5+2*l
h=w-3
X=w/2
Y=h/2-1
z=range
d=[0,1,1,1,0,-1,-1,-1]
for j in z(t+1):
 g=[[' 'for _ in[1]*w]for _ in[1]*h];a=j%2;b=[(k+1)%8for k in b];print''
 if a:g[Y][X:X+2]='/\\';g[Y+1][X:X+2]='\\/'
 else:g[Y][X+1]='_';g[Y+1][X:X+3]='|_|'
 for k in b:k=k+8*a;x=[0,2,3,3,2,0,-1,-1,0,1,2,2,1,0,-2,-1][k]+X;y=[0,0,0,2,2,2,1,0,-1,-1,0,1,2,2,0,0][k]+Y;exec"g[y][x]='|/_\\\\'[k%4];x+=d[k%8];y+=d[(k-2)%8];"*l
 for k in z(h):print''.join(g[k])

Ungolfed Version

numArms, armLength, rotAmount = input()

# Choose which arms to draw
arms = [0,4,2,6,1,5,3,7][:numArms]
for i in xrange(rotAmount+1):

    # Set up the grid spacing
    maxWidth = 5 + 2 * armLength
    maxHeight = 2 + 2 * armLength
    grid = [[' ' for x in xrange(maxWidth)] for y in xrange(maxHeight)]

    # Add the base square
    angle = i%2
    startX = len(grid[0])/2
    startY = len(grid)/2 - 1
    if angle:
        grid[startY][startX:startX+2] = '/\\'
        grid[startY+1][startX:startX+2] = '\\/'
    else:
        grid[startY][startX+1] = '_'
        grid[startY+1][startX:startX+3] = '|_|'

    for armNum in arms:
        # Determine where this arm starts
        armIdx = armNum + 8*angle;
        armX = [0,2,3,3,2,0,-1,-1,0,1,2,2,1,0,-2,-1][armIdx] + startX
        armY = [0,0,0,2,2,2,1,0,-1,-1,0,1,2,2,0,0][armIdx] + startY

        # Determine the direction it travels
        d = [0,1,1,1,0,-1,-1,-1]
        dirX = [0,1,1,1,0,-1,-1,-1][armIdx%8]
        dirY = [-1,-1,0,1,1,1,0,-1][(armIdx)%8]
        sym = '|/_\\'[armIdx%4]

        # Draw the arm
        for i in xrange(armLength):
            grid[armY][armX] = sym
            armX += dirX
            armY += dirY

    # Increment which arms to draw next
    arms = [(a+1)%8 for a in arms]
    for i in xrange(len(grid)):
        print ''.join(grid[i])
    print ''

Explanation

Pretty simple when it's broken down. First figure out how big of grid is required, then plot the base square or diamond.

Each arm's starting location, symbol and direction is hardcoded in for each of the 8 possible arms for the square and diamond base. Then, drawing them is easy enough.

To rotate everything, I simply switch between the square and diamond base, then increment each of the arms, rotating them clockwise once.


How many unique ways are there to achieve a score in Football? Challenge: given a number, calculate how many unique, order-independent ways there are to achieve a score of that number in American Football.

Let's see how few characters can be used in each of your favorite languages! The usual rules apply.  Input and output in a way that is natural to your language.

Recall that the ways to score in Football are safety (2 points), field goal (3 points), touchdown (6 points), touchdown + extra point (7 points), and touchdown + 2-point conversion (8 points).

For example, given 9 as input, the program should return 4, since you could score:

1 touchdown + extra point and 1 safety
1 touchdown and 1 field goal
3 field goals
3 safeties and 1 field goal

Note that order does not matter.

Mathematica - 42

Length@IntegerPartitions[#,∞,{2,3,6,7,8}]&

Prolog - 140

Never wrote anything in Prolog before, just knew that this problem should be quite nice for it.

p(0,_,[]).
p(N,[H|T],O):- N>=H,p(N,T,O).
p(N,[H|S],[H|T]):- N>=H,M is N-H,p(M,[H|S],T).
f(N,C):- aggregate(count,X^p(N,[2,3,6,7,8],X),C).

?- f(9,C).
C = 4.


Generate Numpad-Friendly Numbers Inspired by Generate Keyboard Friendly Numbers.

Background

Many number pads have the following layout:

789

456

123

    0

We define a number's neighborhood as the set of cells orthogonally adjacent to it on the numpad shown, including itself. For example, 2's neighborhood is {1,5,3,0,2} and 0's neighborhood is {1,2,0}. There is a list of each number's neighborhood below, above test cases.

We define a numpad friendly number as a positive integer where, when written in decimal without leading zeroes, each digit except for the first is in the neighborhood of the previous digit.

For example,

7856 is a numpad friendly number because 8 is in the neighborhood of 7, 5 is in the neighborhoood of 8, and 6 is in the neighborhood of 5.
1201 is a numpad friendly number because 2 is in the neighborhood of 1, 0 is in the neighborhood of 2, and 1 is in the neighborhood of 0.
82 is not a numpad friendly number because 2 is not in the neighborhood of 8.
802 is not a numpad friendly number because 0 is not in the neighborhood of 8 (neighborhoods don't wrap around).

Related OEIS Sequence. Note that this related sequence is distinct because it counts 0 as adjacent to 7 instead of 1 and 2.

Challenge

Given a positive integer n, return the n-th or the first n numpad friendly numbers, where the first is 1. You may use 0-based indexing, where the 0-th numpad friendly number would be 1.

Neighborhoods

Each digits's neighborhood is listed here:

0:{0,1,2}
1:{0,1,2,4}
2:{0,1,2,3,5}
3:{2,3,6}
4:{1,4,5,7}
5:{2,4,5,6,8}
6:{3,5,6,9}
7:{4,7,8}
8:{5,7,8,9}
9:{6,8,9}

Test Cases / Sequence

These are the first 100 terms

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 20, 21, 22, 23, 25, 32, 33, 36, 41, 44, 45, 47, 52, 54, 55, 56, 58, 63, 65, 66, 69, 74, 77, 78, 85, 87, 88, 89, 96, 98, 99, 100, 101, 102, 110, 111, 112, 114, 120, 121, 122, 123, 125, 141, 144, 145, 147, 200, 201, 202, 210, 211, 212, 214, 220, 221, 222, 223, 225, 232, 233, 236, 252, 254, 255, 256, 258, 320, 321, 322, 323, 325, 332, 333, 336, 363, 365, 366, 369, 410, 411, 412, 414, 441, 444, 445, 447]


Shortest implementation of a linked list, stack and queue Challenge

Write the shortest program that implements the minimum requirements for a linked list, stack and queue.

Minimum requirements

Functions that allow the user to add and remove elements from the linked list, stack and queue.
Any data type can be added to the linked list, stack and queue (string, int, etc.).
One special function (e.g. sort letters alphabetically).
The program must work (compile without errors and operations and results should make sense in the context of linked lists, stacks and queues)!
Lastly, this program must be hard-coded.  Arrays, however, are allowed (please refer to the restrictions section).

Winning criteria

Standard Codegolf rules.
Number of characters based on the summation of characters for linked list, stack and queue.

Restrictions

No trivial answers (i.e. 0 or 1 for a stack based language).
You are allowed to write the program in any language except for stack-based languages (let me know if this is unfair).
You cannot simply use the functions of another class.  If a language (like Ruby) already has push and pop functions in arrays or any other class, you must write your own push and pop functions.

Little blurb: If this code golf challenge is too simple, I will add more requirements.  I'm also open to any suggestions.

Haskell, 81 69 characters

data L a=N|a:~L a
N~:z=z:~N
(a:~b)~:z=a:~(b~:z)
r N=N
r(a:~z)=r z~:a

This code makes use of no preexisting functions at all. The push operation is :~, the enqueue operation is ~:. Both pop and dequeue are via pattern match against :~. The extra operation r is reverse.

Stacks:

ex1 =
    let stack0 = N                      -- empty stack
        stack1 = 'a' :~ stack0          -- push 'a'
        stack2 = 'b' :~ stack1          -- push 'b'
        first :~ stack3 = stack2        -- pop
        second :~ stack4 = stack3       -- pop
    in mapM_ print [first, second]

—

λ: ex1
'b'
'a'

Queues:

ex2 =
    let queue0 = N                      -- empty queue
        queue1 = queue0 ~: 'x'          -- enq 'x'
        queue2 = queue1 ~: 'y'          -- enq 'y'
        queue3 = queue2 ~: 'z'          -- enq 'z'
        next0 :~ queue4 = queue3        -- deq
        next1 :~ queue5 = queue4        -- deq
        next2 :~ queue6 = queue5        -- deq
    in mapM_ print [next0, next1, next2]

—

λ: ex2
'x'
'y'
'z'

List reverse operation:

ex3 =
    let list = "alpha" :~ ("beta" :~ ("gamma" :~ N)) -- a list
        tsil = r list                   -- reverse the list
        native N = []                   -- convert to native list
        native (a:~z) = a : native z    -- for easy printing
    in mapM_ (print . native) [list, tsil]

—

λ: ex3
["alpha","beta","gamma"]
["gamma","beta","alpha"]


Square-Cube Digit Usage The point of this challenge is to find the smallest positive integer that uses up at least all of the digits supplied in the input after it is squared and cubed.

So, when provided an input such as 0123456789 (i.e. a number that finds the result):

69² = 4761
69³ = 328509

It means that 69 is the result of such an input. (Fun fact: 69 is the smallest number that uses up all of the decimal digits of 0 to 9 after squaring and cubing.)

Specification

The input doesn't have to be unique. For example, the input can be 1466 and here's the result:

4² = 16
4³ = 64

That means we can't just fulfill this input by just doing a number that only uses 1 digit of 6, it has to have 2 digits of 6 in the output.

Test cases

Here's an exhaustive list of all numbers from 1 to 10000.

1333 (or 3133/3313/3331) -> 111

Input specification

You may take input as a list of digits.
Since the test cases (somehow) have a bug in it, here's an extra rule: the 0's in the input will be ignored.

05AB1E, 14 12 13 bytes
-2 bytes thanks to @KevinCruijssen
+1 byte thanks to @Grimmy
∞.Δ23SmJœIÅ?Z

Try it online!

Explanation
∞.Δ                  - First number that...
   23Sm              - Power of 2 and 3 [n^2, n^3]
       J             - Concatenated
        œ            - Permutations of this number
         IÅ?Z        - any of these start with the number

By the way it's quite slow...


Print coordinates of an NxN grid Question: Print out all the coordinates of a NxN grid. Preferably in C, however other languages also accepted

Input: N (integer)

Output: for N=3, a 3x3 grid:

0,0
1,0
2,0
0,1
1,1
2,1
0,2
1,2
2,2

Japt, 3 bytes
o ï

Try it
o       :Range [0,input)
  ï     :Cartesian product with itself


Javascript: Create a 10x10 array of 1s Obviously this challenge would be trivial with separate functions and libraries, so they aren't allowed.

Your code must conform to an ECMAscript specification (any spec will do), so no browser-specific answers.

The array must be accessible after it is instantiated.

I have an answer that I'll withhold for now.

Note: this challenge is specific to javascript because it is notoriously inconvenient to make multi-dimensional arrays in javascript.

Javascript, 34 bytes
for(r=[b=[i=10]];i--;r[i]=b)b[i]=1

Since it's apparently OK to make the rows equal by reference, I guess it's apparently OK to rely on that fact. This helps us shave off one for-loop by building the table at the same time as its rows. So, here's my new contestant.
Since r[0] and b[0] are overwritten during the loop, they can contain garbage. This gives us another free execution slot to shave off some commas. Sadly, r=b=[] won't do, since then they are equal by-ref.
Also, it scales well (99x99 is still 34 bytes), doesn't require ES5 (the new functions have terribly long names, anyways), and as a bonus, it's unreadable :-)


Find the Mr of a Given Compound! Challenge

Given the formula of a chemical, output the Mr of the compound.

Equation

Each element in the compound is followed by a number that denotes the number of said atom in the compound. If there isn't a number, there is only one of that atom in the compound.

Some examples are:

Ethanol (C2H6O) would be C2H6O where there are two carbon atoms, 6 hydrogen atoms and 1 oxygen atom
Magnesium Hydroxide (MgO2H2) would be MgO2H2 where there is one magnesium atom, two oxygen atoms and two hydrogen atoms.

Note that you will never have to handle brackets and each element is included only once in the formula.

Whilst most people will probably stick to the order they feel most comfortable with, there is no strict ordering system. For example, water may be given as either H2O or OH2.

Mr

Note: Here, assume formula mass is the same as molecular mass

The Mr of a compound, the molecular mass, is the sum of the atomic weights of the atoms in the molecule.

The only elements and their atomic weights to 1 decimal place that you have to support (hydrogen to calcium, not including noble gases) are as follows. They can also be found here

H  - 1.0      Li - 6.9      Be - 9.0
B  - 10.8     C  - 12.0     N  - 14.0
O  - 16.0     F  - 19.0     Na - 23.0
Mg - 24.3     Al - 27.0     Si - 28.1
P  - 31.0     S  - 32.1     Cl - 35.5
K  - 39.1     Ca - 40.1

You should always give the output to one decimal place.

For example, ethanol (C2H6O) has an Mr of 46.0 as it is the sum of the atomic weights of the elements in it:

12.0 + 12.0 + 1.0 + 1.0 + 1.0 + 1.0 + 1.0 + 1.0 + 16.0
(2*C + 6*H + 1*O)

Input

A single string in the above format. You can guarantee that the elements included in the equation will be actual elemental symbols.

The given compound isn't guaranteed to exist in reality.

Output

The total Mr of the compound, to 1 decimal place.

Rules

Builtins which access element or chemical data are disallowed (sorry Mathematica)

Examples

Input > Output
CaCO3 > 100.1
H2SO4 > 98.1
SF6 > 146.1
C100H202O53 > 2250.0

Winning

Shortest code in bytes wins.

  This post was adopted with permission from caird coinheringaahing. (Post now deleted)

Jelly, 63 bytes

ḟØDOP%⁽¡ṛị“ÇṚÆ’BH+“Ḳ"ɦṀ⁷6<s¡_-¦y⁼Ḟ¡¡FPɓ‘¤÷5
fØDVȯ1×Ç
Œs>œṗ⁸ḊÇ€S

A monadic link accepting a list of characters and returning a number.

Try it online!

How?

ḟØDOP%⁽¡ṛị“ÇṚÆ’BH+“Ḳ"ɦṀ⁷6<s¡_-¦y⁼Ḟ¡¡FPɓ‘¤÷5 - Link 1, Atomic weight: list of characters
                                            -                              e.g. "Cl23"
 ØD                                         - digit yield = "0123456789"
ḟ                                           - filter discard                      "Cl"
   O                                        - cast to ordinals                [67,108]
    P                                       - product                            7236
      ⁽¡ṛ                                   - base 250 literal = 1223
     %                                      - modulo                             1121
                                        ¤   - nilad followed by link(s) as a nilad:
          “ÇṚÆ’                             -   base 250 literal  = 983264
               B                            -   convert to binary = [    1,    1,     1,     1,   0,  0,  0,   0, 0,  0,  0, 0,     1,     1,     1, 0, 0,  0,  0,   0]
                H                           -   halve             = [  0.5,  0.5,   0.5,   0.5,   0,  0,  0,   0, 0,  0,  0, 0,   0.5,   0.5,   0.5, 0, 0,  0,  0,   0]
                  “Ḳ"ɦṀ⁷6<s¡_-¦y⁼Ḟ¡¡FPɓ‘    -   code-page indexes = [177  , 34  , 160  , 200  , 135, 54, 60, 115, 0, 95, 45, 5, 121  , 140  , 195  , 0, 0, 70, 80, 155]
                 +                          -   addition          = [177.5, 34.5, 160.5, 200.5, 135, 54, 60, 115, 0, 95, 45, 5, 121.5, 140.5, 195.5, 0, 0, 70, 80, 155]
         ị                                  - index into (1-indexed and modular)
                                            -    ...20 items so e.g. 1121%20=1 so 177.5
                                         ÷5 - divide by 5                          35.5

fØDVȯ1×Ç - Link 2: Total weight of multiple of atoms: list of characters   e.g. "Cl23"
 ØD      - digit yield = "0123456789"
f        - filter keep                                                            "23"
   V     - evaluate as Jelly code                                                  23
    ȯ1   - logical or with one (no digits yields an empty string which evaluates to zero)
       Ç - call last link (1) as a monad (get the atomic weight)                   35.5
      ×  - multiply                                                               816.5

Œs>œṗ⁸ḊÇ€S - Main link: list of characters                             e.g. "C24HCl23"
Œs         - swap case                                                      "c24hcL23"
  >        - greater than? (vectorises)                                      10011000
     ⁸     - chain's left argument                                          "C24HCl23"
   œṗ      - partition at truthy indexes                          ["","C24","H","Cl23"]
      Ḋ    - dequeue                                                 ["C24","H","Cl23"]
       Ç€  - call last link (2) as a monad for €ach                  [  288,  1,  816.5]
         S - sum                                                                 1105.5


Go south, east and north, come to the same place There is that famous riddle:

  A bear walks 1 km south, 1 km east and 1 km north, and comes to the place it started from. What color is the bear?

This one is very old, so I'll generalize it:

  A bear walks x km south, y km east and x km north, and comes to the place it started from. This bear thinks that the North Pole is boring, so it never goes there. Which latitude did it start and end at?

Assume that the bear is an idealized point, and the Earth is a perfect sphere with 10000 km distance from the pole to the equator (however, you can use a more accurate model if it's easier for some reason).

Write a program or a subroutine that receives the two numbers x and y, and prints or returns the latitude.

Fine points:

Input with at least 3 decimal places of precision should be supported
Input is in the range (0...99999), bounds not inclusive
If the situation is physically impossible, print an empty string or a message, or return an impossible value (like 91 or NaN - or, in fact, 90 - since 90 is an impossible value)
You should print the most northern (maximal) latitude that satisfies the conditions, except the North Pole. If the North Pole is the only solution, see above.
Output precision should be like IEEE single precison or better (24 bits or 7 decimal digits of precision).
If the output is printed, use decimal notation (e.g. -89.99 for a point near the South Pole) . If the output is returned, use floating-point or fixed-point notation.

Shortest code in bytes wins.

CJam, 62 chars

{4e4/:Y\9e-3*:X90-P180/:Q*mc/XY2$m](/mCQ/+_90<\@XY@m[)/mCQ/-?}

This is a block (subroutine) which takes x y on the stack and leaves the solution on the stack.

Online demo

I'm interpreting the spec to allow returning 90 as an "impossible value" if there is no other solution. If that interpretation is disallowed, I think the best fix would be

{4e4/:Y\9e-3*:X90-P180/:Q*mc/[XY2$m](/mCQ/+\XY@m[)/mCQ/--91]{90<}=}


Recreate the Windows ME screensaver as ASCII This challenge is inspired from this answer at the Ask Ubuntu Stack Exchange.

Intro

Remember the Windows ME screensaver with the pipes? Time to bring the nostalgia back!

Challenge

You should write a program or function which will output an ASCII representation of the screensaver. In the screensaver there should be a single pipe which will grow in semi-random directions.
The start of the pipe will be randomly placed at any of the borders of the screen and the pipe piece should be perpendicular to the border (corner first-pipes can either be horizontal or vertical). Each tick the pipe will grow in the direction it is facing (horizontal/vertical) at an 80% chance or take a corner at a 20% chance.

Pipe representation

To create the pipe, 6 unicode characters will be used

─    \u2500    horizontal pipe
│    \u2502    vertical pipe
┌    \u250C    upper left corner pipe
┐    \u2510    upper right corner pipe
└    \u2514    lower left corner pipe
┘    \u2518    lower right corner pipe

Input

The program / function will take 3 values of input, which can be gathered through function parameters or prompted to the user.

Amount of ticks
Screen width
Screen height

Amount of ticks

For every tick, a piece of pipe will be added to the screen. Pipes will overwrite old pipe pieces if they spawn at the same position.

For example, take a screen of size 3x3

ticks == 3
─┐
 ┘

ticks == 4
─┐
└┘

ticks == 5
│┐
└┘

Whenever a pipe exits the screen, as in the last example at 5 ticks, then a new pipe will spawn at a random border. For example:

ticks == 6
│┐
└┘
  ─

The new pipe should have a 50% chance of being horizontal or vertical.

Screen width/height

The screen width and height can be combined into a single value if that's preferrable in your language of choice. The screen width and height will always have a minimum value of 1 and a maximum value of 255. If your language of choice supports a console or output screen which is smaller than a 255x255 grid of characters then you may assume that the width and height will never exceed the boundaries of your console. (Example: Windows 80x25 cmd window)

Output

The output of your program/function should be printed to the screen, or returned from a function. For every run of your program, a different set of pipes should be generated.

Test cases

The following test cases are all random examples of valid outputs

f(4, 3, 3)
 │
─┘
  │

f(5, 3, 3)
 │
─┘┌
  │

f(6, 3, 3)
─│
─┘┌
  │

f(7, 3, 3)
──
─┘┌
  │

Obviously, the more ticks that have occured, the harder it becomes to prove the validity of your program. Hence, posting a gif of your output running will be preferred. If this is not possible, please post a version of your code which includes printing the output. Obviously, this will not count towards your score.

Rules

This is code-golf, shortest amount of bytes wins
Standard loopholes apply
If you use the unicode pipe characters in your source code, you may count them as a single byte

This is quite a hard challenge that can possibly be solved in many creative ways, you are encouraged to write an answer in a more verbose language even though there are already answers in short esolangs. This will create a catalog of shortest answers per language. Bonus upvotes for fancy coloured gifs ;)

Happy golfing!

Disclaimer: I am aware that Unicode characters aren't ASCII, but in lack of a better name I just call it ASCII art. Suggestions are welcome :)

Nothing says nostalgia quite like...

QBasic, 332 bytes

INPUT t,w,h
RANDOMIZE
CLS
1b=INT(RND*4)
d=b
IF b MOD 2THEN c=(b-1)/2*(w-1)+1:r=1+INT(RND*h)ELSE c=1+INT(RND*w):r=b/2*(h-1)+1
WHILE t
LOCATE r,c
m=(b+d)MOD 4
IF b=d THEN x=8.5*m ELSE x=13*m+(1<((b MOD m*3)+m)MOD 5)
?CHR$(179+x);
r=r-(d-1)MOD 2
c=c-(d-2)MOD 2
b=d
d=(4+d+INT(RND*1.25-.125))MOD 4
t=t-1
IF(r<=h)*(c<=w)*r*c=0GOTO 1
WEND

QBasic is the right language for the task because:

Its encoding includes box drawing characters--no need for Unicode
LOCATE allows you to print to any location on the screen, overwriting what was there previously
Microsoft®

Specifics

This is golfed QBasic, written and tested on QB64 with autoformatting turned off. If you type/paste it into the actual QBasic IDE, it will add a bunch of spaces and expand ? into PRINT, but it should run exactly the same.

The program inputs three comma-separated values: ticks, width, and height. It then asks for a random-number seed. (If this behavior isn't acceptable, change the second line to RANDOMIZE TIMER for +6 bytes.) Finally, it draws the pipes to the screen.

The maximum dimensions that can be entered are 80 (width) by 25 (height). Giving a height of 25 will result in the bottom row getting cut off when QBasic says "Press any key to continue."

How?

TL;DR: A lot of math.

The current row and column are r and c; the current direction is d and the previous direction is b. Direction values 0-3 are down, right, up, left. Arithmetic translates those into the correct step values for r and c, as well as the correct edge coordinates to start on.

The box drawing characters │┐└─┘┌ are code points 179, 191, 192, 196, 217, and 218 in QBasic. Those appear pretty random, but it still used fewer characters to generate the numbers with some (pretty convoluted, I'm-not-sure-even-I-understand-it) math than to do a bunch of conditional statements.

The code for changing direction generates a random number between -0.125 and 1.125 and takes its floor. This gives -1 10% of the time, 0 80% of the time, and 1 10% of the time. We then add this to the current value of d, mod 4. Adding 0 keeps the current direction; adding +/-1 makes a turn.

As for control flow, the WHILE t ... WEND is the main loop; the section before it, starting with line number 1 (1b=INT(RND*4)), restarts the pipe at a random edge. Whenever r and c are outside the window, we GOTO 1.

Show me the GIF!

Here you go:

This was generated by a somewhat ungolfed version with animation, color, and an automatic random seed:

INPUT t, w, h
RANDOMIZE TIMER
CLS

restart:
' Calculate an edge to start from

b = INT(RND * 4)
'0: top edge (moving down)
'1: left edge (moving right)
'2: bottom edge (moving up)
'3: right edge (moving left)
d = b

' Calculate column and row for a random point on that edge
IF b MOD 2 THEN
    c = (b - 1) / 2 * (w - 1) + 1
    r = 1 + INT(RND * h)
ELSE
    c = 1 + INT(RND * w)
    r = b / 2 * (h - 1) + 1
END IF
COLOR INT(RND * 15) + 1

WHILE t
    ' Mathemagic to generate the correct box-drawing character
    m = (b + d) MOD 4
    IF b = d THEN
        x = 17 * m / 2
    ELSE
        x = 13 * m + (1 < ((b MOD m * 3) + m) MOD 5)
    END IF
    LOCATE r, c
    PRINT CHR$(179 + x);

    ' Update row and column
    r = r - (d - 1) MOD 2
    c = c - (d - 2) MOD 2
    ' Generate new direction (10% turn one way, 10% turn the other way,
    ' 80% go straight)
    b = d
    d = (4 + d + INT(RND * 1.25 - .125)) MOD 4

    ' Pause
    z = TIMER
    WHILE TIMER < z + 0.01
        IF z > TIMER THEN z = z - 86400
    WEND

    t = t - 1
    IF r > h OR c > w OR r = 0 OR c = 0 THEN GOTO restart
WEND