I multiply the source, you (probably) multiply the output! Task

The task is to write a program that outputs a consistent but otherwise arbitrary positive integer \$x\$ (so strictly greater than 0). Here's the catch: when the source is repeated \$N\$ times (the code is appended/concatenated \$N-1\$ to itself), the program should have a \$\dfrac{1}{N}\$ probability of outputting \$N\cdot x\$ and the remaining probability of \$\dfrac{N-1}{N}\$ of outputting \$x\$ unchanged.

Example

Let's assume that your initial source is XYZ and produces the integer 3. Then:

For \$N=2\$: XYZXYZ should output \$3\$ with a probability of \$\frac{1}{2}\$ (50% of the time) and \$2\cdot 3=6\$ with a probability of \$\frac{1}{2}\$ as well (50% of the time).
For \$N=3\$: XYZXYZXYZ should output \$3\$ with a probability of \$\frac{2}{3}\$ (66.666% of the time) and \$3\cdot 3=9\$ with a probability of \$\frac{1}{3}\$ (33.333%  of the time)
For \$N=4\$: XYZXYZXYZXYZ should output \$3\$ with a probability of \$\frac{3}{4}\$ (75% of the time) and \$4\cdot 3=12\$  with a probability of \$\frac{1}{4}\$ (25% of the time)

and so on....

Rules

You must build a full program. The output has to be printed to STDOUT.
Your program, should, in theory, output each possible value with the probabilities stated above, but a slight deviation from this due to the implementation of random is fine (provided that the implementation is not of a different distribution - you can't use a normal distribution to save bytes).
The program should (again, in theory) work for an arbitrarily big value of \$N\$, but technical limitations due to precision are fine for large \$N\$.
The output must be in base 10 (outputting in any other base or with scientific notation is forbidden). Trailing / leading spaces and leading zeroes are allowed.
The initial source must (of course) be at least 1 byte long. You may not assume a newline between copies of your source. The program should not take input (or have an unused, empty input).
This is code-golf, so an answer's score is the length of the (original) source in bytes, with a lower score being better.

Note: This challenge is a (much) harder version of this one.

R, 66 35 bytes

-29 bytes thanks to digEmAll.

-2 bytes thanks to Giuseppe.

+0->A
x=!0:F
F=F+1
sample(F*x+!x,1)

Try it online!

Check the distribution for N=4.

The key is the rightwards assignment ->. When the code is multiplied \$N\$ times, the first \$N-1\$ calls to sample will be assigned to A, and only the last call will be printed.

Original, more convoluted solution:

R, 66 bytes

T->TT
F=F+1
TT=0
`?`=function(x)if(x)sample(c(1,F),1,,c(1,F-1))
?T

Try it online!

Try it online (repeated 3 times)!

Uses two tricks: 1) call the main function of interest ?, so that we can call it without ending the program with a bracket, and 2) use variables T and TT, with code which starts with T and ends with ?T.

F is the iteration counter. ? is redefined as a function which takes a boolean argument: if the input of ? is TRUE (or T), it does the required random sampling; if the input is FALSE (or 0), it does nothing. The value of TT is defined as 0, so that ?T does the sampling but ?TT does nothing.

When the source is repeated, it looks like this:

T->TT
F=F+1
TT=0
`?`=function(x)if(x)sample(c(1,F),1,,c(1,F-1))
?TT->TT
F=F+1
TT=0
`?`=function(x)if(x)sample(c(1,F),1,,c(1,F-1))
?T

so the middle call ?TT outputs nothing but the final call ?T outputs the random result.


Determine if a Graph is Toroidal A simple graph is toroidal if it can be drawn on the surface of a torus without any edges intersecting.  Your task is to take a simple undirected graph via any reasonable method (adjacency matrix, edge vertex sets, etc.) and decide whether or not it is a toroidal graph.  You should output one of two distinct values for each of the two decisions.  You may choose what these values are.

This is code-golf so answers will be scored in bytes with less bytes being better.

Test Cases

Here Kn is the complete graph with n vertices and Kn,m is the complete bipartite graph.

Toroidal

K3
K7
K3,3
The Peterson graph
The Möbius Cantor graph

Not Toroidal

K8

Rust, 1210 1200 bytes

use std::collections::HashMap as H;type I=i64;type E=Vec<(I,I)>;fn d(g:&E)->bool{let mut s:Vec<(E,Vec<I>)>=vec![];for e in g{let(v,w)=e;let f=(*v,*w);let z=|x|s.iter().position(|p|p.1.contains(x));match(z(v),z(w)){(Some(i),Some(j))=>{if i!=j{let mut p=s.remove(i);let q=s.remove(j-(i<j)as usize);p.0.extend(q.0);p.1.extend(q.1);s.push(p)}else{s[i].0.push(f)}}(Some(i),_)=>{s[i].0.push(f);s[i].1.push(*w)}(_,Some(j))=>{s[j].0.push(f);s[j].1.push(*v)}_=>{s.push((vec![f], vec![*v, *w]))}}}s.iter().map(|h|{let mut p=H::new();let mut r=H::new();let mut i=0;for e in&h.0{let(v,w)=e;i+=2;p.insert(i-1,i);p.insert(i,i-1);r.entry(v).or_insert(vec![]).push(i-1);r.entry(w).or_insert(vec![]).push(i)}let mut r:Vec<Vec<I>>=r.values().cloned().collect();r.sort();let mut x=0;let m=r.iter().flat_map(|v|1..v.len()).fold(1,|p,n|p*n);for mut w in 0..m{let mut t=H::new();for u in&r{let mut v=u.clone();let s=v.pop().unwrap();let mut f=s;while v.len()>0{let o=v.remove(w%v.len());w/=v.len()+1;t.insert(f,o);f=o}t.insert(f,s);}let mut f=vec![];let mut n=0;for s in p.keys(){if!f.contains(s){n+=1;let mut c=s;loop{f.push(*c);c=&t[&p[c]];if c==s{break}}}}x=x.max(n)}1-(r.len()as I-g.len()as I+x as I)/2}).sum::<I>()<2}

A toroidal example:
Try it online!

That's this toroidal graph:

A non-toroidal example: Try it online!

That's this non-toroidal graph:

The original code I wrote, before golfing, was the following. It has printouts so you can see what's happening:

use std::collections::HashMap;

#[derive(PartialEq, Eq, Hash, Clone, Copy, Debug)]
struct Vertex(u64);
type Edge = (Vertex, Vertex);
type Graph = Vec<Edge>;

fn full_genus(graph: &Graph) -> usize {
    componets(graph).iter().map(|g| genus(g)).sum()
}
fn genus(graph: &Graph) -> usize {
    #[derive(PartialEq, Eq, Hash, Clone, Copy, Debug, PartialOrd, Ord)]
    struct HalfEdge(usize);
    let mut edge_pairing: HashMap<HalfEdge, HalfEdge> = HashMap::new();
    let mut vertex_groups: HashMap<&Vertex, Vec<HalfEdge>> = HashMap::new();
    let mut i = 0;
    for edge in graph {
        let (vert1, vert2) = edge;
        let half1 = HalfEdge(i);
        i += 1;
        let half2 = HalfEdge(i);
        i += 1;
        edge_pairing.insert(half1, half2);
        edge_pairing.insert(half2, half1);
        vertex_groups.entry(vert1).or_insert(vec![]).push(half1);
        vertex_groups.entry(vert2).or_insert(vec![]).push(half2);
    }
    let mut vertex_groups: Vec<Vec<HalfEdge>> = vertex_groups.values().cloned().collect();
    vertex_groups.sort();
    println!("{:?}", edge_pairing);
    println!("{:?}", vertex_groups);

    let mut max_faces = 0;
    let num_rotations = vertex_groups
        .iter()
        .map(|v| v.len() - 1)
        .map(|n| {
            let mut prod = 1;
            for i in 0..n {
                prod *= i + 1;
            }
            prod
        })
        .fold(1, |p, n| p * n);
    println!("\nNum rotations: {}\n", num_rotations);
    for rotation_index in 0..num_rotations {
        let mut working_index = rotation_index;
        let mut rotation: HashMap<HalfEdge, HalfEdge> = HashMap::new();
        let mut pretty_rotation: Vec<Vec<HalfEdge>> = vec![];
        for group in &vertex_groups {
            let mut removal_group = group.clone();
            let start = removal_group.pop().unwrap();
            let mut from = start;
            let mut pretty_group = vec![from];
            while !removal_group.is_empty() {
                let index = working_index % removal_group.len();
                working_index /= removal_group.len();
                let to = removal_group.swap_remove(index);
                rotation.insert(from, to);
                pretty_group.push(to);
                from = to;
            }
            rotation.insert(from, start);
            pretty_rotation.push(pretty_group);
        }
        let mut seen_on_face: Vec<HalfEdge> = Vec::new();
        let mut num_faces = 0;
        for start_halfedge in edge_pairing.keys() {
            if !seen_on_face.contains(start_halfedge) {
                num_faces += 1;
                let mut current_halfedge = start_halfedge;
                loop {
                    seen_on_face.push(*current_halfedge);
                    let pair_halfedge = &edge_pairing[current_halfedge];
                    current_halfedge = &rotation[pair_halfedge];
                    if current_halfedge == start_halfedge {
                        break;
                    }
                }
            }
        }
        if num_faces > max_faces {
            max_faces = num_faces;
            let euler_characteristic: isize =
                vertex_groups.len() as isize - graph.len() as isize + max_faces as isize;
            let genus_num: isize = 1 - euler_characteristic / 2;
            println!(
                "Faces: {}, Genus <= {} on rotation {}",
                max_faces, genus_num, rotation_index
            );
            println!("{:?}\n", pretty_rotation);
        }
        if rotation_index % 1e7 as usize == 0 {
            println!("Faces: {} <= {} on rotation {}", num_faces, max_faces, rotation_index);
        }
    }
    let euler_characteristic: isize =
        vertex_groups.len() as isize - graph.len() as isize + max_faces as isize;
    let genus_num: isize = 1 - euler_characteristic / 2;
    assert!(genus_num >= 0);
    genus_num as usize
}

fn componets(graph: &Graph) -> Vec<Graph> {
    let mut graphs: Vec<(Graph, Vec<Vertex>)> = vec![];
    for edge in graph {
        let (vert1, vert2) = edge;
        let g_index1 = graphs.iter().position(|(_g, h)| h.contains(&vert1));
        let g_index2 = graphs.iter().position(|(_g, h)| h.contains(&vert2));
        match (g_index1, g_index2) {
            (Some(i1), Some(i2)) => {
                if i1 != i2 {
                    let (mut graph1, mut vs1) = graphs.remove(i1);
                    let new_i2 = if i1 < i2 { i2 - 1 } else { i2 };
                    let (graph2, vs2) = graphs.remove(new_i2);
                    graph1.extend(graph2);
                    vs1.extend(vs2);
                    graphs.push((graph1, vs1));
                } else {
                    graphs[i1].0.push(edge.clone());
                }
            }
            (Some(i1), None) => {
                graphs[i1].0.push(edge.clone());
                graphs[i1].1.push(vert2.clone());
            }
            (None, Some(i2)) => {
                graphs[i2].0.push(edge.clone());
                graphs[i2].1.push(vert1.clone());
            }
            (None, None) => {
                let edges = vec![edge.clone()];
                let vs = vec!(vert1.clone(), vert2.clone());
                graphs.push((edges, vs));
            }
        }
    }
    graphs.into_iter().map(|(g, _h)| g).collect()
}

fn main() {
    let graph = vec![
        (Vertex(0), Vertex(1)),
        (Vertex(0), Vertex(2)),
        (Vertex(0), Vertex(3)),
        (Vertex(0), Vertex(4)),
        (Vertex(0), Vertex(5)),
        (Vertex(1), Vertex(2)),
        (Vertex(1), Vertex(3)),
        (Vertex(1), Vertex(4)),
        (Vertex(1), Vertex(5)),
        (Vertex(2), Vertex(3)),
        (Vertex(2), Vertex(4)),
        (Vertex(2), Vertex(5)),
        (Vertex(3), Vertex(4)),
        (Vertex(3), Vertex(5)),
    ];
    let result = full_genus(&graph);
    println!("Result: {}", result);
}

