Tips for golfing in sed What general tips do you have for golfing in sed? I'm looking for ideas which can be applied to code-golf problems and which are also at least somewhat specific to sed (e.g. "remove comments" is not an answer).

Please post one tip per answer.

If you need to use labels then for sure you'll want your label names to be as short as possible.  In fact taken to the extreme, you may even use the empty string as a label name:

:    # define label ""
p    # print pattern space
b    # infinite loop! - branch to label ""


Tips for golfing in Rust While Rust is very, very rarely competitive in code golfing competitions (Java is often shorter), it can still be fun to golf in. What are some tricks for making Rust code shorter?

Please post only one tip in each answer.

Use closures instead of functions

A closure:

|n|n+1

is shorter than a function:

fn f(n:i32)->i32{n+1}

Closures longer than one statement need braces but are still far shorter than a function.


Write a third order quine This challenge is an extension of 'Golf a mutual quine'.

Using three languages of your choice, create a third order Ouroboros program.

That is, in language A, write a program pA which outputs program pB in language B. Program pB should output program pC in language C, which in turn outputs the original program pA in language A.

No two languages in A, B, and C can be the same or subsets or supersets of each other. None of pA, pB or pC may be identical.

For example, a Haskell program outputs a Perl program which outputs a java program which outputs the original Haskell program would be valid.

On the other hand, a C# 4 program which outputs a C# 3 program which outputs a C# 2 program is invalid. Even a Perl -> Ruby -> Bash combination would be invalid if, say, the Perl program and the Ruby program were identical.

This is code golf, so the shortest program pA wins.

Python -> Perl -> Ruby, 48 characters
Adaption of my previous answer. Running
s='print q<puts %%q{s=%r;print s%%s}>';print s%s

with Python generates this Perl snippet
print q<puts %q{s='print q<puts %%q{s=%r;print s%%s}>';print s%s}>

which generates the following Ruby code
puts %q{s='print q<puts %%q{s=%r;print s%%s}>';print s%s}

which then prints the original Python snippet:
diff -s <(ruby <(perl <(python thirdorderquine.py))) thirdorderquine.py
Files /dev/fd/63 and thirdorderquine.py are identical


Cayley Table of the Dihedral Group \$D_3\$ The Dihedral group \$D_3\$ represents the symmetries of an equilateral triangle, using the identity (represented by id), rotations (represented by r1 and r2), and reflections (represented by s0, s1, and s2).

Your task is to compute the composition \$yx\$ of the elements \$x, y \in D_3 \$. They are given by the Cayley table below:

  x  id  r1  r2  s0  s1  s2
y  +-----------------------
id | id  r1  r2  s0  s1  s2
r1 | r1  r2  id  s1  s2  s0
r2 | r2  id  r1  s2  s0  s1
s0 | s0  s2  s1  id  r2  r1
s1 | s1  s0  s2  r1  id  r2
s2 | s2  s1  s0  r2  r1  id

Input

Any reasonable input of x and y. Order does not matter.

Output

y composed with x, or looking up values in the table based on x and y.

Test Cases

These are given in the form x y -> yx.

id id -> id
s1 s2 -> r1
r1 r1 -> r2
r2 r1 -> id
s0 id -> s0
id s0 -> s0

Notes on I/O

You may use any reasonable replacement of id, r1, r2, s0, s1, s2, for example 1, 2, 3, 4, 5, 6, 0, 1, 2, 3, 4, 5, or even [0,0], [0,1], [0,2], [1,0], [1,1], [1,2] (here the first number represents rotation/reflection and the second is the index).

Python 2, 27 bytes

lambda o,O:[o[_]for _ in O]

Try it online!


Convert numbers to binary... but you're allowed to use twos as well Based on the "binary, but with twos" notation mentioned in this numberphile video, write a function that takes a single number as input and outputs all variations of that number in a "binary" system where twos are allowed.
Rules

Code must only be a function/method, not a full program
Input is an integer passed as the sole parameter to the function
Output is all valid variations of the input number converted to "binary, but with twos" notation
Output is the return value of the function, but can be in whatever format is convenient as long as it's obvious (eg, 3 ints, 3 strings, comma/space delimited string, array of ints, etc), order is unimportant
In the unlikely event that a language happens to contain a built-in function to achieve the result, it's disallowed
Shortest code in bytes is the winner

Explanation of the output
By example, if you're passed the number 9, you can convert it to binary as 1001, but if you allowed 2s in each position, you could also write it as 201 (i.e. 2*4 + 0*2 + 1*1), or 121 (i.e. 1*4 + 2*2 + 1*1), as shown in this table:
+----+----+----+----+
| 8s | 4s | 2s | 1s |
+----+----+----+----+
|  1 |  0 |  0 |  1 |
|  0 |  2 |  0 |  1 |
|  0 |  1 |  2 |  1 |
+----+----+----+----+

So, if passed 9, your function would need to return the three numbers, 1001, 201 and 121.
Format and order are irrelevant, so long as it's obvious (i.e. [121,201,1001], "0201 0121 1001", ("1001","121","201") are valid results when given an input of 9).
Examples

2 => 10, 2
9 => 1001, 201, 121
10 => 1010, 210, 202, 1002, 122
23 => 2111, 10111
37 => 100101, 20101, 100021, 20021, 12101, 12021, 11221

GolfScript (25 bytes) / CJam (19 17 bytes)

GolfScript:

{:^.*,{3base}%{2base^=},}

This creates an anonymous function (see meta discussion about permissibility of anonymous functions).

Online demo

A straight translation into CJam is (with thanks to Martin Büttner for shaving a couple of characters)

{:X_*,3fb{2bX=},}

Dissection

{             # Function boilerplate
  :^          # Store parameter as variable ^
  .*          # Square parameter - see detailed explanation below
  ,{3base}%   # Produce an array of 0 to ^*^-1 in ternary
  {2base^=},  # Filter to those which evaluate to ^ in binary
}

The reason for the squaring operation is that we need to iterate up to the largest possible value whose ternary representation, interpreted in binary, is equal to ^. Since 2 = 10, the "normal" binary representation of ^ is the one which matters. If we convert that to ternary, we find that the "worst" cases are powers of 2. An optimal approach would be to take the argument to the power of ln 3/ln 2 ~= 1.585, but squaring is much shorter.


Happy Rounded Pi Day To celebrate Rounded Pi Day, you must take advantage of today's date to make a program that takes in a circle's diameter and outputs its circumference by multiplying the diameter by 3.1416, where 3.1416 must be obtained using today's date.

Input 3
Output 9.4248
etc.

Does not take the date as input. You do not have to use all components of the date but the digits of pi must come from formatting a Date object or using a date object to obtain it. The answers so far look good.

Not sure what else to specify. All the answers so far meet what I was expecting.

My constraint was that you must use components of the date to come up with Pi. You can of course use the components, multiply by 0 then add 3.1416, but that's boring and wastes precious chars!

Shortest code wins!

C, 32 bytes

#define f(d)d*time(0)/464083315.

If losing a little more accuracy is fine, I can get it down to about 29 bytes being still accurate to 4 digits past the decimal (as of the time of this posting):

#define f(d)d*time(0)/46408e4


Running second maximum of a list Given a list of integers, your task is to output the second largest value in the first k elements, for each k between 2 and the length of the input list.

In other words, output the second largest value for each prefix of the input.

You can output an arbitrary value for the first element (where k = 1), or simply omit this value, as there isn't a second maximum for a list of 1 element. You may assume there are at least 2 elements in the input.

Shortest code wins.

Examples

Input:
1 5 2 3 5 9 5 8
Output:
  1 2 3 5 5 5 8
Input:
1 1 2 2 3 3 4
Output:
  1 1 2 2 3 3
Input:
2 1 0 -1 0 1 2
Output:
  1 1 1 1 1 2

Husk, 9 7 bytes
Saved a byte or two thanks to @Zgarb
mȯ→hOtḣ

Returns 0 for the first "second maximum"
Explaination
         -- implicit input, e.g          [1,5,3,6]
      ḣ  -- prefixes                     [[],[1],[1,5],[1,5,3],[1,5,3,6]]
     t   -- remove the first element     [[1],[1,5],[1,5,3],[1,5,3,6]]