This program finds the minimum genus surface that the given graph can be embedded in. A graph is toroidal if that genus is at most 1, the genus of the torus.

The code works by separating the graph into its connected components, finding their genii separately, and adding up the results.

To find the genus of a connected graph, I brute force search over all possible rotation systems of the graph, and figure out which one has the most faces. A rotation system is simply an ordering on the edges emerging from each vertex, saying what order those edges are in going around the vertex. Each rotation system has a straightforward minimum genus it can be embedded in, and having more faces directly corresponds to having lower genus. Since every possible embedding corresponds to some rotation system, if there is a toroidal embedding, my program will find the corresponding rotation system and declare that the graph is toroidal, and vice versa.

This program is very slow, because it searches through a number of rotation systems equal to the product over all degrees d of the vertices of (d-1)!. However, it can search through a little over 10 million such rotation systems per minute, so it can verify the toroidality or non-toroidality of simple graphs like the ones shown above.


Can a fraction be simplified using Anomalous Cancellation? Anomalous Cancellation (from Wolfram Alpha):

  Anomalous cancellation is a "canceling" of digits of a and b in the numerator and denominator of a fraction a/b which results in a fraction equal to the original. Note that if there are multiple but differering counts of one or more digits in the numerator and denominator there is ambiguity about which digits to cancel, so it is simplest to exclude such cases from consideration.
  Link

In simple terms, say you have a fraction a / b. If you can cancel out the digits in the fraction to create another fraction c / d which is equal to the original (a / b = c / d), anomalous cancellation can be used to simplify the fraction.

Your challenge is to make a program or function that inputs a fraction string in the form a/b and outputs or returns a truthy value if the fraction can be simplified using anomalous cancellation, and a falsy value otherwise. a and b will always be non-zero positive integers. a and b will always have two or more digits. Also, all of the digits from either a or b will not be cancelled out (You wont get the input 12/21), at least one digit from a and b will be cancelled each time (You wont get the input 43/21), and the end result will never be 0 for either a or b. Your program must cancel out all common digits between a and b (ie. in 1231/1234, you must cancel out a 1, a 2, and a 3). If there is multiple possibilities for cancellation, choose the leftmost digit first (515/25 becomes 15/2 not 51/2).

Examples:

Input      Output    Why

1019/5095  true      Remove the 0 and the 9 from both sides of the fraction to get 11/55, which is equivalent.
16/64      true      Remove the 6 from both sides, and get 1/4.
14/456     false     Remove the 4s. 14/456 is not equal to 1/56.
1234/4329  false     Remove the 2s, 3s, and 4s. 1234/4329 is not equal to 1/9.
515/25     false     Remove the first 5 from each side. 15/2 is not equal to 515/25.

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

Pyth, 22 19 bytes
Thanks to @isaacg for three bytes!
qFcMsMM,Jcz\/.-M_BJ

Explanation:
qFcMsMM,Jcz\/.-M_BJ      Implicit: z=input().
       ,                 two-element list
        Jcz\/              J = split z on ','
                _BJ      Bifurcate reverse: [J,reversed(J)]
             .-M         map multiset difference of elements in both lists
                             this gives the multiset difference both ways
       ,Jcz\/.-M_BJ      On input 1019/5095: [['1019','5095'], ['11','55']]
    sMM                  convert all strings to numbers
  cM                     map by float division
qF                       fold equality

Try it here.


Add the Fibonnaci Sequence to the Lucas Sequence Background of Lucas Numbers

The French mathematician, Edouard Lucas (1842-1891), who gave the name to the Fibonacci Numbers, found a similar series occurs often when he was investigating Fibonacci number patterns.

The Fibonacci rule of adding the latest two to get the next is kept, but here we start from 2 and 1 (in this order) instead of 0 and 1 for the (ordinary) Fibonacci numbers.
The series, called the Lucas Numbers after him, is defined as follows: where we write its members as Ln, for Lucas:

Challenge

Input

0 < x < ∞
The input will be a positive integer starting at 0.

Output

The output must be a positive integer.

What to do?

Add the Fibonacci numbers to the Lucas numbers.
You will input the index.
The output will be the addition of the Lucas and Fibonacci numbers.

Fibonnaci formula:

  F(0) = 0,
  F(1) = 1,
  F(n) = F(n-1) + F(n-2)

Lucas formula:

  L(0) = 2,
  L(1) = 1,
  L(n) = L(n-1) + L(n-2)

Who wins?

Standard Code-Golf rules apply, so the shortest answer in bytes wins.

Test-cases

  A(0)  = 2
  A(1)  = 2
  A(5)  = 16
  A(10) = 178
  A(19) = 13,530
  A(25) = 242,786


Display the exponent from a binary floating point number as a decimal value Had my software final exams recently, one of the last questions had me thinking for a while after the exam had finished.
Background
IEEE754 numbers are according to the below layout

The exponent is stored as n + 127 so for an exponent of 20 the exponent in binary would be:
127 + 20 = 147 then
10010011
The Challange
Write a program that when given text representing a binary floating point number to the IEEE754 standard, returns the exponent given as a decimal value.
Example
Input: 00111101110011001100110011001101 (0.1)
Isolated exponent bits: 01111011
Convert to binary: 0 + 64 + 32 + 16 + 8 + 0 + 2 + 1 = 123
Remove offset: 123 - 127 = -4
Output -4

Input: 10111111110111101011100001010010 (-1.64)
Isolated exponent bits: 01111111
Convert to binary: 0 + 64 + 32 + 16 + 8 + 4 + 2 + 1 = 127
Remove offset: 127 - 127 = 0
Output 0
Rules

Input must be text/string/equivalent indexable datatype, eg. strings not integer or numerical
Output can be any type, as long as it is decimal
Aim for shortest solutions

Adapted from the 2020 Software Design and Development HSC Paper: 30) d) ii

Design an algorithm that takes in a string of 32 characters representing
a floating point number, and displays the exponent as its signed decimal
value.

Any feedback is appreciated as this is my first question

Haskell, 33 bytes

foldl1(\x y->x*2+y-1).take 8.tail

Try it online!
Input is a list of integers 0 or 1.
It's slightly shorter to foldl1 by x*2+y-1 than to subtract 127 at the end. This works because
  foldl1 (\x y->x*2+y-1) [a,b,c,d,e,f,g,h]
= ((((((a*2+b-1)*2+c-1)*2+d-1)*2+e-1)*2+f-1)*2+g-1)*2+h-1
= a*128 + b*64-64 + c*32-32 + d*16-16 + e*8-8 + f*4-4 + g*2-2 + h-1
= 128a + 64b + 32c + 16d + 8e + 4f + 2g + h - 127
= fromBinary[a,b,c,d,e,f,g,h]-127


Oops, I blew it up (with numbers) Inspired by There, I fixed it (with rope), There, I fixed it (with Tape), There, I broke it (with scissors)

Given a string with characters from a-z or A-Z (whichever you prefer), turn missing letters into numbers and make them explode.

Example

Input: abcafabc

Output: a12344321c

Why?

1) Find the missing letters (only going forward in the alphabet): abca(bcde)fabc

2) Replace them with the number of missing letters: abca4fabc

3) Replace the number with

Itself twice if it's even
Itself + 1 if it's odd

In this case: abca44fabc

4) Explode those numbers outwards replacing any letters: a12344321c

Challenge Rules

Explosions can't exceed the boundaries of the string

ae -> 343 (3 letters are missing but since 3 is odd, it's been replaced by 4)

Numbers can be greater than 9

az -> 23242423 (24 letters are missing and since 24 is even, it's repeated twice)

You can have multiple explosions

abcefghijmnop -> ab121fghi1221nop

Multiple explosions can overlap, take the sum of the number when they do

abceghij -> abc(2)e(2)ghij -> ab12(1+1)21hij -> ab12221hij

It's possible that no explosions occur, in that case simply return the string
No explosions between ab, aa, aaa, etc.
You are allowed to take the input in any reasonable format. Can be a single string, string-array/list, character-array/list, etc. Output has the same flexibility.
You are allowed to use lowercase and/or uppercase any way you'd like. This applies both to the input, output.

General Rules

This is code-golf, so the shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-golfing languages.
Standard rules apply.
Default Loopholes are forbidden.
If possible, please add a link to a test for your code, preferably Tio.
Also, please add an explanation if necessary.

Test cases:

Input  : 'abcdefgklmnopqrstuvwxyz'
Output : 'abcd1234321nopqrstuvwxyz'

Input  : 'abdefgjkl'
Output : 'a121ef1221kl'

Input  : 'xyzaz'
Output : '20212223242423'

Input  : 'abceghij'
Output : 'ab12221hij'

Input  : 'zrabc'
Output : 'zrabc'

Ruby, 162 bytes

->a{b=[*a=a.reduce{|x,y|[*x,*[(n=y.ord+~x[-1].ord)+n%2]*(n<1?0:2-n%2),y]}];i=-1;b.map{|x|d=-~i+=1;a.map!{|y|(z=x.to_i-(d-=1)*s=d<=>0)<1||x==b[i-s]?y:z+y.to_i}};a}

Try it online!

Takes input as an array of chars, returns a mixed array of chars/ints. (I'm still not sure whether this is allowed after reading the comments to the original post. If not allowed, it's +3 bytes to fix).

Explanation

First, we apply a reduce operation, where we aren't actually reducing anything, but rather reconstruct the array a as [*x,*[...],y], where the middle part contains the numbers inserted at ground zero.

We also make a copy of the array: b=[*a] to serve as a reference, so that we don't get confused which numbers are at the center of the explosion, and which ones are introduced later on.

Then we iterate through b and for each element x, iterate through a to record, what effect x will have on each element y of a.

Conveniently, to_i method returns 0 for non-numeric chars, so that we don't have to worry about distinction between numbers and text.

In my initial code, arrays were indexed by i and j, but this was golfed down to use a "delta" value d=i-j.

Another helper variable is the sign of the delta: s=d<=>0. At the first occurrence it performs the same function as abs, and at the second - it helps us to block the other side of one-sided explosions as in 12344321.

Ultimately, if z is estimated to be positive, we add it up with the integer equivalent of y and store in a, otherwise, y remains intact.


Minimum excluded number This is intended to be an easy, bite-size code-golf.

The mex (minimal excluded number) of a finite collection of numbers is the smallest non-negative integer 0, 1, 2, 3, 4, ... that does not appear in the collection. In other words, it's the minimum of the complement. The mex operation is central to the analysis of impartial games in combinatorial game theory.

Your goal is to write a program or named function to compute the mex using as few bytes as possible.

Input:

A list of non-negative integers in any order. May contain repeats. For concreteness, the length of the list and the allowed range of elements will both be between 0 and 20 inclusive.

The definition of "list" here is flexible. Any structure that represents a collection of numbers is fine, as long as it has a fixed ordering of elements and allows repeats. It may not include any auxiliary information except its length.

The input can be taken as a function argument or through STDIN.

Output

The smallest excluded number. Output or print it.

Test cases

[1]
0
[0]
1
[2, 0]
1
[3, 1, 0, 1, 3, 3]
2
[]
0
[1, 2, 3]
0
[5, 4, 1, 5, 4, 8, 2, 1, 5, 4, 0, 7, 7]
3
[3, 2, 1, 0]
4
[0, 0, 1, 1, 2, 2, 3]
4
[1, 0, 7, 6, 3, 11, 15, 1, 9, 2, 3, 1, 5, 2, 3, 4, 6, 8, 1, 18]
10

Pyth, 6 bytes

h-U21Q

Example run

$ pyth -c h-U21Q <<< '[5, 4, 1, 5, 4, 8, 2, 1, 5, 4, 0, 7, 7]'
3

How it works

  U21   range(21)
     Q  eval(input())
 -U21Q  setwisedifference(range(21), eval(input))          # Pyth function. Preserves order.
h-U21Q  setwisedifference(range(21), eval(input))[0]


Find the "unwrapped size" of a list Let's define the "unwrapped size" function u of a nested list l (containing only lists) by the following rules:

If l is empty, then u(l) is 1.
If l is non-empty, u(l) is equal to the sum of the unwrapped sizes of every element in l, plus one.

Your task is to write a program (or function) that takes a list as input and outputs (or returns) the unwrapped size of the list.

Test Cases:

[]                                           ->  1
[[[]],[]]                                    ->  4
[[[]],[[[[]],[]]],[[[]],[[[[]],[[],[[]]]]]]] -> 19
[[[[]]]]                                     ->  4

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

Retina, 1 byte

]

Try it online! (The first line enables a linefeed-separated test suite.)

By default, Retina counts the number of matches of the given regex in the input. The unwrapped size is simply equal to the number of [] pairs in the input and therefore to the number of ].


Is it a pleasing number? A pleasing number (according to this definition) is a number that can be passed through the following process (let's use 41802000 as an example):

Separate the trailing identical numbers (41802000 => [41802, 000])
Sort the first half of the digits and take the maximum ([41802, 000] => [8, 000])
Take the length of the final element. Call the resultant elements A and B ([8, 000] => A=8, B=3)
Is NB = A for any integer N? (True in this example; 23 = 8)

If the input results in True from the following process, it is considered pleasing.

Your task is to take an integer x, and output whether x is a pleasing number. You can output any two distinct values for truthy and falsey, but please state what you're using in your answer. x is guaranteed to have at least two distinct digits (e.g. 111 is an invalid input). As with most challenges, you may take x as a string, or a list of digits.

This is a code-golf so shortest code in bytes wins.

Test cases

          Input          Output
       41802000               1
            100               1
      123456788               0
      451111111               0
234543454545444               0
             12               1
       41902000               0
          92599               1

APL (Dyalog), 36 bytes

{(⊢≡⌊)(⌈/⍎¨⍵/⍨~o)*÷≢⍵/⍨o←⌽⌊\1,2=/⌽⍵}

Try it online!

How?

Almost a poem.

⌽⍵ - reverse the input once,

1,2=/ - get the differences list.

⌊\ - keep only the first group of ones,

⌽ - and flip it over to complete.

o← - assign to o,

~o - switch ones and zero(s),

⍵/⍨ - filter the input with it,

⍎¨ - turn the result into list of each digit,

⌈/ - and get the maximum. (that's A)

⍵/⍨o - filter the input with o unalt(ered),

≢ - and take the length, that would be B.

÷ - get one divided by this result,

* - and take A to that power thee.

⊢≡⌊ - integer?


Find The Sum of the First n Bouncy Numbers Terminology

An increasing number is one where each digit is greater than or equal to all the digits to the left of it (ex. 12239)

A decreasing number is one where each digit is less than or equal to all the digits to the left of it (ex. 95531)

A bouncy number is any number that is not increasing or decreasing. Since this requires at least 3 digits, the first bouncy number is 101

The task

Given an integer n greater than or equal to 1, find the sum of the first n bouncy numbers

Rules

This is code golf, so the answer with the shortest amount of bytes wins
If your language has limits on integer size (ex. 2^32-1) n will be small enough that the sum will fit in the integer
Input can be any reasonable form (stdin, file, command line parameter, integer, string, etc)
Output can be any reasonable form (stdout, file, graphical user element that displays the number, etc)

Test cases

1 > 101
10 > 1065
44701 > 1096472981

Jelly, 10 8 bytes

ṢeṚƬ¬µ#S

Try it online!

How it works

ṢeṚƬ¬µ#S  Main link. No arguments.

      #   Read an integer n from STDIN and call the chain to the left with argument
          k = 0, 1, 2, ... until n of them return a truthy result.
          Yield the array of successful values of k.
     µ    Monadic chain. Argument: k (integer)
Ṣ           Sort, after promoting k to its digit array.
  ṚƬ        Reverse 'til the results are no longer unique and yield unique results.
            Calling Ṛ on k promotes it to its digit array. If k = 14235, the
            result is [14235, [5,3,2,4,1], [1,4,2,3,5]].
 e          Check if the result to the left appears in the result to the right.
    ¬       Negate the resulting Boolean.
       S  Take the sum.


Print a tongue twister! The goal of this challenge is to print the following tongue twister:
She sells seashells by the seashore,
The shells she sells are seashells, I'm sure.
So if she sells seashells on the seashore,
Then I'm sure she sells seashore shells.

This is more complicated than just calling your language's print equivalent. Since there are a lot of repeated words and phrases, you can greatly decrease the size of your code by using other tactics.
Rules:

No querying another website which will respond with the full twister
You must include all the punctuation and line breaks in the original text.
You can end with a trailing newline

This is code-golf, so the shortest code wins!
Good luck!

Retina 0.8.2, 106 103 bytes

S230 by41h012 are30,5.¶So if1230 on4n5123ore1h0.
5
 I'm1ure
4
 the3ore,¶The
3
1eash
2
he10
1
 s
0
ells

Try it online! Explanation: In Retina, a substitution only makes sense if it's long enough l for the number n of repetitions. The substitution saves n(l-1) bytes in the compressed text but costs l+3 bytes in the replacement stages. This gives the minimum length required to be useful as follows:

2 repetitions: length > 5
3 repetitions: length > 3
4 repetitions: length > 3
5 repetitions: length > 2
6+ repetitions: length > 1

Edit: As @Arnauld pointed out, you can count repetitions from the substitution entries as well. This means that although there were only 5 repetitions of space+s in my previous encoded text, there are also 3 repetitions in the substitutions, thus allowing me to save 3 bytes overall. (@Arnauld himself had only spotted 2 of the 3 repetitions.)


Regex, Paper, Scissors, Lizard, Spock Warm up: Regex, Paper, Scissors

This is the challenge I originally wanted to post, before realising that some very short solution exist. Nevertheless, it can be an interesting problem to think about in preparation for the actual challenge below.

Write three regexes R, P and S such that they match each other in a cyclic Rock, Paper, Scissors fashion. In particular, R matches S, S matches P and P matches R, but R doesn't match P, S doesn't match R and P doesn't match S. Here's a handy table:

Regex   Matches   Doesn't match
R       S         P
P       R         S
S       P         R

It doesn't matter what R, P and S do on any other inputs, including themselves.

Here, match just means that some (possibly empty) substring of the input is matched. The match does not need to cover the entire input.

The challenge: Regex, Paper, Scissors, Lizard, Spock

For this challenge, you'll solve a tougher version of the above problem, based on the RPS variant Rock, Paper, Scissors, Lizard, Spock (as popularised by The Big Bang Theory). In RPSLV, there are five different symbols, that beat each other in two cycles:

Rock → Scissors → Lizard → Paper → Spock → Rock
Rock → Lizard → Spock → Scissors → Paper → Rock

You should write five regexes R, P, S, L and V which mimic this structure when given to each other as input. Here is the corresponding table:

Regex   Matches   Doesn't match
R       L, S      V, P
L       V, P      S, R
V       S, R      P, L
S       P, L      R, V
P       R, V      L, S

Just to be clear, you should not match the string R, P, etc, but the other regexes. E.g. if your regex R is ^\w$ for example, then P and V have to match the string ^\w$, whereas S and L shouldn't.

Again, match just means that at least one (possibly empty) substring of the input is matched. The match does not need to cover the entire input. For example \b (word boundary) matches hello (at the beginning and at the end), but it doesn't match (^,^).

You may use any regex flavour, but please state the choice in your answer and, if possible, provide a link to an online tester for the chosen flavour. You may not use any regex features that let you invoke code in the flavour's host language (like the Perl flavour's e modifier).

Delimiters (like /regex/) are not included in the regex when given as input to another, and you cannot use modifiers that are outside of the regex. Some flavours still let you use modifiers with inline syntax like (?s).

Your score is the sum of the lengths of the five regexes in bytes. Lower is better.

It turns out to be a lot simpler to find a working solution to this problem than it may seem at first, but I hope that finding an optimal solution is quite tricky.

PCRE .NET, 35 32 bytes

-3 bytes thanks to Martin Ender

Rock:

([*?]$)

Paper:

[)$]$+

Scissors:

[+?]$.*

Lizard:

[+$]$.?

Spock:

[*)]$

The idea here is to match characters at the end of other regexes which are reserved regex characters, but stop being treated as such when inside a character class.


Prefix Tree Traversal Write a program that takes in (via stdin or command line) a string with the recursive form

PREFIX[SUFFIXES]

where

PREFIX may be any string of lowercase letters (a-z), including the empty string, and
SUFFIXES may be any sequence of strings with the recursive form PREFIX[SUFFIXES] concatenated together, including the empty sequence.

Generate a list of lowercase lettered strings from the input by recursively evaluating the list of strings in each of the suffixes and appending them to the prefix. Output to stdout the strings in this list in any order, one per line (plus an optional trailing newline).

  Example

  If the input is

cat[s[up[][]][]ch[e[r[]s[]]]a[maran[]comb[]pult[[]ing[]]]]

  then the prefix is cat and and the suffixes are s[up[][]], [],
  ch[e[r[]s[]]], and a[maran[]comb[]pult[[]ing[]]]. Each suffix has
  its own prefix and suffixes in turn.

  The output would be these 9 words in any order

catsup
cats
cat
catcher
catches
catamaran
catacomb
catapult
catapulting

  because the input encodes this tree

  and each of the 9 output words can be formed by traversing the tree
  from root to leaf.

Notes

Remember that the prefix may be the empty string, so something like

[donut[][]cruller[]]

is valid input whose output would be (in any order)

donut

cruller

where the empty line is for the empty string that the second suffix matches.
The suffix sequence can also be empty, so the trivial input case

[]

has a single empty line as its output:

You may assume that the input will only produce unique output words.

e.g. hat[s[]ter[]s[]] would be invalid input because hats is encoded twice.
Similarly, [[][]] is invalid because the empty string is encoded twice.

You may not assume that the input is as short or compressed as possible.

e.g. the 'e' node in the main example above could be combined with the 'ch' node, but that's doesn't mean the input is invalid.
Similarly, [[[[[]]]]] is valid, despite only encoding the empty string in a sub-optimal way.

Instead of a program you may write a function that takes the input string as an argument and prints the output normally or returns it as a string or list.

The shortest code in bytes wins.

Haskell, 125 bytes

t=tail.p
p=g.break(=='[')
g(a,(_:t))=(:)&(map(a++).z)$t#[]
z[]=[""];z x=x
(']':u)#a=u:a
s#a=(#)&(a++)$p s
(g&f)(x:y)=g x$f y

The function is t (for traversal):

λ: t "cat[s[up[][]][]ch[e[r[]s[]]]a[maran[]comb[]pult[[]ing[]]]]"
["catsup","cats","cat","catcher","catches","catamaran","catacomb","catapult","catapulting"]
λ: t "[donut[][]cruller[]]"
["donut","","cruller"]
λ: t "[[[[[]]]]]"
[""]


Convert a number to Hexadecimal Challenge

Here's a simple one.

Write a function or program when given a number in base 10 as input, it will return or print that number's value in Hexadecimal.

Examples

15 -> F
1000 -> 3E8
256 -> 100

Rules

No built-in Hexadecimal functions whatsoever
Letters may be lowercase or uppercase
You will only need to worry about non-negative integers, no negatives or pesky decimals
It should work with any arbitrarily large number up to language's default type's limit.
Newline not mandatory
As usual, this is code-golf, so shortest code measured in bytes wins!

Turing Machine Code, 412 bytes

As usual, I'm using the rule table syntax defined here. You can test it on that site or, alternatively, using this java implementation.