mȯ       -- map the composition of 3 functions
    O    --   sort                       [[1],[1,5],[1,3,5],[1,3,5,6]]
   h     --   drop the last element      [[],[1],[1,3],[1,3,5]
  →      --   return the last element    [0,1,3,5]
         -- implicit output

Try it online!


Print Input Sideways Your program must take an alpha/numeric input string and print it sideways (rotated 90 degrees clockwise). So for example, HI, would become:

#####
  #
#####

#####

Rules:

The shortest code wins. For the sake of objectivity this will be the standard font. The input still only has to be alpha-numeric. Capitalization does not matter.

C 550 503

#define L putchar('\n');
c,b,i,j,m[]={0xe9d72e,0x10fd25,0x9ace29,0x556b5,0x4fd184,0x16ad6bd,0x156ae,0xc5e10,0x556aa,0x756a8,0,0,0,0,0,0,0,0xfa51e0,0xaad7e0,0x118c5c0,0xe8c7e0,0x15ad7e0,0x14a53e0,0x16ac5c0,0x1f213e0,0xf8000,0x1e08440,0x11513e0,0x1087e0,0x1f4111f,0x1f223e0,0xe8c62e,0x8a53e0,0xd9462e,0x5d29f,0x12ad6a9,0x1087e10,0xf043e,0x18304d8,0x1c1f07c,0xd909b,0xf14bd,0xcd6b3};main(){for(;;){c=getchar();c=c<48?11:c>90?c-80:c-48;b=0;for(i=0;i<5;i++){for(j=0;j<5;j++)putchar(m[c]&(1<<b++)?35:32);L}L}}

(Incorporated BrainSteel's tips and optimized a bit more)

Here's the non-obfuscated code:

#include <stdio.h>

int map[]
={
    // 0 - 9
    0xe9d72e, 0x10fd25, 0x9ace29, 0x556b5, 0x4fd184, 0x16ad6bd, 0x156ae,     0xc5e10, 0x556aa, 0x756a8,
    // Other stuff
    0,0,0,0,0,0,0,
    // A - Z
    0xfa51e0, 0xaad7e0, 0x118c5c0, 0xe8c7e0, 0x15ad7e0, 0x14a53e0, 0x16ac5c0, 0x1f213e0, 0xf8000, 0x1e08440, 0x11513e0, 0x1087e0, 0x1f4111f, 0x1f223e0, 0xe8c62e, 0x8a53e0, 0xd9462e, 0x5d29f, 0x12ad6a9, 0x1087e10, 0xf043e, 0x18304d8, 0x1c1f07c, 0xd909b, 0xf14bd, 0xcd6b3
};

int main()
{
    for(;;)
    {
        int c = getchar();
        c = c < '0' ? 11 : c > 'Z' ? c - ('0' + 'a' - 'A') : c - '0';
        int bit = 0;
        for(int i=0; i<5; i++)
        {
            for(int j=0; j<5; j++)
                putchar(map[c] & (1 << bit++) ? '#' : ' ');
            putchar('\n');
        }
        putchar('\n');
    }
}

I've encoded the characters the following way: I wrote a C "script" that takes a 5x5 area of characters from STDIN, changes "space" to 0 and anything else to 1, rotates the whole area by 90 degrees and finally puts every cell of the area in one bit of a 32-bit integer (the hex numbers in 'map').
That's how the "script" looks like:

#include <stdio.h>

int main()
{
    int array[5][5];
    for(int i=0; i<5; i++)
    {
        for(int j=0; j<5; j++)
            array[j][i] = (getchar() != ' ');
        getchar();
    }
    int res = 0;
    int bit = 0;
    for(int j=0; j<5; j++)
    {
        for(int i=0; i<5; i++)
            res = res | (array[j][4-i] << bit++);
    }
    printf("0x%x\n", res);
    return 0;
}

I am pretty sure there are FAR smaller programs possible (for example in Perl or Ruby), but this is the best I can come up with right know.


J, 16 15 bytes

[h"2[h"1 h=.,,[

This is an anonymous verb. Try it online!

Thanks to Adám for 1 byte!

Explanation

[h"2[h"1 h=.,,[  Wrapper is x, present is y.
            ,    Prepend x to y
             ,   then append
              [  x.
                 This gives x y x, and the wrapper automatically spreads to form 2D slices.
         h=.     Save the above operation (not its result) to h.
    [h"1         Apply h to x and every 2D slice of the previous result.
[h"2             Apply h to x and every 1D slice of the result of that.


An Old Irish Blessing I don't know who coined these words, and I'm not Irish, but I give you an Irish blessing:

May the road rise up to meet you
May the wind be always at your back
May the sun shine warm upon your face
The rains fall soft upon your fields
And until we meet again
May God hold you in the hollow of His hand

I was planning on posting this a few weeks from now, but it just dawned on me that yesterday was Saint Patrick's Day.

Rules:

Produce the above text exactly.
(Feel free to break this rule for the sake of cleverness and amusement.)
The program must generate the text on its own accord.  cat is not a valid solution.
The solution with the fewest characters "wins".

I saw slight variations in wording among versions of the blessing I obtained from the Internet, so I tried to average them out.  Please use the version posted above.  Also, I dropped the punctuation to make it a bit easier.

May the luck of the Irish enfold you.

Python, 143 chars

#coding:u8
print u'慍⁹桴潲摡爠獩灵琠敭瑥礠畯䴊祡琠敨眠湩敢愠睬祡⁳瑡礠畯⁲慢正䴊祡琠敨猠湵猠楨敮眠牡灵湯礠畯⁲慦散吊敨爠楡獮映污潳瑦甠潰潹牵映敩摬ੳ湁湵楴敷洠敥⁴条楡੮慍⁹潇潨摬礠畯椠桴潨汬睯漠楈⁳慨摮'.encode("u16")[2:]

run at codepad.org


Simulate my keyboard I have an issue with my keyboard (more likely an issue with my browser). Some times when I click on a new text field and begin typing all my text comes out backwards.  After a very short amount of time (for the purpose of the challenge we will say it is 10 milliseconds) it resumes typing forwards again.  It seems that at first my cursor does not move when I begin to type so all the letters get inserted at the beginning of the textfield.

For example if I were typing python and I typed pyt in the first 10 milliseconds the result would be

hontyp

Task

Your job is to simulate this behavior in as few bytes as possible.

Input

You may take input in any reasonable method. You may not however take the input as two separate fields.  The 10 millisecond delay should start when the program begins to allow input.  That is you may have preprocessing to do before input is allowed, which should not be counted towards the 10 milliseconds.

Some leniency is permitted in the timing as long as it averages 10 milliseconds and is off by more than 1 milliseconds no more than 1% of the time on a reasonably speced computer.

Output

You may output the string in whatever method you see fit.  You may either update live as the user is typing or output the result after you are finished taking input (either by a newline or end of file ^D).

Test cases

Some of these were generated by this CMC in The Nineteenth Byte

First 10  | after   | result
bra         in-flak   in-flakarb
ap          ple       plepa
code-       golf      golf-edoc
no          ne        neon
we          st        stew
ai          med       media
draw        back      backward

VimScript, 48 47 bytes

Vim has some nice builtins for this. Requires Vim 8.

se ri|cal timer_start(10,{->execute("se ri&")})

Expects text entered in insert mode, a very reasonable input for VimScript. Explanation:

se ri " short for 'set revins', or 'reverse insert'
cal timer_start(10, " Start a timer that fires after 10ms
                 {->execute("se ri&")}) " Give it a lambda that unsets ri

My initial approach, se ri|sl10m|se ri&, doesn't work because the text is buffered until after the sleep command, and I couldn't find a way around this.


Insert parens into a free-form SKI calculus expression Imagine a simple SKI calculus expression - for example, (((S α) β) γ). As you can see, each node of the rooted tree has exactly two children. Sometimes though, the parenthesis are omitted and the tree is unrooted (just to make the notation clear, I believe). The challenge is to put the parenthesis back, so that the tree is binary and rooted again.

The preferable way of I/O is mostly up to you; although the input and output has to at least look like the SKI calculus, and it obviously has to represent a tree.

The rule on adding parenthesis is simple: α β γ becomes ((α β) γ) (bind to the left), α β γ δ becomes (((α β) γ) δ), and so on.

You may assume that the input is a correct SKI-calculus expression.

If it wasn't clear enough, you may NOT add more braces than necessary. And if it helps you in any way, you can assume that the input contains no redundant parens (like, for example, (((SK)))).

Examples

S(KS)K => ((S(KS))K)
SS(SK) => ((SS)(SK))


Pyth, 26 bytes
Pjbm%"'%02d:%s0',"d*U24"03

Demonstration.
We start with the cartesian product of range(24) (U24) with the string "03".
Then, we map these values to the appropriate string formating substitution (m%"'%02d:%s0',"d).
Then, the resultant strings are joined on the newline character (jb).
Finally, we remove the trailing comma (P) and print.


Smooth vs. Chunky vs. Broken Squiggles Based on Chunky vs. Smooth Strings.
Squiggles /\_/\/\__/\/\/\/\_/\_/\ are fun to make on a keyboard when you are really bored.  But not all squiggles are created equal.  Some squiggles are smooth, like \___/, and some are chunky, like /\/\/\/\.  Others are just downright broken, like ////_\\\
Inside every squiggle of N characters, there are N-1 squiggle-junctions.  Each squiggle-junction is classified into one of three types:

Smooth (angle > "90 degrees"):
\_  __  _/

Chunky (angle = "90 degrees")
/\  \/

Broken (anything that doesn't connect)
//  \\  /_  _\

Let's define the smoothness to be the proportion of junctions that are smooth, with chunkiness and brokenness defined similarly. Each value ranges between 0 and 1. The sum of a squiggle's smoothness, chunkiness, and brokenness is always equal to 1.
For example, the squiggle /\/\\_//\_ has 3 smooth junctions, 4 chunky junctions, and 2 broken junctions.  It is thus 0.3333 smooth, 0.4444 chunky, and 0.2222 broken.
Empty strings and strings with only one character have undefined values, all input will be at least 2 characters long.
Challenge
Write a program that takes in a squiggle of arbitrary length and outputs any two of its smoothness, chunkiness, and brokenness values.

You may write a program or function, with input via STDIN, command line, or as a string argument.
You may assume the input is at least of length >= 2 and consists only of the characters /\_ with an optional trailing newline.
Print (or return if a function) the two floats to a precision of at least 4 decimals, rounded or truncated.  If the true value is 2/3, acceptable values include any value between 0.6666 and 0.6667, even things like 0.666637104.  If the exact value is 1/3, any answer containing 0.3333 is valid.  You may leave off trailing zeros, or the leading zero if the value is less than one.
Output any pair of the three values as you prefer, just be sure to state which two and in what order.

The shortest code in bytes wins.
Examples
/\/\\/\//\\ → Smoothness 0, Chunkiness 0.7, Brokenness 0.3
_/\\_/\\/__/\\\//_ → Smoothness 0.29411764705, Chunkiness 0.29411764705, Brokenness 0.41176470588
//\\__/_\/ → Smoothness 0.3333333, Chunkiness 0.2222222, Brokenness 0.4444444
Bonus question: Which do you prefer, smooth or chunky or broken squiggles?

Pyth, 25 bytes

mcl@.:d2.:z2tlzc2"\__//\/

Test suite

Outputs smoothness, chunkiness. Basically, it takes the hard coded string and cuts it in half. Each half is decomposed into its 2 character substrings, and the same is done for the input. We take the intersection, resulting in the south and chunky pairs. Then, we take the the length, divide by the number of pairs, and print.


Sum of Fibonacci numbers I found this task here.

  Given the ith (1<=i<=35) Fibonacci
  number F(i) calculate the sum of the
  ith till i+9th number
  F(i)+F(i+1)+...+F(i+9) and the last
  digit of the i+246th one F(i+246)

I have been trying to solve this using python and some tricks(Binnet's formula and a tricky recurrence):

 f=lambda n:((1+5**.5)**n-(1-5**.5)**n)/(2**n*5**.5)
 exec"n=input();print int(55*f(n)+88*f(n+1)+f(n+6)%10);"*input()

but I didn't yet managed to squeeze thought the give source code limit which is 111 and mine is 115,any hints how to improve my solution?

I am a rather newbie to python so any sort of help resulting in a successful solution will be much appreciated.

Thanks,

PS:After posting the same question in stackoverflow I thought that this should be more appropriate here as this site is precisely for Puzzles and Codegolf.

GolfScript 28 26 characters
Since the problem is here we might as well golf it. Anyone who plan on participating on spoj.pl better close their eyes while they read this.
~](;{11.@5+{.@+}*;.10%+n}%

It basically says: For all input, start with the numbers 11 and 11, do input+5 Fibonacci iterations, discard the highest of the two results, add itself mod 10 to the lowest result, done. As a formula this can be describes as 11*Fib(input+6) + (11*Fib(input+6)) mod 10.
Why does this work? It is simply a condensed way of calculating two second identities in the same run, one could start at [0 1] and [55 89], do a run on both of the same length and subtract the first result from the second to get the sum of a series of 10 Fibonacci numbers, but one may as well do the subtraction on the initial sets, thus getting the set [55 88], that can be stepped back a few steps to [11 11] which is short to write.
The Fibonacci series mod 10 has a period of 60, so Fib(i+246) mod 10 = Fib(i+6) mod 10.


Generate the fewest lottery tickets to play in order to have at least N good numbers This is a rather complex but very interesting maths subject (known as "covering problem"),

And I'd like your help for implementing it.

Imagine a lottery game, where each ticket must choose 5 random numbers in a set of 50 numbers (from 1 to 50).

It's quite easy to know the probability of a winning ticket, or the probability to have 1, 2, 3 or 4 good numbers.

It's also quite easy to "generate" all the tickets that have 1, 2, 3, 4 good numbers.

My question (and code challenge) is related to this, but slightly different:

I want to buy some lottery tickets (the fewest possible), such as at least one of my tickets has 3 good numbers.

Challenge

Your goal is to implement a generic solution (as a program or just a function), like this, in any language:

// Input: 3 prameters
min_lottery_tickets(total_numbers_to_choose_from, how_many_numbers_to_choose, how_many_good_numbers_i_want)

For the above example, one would just have to call:

min_lottery_tickets(50, 5, 3)

and the program will generate the smallest set of tickets to play to achieve this goal.

Example:

 min_lottery_tickets(10, 5, 2)

would output 7 tickets, like those:

1   2   3   4   5
5   6   7   8   9
10  1   2   6   7
10  3   4   8   9
3   4   6   7   8
1   2   3   8   9
1   4   9   5   10

because such tickets are enough to cover any pair of numbers from 1 to 10.

Output

Text, one line per ticket, tabulations or spaces between numbers

who wins

The most efficient program wins (i.e. the program generating the fewest tickets for the above parameters):

min_lottery_tickets(50, 5, 3)

Thanks!

I know it's not optimal, but here is the code in node.js:

function min_lottery_tickets(total_numbers_to_choose_from, how_many_numbers_to_choose, how_many_good_numbers_i_want) {
    c(function(result) {
        var other = result[result.length - 1];
        while (result.length < how_many_numbers_to_choose) {
            other++;
            var already = false;
            for (var i = 0; i < result.length; i++) {
                if (other === result[i]) {
                    already = true;
                    break;
                }
            }
            if (!already) {
                result.push(other);
            }
        }
        if (other <= total_numbers_to_choose_from) {
            // Print results
            console.log(result);
        }
    }, total_numbers_to_choose_from, how_many_good_numbers_i_want);
}

function c(next, total_numbers, length, start, results) {
    if (!start) start = 1;
    if (!results) results = [];

    for (var i = start; i <= total_numbers + 1 - length; i++) {
        var resultsNew = results.slice(0);
        resultsNew.push(i);
        if (length > 1) {
            c(next, total_numbers, length - 1, i + 1, resultsNew);
        } else {
            next(resultsNew);
        }
    }
}

Some example results:

> min_lottery_tickets(5, 3, 2)
[ 1, 2, 3 ]
[ 1, 3, 4 ]
[ 1, 4, 5 ]
[ 2, 3, 4 ]
[ 2, 4, 5 ]
[ 3, 4, 5 ]

other:

> min_lottery_tickets(10, 5, 2)
[ 1, 2, 3, 4, 5 ]
[ 1, 3, 4, 5, 6 ]
[ 1, 4, 5, 6, 7 ]
[ 1, 5, 6, 7, 8 ]
[ 1, 6, 7, 8, 9 ]
[ 1, 7, 8, 9, 10 ]
[ 2, 3, 4, 5, 6 ]
[ 2, 4, 5, 6, 7 ]
[ 2, 5, 6, 7, 8 ]
[ 2, 6, 7, 8, 9 ]
[ 2, 7, 8, 9, 10 ]
[ 3, 4, 5, 6, 7 ]
[ 3, 5, 6, 7, 8 ]
[ 3, 6, 7, 8, 9 ]
[ 3, 7, 8, 9, 10 ]
[ 4, 5, 6, 7, 8 ]
[ 4, 6, 7, 8, 9 ]
[ 4, 7, 8, 9, 10 ]
[ 5, 6, 7, 8, 9 ]
[ 5, 7, 8, 9, 10 ]
[ 6, 7, 8, 9, 10 ]

other:

> min_lottery_tickets(10, 5, 3)
[ 1, 2, 3, 4, 5 ]
[ 1, 2, 4, 5, 6 ]
[ 1, 2, 5, 6, 7 ]
[ 1, 2, 6, 7, 8 ]
[ 1, 2, 7, 8, 9 ]
[ 1, 2, 8, 9, 10 ]
[ 1, 3, 4, 5, 6 ]
[ 1, 3, 5, 6, 7 ]
[ 1, 3, 6, 7, 8 ]
[ 1, 3, 7, 8, 9 ]
[ 1, 3, 8, 9, 10 ]
[ 1, 4, 5, 6, 7 ]
[ 1, 4, 6, 7, 8 ]
[ 1, 4, 7, 8, 9 ]
[ 1, 4, 8, 9, 10 ]
[ 1, 5, 6, 7, 8 ]
[ 1, 5, 7, 8, 9 ]
[ 1, 5, 8, 9, 10 ]
[ 1, 6, 7, 8, 9 ]
[ 1, 6, 8, 9, 10 ]
[ 1, 7, 8, 9, 10 ]
[ 2, 3, 4, 5, 6 ]
[ 2, 3, 5, 6, 7 ]
[ 2, 3, 6, 7, 8 ]
[ 2, 3, 7, 8, 9 ]
[ 2, 3, 8, 9, 10 ]
[ 2, 4, 5, 6, 7 ]
[ 2, 4, 6, 7, 8 ]
[ 2, 4, 7, 8, 9 ]
[ 2, 4, 8, 9, 10 ]
[ 2, 5, 6, 7, 8 ]
[ 2, 5, 7, 8, 9 ]
[ 2, 5, 8, 9, 10 ]
[ 2, 6, 7, 8, 9 ]
[ 2, 6, 8, 9, 10 ]
[ 2, 7, 8, 9, 10 ]
[ 3, 4, 5, 6, 7 ]
[ 3, 4, 6, 7, 8 ]
[ 3, 4, 7, 8, 9 ]
[ 3, 4, 8, 9, 10 ]
[ 3, 5, 6, 7, 8 ]
[ 3, 5, 7, 8, 9 ]
[ 3, 5, 8, 9, 10 ]
[ 3, 6, 7, 8, 9 ]
[ 3, 6, 8, 9, 10 ]
[ 3, 7, 8, 9, 10 ]
[ 4, 5, 6, 7, 8 ]
[ 4, 5, 7, 8, 9 ]
[ 4, 5, 8, 9, 10 ]
[ 4, 6, 7, 8, 9 ]
[ 4, 6, 8, 9, 10 ]
[ 4, 7, 8, 9, 10 ]
[ 5, 6, 7, 8, 9 ]
[ 5, 6, 8, 9, 10 ]
[ 5, 7, 8, 9, 10 ]
[ 6, 7, 8, 9, 10 ]


Repeated Digit Primes Another sequence, another challenge.*

Definition

A prime p is in this sequence, let's call it A, iff for every digit d in p's decimal expansion, you replace d with d copies of d and the resulting integer is still prime; zeros are not permitted.

For example, 11 is trivially in this sequence (it's the first number, incidentally). Next in the sequence is 31, because 3331 is also prime; then 53 because 55555333 is also prime, and so on.

Challenge

Given an input n, return A(n), i.e. the nth item in this sequence.

Examples

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

11, 31, 53, 131, 149, 223, 283, 311, 313, 331, 397, 463, 641, 691, 937, 941, 1439, 1511, 1741, 1871

This means A(0) = 11, A(1) = 31, etc., when using zero indexing.

Rules

You can choose zero- or one-based indexing; please specify in your answer which.
Instead of returning just the nth element, you can instead choose to return the first n terms.
You can assume that the input/output will not be larger than your language's native integer format; however, the repeated-digit prime may be larger than your language's native format, so that will need to be accounted for.
For example, 1871, the last number of the examples, has a corresponding prime of 18888888877777771, which is quite a bit larger than standard INT32.
Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
Output can be to the console, returned from a function, displayed in an alert popup, etc.
Standard loopholes are forbidden.
This is code-golf so all usual golfing rules apply, and the shortest code (in bytes) wins.

*To be fair, I had come up with the first few terms of the sequence just playing around with some numbers, and then went to OEIS to get the rest of the sequence.

Husk, 15 bytes

!fo§&öεpd´ṘΠdİp

Try it online!

!                 Index into
             İp     the list of primes
 f                    for which:
            d            the digits of p
  o§&                      satisfy both:
     öεpd´Ṙ                  repeated "themselves" times, they form a prime.
           Π                 they are all nonzero.

Erik the Outgolfer saved a byte. Using ṗ instead of εp would save another byte, but that makes the program so slow it times our even for n = 2.


Help my maniacal wife decorate our Christmas tree My wife is very, let's say, particular when it comes to putting ornaments on our Christmas tree. Let's get her some code to help her in this trying time.

Input

Given an input 2 < n < 10 the height of the tree and 0 < k < n the distinct number of ornaments.

Task

Decorate the tree starting with 1 and increment to k as we wrap the ornaments around the tree. If we reach k and we have more branches to decorate then start back at 1.

It is okay if there are not the same number of each ornament on the tree, as long as the pattern is satisfied.

The ornaments should appear above each branch ^ except for the top row.

The tree is structured by starting with one branch  then the next level has + 1 branches with a space between each, staggered from the top like:

 ^
^ ^

For a third row you would add one more branch and stagger them again such that no branch is on the same column (if you think of it like a grid).

  ^
 ^ ^
^ ^ ^

Output

Output your decorated tree.

Examples

1.

 n = 3, k = 2

  ^      //Height is 3
 ^ ^
^ ^ ^

Now we decorate each branch starting with 1 and increment to k:

  ^
 1 2
 ^ ^
1 2 1
^ ^ ^

2.

 n = 6, k = 5

     ^    //Non-Decorated
    ^ ^
   ^ ^ ^
  ^ ^ ^ ^
 ^ ^ ^ ^ ^
^ ^ ^ ^ ^ ^

     ^    //Decorated
    1 2
    ^ ^
   3 4 5
   ^ ^ ^
  1 2 3 4
  ^ ^ ^ ^
 5 1 2 3 4
 ^ ^ ^ ^ ^
5 1 2 3 4 5
^ ^ ^ ^ ^ ^

3.

n = 5, k = 1

    ^
   ^ ^
  ^ ^ ^
 ^ ^ ^ ^
^ ^ ^ ^ ^

    ^
   1 1
   ^ ^
  1 1 1
  ^ ^ ^
 1 1 1 1
 ^ ^ ^ ^
1 1 1 1 1
^ ^ ^ ^ ^

This is code-golf so the shortest code wins! Have fun and good luck!


Decomposing into primes Given an integer n, return the number of ways that n can be written as a list of prime numbers. For example, 2323 can be written as (2,3,23), (23,23) or (2,3,2,3) or (23,2,3), so you would output 4. If it can not be written in this way, you should output 0.

A prime number such as 019 or 00000037 is a valid prime for this problem.

Test cases:

5 -> 1
55 -> 1
3593 -> 4 (359 and 3, or 3 and 593, or 3 and 59 and 3, or 3593)
3079 -> 2 (3 and 079, or 3079)
119 -> 0
5730000037 -> 7 (5,7,3,000003,7, 5,7,3,0000037, 5,73,000003,7, 5,73,0000037, 5,73000003,7, 5,7,30000037, 5730000037)
0-> undefined (you do not have to handle this case)

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

Edit: now I know why I should use the sandbox next time

Haskell, 96 89 bytes

5 bytes saved thanks to H.PWiz's primality test

p x=[1|0<-mod x<$>[2..x]]==[1]
f[]=1
f b=sum[f$drop i b|i<-[1..length b],p$read$take i b]

Try it online!

Explanation

The first thing that's done is creating a prime test function using Wilson's theorem using the definition of prime.

p x=[1|0<-mod x<$>[2..x]]==[1]

Then begin defining f.  The first thing I thought when I saw this problem was to use dynamic programming.  However dynamic programming costs bytes so this uses a "psuedo-dynamic programming" algorithm.  Whereas in dynamic programming you would store a Directed Acyclic graph in memory here we just use recursion and recalculate each node every time we need it.  It loses all of the time benefits of dynamic programming, but this is code-golf so who cares. (still better than brute force search though)

The algorithm is as follows, we construct a Directed Acyclic Graph, L, where each node represents a substring of the number.  In particular Li represents the last i digits of our input (lets call it n).

We define L0 to have a value of 1 and each other value in L to have the sum of each Lj such that j < i and the substring of n from i to j is prime.

Or in a formula:

We then return the value at the largest largest index of L. (Lk where k is the number of digits of n)


Is 7 l8r than 9? (Is seven later than nine?) This is a fairly simple code golf challenge. Your program, given an ASCII string, is to parse that string into two strings, which it will evaluate. If the second string is "later" than the first one, it will return a 1, if it is "earlier" than the first one, it will return a -1, and if they are the same, it will return 0. To clarify what "later" and "earlier" mean, let's take a look at ASCII character codes. You need to compare each character of the string, treating each of them as digits of a number. Later refers to a larger number, occurring after a smaller number. Strings will be formatted with a hyphen character to separate the two input groups.
Take a look at this example:

7-9 as an input should return 1.
7 converts to ASCII code 55, and 9 converts to ASCII code 57.
As 57 occurs numerically after 55, 9 is later than 7.

Another example:

LKzb-LKaj as an input should return -1
The ASCII code sequences for this are 76-75-122-98 and 76-75-97-106

This is a code golf challenge, and byte count is how entries will be scored.
Any input from the 95 printable ASCII characters is accepted, excluding spaces, and hyphens for anything but separating the input. In addition, strings are not guaranteed to be the same length.
Good luck!
EDIT: To be more clear, each character is to be treated like a digit in a number. In the example LKzb-LKaj, though j is later than b, z is later than a, and since it is a more significant digit, it takes precedence. A string supplied will always be at minimum 3 characters, eliminating empty strings from the scope of this problem.
EDIT: Here are some more test cases, for your help:

A-9 -> -1
11-Z -> -1
3h~J*-3h~J* -> 0
Xv-Y0 -> 1

Pyth - 11 bytes
Easy, uses ._ sign to get the sign and C to get char codes.
._-F_CMcz\-

Try it online here.
Test suite.
._               Sign of number
 -F              Fold subtraction (this finds difference of a tuple)
  _              Reverse list to get correct order of operands when subtracting
   CM            Map char, already treats strings as digits of base256 number
    c \-         Split by "-"
     z           Input


Can you cast the spell? In Magic: the Gathering, mages (known as "planeswalkers") battle each other by casting spells. Spells cost mana. Five colors of mana exist: White, Blue, Black, Red, and Green, represented as {W}, {U}, {B}, {R}, and {G}, respectively.

A spell's cost is slightly more complex. The cost can be any combination of the following:

One or more colors
One or more colorless, represented as {X}, where X is a positive integer
One or more hybrids, represented as {Y/Z}, where Y and Z are either a color (represented by one of the five letters) or colorless, represented by a positive integer

The following rules apply when attempting to cast a spell:

A color in a cost must be satisfied by one mana of that color
A colorless cost {X} may be satisfied by X mana of any color
A hybrid cost {Y/Z} may be satisfied by satisfying either Y or Z

Note that braces are not nested
Y and Z are not hybrid

Write a program or function that, given a pool of mana and a cost, prints or returns true (or some truthy value) if and only if the mana in that pool can satisfy the cost, else false (or some falsy value).

A mana pool is a non-empty string of the format:

Color1,Color2,Color3,...,Colorn-1,Colorn

A cost is a non-empty string of the format:

Cost1,Cost2,Cost3,...,Costn-1,Costn

Examples

In the format Pool Cost -> ExpectedOutput (with a space between Pool and Cost):

{R},{R},{G},{B},{R} {4},{R} -> True
{G},{G},{G},{G},{W},{W},{W} {2/W},{2/U},{2/B},{2/R},{2/G} -> False
{G},{G},{R} {R/G},{G/B},{B/R} -> True
{R},{R},{R},{G} {1},{G},{2/G}-> True
{R} {R},{R},{R},{R},{R} -> False
{W},{R},{R} {2/W},{W/B} -> True
{U},{U} {1} -> True
{W},{R},{G} {1},{2} -> True

Pyth, 55 53 52 50 bytes

FN*Fmsm?k}kG^Gvkcd\/ceKc-rz0`Hd\,#=sN)I!.-NhK1B)E0

Try it online: Demonstration or Test harness

Notice that the time and memory complexity is really bad. So the second example doesn't work. I allocates about 1.6 GB of Ram before it crashes on my machine.

Explanation

The explanation is for the 53 solution. The only difference is, that the initial parsing happens in the middle instead of the beginning.

Kc-rz0"{}"dFN*Fmsm?k}kG^Gvkcd\/ceKc-rz0`H\,#=sN)I!.-NhK1B)E0

So here's the initial parsing.

Kc-rz0`Hd
   rz0     convert input() to lowercase
  -   `H   remove all curly brackets (`H = "{}")
 c      d  split at the space
K          assign to K

So the input "{W},{R},{R} {2/W},{W/B}" gets converted into ['w,r,r', '2/w,w/b'].

m               ceK\,    map each cost d of the costs split by "," to:
 s                         the sum of
  m         cd\/           map each value k of cost split by "/" to:
    k                        k
   ? }kG                     if k in "abcdef...xyz" else
        ^Gvk                 Cartesian product with "abc...yz" of int(k) repeats

So what does this do? The cost input '2/w,w/b' gets converted into:

[['aa', 'ab', 'ac', ..., 'zx', 'zy', 'zz', 'w'], 'wb']

Every string in ['aa', 'ab', 'ac', ..., 'zx', 'zy', 'zz', 'w'] satisfies {2/W} and every char in 'wb' satisfies {w/b}.

Now we generate the Cartesian product of these lists (or strings) and see, if any combination can be produced with the mana-pool.

FN*F...              )      for N in Cartesian product of ...:
       #   )                   while 1:
        =sN                      N = sum(N)
                               this flattens N
            I!.-NhK            if not (subtract mana pool from N):
                   1             print 1 (True)
                    B            break
                      E      else:
                       0       print 0 (False)


pleTriwapt Sgpin (Triplet Swapping) Intro/Background

I was looking at a Flybuys card at Coles recently and noticed that if I took something like this:

Source, randomly found on the Internet

And swapped some words around, I'd get this:

After I finished laughing (don't judge my sense of humour please),  I said to myself: "I need a program that can generate text like that". So I devised a set of rules for substring swapping and wrote yet another CGCC challenge!

The Challenge

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

Splitting the string into chunks of three. The last triplet can possibly be shorter. (abcdefgh => [abc, def, gh])
Swap every triplet with every other triplet, leaving the last triplet in place if there is an odd amount of triplets.

The above bullet point more succinctly:

  [D]ivide the list into adjacent pairs and swap each pair ~ @FlipTack

Test Cases

Input->Output
flybuys->buyflys
Once->eOnc
Triplet->pleTrit
Code Golf->e GCodolf
TopAnswers!->AnsTops!wer
Never gonna let you down->er Nevna gon yoletownu d
I'm Sorry, I Haven't a Clue-> SoI'm, Irryven Haa C't lue
Can I please have my vegetables back?-> I Canasepleve  havegmy bleetaacks b?
You are filled with determination-> arYouille fwited eteh dnatrmiion
->

Reference Program

Some Test Cases Explained

flybuys
[fly, buy, s] (split)
[buy, fly, s] (swapped)
buyflys

Once
[Onc, e] (split)
[e, Onc] (swapped)
eOnc

Triplet
[Tri, ple, t] (split)
[ple, Tri, t](swapped)
pleTrit

Code Golf
[Cod, e G, olf] (split)
[e G, Cod, olf] (swapped)
e GCodolf

TopAnswers!
[Top, Ans, wer, s!] (split)
[Ans, Top, s!, wer] (swapped)
AnsTops!wer

Rules

Input/output can be taken/given in any reasonable and convenient format
The input will not contain newlines
Strings can be of any length, and can be empty
Input will only contain printable ASCII characters
All standard loopholes are forbidden

Scoring

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

J, 13 bytes

[:;_2|.\_3<\]

Try it online!

Example input: 'flybuys'

_3<\] Box every group of 3

┌───┬───┬─┐
│fly│buy│s│
└───┴───┴─┘

_2|. Split that into groups of 2, and reverse each one:

┌───┬───┐
│buy│fly│
├───┼───┤
│s  │   │
└───┴───┘

[:; Raze the result:

buyflys


Check if a given string is valid romaji Your program is given a string consisting entirely of lowercase letters at STDIN (or closest alternative). The program must then output a truthy or falsey value, depending on whether the input is valid romaji.

Rules:

It must be possible to divide the entire string into a sequence of kana without any leftover characters.
Each kana can be a single vowel (aeiou)
Each kana can also be a consonant p, g, z, b, d, k, s, t, n, h, m, or r followed by a vowel. For example, ka and te are valid kana, but qa is not.
The exceptions to the above rule are that zi, di, du, si, ti, and tu are not valid kana.
The following are also valid kana: n, wa, wo, ya, yu, yo, ji, vu, fu, chi, shi, tsu.
If a particular consonant is valid before an i (i.e ki, pi), the i can be replaced by a ya, yu, or yo and still be valid (i.e kya, kyu, kyo)
Exceptions to the above rule are chi and shi, for which the y has to be dropped too (i.e cha, chu, cho, sha, shu, sho)
It is also valid to double consonants if they are the first character of a kana (kka is valid but chhi is not)
Shortest answer wins. All regular loopholes are disallowed.

List of all valid kana:

Can have double consonant:

ba, bu, be, bo, bi
ga, gu, ge, go, gi
ha, hu, he, ho, hi
ka, ku, ke, ko, ki
ma, mu, me, mo, mi
na, nu, ne, no, ni
pa, pu, pe, po, pi
ra, ru, re, ro, ri
sa, su, se, so,
za, zu, ze, zo,
da,     de, do,
ta,     te, to,
wa,         wo,
ya, yu,     yo,
    fu,
    vu
                ji

Can not have double consonant:

a, i, u, e, o,
    tsu,
chi, cha, cho, chu,
shi, sha, sho, shu,
n

Test cases

Pass:

kyoto
watashi
tsunami
bunpu
yappari

Fail:

yi
chhi
zhi
kyi

Ruby, 96 149 bytes

Regex solution to match all the valid kana. Interestingly, "ecchi" is not valid according to the current rules, but perhaps it's for the best.

->s{s.gsub(/(?![dt]u)(sh|ch|([gbknhmrp])\2?y?|([zdst])\3?)?[auo]|(\g<2>)?\4?[ie]|(\g<3>)\5?e|ww?[ao]|n|tsu|([fv])\6?u|jj?i|j?y?[aou]|yy[aou]/){}==""}

Try it online! feat. Cruel Angel's Thesis


Implement t9-like functionality Your challenge today is to implement a t9-like functionality.

You will implement a function that will only have 2 parameters.
You will receive 1 phone number in a string and the content of a text file with a list of words (don't assume a specific newline style).
You can use the link https://raw.githubusercontent.com/eneko/data-repository/master/data/words.txt to test the functionality, or use /usr/share/dict/words (check A text file with a list of words [closed] for more information).

You can assume that you will always receive at least 2 numbers.

Given the number, you will read from a list of words and returns the words starting with the letters mapping to those words. This means that the input should be only numbers from 2 to 9.
You can do whatever you want if you receive invalid input.

If no match is found, you can return an empty list, null/nil or 0.

Remember that the cellphone keys are mapped to their equivalent chars:

0 and 1 are invalid
2 matches [abc]
3 matched [def]
4 matches [ghi]
5 matches [jkl]
6 matches [mno]
7 matches [pqrs]
8 matches [tuv]
and 9 matches [wxyz]

Examples:

f('52726')
//returns ["Japan","japan","Japanee","Japanese","Japanesque"...,"larbowlines"]

f('552')
//returns ["Kjeldahl","kjeldahlization","kjeldahlize"...,"Lleu","Llew"]

f('1234')
//makes demons fly out your nose or divide by 0

f('9999')
//returns ["Zyzzogeton"]

f('999999')
//returns [] or null/nil or 0

After you run your function, you can print it in any way you wish.

Rules:

Standard loopholes are INVALID
You must return something, even if it is null/nil
Javascript will return undefined if you don't return something, therefore this rule.
You cannot use or re-implement other's answers or copy my implementation.
You can assume, for Javascript, that the browser will be already opened and that the innerText/textContent of the automatic element will be passed as the 2nd parameter
For compiled languages, you cannot pass special arguments to the compiler
You can receive the file name over compiler arguments
Variables, macros, global variables, constants, non-standard classes and all the sort passing other values inside the function will be considered invalid.
In Javascript, variables without the keyword var render your code invalid
Your function will be named f
You can only and only have 2 arguments on your function
Try to keep your code under 500 seconds to run.
You don't have to worry about whitespace
You must use only ASCII printable characters.
Exceptions are languages that only use non-printable characters (APL and whitespace are 2 examples).

Scoring:

Lowest number of bytes win
Having invalid ASCII printable characters in your answer, will count as the answer being encoded in UTF-32
The exception to the encoding will make your answer be count by characters.
Only the function body counts, don't count anything else you do outside it
Bonus of -30% if you make a prediction system based on the neighborhood or most common words
Bonus of -20% in size if you only return the first 5 matches for each letter corresponding to the first number (e.g.: 245 would returns 5 words starting with 'a', 5 starting with 'b' and 5 starting with 'c').

Here is an example of an implementation, using Javascript:

function f(phone, words)
{
    var keypad=['','','abc','def','ghi','jkl','mno','pqrs','tuv','wxyz'];
    var regex='';

    for(var i=0,l=phone.length;i<l;i++)
    {
        regex+='['+keypad[phone[i]]+']';
    }

    var regexp=new RegExp('\\s('+regex+'[a-z]*)\\s','gi');

    return words.match(regexp);
}

To run it, open the list link and run, for example:

f('9999',document.getElementsByTagName('pre')[0].innerText);
//returns [" Zyzzogeton "]

This example was tested and works under Opera 12.17 64bits on Windows 7 Home Edition 64bits.

CJam, 28 bytes
q~{el{'h-_9/-D+3/}%s1$#!},p;

Takes input in the form of "<number>" [<list of words>]
Example:
"52726" ["Japan" "japan" "Japanee" "Japanese" "Japanesque" "larbowlines" "ablution" "ablutionary" "abluvion" "ably" "abmho" "Abnaki" "abnegate"]

Output:
["Japan" "japan" "Japanee" "Japanese" "Japanesque" "larbowlines"]

Not going for any bonus for now.
Try the code online here but for actual time measurements, run it on the Java compiler
Note that CJam represents empty lists like ""
To convert the raw wordlist into CJam list use the following code with the wordlist as input:
qN/p


Create a programming language interpreter Task:

You must create an interpreter that can parse snippets of a programming language. The language does not need to be complex, but it must include the following syntactical elements:

Ability to assign and read variables (could be as simple as a-z being premade variables)
If statements (elseif and else are not required)
Loops (counting to an arbitrary number, user access to counter is not required)
Simple math with variables (addition, subtraction, multiplication, division, greater/less than, equals)
Print statements

Rules:

You may not copy the syntax of another popular language.
You need to write your own interpreter, not modification of another interpreter.
You can write your interpreter in any language.
Write a 99-bottles-of-beer example program in your language (see here)
This is a popularity-contest, so the most upvoted answer wins.

DogeScript

The 99 bottles of beer program:

many amaze 99 time

such scare bottles-of-beer
such scream on-the-wall
many despair 13 time

such fail take-one-down-pass-it-around

wow

so amaze
so scare
so scream
so despair!

so amaze
so scare
so despair!

much amaze

so fail
so despair!

so amaze
so scare
so scream

so despair!
so despair!

very amaze

wow

The PHP interpreter:

<?php
$input=fopen('php://stdin', 'r');

//pre-process input
$input=preg_replace("/ +/", " ", $input); //replace any multiple spaces by a single space

//split into instructions by newlines
$instructions=explode("\n", $input);

$loopstartpoint= -1;
$variables=array();
$activevariable="";
for($instrpointer=0; $instrpointer<count($instructions); $instrpointer++)
{
    $tokens=explode(" ", $instructions[$instrpointer]);
    switch($tokens[0])
    {
        case "wow":
            if($loopstartpoint<0)
            {
                $loopstartpoint=$instrpointer+1;
            }
            else
            {
                if($variables[ $activevariable ])
                {
                    $instrpointer=$loopstartpoint;
                }
                else
                {
                    $loopstartpoint= -1;
                }
            }
            break;
        case "so":
            if(substr($tokens[1], -1)=="!")
            {
                echo chr($variables[ substr($tokens[1], 0, -1) ]);
            }
            else
            {
                echo $variables[ $tokens[1] ];
                echo " ";
            }
            break;
        case "very":
            $activevariable=$tokens[1];
            break;
        case "much":
            if(!isset($variables[ $tokens[1] ]))
                $variables[ $tokens[1] ]=0;
            if(count($tokens)==2)
            {
                $variables[ $tokens[1] ]--;
            }
            else
            {
                for($loop=0;$loop<$tokens[2];$loop++)
                {
                    $variables[ $tokens[1] ]--;
                }
            }
            $activevariable=$tokens[1];
            break;
        case "many":
            if(!isset($variables[ $tokens[1] ]))
                $variables[ $tokens[1] ]=0;
            if(count($tokens)==2)
            {
                $variables[ $tokens[1] ]++;
            }
            else
            {
                for($loop=0;$loop<$tokens[2];$loop++)
                {
                    $variables[ $tokens[1] ]++;
                }
            }
            $activevariable=$tokens[1];
            break;
        case "such":
            $variables[ $tokens[1] ]=$tokens[2];
            $activevariable=$tokens[1];
            break;
    }
}
?>

The syntax as it currently stands:

wow - start and end loops, end of loop checks if active variable is 0 and loops if not
so without ! - print variable's value
so with ! - print variable's ASCII character
much - decrement this variable
many - increment this variable
such - set variable
very - make variable active
x time - does previous statement x times

Variables are initially 0.

Try it here.
Any suggestions for improvement are welcome.


Work out \$x^y\$ using only addition and subtraction The challenge is to implement a function or program that takes two numbers, \$x\$ and \$y\$ and return the result of \$x^y\$.

The program cannot use any other mathematical operation other than \$+\$ or \$-\$, so no multiplication or division. Functions built into languages are also not allowed.

The code in the least amount of bytes wins.

APL (Dyalog Unicode), 7 bytesSBCS

Anonymous tacit infix function. y is left argument and x is right argument.

(+/⍴)/⍴

Try it online!

⍴ cyclically reshape (gives y copies of x)

(…)/ reduce by the following function:

 ⍴ cyclically reshape to left argument copies of right argument

 +/ sum


Tricky Median Question Given n points, choose a point in the given list such that the sum of distances to this point is minimum ,compared to all others.

Distance is measured in the following manner.

For a point (x,y) all 8 adjacent points have distance 1.

(x+1,y)(x+1,y+1),(x+1,y-1),(x,y+1),(x,y-1),(x-1,y)(x-1,y+1),(x-1,y-1)

EDIT

More clearer explanation.

A function foo is defined as

foo(point_a,point_b) = max(abs(point_a.x - point_b.x),abs(point_a.y - point_b.y))

Find a point x such that sum([foo(x,y) for y in list_of_points]) is minimum.

Example

Input:

0 1
2 5
3 1
4 0

Output

3 1

Eg:
Distance between (4,5) and 6,7) is 2.

This can be done in O(n^2) time, by checking the sum of each pair.
Is there any better algorithm to do it?

I can imagine a scheme better than O(n^2), at least in the common case.

Build a quadtree out of your input points.  For each node in the tree, compute the number and average position of the points within that node.  Then for each point, you can use the quadtree to compute its distance to all other points in less than O(n) time.  If you're computing the distance from a point p to a distant quadtree node v, and v doesn't overlap the 45 degree diagonals from p, then the total distance from p to all the points in v is easy to compute (for v which are more horizontally than vertically separated from p, it is just v.num_points * |p.x - v.average.x|, and similarly using y coordinates if v is predominately vertically seperated).  If v overlaps one of the 45 degree diagonals, recurse on its components.

That should beat O(n^2), at least when you can find a balanced quadtree to represent your points.


Smallest positive integer which is coprime to the last two predecessors and has not yet appeared; a(1)=1, a(2)=2 Definition

Two integers are coprime if they share no positive common divisors other than 1.
a(1) = 1
a(2) = 2
a(n) is the smallest positive integer which is coprime to the a(n-1) and a(n-2) and has not yet appeared, for integer n >= 3.

Task

Given positive integer n, output/print a(n).

Example

a(11) = 6 because 6 is coprime with the last two predecessors (namely, 11 and 13) and 6 has not appeared before.

Notes

Note that the sequence is not ascending, meaning that an element can be smaller than its predecessor.

Specs

You must use 1-indexed.

Testcases

n      a(n)
1      1
2      2
3      3
4      5
5      4
6      7
7      9
8      8
9      11
10     13
11     6
12     17
13     19
14     10
15     21
16     23
17     16
18     15
19     29
20     14
100    139
1000   1355
10000  13387
100000 133361

Scoring

Since coprime means that the two numbers share only one divisor (1), and 1 is a small number, your code should be as small as possible in terms of byte-count.

References

OEIS A084937

Python 3.5, 160 141 126 124 121 109 bytes

This is a simple implementation of the sequence's definition. Golfing suggestions welcome.

Edit: -17 bytes thanks to Leaky Nun. -9 bytes thanks to Peter Taylor. -6 bytes thanks to Sp3000 and switching to Python 3.5.

import math;f=lambda n,r=[2,1],c=3:n<2and r[1]or(c in r)+math.gcd(c,r[0]*r[1])<2and f(n-1,[c]+r)or f(n,r,c+1)

Ungolfing:

import math
def f(n, r=[2,1], c=3):
    if n<2:
        return r[1]
    elif (c in r) + math.gcd(c,r[0]*r[1]) < 2:
        return f(n-1, [c]+r)
    else:
        return f(n, r, c+1)


I reverse the source code, you reverse the input! Yet another blatant rip-off of a rip-off of a rip-off. Go upvote those!

Your task, if you wish to accept it, is to write a program/function that outputs/returns its string input/argument. The tricky part is that if I reverse your source code, the output must be reversed too.

For simplicity, you can assume that the input is always a single line string containing only ASCII letters (a-z), digits (0-9) and spaces.

Should support an input of at least 8 characters long (longer than 8 is not necessary).

Behaviour for empty input is undefined.

Examples

Let's say your source code is ABC and its input is xyz. If I write CBA instead and run it, the output must be zyx.

Let's say your source code is ABC and its input is 96. If I write CBA instead and run it, the output must be 69.

A single leading or trailing white-space is acceptable as long as it is consistent in both normal and reversed outputs.

JavaScript, 32 bytes

s=>s//``nioj.)(esrever.]s...[>=s

Reversed:
s=>[...s].reverse().join``//s>=s


Simple predictive keyboard CG In honor of recent news of Google developing a keyboard for iPhone...

Your input (for simplicity, all input is case sensitive):

Location of standard dictionary file. File format is 1 valid word per line; in alphabetical order. Example file:

apple
banana
citrus
domino
durian
orange
tuna
zabc

Location of personal dictionary file (initially, may be empty or non-existant). Format is 1 word per line, comma separated by count of times that word was used. Example file:

Stackoverflow,15
StackExchange,11
Meta,13
TFGITW,2
VTC,10

A stream of words on standard input (for simplicity, newline separated), in the following format on each line: "Typed_word,intended_word".

You need to emulate a predictive keyboard, as follows. For every line in the stream of words:

Process the typed word character by character
After 3rd character, generate the 5 most-used words that start with the currently-seen substring

"5" is a hard-coded constant, but my example below uses "2" for simplicity. "most-used" are picked as first words when words are sorted in the order of counting; alphabetic order within same counts.

The rules for most-used words are: the word from the standard dictionary is assumed to have the used count of 20 (that's a hard-coded constant, but my example below uses "2" for simplicity). The word from personal dictionary has a used count of whatever number the dictionary file has.
If one of 5 words matches intended word, print the success: "MATCH:$substring,$intended_word" and stop
If typed word is finished and matches intended_word, print it: "FULLWORD:$typed_word,$intended_word" and stop
If typed word is finished, but none of teh matches or the word match intended_word, print ERROR message including both typed and intended word: "MISMATCH:$typed_word,$intended_word"
Add the intended word to the personal dictionary if missing from it; or increment its usage count in personal dictionary if already present

Answers should be genuine working code - no gotchas/loopholes, no edge cases like super-small input.

SAMPLE RUN

(I'm going to change the constants to 2 guesses (instead of 5) and main dictionary words weigh as 2 user-usages instead of 20)

Standard Dictionary:

abacus
abacii
abandon
abandoned
abandonment

User dictionary

EMPTY

INPUT

abanana,abanana
abanana,abanana
abanana,abanana
abandonmint,abandonment
cat,cad

OUTPUT

FULLWORD:abanana,abanana #after this, add "abanana,1" to custom dictionary
MATCH:abana,abanana
   # NOTE: your code should have matched "abandon,abandoned" till seeing "abana"
   # change custom dict count for abanana to 2
MATCH:aban,abanana #By now, aban matches "abanana,abandon"
MATCH:abandonm,abandonment
MISMATCH:cat,cad # Add cad to custom dictionary

NOTE: someone asked to be able to live with no files. I'm fine with that, the simplest spec seems to be to pass all 3 inputs on STDIN, separated by empty line between the inputs.

Python 3.9, 350 bytes
import sys
[s,p,x]=sys.stdin.read().split("\n\n")
p,x=[[l.split(',')for l in d.split("\n")]for d in[p,x]]
s={k:20 for k in s.split("\n")}
p={k:int(v)for k,v in p}
for t,i in x:b=s|p;b={k:b[k]for k in b if k[:4]==t[:4]};b=sorted(b,key=b.get);p[i]=p.get(i,0)+1;print((f"MATCH:{t[:4]},"if i in b[:5]else f"FULLWORD:{t},"if t==i else f"MISMATCH:{t},")+i)

Try it online! (Uses {**a,**b} instead of a|b to merge dictionaries)
The I/O formats are restrictive, but this still makes for a simple and fun challenge.
import sys
#s is the standard dictionary, p is the personal dictionary, and x is the input
#They are separated by a blank line
[s,p,x]=sys.stdin.read().split("\n\n")
#Turn both p and x into lists (separated by \n) of 2-element lists (separated by commas)
p,x=[[l.split(',')for l in d.split("\n")]for d in[p,x]]
#Split s on \n to get list of words, then map to 20, the default no. of occurrences
s={k:20 for k in s.split("\n")}
#Turn p into a dictionary, and make the values ints
p={k:int(v)for k,v in p}
#Iterate over each typed word t and intended word i in the input
for t,i in x:
  #Merge the personal and standard dictionaries and store in b
  b=s|p
  #Filter the words who start with the first 4 characters of t (typed word)
  b={k:b[k]for k in b if k[:4]==t[:4]}
  #b now contains words from the dictionary, sorted by number of occurrences
  b=sorted(b,key=b.get)
  #Increment number of occurrences of i in personal dictionary, or set to 1 if it doesn't exist yet
  p[i]=p.get(i,0)+1
  #Print the corresponding message
  print((f"MATCH:{t[:4]},"if i in b[:5]else f"FULLWORD:{t},"if t==i else f"MISMATCH:{t},")+i)


Broken Path Detection Challenge

Given a plot with broken paths, return the plot with all paths connected in the minimum number of changes.

Explanation

This problem deals with graphs on the Cartesian plane. Every node has 8 possible edges, extending vertically, horizontally, or diagonally. Each direction is represented by a number 0-7 as follows:

        0
     7     1
  6     X     2
     5     3
        4

In other terms:

0 = North
1 = Northeast
2 = East
3 = Southeast
4 = South
5 = Southwest
6 = West
7 = Northwest

A "broken path" occurs when one node has an edge that would reach another node, but the node it reaches toward does not have the corresponding path to reach it. For example, assume we have nodes A, B, C, and D laid out as:

AB
CD

If node A has the path 2 and all the other nodes have no paths, then there is a broken path between nodes A and B. This can be resolved in one of two ways:

Removing path 2 from A
Adding path 6 to B

In this case, it does not matter which way you choose to resolve the conflict, because either way results in 1 node being changed.

This first example can be illustrated as follows (* represents nodes):

Original:
 *- *

 *  *

First method:
 *  *

 *  *

Second method:
 *--*

 *  *

If node A has path 3, B has path 4, C has path 2, and D has no paths, the paths from A to D, B to D, and C to D are all broken. This can be resolved in one of two ways:

Removing path 3 from A, 4 from B, and 2 from C
Adding paths 6, 7, and 0 to D

In this case, adding to node D is the optimal choice, because it results in 1 node being changed rather than 3. It does not matter how many paths get changed when you change a node; the optimal method is determined by how many nodes get changed.

This example can be illustrated as:

Original:
 *  *
  \ |

 *- *

Suboptimal method:
 *  *

 *  *

Optimal method:
 *  *
  \ |
   \|
 *--*

Input

A 2D matrix of bytes, where each bit represents whether that path is present in the node. 7 represents the most significant bit, and 0 the least significant; in other words, the bits are given in the order 76543210.

For example, the first scenario given above would be:

0b00000010 0b00000000
0b00000000 0b00000000

The second scenario given above would be:

0b00000100 0b00001000
0b00000010 0b00000000

You may take in these values as strings in the base of your choice, or integral types with the width of your choice (e.g. if your language supports a byte or char type, you may still use int if you so choose), but include your choice in your answer.

Output

You should either write a function that returns the corrected map or a program that prints it. Your output format should be the same as your input format.

Test Cases

These are just one example of correct output; valid output with the same number of values changed is also accepted.

[[0x04, 0x00], [0x00, 0x00]] -> [[0x04, 0x40], [0x00, 0x00]]

[[0x08, 0x10], [0x04, 0x00]] -> [[0x08, 0x10], [0x04, 0xC1]]

[[0x04, 0x10, 0x00],            [[0x10, 0x10, 0x00],
 [0x01, 0x80, 0x10],         ->  [0x01, 0x09, 0x10],
 [0x00, 0x00, 0x81]]             [0x00, 0x00, 0x81]]

                          Or -> [[0x18, 0x10, 0x00],
                                 [0x01, 0x89, 0x10],
                                 [0x00, 0x00, 0x81]]

The first two test cases are illustrated above. The third test case can be illustrated as:

Original:
 *- *  *
    |
 | \
 *  *  *
       |
      \|
 *  *  *

Solution:
 *  *  *
 |  |
 |  |
 *  *  *
     \ |
      \|
 *  *  *

Another solution:
 *  *  *
 |\ |
 | \|
 *  *  *
     \ |
      \|
 *  *  *

This is code-golf, so the fewest bytes in each language wins.

Haskell, 655 bytes

u%w=u!!w
r=zip[-1,0,1,1,1,0,-1,-1][-1,-1,-1,0,1,1,1,0]
g _[]_= -1
g i(e:l)x|x==e=i|1>0=g(i+1)l x
l?x=g 0 l x
d _[]_ _=[]
d i(e:l)t v|i==t=v:l|1>0=e:d(i+1)l t v
c=d 0
f n|all(==0).concat.q$n=n|1>0=f$foldr(\p b->s b[k,m]p)n$k!m where
 h=length n-1
 e=mapM(\w->[0..w])[h,h]
 i!j=[[x,y]|[x,y]<-e,x>i-2&&x<i+2&&y>j-2&&y<j+2]
 q o=[[sum[1|[x,y]<-w!l,let
  u=(x-w,y-l)
  p=(w-x,l-y)in u/=p&&('1'==(o%w%l)%(r?u))/=('1'==(o%x%y)%(r?p))]|l<-[0..h]]|w<-[0..h]]
 v[x,y][a,b]|q n%x%y>q n%a%b=[x,y]|1>0=[a,b]
 [k,m]=foldr1 v e
 s w[x,y][a,b]|x==a&&y==b=w|'1'==w%x%y%(r?(a-x,b-y))=z '0'|'1'==w%a%b%(r?(x-a,y-b))=z '1'|1>0=w where z u=c w x$c(w%x)y$c(w%x%y)(r?(a-x,b-y))u

Man... 655 is a lot. I'm sure this isn't the best approach but since no one's answered this challenge yet I figured I would throw something at it.

Input is a list of lists of strings, viz. [[String]] or, equivalently, [[[Char]]]. The string format is "76543210", where the string is a '0' or a '1' in any given position based on whether or not the node points in that corresponding direction. This should conform with the spec:

  7 represents the most significant bit, and 0 the least significant; in other words, the bits are given in the order 76543210.

But the examples below that seem to contradict it, instead doing something more like ?7654321, so I'm not sure.

Test suite:

main :: IO ()
main = print $ f
    [ ["00000100", "00010000", "00000000"]
    , ["00000001", "10000000", "00010000"]
    , ["00000000", "00000000", "10000001"]
    ]

(That's the last test case in the spec^)


Extrude the faces of a cube symmetrically along XYZ Sandbox

For the purposes of the current task, a cube of unit length is rendered in oblique projection with ASCII symbols as follows:

  +-----+
 /     /|
+-----+ |
|     | +
|     |/
+-----+

+ for the vertices.
- for the X edges. The unit length along X is represented by five - between two vertices.
| for the Y edges. The unit length along Y is represented by two | between two vertices.
/ for the Z edges. The unit length along Z is represented by one / between two vertices.
Vertices are only drawn where all the three planes intersect.
Edges are only drawn where exactly two planes intersect.

When a unit face is extruded, it is offset by a unit length from its original position and four new edges are created for each direction (positive and negative).

You can think of the extrusion as of drawing the axes of a 3D Cartesian coordinate system where each axis is represented as a cuboid with cross section 1x1 and length n away from (0,0,0)

Extruded by 1 along X:

  +-----------------+
 /                 /|
+-----------------+ |
|                 | +
|                 |/
+-----------------+

Task

Given three numbers for the XYZ axes, extrude the faces of a unit cube symmetrically by the indicated amounts and render the result with the ASCII symbols as specified above.

Input

x, y, z – non-negative numbers - extrusion lengths for the respective axes. 0 means no extrusion.
The input can be three numbers, a list of three numbers, a triple, a string or anything that’s convenient for you.

Output

The ASCII drawing of the cube after extrusion. Leading and trailing wihtespaces are allowed.

Test cases

X Y Z
0 0 0

  +-----+
 /     /|
+-----+ |
|     | +
|     |/
+-----+

1 0 0

  +-----------------+
 /                 /|
+-----------------+ |
|                 | +
|                 |/
+-----------------+

0 0 1
        +-----+
       /     /|
      /     / |
     /     /  +
    /     /  /
   /     /  /
  +-----+  /
  |     | /
  |     |/
  +-----+

1 1 0

        +-----+
       /     /|
      +-----+ |
  +---|     | +-----+
 /    |     |/     /|
+-----+     +-----+ |
|                 | +
|                 |/
+-----+     +-----+
      |     | +
      |     |/
      +-----+

2 0 1

                +-----+
               /     /|
  +-----------+     +-----------+
 /                             /|
+-----------+     +-----------+ |
|          /     /|           | +
|         +-----+ |           |/
+---------|     | +-----------+
          |     |/
          +-----+

1 1 1

        +-----+
       /     /|-+
      +-----+ |/|
  +---|     | +-----+
 /    |     |/     /|
+-----+-----+-----+ |
|    /     /|     | +
|   +-----+ |     |/
+---|     | +-----+
    |     |/| +
    +-----+ |/
      +-----+

Winning criteria

The shortest solution in bytes in every language wins. Please add a short description of the method used and your code.

JavaScript (ES6),  525 ... 475 471  459 bytes
Saved 13 bytes thanks to @Neil
Takes input as an array [X,Y,Z]. Returns a matrix of characters.
a=>([X,Y,Z]=a,m=[],W=X*6+Z*2,'1uol9h824lsqpq17de52u1okgnv21dnjaww111qmhx1gxf4m50xg6pb42kzijq21xyh34t0h2gueq0qznnza2rrimsg3bkrxfh3yrh0em').replace(/.{7}/g,s=>[[c,x,A,y,B,w,C,h,D,t]=parseInt(s,36)+s,Y*W,Z,X,Y|!W,Z*X,X*Y*!Z,X*Z*!Y,Y*Z*!X][c]&&(g=H=>V<h&&((m[r=y-(3-B)*p+(t>1?H-V:V)+Y*3+Z*2]=m[r]||Array(W*2+9).fill` `)[x-2*(3-A)*p+(t>1?V:H-V*t)+W]=` ${c>5?'  + ':t>1?'|-':'-|'}+/+`[(H%~-w?0:+t?4:2)|!(V%~-h)],g(++H<w?H:!++V)))(V=0,p=a[c%3],w-=-3*C*p,h-=-D*p))&&m

Try it online!
How?
Drawing steps
The output consists of 15 sides, drawn in a specific order.

Implementation
The drawing function is \$g\$. It works with the following parameters:

\$(x, y)\$: where to start drawing
\$w\$: width
\$h\$: height
\$t\$: type of side

The vertices are always drawn. Depending on the value of another parameter \$c\$, the edges are either drawn or erased.
If \$t=0\$, the function draws a front side:
...........      ...........
..+-----+..      ..+     +..
..|     |..  or  ..       ..
..|     |..      ..       ..
..+-----+..      ..+     +..
...........      ...........

If \$t=1\$, it draws a top side:
...........      ...........
...+-----+.      ...+     +.
../     /..  or  ..       ..
.+-----+...      .+     +...
...........      ...........

If \$t=2\$, it draws a right side:
......+....      ......+....
...../|....      .....  ....
....+ |....  or  ....+  ....
....| +....      ....  +....
....|/.....      ....  .....
....+......      ....+......

The coordinates \$(x,y)\$ and the size \$(w,h)\$ of each side either have a constant value or depend on exactly one of the input variables: \$X\$, \$Y\$ or \$Z\$. Besides, each side is drawn if and only if a specific condition is met.
Both the input variable to use and the condition to check are identified with the parameter \$c \in[1..8]\$.
To summarize, a side is fully described with:
$$\begin{cases}
c\\
t\\
x=o_x+m_x\times P\\
y=o_y+m_y\times P\\
w=o_w+m_w\times P\\
h=o_h+m_h\times P
\end{cases}
$$
where \$P\$ is the input variable deduced from \$c\$.
Therefore, we need to store the following 10 parameters for each side:
$$[c, o_x, m_x, o_y, m_y, o_w, m_w, o_h, m_h, t]$$
Below are the parameters of the 15 sides that need to be drawn:
$$\begin{array}{|c|c|}
\hline
\text{side} & c & o_x & m_x & o_y & m_y & o_w & m_w & o_h & m_h & t\\
\hline
0 & 4 & 0 & 0 & 2 & -3 & 7 & 0 & 4 & 6 & 0\\
1 & 4 & 6 & 0 & 2 & -3 & 4 & 6 & 3 & 0 & 2\\
2 & 2 & 6 & -2 & 2 & 2 & 4 & 0 & 3 & 4 & 2\\
3 & 3 & 6 & 6 & 2 & 0 & 4 & 0 & 3 & 0 & 2\\
4 & 3 & 0 & -6 & 2 & 0 & 7 & 12 & 4 & 0 & 0\\
5 & 2 & 2 & 2 & 0 & -2 & 7 & 0 & 3 & 4 & 1\\
6 & 3 & 2 & -6 & 0 & 0 & 7 & 12 & 3 & 0 & 1\\
7 & 2 & 0 & -2 & 2 & 2 & 7 & 0 & 4 & 0 & 0\\
8 & 5 & 6 & -2 & 2 & 2 & 4 & 0 & 1 & 2 & 2\\
9 & 4 & 2 & 0 & 0 & -3 & 7 & 0 & 3 & 0 & 1\\
10 & 1 & 0 & 0 & 2 & -3 & 7 & 0 & 1 & 3 & 0\\
11 & 1 & 6 & 0 & 2 & -3 & 1 & 3 & 3 & 0 & 2\\
12 & 6 & 0 & 0 & 2 & 0 & 7 & 0 & 4 & 0 & 0\\
13 & 7 & 2 & 0 & 0 & 0 & 7 & 0 & 3 & 0 & 1\\
14 & 8 & 6 & 0 & 2 & 0 & 4 & 0 & 3 & 0 & 2\\
\hline
\end{array}$$
We force all values into the range \$[0..9]\$ by applying the following operations:
$$m_x\gets (m_x+6)/2\\
m_y\gets m_y+3\\
m_w\gets m_w/3$$
It results in 15 numbers of exactly 10 decimal digits, which are stored as 15 groups of 7 digits in base 36.
For instance, the first side is encoded as 4032070460 and stored as 1uol9h8.


Hiding elements with CSS only In the following markup without changing it or using JS, implement the behavior to show only the ul element of div which name is clicked in the first ul (before div). Name is content of li in top ul and it matches the content of the first li in ul you want to show. Elements that have {content} are just fillers and have no meaning for problem.

Favourite dishes

Breakfasts

Dinners

Suppers

Breakfasts

{Breakfast 1}

{Breakfast 2}

{Breakfast 3}

Dinners

{Dinner 1}

{Dinner 2}

{Dinner 3}

Dinners

{Supper 1}

{Supper 2}

{Supper 3}

Favourites

{Favourite 1}

{Favourite 2}

{Favourite 3}

This problem really has the solution and was very interesting for me, so I decided to post it here even if it's not very practical.
Hint: you have to use :target pseudo-class.

I think your hint gave too much away:

div>ul:target{
   display: block;
}
div>ul{
   display: none;
}


Output some reserved words For a computer language, a reserved word is a word that cannot be used as an identifier, such as the name of a variable, function, or label. For other computer languages, keywords can be considered as the set of the language instructions.
Challenge
Using your language of choice, write a code in the chosen language that given a number between one and ten, 1<=n<=10, outputs any n reserved words (keywords) of the chosen language.
Specifics

If the chosen language is case sensitive the outputted keywords must be also.
If the chosen language is not case sensitive the outputted keywords can be in any case.
If the chosen language has less than 10 keywords saying p, the code must output all the reserved words for any n between p and 10.
If possible specify in the answer whether you consider operators as keywords or not.

Possible samples for Java (JDK10)

n=1 --> true
n=3 --> try new interface
n=4 --> continue this long break

Possible samples for ><>

n=1 --> >
n=3 --> > < ^
n=4 --> > < \ /

Possible samples for Brain-Flak

n=1 --> (
n=3 --> ( ) [ ]
n=9 --> ( ) [ ] { } < >

Rules

The input and output can be given in any convenient format.
No need to handle invalid input values, valid inputs are: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10.
Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
If possible, please include a link to an on-line testing environment so other people can try out your code!
Standard loopholes are forbidden.
This is code-golf so all usual golfing rules apply, and the shortest code (in bytes) wins.

APL (Dyalog Unicode), 9 bytesSBCS

Full program. Prompts stdin for n (actually works for the range 0–29). APL keywords are single character symbols, so this prints n symbols to stdout.

⎕↑156↓⎕AV

Try it online!

⎕AV the Atomic Vector (i.e. the character set)

156↓ drop the first 156 elements

⎕↑ prompt for n and take that many elements from the above


Implement SKI combinator calculus This challenge is to golf an implementation of SKI formal combinator calculus.

Definition

Terms

S, K, and I are terms.

If x and y are terms then (xy) is a term.

Evaluation

The following three steps will be repeated until none of them apply.
In these, x, y, and z must be terms.

(Ix) will be replaced by x

((Kx)y) will be replaced by x

(((Sx)y)z) will be replaced by ((xz)(yz))

Input

A string or array, you do not have to parse the strings in the program.

The input is assumed to be a term.

If the simplification does not terminate, the program should not terminate.

Examples

(((SI)I)K) should evaluate to (KK) ((((SI)I)K) > ((IK)(IK)) > (K(IK)) > (KK))

The evaluation order is up to you.

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

Wolfram Language, 63 bytes

#//.{{I,x_}->x,{{K,x_},y_}->x,{{{S,x_},y_},z_}->{{x,z},{y,z}}}&

Try it online!

God, I love pattern matching in Wolfram Language. Represents (xy) as {x,y} (a list of two elements).

Alternatively, if we represent (xy) with x>y, we can do it in 55 bytes.

#//.{I>x_->x,(K>x_)>y_->x,((S>x_)>y_)>z_->(x>z)>(y>z)}&

Try it online!


Determine sets of associatively equivalent permutations of commutative operations There are many types of binary operations, which can be categorized by their associative properties and their commutative properties.

A binary operation () is associative if the order of operations between operands does not affect the result — i.e. if (a(bc)) = ((ab)c).
A binary operation () is commutative if the order of two operands within one operation does not affect the result — i.e. if (ab) = (ba).

There are operations like addition and multiplication that are both associative and commutative, and operations like subtraction and division that are neither associative nor commutative.

There are also operations — such as the group composition operator — that are associative but not commutative.

But then there are operations that are commutative but not associative. These are more rare and not analyzed as much mathematically, but they occur. For example, rounded multiplication is such an operation. If you round a calculation to the nearest tenth after every multiplication, you can get anomalies like (6.8 × 5.7) × 2.9 = 112.5 while 6.8 × (5.7 × 2.9) = 112.2.

Let a permutation of the operands P in an operation tree (such as ((x(xx))((x(xx))x))) be associatively equivalent to another permutation Q, if the operands in P can be rearranged by the commutative property to form an operation tree identical to the original.

For example, permutations (a(b(c(de)))) and (a(b(c(ed)))) of the operation tree (x(x(x(xx)))) are equivalent, because d commutes with e. However, (a(b(c(de)))) and (a(b(d(ce)))) are not equivalent, because (c(de)) is not equal to (d(ce)).

A more complex example might be (((ab)c)(d(ef))) and (((ef)d)(c(ba))). Step-by-step, the two of these can be shown to be equivalent as follows:

(((ab)c)(d(ef))) = (((ba)c)(d(ef)))     since    a    commutes with    b
(((ba)c)(d(ef))) = (((ba)c)((ef)d))     since  (ef)   commutes with    d
(((ba)c)((ef)d)) = ((c(ba))((ef)d))     since  (ba)   commutes with    c
((c(ba))((ef)d)) = (((ef)d)(c(ba)))     since (c(ba)) commutes with ((ef)d)

Permutations of different operation trees are not comparable. (a(b(c(de)))) and ((((ab)c)d)e) are neither associatively equivalent nor associatively distinct, because their operation trees are different.

Your task is to build a program that will find all the associatively equivalent permutations of the operands of a given operation tree.

Your program will take input in the form given above, with brackets enclosing juxtaposed operators. The operands will always be lowercase letters, in alphabetical order starting from a, and will contain a maximum of 26 letters.

Your program will output a series of permutations of the letters, without the brackets, representing all of the permutations that are associatively equivalent with the original permutation.

For example, if you are given an input of:

((ab)(cd))

Then your program will output:

abcd
abdc
bacd
badc
cdab
cdba
dcab
dcba

Your program must be accompanied by a description of its algorithm, and a proof of its asymptotic runtime with respect to the number of operands in the operation tree. The program with the lowest asymptotic runtime in this manner wins.

Every parenthesis has in it two elements, either a terminal symbol, or another parenthesis. These two elements have two possible permutations, ab and ba.

This means that the expression forms a binary tree, and every node inside the tree has two possible permutations. So the total output is always 2n where n is the number of parenthesis pairs. This means that an asymptotical algorithm will always do this amount of work.

For this optimal algorithm we will parse the expression, then recursively generate possibilities, 2 for each parenthesis pair. As seen in the paragraph above, this is optimal.

def parse(inp):
    c = inp.pop(0)
    while c == ")": c = inp.pop(0)

    if c == "(":
        return [parse(inp), parse(inp)]

    return c

def possibs(tree):
    if len(tree) == 2:
        for left_possib in possibs(tree[0]):
            for right_possib in possibs(tree[1]):
                yield left_possib + right_possib
                yield right_possib + left_possib
    else:
        yield tree

tree = parse(list("((ab)(cd))"))

for possib in possibs(tree):
    print(possib)


Multiply Two Integer Polynomials Your task is to take two single-variable integer polynomial expressions and multiply them into their unsimplified first-term-major left-to-right expansion (A.K.A. FOIL in the case of binomials). Do not combine like terms or reorder the result. To be more explicit about the expansion, multiply the first term in the first expression by each term in the second, in order, and continue in the first expression until all terms have been multiplied by all other terms. Expressions will be given in a simplified LaTeX variant.

Each expression will be a sequence of terms separated by + (with exactly one space on each side) Each term will conform to the following regular expression: (PCRE notation)

-?\d+x\^\d+

In plain English, the term is an optional leading - followed by one or more digits followed by x and a nonnegative integer power (with ^)

An example of a full expression:

6x^3 + 1337x^2 + -4x^1 + 2x^0

When plugged into LaTeX, you get \$6x^3 + 1337x^2 + -4x^1 + 2x^0\$

The output should also conform to this format.

Since brackets do not surround exponents in this format, LaTeX will actually render multi-digit exponents incorrectly. (e.g. 4x^3 + -2x^14 + 54x^28 + -4x^5 renders as \$4x^3 + -2x^14 + 54x^28 + -4x^5\$) You do not need to account for this and you should not include the brackets in your output.

Example Test Cases

5x^4
3x^23

15x^27

6x^2 + 7x^1 + -2x^0
1x^2 + -2x^3

6x^4 + -12x^5 + 7x^3 + -14x^4 + -2x^2 + 4x^3

3x^1 + 5x^2 + 2x^4 + 3x^0
3x^0

9x^1 + 15x^2 + 6x^4 + 9x^0

4x^3 + -2x^14 + 54x^28 + -4x^5
-0x^7

0x^10 + 0x^21 + 0x^35 + 0x^12

4x^3 + -2x^4 + 0x^255 + -4x^5
-3x^4 + 2x^2

-12x^7 + 8x^5 + 6x^8 + -4x^6 + 0x^259 + 0x^257 + 12x^9 + -8x^7

Rules and Assumptions

You may assume that all inputs conform to this exact format. Behavior for any other format is undefined for the purposes of this challenge.

It should be noted that any method of taking in the two polynomials is valid, provided that both are read in as strings conforming to the above format.

The order of the polynomials matters due to the expected order of the product expansion.
You must support input coefficients between \$-128\$ and \$127\$ and input exponents up to \$255\$.

Output coefficents between \$-16,256\$ and \$16,384\$ and exponents up to \$510\$ must therefore be supported.

You may assume each input polynomial contains no more than 16 terms

Therefore you must (at minimum) support up to 256 terms in the output

Terms with zero coefficients should be left as is, with exponents being properly combined
Negative zero is allowed in the input, but is indistinguishable from positive zero semantically. Always output positive zero. Do not omit zero terms.

Happy Golfing! Good luck!

R, 159 153 148 bytes

function(P,Q,a=h(P),b=h(Q))paste0(b[1,]%o%a[1,],"x^",outer(b,a,"+")[2,,2,],collapse=" + ")
h=function(s,`/`=strsplit)sapply(el(s/" . ")/"x.",strtoi)

Try it online!

I really wanted to use outer, so there's almost surely a more efficient approach.


Counting from 1 to an Integer… in Binary Intro:

I remember, when I was a kid, I would get a calculator and keep on pressing the + button, and see how high I could count. Now, I like to program, and I'm developing for iOS.

Counting is a fundamental skill for both humans and computers alike to do. Without it, the rest of math can't be done. It's done simply by starting at 1 and repetitively adding 1 to it.

The challenge:

This is but a simple challenge. What I would like your program to do is print from 1 to whatever Integer it takes in. However, I'll throw a twist in it, since decimal counting is kinda boring:

The counting cannot be in base 10, it has to show itself counting in binary.

So, to count to 5, using 32-bit integers, it would look like this:

0000 0000 0000 0000 0000 0000 0000 0001 ..... 1
0000 0000 0000 0000 0000 0000 0000 0010 ..... 2
0000 0000 0000 0000 0000 0000 0000 0011 ..... 3
0000 0000 0000 0000 0000 0000 0000 0100 ..... 4
0000 0000 0000 0000 0000 0000 0000 0101 ..... 5

It's a computer. They know binary best. Your input can be either a 32-bit or 64-bit integer. It is truly up to you. However, if you use 32-bit integers, your output must be 32-bit integers in binary, and if you use 64-bit integers, your output must be 64-bit integers in binary.

Sample input:

a 32-bit integer, 5

Sample output:

0000 0000 0000 0000 0000 0000 0000 0001
0000 0000 0000 0000 0000 0000 0000 0010
0000 0000 0000 0000 0000 0000 0000 0011
0000 0000 0000 0000 0000 0000 0000 0100
0000 0000 0000 0000 0000 0000 0000 0101

Scoring:

Your score is equal to however many bytes your code is. As this is Code Golf, lowest score wins.

Bonus points:

If you show, in the output, the number it's at as a base 10 number (for example, 0000 0000 0000 0000 0000 0000 0000 0001 in binary is equal to the base 10 1), multiply your score by 0.8.

If you group 4 digits of output like I did, then multiply your score by 0.8 (again). This isn't required.

Do not round up, and do not round down. Your score is a floating-point number.

Good luck!

APL, 10 characters

Another on in APL. Assumes⎕IO←1 (the default). No bonus points. Reads the number from the input device. If your APL uses 64 bit integers instead of 32 bit integers, substitute 64 for 32 as needed.

Notice that APL transparently converts to floating point numbers when the range of an integer is exceeded. It's hard thus to exactly say what integer size APL works with.

⍉(32⍴2)⊤⍳⎕

explanation

2          ⍝ the number 2
32⍴2       ⍝ a vector of 32 twos.
(32⍴2)⊤X   ⍝ X represented as base 2 to 32 digits precision
⍳X         ⍝ a vector of the integers from 1 to X
⎕          ⍝ a number queried from the terminal
(32⍴2)⊤⍳⎕  ⍝ the output we want, flipped by 90°
⍉(32⍴2)⊤⍳⎕ ⍝ the output we want in correct orientation (⍉ is transpose)


How to solve the total task on "return true to win" in 21 chars There is a site called "Return True to Win" with interesting tasks for Javascript programmers. The goal is to find arguments to a given function that force it to return true.

The following is one of the tasks:

function total(x) {
  return (x < x) && (x == x) && (x > x);
}

The users must find snippets for the value of x that cause the function to return true. To test snippets, you call the function with your snippet as the parameter (i.e. total(<snippet>)).

I found a 22-character solution:

{valueOf:_=>n++%3},n=0

Some people found the solution in 21 chars. I can't find out this solution. What is the solution in 21 chars?

21 chars

{valueOf:n=_=>n=2<<n}

My original joke, which got downvoted and proposed for deletion:

11 chars :)

total=_=>!0

Test:

function total(x) {
  return (x < x) && (x == x) && (x > x);
}
var arg = total=_=>!0
console.log(total(arg))


Find the maximum of ax+b You are given a list of (a,b), and a list of x. Compute the maximum ax+b for each x. You can assume a, b and x are non-negative integers.

Your program or function must run in expected (to the randomness if your code involves that, not the input) O(nlogn) time where n is the total input length (sum or maximum of the lengths of both lists).

This is code-golf. Shortest code wins.

Example

[[2 8] [4 0] [2 1] [1 10] [3 3] [0 4]] [1 2 3 4 5]

Output:

[11 12 14 16 20]

Explanation:

11 = 1*1 + 10
12 = 1*2 + 10 = 2*2 + 8
14 = 2*3 + 8
16 = 2*4 + 8 = 4*4 + 0
20 = 4*5 + 0

Note about the complexity:

If you used a builtin having a good average-case complexity, and it can be randomized to get the expected complexity easily in theory, you can assume your language did that.

That means, if your program can be tested to be in O(nlogn), possibly with edge case exceptions because of the implementation of your language, but cannot be seen logically in your own code, we'll say it is O(nlogn).

Python, 214 bytes

S=sorted
def M(L,X):
 H=[-1,0];R={}
 for a,b in S(L):
    while H[2:]and a*H[-3]+b>H[-2]*H[-3]+H[-1]:H=H[:-3]
    H+=[1.*(H[-1]-b)/(a-H[-2]),a,b]
 for x in S(X):
    while H[2:]and x>H[2]:H=H[3:]
    R[x]=H[0]*x+H[1]
 return R

Computes the convex hull by iterating through the input a,b in increasing a order.  The convex hull is recorded in H using the format -1,0,x1,a1,b1,x2,a2,b2,x2,...,xn,an,bn where xi is the x coordinate of the intersection of a{i-1},b{i-1} and ai,bi.

Then I iterate though the input xs in sorted order, truncating the convex hull to keep up as I go.

Everything is linear except for the sorts which are O(n lgn).

Run it like:

>>> print M([[2,8],[4,0],[2,1],[1,10],[3,3],[0,4]], [1,2,3,4,5])
{1: 11, 2: 12, 3: 14, 4: 16, 5: 20}


Repeat the Nth elements We haven't had a string question for a while (5 days to be precise), so let's go for one.

Given a string s and a positive integer n, take every nth element of s, repeat it n times, and put it back into s.

For example, if n = 3 and s = "Hello, World!", every third character is Hl r!. You then repeat each character n times to produce HHHlll   rrr!!!. You then replace the original letters with the repeated versions to produce the final product of HHHellllo,   Worrrld!!!

You are to accomplish this task in the shortest code possible in your language!

Rules

This is a code-golf so the shortest code in bytes wins
n is guaranteed to be smaller than the length of s and greater than 0
The first character of s is where the nth characters are taken from, and is always repeated n times
s will only consist of printable ASCII (code points 0x20 (space) to 0x7E (~))

Test cases

s, n => output

"Hello, World!", 3 => "HHHellllo,   Worrrld!!!"
"Code golf", 1 => "Code golf"
"abcdefghijklm", 10 => "aaaaaaaaaabcdefghijkkkkkkkkkklm"
"tesTing", 6 => "ttttttesTingggggg"
"very very very long string for you to really make sure that your program works", 4 => "vvvvery    veryyyy verrrry loooong sssstrinnnng foooor yoooou toooo reaaaally    makeeee surrrre thhhhat yyyyour    proggggram    workkkks"

Jelly, 3 bytes

Ḣs×

Input is taken as s, n.

Try it online!

How it works

Ḣs×  Main link. Argument: s, n

Ḣ    Head; yield s.
     This pops the list, leaving [n] as the main link's argument.
 s   Split s into chunks of length n.
  ×  Multiply each chunk by [n], repeating its first element n times.


Build a Compiler Bomb Introduction

You're probably familiar with zip bombs, XML bombs, etc. Put simply, they are (relatively) small files which produce enormous output when interpreted by naïve software. The challenge here is to abuse a compiler in the same way.

Challenge

Write some source code which occupies 512 bytes or less and which compiles into a file which occupies the most possible space. Largest output file wins!

Rules

OK, so there are a few important clarifications, definitions and restrictions;

The output of the compilation must be an ELF file, a Windows Portable Executable (.exe), or virtual bytecode for the JVM or .Net's CLR (other types of virtual bytecode are also likely to be OK if asked for). Update: Python's .pyc / .pyo output also counts.
If your language-of-choice can't be compiled directly into one of those formats, transpilation followed by compilation is also allowed (Update: you can transpile multiple times, just so long as you never use the same language more than once).
Your source code can consist of multiple files, and even resource files, but the summed size of all these files must not exceed 512 bytes.
You cannot use any other input than your source file(s) and the standard library of your language-of-choice. Static linking standard libraries is OK when it's supported. Specifically, no third party libraries or OS libraries.
It must be possible to invoke your compilation using a command or series of commands. If you require specific flags when compiling, these count towards your byte limit (e.g. if your compile line is gcc bomb.c -o bomb -O3 -lm, the -O3 -lm part (7 bytes) will be counted (note the initial leading space isn't counted).
Preprocessors are permitted only if they are a standard compilation option for your language.
The environment is up to you, but in the interests of making this verifiable, please stick to recent (i.e. available) compiler versions and operating systems (and obviously specify which you're using).
It must compile without errors (warnings are OK), and crashing the compiler doesn't count for anything.
What your program actually does is irrelevant, though it can't be anything malicious. It doesn't even have to be able to start.

Example 1

The C program

main(){return 1;}

Compiled with Apple LLVM version 7.0.2 (clang-700.1.81) on OS X 10.11 (64-bit):

clang bomb.c -o bomb -pg

Produces a file of 9228 bytes. The total source size is 17+3 (for the -pg) = 20 bytes, which is easily within size limit.

Example 2

The Brainfuck program:

++++++[->++++++++++++<]>.----[--<+++>]<-.+++++++..+++.[--->+<]>-----.--
-[-<+++>]<.---[--->++++<]>-.+++.------.--------.-[---<+>]<.[--->+<]>-.

Transpiled with awib to c with:

./awib < bomb.bf > bomb.c

Then compiled with Apple LLVM version 7.0.2 (clang-700.1.81) on OS X 10.11 (64-bit):

clang bomb.c

Produces a file of 8464 bytes. The total input here is 143 bytes (since @lang_c is the default for awib it didn't need to be added to the source file, and there are no special flags on either command).

Also note that in this case, the temporary bomb.c file is 802 bytes, but this counts towards neither the source size nor the output size.

Final Note

If an output of more than 4GB is achieved (perhaps if somebody finds a turing complete preprocessor), the competition will be for the smallest source which produces a file of at least that size (it's just not practical to test submissions which get too big).

C, (14 + 15) = 29 byte source, 17,179,875,837 (16 GB) byte executable
Thanks to @viraptor for 6 bytes off.
Thanks to @hvd for 2 bytes off and executable size x4.
This defines the main function as a large array and initialises its first element.  This causes GCC to store the entire array in the resulting executable.
Because this array is bigger than 2GB, we need to provide the -mcmodel=medium flag to GCC.  The extra 15 bytes are included in the score, as per the rules.

main[-1u]={1};

Don't expect this code to do anything nice when run.
Compile with:
gcc -mcmodel=medium cbomb.c -o cbomb

It took me a while to get round to testing @hvd's suggestion - and to find a machine with enough juice to handle it. Eventually I found a old non-production RedHat 5.6 VM with 10GB RAM, 12GB swap, and /tmp set to a large local partition.  GCC version is 4.1.2.  Total compile time about 27 minutes.

Due to the CPU and RAM load, I recommend against doing this compile on any remotely production-related machine.


Interquine - Two programs that output each other in a loop Program A outputs program B's code when run, and B outputs A's source.

Requirements:

Only one language across both programs
Programs are different. One program that outputs itself does not qualify.
Both programs are non-empty, or at least 1 byte in length. Trailing newlines in both source and output are ignored
stdin is closed. Do not read anything (so you can't read the source and manipulate it). Output goes to stdout.
Edit: stdin is connected to /dev/null. You can order it be closed if clarified.
Do not use random functions.

Additional:

Give explanations if possible

Score is total length. Trailing newline does not count if it doesn't affect the program.

CJam, 13 + 13 = 26 bytes

{sYZe\"_~"}_~

Try it online!

Outputs

{sZYe\"_~"}_~

Explanation

{       e# Standard quine framework, leaves a copy of the block on the stack
        e# for the block itself to process.
  s     e# Stringify the block.
  YZe\  e# Swap the characters at indices 2 and 3, which are Y and Z themselves.
  "_~"  e# Push the "_~" to complete the quine.
}_~

Since e\ is commutative in its second and third operand, the other program does exactly the same, swapping Z and Y back into their original order.


What is the average of n, the closest prime to n, the square of n and the closest Fibonacci number to n? This is a math problem which takes quite many things into question, making it rather challenging, and as you might have guessed, it's a code golf, so it should be as short as possible as well.
The input, \$n\$, is any integer number (should at least support integers, but needn't be limited to). The output is the average of:

\$n\$
The square of \$n\$, \$n^2\$
The closest prime number to \$n\$, \$p\$
The closest number to \$n\$ in the Fibonacci sequence, \$f\$

Shortly, the program should print to the standard output channel the result of $$\frac {n + n^2 + p + f} 4$$.
You don't have to care about possible overflows etc. Normal floating point precision is also ok.
The way the input is given is completely up to you. Shortest program (in characters) wins, as always with code golfs.
In the case a tie occurs when you are looking for the closest, choose one of the following:

Go up
Go down
Choose one randomly

Python 160 Chars

p=lambda n:any(n%x<1for x in range(2,n))
N=input()
a=0;b=1
while b<N:a,b=b,a+b
c=d=N
while p(c)and p(d):c-=1;d+=1
print (N+N*N+[b,a][2*N-a-b<0]+[c,d][p(c)])/4.0

A little explanation about the closestFib part:

  When the while loop ends a is smaller
  than N and b is either equal to or
  greater than N. Now the
  [b,a][2*N-a-b<0] part. Look at it as
  [b,a][(N-a)-(b-N)]. (N-a) is the
  difference between N and a and
  similarly (b-N) the difference between
  b and N. If the difference between
  these two is less than 0 it means a is
  closer to N and vice-versa.