0 * * l B
B * * l C
C * 0 r D
D * * r E
E * * r A
A _ * l 1
A * * r *
1 0 9 l 1
1 1 0 l 2
1 2 1 l 2
1 3 2 l 2
1 4 3 l 2
1 5 4 l 2
1 6 5 l 2
1 7 6 l 2
1 8 7 l 2
1 9 8 l 2
1 _ * r Y
Y * * * X
X * _ r X
X _ _ * halt
2 * * l 2
2 _ _ l 3
3 * 1 r 4
3 1 2 r 4
3 2 3 r 4
3 3 4 r 4
3 4 5 r 4
3 5 6 r 4
3 6 7 r 4
3 7 8 r 4
3 8 9 r 4
3 9 A r 4
3 A B r 4
3 B C r 4
3 C D r 4
3 D E r 4
3 E F r 4
3 F 0 l 3
4 * * r 4
4 _ _ r A

Counts down from the input in base 10 while counting up from 0 in base 16. On decrementing zero, it erases the input block and terminates.


Maximum summed sub sequences with no two numbers sharing the same digit Suppose there are 5 positive integers in an array or list as 14, 12, 23, 45, 39.

14 and 12 cannot be taken in the subset as 1 is common in both. Similarly {12, 23}, {23, 39}, {14, 45} cannot be included in the same subset.

So the subset which forms the maximum sum is {12, 45, 39}. The maximum sum such formed is 96.

the result should be the maximum sum of such combination.

Sample TestCase 1
Input
3,5,7,2
Output
17

Sample Test Case 2
Input
121,23,3,333,4
Output
458

Sample Test Case 3
Input
32,42,52,62,72,82,92
Output
92

Explanation

Test Case 1: {3, 5, 7, 2} = 17

Test Case 2: {121, 333, 4} = 458

Test Case 3: {92} = 92

05AB1E, 11 bytes

æʒ€ÙJDÙQ}OZ

Try it online!

Explanation

æʒ      }    # filter the powerset of the input, keep only elements
  €Ù         # where each number with duplicate digits removed
    JDÙQ     # have different digits from the other numbers
         O   # sum each
          Z  # take max


Draw A Sierpinski Triangle The Sierpinsky Triangle is a fractal created by taking a triangle, decreasing the height and width by 1/2, creating 3 copies of the resulting triangle, and place them such each triangle touches the other two on a corner.  This process is repeated over and over again with the resulting triangles to produce the Sierpinski triangle, as illustrated below.

Write a program to generate a Sierpinski triangle.  You can use any method you want to generate the pattern, either by drawing the actual triangles, or by using a random algorithm to generate the picture.  You can draw in pixels, ascii art, or whatever you want, so long as the output looks similar to the last picture shown above.  Fewest characters wins.

HTML + JavaScript, 150 characters (see notes for 126 characters)

Whitespace inserted for readability and not counted.

<title></title><canvas></canvas><script>
for(x=k=128;x--;)for(y=k;y--;)
  x&y||document.body.firstChild.getContext("2d").fillRect(x-~y/2,k-y,1,1)
</script>

The core of it is applying the rule of coloring pixels for which x & y == 0 by the conditional x&y||, which produces a “Sierpinski right triangle”; and x-~y/2,k-y are a coordinate transformation to produce the approximately equilateral display.

A less correct (HTML-wise) version is 126 characters:

<canvas><script>
for(x=k=128;x--;)for(y=k;y--;)
  x&y||document.body.firstChild.getContext("2d").fillRect(x-~y/2,k-y,1,1)
</script>

(The way in which this is less correct is that it omits the title element and the end tag of the canvas element, both of which are required for a correct document even though omitting them does not change the interpretation of the document.)

Three characters can be saved by eliminating k in favor of the constant 64, at the cost of a smaller result; I wouldn't count the 8 option as it has insufficient detail.

Note that a size of 256 or higher requires attributes on the <canvas> to increase the canvas size from the default.


Tips for golfing in Haskell What general tips do you have for golfing in Haskell? I am looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Haskell. Please post only one tip per answer.

If you are new to golfing in Haskell, please have a look at the Guide to Golfing Rules in Haskell. There is also a dedicated Haskell chat room: Of Monads and Men.

Define infix operators instead of binary functions

This saves usually one or two spaces per definition or call.

0!(y:_)=y
x!(y:z)=(x-1)!z

vs.

f 0(y:_)=y
f x(y:z)=f(x-1)z

The available symbols for 1-byte operators are !, #, %, &, and ?. All other ASCII punctuation is either already defined as an operator by the Prelude (such as $) or has a special meaning in Haskell's syntax (such as @).

If you need more than five operators, you could use combinations of the above, such as !#, or certain Unicode punctuation characters, such as these (all 2 bytes in UTF-8):

¡ ¢ £ ¤ ¥ ¦ § ¨ © ¬ ® ¯ ° ± ´ ¶ · ¸ ¿ × ÷


Bijection between binary strings and pairs thereof Input: Either one or two strings consisting of '0's and '1's.  If there are 2, they are separated by a space. All strings are of length at least 1.
Output:

If a single input was given as input,  2 are output.
If 2 were input, 1 is output.

The output strings can be whatever you like, but if running your program with input A gives you B, then running it with B must give A (if inputting 111 11 gives 00000, then inputting 00000 must give 111 11).
That means if you pipe your program to itself, you should get back whatever you input.  If your program is called foo, you can test that like this:
>echo 101 101|foo|foo
101 101

To prevent the use of brute force techniques, your code should be able to run with 1000 digit strings in under 10 seconds.  My Python solution for this takes less than 1 second on 10000 digit strings so this shouldn't be a problem.
Shortest code wins.

Python, 183

Bijection is cached on disk.

x=raw_input()
try:d=eval(open('d').read())
except:d={'':'','1 ':'1 '}
t='1 '*not' 'in x
if x not in d:
 while t in d:t+=`(id(t)/9)%2`
 d[t]=x;d[x]=t
 open(*'dw').write(`d`)
print d[x]

edit: Oops, looks like this isn't the first smartassed answer.  Mine's consistent between runs!


Solve the (Rubiks) Pocket Cube Your task

.. is to do what Brian Fantana apparently couldn't do, and solve the 2x2x2 Rubik's Cube.

The Layout

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

E F   G H   I J   K L
M N   O P   Q R   S T

- -   U V   - -   - -
- -   W X   - -   - -

And will be given to you via stdin or the command line (your choice - please specify in your answer) in the format:

ABCDEFGHIJKLMNOPQRSTUVWX

Note that A-D make up the U-face(up), EFMN make up the L-face(left), GHOP make up the F-face(front),  IJQR make up the R-face(right), KLST make up the B-face(back), and U-X make up the D-face(down).

There will be six unique characters representing each color, but they may vary, so prepare for any combination of 6 ascii characters to be used for each color.

Specifications

Your code should output a solution using only the Right (R), Upper (U), and Front(F) faces, and should use the standard notation: R , R' , R2 , U , U' , U2 , F , F' , F2. You can find more info here. The restriction to the RUF subset is standard for the 2x2 cube (Hint: treat the bottom-back-left corner as a fixed base to work from).
Your code must be capable of solving all possible permutations of the pocket cube.
Each solution should take less than 30 seconds to complete.
Each solution should be less than 30 moves.
A bonus of -20% will be given for solutions always providing answers less than 20 moves (please advertise it in your answer so I can do a thorough check for it)
A bonus of -50% will be given for code which always provides an optimal solution. - Again, please advertise in your answer
Solutions must not contain two consecutive moves on the same face, because they can be easily combined into one move.
Solutions can optionally contain a single space - and only a single space - between each move.
The whole solution sequence, if necessary, may be contained in a pair of parentheses, quotation marks, braces, brackets, or carets, but no other extraneous output is allowed.
Please provide either a briefly commented version of your code or a thorough explanation of your code.
No use of external files. This includes internet, data tables, and libraries/packages made for this sort of problem.
Shortest code by byte count wins.
Winner chosen Wednesday (July 30, 2014).

Python 2.7: 544 bytes -50% = 272 bytes**

import sys;o=''.join;r=range;a=sys.argv[1];a=o([(' ',x)[x in a[12]+a[19]+a[22]] for x in a]);v={a:''};w={' '*4+(a[12]*2+' '*4+a[19]*2)*2+a[22]*4:''}
m=lambda a,k:o([a[([0x55a5498531bb9ac58d10a98a4788e0,0xbdab49ca307b9ac2916a4a0e608c02,0xbd9109ca233beac5a92233a842b420][k]>>5*i)%32] for i in r(24)])
def z(d,h):
 t={}
 for s in d[0]:
  if s in d[1]:print d[h][s]+d[1-h][s];exit()
  n=[d[0][s],'']
  for k in r(3):
   for j in r(3):s=m(s,k);t[s]=n[h]+'RUF'[k]+" 2'"[(j,2-j)[h]]+n[1-h]
   s=m(s,k)
 d[0]=t;return d
while 1:v,w=z([v,w],0);w,v=z([w,v],1)

Stackexchange replaces tabs with multiple whitespaces. So technical this version has 549 bytes. Just replace the first two spaces in the lines 6-10 with a tabulator.

Idea behind my program:
My first idea was a breath first search. But this took too long. Around 2 minutes for a hard (11 move optimal) scramble.
So I decided to approach the problem from both sides. I use two sets. I generate    sequentially all states with distance 1,2,3,... to the scramble and save them in set1, and at the same time all states with distance 1,2,3,... to the solved state and save them in set2.
The first time a state is in both sets, we found the solution.

For this I need the colors of the solved cube, which are not known. The characters 13, 20 and 23 define the left, back and down color. But these 3 colors are sufficient to represent the cube. I simply replace the other 3 colors with whitespaces and I can represent my solved state as '____ll____bbll____dddd'.

Oh, and for shortening the permutations I used an idea from https://codegolf.stackexchange.com/a/34651/29577

Ungolfed version:

import sys

#define permutations for R,U,F
permutation = [[0,7,2,15,4,5,6,21,16,8,3,11,12,13,14,23,17,9,1,19,20,18,22,10],
            [2,0,3,1,6,7,8,9,10,11,4,5,12,13,14,15,16,17,18,19,20,21,22,23],
            [0,1,13,5,4,20,14,6,2,9,10,11,12,21,15,7,3,17,18,19,16,8,22,23]]

def applyMove(state, move):
    return ''.join([state[i] for i in permutation[move]])

scramble = sys.argv[1]
#remove up,front,rigth colors
scramble = ''.join([(' ', x)[x in scramble[12]+scramble[19]+scramble[22]] for x in scramble])
solved = ' '*4+scramble[12]*2+' '*4+scramble[19]*2+scramble[12]*2+' '*4+scramble[19]*2+scramble[22]*4

dict1 = {scramble: ''} #stores states with dist 0,1,2,... from the scramble
dict2 = {solved: ''} #stores states with dist 0,1,2,... from the solved state

moveName = 'RUF'
turnName = " 2'"

for i in range(6):
    tmp = {}
    for state in dict1:
        if state in dict2:
            #solution found
            print dict1[state] + dict2[state]
            exit()
        moveString = dict1[state]
        #do all 9 moves
        for move in range(3):
            for turn in range(3):
                state = applyMove(state, move)
                tmp[state] = moveString + moveName[move] + turnName[turn]
            state = applyMove(state, move)
    dict1 = tmp
    tmp = {}
    for state in dict2:
        if state in dict1:
            #solution found
            print dict1[state] + dict2[state]
            exit()
        moveString = dict2[state]
        #do all 9 moves
        for move in range(3):
            for turn in range(3):
                state = applyMove(state, move)
                tmp[state] = moveName[move] + turnName[2 - turn] + moveString
            state = applyMove(state, move)
    dict2 = tmp

I'm pretty happy with the result, because I'm quite new to Python. This is one of my first python programs.

edit: half a year later: 427 - 50% = 213.5

Got a little bit more experience in Python and in golfing. So I revised my original code and could save more than 100 character.

import sys;o=''.join;a=sys.argv[1];d=[{o((' ',x)[x in a[12]+a[19]+a[22]]for x in a):[]},{' '*4+(a[12]*2+' '*4+a[19]*2)*2+a[22]*4:[]}]
for h in[0,1]*6:
 for s,x in d[h].items():
  for y in range(12):
   d[h][s]=x+[y-[1,-1,1,3][h*y%4]];
   if s in d[1-h]:print o('RUF'[x/4]+" 2'"[x%4]for x in d[0][s]+d[1][s][::-1]);exit()
   s=o(s[ord(c)-97]for c in'acahabcdnpbfegefhugiovjgqkciljdeklflmmmnnvoopxphrqdjrrbsstttuuqsviwwwkxx'[y/4::3])

I basically use the exact same approach. The biggest change is, that I don't define a function anymore. Instead of

def z(d,h):
 for s in d[0]:
  if s in d[1]:...
while 1:v,w=z([v,w],0);w,v=z([w,v],1)

I can do

for h in[0,1]*6:
 for s in d[h]:
  if s in d[1-h]:...

Also I changed the move lamda a little bit. First shortend, and then integrated the code directly, since the function call only appears once.

I keep for each state a list of numbers between 0 and 11, to represent the moves, instead of a string containing the moves. The numbers are converted at the very end.

Also I combined the two for-loops 'for k in r(3):for j in r(3): into one for y in r(12). Therefore I also have to do the moves U4, R4, F4. Of course such a move doesn't appear in the shortest solution, so " 2'"[x%4] works. (If x % 4 == 3, there would be a index out of range exception)

It's also a little bit faster, since I look for the entry in the second set earlier. About 0.5 second for a 11 move solution.


Find The Least Common Characters Given a string, find the 10 least common alpha-numeric characters within that string.

Output should be formatted with numbers left-padded with spaces so they look like this:

e:      1
t:     16
c:     42
b:    400
z:  50000
a: 100000

Use this to test your program: here

Output for test case:

j:  2
x:  3
q:  9
k: 32
v: 67
c: 73
w: 79
f: 93
b: 94
p: 96

Shortest code wins. You can submit a program or a function.

Mathematica, 102 93:

v2:

  Grid[SortBy[
             Tally@StringCases[ToLowerCase@#,x_?LetterQ:>x<>":"],
              Last@# &],
      Alignment->Right]&@s

v1:

TableForm[
         SortBy[Tally@StringCases[ToLowerCase@#, x_?LetterQ :> x <> ":"],
                #[[2]] &],
         TableAlignments -> Right] &


Print the previous answer in reverse - with a catch (pt. 2) Your challenge is very simple: output the previous answer, in reverse.
However, as with this similarly-titled question, there's a catch: in this case, you cannot use characters from the answer before the last. For example:
Let's say the first answer looks like this:

1 - Python
print('hi!')

And the second answer looks like this: (see 'Chaining' section for more info)

2 - Javascript
console.log(")'!ih'(tnirp")

Now, it would be my job to write the third answer: a program to output the text )"print('hi!')"(gol.elosnoc, without using the characters p, r, i, n, t, (, ', h, i, ! and ). I can choose whatever language I like to complete this task.
Chaining
The first answer can output any text: but it must output something. The second answer should simply output the first answer in reverse, using any characters you like. The further rules about restricted characters, as described above, come into play from the third answer onwards.
Scoring
Your score is \$\frac{l_{n}}{l_{n-1}} - l_{n-2}\$, where \$l_x\$ represents the length of the \$x\$th answer, and \$n\$ is the position your answer is at in the chain. (all lengths are in bytes; if your answer is no. 1 or no. 2 then miss out \$l_{n-1}\$ and/or \$l_{n-2}\$ where necessary.)
Best (lowest) score by August 1st wins.
Formatting
Please format your post like this:
[Answer Number] - [language]

    [code]
    (preferably a TIO link)

SCORE: [Submission Score]

(notes, explanations, whatever you want)

Everything in square brackets is a required argument to fill in; everything in normal brackets is an optional argument; everything not in brackets is there to make the snippet work.
Rules

All characters, etc. are case sensitive.
Preceeding/trailing whitespace is allowed, within reason (I'm looking at you, Whitespace).
Every submission must be a unique language.
You must wait at least 1 hour before submitting a new answer if you have just posted.
You may NOT submit two answers in a row, you must wait for TWO more submissions before posting a new answer.
Of course, standard loopholes are disallowed.
Please make sure to triple check that your answer is valid. This is especially important, because someone may start writing their answer based on yours, so if it's wrong you can't really edit it any more... and the whole chain breaks down. Also, you can't edit answers for continuity purposes.
Standard I/O methods are allowed.

Answer list/used languages

$.ajax({type: "GET",url: "https://api.stackexchange.com/2.2/questions/187674/answers?site=codegolf&filter=withbody&sort=creation&order=asc",success: function(data) {for (var i = 0; i < data.items.length; i++) {var temp = document.createElement('p');temp.innerHTML = data.items[i].body.split("\n")[0];try {temp.innerHTML += " - Score: " +data.items[i].body.split("SCORE")[1].split("\n")[0].match(/(?<!h)[+-]?(\d+(\.\d+)?)/g).slice(-1)[0].trim() +"";} catch (TypeError) {temp.innerHTML += " (no score)";} finally {$('#list').append('
' + temp.innerText || temp.textContent + '');}}}})

   <base href="https://codegolf.stackexchange.com">

1 - 05AB1E

"Hello, World!"

SCORE: \$\frac{15}{1} - 0 = 15\$

Try it online!


Hell0 W0rld! scored by ASCII values Write a program that outputs Hell0 W0rld!.  It must match this output exactly, including capitalization, zeroes instead of o's, exactly one space, etc.  Trailing new lines are allowed.

Lowest score wins.  Scoring is based on the sum of the values of each character in the language's code page - otherwise Unicode values should be used.  New lines are treated as spaces.

Here are a few example scores:

abc //Score: 294

print(Hell0 W0rld!) //Score: 1597

//Score: 1454
multi
line
code

You can check your ASCII score by inputting your code here.  You can view individual ASCII values here.

Lenguage, score 0
Well, this is quite boring and obvious, but it seems to achieve the perfect score (assuming I understand the challenge correctly). To fix this loophole, you should probably add the program's length to the sum of the code points; I'm pretty sure that won't break the relative order of the current answers.
The program is
2282524454641945458940768311481012240407465625061984267694778013056442426959468031225640633070772676474431950201473533908

null bytes. Fortunately, 0 multiplied by the number above is still 0.
I believe this decompresses (alternatively, it compresses) to the automatically generated (with the help of a random web page that claims "Original Java program not from me") brainfuck program:
-[------->+<]>-.-[->+++++<]>++.+++++++..[-->+<]>------.[--->++<]>.---[->+++<]>.+[-->+<]>++++.[----->+<]>++.------.--------.-[--->+<]>.

It almost certainly could be golfed (but I haven't tried), but that is unnecessary.


Make the most useful program within 100 characters In this task, you are allowed make an useful program to do anything you can write within 100 characters. You are allowed to use less characters, but not more.

Rules, just to protect from standard loopholes that are no longer funny:

Your program cannot access the internet, unless it really has to. For example, the program which shows the most upvoted question on this website may use the Internet to check this question. However, it's not allowed to browse the Internet in order to find its real source and run it.
Your program cannot be an interpreter for the language it was written in. However, Brainfuck interpreter in non-Brainfuck language would be fine.
Your program cannot execute external programs that does exactly what your program does. For example, you cannot run vim, and claim that your program is vim implementation.
Your program cannot be dangerous for the computer it's being ran on and other computers. You aren't allowed to write program like rmdir / (the example here intentionally doesn't work, don't fix it), and claim it's an useful program to remove all files on the computer.
Your program may be as slow as you want, and use as much resources as you want, as long you can prove it does what it meant to do.
You aren't allowed to make language specifically for this task. However, you are allowed to make interpreter for your invented language in some other programming language.

C - 47 bytes

The following program outputs every document ever written in human history, along with every document that will ever be written and loads of interesting texts that no human will ever come up with (along with a "little bit" of garbage in between). Just give it some time. Moreover, every time you run it, it will output different texts first! If that's not useful! (And all of that within half the character limit!)

main(){srand(time(0));while(1)putchar(rand());}

If you don't care about it outputting something else each time, you only need 41 bytes!

main(){srand(0);while(1)putchar(rand());}

Not quite C99 conform, but it compiles smoothly with gcc.exe (GCC) 4.7.0 20111220.

The rules state

  Your program may be as slow as you want, and use as much resources as you want, as long you can prove it does what it meant to do.

No problem.

Some things, this program will output:

a solution to every Millennium Problem
tomorrow's newspaper articles
the complete works of Shakespeare's (of course)
your darkest secret
all the other answers to this question

   Not really, because (as ace correctly mentioned in the comment), rand() is only a pseudo-random generator, that will wrap around at some point - probably way too early to produce a lot of meaningful texts. But I doubt that getting data from a true (hardware) random number generator is remotely possible within 100 characters. I'll leave this here for the fun of it, though.

As Dennis notes, the randomness of the the algorithm, could be somewhat improved (within the character limit), by using rand()^rand()>>16 instead of rand().


Compare four integers, return word based on maximum This function should take four integer inputs (a,b,c,d) and return a binary word based on which values equal the maximum of the four.

The return value will be between 1 and 0xF.

For example:

a = 6, b = 77, c = 1, d = 4

returns 2 (binary 0010; only 2nd-least significant bit is set corresponding to b being sole max value)

a = 4, b = 5, c = 10, d = 10

returns 0xC (binary 1100; 3rd- and 4th-least significant bits set corresponding to c and d equaling max value)

a = 1, b = 1, c = 1, d = 1

returns 0xF (binary 1111; all four bits set because all values equal the max)

Here is a simple implementation:

int getWord(int a, int b, int c, int d)
{
    int max = a;
    int word = 1;
    if (b > max)
    {
        max = b;
        word = 2;
    }
    else if (b == max)
    {
        word |= 2;
    }
    if (c > max)
    {
        max = c;
        word = 4;
    }
    else if (c == max)
    {
        word |= 4;
    }
    if (d > max)
    {
        word = 8;
    }
    else if (d == max)
    {
        word |= 8;
    }
    return word;
}

return value can be string of 0's and 1's, bool / bit vector, or integer

Jelly, 2 bytes

Takes input as [d,c,b,a]. Returns a list of Booleans.

Ṁ=

Try it online!

Ṁ Maximum

= equal to (implies the other argument is the original argument; vectorises)


Golf String's format() inverse Invert the Format method.

The Format method of the String class (or equivallent, such as sprintf) is available in most languages. It basically takes a "Format" string which may contain placeholders with some extra formatting, and zero or more values to be inserted instead of those placeholders.

Your task is to implement the inverse function in your language of choice.

API

Method name should be either format1 or deformat.

Input: 1st parameter will be the "Format" string, just like in the original format method. 2nd parameter will be the parsed string (see examples below). No other parameters are needed nor allowed.

Output: an array (or your language-of-choice's equivalent) of values that were extracted correspondingly with the placeholders in the format.

The placeholders are {0}, {1}, {2}, etc.

In case of bad format you may throw an error, or return whatever you like.

In case of invalid input, you may throw an error, or return whatever you like. Invalid input is such that cannot be generated by String.Format using same format string, for example: '{0}{0}', 'AAB'.

Examples

deformat('{0} {1}', 'hello world') => ['hello', 'world']
deformat('http{0}://', 'https://') => ['s']
deformat('http{0}://', 'http://') => [''] // array of one item which is an empty string
deformat('{0}{1}{0}', 'ABBA') => ['A', 'BB']

Ambiguity

In case of ambiguity you may return any suitable answer. For example:

deformat('{0} {1}', 'Edsger W. Dijkstra')
// both ['Edsger', 'W. Dijkstra'] and ['Edsger W.', 'Dijkstra'] are applicable.

Some More Rules

To make it easier, there's no need to actually support formatting. You can forget all about leading zeros, decimal point or rounding issues. Just generate the values as strings.
To make it non-trivial, Regular Expressions are not allowed.
You don't need to take care of curly braces in input (i.e. 2nd input parameter will not contain any {s or }s).

Winning

This is code-golf! (should be read as "This is Sparta!") the correct function having shortest length wins. Standard loopholes are forbidden.

Haskell, 220 characters

import Data.Map;f""""=[empty]
f('{':b)d=[insert k m b|(k,('}':a))<-lex b,(m,c)<-[splitAt n d|n<-[0..length d]],b<-f a c,notMember k b||b!k==m]
f(x:b)(y:d)|x==y=f b d;f _ _=[];format1 x y=elems$mapKeys((0+).read)$f x y!!0

Breaks if you use multiple representations for the same pattern ({1} vs {01}) - doesn't enforce their equality, discarding matches for all but one representation instead.

19 characters can be saved by omiting mapKeys((0+).read)$ if proper ordering of matches above 10 patterns doesn't matter, or if padding to the same length may be required, or if string ordering of patterns is acceptable. In any case, if a pattern is omitted from the first argument, it is omitted from the result as well.

Removing !!0 from the end makes format1 return the list of all solutions, rather than just the first one.

before golfing:

import Data.Map
import Control.Monad

cuts :: [a] -> [([a],[a])]
cuts a=[splitAt n a | n <- [0..length a]]

f :: String -> String -> [Map String String]
-- empty format + empty parsed = one interpretation with no binding
f "" "" = [empty]
-- template-start format + some matched = branch search
f ('{':xs) ys = do
    let [(key, '}':xr)] = lex xs
    (match, yr) <- cuts ys
    b <- f xr yr
    guard $ notMember key b || b!key == match
    return $ insert key match b
-- non-empty format + matching parsed = exact match
f (x:xs) (y:ys) | x == y = f xs ys
-- anything else = no interpretation
f _ _ = []

deformat :: String -> String -> [String]
deformat x y = elems $ mapKeys ((0+).read) $ head $ f x y


Draw a regular polygon The goal of this code golf is to draw a regular polygon (one with equal side lengths) given the number of sides and radius (distance from center to vertex).

The number of sides and the radius can be entered via a file, STDIN, or just a plain old variable. Use whatever is shorter in your language.
-25% of total characters/bytes if the image is actually drawn instead of ASCII art.

LOGO 37 - 25% = 27.75 (with variables)

REPEAT:S[FD:R*2*sin(180/:S)RT 360/:S]

LOGO 49 - 25% = 36.75 (as a function)

TO P:R:S REPEAT:S[FD:R*2*sin(180/:S)RT 360/:S]END

Triangle

Called with variables

Make "R 100
Make "S 3
REPEAT:S[FD:R*2*sin(180/:S)RT 360/:S]

Used as a function P 100 3

Square

Called with variables

Make "R 100
Make "S 4
REPEAT:S[FD:R*2*sin(180/:S)RT 360/:S]

Used as a function P 100 4

Pentagon

Called with variables

Make "R 100
Make "S 5
REPEAT:S[FD:R*2*sin(180/:S)RT 360/:S]

Used as a function P 100 5

Decagon

Called with variables

Make "R 100
Make "S 10
REPEAT:S[FD:R*2*sin(180/:S)RT 360/:S]

Used as a function P 100 10

Circle

Called with variables

Make "R 100
Make "S 360
REPEAT:S[FD:R*2*sin(180/:S)RT 360/:S]

Used as a function P 100 360


Code Golfing Split String in Bash Let us play a little golfing game.
Given a single line of N space separated numbers from STDIN, one must output those numbers on N lines.

So far, I came up with the three following bash solutions :

xargs -n1 (9)
tr \ \\n (8)
fmt -1 (6)

Can anyone do better? I am eager to learn new tricks

Bash (22)

read X;printf %d\\n $X  (thanks to manatwork but without literal NL)

30 read -aX;printf "%d\n" ${X[*]}
26 read X;echo -e ${X// /\n}
28 printf "%d\n" $(</dev/stdin)
27 printf "%d\n" $(</dev/fd/0)
26 printf %d\n $(</dev/fd/0)
23 read X;printf "%d\n" $X


Compact coding of integer into bitstring I want to compactly code positive integers x into bits, in a manner allowing decoding back into the original integers for a stateless decoder knowing the maximum value m of each x; it shall be possible to uniquely decode the concatenation of encodings, as is the case in Huffman coding.
[The above introduction motivates the rest, but is not part of the formal definition]

Notation: for any non-negative integer i, let n(i) be the number of bits necessary to represent i in binary; that is the smallest non-negative integer k such that i>>k == 0

  i :   0   1   2   3   4   5   6   7   8   9   10  11  12  13  14  15  16  17  18  ..
n(i):   0   1   2   2   3   3   3   3   4   4   4   4   4   4   4   4   5   5   5   ..

I want a function F(x,m) defined for 0<x and x<=m, with output a string of '0' or '1', having these properties:

F(x,m) has length less than 2*n(x) or 2*n(m)-1, whichever is smaller.
If x<y then:

F(x,m) is no longer than F(y,m);
F(x,m) and F(y,m) differ at some position over the length of F(x,m);
there's a 0 in F(x,m) at the first such position.

When for a certain m properties 1 and 2 do not uniquely define F(x,m) for all positive x at most m, we reject any encoding giving a longer F(x,m) than some otherwise acceptable encoding, for the smallest x for which the length do not match.

Note: In the above, implicitly, 0<x, 0<y, 0<m, x<=m, and y<=m, so that F(x,m) and F(y,m) are defined.

It is asked the shortest program that, given any x and m meeting the above constraints and up to 9 decimal digits, outputs an F(x,m) consistent with the above rules. The following C framework (or its equivalent in other languages) is not counted:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define C(c) putchar((c)?'1':'0') // output '0' or '1'
#define S(s) fputs((s),stdout)    // output a string
typedef unsigned long t;          // at least 32 bits
void F(t x,t m);                  // prototype for F
int main(int argc,char *argv[]){
 if(argc==3)F((t)atol(argv[1]),(t)atol(argv[2]));
 return 0;}
void F(t x,t m) {   // counting starts on next line
}                   // counting ends before this line

Comment: Property 1 aggressively bounds the encoded length; property 2 formalizes that unambiguous decoding is possible, and canonicalizes the encoding; I assert (without proof) this is enough to uniquely define the output of F when m+1 is a power of two, and that property 3 is enough to uniquely define F for other m.

Here is a partial table (handmade; the first version posted was riddled with errors, sorry):

  x     :   1       2       3       4       5       6       7       8       9       10      11      12      13      14      15
F(x,1)  : empty
F(x,2)  :   0       1
F(x,3)  :   0       10      11
F(x,4)  :   0       10      110     111
F(x,5)  :   0       10      110     1110    1111
F(x,6)  :   0       100     101     110     1110    1111
F(x,7)  :   0       100     101     1100    1101    1110    1111
F(x,8)  :   0       100     101     110     11100   11101   11110   11111

F(x,15) :   0       100     101     11000   11001   11010   11011   111000  111001  111010  111011  111100  111101  111110  111111


Write a self-replicating program. Write a simple program that copies itself when executed.

Your program should be some kind of executable file on Windows, Linux, etc.., should generate new executable file, which is identical to your original executable file, with random name, and quits.

Your program shouldn't involve any kind of file reading or copying. Only file writing for generating new executable file is permitted.

(PS. I was quite embarrassed when at Wikipedia, Self-replicating program redirects to Computer virus article... :/...)

Smallest executable file size wins. Your answer may be a programming code with proper OS & compiler, assembly code, or HEX dump of a executable file.

Assembly for x86 Linux, 106 bytes

BITS 32
                org     0x2E620000
                db      0x7F, "ELF", 1, 1, 1, 0 ; e_ident
                dd      0, 0
                dw      2                       ; e_type
                dw      3                       ; e_machine
                dd      1                       ; e_version
                dd      _start                  ; e_entry
                dd      phdr - $$               ; e_phoff
                dd      0                       ; e_shoff
                dd      0                       ; e_flags
                dw      0x34                    ; e_ehsize
                dw      0x20                    ; e_phentsize
phdr:           dd      1                       ; e_phnum       ; p_type
                                                ; e_shentsize
                dd      0                       ; e_shnum       ; p_offset
                                                ; e_shstrndx
                dd      $$                                      ; p_vaddr
fname           equ     $ - 2
                db      'out', 0                                ; p_paddr
                dd      filesize                                ; p_filesz
                dd      filesize                                ; p_memsz
                dd      5                                       ; p_flags
                dd      0x1000                                  ; p_align
_start:         mov     al, 5                   ; 5 = open syscall
                mov     ebx, fname
                mov     cl, 65                  ; 65 = O_WRONLY | O_CREAT
                mov     dx, 666q
                int     0x80
                lea     edx, [byte ecx + filesize - 65]
                xchg    eax, ebx
                xchg    eax, ecx
                mov     cl, 0
                mov     al, 4                   ; 4 = write syscall
                int     0x80
                mov     al, 1                   ; 1 = exit syscall
                int     0x80
filesize        equ     $ - $$

This is for the nasm assembler. Build the binary with the command line: nasm -f bin -o a.out selfrep.asm && chmod +x a.out

Here's the same file as a hex dump: 7F 45 4C 46 01 01 01 00 00 00 00 00 00 00 00 00 02 00 03 00 01 00 00 00 4C 00 62 2E 2C 00 00 00 00 00 00 00 00 00 00 00 34 00 20 00 01 00 00 00 00 00 00 00 00 00 62 2E 6F 75 74 00 6A 00 00 00 6A 00 00 00 05 00 00 00 00 10 00 00 B0 05 BB 36 00 62 2E B1 41 66 BA B6 01 CD 80 8D 51 29 93 91 B1 00 B0 04 CD 80 B0 01 CD 80

As requested, the program copies itself to a separate file. (The program could have been significantly shorter if it had been allowed to just write to stdout and let the user redirect to a file.)

I avoided using any borderline tricks to reduce the size. This should be a fully conformant 32-bit ELF binary.

Edited to add: In the above version the created file is just a plain file, but it occurs to me that for a couple of bytes (and a tiny bend of the rules), you can create something a little more interesting. This version is only two bytes longer, at 108 bytes:

BITS 32
                org     0x00010000
                db      0x7F, "ELF", 1, 1, 1, 0 ; e_ident
                dd      0, 0
                dw      2                       ; e_type
                dw      3                       ; e_machine
                dd      1                       ; e_version
                dd      _start                  ; e_entry
                dd      phdr - $$               ; e_phoff
                dd      0                       ; e_shoff
                dd      0                       ; e_flags
                dw      0x34                    ; e_ehsize
                dw      0x20                    ; e_phentsize
phdr:           dd      1                       ; e_phnum       ; p_type
                                                ; e_shentsize
                dd      0                       ; e_shnum       ; p_offset
                                                ; e_shstrndx
                dd      $$                                      ; p_vaddr
fname:          db      'asr', 0                                ; p_paddr
                dd      filesize                                ; p_filesz
                dd      filesize                                ; p_memsz
                dd      7                                       ; p_flags
                dd      0x1000                                  ; p_align
_start:         mov     al, 5                   ; 5 = open syscall
                mov     ebx, fname
                inc     byte [ebx]
                mov     cl, 65                  ; 65 = O_WRONLY | O_CREAT
                mov     dx, 777q
                int     0x80
                lea     edx, [byte ecx + filesize - 65]
                xchg    eax, ebx
                xchg    eax, ecx
                mov     cl, 0
                mov     al, 4                   ; 4 = write syscall
                int     0x80
                mov     al, 1                   ; 1 = exit syscall
                int     0x80
filesize        equ     $ - $$

Name this version asr, for "a self-replicator": nasm -f bin -o asr asr.asm && chmod +x asr

Hex dump version for the nasm-impaired:
7F 45 4C 46 01 01 01 00 00 00 00 00 00 00 00 00 02 00 03 00 01 00 00 00 4C 00 01 00 2C 00 00 00 00 00 00 00 00 00 00 00 34 00 20 00 01 00 00 00 00 00 00 00 00 00 01 00 61 73 72 00 6C 00 00 00 6C 00 00 00 07 00 00 00 00 10 00 00 B0 05 BB 38 00 01 00 FE 03 B1 41 66 BA FF 01 CD 80 8D 51 2B 93 91 B1 00 B0 04 CD 80 B0 01 CD 80

When you run it, it creates an almost-identical file named bsr, but one that is itself executable. Running it will create another binary file named csr. And so on.

(Note that annoying things start to happen after zsr. I considered making a version that would cascade the name change to atr and so on, but I think most people will get bored well before then, so it probably isn't worth all the extra bytes.)


Is this a Hardy-Ramanujan-Number-ish Harshad Number? Background
The number 1729 is the Hardy-Ramanujan number. An amazing property of it was discovered by S. Ramanujan (who is widely regarded as the greatest Indian mathematician1), when G.H. Hardy paid a visit to him in a hospital. In Hardy's own words:

I remember once going to see him when he was ill at Putney. I had ridden in taxi cab number 1729 and remarked that the number seemed to me rather a dull one, and that I hoped it was not an unfavorable omen. "No," he replied, "it is a very interesting number; it is the smallest number expressible as the sum of two cubes in two different ways."

Besides that, it has many other amazing properties. One such property is that it's a Harshad Number, i.e the sum of its digits (1+7+2+9=19) is a factor of it. That too, a special one. As Masahiko Fujiwara showed, 1729 is a positive integer which, when its digits are added together, produces a sum which, when multiplied by its reversal, yields the original number:
1+7+2+9 = 19
19 × 91 = 1729
A positive integer having such property is what I define as Hardy-Ramanujan-ish Harshad Number, for the purpose of this post. (There might be a technical term for it, but I couldn't find it, unless it's member of A110921)

The Task
Given a positive integer n as input, output a truthy or falsey value based on whether the input n is a Hardy-Ramanujan-ish Harshad Number. Output truthy, if it is. Otherwise, output falsey.
Note that only four Hardy-Ramanujan-ish Harshad Numbers exist (1,81,1458 and 1729), and you can write code which checks for equivalence with them. But I don't think that will be fun.

Input
Your program should take a positive integer (a natural number, in other words). It may take it in any way except assuming it to be present in a variable. Reading from modal window, input box, command line, file etc. is allowed. Taking input as function argument is allowed as well.

Output
Your program should output a truthy or falsey value. They need not be consistent. Your program may output in any way except writing the output to a variable. Writing to screen, command line, file etc. is allowed. Outputting with function return is allowed as well.

Additional Rules

You must not use a built-in to accomplish the task (I wonder any language will have such built-in, but then Mathematica...)

Standard Loopholes apply.

Test Cases
Input        Output
1            Truthy (because 1 × 1 (reverse of 1) = 1)
2            Falsey
3            Falsey
4            Falsey
5            Falsey
81           Truthy (because 9 (8 + 1) × 9 (reverse of 9) = 81)
1458         Truthy (because 18 (1 + 4 + 5 + 8) × 81 (reverse of 18) = 1458)
1729         Truthy (because 19 (1 + 7 + 2 + 9) × 91 (reverse of 19) = 1729)
1730         Falsey
2017         Falsey

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

1Every year, on 22nd December, the birthday of Srinivasa Ramanujan, National Mathematics Day is observed in India. His colleagues, those in Cambridge, compared him to Jacobi, Euler, and even Newton. Besides being so great, he had almost no formal training in Pure Mathematics, but still, he made important contributions to mathematical analysis, number theory, infinite series, and continued fractions. Unfortunately, he died at an early age of 32 with thousands of mathematical discoveries in his mind. A film was also made on him, which was based on his biography, The Man Who Knew Infinity.

ArnoldC, 888 Bytes

IT'S SHOWTIME
HEY CHRISTMAS TREE i
YOU SET US UP 0
GET YOUR ASS TO MARS i
DO IT NOW
I WANT TO ASK YOU A BUNCH OF QUESTIONS AND I WANT TO HAVE THEM ANSWERED IMMEDIATELY
HEY CHRISTMAS TREE a
YOU SET US UP 0
GET TO THE CHOPPER a
HERE IS MY INVITATION 1
YOU ARE NOT YOU YOU ARE ME i
ENOUGH TALK
HEY CHRISTMAS TREE b
YOU SET US UP 0
GET TO THE CHOPPER b
HERE IS MY INVITATION 81
YOU ARE NOT YOU YOU ARE ME i
ENOUGH TALK
HEY CHRISTMAS TREE c
YOU SET US UP 0
GET TO THE CHOPPER c
HERE IS MY INVITATION 1458
YOU ARE NOT YOU YOU ARE ME i
ENOUGH TALK
HEY CHRISTMAS TREE d
YOU SET US UP 0
GET TO THE CHOPPER d
HERE IS MY INVITATION 1729
YOU ARE NOT YOU YOU ARE ME i
ENOUGH TALK
HEY CHRISTMAS TREE res
YOU SET US UP 0
GET TO THE CHOPPER res
HERE IS MY INVITATION a
CONSIDER THAT A DIVORCE b
CONSIDER THAT A DIVORCE c
CONSIDER THAT A DIVORCE d
ENOUGH TALK
TALK TO THE HAND res
YOU HAVE BEEN TERMINATED

I know, I just check for equality, but that shouldn't be the fun part of the program.

Enjoy reading it. :)

Added some newlines there for easier readability:

Try it online


The dot is chasing me! Your Task
Write a program that displays a dot that moves toward the position of your mouse at 4 pixels per second. The dot must be 100 pixels big and the window must fill the computer screen.
Input
None
Output
A window showing an animated dot moving towards the mouse at a fixed, non-changing speed.
Scoring
This is code-golf, so the shortest code in bytes wins.

HTML + JavaScript, 140 bytes

Infinite speed

t=c.getContext`2d`
c.onmousemove=e=>(x=e.clientX,y=e.clientY)
setInterval(_=>t.clearRect(0,0,1e5,1e5)||t.fillRect(x,y,10,10),9)
<canvas id=c>

Non-cheaty, 188 bytes

x=y=0,t=c.getContext`2d`
c.onmousemove=e=>(z=e.pageX,w=e.pageY)
f=_=>t.clearRect(0,0,1e5,1e5)||(m=((a=z-x)**2+(b=w-y)**2)**.5)|t.fillRect(x+=a/m,y+=b/m,10,10)
setInterval(f,9)
<canvas id=c>

Larger and faster:

x=y=0,s=3,t=c.getContext`2d`
c.onmousemove=e=>(z=e.pageX,w=e.pageY)
f=_=>t.clearRect(0,0,1e5,1e5)||(m=((a=z-x)**2+(b=w-y)**2)**.5)|t.fillRect(x+=s*a/m,y+=s*b/m,10,10)
setInterval(f,9)
<canvas id=c height=999 width=999>


Build a Twitter-quine A short while, ago, @daniel_ernston sent the following challenge to @StackCodeGolf on Twitter:

  @StackCodeGolf Your task is to build a program that uses the API of your choice to tweet its own source code. Shortest code wins, of course.

JavaScript, 38 characters

window.open("http://tinyurl.com/erjk34");

Here is the tweet, in all its glory: https://twitter.com/kevinaworkman/status/575425948562014209

And here is my previous entry at 95 characters:

function q() {
window.open("https://twitter.com/intent/tweet?text="+encodeURIComponent(q+";{q();}"));
};{q();}

And if that's not cheating...

HTML, 22 characters

http://tinyurl.com/erjk35


Best place for learning GolfScript? It looks like a fun language, but the official site is down and the EsoLangs page doesn't explain it quite well and looks like it's missing stuff. Is there anywhere that the language is documented?

A cached copy of the offical site is available on the Internet Archive's Way Back Machine.


Turn an Array into a Math Problem Given a nonempty list of nonnegative integers, consider rewriting it as an arithmetic problem where:

A plus sign (+) is inserted between pairs of numbers that increase from left to right (a.k.a. from the start of the list to the end).
A minus sign (-) is inserted between pairs of numbers that decrease from left to right.
A multiplication sign (*) is inserted between pairs of numbers that are equal.

Said another way: any sublist a,b becomes a+b if a<b, a-b if  a>b, and a*b if a==b.

For example, the list

[12, 0, 7, 7, 29, 10, 2, 2, 1]

would become the expression

12 - 0 + 7*7 + 29 - 10 - 2*2 - 1

which evaluates to 75.

Write a program or function that takes in such a list and evaluates it, printing or returning the result.

Order of operations matters. Multiplications should be done before any addition or subtraction.
If the input list has one number, that should be what it evaluates to. e.g. [64] should give 64.
Use of eval or exec or similar constructs is allowed.

Here are some additional examples:

[list]
expression
value

[0]
0
0

[1]
1
1

[78557]
78557
78557

[0,0]
0*0
0

[1,1]
1*1
1

[2,2]
2*2
4

[0,1]
0+1
1

[1,0]
1-0
1

[1,2]
1+2
3

[2,1]
2-1
1

[15,4,4]
15-4*4
-1

[9,8,1]
9-8-1
0

[4,2,2,4]
4-2*2+4
4

[10,9,9,12]
10-9*9+12
-59

[1,1,2,2,3,3]
1*1+2*2+3*3
14

[5,5,4,4,3,3]
5*5-4*4-3*3
0

[3,1,4,1,5,9,2,6,5,3,5,9]
3-1+4-1+5+9-2+6-5-3+5+9
29

[7637,388,389,388,387,12,0,0,34,35,35,27,27,2]
7637-388+389-388-387-12-0*0+34+35*35-27*27-2
7379

The shortest code in bytes wins. Tiebreaker is earlier answer.

Python 2, 63 bytes

p=s='print-'
for x in input():s+='*+-'[cmp(x,p)]+`x`;p=x
exec s

Constructs and evals the expression string. The arithmetic symbol is chosen by comparing the previous number p to the current one x. The symbol is appended followed by the current number.
The first number is handled with a clever trick from Sp3000. The initial value of p is set to a string, which is bigger than any number and therefore causes a - before the first number. But, s is initialized to print- at the same time that makes the result start with print-- (thanks to xsot for saving 2 bytes by initializing with print.)


Walking on the Hypercube I recently read up on graph theory, especially hypercubes and thought about interesting ways to construct paths on them. Here's what I came up with.
As you might know, you can construct an n-dimensional hypercube by taking all n-tuples consisting of 1 and 0 as vertices and connect them, iff they differ in one digit. If you interpret these binary digits as an integer number, you end up with a graph with nicely numerated vertices. For example for n=3:

Let's say you want to take a walk on this hypercube and start at the vertex 0. Now, how do you determine which vertex you want to visit next? The rule I came up with is to take the number a of the vertex you are on, flip its mod(a,n)s bit (zero-based indexing) and go to the resulting vertex.
Formally this rule can be recursively defined as
a[m+1] = xor(a[m], 2^mod(a[m],n)).

By following this rule, you will always stay on the cube and travel along the edges. The resulting path looks like this

As you can see, you will walk in a circle! In fact, in all dimensions and for all starting points your path will end up in a loop. For example for n=14 and a[0]=0 it looks like this

For the avid ambler, the length of his planned route is quite a crucial information. So, your job is to write a function or a program that takes the hypercube dimension n an the starting vertex a[0] as inputs and output the number of vertices in the resulting loop.
Test cases
n   a[0]   Output
-----------------
3   0      6
14  0      50
5   6      8
17  3      346

Rules

Standard loopholes are forbidden
Output/Input may be in any suitable format
You may assume a[0] to be a valid vertex

Scoring
Shortest code in bytes wins.
If you have any additional information on this topic, I'd be glad to hear!

Jelly, 9 bytes
%⁴2*^µÐḶL

Takes two command-line arguments.
%⁴2*^µÐḶL        A monadic link. Inputs: a_0. b also taken from command line.
%⁴2*^              Variadic link. Input: a
%⁴                   a modulo b. ⁴ is second input, b.
  2*                 Get 2 to that power
    ^                and bitwise xor with a.
     µ             Start a new, monadic link (input: a_0)
      ÐḶ             All elements of the cycle created when the preceding link
                     is applied repeatedly, starting with a_0.
        L            Length.

Try it here.


Final Fantasy XV UNCOVERED! Since I am INSANELY hyped for the Final Fantasy XV Uncovered event, I want you to write me a program to tell me when it is!!!

The input

Your take input in the form of HH:MM XDT, where HH is a number in the range 1-12, MM is a number between 0-60, and XDT is a time zone, with X being one of E (eastern, UTC-4), C (central, UTC-5), P (pacific, UTC-7), or M (mountain, UTC-6). This is a time assumed to be PM. Valid inputs include:

1:00 EDT (1 PM Eastern Daylight Time)
4:05 MDT (4:05 PM Mountain Daylight Time)
12:23 PDT (12:23 PM Pacific Daylight Time)
1:10 CDT (1:10 PM Central Daylight Time)

The input may be assumed to be valid.

The output

Your program must do the following:

Convert the given time to PDT and output It is XX:XX PM PDT., where XX:XX is the converted time. Note that you do not need to handle any case where converting the time would cross the AM/PM boundary.
Print one of the following:

If the converted time is before 6:00 PM PDT, print X minutes until the pre-show!, replacing X with the number of minutes until 6:00 PM PDT.
If the converted time is after or equal to 6:00 PM PDT and before 7:00 PM PDT, print Pre-show started X minutes ago; UNCOVERED is starting in Y minutes!, where X is the number of minutes that have passed since 6:00 PM PDT, and Y is the number of minutes until 7:00 PM PDT.
If the converted time is after or equal to 7:00 PM PDT, print UNCOVERED started X minutes ago!, where X is the number of minutes that have passed since 7:00 PM PDT.

Each string printed must be followed by a newline.

Scoring

This is code golf, so the shortest program wins.

Python (335 bytes)

t=raw_input().replace(*': ').split();x='PMCE'.index(t[2][0]);t[0]=int(t[0])+x;print '%s:%s PM PDT' % tuple(t[:1]);x=t[0]*60+int(t[1]);print ['%s minutes until the pre-show!'%(360-x),'Pre-show started %s minutes ago; UNCOVERED is starting in %s minutes!'%((x-360),(420-x)), 'UNCOVERED started %s minutes ago!'%(x-420)][(x>360)+(x>420)]

Output:

1:00 MDT
2:00 PM PDT
240 minutes until the pre-show!

6:00 CDT
8:00 PM PDT
UNCOVERED started 60 minutes ago!

6:50 PDT
6:50 PM PDT
Pre-show started 50 minutes ago; UNCOVERED is starting in 10 minutes!


Check the validity of a 10-digit telephone number Your task is to write a program or function that checks if a string is a valid phone number.

Given a string (or list of characters/codepoints) input, you will output a truthy value if the input is a valid phone number. If it is not, output a falsey value. An input string is considered a valid phone number for this challenge if it meets all of these criteria:

It contains ten digits, which are grouped like this: ###-###-####
The strings separating the digit groups must be the same
The first and last characters must be part of the phone number (i.e. must not be part of a separator)

Test cases:

111-222-3333     truthy
123-456-7890     truthy (number groups can contain different numbers)
1112223333       truthy (can have 0 length separators)
111022203333     falsey (has more than 10 numbers)
111ABC222ABC3333 truthy (can have length>1 separators)
111-222_3333     falsey (non-matching separators)
111-22-23333     falsey (missing digit in middle group)
111--222--33333  falsey (extra digit in last group)
-111-222-3333    falsey (first character is not part of number)
111-222-3333a    falsey (last character is not part of number)
aaa-aaa-aaaa     falsey (not enough numbers)
11-2222-3333     falsey (wrong separator location)
111-1-222-1-3333 falsey (too many numbers)

This is a code golf challenge, shortest answer per language wins.

APL (Dyalog Unicode), 30 29 bytesSBCS

'^\d{3}(\D*)\d{3}\1\d{4}$'⎕S⍬

It simply ⎕Searches for the PCRE regex and returns a dummy value (the empty numeric list) for each match. If none are found, it returns a single empty numeric list.

Try it online! The effect of printing a list of empty lists is to print two spaces on a line, while the effect of printing an empty list is to print an empty line. Select all contents in the Output field to reveal the spaces, or use this to lead each printed line with → and each space with ·.


Lossy Text Compression Background
Of the 256 possible characters that a byte can represent, only a few of these are used under most circumstances. Couldn't we somehow take advantage of this, and make our text files smaller by eliminating the need for the rarely used letters?
Many letters don't add any value in most situations, and can be replaced by more common letters. For example, a lower-case "L", capital "I", and the number "1" look nearly identical in most situations, so they can be consolidated.
There is little need for capital letters, so they can be dispensed with. The decompression/display program could even automatically capitalize the first letter of every sentence, common names, etc.
Rules
Entries will be judged on:

compression ratio
readability after de-compression

Entries will be tested against the plain text version of this article: http://en.wikipedia.org/wiki/Babbage and a randomly selected BBC News article.
Extra marks will be awarded for; preserving any mark-up, beautifying after de-compression (i.e. Capitalising sentences etc).
Languages

Any you like, but must easily compile (or be interpreted) on a basic *nix box.


Uniquify Identifiers Introduction

By definition, unique identifiers should be unique.  Having multiple identifiers that are the same causes one to retrieve unexpected data.  But with data arriving concurrently from multiple sources, it can be difficult to ensure uniqueness.  Write a function the uniquifies a list of identifiers.

This is possibly the worst puzzle fluff I have written, but you get the idea.

Requirements

Given a list of zero or more positive integers, apply the following rules to each number from first to last:

If the number is the first of its kind, keep it.
If the number has previously been encountered, replace it with the lowest positive integer not found anywhere in the entire input list or any existing output.

For the solution:

The solution may be a program or a function.
The input may be a string, an array, passed as arguments, or keyboard input.
The output may be a string, an array, or printed to the screen.
All numbers in the output list are distinct.

Assumptions

The input list is clean.  It only contains positive integers.
A positive integer has the range from 1 to 231-1.
Less than 256 MB of memory is available for your program's variables.  (Basically, no 2,147,483,648-element arrays are permitted.)

Test Cases

Input:  empty
Output: empty

Input:  5
Output: 5

Input:  1, 4, 2, 5, 3, 6
Output: 1, 4, 2, 5, 3, 6

Input:  3, 3, 3, 3, 3, 3
Output: 3, 1, 2, 4, 5, 6

Input:  6, 6, 4, 4, 2, 2
Output: 6, 1, 4, 3, 2, 5

Input:  2147483647, 2, 2147483647, 2
Output: 2147483647, 2, 1, 3

Scoring

Just a simple code golf.  Lowest byte count by this time next week wins.

Brachylog, 8 bytes
{|∧ℕ₁}ᵐ≠

Try it online!
Explanation
{    }ᵐ     Map on the Input:
              Input = Output…
 |            …or…
  ∧ℕ₁         …Output is in [1,+inf)
       ≠    All elements of the output must be different
            (Implicit labeling)


Hangman wordgame golf Inspired by reddit.

Write a program which plays Hangman.

The program chooses a random word from a list of N words, where N > 2.
The word list can be provided to the program in any way you choose.
At each iteration

Print out the state of the game using underscores for letters not yet discovered:

H _ N _ _ _ N

Print the number of remaining attempts

10

Read a letter from stdin, and update the state of the game, subtracting an attempt if they guess an incorrect letter.

A (input)

H A N _ _ A N

10

Repeat until all letters are guessed or attempts reaches 0

Use any language
Fewest number of characters wins.
Drawing the gallows is not necessary, but will earn you upvotes and kudos.

Python 3.

from random,sys import *
w=choice(*argv)
L=set(w)
a=10
while L and a:
 print(" ".join("_"if x in L else x for x in w),a)
 try:L-=set(input()[0])
 except:a-=1

I prefer this one though: longer but nicer.

import random
w=random.choice(list(open("/usr/dict/words")))[:-1]
L=set(w)
a=10
while L and a:
 print(" ".join("_"if x in L else x for x in w),a)
 try:L.remove(input()[0])
 except:a-=1
print w


Shortest code to check if a number is in a range in JavaScript This is how I checkout to see if a number is in a range (in between two other numbers):

var a = 10,
    b = 30,
    x = 15,
    y = 35;

x < Math.max(a,b) && x > Math.min(a,b) // -> true
y < Math.max(a,b) && y > Math.min(a,b) // -> false

I have to do this math in my code a lot and I'm looking for shorter equivalent code.

This is a shorter version I came up with. But I am sure it can get much shorter:

a < x && x < b
true
a < y && y < b
false

But downside is I have to repeat x or y

13 chars, checks both variants a<b and b<a

(x-a)*(x-b)<0

In C may be used expression (may be also in JavaScript). 11 chars, No multiplications (fast)

(x-a^x-b)<0


Build a steady brick wall A brick wall is a rectangle made of horizontal 1-by-n bricks stacked into rows. Here's a wall of height 4 and width 8, with brick sizes shown on the right.

[______][______]    4 4
[__][____][__][]    2 3 2 1
[][______][____]    1 4 3
[____][______][]    3 4 1

This wall is unsteady because it has a fault, a place where two vertical cracks between bricks line up, shown below with parens in the surrounding bricks.

[______][______]
[__][____)(__][]
[][______)(____]
[____][______][]

But, the cracks bordering the size-1 bricks on the right don't form a fault because they are separated by a row.

Write code that finds and displays a steady wall constructed out of bricks of specified sizes. Fewest bytes wins.

Input

A non-empty list of brick sizes (positive numbers) and a height that's at least 2. This list may be sorted if you wish. You may alternatively take in a count of bricks of each size.

Output

A picture of a steady rectangular wall of the required height that uses all the bricks given. Print it or return it as a string with newlines.

Draw a brick of size n as 2n characters, underscores surrounded by brackets.

1: []
2: [__]
3: [____]
4: [______]
...

The input is guaranteed to have at least one solution. If there's multiple, you should still only draw one wall.

There's no time restriction; use as much brute force as you want. Your algorithm should in theory work on inputs of any size.

Test cases:

There are multiple solutions, so your outputs might be different.

>> [1, 1, 2, 2], 2
[][__]
[__][]

>> [1, 1, 1, 2, 2, 2, 2, 3], 2
[__][____][__]
[][__][][__][]

>> [1, 1, 2, 2, 3, 3, 3, 3], 3
[][__][____]
[__][____][]
[____][____]

>> [1, 2, 3, 4, 5, 6, 7, 8, 9], 5
[][______________]
[__][____________]
[________________]
[____][__________]
[______][________]

>> [1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2], 5
[][__][__]
[__][__][]
[][__][__]
[__][__][]
[][__][__]


Convert numbers to symbols without string or char literals Read infinitely from stdin, and convert every number to the corresponding symbol on a US qwerty keyboard.

No string or character literals anywhere are permitted.

E.g. if the input is 117758326, the output is !!&&%*#@^.

Letters and symbols that aren't on numbers are left alone; 11g2;;'1g2311hh21930 turns into !!g@;;'!g@#!!hh@!(#)

Shortest code, in bytes, wins.

For those who don't have a US qwerty keyboard, use the following as a guide:

1 -> !
2 -> @
3 -> #
4 -> $
5 -> %
6 -> ^
7 -> &
8 -> *
9 -> (
0 -> )

C, 90 bytes

The line between a character and an integer literal is a very fine one in C.

a[]={8,0,31,2,3,4,61,5,9,7};main(d){for(;~(d=getchar());)putchar(d>47&d<58?a[d-48]+33:d);}